Share.php 80 KB

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