Helper.php 9.9 KB

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