Passed
Push — master ( c1161e...940996 )
by John
12:59 queued 11s
created

Helper::generateTarget()   B

Complexity

Conditions 7
Paths 10

Size

Total Lines 25
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 15
nc 10
nop 7
dl 0
loc 25
rs 8.8333
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Björn Schießle <[email protected]>
6
 * @author Christoph Wurst <[email protected]>
7
 * @author Joas Schilling <[email protected]>
8
 * @author Miguel Prokop <[email protected]>
9
 * @author Morris Jobke <[email protected]>
10
 * @author Robin Appelman <[email protected]>
11
 * @author Robin McCorkell <[email protected]>
12
 * @author Thomas Müller <[email protected]>
13
 * @author Vincent Petry <[email protected]>
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
31
namespace OC\Share;
32
33
use OC\HintException;
34
use OCP\DB\QueryBuilder\IQueryBuilder;
35
36
class Helper extends \OC\Share\Constants {
37
38
	/**
39
	 * Delete all reshares and group share children of an item
40
	 * @param int $parent Id of item to delete
41
	 * @param bool $excludeParent If true, exclude the parent from the delete (optional)
42
	 * @param string $uidOwner The user that the parent was shared with (optional)
43
	 * @param int $newParent new parent for the childrens
44
	 * @param bool $excludeGroupChildren exclude group children elements
45
	 */
46
	public static function delete($parent, $excludeParent = false, $uidOwner = null, $newParent = null, $excludeGroupChildren = false) {
47
		$ids = [$parent];
48
		$deletedItems = [];
49
		$changeParent = [];
50
		$parents = [$parent];
51
		while (!empty($parents)) {
52
			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
53
			$query->select(
54
				'id', 'share_with', 'item_type', 'share_type',
55
				'item_target', 'file_target', 'parent'
56
				)
57
				->from('share')
58
				->where($query->expr()->in('parent', $query->createNamedParameter(
59
					$parents, IQueryBuilder::PARAM_INT_ARRAY
60
				)));
61
62
			if (count($ids) === 1 && isset($uidOwner)) {
63
				// Check the owner on the first search of reshares, useful for
64
				// finding and deleting the reshares by a single user of a group share
65
				$query->andWhere($query->expr()->eq('uid_owner', $uidOwner));
66
			}
67
68
			if ($excludeGroupChildren) {
69
				$query->andWhere($query->expr()->eq('share_type', self::$shareTypeGroupUserUnique));
70
			}
71
72
			$result = $query->execute();
73
			// Reset parents array, only go through loop again if items are found
74
			$parents = [];
75
			while ($item = $result->fetch()) {
76
				$tmpItem = [
77
					'id' => $item['id'],
78
					'shareWith' => $item['share_with'],
79
					'itemTarget' => $item['item_target'],
80
					'itemType' => $item['item_type'],
81
					'shareType' => (int)$item['share_type'],
82
				];
83
				if (isset($item['file_target'])) {
84
					$tmpItem['fileTarget'] = $item['file_target'];
85
				}
86
				// if we have a new parent for the child we remember the child
87
				// to update the parent, if not we add it to the list of items
88
				// which should be deleted
89
				if ($newParent !== null) {
90
					$changeParent[] = $item['id'];
91
				} else {
92
					$deletedItems[] = $tmpItem;
93
					$ids[] = $item['id'];
94
					$parents[] = $item['id'];
95
				}
96
			}
97
			$result->closeCursor();
98
		}
99
		if ($excludeParent) {
100
			unset($ids[0]);
101
		}
102
103
		if (!empty($changeParent)) {
104
			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
105
			$query->update('share')
106
				->set('parent', $query->createNamedParameter($newParent, IQueryBuilder::PARAM_INT))
107
				->where($query->expr()->in('id', $query->createNamedParameter($changeParent, IQueryBuilder::PARAM_INT_ARRAY)));
108
			$query->execute();
109
		}
110
111
		if (!empty($ids)) {
112
			$query = \OC::$server->getDatabaseConnection()->getQueryBuilder();
113
			$query->delete('share')
114
				->where($query->expr()->in('id', $query->createNamedParameter($ids, IQueryBuilder::PARAM_INT_ARRAY)));
115
			$query->execute();
116
		}
117
118
		return $deletedItems;
119
	}
120
121
	/**
122
	 * get default expire settings defined by the admin
123
	 * @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
124
	 */
125
	public static function getDefaultExpireSetting() {
126
		$config = \OC::$server->getConfig();
127
128
		$defaultExpireSettings = ['defaultExpireDateSet' => false];
129
130
		// get default expire settings
131
		$defaultExpireDate = $config->getAppValue('core', 'shareapi_default_expire_date', 'no');
132
		if ($defaultExpireDate === 'yes') {
133
			$enforceExpireDate = $config->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
134
			$defaultExpireSettings['defaultExpireDateSet'] = true;
135
			$defaultExpireSettings['expireAfterDays'] = (int)$config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
136
			$defaultExpireSettings['enforceExpireDate'] = $enforceExpireDate === 'yes';
137
		}
138
139
		return $defaultExpireSettings;
140
	}
141
142
	public static function calcExpireDate() {
143
		$expireAfter = \OC\Share\Share::getExpireInterval() * 24 * 60 * 60;
144
		$expireAt = time() + $expireAfter;
145
		$date = new \DateTime();
146
		$date->setTimestamp($expireAt);
147
		$date->setTime(0, 0, 0);
148
		//$dateString = $date->format('Y-m-d') . ' 00:00:00';
149
150
		return $date;
151
	}
152
153
	/**
154
	 * calculate expire date
155
	 * @param array $defaultExpireSettings contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
156
	 * @param int $creationTime timestamp when the share was created
157
	 * @param int $userExpireDate expire timestamp set by the user
158
	 * @return mixed integer timestamp or False
159
	 */
160
	public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) {
161
		$expires = false;
162
		$defaultExpires = null;
163
164
		if (!empty($defaultExpireSettings['defaultExpireDateSet'])) {
165
			$defaultExpires = $creationTime + $defaultExpireSettings['expireAfterDays'] * 86400;
166
		}
167
168
169
		if (isset($userExpireDate)) {
170
			// if the admin decided to enforce the default expire date then we only take
171
			// the user defined expire date of it is before the default expire date
172
			if ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $defaultExpires of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
173
				$expires = min($userExpireDate, $defaultExpires);
174
			} else {
175
				$expires = $userExpireDate;
176
			}
177
		} elseif ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $defaultExpires of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
