share.php 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563
  1. <?php
  2. /**
  3. * @author Bart Visscher <bartv@thisnet.nl>
  4. * @author Bernhard Reiter <ockham@raz.or.at>
  5. * @author Björn Schießle <schiessle@owncloud.com>
  6. * @author Christopher Schäpers <kondou@ts.unde.re>
  7. * @author Daniel Hansson <enoch85@gmail.com>
  8. * @author Joas Schilling <nickvergessen@owncloud.com>
  9. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  10. * @author Lukas Reschke <lukas@owncloud.com>
  11. * @author Michael Kuhn <suraia@ikkoku.de>
  12. * @author Morris Jobke <hey@morrisjobke.de>
  13. * @author Robin Appelman <icewind@owncloud.com>
  14. * @author Robin McCorkell <rmccorkell@karoshi.org.uk>
  15. * @author Roeland Jago Douma <roeland@famdouma.nl>
  16. * @author Sebastian Döll <sebastian.doell@libasys.de>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Vincent Petry <pvince81@owncloud.com>
  19. * @author Volkan Gezer <volkangezer@gmail.com>
  20. *
  21. * @copyright Copyright (c) 2015, ownCloud, Inc.
  22. * @license AGPL-3.0
  23. *
  24. * This code is free software: you can redistribute it and/or modify
  25. * it under the terms of the GNU Affero General Public License, version 3,
  26. * as published by the Free Software Foundation.
  27. *
  28. * This program is distributed in the hope that it will be useful,
  29. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  30. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  31. * GNU Affero General Public License for more details.
  32. *
  33. * You should have received a copy of the GNU Affero General Public License, version 3,
  34. * along with this program. If not, see <http://www.gnu.org/licenses/>
  35. *
  36. */
  37. namespace OC\Share;
  38. use OCP\IUserSession;
  39. use OC\DB\Connection;
  40. use OCP\IConfig;
  41. /**
  42. * This class provides the ability for apps to share their content between users.
  43. * Apps must create a backend class that implements OCP\Share_Backend and register it with this class.
  44. *
  45. * It provides the following hooks:
  46. * - post_shared
  47. */
  48. class Share extends Constants {
  49. /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
  50. * Construct permissions for share() and setPermissions with Or (|) e.g.
  51. * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
  52. *
  53. * Check if permission is granted with And (&) e.g. Check if delete is
  54. * granted: if ($permissions & PERMISSION_DELETE)
  55. *
  56. * Remove permissions with And (&) and Not (~) e.g. Remove the update
  57. * permission: $permissions &= ~PERMISSION_UPDATE
  58. *
  59. * Apps are required to handle permissions on their own, this class only
  60. * stores and manages the permissions of shares
  61. * @see lib/public/constants.php
  62. */
  63. /**
  64. * Register a sharing backend class that implements OCP\Share_Backend for an item type
  65. * @param string $itemType Item type
  66. * @param string $class Backend class
  67. * @param string $collectionOf (optional) Depends on item type
  68. * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
  69. * @return boolean true if backend is registered or false if error
  70. */
  71. public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
  72. if (self::isEnabled()) {
  73. if (!isset(self::$backendTypes[$itemType])) {
  74. self::$backendTypes[$itemType] = array(
  75. 'class' => $class,
  76. 'collectionOf' => $collectionOf,
  77. 'supportedFileExtensions' => $supportedFileExtensions
  78. );
  79. if(count(self::$backendTypes) === 1) {
  80. \OC_Util::addScript('core', 'share');
  81. \OC_Util::addStyle('core', 'share');
  82. }
  83. return true;
  84. }
  85. \OC_Log::write('OCP\Share',
  86. 'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
  87. .' is already registered for '.$itemType,
  88. \OC_Log::WARN);
  89. }
  90. return false;
  91. }
  92. /**
  93. * Check if the Share API is enabled
  94. * @return boolean true if enabled or false
  95. *
  96. * The Share API is enabled by default if not configured
  97. */
  98. public static function isEnabled() {
  99. if (\OC_Appconfig::getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
  100. return true;
  101. }
  102. return false;
  103. }
  104. /**
  105. * Find which users can access a shared item
  106. * @param string $path to the file
  107. * @param string $ownerUser owner of the file
  108. * @param boolean $includeOwner include owner to the list of users with access to the file
  109. * @param boolean $returnUserPaths Return an array with the user => path map
  110. * @return array
  111. * @note $path needs to be relative to user data dir, e.g. 'file.txt'
  112. * not '/admin/data/file.txt'
  113. */
  114. public static function getUsersSharingFile($path, $ownerUser, $includeOwner = false, $returnUserPaths = false) {
  115. $shares = $sharePaths = $fileTargets = array();
  116. $publicShare = false;
  117. $remoteShare = false;
  118. $source = -1;
  119. $cache = false;
  120. $view = new \OC\Files\View('/' . $ownerUser . '/files');
  121. if ($view->file_exists($path)) {
  122. $meta = $view->getFileInfo($path);
  123. $path = substr($meta->getPath(), strlen('/' . $ownerUser . '/files'));
  124. } else {
  125. // if the file doesn't exists yet we start with the parent folder
  126. $meta = $view->getFileInfo(dirname($path));
  127. }
  128. if($meta !== false) {
  129. $source = $meta['fileid'];
  130. $cache = new \OC\Files\Cache\Cache($meta['storage']);
  131. }
  132. while ($source !== -1) {
  133. // Fetch all shares with another user
  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_USER));
  142. if (\OCP\DB::isError($result)) {
  143. \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OC_Log::ERROR);
  144. } else {
  145. while ($row = $result->fetchRow()) {
  146. $shares[] = $row['share_with'];
  147. if ($returnUserPaths) {
  148. $fileTargets[(int) $row['file_source']][$row['share_with']] = $row;
  149. }
  150. }
  151. }
  152. // We also need to take group shares into account
  153. $query = \OC_DB::prepare(
  154. 'SELECT `share_with`, `file_source`, `file_target`
  155. FROM
  156. `*PREFIX*share`
  157. WHERE
  158. `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')'
  159. );
  160. $result = $query->execute(array($source, self::SHARE_TYPE_GROUP));
  161. if (\OCP\DB::isError($result)) {
  162. \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OC_Log::ERROR);
  163. } else {
  164. while ($row = $result->fetchRow()) {
  165. $usersInGroup = \OC_Group::usersInGroup($row['share_with']);
  166. $shares = array_merge($shares, $usersInGroup);
  167. if ($returnUserPaths) {
  168. foreach ($usersInGroup as $user) {
  169. $fileTargets[(int) $row['file_source']][$user] = $row;
  170. }
  171. }
  172. }
  173. }
  174. //check for public link shares
  175. if (!$publicShare) {
  176. $query = \OC_DB::prepare('
  177. SELECT `share_with`
  178. FROM `*PREFIX*share`
  179. WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')', 1
  180. );
  181. $result = $query->execute(array($source, self::SHARE_TYPE_LINK));
  182. if (\OCP\DB::isError($result)) {
  183. \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
  184. } else {
  185. if ($result->fetchRow()) {
  186. $publicShare = true;
  187. }
  188. }
  189. }
  190. //check for remote share
  191. if (!$remoteShare) {
  192. $query = \OC_DB::prepare('
  193. SELECT `share_with`
  194. FROM `*PREFIX*share`
  195. WHERE `item_source` = ? AND `share_type` = ? AND `item_type` IN (\'file\', \'folder\')', 1
  196. );
  197. $result = $query->execute(array($source, self::SHARE_TYPE_REMOTE));
  198. if (\OCP\DB::isError($result)) {
  199. \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OCP\Util::ERROR);
  200. } else {
  201. if ($result->fetchRow()) {
  202. $remoteShare = true;
  203. }
  204. }
  205. }
  206. // let's get the parent for the next round
  207. $meta = $cache->get((int)$source);
  208. if($meta !== false) {
  209. $source = (int)$meta['parent'];
  210. } else {
  211. $source = -1;
  212. }
  213. }
  214. // Include owner in list of users, if requested
  215. if ($includeOwner) {
  216. $shares[] = $ownerUser;
  217. if ($returnUserPaths) {
  218. $sharePaths[$ownerUser] = $path;
  219. }
  220. }
  221. if ($returnUserPaths) {
  222. $fileTargetIDs = array_keys($fileTargets);
  223. $fileTargetIDs = array_unique($fileTargetIDs);
  224. if (!empty($fileTargetIDs)) {
  225. $query = \OC_DB::prepare(
  226. 'SELECT `fileid`, `path`
  227. FROM `*PREFIX*filecache`
  228. WHERE `fileid` IN (' . implode(',', $fileTargetIDs) . ')'
  229. );
  230. $result = $query->execute();
  231. if (\OCP\DB::isError($result)) {
  232. \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage(), \OC_Log::ERROR);
  233. } else {
  234. while ($row = $result->fetchRow()) {
  235. foreach ($fileTargets[$row['fileid']] as $uid => $shareData) {
  236. $sharedPath = $shareData['file_target'];
  237. $sharedPath .= substr($path, strlen($row['path']) -5);
  238. $sharePaths[$uid] = $sharedPath;
  239. }
  240. }
  241. }
  242. }
  243. return $sharePaths;
  244. }
  245. return array('users' => array_unique($shares), 'public' => $publicShare, 'remote' => $remoteShare);
  246. }
  247. /**
  248. * Get the items of item type shared with the current user
  249. * @param string $itemType
  250. * @param int $format (optional) Format type must be defined by the backend
  251. * @param mixed $parameters (optional)
  252. * @param int $limit Number of items to return (optional) Returns all by default
  253. * @param boolean $includeCollections (optional)
  254. * @return mixed Return depends on format
  255. */
  256. public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
  257. $parameters = null, $limit = -1, $includeCollections = false) {
  258. return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
  259. $parameters, $limit, $includeCollections);
  260. }
  261. /**
  262. * Get the items of item type shared with a user
  263. * @param string $itemType
  264. * @param string $user id for which user we want the shares
  265. * @param int $format (optional) Format type must be defined by the backend
  266. * @param mixed $parameters (optional)
  267. * @param int $limit Number of items to return (optional) Returns all by default
  268. * @param boolean $includeCollections (optional)
  269. * @return mixed Return depends on format
  270. */
  271. public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
  272. $parameters = null, $limit = -1, $includeCollections = false) {
  273. return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
  274. $parameters, $limit, $includeCollections);
  275. }
  276. /**
  277. * Get the item of item type shared with the current user
  278. * @param string $itemType
  279. * @param string $itemTarget
  280. * @param int $format (optional) Format type must be defined by the backend
  281. * @param mixed $parameters (optional)
  282. * @param boolean $includeCollections (optional)
  283. * @return mixed Return depends on format
  284. */
  285. public static function getItemSharedWith($itemType, $itemTarget, $format = self::FORMAT_NONE,
  286. $parameters = null, $includeCollections = false) {
  287. return self::getItems($itemType, $itemTarget, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
  288. $parameters, 1, $includeCollections);
  289. }
  290. /**
  291. * Get the item of item type shared with a given user by source
  292. * @param string $itemType
  293. * @param string $itemSource
  294. * @param string $user User to whom the item was shared
  295. * @param string $owner Owner of the share
  296. * @param int $shareType only look for a specific share type
  297. * @return array Return list of items with file_target, permissions and expiration
  298. */
  299. public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
  300. $shares = array();
  301. $fileDependent = false;
  302. $where = 'WHERE';
  303. $fileDependentWhere = '';
  304. if ($itemType === 'file' || $itemType === 'folder') {
  305. $fileDependent = true;
  306. $column = 'file_source';
  307. $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
  308. $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
  309. } else {
  310. $column = 'item_source';
  311. }
  312. $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
  313. $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
  314. $arguments = array($itemSource, $itemType);
  315. // for link shares $user === null
  316. if ($user !== null) {
  317. $where .= ' AND `share_with` = ? ';
  318. $arguments[] = $user;
  319. }
  320. if ($shareType !== null) {
  321. $where .= ' AND `share_type` = ? ';
  322. $arguments[] = $shareType;
  323. }
  324. if ($owner !== null) {
  325. $where .= ' AND `uid_owner` = ? ';
  326. $arguments[] = $owner;
  327. }
  328. $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
  329. $result = \OC_DB::executeAudited($query, $arguments);
  330. while ($row = $result->fetchRow()) {
  331. if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
  332. continue;
  333. }
  334. $shares[] = $row;
  335. }
  336. //if didn't found a result than let's look for a group share.
  337. if(empty($shares) && $user !== null) {
  338. $groups = \OC_Group::getUserGroups($user);
  339. if (!empty($groups)) {
  340. $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
  341. $arguments = array($itemSource, $itemType, $groups);
  342. $types = array(null, null, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY);
  343. if ($owner !== null) {
  344. $where .= ' AND `uid_owner` = ?';
  345. $arguments[] = $owner;
  346. $types[] = null;
  347. }
  348. // TODO: inject connection, hopefully one day in the future when this
  349. // class isn't static anymore...
  350. $conn = \OC_DB::getConnection();
  351. $result = $conn->executeQuery(
  352. 'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
  353. $arguments,
  354. $types
  355. );
  356. while ($row = $result->fetch()) {
  357. $shares[] = $row;
  358. }
  359. }
  360. }
  361. return $shares;
  362. }
  363. /**
  364. * Get the item of item type shared with the current user by source
  365. * @param string $itemType
  366. * @param string $itemSource
  367. * @param int $format (optional) Format type must be defined by the backend
  368. * @param mixed $parameters
  369. * @param boolean $includeCollections
  370. * @param string $shareWith (optional) define against which user should be checked, default: current user
  371. * @return array
  372. */
  373. public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
  374. $parameters = null, $includeCollections = false, $shareWith = null) {
  375. $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
  376. return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
  377. $parameters, 1, $includeCollections, true);
  378. }
  379. /**
  380. * Get the item of item type shared by a link
  381. * @param string $itemType
  382. * @param string $itemSource
  383. * @param string $uidOwner Owner of link
  384. * @return array
  385. */
  386. public static function getItemSharedWithByLink($itemType, $itemSource, $uidOwner) {
  387. return self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null, $uidOwner, self::FORMAT_NONE,
  388. null, 1);
  389. }
  390. /**
  391. * Based on the given token the share information will be returned - password protected shares will be verified
  392. * @param string $token
  393. * @param bool $checkPasswordProtection
  394. * @return array|boolean false will be returned in case the token is unknown or unauthorized
  395. */
  396. public static function getShareByToken($token, $checkPasswordProtection = true) {
  397. $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
  398. $result = $query->execute(array($token));
  399. if (\OC_DB::isError($result)) {
  400. \OC_Log::write('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OC_Log::ERROR);
  401. }
  402. $row = $result->fetchRow();
  403. if ($row === false) {
  404. return false;
  405. }
  406. if (is_array($row) and self::expireItem($row)) {
  407. return false;
  408. }
  409. // password protected shares need to be authenticated
  410. if ($checkPasswordProtection && !\OCP\Share::checkPasswordProtectedShare($row)) {
  411. return false;
  412. }
  413. return $row;
  414. }
  415. /**
  416. * resolves reshares down to the last real share
  417. * @param array $linkItem
  418. * @return array file owner
  419. */
  420. public static function resolveReShare($linkItem)
  421. {
  422. if (isset($linkItem['parent'])) {
  423. $parent = $linkItem['parent'];
  424. while (isset($parent)) {
  425. $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
  426. $item = $query->execute(array($parent))->fetchRow();
  427. if (isset($item['parent'])) {
  428. $parent = $item['parent'];
  429. } else {
  430. return $item;
  431. }
  432. }
  433. }
  434. return $linkItem;
  435. }
  436. /**
  437. * Get the shared items of item type owned by the current user
  438. * @param string $itemType
  439. * @param int $format (optional) Format type must be defined by the backend
  440. * @param mixed $parameters
  441. * @param int $limit Number of items to return (optional) Returns all by default
  442. * @param boolean $includeCollections
  443. * @return mixed Return depends on format
  444. */
  445. public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
  446. $limit = -1, $includeCollections = false) {
  447. return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
  448. $parameters, $limit, $includeCollections);
  449. }
  450. /**
  451. * Get the shared item of item type owned by the current user
  452. * @param string $itemType
  453. * @param string $itemSource
  454. * @param int $format (optional) Format type must be defined by the backend
  455. * @param mixed $parameters
  456. * @param boolean $includeCollections
  457. * @return mixed Return depends on format
  458. */
  459. public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
  460. $parameters = null, $includeCollections = false) {
  461. return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
  462. $parameters, -1, $includeCollections);
  463. }
  464. /**
  465. * Get all users an item is shared with
  466. * @param string $itemType
  467. * @param string $itemSource
  468. * @param string $uidOwner
  469. * @param boolean $includeCollections
  470. * @param boolean $checkExpireDate
  471. * @return array Return array of users
  472. */
  473. public static function getUsersItemShared($itemType, $itemSource, $uidOwner, $includeCollections = false, $checkExpireDate = true) {
  474. $users = array();
  475. $items = self::getItems($itemType, $itemSource, null, null, $uidOwner, self::FORMAT_NONE, null, -1, $includeCollections, false, $checkExpireDate);
  476. if ($items) {
  477. foreach ($items as $item) {
  478. if ((int)$item['share_type'] === self::SHARE_TYPE_USER) {
  479. $users[] = $item['share_with'];
  480. } else if ((int)$item['share_type'] === self::SHARE_TYPE_GROUP) {
  481. $users = array_merge($users, \OC_Group::usersInGroup($item['share_with']));
  482. }
  483. }
  484. }
  485. return $users;
  486. }
  487. /**
  488. * Share an item with a user, group, or via private link
  489. * @param string $itemType
  490. * @param string $itemSource
  491. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  492. * @param string $shareWith User or group the item is being shared with
  493. * @param int $permissions CRUDS
  494. * @param string $itemSourceName
  495. * @param \DateTime $expirationDate
  496. * @return boolean|string Returns true on success or false on failure, Returns token on success for links
  497. * @throws \Exception
  498. */
  499. public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null) {
  500. $backend = self::getBackend($itemType);
  501. $l = \OC::$server->getL10N('lib');
  502. if ($backend->isShareTypeAllowed($shareType) === false) {
  503. $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
  504. $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
  505. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OC_Log::ERROR);
  506. throw new \Exception($message_t);
  507. }
  508. $uidOwner = \OC_User::getUser();
  509. $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
  510. if (is_null($itemSourceName)) {
  511. $itemSourceName = $itemSource;
  512. }
  513. // check if file can be shared
  514. if ($itemType === 'file' or $itemType === 'folder') {
  515. $path = \OC\Files\Filesystem::getPath($itemSource);
  516. // verify that the file exists before we try to share it
  517. if (!$path) {
  518. $message = 'Sharing %s failed, because the file does not exist';
  519. $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
  520. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
  521. throw new \Exception($message_t);
  522. }
  523. // verify that the user has share permission
  524. if (!\OC\Files\Filesystem::isSharable($path)) {
  525. $message = 'You are not allowed to share %s';
  526. $message_t = $l->t('You are not allowed to share %s', array($itemSourceName));
  527. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
  528. throw new \Exception($message_t);
  529. }
  530. }
  531. //verify that we don't share a folder which already contains a share mount point
  532. if ($itemType === 'folder') {
  533. $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
  534. $mountManager = \OC\Files\Filesystem::getMountManager();
  535. $mounts = $mountManager->findIn($path);
  536. foreach ($mounts as $mount) {
  537. if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
  538. $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
  539. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  540. throw new \Exception($message);
  541. }
  542. }
  543. }
  544. // single file shares should never have delete permissions
  545. if ($itemType === 'file') {
  546. $permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
  547. }
  548. // Verify share type and sharing conditions are met
  549. if ($shareType === self::SHARE_TYPE_USER) {
  550. if ($shareWith == $uidOwner) {
  551. $message = 'Sharing %s failed, because the user %s is the item owner';
  552. $message_t = $l->t('Sharing %s failed, because the user %s is the item owner', array($itemSourceName, $shareWith));
  553. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  554. throw new \Exception($message_t);
  555. }
  556. if (!\OC_User::userExists($shareWith)) {
  557. $message = 'Sharing %s failed, because the user %s does not exist';
  558. $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
  559. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  560. throw new \Exception($message_t);
  561. }
  562. if ($shareWithinGroupOnly) {
  563. $inGroup = array_intersect(\OC_Group::getUserGroups($uidOwner), \OC_Group::getUserGroups($shareWith));
  564. if (empty($inGroup)) {
  565. $message = 'Sharing %s failed, because the user '
  566. .'%s is not a member of any groups that %s is a member of';
  567. $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));
  568. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith, $uidOwner), \OC_Log::ERROR);
  569. throw new \Exception($message_t);
  570. }
  571. }
  572. // Check if the item source is already shared with the user, either from the same owner or a different user
  573. if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
  574. $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
  575. // Only allow the same share to occur again if it is the same
  576. // owner and is not a user share, this use case is for increasing
  577. // permissions for a specific user
  578. if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
  579. $message = 'Sharing %s failed, because this item is already shared with %s';
  580. $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
  581. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  582. throw new \Exception($message_t);
  583. }
  584. }
  585. } else if ($shareType === self::SHARE_TYPE_GROUP) {
  586. if (!\OC_Group::groupExists($shareWith)) {
  587. $message = 'Sharing %s failed, because the group %s does not exist';
  588. $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
  589. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  590. throw new \Exception($message_t);
  591. }
  592. if ($shareWithinGroupOnly && !\OC_Group::inGroup($uidOwner, $shareWith)) {
  593. $message = 'Sharing %s failed, because '
  594. .'%s is not a member of the group %s';
  595. $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
  596. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OC_Log::ERROR);
  597. throw new \Exception($message_t);
  598. }
  599. // Check if the item source is already shared with the group, either from the same owner or a different user
  600. // The check for each user in the group is done inside the put() function
  601. if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
  602. null, self::FORMAT_NONE, null, 1, true, true)) {
  603. // Only allow the same share to occur again if it is the same
  604. // owner and is not a group share, this use case is for increasing
  605. // permissions for a specific user
  606. if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
  607. $message = 'Sharing %s failed, because this item is already shared with %s';
  608. $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
  609. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  610. throw new \Exception($message_t);
  611. }
  612. }
  613. // Convert share with into an array with the keys group and users
  614. $group = $shareWith;
  615. $shareWith = array();
  616. $shareWith['group'] = $group;
  617. $shareWith['users'] = array_diff(\OC_Group::usersInGroup($group), array($uidOwner));
  618. } else if ($shareType === self::SHARE_TYPE_LINK) {
  619. $updateExistingShare = false;
  620. if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
  621. // when updating a link share
  622. // FIXME Don't delete link if we update it
  623. if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
  624. $uidOwner, self::FORMAT_NONE, null, 1)) {
  625. // remember old token
  626. $oldToken = $checkExists['token'];
  627. $oldPermissions = $checkExists['permissions'];
  628. //delete the old share
  629. Helper::delete($checkExists['id']);
  630. $updateExistingShare = true;
  631. }
  632. // Generate hash of password - same method as user passwords
  633. if (!empty($shareWith)) {
  634. $shareWith = \OC::$server->getHasher()->hash($shareWith);
  635. } else {
  636. // reuse the already set password, but only if we change permissions
  637. // otherwise the user disabled the password protection
  638. if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
  639. $shareWith = $checkExists['share_with'];
  640. }
  641. }
  642. if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
  643. $message = 'You need to provide a password to create a public link, only protected links are allowed';
  644. $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
  645. \OC_Log::write('OCP\Share', $message, \OC_Log::ERROR);
  646. throw new \Exception($message_t);
  647. }
  648. if ($updateExistingShare === false &&
  649. self::isDefaultExpireDateEnabled() &&
  650. empty($expirationDate)) {
  651. $expirationDate = Helper::calcExpireDate();
  652. }
  653. // Generate token
  654. if (isset($oldToken)) {
  655. $token = $oldToken;
  656. } else {
  657. $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(self::TOKEN_LENGTH,
  658. \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_UPPER.
  659. \OCP\Security\ISecureRandom::CHAR_DIGITS
  660. );
  661. }
  662. $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
  663. null, $token, $itemSourceName, $expirationDate);
  664. if ($result) {
  665. return $token;
  666. } else {
  667. return false;
  668. }
  669. }
  670. $message = 'Sharing %s failed, because sharing with links is not allowed';
  671. $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
  672. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
  673. throw new \Exception($message_t);
  674. } else if ($shareType === self::SHARE_TYPE_REMOTE) {
  675. $token = \OC::$server->getSecureRandom()->getMediumStrengthGenerator()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
  676. \OCP\Security\ISecureRandom::CHAR_DIGITS);
  677. $shareWith = Helper::fixRemoteURLInShareWith($shareWith);
  678. $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
  679. $send = false;
  680. if ($shareId) {
  681. $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
  682. }
  683. if ($send === false) {
  684. $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
  685. self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
  686. $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
  687. throw new \Exception($message_t);
  688. }
  689. return $send;
  690. } else {
  691. // Future share types need to include their own conditions
  692. $message = 'Share type %s is not valid for %s';
  693. $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
  694. \OC_Log::write('OCP\Share', sprintf($message, $shareType, $itemSource), \OC_Log::ERROR);
  695. throw new \Exception($message_t);
  696. }
  697. // Put the item into the database
  698. $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
  699. return $result ? true : false;
  700. }
  701. /**
  702. * Unshare an item from a user, group, or delete a private link
  703. * @param string $itemType
  704. * @param string $itemSource
  705. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  706. * @param string $shareWith User or group the item is being shared with
  707. * @param string $owner owner of the share, if null the current user is used
  708. * @return boolean true on success or false on failure
  709. */
  710. public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
  711. // check if it is a valid itemType
  712. self::getBackend($itemType);
  713. $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
  714. $toDelete = array();
  715. $newParent = null;
  716. $currentUser = $owner ? $owner : \OC_User::getUser();
  717. foreach ($items as $item) {
  718. // delete the item with the expected share_type and owner
  719. if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
  720. $toDelete = $item;
  721. // if there is more then one result we don't have to delete the children
  722. // but update their parent. For group shares the new parent should always be
  723. // the original group share and not the db entry with the unique name
  724. } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
  725. $newParent = $item['parent'];
  726. } else {
  727. $newParent = $item['id'];
  728. }
  729. }
  730. if (!empty($toDelete)) {
  731. self::unshareItem($toDelete, $newParent);
  732. return true;
  733. }
  734. return false;
  735. }
  736. /**
  737. * Unshare an item from all users, groups, and remove all links
  738. * @param string $itemType
  739. * @param string $itemSource
  740. * @return boolean true on success or false on failure
  741. */
  742. public static function unshareAll($itemType, $itemSource) {
  743. // Get all of the owners of shares of this item.
  744. $query = \OC_DB::prepare( 'SELECT `uid_owner` from `*PREFIX*share` WHERE `item_type`=? AND `item_source`=?' );
  745. $result = $query->execute(array($itemType, $itemSource));
  746. $shares = array();
  747. // Add each owner's shares to the array of all shares for this item.
  748. while ($row = $result->fetchRow()) {
  749. $shares = array_merge($shares, self::getItems($itemType, $itemSource, null, null, $row['uid_owner']));
  750. }
  751. if (!empty($shares)) {
  752. // Pass all the vars we have for now, they may be useful
  753. $hookParams = array(
  754. 'itemType' => $itemType,
  755. 'itemSource' => $itemSource,
  756. 'shares' => $shares,
  757. );
  758. \OC_Hook::emit('OCP\Share', 'pre_unshareAll', $hookParams);
  759. foreach ($shares as $share) {
  760. self::unshareItem($share);
  761. }
  762. \OC_Hook::emit('OCP\Share', 'post_unshareAll', $hookParams);
  763. return true;
  764. }
  765. return false;
  766. }
  767. /**
  768. * Unshare an item shared with the current user
  769. * @param string $itemType
  770. * @param string $itemOrigin Item target or source
  771. * @param boolean $originIsSource true if $itemOrigin is the source, false if $itemOrigin is the target (optional)
  772. * @return boolean true on success or false on failure
  773. *
  774. * Unsharing from self is not allowed for items inside collections
  775. */
  776. public static function unshareFromSelf($itemType, $itemOrigin, $originIsSource = false) {
  777. $originType = ($originIsSource) ? 'source' : 'target';
  778. $uid = \OCP\User::getUser();
  779. if ($itemType === 'file' || $itemType === 'folder') {
  780. $statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `file_' . $originType . '` = ?';
  781. } else {
  782. $statement = 'SELECT * FROM `*PREFIX*share` WHERE `item_type` = ? and `item_' . $originType . '` = ?';
  783. }
  784. $query = \OCP\DB::prepare($statement);
  785. $result = $query->execute(array($itemType, $itemOrigin));
  786. $shares = $result->fetchAll();
  787. $listOfUnsharedItems = array();
  788. $itemUnshared = false;
  789. foreach ($shares as $share) {
  790. if ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_USER &&
  791. $share['share_with'] === $uid) {
  792. $deletedShares = Helper::delete($share['id']);
  793. $shareTmp = array(
  794. 'id' => $share['id'],
  795. 'shareWith' => $share['share_with'],
  796. 'itemTarget' => $share['item_target'],
  797. 'itemType' => $share['item_type'],
  798. 'shareType' => (int)$share['share_type'],
  799. );
  800. if (isset($share['file_target'])) {
  801. $shareTmp['fileTarget'] = $share['file_target'];
  802. }
  803. $listOfUnsharedItems = array_merge($listOfUnsharedItems, $deletedShares, array($shareTmp));
  804. $itemUnshared = true;
  805. break;
  806. } elseif ((int)$share['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
  807. if (\OC_Group::inGroup($uid, $share['share_with'])) {
  808. $groupShare = $share;
  809. }
  810. } elseif ((int)$share['share_type'] === self::$shareTypeGroupUserUnique &&
  811. $share['share_with'] === $uid) {
  812. $uniqueGroupShare = $share;
  813. }
  814. }
  815. if (!$itemUnshared && isset($groupShare) && !isset($uniqueGroupShare)) {
  816. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share`'
  817. .' (`item_type`, `item_source`, `item_target`, `parent`, `share_type`,'
  818. .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`, `file_target`)'
  819. .' VALUES (?,?,?,?,?,?,?,?,?,?,?)');
  820. $query->execute(array($groupShare['item_type'], $groupShare['item_source'], $groupShare['item_target'],
  821. $groupShare['id'], self::$shareTypeGroupUserUnique,
  822. \OC_User::getUser(), $groupShare['uid_owner'], 0, $groupShare['stime'], $groupShare['file_source'],
  823. $groupShare['file_target']));
  824. $shareTmp = array(
  825. 'id' => $groupShare['id'],
  826. 'shareWith' => $groupShare['share_with'],
  827. 'itemTarget' => $groupShare['item_target'],
  828. 'itemType' => $groupShare['item_type'],
  829. 'shareType' => (int)$groupShare['share_type'],
  830. );
  831. if (isset($groupShare['file_target'])) {
  832. $shareTmp['fileTarget'] = $groupShare['file_target'];
  833. }
  834. $listOfUnsharedItems = array_merge($listOfUnsharedItems, array($groupShare));
  835. $itemUnshared = true;
  836. } elseif (!$itemUnshared && isset($uniqueGroupShare)) {
  837. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
  838. $query->execute(array(0, $uniqueGroupShare['id']));
  839. $shareTmp = array(
  840. 'id' => $uniqueGroupShare['id'],
  841. 'shareWith' => $uniqueGroupShare['share_with'],
  842. 'itemTarget' => $uniqueGroupShare['item_target'],
  843. 'itemType' => $uniqueGroupShare['item_type'],
  844. 'shareType' => (int)$uniqueGroupShare['share_type'],
  845. );
  846. if (isset($uniqueGroupShare['file_target'])) {
  847. $shareTmp['fileTarget'] = $uniqueGroupShare['file_target'];
  848. }
  849. $listOfUnsharedItems = array_merge($listOfUnsharedItems, array($uniqueGroupShare));
  850. $itemUnshared = true;
  851. }
  852. if ($itemUnshared) {
  853. \OC_Hook::emit('OCP\Share', 'post_unshareFromSelf',
  854. array('unsharedItems' => $listOfUnsharedItems, 'itemType' => $itemType));
  855. }
  856. return $itemUnshared;
  857. }
  858. /**
  859. * sent status if users got informed by mail about share
  860. * @param string $itemType
  861. * @param string $itemSource
  862. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  863. * @param string $recipient with whom was the file shared
  864. * @param boolean $status
  865. */
  866. public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
  867. $status = $status ? 1 : 0;
  868. $query = \OC_DB::prepare(
  869. 'UPDATE `*PREFIX*share`
  870. SET `mail_send` = ?
  871. WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
  872. $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
  873. if($result === false) {
  874. \OC_Log::write('OCP\Share', 'Couldn\'t set send mail status', \OC_Log::ERROR);
  875. }
  876. }
  877. /**
  878. * Set the permissions of an item for a specific user or group
  879. * @param string $itemType
  880. * @param string $itemSource
  881. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  882. * @param string $shareWith User or group the item is being shared with
  883. * @param int $permissions CRUDS permissions
  884. * @return boolean true on success or false on failure
  885. * @throws \Exception when trying to grant more permissions then the user has himself
  886. */
  887. public static function setPermissions($itemType, $itemSource, $shareType, $shareWith, $permissions) {
  888. $l = \OC::$server->getL10N('lib');
  889. if ($item = self::getItems($itemType, $itemSource, $shareType, $shareWith,
  890. \OC_User::getUser(), self::FORMAT_NONE, null, 1, false)) {
  891. // Check if this item is a reshare and verify that the permissions
  892. // granted don't exceed the parent shared item
  893. if (isset($item['parent'])) {
  894. $query = \OC_DB::prepare('SELECT `permissions` FROM `*PREFIX*share` WHERE `id` = ?', 1);
  895. $result = $query->execute(array($item['parent']))->fetchRow();
  896. if (~(int)$result['permissions'] & $permissions) {
  897. $message = 'Setting permissions for %s failed,'
  898. .' because the permissions exceed permissions granted to %s';
  899. $message_t = $l->t('Setting permissions for %s failed, because the permissions exceed permissions granted to %s', array($itemSource, \OC_User::getUser()));
  900. \OC_Log::write('OCP\Share', sprintf($message, $itemSource, \OC_User::getUser()), \OC_Log::ERROR);
  901. throw new \Exception($message_t);
  902. }
  903. }
  904. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = ? WHERE `id` = ?');
  905. $query->execute(array($permissions, $item['id']));
  906. if ($itemType === 'file' || $itemType === 'folder') {
  907. \OC_Hook::emit('OCP\Share', 'post_update_permissions', array(
  908. 'itemType' => $itemType,
  909. 'itemSource' => $itemSource,
  910. 'shareType' => $shareType,
  911. 'shareWith' => $shareWith,
  912. 'uidOwner' => \OC_User::getUser(),
  913. 'permissions' => $permissions,
  914. 'path' => $item['path'],
  915. ));
  916. }
  917. // Check if permissions were removed
  918. if ($item['permissions'] & ~$permissions) {
  919. // If share permission is removed all reshares must be deleted
  920. if (($item['permissions'] & \OCP\Constants::PERMISSION_SHARE) && (~$permissions & \OCP\Constants::PERMISSION_SHARE)) {
  921. // delete all shares, keep parent and group children
  922. Helper::delete($item['id'], true, null, null, true);
  923. } else {
  924. $ids = array();
  925. $parents = array($item['id']);
  926. while (!empty($parents)) {
  927. $parents = "'".implode("','", $parents)."'";
  928. $query = \OC_DB::prepare('SELECT `id`, `permissions` FROM `*PREFIX*share`'
  929. .' WHERE `parent` IN ('.$parents.')');
  930. $result = $query->execute();
  931. // Reset parents array, only go through loop again if
  932. // items are found that need permissions removed
  933. $parents = array();
  934. while ($item = $result->fetchRow()) {
  935. // Check if permissions need to be removed
  936. if ($item['permissions'] & ~$permissions) {
  937. // Add to list of items that need permissions removed
  938. $ids[] = $item['id'];
  939. $parents[] = $item['id'];
  940. }
  941. }
  942. }
  943. // Remove the permissions for all reshares of this item
  944. if (!empty($ids)) {
  945. $ids = "'".implode("','", $ids)."'";
  946. // TODO this should be done with Doctrine platform objects
  947. if (\OC_Config::getValue( "dbtype") === 'oci') {
  948. $andOp = 'BITAND(`permissions`, ?)';
  949. } else {
  950. $andOp = '`permissions` & ?';
  951. }
  952. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `permissions` = '.$andOp
  953. .' WHERE `id` IN ('.$ids.')');
  954. $query->execute(array($permissions));
  955. }
  956. }
  957. }
  958. return true;
  959. }
  960. $message = 'Setting permissions for %s failed, because the item was not found';
  961. $message_t = $l->t('Setting permissions for %s failed, because the item was not found', array($itemSource));
  962. \OC_Log::write('OCP\Share', sprintf($message, $itemSource), \OC_Log::ERROR);
  963. throw new \Exception($message_t);
  964. }
  965. /**
  966. * validate expiration date if it meets all constraints
  967. *
  968. * @param string $expireDate well formate date string, e.g. "DD-MM-YYYY"
  969. * @param string $shareTime timestamp when the file was shared
  970. * @param string $itemType
  971. * @param string $itemSource
  972. * @return \DateTime validated date
  973. * @throws \Exception when the expire date is in the past or further in the future then the enforced date
  974. */
  975. private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
  976. $l = \OC::$server->getL10N('lib');
  977. $date = new \DateTime($expireDate);
  978. $today = new \DateTime('now');
  979. // if the user doesn't provide a share time we need to get it from the database
  980. // fall-back mode to keep API stable, because the $shareTime parameter was added later
  981. $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
  982. if ($defaultExpireDateEnforced && $shareTime === null) {
  983. $items = self::getItemShared($itemType, $itemSource);
  984. $firstItem = reset($items);
  985. $shareTime = (int)$firstItem['stime'];
  986. }
  987. if ($defaultExpireDateEnforced) {
  988. // initialize max date with share time
  989. $maxDate = new \DateTime();
  990. $maxDate->setTimestamp($shareTime);
  991. $maxDays = \OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
  992. $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
  993. if ($date > $maxDate) {
  994. $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
  995. $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
  996. \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
  997. throw new \Exception($warning_t);
  998. }
  999. }
  1000. if ($date < $today) {
  1001. $message = 'Cannot set expiration date. Expiration date is in the past';
  1002. $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
  1003. \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
  1004. throw new \Exception($message_t);
  1005. }
  1006. return $date;
  1007. }
  1008. /**
  1009. * Set expiration date for a share
  1010. * @param string $itemType
  1011. * @param string $itemSource
  1012. * @param string $date expiration date
  1013. * @param int $shareTime timestamp from when the file was shared
  1014. * @return boolean
  1015. * @throws \Exception when the expire date is not set, in the past or further in the future then the enforced date
  1016. */
  1017. public static function setExpirationDate($itemType, $itemSource, $date, $shareTime = null) {
  1018. $user = \OC_User::getUser();
  1019. $l = \OC::$server->getL10N('lib');
  1020. if ($date == '') {
  1021. if (\OCP\Util::isDefaultExpireDateEnforced()) {
  1022. $warning = 'Cannot clear expiration date. Shares are required to have an expiration date.';
  1023. $warning_t = $l->t('Cannot clear expiration date. Shares are required to have an expiration date.');
  1024. \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
  1025. throw new \Exception($warning_t);
  1026. } else {
  1027. $date = null;
  1028. }
  1029. } else {
  1030. $date = self::validateExpireDate($date, $shareTime, $itemType, $itemSource);
  1031. }
  1032. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `expiration` = ? WHERE `item_type` = ? AND `item_source` = ? AND `uid_owner` = ? AND `share_type` = ?');
  1033. $query->bindValue(1, $date, 'datetime');
  1034. $query->bindValue(2, $itemType);
  1035. $query->bindValue(3, $itemSource);
  1036. $query->bindValue(4, $user);
  1037. $query->bindValue(5, \OCP\Share::SHARE_TYPE_LINK);
  1038. $query->execute();
  1039. \OC_Hook::emit('OCP\Share', 'post_set_expiration_date', array(
  1040. 'itemType' => $itemType,
  1041. 'itemSource' => $itemSource,
  1042. 'date' => $date,
  1043. 'uidOwner' => $user
  1044. ));
  1045. return true;
  1046. }
  1047. /**
  1048. * Retrieve the owner of a connection
  1049. *
  1050. * @param Connection $connection
  1051. * @param int $shareId
  1052. * @throws \Exception
  1053. * @return string uid of share owner
  1054. */
  1055. private static function getShareOwner(Connection $connection, $shareId) {
  1056. $qb = $connection->createQueryBuilder();
  1057. $qb->select('`uid_owner`')
  1058. ->from('`*PREFIX*share`')
  1059. ->where('`id` = :shareId')
  1060. ->setParameter(':shareId', $shareId);
  1061. $result = $qb->execute();
  1062. $result = $result->fetch();
  1063. if (empty($result)) {
  1064. throw new \Exception('Share not found');
  1065. }
  1066. return $result['uid_owner'];
  1067. }
  1068. /**
  1069. * Set expiration date for a share
  1070. *
  1071. * @param IUserSession $userSession
  1072. * @param Connection $connection
  1073. * @param IConfig $config
  1074. * @param int $shareId
  1075. * @param string $password
  1076. * @throws \Exception
  1077. * @return boolean
  1078. */
  1079. public static function setPassword(IUserSession $userSession,
  1080. Connection $connection,
  1081. IConfig $config,
  1082. $shareId, $password) {
  1083. $user = $userSession->getUser();
  1084. if (is_null($user)) {
  1085. throw new \Exception("User not logged in");
  1086. }
  1087. $uid = self::getShareOwner($connection, $shareId);
  1088. if ($uid !== $user->getUID()) {
  1089. throw new \Exception('Cannot update share of a different user');
  1090. }
  1091. if ($password === '') {
  1092. $password = null;
  1093. }
  1094. //If passwords are enforced the password can't be null
  1095. if (self::enforcePassword($config) && is_null($password)) {
  1096. throw new \Exception('Cannot remove password');
  1097. }
  1098. $qb = $connection->createQueryBuilder();
  1099. $qb->update('`*PREFIX*share`')
  1100. ->set('`share_with`', ':pass')
  1101. ->where('`id` = :shareId')
  1102. ->setParameter(':pass', is_null($password) ? 'NULL' : \OC::$server->getHasher()->hash($password))
  1103. ->setParameter(':shareId', $shareId);
  1104. $qb->execute();
  1105. return true;
  1106. }
  1107. /**
  1108. * Checks whether a share has expired, calls unshareItem() if yes.
  1109. * @param array $item Share data (usually database row)
  1110. * @return boolean True if item was expired, false otherwise.
  1111. */
  1112. protected static function expireItem(array $item) {
  1113. $result = false;
  1114. // only use default expiration date for link shares
  1115. if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
  1116. // calculate expiration date
  1117. if (!empty($item['expiration'])) {
  1118. $userDefinedExpire = new \DateTime($item['expiration']);
  1119. $expires = $userDefinedExpire->getTimestamp();
  1120. } else {
  1121. $expires = null;
  1122. }
  1123. // get default expiration settings
  1124. $defaultSettings = Helper::getDefaultExpireSetting();
  1125. $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
  1126. if (is_int($expires)) {
  1127. $now = time();
  1128. if ($now > $expires) {
  1129. self::unshareItem($item);
  1130. $result = true;
  1131. }
  1132. }
  1133. }
  1134. return $result;
  1135. }
  1136. /**
  1137. * Unshares a share given a share data array
  1138. * @param array $item Share data (usually database row)
  1139. * @param int $newParent parent ID
  1140. * @return null
  1141. */
  1142. protected static function unshareItem(array $item, $newParent = null) {
  1143. $shareType = (int)$item['share_type'];
  1144. $shareWith = null;
  1145. if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
  1146. $shareWith = $item['share_with'];
  1147. }
  1148. // Pass all the vars we have for now, they may be useful
  1149. $hookParams = array(
  1150. 'id' => $item['id'],
  1151. 'itemType' => $item['item_type'],
  1152. 'itemSource' => $item['item_source'],
  1153. 'shareType' => $shareType,
  1154. 'shareWith' => $shareWith,
  1155. 'itemParent' => $item['parent'],
  1156. 'uidOwner' => $item['uid_owner'],
  1157. );
  1158. if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
  1159. $hookParams['fileSource'] = $item['file_source'];
  1160. $hookParams['fileTarget'] = $item['file_target'];
  1161. }
  1162. \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
  1163. $deletedShares = Helper::delete($item['id'], false, null, $newParent);
  1164. $deletedShares[] = $hookParams;
  1165. $hookParams['deletedShares'] = $deletedShares;
  1166. \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
  1167. if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
  1168. $urlParts = explode('@', $item['share_with'], 2);
  1169. self::sendRemoteUnshare($urlParts[1], $item['id'], $item['token']);
  1170. }
  1171. }
  1172. /**
  1173. * Get the backend class for the specified item type
  1174. * @param string $itemType
  1175. * @throws \Exception
  1176. * @return \OCP\Share_Backend
  1177. */
  1178. public static function getBackend($itemType) {
  1179. $l = \OC::$server->getL10N('lib');
  1180. if (isset(self::$backends[$itemType])) {
  1181. return self::$backends[$itemType];
  1182. } else if (isset(self::$backendTypes[$itemType]['class'])) {
  1183. $class = self::$backendTypes[$itemType]['class'];
  1184. if (class_exists($class)) {
  1185. self::$backends[$itemType] = new $class;
  1186. if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
  1187. $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
  1188. $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
  1189. \OC_Log::write('OCP\Share', sprintf($message, $class), \OC_Log::ERROR);
  1190. throw new \Exception($message_t);
  1191. }
  1192. return self::$backends[$itemType];
  1193. } else {
  1194. $message = 'Sharing backend %s not found';
  1195. $message_t = $l->t('Sharing backend %s not found', array($class));
  1196. \OC_Log::write('OCP\Share', sprintf($message, $class), \OC_Log::ERROR);
  1197. throw new \Exception($message_t);
  1198. }
  1199. }
  1200. $message = 'Sharing backend for %s not found';
  1201. $message_t = $l->t('Sharing backend for %s not found', array($itemType));
  1202. \OC_Log::write('OCP\Share', sprintf($message, $itemType), \OC_Log::ERROR);
  1203. throw new \Exception($message_t);
  1204. }
  1205. /**
  1206. * Check if resharing is allowed
  1207. * @return boolean true if allowed or false
  1208. *
  1209. * Resharing is allowed by default if not configured
  1210. */
  1211. public static function isResharingAllowed() {
  1212. if (!isset(self::$isResharingAllowed)) {
  1213. if (\OC_Appconfig::getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
  1214. self::$isResharingAllowed = true;
  1215. } else {
  1216. self::$isResharingAllowed = false;
  1217. }
  1218. }
  1219. return self::$isResharingAllowed;
  1220. }
  1221. /**
  1222. * Get a list of collection item types for the specified item type
  1223. * @param string $itemType
  1224. * @return array
  1225. */
  1226. private static function getCollectionItemTypes($itemType) {
  1227. $collectionTypes = array($itemType);
  1228. foreach (self::$backendTypes as $type => $backend) {
  1229. if (in_array($backend['collectionOf'], $collectionTypes)) {
  1230. $collectionTypes[] = $type;
  1231. }
  1232. }
  1233. // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
  1234. if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
  1235. unset($collectionTypes[0]);
  1236. }
  1237. // Return array if collections were found or the item type is a
  1238. // collection itself - collections can be inside collections
  1239. if (count($collectionTypes) > 0) {
  1240. return $collectionTypes;
  1241. }
  1242. return false;
  1243. }
  1244. /**
  1245. * Get the owners of items shared with a user.
  1246. *
  1247. * @param string $user The user the items are shared with.
  1248. * @param string $type The type of the items shared with the user.
  1249. * @param boolean $includeCollections Include collection item types (optional)
  1250. * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
  1251. * @return array
  1252. */
  1253. public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
  1254. // First, we find out if $type is part of a collection (and if that collection is part of
  1255. // another one and so on).
  1256. $collectionTypes = array();
  1257. if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
  1258. $collectionTypes[] = $type;
  1259. }
  1260. // Of these collection types, along with our original $type, we make a
  1261. // list of the ones for which a sharing backend has been registered.
  1262. // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
  1263. // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
  1264. $allMaybeSharedItems = array();
  1265. foreach ($collectionTypes as $collectionType) {
  1266. if (isset(self::$backends[$collectionType])) {
  1267. $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
  1268. $collectionType,
  1269. $user,
  1270. self::FORMAT_NONE
  1271. );
  1272. }
  1273. }
  1274. $owners = array();
  1275. if ($includeOwner) {
  1276. $owners[] = $user;
  1277. }
  1278. // We take a look at all shared items of the given $type (or of the collections it is part of)
  1279. // and find out their owners. Then, we gather the tags for the original $type from all owners,
  1280. // and return them as elements of a list that look like "Tag (owner)".
  1281. foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
  1282. foreach ($maybeSharedItems as $sharedItem) {
  1283. if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
  1284. $owners[] = $sharedItem['uid_owner'];
  1285. }
  1286. }
  1287. }
  1288. return $owners;
  1289. }
  1290. /**
  1291. * Get shared items from the database
  1292. * @param string $itemType
  1293. * @param string $item Item source or target (optional)
  1294. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
  1295. * @param string $shareWith User or group the item is being shared with
  1296. * @param string $uidOwner User that is the owner of shared items (optional)
  1297. * @param int $format Format to convert items to with formatItems() (optional)
  1298. * @param mixed $parameters to pass to formatItems() (optional)
  1299. * @param int $limit Number of items to return, -1 to return all matches (optional)
  1300. * @param boolean $includeCollections Include collection item types (optional)
  1301. * @param boolean $itemShareWithBySource (optional)
  1302. * @param boolean $checkExpireDate
  1303. * @return array
  1304. *
  1305. * See public functions getItem(s)... for parameter usage
  1306. *
  1307. */
  1308. public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
  1309. $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
  1310. $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate = true) {
  1311. if (!self::isEnabled()) {
  1312. return array();
  1313. }
  1314. $backend = self::getBackend($itemType);
  1315. $collectionTypes = false;
  1316. // Get filesystem root to add it to the file target and remove from the
  1317. // file source, match file_source with the file cache
  1318. if ($itemType == 'file' || $itemType == 'folder') {
  1319. if(!is_null($uidOwner)) {
  1320. $root = \OC\Files\Filesystem::getRoot();
  1321. } else {
  1322. $root = '';
  1323. }
  1324. $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
  1325. if (!isset($item)) {
  1326. $where .= ' AND `file_target` IS NOT NULL ';
  1327. }
  1328. $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
  1329. $fileDependent = true;
  1330. $queryArgs = array();
  1331. } else {
  1332. $fileDependent = false;
  1333. $root = '';
  1334. $collectionTypes = self::getCollectionItemTypes($itemType);
  1335. if ($includeCollections && !isset($item) && $collectionTypes) {
  1336. // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
  1337. if (!in_array($itemType, $collectionTypes)) {
  1338. $itemTypes = array_merge(array($itemType), $collectionTypes);
  1339. } else {
  1340. $itemTypes = $collectionTypes;
  1341. }
  1342. $placeholders = join(',', array_fill(0, count($itemTypes), '?'));
  1343. $where = ' WHERE `item_type` IN ('.$placeholders.'))';
  1344. $queryArgs = $itemTypes;
  1345. } else {
  1346. $where = ' WHERE `item_type` = ?';
  1347. $queryArgs = array($itemType);
  1348. }
  1349. }
  1350. if (\OC_Appconfig::getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
  1351. $where .= ' AND `share_type` != ?';
  1352. $queryArgs[] = self::SHARE_TYPE_LINK;
  1353. }
  1354. if (isset($shareType)) {
  1355. // Include all user and group items
  1356. if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
  1357. $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
  1358. $queryArgs[] = self::SHARE_TYPE_USER;
  1359. $queryArgs[] = self::$shareTypeGroupUserUnique;
  1360. $queryArgs[] = $shareWith;
  1361. $groups = \OC_Group::getUserGroups($shareWith);
  1362. if (!empty($groups)) {
  1363. $placeholders = join(',', array_fill(0, count($groups), '?'));
  1364. $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
  1365. $queryArgs[] = self::SHARE_TYPE_GROUP;
  1366. $queryArgs = array_merge($queryArgs, $groups);
  1367. }
  1368. $where .= ')';
  1369. // Don't include own group shares
  1370. $where .= ' AND `uid_owner` != ?';
  1371. $queryArgs[] = $shareWith;
  1372. } else {
  1373. $where .= ' AND `share_type` = ?';
  1374. $queryArgs[] = $shareType;
  1375. if (isset($shareWith)) {
  1376. $where .= ' AND `share_with` = ?';
  1377. $queryArgs[] = $shareWith;
  1378. }
  1379. }
  1380. }
  1381. if (isset($uidOwner)) {
  1382. $where .= ' AND `uid_owner` = ?';
  1383. $queryArgs[] = $uidOwner;
  1384. if (!isset($shareType)) {
  1385. // Prevent unique user targets for group shares from being selected
  1386. $where .= ' AND `share_type` != ?';
  1387. $queryArgs[] = self::$shareTypeGroupUserUnique;
  1388. }
  1389. if ($fileDependent) {
  1390. $column = 'file_source';
  1391. } else {
  1392. $column = 'item_source';
  1393. }
  1394. } else {
  1395. if ($fileDependent) {
  1396. $column = 'file_target';
  1397. } else {
  1398. $column = 'item_target';
  1399. }
  1400. }
  1401. if (isset($item)) {
  1402. $collectionTypes = self::getCollectionItemTypes($itemType);
  1403. if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
  1404. $where .= ' AND (';
  1405. } else {
  1406. $where .= ' AND';
  1407. }
  1408. // If looking for own shared items, check item_source else check item_target
  1409. if (isset($uidOwner) || $itemShareWithBySource) {
  1410. // If item type is a file, file source needs to be checked in case the item was converted
  1411. if ($fileDependent) {
  1412. $where .= ' `file_source` = ?';
  1413. $column = 'file_source';
  1414. } else {
  1415. $where .= ' `item_source` = ?';
  1416. $column = 'item_source';
  1417. }
  1418. } else {
  1419. if ($fileDependent) {
  1420. $where .= ' `file_target` = ?';
  1421. $item = \OC\Files\Filesystem::normalizePath($item);
  1422. } else {
  1423. $where .= ' `item_target` = ?';
  1424. }
  1425. }
  1426. $queryArgs[] = $item;
  1427. if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
  1428. $placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
  1429. $where .= ' OR `item_type` IN ('.$placeholders.'))';
  1430. $queryArgs = array_merge($queryArgs, $collectionTypes);
  1431. }
  1432. }
  1433. if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
  1434. // Make sure the unique user target is returned if it exists,
  1435. // unique targets should follow the group share in the database
  1436. // If the limit is not 1, the filtering can be done later
  1437. $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
  1438. } else {
  1439. $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
  1440. }
  1441. if ($limit != -1 && !$includeCollections) {
  1442. // The limit must be at least 3, because filtering needs to be done
  1443. if ($limit < 3) {
  1444. $queryLimit = 3;
  1445. } else {
  1446. $queryLimit = $limit;
  1447. }
  1448. } else {
  1449. $queryLimit = null;
  1450. }
  1451. $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
  1452. $root = strlen($root);
  1453. $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
  1454. $result = $query->execute($queryArgs);
  1455. if (\OC_DB::isError($result)) {
  1456. \OC_Log::write('OCP\Share',
  1457. \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
  1458. \OC_Log::ERROR);
  1459. }
  1460. $items = array();
  1461. $targets = array();
  1462. $switchedItems = array();
  1463. $mounts = array();
  1464. while ($row = $result->fetchRow()) {
  1465. self::transformDBResults($row);
  1466. // Filter out duplicate group shares for users with unique targets
  1467. if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
  1468. continue;
  1469. }
  1470. if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
  1471. $row['share_type'] = self::SHARE_TYPE_GROUP;
  1472. $row['unique_name'] = true; // remember that we use a unique name for this user
  1473. $row['share_with'] = $items[$row['parent']]['share_with'];
  1474. // if the group share was unshared from the user we keep the permission, otherwise
  1475. // we take the permission from the parent because this is always the up-to-date
  1476. // permission for the group share
  1477. if ($row['permissions'] > 0) {
  1478. $row['permissions'] = $items[$row['parent']]['permissions'];
  1479. }
  1480. // Remove the parent group share
  1481. unset($items[$row['parent']]);
  1482. if ($row['permissions'] == 0) {
  1483. continue;
  1484. }
  1485. } else if (!isset($uidOwner)) {
  1486. // Check if the same target already exists
  1487. if (isset($targets[$row['id']])) {
  1488. // Check if the same owner shared with the user twice
  1489. // through a group and user share - this is allowed
  1490. $id = $targets[$row['id']];
  1491. if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
  1492. // Switch to group share type to ensure resharing conditions aren't bypassed
  1493. if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
  1494. $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
  1495. $items[$id]['share_with'] = $row['share_with'];
  1496. }
  1497. // Switch ids if sharing permission is granted on only
  1498. // one share to ensure correct parent is used if resharing
  1499. if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
  1500. && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
  1501. $items[$row['id']] = $items[$id];
  1502. $switchedItems[$id] = $row['id'];
  1503. unset($items[$id]);
  1504. $id = $row['id'];
  1505. }
  1506. $items[$id]['permissions'] |= (int)$row['permissions'];
  1507. }
  1508. continue;
  1509. } elseif (!empty($row['parent'])) {
  1510. $targets[$row['parent']] = $row['id'];
  1511. }
  1512. }
  1513. // Remove root from file source paths if retrieving own shared items
  1514. if (isset($uidOwner) && isset($row['path'])) {
  1515. if (isset($row['parent'])) {
  1516. $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
  1517. $parentResult = $query->execute(array($row['parent']));
  1518. if (\OC_DB::isError($result)) {
  1519. \OC_Log::write('OCP\Share', 'Can\'t select parent: ' .
  1520. \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
  1521. \OC_Log::ERROR);
  1522. } else {
  1523. $parentRow = $parentResult->fetchRow();
  1524. $tmpPath = $parentRow['file_target'];
  1525. // find the right position where the row path continues from the target path
  1526. $pos = strrpos($row['path'], $parentRow['file_target']);
  1527. $subPath = substr($row['path'], $pos);
  1528. $splitPath = explode('/', $subPath);
  1529. foreach (array_slice($splitPath, 2) as $pathPart) {
  1530. $tmpPath = $tmpPath . '/' . $pathPart;
  1531. }
  1532. $row['path'] = $tmpPath;
  1533. }
  1534. } else {
  1535. if (!isset($mounts[$row['storage']])) {
  1536. $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
  1537. if (is_array($mountPoints) && !empty($mountPoints)) {
  1538. $mounts[$row['storage']] = current($mountPoints);
  1539. }
  1540. }
  1541. if (!empty($mounts[$row['storage']])) {
  1542. $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
  1543. $relPath = substr($path, $root); // path relative to data/user
  1544. $row['path'] = rtrim($relPath, '/');
  1545. }
  1546. }
  1547. }
  1548. if($checkExpireDate) {
  1549. if (self::expireItem($row)) {
  1550. continue;
  1551. }
  1552. }
  1553. // Check if resharing is allowed, if not remove share permission
  1554. if (isset($row['permissions']) && (!self::isResharingAllowed() | \OC_Util::isSharingDisabledForUser())) {
  1555. $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
  1556. }
  1557. // Add display names to result
  1558. if ( isset($row['share_with']) && $row['share_with'] != '' &&
  1559. isset($row['share_with']) && $row['share_type'] === self::SHARE_TYPE_USER) {
  1560. $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
  1561. } else {
  1562. $row['share_with_displayname'] = $row['share_with'];
  1563. }
  1564. if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
  1565. $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
  1566. }
  1567. if ($row['permissions'] > 0) {
  1568. $items[$row['id']] = $row;
  1569. }
  1570. }
  1571. // group items if we are looking for items shared with the current user
  1572. if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
  1573. $items = self::groupItems($items, $itemType);
  1574. }
  1575. if (!empty($items)) {
  1576. $collectionItems = array();
  1577. foreach ($items as &$row) {
  1578. // Return only the item instead of a 2-dimensional array
  1579. if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
  1580. if ($format == self::FORMAT_NONE) {
  1581. return $row;
  1582. } else {
  1583. break;
  1584. }
  1585. }
  1586. // Check if this is a collection of the requested item type
  1587. if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
  1588. if (($collectionBackend = self::getBackend($row['item_type']))
  1589. && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
  1590. // Collections can be inside collections, check if the item is a collection
  1591. if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
  1592. $collectionItems[] = $row;
  1593. } else {
  1594. $collection = array();
  1595. $collection['item_type'] = $row['item_type'];
  1596. if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
  1597. $collection['path'] = basename($row['path']);
  1598. }
  1599. $row['collection'] = $collection;
  1600. // Fetch all of the children sources
  1601. $children = $collectionBackend->getChildren($row[$column]);
  1602. foreach ($children as $child) {
  1603. $childItem = $row;
  1604. $childItem['item_type'] = $itemType;
  1605. if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
  1606. $childItem['item_source'] = $child['source'];
  1607. $childItem['item_target'] = $child['target'];
  1608. }
  1609. if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
  1610. if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
  1611. $childItem['file_source'] = $child['source'];
  1612. } else { // TODO is this really needed if we already know that we use the file backend?
  1613. $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
  1614. $childItem['file_source'] = $meta['fileid'];
  1615. }
  1616. $childItem['file_target'] =
  1617. \OC\Files\Filesystem::normalizePath($child['file_path']);
  1618. }
  1619. if (isset($item)) {
  1620. if ($childItem[$column] == $item) {
  1621. // Return only the item instead of a 2-dimensional array
  1622. if ($limit == 1) {
  1623. if ($format == self::FORMAT_NONE) {
  1624. return $childItem;
  1625. } else {
  1626. // Unset the items array and break out of both loops
  1627. $items = array();
  1628. $items[] = $childItem;
  1629. break 2;
  1630. }
  1631. } else {
  1632. $collectionItems[] = $childItem;
  1633. }
  1634. }
  1635. } else {
  1636. $collectionItems[] = $childItem;
  1637. }
  1638. }
  1639. }
  1640. }
  1641. // Remove collection item
  1642. $toRemove = $row['id'];
  1643. if (array_key_exists($toRemove, $switchedItems)) {
  1644. $toRemove = $switchedItems[$toRemove];
  1645. }
  1646. unset($items[$toRemove]);
  1647. } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
  1648. // FIXME: Thats a dirty hack to improve file sharing performance,
  1649. // see github issue #10588 for more details
  1650. // Need to find a solution which works for all back-ends
  1651. $collectionBackend = self::getBackend($row['item_type']);
  1652. $sharedParents = $collectionBackend->getParents($row['item_source']);
  1653. foreach ($sharedParents as $parent) {
  1654. $collectionItems[] = $parent;
  1655. }
  1656. }
  1657. }
  1658. if (!empty($collectionItems)) {
  1659. $items = array_merge($items, $collectionItems);
  1660. }
  1661. return self::formatResult($items, $column, $backend, $format, $parameters);
  1662. } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
  1663. // FIXME: Thats a dirty hack to improve file sharing performance,
  1664. // see github issue #10588 for more details
  1665. // Need to find a solution which works for all back-ends
  1666. $collectionItems = array();
  1667. $collectionBackend = self::getBackend('folder');
  1668. $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
  1669. foreach ($sharedParents as $parent) {
  1670. $collectionItems[] = $parent;
  1671. }
  1672. if ($limit === 1) {
  1673. return reset($collectionItems);
  1674. }
  1675. return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
  1676. }
  1677. return array();
  1678. }
  1679. /**
  1680. * group items with link to the same source
  1681. *
  1682. * @param array $items
  1683. * @param string $itemType
  1684. * @return array of grouped items
  1685. */
  1686. protected static function groupItems($items, $itemType) {
  1687. $fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
  1688. $result = array();
  1689. foreach ($items as $item) {
  1690. $grouped = false;
  1691. foreach ($result as $key => $r) {
  1692. // for file/folder shares we need to compare file_source, otherwise we compare item_source
  1693. // only group shares if they already point to the same target, otherwise the file where shared
  1694. // before grouping of shares was added. In this case we don't group them toi avoid confusions
  1695. if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
  1696. (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
  1697. // add the first item to the list of grouped shares
  1698. if (!isset($result[$key]['grouped'])) {
  1699. $result[$key]['grouped'][] = $result[$key];
  1700. }
  1701. $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
  1702. $result[$key]['grouped'][] = $item;
  1703. $grouped = true;
  1704. break;
  1705. }
  1706. }
  1707. if (!$grouped) {
  1708. $result[] = $item;
  1709. }
  1710. }
  1711. return $result;
  1712. }
  1713. /**
  1714. * Put shared item into the database
  1715. * @param string $itemType Item type
  1716. * @param string $itemSource Item source
  1717. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  1718. * @param string $shareWith User or group the item is being shared with
  1719. * @param string $uidOwner User that is the owner of shared item
  1720. * @param int $permissions CRUDS permissions
  1721. * @param boolean|array $parentFolder Parent folder target (optional)
  1722. * @param string $token (optional)
  1723. * @param string $itemSourceName name of the source item (optional)
  1724. * @param \DateTime $expirationDate (optional)
  1725. * @throws \Exception
  1726. * @return mixed id of the new share or false
  1727. */
  1728. private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
  1729. $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
  1730. $queriesToExecute = array();
  1731. $suggestedItemTarget = null;
  1732. $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
  1733. if(!empty($result)) {
  1734. $parent = $result['parent'];
  1735. $itemSource = $result['itemSource'];
  1736. $fileSource = $result['fileSource'];
  1737. $suggestedItemTarget = $result['suggestedItemTarget'];
  1738. $suggestedFileTarget = $result['suggestedFileTarget'];
  1739. $filePath = $result['filePath'];
  1740. $expirationDate = $result['expirationDate'];
  1741. }
  1742. $isGroupShare = false;
  1743. if ($shareType == self::SHARE_TYPE_GROUP) {
  1744. $isGroupShare = true;
  1745. if (isset($shareWith['users'])) {
  1746. $users = $shareWith['users'];
  1747. } else {
  1748. $users = \OC_Group::usersInGroup($shareWith['group']);
  1749. }
  1750. // remove current user from list
  1751. if (in_array(\OCP\User::getUser(), $users)) {
  1752. unset($users[array_search(\OCP\User::getUser(), $users)]);
  1753. }
  1754. $groupItemTarget = Helper::generateTarget($itemType, $itemSource,
  1755. $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
  1756. $groupFileTarget = Helper::generateTarget($itemType, $itemSource,
  1757. $shareType, $shareWith['group'], $uidOwner, $filePath);
  1758. // add group share to table and remember the id as parent
  1759. $queriesToExecute['groupShare'] = array(
  1760. 'itemType' => $itemType,
  1761. 'itemSource' => $itemSource,
  1762. 'itemTarget' => $groupItemTarget,
  1763. 'shareType' => $shareType,
  1764. 'shareWith' => $shareWith['group'],
  1765. 'uidOwner' => $uidOwner,
  1766. 'permissions' => $permissions,
  1767. 'shareTime' => time(),
  1768. 'fileSource' => $fileSource,
  1769. 'fileTarget' => $groupFileTarget,
  1770. 'token' => $token,
  1771. 'parent' => $parent,
  1772. 'expiration' => $expirationDate,
  1773. );
  1774. } else {
  1775. $users = array($shareWith);
  1776. $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
  1777. $suggestedItemTarget);
  1778. }
  1779. $run = true;
  1780. $error = '';
  1781. $preHookData = array(
  1782. 'itemType' => $itemType,
  1783. 'itemSource' => $itemSource,
  1784. 'shareType' => $shareType,
  1785. 'uidOwner' => $uidOwner,
  1786. 'permissions' => $permissions,
  1787. 'fileSource' => $fileSource,
  1788. 'expiration' => $expirationDate,
  1789. 'token' => $token,
  1790. 'run' => &$run,
  1791. 'error' => &$error
  1792. );
  1793. $preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
  1794. $preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
  1795. \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
  1796. if ($run === false) {
  1797. throw new \Exception($error);
  1798. }
  1799. foreach ($users as $user) {
  1800. $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
  1801. $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
  1802. $userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
  1803. if ($sourceExists) {
  1804. $fileTarget = $sourceExists['file_target'];
  1805. $itemTarget = $sourceExists['item_target'];
  1806. // for group shares we don't need a additional entry if the target is the same
  1807. if($isGroupShare && $groupItemTarget === $itemTarget) {
  1808. continue;
  1809. }
  1810. } elseif(!$sourceExists && !$isGroupShare) {
  1811. $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
  1812. $uidOwner, $suggestedItemTarget, $parent);
  1813. if (isset($fileSource)) {
  1814. if ($parentFolder) {
  1815. if ($parentFolder === true) {
  1816. $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
  1817. $uidOwner, $suggestedFileTarget, $parent);
  1818. if ($fileTarget != $groupFileTarget) {
  1819. $parentFolders[$user]['folder'] = $fileTarget;
  1820. }
  1821. } else if (isset($parentFolder[$user])) {
  1822. $fileTarget = $parentFolder[$user]['folder'].$itemSource;
  1823. $parent = $parentFolder[$user]['id'];
  1824. }
  1825. } else {
  1826. $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
  1827. $user, $uidOwner, $suggestedFileTarget, $parent);
  1828. }
  1829. } else {
  1830. $fileTarget = null;
  1831. }
  1832. } else {
  1833. // group share which doesn't exists until now, check if we need a unique target for this user
  1834. $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
  1835. $uidOwner, $suggestedItemTarget, $parent);
  1836. // do we also need a file target
  1837. if (isset($fileSource)) {
  1838. $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
  1839. $uidOwner, $suggestedFileTarget, $parent);
  1840. } else {
  1841. $fileTarget = null;
  1842. }
  1843. if (($itemTarget === $groupItemTarget) &&
  1844. (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
  1845. continue;
  1846. }
  1847. }
  1848. $queriesToExecute[] = array(
  1849. 'itemType' => $itemType,
  1850. 'itemSource' => $itemSource,
  1851. 'itemTarget' => $itemTarget,
  1852. 'shareType' => $userShareType,
  1853. 'shareWith' => $user,
  1854. 'uidOwner' => $uidOwner,
  1855. 'permissions' => $permissions,
  1856. 'shareTime' => time(),
  1857. 'fileSource' => $fileSource,
  1858. 'fileTarget' => $fileTarget,
  1859. 'token' => $token,
  1860. 'parent' => $parent,
  1861. 'expiration' => $expirationDate,
  1862. );
  1863. }
  1864. $id = false;
  1865. if ($isGroupShare) {
  1866. $id = self::insertShare($queriesToExecute['groupShare']);
  1867. // Save this id, any extra rows for this group share will need to reference it
  1868. $parent = \OC_DB::insertid('*PREFIX*share');
  1869. unset($queriesToExecute['groupShare']);
  1870. }
  1871. foreach ($queriesToExecute as $shareQuery) {
  1872. $shareQuery['parent'] = $parent;
  1873. $id = self::insertShare($shareQuery);
  1874. }
  1875. $postHookData = array(
  1876. 'itemType' => $itemType,
  1877. 'itemSource' => $itemSource,
  1878. 'parent' => $parent,
  1879. 'shareType' => $shareType,
  1880. 'uidOwner' => $uidOwner,
  1881. 'permissions' => $permissions,
  1882. 'fileSource' => $fileSource,
  1883. 'id' => $parent,
  1884. 'token' => $token,
  1885. 'expirationDate' => $expirationDate,
  1886. );
  1887. $postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
  1888. $postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
  1889. $postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
  1890. \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
  1891. return $id ? $id : false;
  1892. }
  1893. private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
  1894. $backend = self::getBackend($itemType);
  1895. $l = \OC::$server->getL10N('lib');
  1896. $result = array();
  1897. $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
  1898. $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
  1899. if ($checkReshare) {
  1900. // Check if attempting to share back to owner
  1901. if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
  1902. $message = 'Sharing %s failed, because the user %s is the original sharer';
  1903. $message_t = $l->t('Sharing %s failed, because the user %s is the original sharer', array($itemSourceName, $shareWith));
  1904. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OC_Log::ERROR);
  1905. throw new \Exception($message_t);
  1906. }
  1907. }
  1908. if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
  1909. // Check if share permissions is granted
  1910. if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
  1911. if (~(int)$checkReshare['permissions'] & $permissions) {
  1912. $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
  1913. $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
  1914. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OC_Log::ERROR);
  1915. throw new \Exception($message_t);
  1916. } else {
  1917. // TODO Don't check if inside folder
  1918. $result['parent'] = $checkReshare['id'];
  1919. $result['expirationDate'] = min($expirationDate, $checkReshare['expiration']);
  1920. // only suggest the same name as new target if it is a reshare of the
  1921. // same file/folder and not the reshare of a child
  1922. if ($checkReshare[$column] === $itemSource) {
  1923. $result['filePath'] = $checkReshare['file_target'];
  1924. $result['itemSource'] = $checkReshare['item_source'];
  1925. $result['fileSource'] = $checkReshare['file_source'];
  1926. $result['suggestedItemTarget'] = $checkReshare['item_target'];
  1927. $result['suggestedFileTarget'] = $checkReshare['file_target'];
  1928. } else {
  1929. $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
  1930. $result['suggestedItemTarget'] = null;
  1931. $result['suggestedFileTarget'] = null;
  1932. $result['itemSource'] = $itemSource;
  1933. $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
  1934. }
  1935. }
  1936. } else {
  1937. $message = 'Sharing %s failed, because resharing is not allowed';
  1938. $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
  1939. \OC_Log::write('OCP\Share', sprintf($message, $itemSourceName), \OC_Log::ERROR);
  1940. throw new \Exception($message_t);
  1941. }
  1942. } else {
  1943. $result['parent'] = null;
  1944. $result['suggestedItemTarget'] = null;
  1945. $result['suggestedFileTarget'] = null;
  1946. $result['itemSource'] = $itemSource;
  1947. $result['expirationDate'] = $expirationDate;
  1948. if (!$backend->isValidSource($itemSource, $uidOwner)) {
  1949. $message = 'Sharing %s failed, because the sharing backend for '
  1950. .'%s could not find its source';
  1951. $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
  1952. \OC_Log::write('OCP\Share', sprintf($message, $itemSource, $itemType), \OC_Log::ERROR);
  1953. throw new \Exception($message_t);
  1954. }
  1955. if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
  1956. $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
  1957. if ($itemType == 'file' || $itemType == 'folder') {
  1958. $result['fileSource'] = $itemSource;
  1959. } else {
  1960. $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
  1961. $result['fileSource'] = $meta['fileid'];
  1962. }
  1963. if ($result['fileSource'] == -1) {
  1964. $message = 'Sharing %s failed, because the file could not be found in the file cache';
  1965. $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
  1966. \OC_Log::write('OCP\Share', sprintf($message, $itemSource), \OC_Log::ERROR);
  1967. throw new \Exception($message_t);
  1968. }
  1969. } else {
  1970. $result['filePath'] = null;
  1971. $result['fileSource'] = null;
  1972. }
  1973. }
  1974. return $result;
  1975. }
  1976. /**
  1977. *
  1978. * @param array $shareData
  1979. * @return mixed false in case of a failure or the id of the new share
  1980. */
  1981. private static function insertShare(array $shareData) {
  1982. $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
  1983. .' `item_type`, `item_source`, `item_target`, `share_type`,'
  1984. .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
  1985. .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
  1986. $query->bindValue(1, $shareData['itemType']);
  1987. $query->bindValue(2, $shareData['itemSource']);
  1988. $query->bindValue(3, $shareData['itemTarget']);
  1989. $query->bindValue(4, $shareData['shareType']);
  1990. $query->bindValue(5, $shareData['shareWith']);
  1991. $query->bindValue(6, $shareData['uidOwner']);
  1992. $query->bindValue(7, $shareData['permissions']);
  1993. $query->bindValue(8, $shareData['shareTime']);
  1994. $query->bindValue(9, $shareData['fileSource']);
  1995. $query->bindValue(10, $shareData['fileTarget']);
  1996. $query->bindValue(11, $shareData['token']);
  1997. $query->bindValue(12, $shareData['parent']);
  1998. $query->bindValue(13, $shareData['expiration'], 'datetime');
  1999. $result = $query->execute();
  2000. $id = false;
  2001. if ($result) {
  2002. $id = \OC::$server->getDatabaseConnection()->lastInsertId();
  2003. // Fallback, if lastInterId() doesn't work we need to perform a select
  2004. // to get the ID (seems to happen sometimes on Oracle)
  2005. if (!$id) {
  2006. $getId = \OC_DB::prepare('
  2007. SELECT `id`
  2008. FROM`*PREFIX*share`
  2009. WHERE `uid_owner` = ? AND `item_target` = ? AND `item_source` = ? AND `stime` = ?
  2010. ');
  2011. $r = $getId->execute(array($shareData['uidOwner'], $shareData['itemTarget'], $shareData['itemSource'], $shareData['shareTime']));
  2012. if ($r) {
  2013. $row = $r->fetchRow();
  2014. $id = $row['id'];
  2015. }
  2016. }
  2017. }
  2018. return $id;
  2019. }
  2020. /**
  2021. * Delete all shares with type SHARE_TYPE_LINK
  2022. */
  2023. public static function removeAllLinkShares() {
  2024. // Delete any link shares
  2025. $query = \OC_DB::prepare('SELECT `id` FROM `*PREFIX*share` WHERE `share_type` = ?');
  2026. $result = $query->execute(array(self::SHARE_TYPE_LINK));
  2027. while ($item = $result->fetchRow()) {
  2028. Helper::delete($item['id']);
  2029. }
  2030. }
  2031. /**
  2032. * In case a password protected link is not yet authenticated this function will return false
  2033. *
  2034. * @param array $linkItem
  2035. * @return boolean
  2036. */
  2037. public static function checkPasswordProtectedShare(array $linkItem) {
  2038. if (!isset($linkItem['share_with'])) {
  2039. return true;
  2040. }
  2041. if (!isset($linkItem['share_type'])) {
  2042. return true;
  2043. }
  2044. if (!isset($linkItem['id'])) {
  2045. return true;
  2046. }
  2047. if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
  2048. return true;
  2049. }
  2050. if ( \OC::$server->getSession()->exists('public_link_authenticated')
  2051. && \OC::$server->getSession()->get('public_link_authenticated') === $linkItem['id'] ) {
  2052. return true;
  2053. }
  2054. return false;
  2055. }
  2056. /**
  2057. * construct select statement
  2058. * @param int $format
  2059. * @param boolean $fileDependent ist it a file/folder share or a generla share
  2060. * @param string $uidOwner
  2061. * @return string select statement
  2062. */
  2063. private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
  2064. $select = '*';
  2065. if ($format == self::FORMAT_STATUSES) {
  2066. if ($fileDependent) {
  2067. $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
  2068. . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
  2069. . '`*PREFIX*storages`.`id` AS `storage_id`';
  2070. } else {
  2071. $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
  2072. }
  2073. } else {
  2074. if (isset($uidOwner)) {
  2075. if ($fileDependent) {
  2076. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
  2077. . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
  2078. . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
  2079. . '`*PREFIX*storages`.`id` AS `storage_id`';
  2080. } else {
  2081. $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
  2082. . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
  2083. }
  2084. } else {
  2085. if ($fileDependent) {
  2086. if ($format == \OC_Share_Backend_File::FORMAT_GET_FOLDER_CONTENTS || $format == \OC_Share_Backend_File::FORMAT_FILE_APP_ROOT) {
  2087. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
  2088. . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
  2089. . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
  2090. . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
  2091. } else {
  2092. $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
  2093. . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
  2094. . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
  2095. . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
  2096. . '`*PREFIX*storages`.`id` AS `storage_id`';
  2097. }
  2098. }
  2099. }
  2100. }
  2101. return $select;
  2102. }
  2103. /**
  2104. * transform db results
  2105. * @param array $row result
  2106. */
  2107. private static function transformDBResults(&$row) {
  2108. if (isset($row['id'])) {
  2109. $row['id'] = (int) $row['id'];
  2110. }
  2111. if (isset($row['share_type'])) {
  2112. $row['share_type'] = (int) $row['share_type'];
  2113. }
  2114. if (isset($row['parent'])) {
  2115. $row['parent'] = (int) $row['parent'];
  2116. }
  2117. if (isset($row['file_parent'])) {
  2118. $row['file_parent'] = (int) $row['file_parent'];
  2119. }
  2120. if (isset($row['file_source'])) {
  2121. $row['file_source'] = (int) $row['file_source'];
  2122. }
  2123. if (isset($row['permissions'])) {
  2124. $row['permissions'] = (int) $row['permissions'];
  2125. }
  2126. if (isset($row['storage'])) {
  2127. $row['storage'] = (int) $row['storage'];
  2128. }
  2129. if (isset($row['stime'])) {
  2130. $row['stime'] = (int) $row['stime'];
  2131. }
  2132. }
  2133. /**
  2134. * format result
  2135. * @param array $items result
  2136. * @param string $column is it a file share or a general share ('file_target' or 'item_target')
  2137. * @param \OCP\Share_Backend $backend sharing backend
  2138. * @param int $format
  2139. * @param array $parameters additional format parameters
  2140. * @return array format result
  2141. */
  2142. private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
  2143. if ($format === self::FORMAT_NONE) {
  2144. return $items;
  2145. } else if ($format === self::FORMAT_STATUSES) {
  2146. $statuses = array();
  2147. foreach ($items as $item) {
  2148. if ($item['share_type'] === self::SHARE_TYPE_LINK) {
  2149. $statuses[$item[$column]]['link'] = true;
  2150. } else if (!isset($statuses[$item[$column]])) {
  2151. $statuses[$item[$column]]['link'] = false;
  2152. }
  2153. if (!empty($item['file_target'])) {
  2154. $statuses[$item[$column]]['path'] = $item['path'];
  2155. }
  2156. }
  2157. return $statuses;
  2158. } else {
  2159. return $backend->formatItems($items, $format, $parameters);
  2160. }
  2161. }
  2162. /**
  2163. * remove protocol from URL
  2164. *
  2165. * @param string $url
  2166. * @return string
  2167. */
  2168. private static function removeProtocolFromUrl($url) {
  2169. if (strpos($url, 'https://') === 0) {
  2170. return substr($url, strlen('https://'));
  2171. } else if (strpos($url, 'http://') === 0) {
  2172. return substr($url, strlen('http://'));
  2173. }
  2174. return $url;
  2175. }
  2176. /**
  2177. * try http post first with https and then with http as a fallback
  2178. *
  2179. * @param string $url
  2180. * @param array $fields post parameters
  2181. * @return array
  2182. */
  2183. private static function tryHttpPost($url, $fields) {
  2184. $protocol = 'https://';
  2185. $result = [
  2186. 'success' => false,
  2187. 'result' => '',
  2188. ];
  2189. $try = 0;
  2190. while ($result['success'] === false && $try < 2) {
  2191. $result = \OC::$server->getHTTPHelper()->post($protocol . $url, $fields);
  2192. $try++;
  2193. $protocol = 'http://';
  2194. }
  2195. return $result;
  2196. }
  2197. /**
  2198. * send server-to-server share to remote server
  2199. *
  2200. * @param string $token
  2201. * @param string $shareWith
  2202. * @param string $name
  2203. * @param int $remote_id
  2204. * @param string $owner
  2205. * @return bool
  2206. */
  2207. private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
  2208. list($user, $remote) = explode('@', $shareWith, 2);
  2209. if ($user && $remote) {
  2210. $url = rtrim($remote, '/') . self::BASE_PATH_TO_SHARE_API . '?format=' . self::RESPONSE_FORMAT;
  2211. $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
  2212. $fields = array(
  2213. 'shareWith' => $user,
  2214. 'token' => $token,
  2215. 'name' => $name,
  2216. 'remoteId' => $remote_id,
  2217. 'owner' => $owner,
  2218. 'remote' => $local,
  2219. );
  2220. $url = self::removeProtocolFromUrl($url);
  2221. $result = self::tryHttpPost($url, $fields);
  2222. $status = json_decode($result['result'], true);
  2223. return ($result['success'] && $status['ocs']['meta']['statuscode'] === 100);
  2224. }
  2225. return false;
  2226. }
  2227. /**
  2228. * send server-to-server unshare to remote server
  2229. *
  2230. * @param string $remote url
  2231. * @param int $id share id
  2232. * @param string $token
  2233. * @return bool
  2234. */
  2235. private static function sendRemoteUnshare($remote, $id, $token) {
  2236. $url = rtrim($remote, '/') . self::BASE_PATH_TO_SHARE_API . '/' . $id . '/unshare?format=' . self::RESPONSE_FORMAT;
  2237. $fields = array('token' => $token, 'format' => 'json');
  2238. $url = self::removeProtocolFromUrl($url);
  2239. $result = self::tryHttpPost($url, $fields);
  2240. $status = json_decode($result['result'], true);
  2241. return ($result['success'] && $status['ocs']['meta']['statuscode'] === 100);
  2242. }
  2243. /**
  2244. * check if user can only share with group members
  2245. * @return bool
  2246. */
  2247. public static function shareWithGroupMembersOnly() {
  2248. $value = \OC_Appconfig::getValue('core', 'shareapi_only_share_with_group_members', 'no');
  2249. return ($value === 'yes') ? true : false;
  2250. }
  2251. /**
  2252. * @return bool
  2253. */
  2254. public static function isDefaultExpireDateEnabled() {
  2255. $defaultExpireDateEnabled = \OCP\Config::getAppValue('core', 'shareapi_default_expire_date', 'no');
  2256. return ($defaultExpireDateEnabled === "yes") ? true : false;
  2257. }
  2258. /**
  2259. * @return bool
  2260. */
  2261. public static function enforceDefaultExpireDate() {
  2262. $enforceDefaultExpireDate = \OCP\Config::getAppValue('core', 'shareapi_enforce_expire_date', 'no');
  2263. return ($enforceDefaultExpireDate === "yes") ? true : false;
  2264. }
  2265. /**
  2266. * @return int
  2267. */
  2268. public static function getExpireInterval() {
  2269. return (int)\OCP\Config::getAppValue('core', 'shareapi_expire_after_n_days', '7');
  2270. }
  2271. /**
  2272. * Checks whether the given path is reachable for the given owner
  2273. *
  2274. * @param string $path path relative to files
  2275. * @param string $ownerStorageId storage id of the owner
  2276. *
  2277. * @return boolean true if file is reachable, false otherwise
  2278. */
  2279. private static function isFileReachable($path, $ownerStorageId) {
  2280. // if outside the home storage, file is always considered reachable
  2281. if (!(substr($ownerStorageId, 0, 6) === 'home::')) {
  2282. return true;
  2283. }
  2284. // if inside the home storage, the file has to be under "/files/"
  2285. $path = ltrim($path, '/');
  2286. if (substr($path, 0, 6) === 'files/') {
  2287. return true;
  2288. }
  2289. return false;
  2290. }
  2291. /**
  2292. * @param IConfig $config
  2293. * @return bool
  2294. */
  2295. public static function enforcePassword(IConfig $config) {
  2296. $enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
  2297. return ($enforcePassword === "yes") ? true : false;
  2298. }
  2299. /**
  2300. * Get all share entries, including non-unique group items
  2301. *
  2302. * @param string $owner
  2303. * @return array
  2304. */
  2305. public static function getAllSharesForOwner($owner) {
  2306. $query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
  2307. $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
  2308. return $result->fetchAll();
  2309. }
  2310. /**
  2311. * Get all share entries, including non-unique group items for a file
  2312. *
  2313. * @param int $id
  2314. * @return array
  2315. */
  2316. public static function getAllSharesForFileId($id) {
  2317. $query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
  2318. $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
  2319. return $result->fetchAll();
  2320. }
  2321. }