You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

294 lines
9.9 KiB

3 years ago
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Björn Schießle <bjoern@schiessle.org>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Miguel Prokop <miguel.prokop@vtu.com>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Robin McCorkell <robin@mccorkell.me.uk>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <pvince81@owncloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Share;
  31. use OC\HintException;
  32. use OCP\Share\IShare;
  33. class Helper extends \OC\Share\Constants {
  34. /**
  35. * Generate a unique target for the item
  36. * @param string $itemType
  37. * @param string $itemSource
  38. * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
  39. * @param string $shareWith User or group the item is being shared with
  40. * @param string $uidOwner User that is the owner of shared item
  41. * @param string $suggestedTarget The suggested target originating from a reshare (optional)
  42. * @param int $groupParent The id of the parent group share (optional)
  43. * @throws \Exception
  44. * @return string Item target
  45. */
  46. public static function generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $suggestedTarget = null, $groupParent = null) {
  47. // FIXME: $uidOwner and $groupParent seems to be unused
  48. $backend = \OC\Share\Share::getBackend($itemType);
  49. if ($shareType === IShare::TYPE_LINK || $shareType === IShare::TYPE_REMOTE) {
  50. if (isset($suggestedTarget)) {
  51. return $suggestedTarget;
  52. }
  53. return $backend->generateTarget($itemSource, false);
  54. } else {
  55. if ($shareType == IShare::TYPE_USER) {
  56. // Share with is a user, so set share type to user and groups
  57. $shareType = self::$shareTypeUserAndGroups;
  58. }
  59. // Check if suggested target exists first
  60. if (!isset($suggestedTarget)) {
  61. $suggestedTarget = $itemSource;
  62. }
  63. if ($shareType == IShare::TYPE_GROUP) {
  64. $target = $backend->generateTarget($suggestedTarget, false);
  65. } else {
  66. $target = $backend->generateTarget($suggestedTarget, $shareWith);
  67. }
  68. return $target;
  69. }
  70. }
  71. /**
  72. * Delete all reshares and group share children of an item
  73. * @param int $parent Id of item to delete
  74. * @param bool $excludeParent If true, exclude the parent from the delete (optional)
  75. * @param string $uidOwner The user that the parent was shared with (optional)
  76. * @param int $newParent new parent for the childrens
  77. * @param bool $excludeGroupChildren exclude group children elements
  78. */
  79. public static function delete($parent, $excludeParent = false, $uidOwner = null, $newParent = null, $excludeGroupChildren = false) {
  80. $ids = [$parent];
  81. $deletedItems = [];
  82. $changeParent = [];
  83. $parents = [$parent];
  84. while (!empty($parents)) {
  85. $parents = "'".implode("','", $parents)."'";
  86. // Check the owner on the first search of reshares, useful for
  87. // finding and deleting the reshares by a single user of a group share
  88. $params = [];
  89. if (count($ids) == 1 && isset($uidOwner)) {
  90. // FIXME: don't concat $parents, use Docrine's PARAM_INT_ARRAY approach
  91. $queryString = 'SELECT `id`, `share_with`, `item_type`, `share_type`, ' .
  92. '`item_target`, `file_target`, `parent` ' .
  93. 'FROM `*PREFIX*share` ' .
  94. 'WHERE `parent` IN ('.$parents.') AND `uid_owner` = ? ';
  95. $params[] = $uidOwner;
  96. } else {
  97. $queryString = 'SELECT `id`, `share_with`, `item_type`, `share_type`, ' .
  98. '`item_target`, `file_target`, `parent`, `uid_owner` ' .
  99. 'FROM `*PREFIX*share` WHERE `parent` IN ('.$parents.') ';
  100. }
  101. if ($excludeGroupChildren) {
  102. $queryString .= ' AND `share_type` != ?';
  103. $params[] = self::$shareTypeGroupUserUnique;
  104. }
  105. $query = \OC_DB::prepare($queryString);
  106. $result = $query->execute($params);
  107. // Reset parents array, only go through loop again if items are found
  108. $parents = [];
  109. while ($item = $result->fetchRow()) {
  110. $tmpItem = [
  111. 'id' => $item['id'],
  112. 'shareWith' => $item['share_with'],
  113. 'itemTarget' => $item['item_target'],
  114. 'itemType' => $item['item_type'],
  115. 'shareType' => (int)$item['share_type'],
  116. ];
  117. if (isset($item['file_target'])) {
  118. $tmpItem['fileTarget'] = $item['file_target'];
  119. }
  120. // if we have a new parent for the child we remember the child
  121. // to update the parent, if not we add it to the list of items
  122. // which should be deleted
  123. if ($newParent !== null) {
  124. $changeParent[] = $item['id'];
  125. } else {
  126. $deletedItems[] = $tmpItem;
  127. $ids[] = $item['id'];
  128. $parents[] = $item['id'];
  129. }
  130. }
  131. }
  132. if ($excludeParent) {
  133. unset($ids[0]);
  134. }
  135. if (!empty($changeParent)) {
  136. $idList = "'".implode("','", $changeParent)."'";
  137. $query = \OC_DB::prepare('UPDATE `*PREFIX*share` SET `parent` = ? WHERE `id` IN ('.$idList.')');
  138. $query->execute([$newParent]);
  139. }
  140. if (!empty($ids)) {
  141. $idList = "'".implode("','", $ids)."'";
  142. $query = \OC_DB::prepare('DELETE FROM `*PREFIX*share` WHERE `id` IN ('.$idList.')');
  143. $query->execute();
  144. }
  145. return $deletedItems;
  146. }
  147. /**
  148. * get default expire settings defined by the admin
  149. * @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
  150. */
  151. public static function getDefaultExpireSetting() {
  152. $config = \OC::$server->getConfig();
  153. $defaultExpireSettings = ['defaultExpireDateSet' => false];
  154. // get default expire settings
  155. $defaultExpireDate = $config->getAppValue('core', 'shareapi_default_expire_date', 'no');
  156. if ($defaultExpireDate === 'yes') {
  157. $enforceExpireDate = $config->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
  158. $defaultExpireSettings['defaultExpireDateSet'] = true;
  159. $defaultExpireSettings['expireAfterDays'] = (int)$config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
  160. $defaultExpireSettings['enforceExpireDate'] = $enforceExpireDate === 'yes';
  161. }
  162. return $defaultExpireSettings;
  163. }
  164. public static function calcExpireDate() {
  165. $expireAfter = \OC\Share\Share::getExpireInterval() * 24 * 60 * 60;
  166. $expireAt = time() + $expireAfter;
  167. $date = new \DateTime();
  168. $date->setTimestamp($expireAt);
  169. $date->setTime(0, 0, 0);
  170. //$dateString = $date->format('Y-m-d') . ' 00:00:00';
  171. return $date;
  172. }
  173. /**
  174. * calculate expire date
  175. * @param array $defaultExpireSettings contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
  176. * @param int $creationTime timestamp when the share was created
  177. * @param int $userExpireDate expire timestamp set by the user
  178. * @return mixed integer timestamp or False
  179. */
  180. public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) {
  181. $expires = false;
  182. $defaultExpires = null;
  183. if (!empty($defaultExpireSettings['defaultExpireDateSet'])) {
  184. $defaultExpires = $creationTime + $defaultExpireSettings['expireAfterDays'] * 86400;
  185. }
  186. if (isset($userExpireDate)) {
  187. // if the admin decided to enforce the default expire date then we only take
  188. // the user defined expire date of it is before the default expire date
  189. if ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) {
  190. $expires = min($userExpireDate, $defaultExpires);
  191. } else {
  192. $expires = $userExpireDate;
  193. }
  194. } elseif ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) {
  195. $expires = $defaultExpires;
  196. }
  197. return $expires;
  198. }
  199. /**
  200. * Strips away a potential file names and trailing slashes:
  201. * - http://localhost
  202. * - http://localhost/
  203. * - http://localhost/index.php
  204. * - http://localhost/index.php/s/{shareToken}
  205. *
  206. * all return: http://localhost
  207. *
  208. * @param string $remote
  209. * @return string
  210. */
  211. protected static function fixRemoteURL($remote) {
  212. $remote = str_replace('\\', '/', $remote);
  213. if ($fileNamePosition = strpos($remote, '/index.php')) {
  214. $remote = substr($remote, 0, $fileNamePosition);
  215. }
  216. $remote = rtrim($remote, '/');
  217. return $remote;
  218. }
  219. /**
  220. * split user and remote from federated cloud id
  221. *
  222. * @param string $id
  223. * @return string[]
  224. * @throws HintException
  225. */
  226. public static function splitUserRemote($id) {
  227. try {
  228. $cloudId = \OC::$server->getCloudIdManager()->resolveCloudId($id);
  229. return [$cloudId->getUser(), $cloudId->getRemote()];
  230. } catch (\InvalidArgumentException $e) {
  231. $l = \OC::$server->getL10N('core');
  232. $hint = $l->t('Invalid Federated Cloud ID');
  233. throw new HintException('Invalid Federated Cloud ID', $hint, 0, $e);
  234. }
  235. }
  236. /**
  237. * check if two federated cloud IDs refer to the same user
  238. *
  239. * @param string $user1
  240. * @param string $server1
  241. * @param string $user2
  242. * @param string $server2
  243. * @return bool true if both users and servers are the same
  244. */
  245. public static function isSameUserOnSameServer($user1, $server1, $user2, $server2) {
  246. $normalizedServer1 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server1));
  247. $normalizedServer2 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server2));
  248. if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) {
  249. // FIXME this should be a method in the user management instead
  250. \OCP\Util::emitHook(
  251. '\OCA\Files_Sharing\API\Server2Server',
  252. 'preLoginNameUsedAsUserName',
  253. ['uid' => &$user1]
  254. );
  255. \OCP\Util::emitHook(
  256. '\OCA\Files_Sharing\API\Server2Server',
  257. 'preLoginNameUsedAsUserName',
  258. ['uid' => &$user2]
  259. );
  260. if ($user1 === $user2) {
  261. return true;
  262. }
  263. }
  264. return false;
  265. }
  266. }