178
			$expires = $defaultExpires;
179
		}
180
181
		return $expires;
182
	}
183
184
	/**
185
	 * Strips away a potential file names and trailing slashes:
186
	 * - http://localhost
187
	 * - http://localhost/
188
	 * - http://localhost/index.php
189
	 * - http://localhost/index.php/s/{shareToken}
190
	 *
191
	 * all return: http://localhost
192
	 *
193
	 * @param string $remote
194
	 * @return string
195
	 */
196
	protected static function fixRemoteURL($remote) {
197
		$remote = str_replace('\\', '/', $remote);
198
		if ($fileNamePosition = strpos($remote, '/index.php')) {
199
			$remote = substr($remote, 0, $fileNamePosition);
200
		}
201
		$remote = rtrim($remote, '/');
202
203
		return $remote;
204
	}
205
206
	/**
207
	 * split user and remote from federated cloud id
208
	 *
209
	 * @param string $id
210
	 * @return string[]
211
	 * @throws HintException
212
	 */
213
	public static function splitUserRemote($id) {
214
		try {
215
			$cloudId = \OC::$server->getCloudIdManager()->resolveCloudId($id);
216
			return [$cloudId->getUser(), $cloudId->getRemote()];
217
		} catch (\InvalidArgumentException $e) {
218
			$l = \OC::$server->getL10N('core');
219
			$hint = $l->t('Invalid Federated Cloud ID');
220
			throw new HintException('Invalid Federated Cloud ID', $hint, 0, $e);
221
		}
222
	}
223
224
	/**
225
	 * check if two federated cloud IDs refer to the same user
226
	 *
227
	 * @param string $user1
228
	 * @param string $server1
229
	 * @param string $user2
230
	 * @param string $server2
231
	 * @return bool true if both users and servers are the same
232
	 */
233
	public static function isSameUserOnSameServer($user1, $server1, $user2, $server2) {
234
		$normalizedServer1 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server1));
235
		$normalizedServer2 = strtolower(\OC\Share\Share::removeProtocolFromUrl($server2));
236
237
		if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) {
238
			// FIXME this should be a method in the user management instead
239
			\OCP\Util::emitHook(
240
					'\OCA\Files_Sharing\API\Server2Server',
241
					'preLoginNameUsedAsUserName',
242
					['uid' => &$user1]
243
			);
244
			\OCP\Util::emitHook(
245
					'\OCA\Files_Sharing\API\Server2Server',
246
					'preLoginNameUsedAsUserName',
247
					['uid' => &$user2]
248
			);
249
250
			if ($user1 === $user2) {
251
				return true;
252
			}
253
		}
254
255
		return false;
256
	}
257
}
258