Share.php 80 KB

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