Completed
Pull Request — master (#7884)
by Morris
55:02 queued 36:52
created
settings/users.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -48,18 +48,18 @@  discard block
 block discarded – undo
48 48
 $config = \OC::$server->getConfig();
49 49
 
50 50
 if ($config->getSystemValue('sort_groups_by_name', false)) {
51
-	$sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
51
+    $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
52 52
 } else {
53
-	$isLDAPUsed = false;
54
-	if ($appManager->isEnabledForUser('user_ldap')) {
55
-		$isLDAPUsed =
56
-			$groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
57
-			|| $groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
58
-		if ($isLDAPUsed) {
59
-			// LDAP user count can be slow, so we sort by group name here
60
-			$sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
61
-		}
62
-	}
53
+    $isLDAPUsed = false;
54
+    if ($appManager->isEnabledForUser('user_ldap')) {
55
+        $isLDAPUsed =
56
+            $groupManager->isBackendUsed('\OCA\User_LDAP\Group_LDAP')
57
+            || $groupManager->isBackendUsed('\OCA\User_LDAP\Group_Proxy');
58
+        if ($isLDAPUsed) {
59
+            // LDAP user count can be slow, so we sort by group name here
60
+            $sortGroupsBy = \OC\Group\MetaData::SORT_GROUPNAME;
61
+        }
62
+    }
63 63
 }
64 64
 
65 65
 $uid = \OC_User::getUser();
@@ -68,62 +68,62 @@  discard block
 block discarded – undo
68 68
 $isDisabled = true;
69 69
 $user = $userManager->get($uid);
70 70
 if ($user) {
71
-	$isDisabled = !$user->isEnabled();
71
+    $isDisabled = !$user->isEnabled();
72 72
 }
73 73
 
74 74
 $groupsInfo = new \OC\Group\MetaData(
75
-	$uid,
76
-	$isAdmin,
77
-	$groupManager,
78
-	\OC::$server->getUserSession()
75
+    $uid,
76
+    $isAdmin,
77
+    $groupManager,
78
+    \OC::$server->getUserSession()
79 79
 );
80 80
 
81 81
 $groupsInfo->setSorting($sortGroupsBy);
82 82
 list($adminGroup, $groups) = $groupsInfo->get();
83 83
 
84 84
 $recoveryAdminEnabled = $appManager->isEnabledForUser('encryption') &&
85
-					    $config->getAppValue( 'encryption', 'recoveryAdminEnabled', '0');
85
+                        $config->getAppValue( 'encryption', 'recoveryAdminEnabled', '0');
86 86
 
87 87
 if($isAdmin) {
88
-	$subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
89
-	// New class returns IUser[] so convert back
90
-	$result = [];
91
-	foreach ($subAdmins as $subAdmin) {
92
-		$result[] = [
93
-			'gid' => $subAdmin['group']->getGID(),
94
-			'uid' => $subAdmin['user']->getUID(),
95
-		];
96
-	}
97
-	$subAdmins = $result;
88
+    $subAdmins = \OC::$server->getGroupManager()->getSubAdmin()->getAllSubAdmins();
89
+    // New class returns IUser[] so convert back
90
+    $result = [];
91
+    foreach ($subAdmins as $subAdmin) {
92
+        $result[] = [
93
+            'gid' => $subAdmin['group']->getGID(),
94
+            'uid' => $subAdmin['user']->getUID(),
95
+        ];
96
+    }
97
+    $subAdmins = $result;
98 98
 }else{
99
-	/* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
100
-	$gids = array();
101
-	foreach($groups as $group) {
102
-		if (isset($group['id'])) {
103
-			$gids[] = $group['id'];
104
-		}
105
-	}
106
-	$subAdmins = false;
99
+    /* Retrieve group IDs from $groups array, so we can pass that information into OC_Group::displayNamesInGroups() */
100
+    $gids = array();
101
+    foreach($groups as $group) {
102
+        if (isset($group['id'])) {
103
+            $gids[] = $group['id'];
104
+        }
105
+    }
106
+    $subAdmins = false;
107 107
 }
108 108
 
109 109
 $disabledUsers = $isLDAPUsed ? 0 : $userManager->countDisabledUsers();
110 110
 $disabledUsersGroup = [
111
-	'id' => '_disabledUsers',
112
-	'name' => '_disabledUsers',
113
-	'usercount' => $disabledUsers
111
+    'id' => '_disabledUsers',
112
+    'name' => '_disabledUsers',
113
+    'usercount' => $disabledUsers
114 114
 ];
115 115
 
116 116
 // load preset quotas
117 117
 $quotaPreset=$config->getAppValue('files', 'quota_preset', '1 GB, 5 GB, 10 GB');
118 118
 $quotaPreset=explode(',', $quotaPreset);
119 119
 foreach($quotaPreset as &$preset) {
120
-	$preset=trim($preset);
120
+    $preset=trim($preset);
121 121
 }
122 122
 $quotaPreset=array_diff($quotaPreset, array('default', 'none'));
123 123
 
124 124
 $defaultQuota=$config->getAppValue('files', 'default_quota', 'none');
125 125
 $defaultQuotaIsUserDefined=array_search($defaultQuota, $quotaPreset)===false
126
-	&& array_search($defaultQuota, array('none', 'default'))===false;
126
+    && array_search($defaultQuota, array('none', 'default'))===false;
127 127
 
128 128
 \OC::$server->getEventDispatcher()->dispatch('OC\Settings\Users::loadAdditionalScripts');
129 129
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Access.php 2 patches
Indentation   +1868 added lines, -1868 removed lines patch added patch discarded remove patch
@@ -59,1633 +59,1633 @@  discard block
 block discarded – undo
59 59
  * @package OCA\User_LDAP
60 60
  */
61 61
 class Access extends LDAPUtility implements IUserTools {
62
-	const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
63
-
64
-	/** @var \OCA\User_LDAP\Connection */
65
-	public $connection;
66
-	/** @var Manager */
67
-	public $userManager;
68
-	//never ever check this var directly, always use getPagedSearchResultState
69
-	protected $pagedSearchedSuccessful;
70
-
71
-	/**
72
-	 * @var string[] $cookies an array of returned Paged Result cookies
73
-	 */
74
-	protected $cookies = array();
75
-
76
-	/**
77
-	 * @var string $lastCookie the last cookie returned from a Paged Results
78
-	 * operation, defaults to an empty string
79
-	 */
80
-	protected $lastCookie = '';
81
-
82
-	/**
83
-	 * @var AbstractMapping $userMapper
84
-	 */
85
-	protected $userMapper;
86
-
87
-	/**
88
-	* @var AbstractMapping $userMapper
89
-	*/
90
-	protected $groupMapper;
91
-
92
-	/**
93
-	 * @var \OCA\User_LDAP\Helper
94
-	 */
95
-	private $helper;
96
-	/** @var IConfig */
97
-	private $config;
98
-
99
-	public function __construct(
100
-		Connection $connection,
101
-		ILDAPWrapper $ldap,
102
-		Manager $userManager,
103
-		Helper $helper,
104
-		IConfig $config
105
-	) {
106
-		parent::__construct($ldap);
107
-		$this->connection = $connection;
108
-		$this->userManager = $userManager;
109
-		$this->userManager->setLdapAccess($this);
110
-		$this->helper = $helper;
111
-		$this->config = $config;
112
-	}
113
-
114
-	/**
115
-	 * sets the User Mapper
116
-	 * @param AbstractMapping $mapper
117
-	 */
118
-	public function setUserMapper(AbstractMapping $mapper) {
119
-		$this->userMapper = $mapper;
120
-	}
121
-
122
-	/**
123
-	 * returns the User Mapper
124
-	 * @throws \Exception
125
-	 * @return AbstractMapping
126
-	 */
127
-	public function getUserMapper() {
128
-		if(is_null($this->userMapper)) {
129
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
130
-		}
131
-		return $this->userMapper;
132
-	}
133
-
134
-	/**
135
-	 * sets the Group Mapper
136
-	 * @param AbstractMapping $mapper
137
-	 */
138
-	public function setGroupMapper(AbstractMapping $mapper) {
139
-		$this->groupMapper = $mapper;
140
-	}
141
-
142
-	/**
143
-	 * returns the Group Mapper
144
-	 * @throws \Exception
145
-	 * @return AbstractMapping
146
-	 */
147
-	public function getGroupMapper() {
148
-		if(is_null($this->groupMapper)) {
149
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
150
-		}
151
-		return $this->groupMapper;
152
-	}
153
-
154
-	/**
155
-	 * @return bool
156
-	 */
157
-	private function checkConnection() {
158
-		return ($this->connection instanceof Connection);
159
-	}
160
-
161
-	/**
162
-	 * returns the Connection instance
163
-	 * @return \OCA\User_LDAP\Connection
164
-	 */
165
-	public function getConnection() {
166
-		return $this->connection;
167
-	}
168
-
169
-	/**
170
-	 * reads a given attribute for an LDAP record identified by a DN
171
-	 * @param string $dn the record in question
172
-	 * @param string $attr the attribute that shall be retrieved
173
-	 *        if empty, just check the record's existence
174
-	 * @param string $filter
175
-	 * @return array|false an array of values on success or an empty
176
-	 *          array if $attr is empty, false otherwise
177
-	 */
178
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
179
-		if(!$this->checkConnection()) {
180
-			\OCP\Util::writeLog('user_ldap',
181
-				'No LDAP Connector assigned, access impossible for readAttribute.',
182
-				\OCP\Util::WARN);
183
-			return false;
184
-		}
185
-		$cr = $this->connection->getConnectionResource();
186
-		if(!$this->ldap->isResource($cr)) {
187
-			//LDAP not available
188
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
189
-			return false;
190
-		}
191
-		//Cancel possibly running Paged Results operation, otherwise we run in
192
-		//LDAP protocol errors
193
-		$this->abandonPagedSearch();
194
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
195
-		// but does not hurt either.
196
-		$pagingSize = intval($this->connection->ldapPagingSize);
197
-		// 0 won't result in replies, small numbers may leave out groups
198
-		// (cf. #12306), 500 is default for paging and should work everywhere.
199
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
200
-		$attr = mb_strtolower($attr, 'UTF-8');
201
-		// the actual read attribute later may contain parameters on a ranged
202
-		// request, e.g. member;range=99-199. Depends on server reply.
203
-		$attrToRead = $attr;
204
-
205
-		$values = [];
206
-		$isRangeRequest = false;
207
-		do {
208
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
209
-			if(is_bool($result)) {
210
-				// when an exists request was run and it was successful, an empty
211
-				// array must be returned
212
-				return $result ? [] : false;
213
-			}
214
-
215
-			if (!$isRangeRequest) {
216
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
217
-				if (!empty($values)) {
218
-					return $values;
219
-				}
220
-			}
221
-
222
-			$isRangeRequest = false;
223
-			$result = $this->extractRangeData($result, $attr);
224
-			if (!empty($result)) {
225
-				$normalizedResult = $this->extractAttributeValuesFromResult(
226
-					[ $attr => $result['values'] ],
227
-					$attr
228
-				);
229
-				$values = array_merge($values, $normalizedResult);
230
-
231
-				if($result['rangeHigh'] === '*') {
232
-					// when server replies with * as high range value, there are
233
-					// no more results left
234
-					return $values;
235
-				} else {
236
-					$low  = $result['rangeHigh'] + 1;
237
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
238
-					$isRangeRequest = true;
239
-				}
240
-			}
241
-		} while($isRangeRequest);
242
-
243
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
244
-		return false;
245
-	}
246
-
247
-	/**
248
-	 * Runs an read operation against LDAP
249
-	 *
250
-	 * @param resource $cr the LDAP connection
251
-	 * @param string $dn
252
-	 * @param string $attribute
253
-	 * @param string $filter
254
-	 * @param int $maxResults
255
-	 * @return array|bool false if there was any error, true if an exists check
256
-	 *                    was performed and the requested DN found, array with the
257
-	 *                    returned data on a successful usual operation
258
-	 */
259
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
260
-		$this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
261
-		$dn = $this->helper->DNasBaseParameter($dn);
262
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
263
-		if (!$this->ldap->isResource($rr)) {
264
-			if ($attribute !== '') {
265
-				//do not throw this message on userExists check, irritates
266
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
267
-			}
268
-			//in case an error occurs , e.g. object does not exist
269
-			return false;
270
-		}
271
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
272
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
273
-			return true;
274
-		}
275
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
276
-		if (!$this->ldap->isResource($er)) {
277
-			//did not match the filter, return false
278
-			return false;
279
-		}
280
-		//LDAP attributes are not case sensitive
281
-		$result = \OCP\Util::mb_array_change_key_case(
282
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
283
-
284
-		return $result;
285
-	}
286
-
287
-	/**
288
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
289
-	 * data if present.
290
-	 *
291
-	 * @param array $result from ILDAPWrapper::getAttributes()
292
-	 * @param string $attribute the attribute name that was read
293
-	 * @return string[]
294
-	 */
295
-	public function extractAttributeValuesFromResult($result, $attribute) {
296
-		$values = [];
297
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
298
-			$lowercaseAttribute = strtolower($attribute);
299
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
300
-				if($this->resemblesDN($attribute)) {
301
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
302
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
303
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
304
-				} else {
305
-					$values[] = $result[$attribute][$i];
306
-				}
307
-			}
308
-		}
309
-		return $values;
310
-	}
311
-
312
-	/**
313
-	 * Attempts to find ranged data in a getAttribute results and extracts the
314
-	 * returned values as well as information on the range and full attribute
315
-	 * name for further processing.
316
-	 *
317
-	 * @param array $result from ILDAPWrapper::getAttributes()
318
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
319
-	 * @return array If a range was detected with keys 'values', 'attributeName',
320
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
321
-	 */
322
-	public function extractRangeData($result, $attribute) {
323
-		$keys = array_keys($result);
324
-		foreach($keys as $key) {
325
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
326
-				$queryData = explode(';', $key);
327
-				if(strpos($queryData[1], 'range=') === 0) {
328
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
329
-					$data = [
330
-						'values' => $result[$key],
331
-						'attributeName' => $queryData[0],
332
-						'attributeFull' => $key,
333
-						'rangeHigh' => $high,
334
-					];
335
-					return $data;
336
-				}
337
-			}
338
-		}
339
-		return [];
340
-	}
62
+    const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
63
+
64
+    /** @var \OCA\User_LDAP\Connection */
65
+    public $connection;
66
+    /** @var Manager */
67
+    public $userManager;
68
+    //never ever check this var directly, always use getPagedSearchResultState
69
+    protected $pagedSearchedSuccessful;
70
+
71
+    /**
72
+     * @var string[] $cookies an array of returned Paged Result cookies
73
+     */
74
+    protected $cookies = array();
75
+
76
+    /**
77
+     * @var string $lastCookie the last cookie returned from a Paged Results
78
+     * operation, defaults to an empty string
79
+     */
80
+    protected $lastCookie = '';
81
+
82
+    /**
83
+     * @var AbstractMapping $userMapper
84
+     */
85
+    protected $userMapper;
86
+
87
+    /**
88
+     * @var AbstractMapping $userMapper
89
+     */
90
+    protected $groupMapper;
91
+
92
+    /**
93
+     * @var \OCA\User_LDAP\Helper
94
+     */
95
+    private $helper;
96
+    /** @var IConfig */
97
+    private $config;
98
+
99
+    public function __construct(
100
+        Connection $connection,
101
+        ILDAPWrapper $ldap,
102
+        Manager $userManager,
103
+        Helper $helper,
104
+        IConfig $config
105
+    ) {
106
+        parent::__construct($ldap);
107
+        $this->connection = $connection;
108
+        $this->userManager = $userManager;
109
+        $this->userManager->setLdapAccess($this);
110
+        $this->helper = $helper;
111
+        $this->config = $config;
112
+    }
113
+
114
+    /**
115
+     * sets the User Mapper
116
+     * @param AbstractMapping $mapper
117
+     */
118
+    public function setUserMapper(AbstractMapping $mapper) {
119
+        $this->userMapper = $mapper;
120
+    }
121
+
122
+    /**
123
+     * returns the User Mapper
124
+     * @throws \Exception
125
+     * @return AbstractMapping
126
+     */
127
+    public function getUserMapper() {
128
+        if(is_null($this->userMapper)) {
129
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
130
+        }
131
+        return $this->userMapper;
132
+    }
133
+
134
+    /**
135
+     * sets the Group Mapper
136
+     * @param AbstractMapping $mapper
137
+     */
138
+    public function setGroupMapper(AbstractMapping $mapper) {
139
+        $this->groupMapper = $mapper;
140
+    }
141
+
142
+    /**
143
+     * returns the Group Mapper
144
+     * @throws \Exception
145
+     * @return AbstractMapping
146
+     */
147
+    public function getGroupMapper() {
148
+        if(is_null($this->groupMapper)) {
149
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
150
+        }
151
+        return $this->groupMapper;
152
+    }
153
+
154
+    /**
155
+     * @return bool
156
+     */
157
+    private function checkConnection() {
158
+        return ($this->connection instanceof Connection);
159
+    }
160
+
161
+    /**
162
+     * returns the Connection instance
163
+     * @return \OCA\User_LDAP\Connection
164
+     */
165
+    public function getConnection() {
166
+        return $this->connection;
167
+    }
168
+
169
+    /**
170
+     * reads a given attribute for an LDAP record identified by a DN
171
+     * @param string $dn the record in question
172
+     * @param string $attr the attribute that shall be retrieved
173
+     *        if empty, just check the record's existence
174
+     * @param string $filter
175
+     * @return array|false an array of values on success or an empty
176
+     *          array if $attr is empty, false otherwise
177
+     */
178
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
179
+        if(!$this->checkConnection()) {
180
+            \OCP\Util::writeLog('user_ldap',
181
+                'No LDAP Connector assigned, access impossible for readAttribute.',
182
+                \OCP\Util::WARN);
183
+            return false;
184
+        }
185
+        $cr = $this->connection->getConnectionResource();
186
+        if(!$this->ldap->isResource($cr)) {
187
+            //LDAP not available
188
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
189
+            return false;
190
+        }
191
+        //Cancel possibly running Paged Results operation, otherwise we run in
192
+        //LDAP protocol errors
193
+        $this->abandonPagedSearch();
194
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
195
+        // but does not hurt either.
196
+        $pagingSize = intval($this->connection->ldapPagingSize);
197
+        // 0 won't result in replies, small numbers may leave out groups
198
+        // (cf. #12306), 500 is default for paging and should work everywhere.
199
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
200
+        $attr = mb_strtolower($attr, 'UTF-8');
201
+        // the actual read attribute later may contain parameters on a ranged
202
+        // request, e.g. member;range=99-199. Depends on server reply.
203
+        $attrToRead = $attr;
204
+
205
+        $values = [];
206
+        $isRangeRequest = false;
207
+        do {
208
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
209
+            if(is_bool($result)) {
210
+                // when an exists request was run and it was successful, an empty
211
+                // array must be returned
212
+                return $result ? [] : false;
213
+            }
214
+
215
+            if (!$isRangeRequest) {
216
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
217
+                if (!empty($values)) {
218
+                    return $values;
219
+                }
220
+            }
221
+
222
+            $isRangeRequest = false;
223
+            $result = $this->extractRangeData($result, $attr);
224
+            if (!empty($result)) {
225
+                $normalizedResult = $this->extractAttributeValuesFromResult(
226
+                    [ $attr => $result['values'] ],
227
+                    $attr
228
+                );
229
+                $values = array_merge($values, $normalizedResult);
230
+
231
+                if($result['rangeHigh'] === '*') {
232
+                    // when server replies with * as high range value, there are
233
+                    // no more results left
234
+                    return $values;
235
+                } else {
236
+                    $low  = $result['rangeHigh'] + 1;
237
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
238
+                    $isRangeRequest = true;
239
+                }
240
+            }
241
+        } while($isRangeRequest);
242
+
243
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
244
+        return false;
245
+    }
246
+
247
+    /**
248
+     * Runs an read operation against LDAP
249
+     *
250
+     * @param resource $cr the LDAP connection
251
+     * @param string $dn
252
+     * @param string $attribute
253
+     * @param string $filter
254
+     * @param int $maxResults
255
+     * @return array|bool false if there was any error, true if an exists check
256
+     *                    was performed and the requested DN found, array with the
257
+     *                    returned data on a successful usual operation
258
+     */
259
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
260
+        $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
261
+        $dn = $this->helper->DNasBaseParameter($dn);
262
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
263
+        if (!$this->ldap->isResource($rr)) {
264
+            if ($attribute !== '') {
265
+                //do not throw this message on userExists check, irritates
266
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
267
+            }
268
+            //in case an error occurs , e.g. object does not exist
269
+            return false;
270
+        }
271
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
272
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
273
+            return true;
274
+        }
275
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
276
+        if (!$this->ldap->isResource($er)) {
277
+            //did not match the filter, return false
278
+            return false;
279
+        }
280
+        //LDAP attributes are not case sensitive
281
+        $result = \OCP\Util::mb_array_change_key_case(
282
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
283
+
284
+        return $result;
285
+    }
286
+
287
+    /**
288
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
289
+     * data if present.
290
+     *
291
+     * @param array $result from ILDAPWrapper::getAttributes()
292
+     * @param string $attribute the attribute name that was read
293
+     * @return string[]
294
+     */
295
+    public function extractAttributeValuesFromResult($result, $attribute) {
296
+        $values = [];
297
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
298
+            $lowercaseAttribute = strtolower($attribute);
299
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
300
+                if($this->resemblesDN($attribute)) {
301
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
302
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
303
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
304
+                } else {
305
+                    $values[] = $result[$attribute][$i];
306
+                }
307
+            }
308
+        }
309
+        return $values;
310
+    }
311
+
312
+    /**
313
+     * Attempts to find ranged data in a getAttribute results and extracts the
314
+     * returned values as well as information on the range and full attribute
315
+     * name for further processing.
316
+     *
317
+     * @param array $result from ILDAPWrapper::getAttributes()
318
+     * @param string $attribute the attribute name that was read. Without ";range=…"
319
+     * @return array If a range was detected with keys 'values', 'attributeName',
320
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
321
+     */
322
+    public function extractRangeData($result, $attribute) {
323
+        $keys = array_keys($result);
324
+        foreach($keys as $key) {
325
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
326
+                $queryData = explode(';', $key);
327
+                if(strpos($queryData[1], 'range=') === 0) {
328
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
329
+                    $data = [
330
+                        'values' => $result[$key],
331
+                        'attributeName' => $queryData[0],
332
+                        'attributeFull' => $key,
333
+                        'rangeHigh' => $high,
334
+                    ];
335
+                    return $data;
336
+                }
337
+            }
338
+        }
339
+        return [];
340
+    }
341 341
 	
342
-	/**
343
-	 * Set password for an LDAP user identified by a DN
344
-	 *
345
-	 * @param string $userDN the user in question
346
-	 * @param string $password the new password
347
-	 * @return bool
348
-	 * @throws HintException
349
-	 * @throws \Exception
350
-	 */
351
-	public function setPassword($userDN, $password) {
352
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
353
-			throw new \Exception('LDAP password changes are disabled.');
354
-		}
355
-		$cr = $this->connection->getConnectionResource();
356
-		if(!$this->ldap->isResource($cr)) {
357
-			//LDAP not available
358
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
359
-			return false;
360
-		}
361
-		try {
362
-			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
363
-		} catch(ConstraintViolationException $e) {
364
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
365
-		}
366
-	}
367
-
368
-	/**
369
-	 * checks whether the given attributes value is probably a DN
370
-	 * @param string $attr the attribute in question
371
-	 * @return boolean if so true, otherwise false
372
-	 */
373
-	private function resemblesDN($attr) {
374
-		$resemblingAttributes = array(
375
-			'dn',
376
-			'uniquemember',
377
-			'member',
378
-			// memberOf is an "operational" attribute, without a definition in any RFC
379
-			'memberof'
380
-		);
381
-		return in_array($attr, $resemblingAttributes);
382
-	}
383
-
384
-	/**
385
-	 * checks whether the given string is probably a DN
386
-	 * @param string $string
387
-	 * @return boolean
388
-	 */
389
-	public function stringResemblesDN($string) {
390
-		$r = $this->ldap->explodeDN($string, 0);
391
-		// if exploding a DN succeeds and does not end up in
392
-		// an empty array except for $r[count] being 0.
393
-		return (is_array($r) && count($r) > 1);
394
-	}
395
-
396
-	/**
397
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
398
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
399
-	 * becomes dc=foobar,dc=server,dc=org
400
-	 * @param string $dn
401
-	 * @return string
402
-	 */
403
-	public function getDomainDNFromDN($dn) {
404
-		$allParts = $this->ldap->explodeDN($dn, 0);
405
-		if($allParts === false) {
406
-			//not a valid DN
407
-			return '';
408
-		}
409
-		$domainParts = array();
410
-		$dcFound = false;
411
-		foreach($allParts as $part) {
412
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
413
-				$dcFound = true;
414
-			}
415
-			if($dcFound) {
416
-				$domainParts[] = $part;
417
-			}
418
-		}
419
-		$domainDN = implode(',', $domainParts);
420
-		return $domainDN;
421
-	}
422
-
423
-	/**
424
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
425
-	 * @param string $name the Nextcloud name in question
426
-	 * @return string|false LDAP DN on success, otherwise false
427
-	 */
428
-	public function groupname2dn($name) {
429
-		return $this->groupMapper->getDNByName($name);
430
-	}
431
-
432
-	/**
433
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
434
-	 * @param string $name the Nextcloud name in question
435
-	 * @return string|false with the LDAP DN on success, otherwise false
436
-	 */
437
-	public function username2dn($name) {
438
-		$fdn = $this->userMapper->getDNByName($name);
439
-
440
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
441
-		//server setups
442
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
443
-			return $fdn;
444
-		}
445
-
446
-		return false;
447
-	}
448
-
449
-	/**
450
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
451
-	 * @param string $fdn the dn of the group object
452
-	 * @param string $ldapName optional, the display name of the object
453
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
454
-	 */
455
-	public function dn2groupname($fdn, $ldapName = null) {
456
-		//To avoid bypassing the base DN settings under certain circumstances
457
-		//with the group support, check whether the provided DN matches one of
458
-		//the given Bases
459
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
460
-			return false;
461
-		}
462
-
463
-		return $this->dn2ocname($fdn, $ldapName, false);
464
-	}
465
-
466
-	/**
467
-	 * accepts an array of group DNs and tests whether they match the user
468
-	 * filter by doing read operations against the group entries. Returns an
469
-	 * array of DNs that match the filter.
470
-	 *
471
-	 * @param string[] $groupDNs
472
-	 * @return string[]
473
-	 */
474
-	public function groupsMatchFilter($groupDNs) {
475
-		$validGroupDNs = [];
476
-		foreach($groupDNs as $dn) {
477
-			$cacheKey = 'groupsMatchFilter-'.$dn;
478
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
479
-			if(!is_null($groupMatchFilter)) {
480
-				if($groupMatchFilter) {
481
-					$validGroupDNs[] = $dn;
482
-				}
483
-				continue;
484
-			}
485
-
486
-			// Check the base DN first. If this is not met already, we don't
487
-			// need to ask the server at all.
488
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
489
-				$this->connection->writeToCache($cacheKey, false);
490
-				continue;
491
-			}
492
-
493
-			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
494
-			if(is_array($result)) {
495
-				$this->connection->writeToCache($cacheKey, true);
496
-				$validGroupDNs[] = $dn;
497
-			} else {
498
-				$this->connection->writeToCache($cacheKey, false);
499
-			}
500
-
501
-		}
502
-		return $validGroupDNs;
503
-	}
504
-
505
-	/**
506
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
507
-	 * @param string $dn the dn of the user object
508
-	 * @param string $ldapName optional, the display name of the object
509
-	 * @return string|false with with the name to use in Nextcloud
510
-	 */
511
-	public function dn2username($fdn, $ldapName = null) {
512
-		//To avoid bypassing the base DN settings under certain circumstances
513
-		//with the group support, check whether the provided DN matches one of
514
-		//the given Bases
515
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
516
-			return false;
517
-		}
518
-
519
-		return $this->dn2ocname($fdn, $ldapName, true);
520
-	}
521
-
522
-	/**
523
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
524
-	 *
525
-	 * @param string $fdn the dn of the user object
526
-	 * @param string|null $ldapName optional, the display name of the object
527
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
528
-	 * @param bool|null $newlyMapped
529
-	 * @param array|null $record
530
-	 * @return false|string with with the name to use in Nextcloud
531
-	 * @throws \Exception
532
-	 */
533
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
534
-		$newlyMapped = false;
535
-		if($isUser) {
536
-			$mapper = $this->getUserMapper();
537
-			$nameAttribute = $this->connection->ldapUserDisplayName;
538
-		} else {
539
-			$mapper = $this->getGroupMapper();
540
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
541
-		}
542
-
543
-		//let's try to retrieve the Nextcloud name from the mappings table
544
-		$ncName = $mapper->getNameByDN($fdn);
545
-		if(is_string($ncName)) {
546
-			return $ncName;
547
-		}
548
-
549
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
550
-		$uuid = $this->getUUID($fdn, $isUser, $record);
551
-		if(is_string($uuid)) {
552
-			$ncName = $mapper->getNameByUUID($uuid);
553
-			if(is_string($ncName)) {
554
-				$mapper->setDNbyUUID($fdn, $uuid);
555
-				return $ncName;
556
-			}
557
-		} else {
558
-			//If the UUID can't be detected something is foul.
559
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
560
-			return false;
561
-		}
562
-
563
-		if(is_null($ldapName)) {
564
-			$ldapName = $this->readAttribute($fdn, $nameAttribute);
565
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
566
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
567
-				return false;
568
-			}
569
-			$ldapName = $ldapName[0];
570
-		}
571
-
572
-		if($isUser) {
573
-			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
574
-			if ($usernameAttribute !== '') {
575
-				$username = $this->readAttribute($fdn, $usernameAttribute);
576
-				$username = $username[0];
577
-			} else {
578
-				$username = $uuid;
579
-			}
580
-			$intName = $this->sanitizeUsername($username);
581
-		} else {
582
-			$intName = $ldapName;
583
-		}
584
-
585
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
586
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
587
-		//NOTE: mind, disabling cache affects only this instance! Using it
588
-		// outside of core user management will still cache the user as non-existing.
589
-		$originalTTL = $this->connection->ldapCacheTTL;
590
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
591
-		if(($isUser && $intName !== '' && !\OC::$server->getUserManager()->userExists($intName))
592
-			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
593
-			if($mapper->map($fdn, $intName, $uuid)) {
594
-				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
595
-				$newlyMapped = true;
596
-				return $intName;
597
-			}
598
-		}
599
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
600
-
601
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
602
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
603
-			$newlyMapped = true;
604
-			return $altName;
605
-		}
606
-
607
-		//if everything else did not help..
608
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
609
-		return false;
610
-	}
611
-
612
-	/**
613
-	 * gives back the user names as they are used ownClod internally
614
-	 * @param array $ldapUsers as returned by fetchList()
615
-	 * @return array an array with the user names to use in Nextcloud
616
-	 *
617
-	 * gives back the user names as they are used ownClod internally
618
-	 */
619
-	public function nextcloudUserNames($ldapUsers) {
620
-		return $this->ldap2NextcloudNames($ldapUsers, true);
621
-	}
622
-
623
-	/**
624
-	 * gives back the group names as they are used ownClod internally
625
-	 * @param array $ldapGroups as returned by fetchList()
626
-	 * @return array an array with the group names to use in Nextcloud
627
-	 *
628
-	 * gives back the group names as they are used ownClod internally
629
-	 */
630
-	public function nextcloudGroupNames($ldapGroups) {
631
-		return $this->ldap2NextcloudNames($ldapGroups, false);
632
-	}
633
-
634
-	/**
635
-	 * @param array $ldapObjects as returned by fetchList()
636
-	 * @param bool $isUsers
637
-	 * @return array
638
-	 */
639
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
640
-		if($isUsers) {
641
-			$nameAttribute = $this->connection->ldapUserDisplayName;
642
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
643
-		} else {
644
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
645
-		}
646
-		$nextcloudNames = array();
647
-
648
-		foreach($ldapObjects as $ldapObject) {
649
-			$nameByLDAP = null;
650
-			if(    isset($ldapObject[$nameAttribute])
651
-				&& is_array($ldapObject[$nameAttribute])
652
-				&& isset($ldapObject[$nameAttribute][0])
653
-			) {
654
-				// might be set, but not necessarily. if so, we use it.
655
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
656
-			}
657
-
658
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
659
-			if($ncName) {
660
-				$nextcloudNames[] = $ncName;
661
-				if($isUsers) {
662
-					//cache the user names so it does not need to be retrieved
663
-					//again later (e.g. sharing dialogue).
664
-					if(is_null($nameByLDAP)) {
665
-						continue;
666
-					}
667
-					$sndName = isset($ldapObject[$sndAttribute][0])
668
-						? $ldapObject[$sndAttribute][0] : '';
669
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
670
-				}
671
-			}
672
-		}
673
-		return $nextcloudNames;
674
-	}
675
-
676
-	/**
677
-	 * caches the user display name
678
-	 * @param string $ocName the internal Nextcloud username
679
-	 * @param string|false $home the home directory path
680
-	 */
681
-	public function cacheUserHome($ocName, $home) {
682
-		$cacheKey = 'getHome'.$ocName;
683
-		$this->connection->writeToCache($cacheKey, $home);
684
-	}
685
-
686
-	/**
687
-	 * caches a user as existing
688
-	 * @param string $ocName the internal Nextcloud username
689
-	 */
690
-	public function cacheUserExists($ocName) {
691
-		$this->connection->writeToCache('userExists'.$ocName, true);
692
-	}
693
-
694
-	/**
695
-	 * caches the user display name
696
-	 * @param string $ocName the internal Nextcloud username
697
-	 * @param string $displayName the display name
698
-	 * @param string $displayName2 the second display name
699
-	 */
700
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
701
-		$user = $this->userManager->get($ocName);
702
-		if($user === null) {
703
-			return;
704
-		}
705
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
706
-		$cacheKeyTrunk = 'getDisplayName';
707
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
708
-	}
709
-
710
-	/**
711
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
712
-	 * @param string $name the display name of the object
713
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
714
-	 *
715
-	 * Instead of using this method directly, call
716
-	 * createAltInternalOwnCloudName($name, true)
717
-	 */
718
-	private function _createAltInternalOwnCloudNameForUsers($name) {
719
-		$attempts = 0;
720
-		//while loop is just a precaution. If a name is not generated within
721
-		//20 attempts, something else is very wrong. Avoids infinite loop.
722
-		while($attempts < 20){
723
-			$altName = $name . '_' . rand(1000,9999);
724
-			if(!\OC::$server->getUserManager()->userExists($altName)) {
725
-				return $altName;
726
-			}
727
-			$attempts++;
728
-		}
729
-		return false;
730
-	}
731
-
732
-	/**
733
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
734
-	 * @param string $name the display name of the object
735
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
736
-	 *
737
-	 * Instead of using this method directly, call
738
-	 * createAltInternalOwnCloudName($name, false)
739
-	 *
740
-	 * Group names are also used as display names, so we do a sequential
741
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
742
-	 * "Developers"
743
-	 */
744
-	private function _createAltInternalOwnCloudNameForGroups($name) {
745
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
746
-		if(!($usedNames) || count($usedNames) === 0) {
747
-			$lastNo = 1; //will become name_2
748
-		} else {
749
-			natsort($usedNames);
750
-			$lastName = array_pop($usedNames);
751
-			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
752
-		}
753
-		$altName = $name.'_'.strval($lastNo+1);
754
-		unset($usedNames);
755
-
756
-		$attempts = 1;
757
-		while($attempts < 21){
758
-			// Check to be really sure it is unique
759
-			// while loop is just a precaution. If a name is not generated within
760
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
761
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
762
-				return $altName;
763
-			}
764
-			$altName = $name . '_' . ($lastNo + $attempts);
765
-			$attempts++;
766
-		}
767
-		return false;
768
-	}
769
-
770
-	/**
771
-	 * creates a unique name for internal Nextcloud use.
772
-	 * @param string $name the display name of the object
773
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
774
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
775
-	 */
776
-	private function createAltInternalOwnCloudName($name, $isUser) {
777
-		$originalTTL = $this->connection->ldapCacheTTL;
778
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
779
-		if($isUser) {
780
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
781
-		} else {
782
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
783
-		}
784
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
785
-
786
-		return $altName;
787
-	}
788
-
789
-	/**
790
-	 * fetches a list of users according to a provided loginName and utilizing
791
-	 * the login filter.
792
-	 *
793
-	 * @param string $loginName
794
-	 * @param array $attributes optional, list of attributes to read
795
-	 * @return array
796
-	 */
797
-	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
798
-		$loginName = $this->escapeFilterPart($loginName);
799
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
800
-		$users = $this->fetchListOfUsers($filter, $attributes);
801
-		return $users;
802
-	}
803
-
804
-	/**
805
-	 * counts the number of users according to a provided loginName and
806
-	 * utilizing the login filter.
807
-	 *
808
-	 * @param string $loginName
809
-	 * @return int
810
-	 */
811
-	public function countUsersByLoginName($loginName) {
812
-		$loginName = $this->escapeFilterPart($loginName);
813
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
814
-		$users = $this->countUsers($filter);
815
-		return $users;
816
-	}
817
-
818
-	/**
819
-	 * @param string $filter
820
-	 * @param string|string[] $attr
821
-	 * @param int $limit
822
-	 * @param int $offset
823
-	 * @param bool $forceApplyAttributes
824
-	 * @return array
825
-	 */
826
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
827
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
828
-		$recordsToUpdate = $ldapRecords;
829
-		if(!$forceApplyAttributes) {
830
-			$isBackgroundJobModeAjax = $this->config
831
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
832
-			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
833
-				$newlyMapped = false;
834
-				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
835
-				if(is_string($uid)) {
836
-					$this->cacheUserExists($uid);
837
-				}
838
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
839
-			});
840
-		}
841
-		$this->batchApplyUserAttributes($recordsToUpdate);
842
-		return $this->fetchList($ldapRecords, (count($attr) > 1));
843
-	}
844
-
845
-	/**
846
-	 * provided with an array of LDAP user records the method will fetch the
847
-	 * user object and requests it to process the freshly fetched attributes and
848
-	 * and their values
849
-	 * @param array $ldapRecords
850
-	 */
851
-	public function batchApplyUserAttributes(array $ldapRecords){
852
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
853
-		foreach($ldapRecords as $userRecord) {
854
-			if(!isset($userRecord[$displayNameAttribute])) {
855
-				// displayName is obligatory
856
-				continue;
857
-			}
858
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
859
-			if($ocName === false) {
860
-				continue;
861
-			}
862
-			$user = $this->userManager->get($ocName);
863
-			if($user instanceof OfflineUser) {
864
-				$user->unmark();
865
-				$user = $this->userManager->get($ocName);
866
-			}
867
-			if ($user !== null) {
868
-				$user->processAttributes($userRecord);
869
-			} else {
870
-				\OC::$server->getLogger()->debug(
871
-					"The ldap user manager returned null for $ocName",
872
-					['app'=>'user_ldap']
873
-				);
874
-			}
875
-		}
876
-	}
877
-
878
-	/**
879
-	 * @param string $filter
880
-	 * @param string|string[] $attr
881
-	 * @param int $limit
882
-	 * @param int $offset
883
-	 * @return array
884
-	 */
885
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
886
-		return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
887
-	}
888
-
889
-	/**
890
-	 * @param array $list
891
-	 * @param bool $manyAttributes
892
-	 * @return array
893
-	 */
894
-	private function fetchList($list, $manyAttributes) {
895
-		if(is_array($list)) {
896
-			if($manyAttributes) {
897
-				return $list;
898
-			} else {
899
-				$list = array_reduce($list, function($carry, $item) {
900
-					$attribute = array_keys($item)[0];
901
-					$carry[] = $item[$attribute][0];
902
-					return $carry;
903
-				}, array());
904
-				return array_unique($list, SORT_LOCALE_STRING);
905
-			}
906
-		}
907
-
908
-		//error cause actually, maybe throw an exception in future.
909
-		return array();
910
-	}
911
-
912
-	/**
913
-	 * executes an LDAP search, optimized for Users
914
-	 * @param string $filter the LDAP filter for the search
915
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
916
-	 * @param integer $limit
917
-	 * @param integer $offset
918
-	 * @return array with the search result
919
-	 *
920
-	 * Executes an LDAP search
921
-	 */
922
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
923
-		return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
924
-	}
925
-
926
-	/**
927
-	 * @param string $filter
928
-	 * @param string|string[] $attr
929
-	 * @param int $limit
930
-	 * @param int $offset
931
-	 * @return false|int
932
-	 */
933
-	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
934
-		return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
935
-	}
936
-
937
-	/**
938
-	 * executes an LDAP search, optimized for Groups
939
-	 * @param string $filter the LDAP filter for the search
940
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
941
-	 * @param integer $limit
942
-	 * @param integer $offset
943
-	 * @return array with the search result
944
-	 *
945
-	 * Executes an LDAP search
946
-	 */
947
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
948
-		return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
949
-	}
950
-
951
-	/**
952
-	 * returns the number of available groups
953
-	 * @param string $filter the LDAP search filter
954
-	 * @param string[] $attr optional
955
-	 * @param int|null $limit
956
-	 * @param int|null $offset
957
-	 * @return int|bool
958
-	 */
959
-	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
960
-		return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
961
-	}
962
-
963
-	/**
964
-	 * returns the number of available objects on the base DN
965
-	 *
966
-	 * @param int|null $limit
967
-	 * @param int|null $offset
968
-	 * @return int|bool
969
-	 */
970
-	public function countObjects($limit = null, $offset = null) {
971
-		return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
972
-	}
973
-
974
-	/**
975
-	 * Returns the LDAP handler
976
-	 * @throws \OC\ServerNotAvailableException
977
-	 */
978
-
979
-	/**
980
-	 * @return mixed
981
-	 * @throws \OC\ServerNotAvailableException
982
-	 */
983
-	private function invokeLDAPMethod() {
984
-		$arguments = func_get_args();
985
-		$command = array_shift($arguments);
986
-		$cr = array_shift($arguments);
987
-		if (!method_exists($this->ldap, $command)) {
988
-			return null;
989
-		}
990
-		array_unshift($arguments, $cr);
991
-		// php no longer supports call-time pass-by-reference
992
-		// thus cannot support controlPagedResultResponse as the third argument
993
-		// is a reference
994
-		$doMethod = function () use ($command, &$arguments) {
995
-			if ($command == 'controlPagedResultResponse') {
996
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
997
-			} else {
998
-				return call_user_func_array(array($this->ldap, $command), $arguments);
999
-			}
1000
-		};
1001
-		try {
1002
-			$ret = $doMethod();
1003
-		} catch (ServerNotAvailableException $e) {
1004
-			/* Server connection lost, attempt to reestablish it
342
+    /**
343
+     * Set password for an LDAP user identified by a DN
344
+     *
345
+     * @param string $userDN the user in question
346
+     * @param string $password the new password
347
+     * @return bool
348
+     * @throws HintException
349
+     * @throws \Exception
350
+     */
351
+    public function setPassword($userDN, $password) {
352
+        if(intval($this->connection->turnOnPasswordChange) !== 1) {
353
+            throw new \Exception('LDAP password changes are disabled.');
354
+        }
355
+        $cr = $this->connection->getConnectionResource();
356
+        if(!$this->ldap->isResource($cr)) {
357
+            //LDAP not available
358
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
359
+            return false;
360
+        }
361
+        try {
362
+            return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
363
+        } catch(ConstraintViolationException $e) {
364
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
365
+        }
366
+    }
367
+
368
+    /**
369
+     * checks whether the given attributes value is probably a DN
370
+     * @param string $attr the attribute in question
371
+     * @return boolean if so true, otherwise false
372
+     */
373
+    private function resemblesDN($attr) {
374
+        $resemblingAttributes = array(
375
+            'dn',
376
+            'uniquemember',
377
+            'member',
378
+            // memberOf is an "operational" attribute, without a definition in any RFC
379
+            'memberof'
380
+        );
381
+        return in_array($attr, $resemblingAttributes);
382
+    }
383
+
384
+    /**
385
+     * checks whether the given string is probably a DN
386
+     * @param string $string
387
+     * @return boolean
388
+     */
389
+    public function stringResemblesDN($string) {
390
+        $r = $this->ldap->explodeDN($string, 0);
391
+        // if exploding a DN succeeds and does not end up in
392
+        // an empty array except for $r[count] being 0.
393
+        return (is_array($r) && count($r) > 1);
394
+    }
395
+
396
+    /**
397
+     * returns a DN-string that is cleaned from not domain parts, e.g.
398
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
399
+     * becomes dc=foobar,dc=server,dc=org
400
+     * @param string $dn
401
+     * @return string
402
+     */
403
+    public function getDomainDNFromDN($dn) {
404
+        $allParts = $this->ldap->explodeDN($dn, 0);
405
+        if($allParts === false) {
406
+            //not a valid DN
407
+            return '';
408
+        }
409
+        $domainParts = array();
410
+        $dcFound = false;
411
+        foreach($allParts as $part) {
412
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
413
+                $dcFound = true;
414
+            }
415
+            if($dcFound) {
416
+                $domainParts[] = $part;
417
+            }
418
+        }
419
+        $domainDN = implode(',', $domainParts);
420
+        return $domainDN;
421
+    }
422
+
423
+    /**
424
+     * returns the LDAP DN for the given internal Nextcloud name of the group
425
+     * @param string $name the Nextcloud name in question
426
+     * @return string|false LDAP DN on success, otherwise false
427
+     */
428
+    public function groupname2dn($name) {
429
+        return $this->groupMapper->getDNByName($name);
430
+    }
431
+
432
+    /**
433
+     * returns the LDAP DN for the given internal Nextcloud name of the user
434
+     * @param string $name the Nextcloud name in question
435
+     * @return string|false with the LDAP DN on success, otherwise false
436
+     */
437
+    public function username2dn($name) {
438
+        $fdn = $this->userMapper->getDNByName($name);
439
+
440
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
441
+        //server setups
442
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
443
+            return $fdn;
444
+        }
445
+
446
+        return false;
447
+    }
448
+
449
+    /**
450
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
451
+     * @param string $fdn the dn of the group object
452
+     * @param string $ldapName optional, the display name of the object
453
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
454
+     */
455
+    public function dn2groupname($fdn, $ldapName = null) {
456
+        //To avoid bypassing the base DN settings under certain circumstances
457
+        //with the group support, check whether the provided DN matches one of
458
+        //the given Bases
459
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
460
+            return false;
461
+        }
462
+
463
+        return $this->dn2ocname($fdn, $ldapName, false);
464
+    }
465
+
466
+    /**
467
+     * accepts an array of group DNs and tests whether they match the user
468
+     * filter by doing read operations against the group entries. Returns an
469
+     * array of DNs that match the filter.
470
+     *
471
+     * @param string[] $groupDNs
472
+     * @return string[]
473
+     */
474
+    public function groupsMatchFilter($groupDNs) {
475
+        $validGroupDNs = [];
476
+        foreach($groupDNs as $dn) {
477
+            $cacheKey = 'groupsMatchFilter-'.$dn;
478
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
479
+            if(!is_null($groupMatchFilter)) {
480
+                if($groupMatchFilter) {
481
+                    $validGroupDNs[] = $dn;
482
+                }
483
+                continue;
484
+            }
485
+
486
+            // Check the base DN first. If this is not met already, we don't
487
+            // need to ask the server at all.
488
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
489
+                $this->connection->writeToCache($cacheKey, false);
490
+                continue;
491
+            }
492
+
493
+            $result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
494
+            if(is_array($result)) {
495
+                $this->connection->writeToCache($cacheKey, true);
496
+                $validGroupDNs[] = $dn;
497
+            } else {
498
+                $this->connection->writeToCache($cacheKey, false);
499
+            }
500
+
501
+        }
502
+        return $validGroupDNs;
503
+    }
504
+
505
+    /**
506
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
507
+     * @param string $dn the dn of the user object
508
+     * @param string $ldapName optional, the display name of the object
509
+     * @return string|false with with the name to use in Nextcloud
510
+     */
511
+    public function dn2username($fdn, $ldapName = null) {
512
+        //To avoid bypassing the base DN settings under certain circumstances
513
+        //with the group support, check whether the provided DN matches one of
514
+        //the given Bases
515
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
516
+            return false;
517
+        }
518
+
519
+        return $this->dn2ocname($fdn, $ldapName, true);
520
+    }
521
+
522
+    /**
523
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
524
+     *
525
+     * @param string $fdn the dn of the user object
526
+     * @param string|null $ldapName optional, the display name of the object
527
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
528
+     * @param bool|null $newlyMapped
529
+     * @param array|null $record
530
+     * @return false|string with with the name to use in Nextcloud
531
+     * @throws \Exception
532
+     */
533
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
534
+        $newlyMapped = false;
535
+        if($isUser) {
536
+            $mapper = $this->getUserMapper();
537
+            $nameAttribute = $this->connection->ldapUserDisplayName;
538
+        } else {
539
+            $mapper = $this->getGroupMapper();
540
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
541
+        }
542
+
543
+        //let's try to retrieve the Nextcloud name from the mappings table
544
+        $ncName = $mapper->getNameByDN($fdn);
545
+        if(is_string($ncName)) {
546
+            return $ncName;
547
+        }
548
+
549
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
550
+        $uuid = $this->getUUID($fdn, $isUser, $record);
551
+        if(is_string($uuid)) {
552
+            $ncName = $mapper->getNameByUUID($uuid);
553
+            if(is_string($ncName)) {
554
+                $mapper->setDNbyUUID($fdn, $uuid);
555
+                return $ncName;
556
+            }
557
+        } else {
558
+            //If the UUID can't be detected something is foul.
559
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
560
+            return false;
561
+        }
562
+
563
+        if(is_null($ldapName)) {
564
+            $ldapName = $this->readAttribute($fdn, $nameAttribute);
565
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
566
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
567
+                return false;
568
+            }
569
+            $ldapName = $ldapName[0];
570
+        }
571
+
572
+        if($isUser) {
573
+            $usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
574
+            if ($usernameAttribute !== '') {
575
+                $username = $this->readAttribute($fdn, $usernameAttribute);
576
+                $username = $username[0];
577
+            } else {
578
+                $username = $uuid;
579
+            }
580
+            $intName = $this->sanitizeUsername($username);
581
+        } else {
582
+            $intName = $ldapName;
583
+        }
584
+
585
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
586
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
587
+        //NOTE: mind, disabling cache affects only this instance! Using it
588
+        // outside of core user management will still cache the user as non-existing.
589
+        $originalTTL = $this->connection->ldapCacheTTL;
590
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
591
+        if(($isUser && $intName !== '' && !\OC::$server->getUserManager()->userExists($intName))
592
+            || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
593
+            if($mapper->map($fdn, $intName, $uuid)) {
594
+                $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
595
+                $newlyMapped = true;
596
+                return $intName;
597
+            }
598
+        }
599
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
600
+
601
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
602
+        if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
603
+            $newlyMapped = true;
604
+            return $altName;
605
+        }
606
+
607
+        //if everything else did not help..
608
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
609
+        return false;
610
+    }
611
+
612
+    /**
613
+     * gives back the user names as they are used ownClod internally
614
+     * @param array $ldapUsers as returned by fetchList()
615
+     * @return array an array with the user names to use in Nextcloud
616
+     *
617
+     * gives back the user names as they are used ownClod internally
618
+     */
619
+    public function nextcloudUserNames($ldapUsers) {
620
+        return $this->ldap2NextcloudNames($ldapUsers, true);
621
+    }
622
+
623
+    /**
624
+     * gives back the group names as they are used ownClod internally
625
+     * @param array $ldapGroups as returned by fetchList()
626
+     * @return array an array with the group names to use in Nextcloud
627
+     *
628
+     * gives back the group names as they are used ownClod internally
629
+     */
630
+    public function nextcloudGroupNames($ldapGroups) {
631
+        return $this->ldap2NextcloudNames($ldapGroups, false);
632
+    }
633
+
634
+    /**
635
+     * @param array $ldapObjects as returned by fetchList()
636
+     * @param bool $isUsers
637
+     * @return array
638
+     */
639
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
640
+        if($isUsers) {
641
+            $nameAttribute = $this->connection->ldapUserDisplayName;
642
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
643
+        } else {
644
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
645
+        }
646
+        $nextcloudNames = array();
647
+
648
+        foreach($ldapObjects as $ldapObject) {
649
+            $nameByLDAP = null;
650
+            if(    isset($ldapObject[$nameAttribute])
651
+                && is_array($ldapObject[$nameAttribute])
652
+                && isset($ldapObject[$nameAttribute][0])
653
+            ) {
654
+                // might be set, but not necessarily. if so, we use it.
655
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
656
+            }
657
+
658
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
659
+            if($ncName) {
660
+                $nextcloudNames[] = $ncName;
661
+                if($isUsers) {
662
+                    //cache the user names so it does not need to be retrieved
663
+                    //again later (e.g. sharing dialogue).
664
+                    if(is_null($nameByLDAP)) {
665
+                        continue;
666
+                    }
667
+                    $sndName = isset($ldapObject[$sndAttribute][0])
668
+                        ? $ldapObject[$sndAttribute][0] : '';
669
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
670
+                }
671
+            }
672
+        }
673
+        return $nextcloudNames;
674
+    }
675
+
676
+    /**
677
+     * caches the user display name
678
+     * @param string $ocName the internal Nextcloud username
679
+     * @param string|false $home the home directory path
680
+     */
681
+    public function cacheUserHome($ocName, $home) {
682
+        $cacheKey = 'getHome'.$ocName;
683
+        $this->connection->writeToCache($cacheKey, $home);
684
+    }
685
+
686
+    /**
687
+     * caches a user as existing
688
+     * @param string $ocName the internal Nextcloud username
689
+     */
690
+    public function cacheUserExists($ocName) {
691
+        $this->connection->writeToCache('userExists'.$ocName, true);
692
+    }
693
+
694
+    /**
695
+     * caches the user display name
696
+     * @param string $ocName the internal Nextcloud username
697
+     * @param string $displayName the display name
698
+     * @param string $displayName2 the second display name
699
+     */
700
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
701
+        $user = $this->userManager->get($ocName);
702
+        if($user === null) {
703
+            return;
704
+        }
705
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
706
+        $cacheKeyTrunk = 'getDisplayName';
707
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
708
+    }
709
+
710
+    /**
711
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
712
+     * @param string $name the display name of the object
713
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
714
+     *
715
+     * Instead of using this method directly, call
716
+     * createAltInternalOwnCloudName($name, true)
717
+     */
718
+    private function _createAltInternalOwnCloudNameForUsers($name) {
719
+        $attempts = 0;
720
+        //while loop is just a precaution. If a name is not generated within
721
+        //20 attempts, something else is very wrong. Avoids infinite loop.
722
+        while($attempts < 20){
723
+            $altName = $name . '_' . rand(1000,9999);
724
+            if(!\OC::$server->getUserManager()->userExists($altName)) {
725
+                return $altName;
726
+            }
727
+            $attempts++;
728
+        }
729
+        return false;
730
+    }
731
+
732
+    /**
733
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
734
+     * @param string $name the display name of the object
735
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
736
+     *
737
+     * Instead of using this method directly, call
738
+     * createAltInternalOwnCloudName($name, false)
739
+     *
740
+     * Group names are also used as display names, so we do a sequential
741
+     * numbering, e.g. Developers_42 when there are 41 other groups called
742
+     * "Developers"
743
+     */
744
+    private function _createAltInternalOwnCloudNameForGroups($name) {
745
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
746
+        if(!($usedNames) || count($usedNames) === 0) {
747
+            $lastNo = 1; //will become name_2
748
+        } else {
749
+            natsort($usedNames);
750
+            $lastName = array_pop($usedNames);
751
+            $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
752
+        }
753
+        $altName = $name.'_'.strval($lastNo+1);
754
+        unset($usedNames);
755
+
756
+        $attempts = 1;
757
+        while($attempts < 21){
758
+            // Check to be really sure it is unique
759
+            // while loop is just a precaution. If a name is not generated within
760
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
761
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
762
+                return $altName;
763
+            }
764
+            $altName = $name . '_' . ($lastNo + $attempts);
765
+            $attempts++;
766
+        }
767
+        return false;
768
+    }
769
+
770
+    /**
771
+     * creates a unique name for internal Nextcloud use.
772
+     * @param string $name the display name of the object
773
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
774
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
775
+     */
776
+    private function createAltInternalOwnCloudName($name, $isUser) {
777
+        $originalTTL = $this->connection->ldapCacheTTL;
778
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
779
+        if($isUser) {
780
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
781
+        } else {
782
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
783
+        }
784
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
785
+
786
+        return $altName;
787
+    }
788
+
789
+    /**
790
+     * fetches a list of users according to a provided loginName and utilizing
791
+     * the login filter.
792
+     *
793
+     * @param string $loginName
794
+     * @param array $attributes optional, list of attributes to read
795
+     * @return array
796
+     */
797
+    public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
798
+        $loginName = $this->escapeFilterPart($loginName);
799
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
800
+        $users = $this->fetchListOfUsers($filter, $attributes);
801
+        return $users;
802
+    }
803
+
804
+    /**
805
+     * counts the number of users according to a provided loginName and
806
+     * utilizing the login filter.
807
+     *
808
+     * @param string $loginName
809
+     * @return int
810
+     */
811
+    public function countUsersByLoginName($loginName) {
812
+        $loginName = $this->escapeFilterPart($loginName);
813
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
814
+        $users = $this->countUsers($filter);
815
+        return $users;
816
+    }
817
+
818
+    /**
819
+     * @param string $filter
820
+     * @param string|string[] $attr
821
+     * @param int $limit
822
+     * @param int $offset
823
+     * @param bool $forceApplyAttributes
824
+     * @return array
825
+     */
826
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
827
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
828
+        $recordsToUpdate = $ldapRecords;
829
+        if(!$forceApplyAttributes) {
830
+            $isBackgroundJobModeAjax = $this->config
831
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
832
+            $recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
833
+                $newlyMapped = false;
834
+                $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
835
+                if(is_string($uid)) {
836
+                    $this->cacheUserExists($uid);
837
+                }
838
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
839
+            });
840
+        }
841
+        $this->batchApplyUserAttributes($recordsToUpdate);
842
+        return $this->fetchList($ldapRecords, (count($attr) > 1));
843
+    }
844
+
845
+    /**
846
+     * provided with an array of LDAP user records the method will fetch the
847
+     * user object and requests it to process the freshly fetched attributes and
848
+     * and their values
849
+     * @param array $ldapRecords
850
+     */
851
+    public function batchApplyUserAttributes(array $ldapRecords){
852
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
853
+        foreach($ldapRecords as $userRecord) {
854
+            if(!isset($userRecord[$displayNameAttribute])) {
855
+                // displayName is obligatory
856
+                continue;
857
+            }
858
+            $ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
859
+            if($ocName === false) {
860
+                continue;
861
+            }
862
+            $user = $this->userManager->get($ocName);
863
+            if($user instanceof OfflineUser) {
864
+                $user->unmark();
865
+                $user = $this->userManager->get($ocName);
866
+            }
867
+            if ($user !== null) {
868
+                $user->processAttributes($userRecord);
869
+            } else {
870
+                \OC::$server->getLogger()->debug(
871
+                    "The ldap user manager returned null for $ocName",
872
+                    ['app'=>'user_ldap']
873
+                );
874
+            }
875
+        }
876
+    }
877
+
878
+    /**
879
+     * @param string $filter
880
+     * @param string|string[] $attr
881
+     * @param int $limit
882
+     * @param int $offset
883
+     * @return array
884
+     */
885
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
886
+        return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
887
+    }
888
+
889
+    /**
890
+     * @param array $list
891
+     * @param bool $manyAttributes
892
+     * @return array
893
+     */
894
+    private function fetchList($list, $manyAttributes) {
895
+        if(is_array($list)) {
896
+            if($manyAttributes) {
897
+                return $list;
898
+            } else {
899
+                $list = array_reduce($list, function($carry, $item) {
900
+                    $attribute = array_keys($item)[0];
901
+                    $carry[] = $item[$attribute][0];
902
+                    return $carry;
903
+                }, array());
904
+                return array_unique($list, SORT_LOCALE_STRING);
905
+            }
906
+        }
907
+
908
+        //error cause actually, maybe throw an exception in future.
909
+        return array();
910
+    }
911
+
912
+    /**
913
+     * executes an LDAP search, optimized for Users
914
+     * @param string $filter the LDAP filter for the search
915
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
916
+     * @param integer $limit
917
+     * @param integer $offset
918
+     * @return array with the search result
919
+     *
920
+     * Executes an LDAP search
921
+     */
922
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
923
+        return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
924
+    }
925
+
926
+    /**
927
+     * @param string $filter
928
+     * @param string|string[] $attr
929
+     * @param int $limit
930
+     * @param int $offset
931
+     * @return false|int
932
+     */
933
+    public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
934
+        return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
935
+    }
936
+
937
+    /**
938
+     * executes an LDAP search, optimized for Groups
939
+     * @param string $filter the LDAP filter for the search
940
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
941
+     * @param integer $limit
942
+     * @param integer $offset
943
+     * @return array with the search result
944
+     *
945
+     * Executes an LDAP search
946
+     */
947
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
948
+        return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
949
+    }
950
+
951
+    /**
952
+     * returns the number of available groups
953
+     * @param string $filter the LDAP search filter
954
+     * @param string[] $attr optional
955
+     * @param int|null $limit
956
+     * @param int|null $offset
957
+     * @return int|bool
958
+     */
959
+    public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
960
+        return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
961
+    }
962
+
963
+    /**
964
+     * returns the number of available objects on the base DN
965
+     *
966
+     * @param int|null $limit
967
+     * @param int|null $offset
968
+     * @return int|bool
969
+     */
970
+    public function countObjects($limit = null, $offset = null) {
971
+        return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
972
+    }
973
+
974
+    /**
975
+     * Returns the LDAP handler
976
+     * @throws \OC\ServerNotAvailableException
977
+     */
978
+
979
+    /**
980
+     * @return mixed
981
+     * @throws \OC\ServerNotAvailableException
982
+     */
983
+    private function invokeLDAPMethod() {
984
+        $arguments = func_get_args();
985
+        $command = array_shift($arguments);
986
+        $cr = array_shift($arguments);
987
+        if (!method_exists($this->ldap, $command)) {
988
+            return null;
989
+        }
990
+        array_unshift($arguments, $cr);
991
+        // php no longer supports call-time pass-by-reference
992
+        // thus cannot support controlPagedResultResponse as the third argument
993
+        // is a reference
994
+        $doMethod = function () use ($command, &$arguments) {
995
+            if ($command == 'controlPagedResultResponse') {
996
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
997
+            } else {
998
+                return call_user_func_array(array($this->ldap, $command), $arguments);
999
+            }
1000
+        };
1001
+        try {
1002
+            $ret = $doMethod();
1003
+        } catch (ServerNotAvailableException $e) {
1004
+            /* Server connection lost, attempt to reestablish it
1005 1005
 			 * Maybe implement exponential backoff?
1006 1006
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1007 1007
 			 */
1008
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG);
1009
-			$this->connection->resetConnectionResource();
1010
-			$cr = $this->connection->getConnectionResource();
1011
-
1012
-			if(!$this->ldap->isResource($cr)) {
1013
-				// Seems like we didn't find any resource.
1014
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1015
-				throw $e;
1016
-			}
1017
-
1018
-			$arguments[0] = array_pad([], count($arguments[0]), $cr);
1019
-			$ret = $doMethod();
1020
-		}
1021
-		return $ret;
1022
-	}
1023
-
1024
-	/**
1025
-	 * retrieved. Results will according to the order in the array.
1026
-	 *
1027
-	 * @param $filter
1028
-	 * @param $base
1029
-	 * @param string[]|string|null $attr
1030
-	 * @param int $limit optional, maximum results to be counted
1031
-	 * @param int $offset optional, a starting point
1032
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1033
-	 * second | false if not successful
1034
-	 * @throws ServerNotAvailableException
1035
-	 */
1036
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1037
-		if(!is_null($attr) && !is_array($attr)) {
1038
-			$attr = array(mb_strtolower($attr, 'UTF-8'));
1039
-		}
1040
-
1041
-		// See if we have a resource, in case not cancel with message
1042
-		$cr = $this->connection->getConnectionResource();
1043
-		if(!$this->ldap->isResource($cr)) {
1044
-			// Seems like we didn't find any resource.
1045
-			// Return an empty array just like before.
1046
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
1047
-			return false;
1048
-		}
1049
-
1050
-		//check whether paged search should be attempted
1051
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
1052
-
1053
-		$linkResources = array_pad(array(), count($base), $cr);
1054
-		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1055
-		// cannot use $cr anymore, might have changed in the previous call!
1056
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1057
-		if(!is_array($sr) || $error !== 0) {
1058
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1059
-			return false;
1060
-		}
1061
-
1062
-		return array($sr, $pagedSearchOK);
1063
-	}
1064
-
1065
-	/**
1066
-	 * processes an LDAP paged search operation
1067
-	 * @param array $sr the array containing the LDAP search resources
1068
-	 * @param string $filter the LDAP filter for the search
1069
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1070
-	 * @param int $iFoundItems number of results in the single search operation
1071
-	 * @param int $limit maximum results to be counted
1072
-	 * @param int $offset a starting point
1073
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1074
-	 * @param bool $skipHandling required for paged search when cookies to
1075
-	 * prior results need to be gained
1076
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1077
-	 */
1078
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1079
-		$cookie = null;
1080
-		if($pagedSearchOK) {
1081
-			$cr = $this->connection->getConnectionResource();
1082
-			foreach($sr as $key => $res) {
1083
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1084
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1085
-				}
1086
-			}
1087
-
1088
-			//browsing through prior pages to get the cookie for the new one
1089
-			if($skipHandling) {
1090
-				return false;
1091
-			}
1092
-			// if count is bigger, then the server does not support
1093
-			// paged search. Instead, he did a normal search. We set a
1094
-			// flag here, so the callee knows how to deal with it.
1095
-			if($iFoundItems <= $limit) {
1096
-				$this->pagedSearchedSuccessful = true;
1097
-			}
1098
-		} else {
1099
-			if(!is_null($limit) && intval($this->connection->ldapPagingSize) !== 0) {
1100
-				\OC::$server->getLogger()->debug(
1101
-					'Paged search was not available',
1102
-					[ 'app' => 'user_ldap' ]
1103
-				);
1104
-			}
1105
-		}
1106
-		/* ++ Fixing RHDS searches with pages with zero results ++
1008
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG);
1009
+            $this->connection->resetConnectionResource();
1010
+            $cr = $this->connection->getConnectionResource();
1011
+
1012
+            if(!$this->ldap->isResource($cr)) {
1013
+                // Seems like we didn't find any resource.
1014
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1015
+                throw $e;
1016
+            }
1017
+
1018
+            $arguments[0] = array_pad([], count($arguments[0]), $cr);
1019
+            $ret = $doMethod();
1020
+        }
1021
+        return $ret;
1022
+    }
1023
+
1024
+    /**
1025
+     * retrieved. Results will according to the order in the array.
1026
+     *
1027
+     * @param $filter
1028
+     * @param $base
1029
+     * @param string[]|string|null $attr
1030
+     * @param int $limit optional, maximum results to be counted
1031
+     * @param int $offset optional, a starting point
1032
+     * @return array|false array with the search result as first value and pagedSearchOK as
1033
+     * second | false if not successful
1034
+     * @throws ServerNotAvailableException
1035
+     */
1036
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1037
+        if(!is_null($attr) && !is_array($attr)) {
1038
+            $attr = array(mb_strtolower($attr, 'UTF-8'));
1039
+        }
1040
+
1041
+        // See if we have a resource, in case not cancel with message
1042
+        $cr = $this->connection->getConnectionResource();
1043
+        if(!$this->ldap->isResource($cr)) {
1044
+            // Seems like we didn't find any resource.
1045
+            // Return an empty array just like before.
1046
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
1047
+            return false;
1048
+        }
1049
+
1050
+        //check whether paged search should be attempted
1051
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
1052
+
1053
+        $linkResources = array_pad(array(), count($base), $cr);
1054
+        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1055
+        // cannot use $cr anymore, might have changed in the previous call!
1056
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1057
+        if(!is_array($sr) || $error !== 0) {
1058
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1059
+            return false;
1060
+        }
1061
+
1062
+        return array($sr, $pagedSearchOK);
1063
+    }
1064
+
1065
+    /**
1066
+     * processes an LDAP paged search operation
1067
+     * @param array $sr the array containing the LDAP search resources
1068
+     * @param string $filter the LDAP filter for the search
1069
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1070
+     * @param int $iFoundItems number of results in the single search operation
1071
+     * @param int $limit maximum results to be counted
1072
+     * @param int $offset a starting point
1073
+     * @param bool $pagedSearchOK whether a paged search has been executed
1074
+     * @param bool $skipHandling required for paged search when cookies to
1075
+     * prior results need to be gained
1076
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1077
+     */
1078
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1079
+        $cookie = null;
1080
+        if($pagedSearchOK) {
1081
+            $cr = $this->connection->getConnectionResource();
1082
+            foreach($sr as $key => $res) {
1083
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1084
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1085
+                }
1086
+            }
1087
+
1088
+            //browsing through prior pages to get the cookie for the new one
1089
+            if($skipHandling) {
1090
+                return false;
1091
+            }
1092
+            // if count is bigger, then the server does not support
1093
+            // paged search. Instead, he did a normal search. We set a
1094
+            // flag here, so the callee knows how to deal with it.
1095
+            if($iFoundItems <= $limit) {
1096
+                $this->pagedSearchedSuccessful = true;
1097
+            }
1098
+        } else {
1099
+            if(!is_null($limit) && intval($this->connection->ldapPagingSize) !== 0) {
1100
+                \OC::$server->getLogger()->debug(
1101
+                    'Paged search was not available',
1102
+                    [ 'app' => 'user_ldap' ]
1103
+                );
1104
+            }
1105
+        }
1106
+        /* ++ Fixing RHDS searches with pages with zero results ++
1107 1107
 		 * Return cookie status. If we don't have more pages, with RHDS
1108 1108
 		 * cookie is null, with openldap cookie is an empty string and
1109 1109
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1110 1110
 		 */
1111
-		return !empty($cookie) || $cookie === '0';
1112
-	}
1113
-
1114
-	/**
1115
-	 * executes an LDAP search, but counts the results only
1116
-	 *
1117
-	 * @param string $filter the LDAP filter for the search
1118
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1119
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1120
-	 * retrieved. Results will according to the order in the array.
1121
-	 * @param int $limit optional, maximum results to be counted
1122
-	 * @param int $offset optional, a starting point
1123
-	 * @param bool $skipHandling indicates whether the pages search operation is
1124
-	 * completed
1125
-	 * @return int|false Integer or false if the search could not be initialized
1126
-	 * @throws ServerNotAvailableException
1127
-	 */
1128
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1129
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1130
-
1131
-		$limitPerPage = intval($this->connection->ldapPagingSize);
1132
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1133
-			$limitPerPage = $limit;
1134
-		}
1135
-
1136
-		$counter = 0;
1137
-		$count = null;
1138
-		$this->connection->getConnectionResource();
1139
-
1140
-		do {
1141
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1142
-			if($search === false) {
1143
-				return $counter > 0 ? $counter : false;
1144
-			}
1145
-			list($sr, $pagedSearchOK) = $search;
1146
-
1147
-			/* ++ Fixing RHDS searches with pages with zero results ++
1111
+        return !empty($cookie) || $cookie === '0';
1112
+    }
1113
+
1114
+    /**
1115
+     * executes an LDAP search, but counts the results only
1116
+     *
1117
+     * @param string $filter the LDAP filter for the search
1118
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1119
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1120
+     * retrieved. Results will according to the order in the array.
1121
+     * @param int $limit optional, maximum results to be counted
1122
+     * @param int $offset optional, a starting point
1123
+     * @param bool $skipHandling indicates whether the pages search operation is
1124
+     * completed
1125
+     * @return int|false Integer or false if the search could not be initialized
1126
+     * @throws ServerNotAvailableException
1127
+     */
1128
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1129
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1130
+
1131
+        $limitPerPage = intval($this->connection->ldapPagingSize);
1132
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1133
+            $limitPerPage = $limit;
1134
+        }
1135
+
1136
+        $counter = 0;
1137
+        $count = null;
1138
+        $this->connection->getConnectionResource();
1139
+
1140
+        do {
1141
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1142
+            if($search === false) {
1143
+                return $counter > 0 ? $counter : false;
1144
+            }
1145
+            list($sr, $pagedSearchOK) = $search;
1146
+
1147
+            /* ++ Fixing RHDS searches with pages with zero results ++
1148 1148
 			 * countEntriesInSearchResults() method signature changed
1149 1149
 			 * by removing $limit and &$hasHitLimit parameters
1150 1150
 			 */
1151
-			$count = $this->countEntriesInSearchResults($sr);
1152
-			$counter += $count;
1151
+            $count = $this->countEntriesInSearchResults($sr);
1152
+            $counter += $count;
1153 1153
 
1154
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1155
-										$offset, $pagedSearchOK, $skipHandling);
1156
-			$offset += $limitPerPage;
1157
-			/* ++ Fixing RHDS searches with pages with zero results ++
1154
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1155
+                                        $offset, $pagedSearchOK, $skipHandling);
1156
+            $offset += $limitPerPage;
1157
+            /* ++ Fixing RHDS searches with pages with zero results ++
1158 1158
 			 * Continue now depends on $hasMorePages value
1159 1159
 			 */
1160
-			$continue = $pagedSearchOK && $hasMorePages;
1161
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1162
-
1163
-		return $counter;
1164
-	}
1165
-
1166
-	/**
1167
-	 * @param array $searchResults
1168
-	 * @return int
1169
-	 */
1170
-	private function countEntriesInSearchResults($searchResults) {
1171
-		$counter = 0;
1172
-
1173
-		foreach($searchResults as $res) {
1174
-			$count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1175
-			$counter += $count;
1176
-		}
1177
-
1178
-		return $counter;
1179
-	}
1180
-
1181
-	/**
1182
-	 * Executes an LDAP search
1183
-	 *
1184
-	 * @param string $filter the LDAP filter for the search
1185
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1186
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1187
-	 * @param int $limit
1188
-	 * @param int $offset
1189
-	 * @param bool $skipHandling
1190
-	 * @return array with the search result
1191
-	 * @throws ServerNotAvailableException
1192
-	 */
1193
-	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1194
-		$limitPerPage = intval($this->connection->ldapPagingSize);
1195
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1196
-			$limitPerPage = $limit;
1197
-		}
1198
-
1199
-		/* ++ Fixing RHDS searches with pages with zero results ++
1160
+            $continue = $pagedSearchOK && $hasMorePages;
1161
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1162
+
1163
+        return $counter;
1164
+    }
1165
+
1166
+    /**
1167
+     * @param array $searchResults
1168
+     * @return int
1169
+     */
1170
+    private function countEntriesInSearchResults($searchResults) {
1171
+        $counter = 0;
1172
+
1173
+        foreach($searchResults as $res) {
1174
+            $count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1175
+            $counter += $count;
1176
+        }
1177
+
1178
+        return $counter;
1179
+    }
1180
+
1181
+    /**
1182
+     * Executes an LDAP search
1183
+     *
1184
+     * @param string $filter the LDAP filter for the search
1185
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1186
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1187
+     * @param int $limit
1188
+     * @param int $offset
1189
+     * @param bool $skipHandling
1190
+     * @return array with the search result
1191
+     * @throws ServerNotAvailableException
1192
+     */
1193
+    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1194
+        $limitPerPage = intval($this->connection->ldapPagingSize);
1195
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1196
+            $limitPerPage = $limit;
1197
+        }
1198
+
1199
+        /* ++ Fixing RHDS searches with pages with zero results ++
1200 1200
 		 * As we can have pages with zero results and/or pages with less
1201 1201
 		 * than $limit results but with a still valid server 'cookie',
1202 1202
 		 * loops through until we get $continue equals true and
1203 1203
 		 * $findings['count'] < $limit
1204 1204
 		 */
1205
-		$findings = [];
1206
-		$savedoffset = $offset;
1207
-		do {
1208
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1209
-			if($search === false) {
1210
-				return [];
1211
-			}
1212
-			list($sr, $pagedSearchOK) = $search;
1213
-			$cr = $this->connection->getConnectionResource();
1214
-
1215
-			if($skipHandling) {
1216
-				//i.e. result do not need to be fetched, we just need the cookie
1217
-				//thus pass 1 or any other value as $iFoundItems because it is not
1218
-				//used
1219
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1220
-								$offset, $pagedSearchOK,
1221
-								$skipHandling);
1222
-				return array();
1223
-			}
1224
-
1225
-			$iFoundItems = 0;
1226
-			foreach($sr as $res) {
1227
-				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1228
-				$iFoundItems = max($iFoundItems, $findings['count']);
1229
-				unset($findings['count']);
1230
-			}
1231
-
1232
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1233
-				$limitPerPage, $offset, $pagedSearchOK,
1234
-										$skipHandling);
1235
-			$offset += $limitPerPage;
1236
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1237
-		// reseting offset
1238
-		$offset = $savedoffset;
1239
-
1240
-		// if we're here, probably no connection resource is returned.
1241
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1242
-		if(is_null($findings)) {
1243
-			return array();
1244
-		}
1245
-
1246
-		if(!is_null($attr)) {
1247
-			$selection = [];
1248
-			$i = 0;
1249
-			foreach($findings as $item) {
1250
-				if(!is_array($item)) {
1251
-					continue;
1252
-				}
1253
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1254
-				foreach($attr as $key) {
1255
-					if(isset($item[$key])) {
1256
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1257
-							unset($item[$key]['count']);
1258
-						}
1259
-						if($key !== 'dn') {
1260
-							if($this->resemblesDN($key)) {
1261
-								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1262
-							} else if($key === 'objectguid' || $key === 'guid') {
1263
-								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1264
-							} else {
1265
-								$selection[$i][$key] = $item[$key];
1266
-							}
1267
-						} else {
1268
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1269
-						}
1270
-					}
1271
-
1272
-				}
1273
-				$i++;
1274
-			}
1275
-			$findings = $selection;
1276
-		}
1277
-		//we slice the findings, when
1278
-		//a) paged search unsuccessful, though attempted
1279
-		//b) no paged search, but limit set
1280
-		if((!$this->getPagedSearchResultState()
1281
-			&& $pagedSearchOK)
1282
-			|| (
1283
-				!$pagedSearchOK
1284
-				&& !is_null($limit)
1285
-			)
1286
-		) {
1287
-			$findings = array_slice($findings, intval($offset), $limit);
1288
-		}
1289
-		return $findings;
1290
-	}
1291
-
1292
-	/**
1293
-	 * @param string $name
1294
-	 * @return bool|mixed|string
1295
-	 */
1296
-	public function sanitizeUsername($name) {
1297
-		if($this->connection->ldapIgnoreNamingRules) {
1298
-			return trim($name);
1299
-		}
1300
-
1301
-		// Transliteration
1302
-		// latin characters to ASCII
1303
-		$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1304
-
1305
-		// Replacements
1306
-		$name = str_replace(' ', '_', $name);
1307
-
1308
-		// Every remaining disallowed characters will be removed
1309
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1310
-
1311
-		return $name;
1312
-	}
1313
-
1314
-	/**
1315
-	* escapes (user provided) parts for LDAP filter
1316
-	* @param string $input, the provided value
1317
-	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1318
-	* @return string the escaped string
1319
-	*/
1320
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1321
-		$asterisk = '';
1322
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1323
-			$asterisk = '*';
1324
-			$input = mb_substr($input, 1, null, 'UTF-8');
1325
-		}
1326
-		$search  = array('*', '\\', '(', ')');
1327
-		$replace = array('\\*', '\\\\', '\\(', '\\)');
1328
-		return $asterisk . str_replace($search, $replace, $input);
1329
-	}
1330
-
1331
-	/**
1332
-	 * combines the input filters with AND
1333
-	 * @param string[] $filters the filters to connect
1334
-	 * @return string the combined filter
1335
-	 */
1336
-	public function combineFilterWithAnd($filters) {
1337
-		return $this->combineFilter($filters, '&');
1338
-	}
1339
-
1340
-	/**
1341
-	 * combines the input filters with OR
1342
-	 * @param string[] $filters the filters to connect
1343
-	 * @return string the combined filter
1344
-	 * Combines Filter arguments with OR
1345
-	 */
1346
-	public function combineFilterWithOr($filters) {
1347
-		return $this->combineFilter($filters, '|');
1348
-	}
1349
-
1350
-	/**
1351
-	 * combines the input filters with given operator
1352
-	 * @param string[] $filters the filters to connect
1353
-	 * @param string $operator either & or |
1354
-	 * @return string the combined filter
1355
-	 */
1356
-	private function combineFilter($filters, $operator) {
1357
-		$combinedFilter = '('.$operator;
1358
-		foreach($filters as $filter) {
1359
-			if ($filter !== '' && $filter[0] !== '(') {
1360
-				$filter = '('.$filter.')';
1361
-			}
1362
-			$combinedFilter.=$filter;
1363
-		}
1364
-		$combinedFilter.=')';
1365
-		return $combinedFilter;
1366
-	}
1367
-
1368
-	/**
1369
-	 * creates a filter part for to perform search for users
1370
-	 * @param string $search the search term
1371
-	 * @return string the final filter part to use in LDAP searches
1372
-	 */
1373
-	public function getFilterPartForUserSearch($search) {
1374
-		return $this->getFilterPartForSearch($search,
1375
-			$this->connection->ldapAttributesForUserSearch,
1376
-			$this->connection->ldapUserDisplayName);
1377
-	}
1378
-
1379
-	/**
1380
-	 * creates a filter part for to perform search for groups
1381
-	 * @param string $search the search term
1382
-	 * @return string the final filter part to use in LDAP searches
1383
-	 */
1384
-	public function getFilterPartForGroupSearch($search) {
1385
-		return $this->getFilterPartForSearch($search,
1386
-			$this->connection->ldapAttributesForGroupSearch,
1387
-			$this->connection->ldapGroupDisplayName);
1388
-	}
1389
-
1390
-	/**
1391
-	 * creates a filter part for searches by splitting up the given search
1392
-	 * string into single words
1393
-	 * @param string $search the search term
1394
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1395
-	 * otherwise it does not make sense :)
1396
-	 * @return string the final filter part to use in LDAP searches
1397
-	 * @throws \Exception
1398
-	 */
1399
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1400
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1401
-			throw new \Exception('searchAttributes must be an array with at least two string');
1402
-		}
1403
-		$searchWords = explode(' ', trim($search));
1404
-		$wordFilters = array();
1405
-		foreach($searchWords as $word) {
1406
-			$word = $this->prepareSearchTerm($word);
1407
-			//every word needs to appear at least once
1408
-			$wordMatchOneAttrFilters = array();
1409
-			foreach($searchAttributes as $attr) {
1410
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1411
-			}
1412
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1413
-		}
1414
-		return $this->combineFilterWithAnd($wordFilters);
1415
-	}
1416
-
1417
-	/**
1418
-	 * creates a filter part for searches
1419
-	 * @param string $search the search term
1420
-	 * @param string[]|null $searchAttributes
1421
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1422
-	 * did not define search attributes. Typically the display name attribute.
1423
-	 * @return string the final filter part to use in LDAP searches
1424
-	 */
1425
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1426
-		$filter = array();
1427
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1428
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1429
-			try {
1430
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1431
-			} catch(\Exception $e) {
1432
-				\OCP\Util::writeLog(
1433
-					'user_ldap',
1434
-					'Creating advanced filter for search failed, falling back to simple method.',
1435
-					\OCP\Util::INFO
1436
-				);
1437
-			}
1438
-		}
1439
-
1440
-		$search = $this->prepareSearchTerm($search);
1441
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1442
-			if ($fallbackAttribute === '') {
1443
-				return '';
1444
-			}
1445
-			$filter[] = $fallbackAttribute . '=' . $search;
1446
-		} else {
1447
-			foreach($searchAttributes as $attribute) {
1448
-				$filter[] = $attribute . '=' . $search;
1449
-			}
1450
-		}
1451
-		if(count($filter) === 1) {
1452
-			return '('.$filter[0].')';
1453
-		}
1454
-		return $this->combineFilterWithOr($filter);
1455
-	}
1456
-
1457
-	/**
1458
-	 * returns the search term depending on whether we are allowed
1459
-	 * list users found by ldap with the current input appended by
1460
-	 * a *
1461
-	 * @return string
1462
-	 */
1463
-	private function prepareSearchTerm($term) {
1464
-		$config = \OC::$server->getConfig();
1465
-
1466
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1467
-
1468
-		$result = $term;
1469
-		if ($term === '') {
1470
-			$result = '*';
1471
-		} else if ($allowEnum !== 'no') {
1472
-			$result = $term . '*';
1473
-		}
1474
-		return $result;
1475
-	}
1476
-
1477
-	/**
1478
-	 * returns the filter used for counting users
1479
-	 * @return string
1480
-	 */
1481
-	public function getFilterForUserCount() {
1482
-		$filter = $this->combineFilterWithAnd(array(
1483
-			$this->connection->ldapUserFilter,
1484
-			$this->connection->ldapUserDisplayName . '=*'
1485
-		));
1486
-
1487
-		return $filter;
1488
-	}
1489
-
1490
-	/**
1491
-	 * @param string $name
1492
-	 * @param string $password
1493
-	 * @return bool
1494
-	 */
1495
-	public function areCredentialsValid($name, $password) {
1496
-		$name = $this->helper->DNasBaseParameter($name);
1497
-		$testConnection = clone $this->connection;
1498
-		$credentials = array(
1499
-			'ldapAgentName' => $name,
1500
-			'ldapAgentPassword' => $password
1501
-		);
1502
-		if(!$testConnection->setConfiguration($credentials)) {
1503
-			return false;
1504
-		}
1505
-		return $testConnection->bind();
1506
-	}
1507
-
1508
-	/**
1509
-	 * reverse lookup of a DN given a known UUID
1510
-	 *
1511
-	 * @param string $uuid
1512
-	 * @return string
1513
-	 * @throws \Exception
1514
-	 */
1515
-	public function getUserDnByUuid($uuid) {
1516
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1517
-		$filter       = $this->connection->ldapUserFilter;
1518
-		$base         = $this->connection->ldapBaseUsers;
1519
-
1520
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1521
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1522
-			// existing DN to be able to reliably detect it.
1523
-			$result = $this->search($filter, $base, ['dn'], 1);
1524
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1525
-				throw new \Exception('Cannot determine UUID attribute');
1526
-			}
1527
-			$dn = $result[0]['dn'][0];
1528
-			if(!$this->detectUuidAttribute($dn, true)) {
1529
-				throw new \Exception('Cannot determine UUID attribute');
1530
-			}
1531
-		} else {
1532
-			// The UUID attribute is either known or an override is given.
1533
-			// By calling this method we ensure that $this->connection->$uuidAttr
1534
-			// is definitely set
1535
-			if(!$this->detectUuidAttribute('', true)) {
1536
-				throw new \Exception('Cannot determine UUID attribute');
1537
-			}
1538
-		}
1539
-
1540
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1541
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1542
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1543
-		}
1544
-
1545
-		$filter = $uuidAttr . '=' . $uuid;
1546
-		$result = $this->searchUsers($filter, ['dn'], 2);
1547
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1548
-			// we put the count into account to make sure that this is
1549
-			// really unique
1550
-			return $result[0]['dn'][0];
1551
-		}
1552
-
1553
-		throw new \Exception('Cannot determine UUID attribute');
1554
-	}
1555
-
1556
-	/**
1557
-	 * auto-detects the directory's UUID attribute
1558
-	 *
1559
-	 * @param string $dn a known DN used to check against
1560
-	 * @param bool $isUser
1561
-	 * @param bool $force the detection should be run, even if it is not set to auto
1562
-	 * @param array|null $ldapRecord
1563
-	 * @return bool true on success, false otherwise
1564
-	 */
1565
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1566
-		if($isUser) {
1567
-			$uuidAttr     = 'ldapUuidUserAttribute';
1568
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1569
-		} else {
1570
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1571
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1572
-		}
1573
-
1574
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1575
-			return true;
1576
-		}
1577
-
1578
-		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1579
-			$this->connection->$uuidAttr = $uuidOverride;
1580
-			return true;
1581
-		}
1582
-
1583
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1584
-			if($ldapRecord !== null) {
1585
-				// we have the info from LDAP already, we don't need to talk to the server again
1586
-				if(isset($ldapRecord[$attribute])) {
1587
-					$this->connection->$uuidAttr = $attribute;
1588
-					return true;
1589
-				} else {
1590
-					continue;
1591
-				}
1592
-			}
1593
-
1594
-			$value = $this->readAttribute($dn, $attribute);
1595
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1596
-				\OCP\Util::writeLog('user_ldap',
1597
-									'Setting '.$attribute.' as '.$uuidAttr,
1598
-									\OCP\Util::DEBUG);
1599
-				$this->connection->$uuidAttr = $attribute;
1600
-				return true;
1601
-			}
1602
-		}
1603
-		\OCP\Util::writeLog('user_ldap',
1604
-							'Could not autodetect the UUID attribute',
1605
-							\OCP\Util::ERROR);
1606
-
1607
-		return false;
1608
-	}
1609
-
1610
-	/**
1611
-	 * @param string $dn
1612
-	 * @param bool $isUser
1613
-	 * @param null $ldapRecord
1614
-	 * @return bool|string
1615
-	 */
1616
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1617
-		if($isUser) {
1618
-			$uuidAttr     = 'ldapUuidUserAttribute';
1619
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1620
-		} else {
1621
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1622
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1623
-		}
1624
-
1625
-		$uuid = false;
1626
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1627
-			$attr = $this->connection->$uuidAttr;
1628
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1629
-			if( !is_array($uuid)
1630
-				&& $uuidOverride !== ''
1631
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1632
-			{
1633
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1634
-					? $ldapRecord[$this->connection->$uuidAttr]
1635
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1636
-			}
1637
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1638
-				$uuid = $uuid[0];
1639
-			}
1640
-		}
1641
-
1642
-		return $uuid;
1643
-	}
1644
-
1645
-	/**
1646
-	 * converts a binary ObjectGUID into a string representation
1647
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1648
-	 * @return string
1649
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1650
-	 */
1651
-	private function convertObjectGUID2Str($oguid) {
1652
-		$hex_guid = bin2hex($oguid);
1653
-		$hex_guid_to_guid_str = '';
1654
-		for($k = 1; $k <= 4; ++$k) {
1655
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1656
-		}
1657
-		$hex_guid_to_guid_str .= '-';
1658
-		for($k = 1; $k <= 2; ++$k) {
1659
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1660
-		}
1661
-		$hex_guid_to_guid_str .= '-';
1662
-		for($k = 1; $k <= 2; ++$k) {
1663
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1664
-		}
1665
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1666
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1667
-
1668
-		return strtoupper($hex_guid_to_guid_str);
1669
-	}
1670
-
1671
-	/**
1672
-	 * the first three blocks of the string-converted GUID happen to be in
1673
-	 * reverse order. In order to use it in a filter, this needs to be
1674
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1675
-	 * to every two hax figures.
1676
-	 *
1677
-	 * If an invalid string is passed, it will be returned without change.
1678
-	 *
1679
-	 * @param string $guid
1680
-	 * @return string
1681
-	 */
1682
-	public function formatGuid2ForFilterUser($guid) {
1683
-		if(!is_string($guid)) {
1684
-			throw new \InvalidArgumentException('String expected');
1685
-		}
1686
-		$blocks = explode('-', $guid);
1687
-		if(count($blocks) !== 5) {
1688
-			/*
1205
+        $findings = [];
1206
+        $savedoffset = $offset;
1207
+        do {
1208
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1209
+            if($search === false) {
1210
+                return [];
1211
+            }
1212
+            list($sr, $pagedSearchOK) = $search;
1213
+            $cr = $this->connection->getConnectionResource();
1214
+
1215
+            if($skipHandling) {
1216
+                //i.e. result do not need to be fetched, we just need the cookie
1217
+                //thus pass 1 or any other value as $iFoundItems because it is not
1218
+                //used
1219
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1220
+                                $offset, $pagedSearchOK,
1221
+                                $skipHandling);
1222
+                return array();
1223
+            }
1224
+
1225
+            $iFoundItems = 0;
1226
+            foreach($sr as $res) {
1227
+                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1228
+                $iFoundItems = max($iFoundItems, $findings['count']);
1229
+                unset($findings['count']);
1230
+            }
1231
+
1232
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1233
+                $limitPerPage, $offset, $pagedSearchOK,
1234
+                                        $skipHandling);
1235
+            $offset += $limitPerPage;
1236
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1237
+        // reseting offset
1238
+        $offset = $savedoffset;
1239
+
1240
+        // if we're here, probably no connection resource is returned.
1241
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1242
+        if(is_null($findings)) {
1243
+            return array();
1244
+        }
1245
+
1246
+        if(!is_null($attr)) {
1247
+            $selection = [];
1248
+            $i = 0;
1249
+            foreach($findings as $item) {
1250
+                if(!is_array($item)) {
1251
+                    continue;
1252
+                }
1253
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1254
+                foreach($attr as $key) {
1255
+                    if(isset($item[$key])) {
1256
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1257
+                            unset($item[$key]['count']);
1258
+                        }
1259
+                        if($key !== 'dn') {
1260
+                            if($this->resemblesDN($key)) {
1261
+                                $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1262
+                            } else if($key === 'objectguid' || $key === 'guid') {
1263
+                                $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1264
+                            } else {
1265
+                                $selection[$i][$key] = $item[$key];
1266
+                            }
1267
+                        } else {
1268
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1269
+                        }
1270
+                    }
1271
+
1272
+                }
1273
+                $i++;
1274
+            }
1275
+            $findings = $selection;
1276
+        }
1277
+        //we slice the findings, when
1278
+        //a) paged search unsuccessful, though attempted
1279
+        //b) no paged search, but limit set
1280
+        if((!$this->getPagedSearchResultState()
1281
+            && $pagedSearchOK)
1282
+            || (
1283
+                !$pagedSearchOK
1284
+                && !is_null($limit)
1285
+            )
1286
+        ) {
1287
+            $findings = array_slice($findings, intval($offset), $limit);
1288
+        }
1289
+        return $findings;
1290
+    }
1291
+
1292
+    /**
1293
+     * @param string $name
1294
+     * @return bool|mixed|string
1295
+     */
1296
+    public function sanitizeUsername($name) {
1297
+        if($this->connection->ldapIgnoreNamingRules) {
1298
+            return trim($name);
1299
+        }
1300
+
1301
+        // Transliteration
1302
+        // latin characters to ASCII
1303
+        $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1304
+
1305
+        // Replacements
1306
+        $name = str_replace(' ', '_', $name);
1307
+
1308
+        // Every remaining disallowed characters will be removed
1309
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1310
+
1311
+        return $name;
1312
+    }
1313
+
1314
+    /**
1315
+     * escapes (user provided) parts for LDAP filter
1316
+     * @param string $input, the provided value
1317
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1318
+     * @return string the escaped string
1319
+     */
1320
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1321
+        $asterisk = '';
1322
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1323
+            $asterisk = '*';
1324
+            $input = mb_substr($input, 1, null, 'UTF-8');
1325
+        }
1326
+        $search  = array('*', '\\', '(', ')');
1327
+        $replace = array('\\*', '\\\\', '\\(', '\\)');
1328
+        return $asterisk . str_replace($search, $replace, $input);
1329
+    }
1330
+
1331
+    /**
1332
+     * combines the input filters with AND
1333
+     * @param string[] $filters the filters to connect
1334
+     * @return string the combined filter
1335
+     */
1336
+    public function combineFilterWithAnd($filters) {
1337
+        return $this->combineFilter($filters, '&');
1338
+    }
1339
+
1340
+    /**
1341
+     * combines the input filters with OR
1342
+     * @param string[] $filters the filters to connect
1343
+     * @return string the combined filter
1344
+     * Combines Filter arguments with OR
1345
+     */
1346
+    public function combineFilterWithOr($filters) {
1347
+        return $this->combineFilter($filters, '|');
1348
+    }
1349
+
1350
+    /**
1351
+     * combines the input filters with given operator
1352
+     * @param string[] $filters the filters to connect
1353
+     * @param string $operator either & or |
1354
+     * @return string the combined filter
1355
+     */
1356
+    private function combineFilter($filters, $operator) {
1357
+        $combinedFilter = '('.$operator;
1358
+        foreach($filters as $filter) {
1359
+            if ($filter !== '' && $filter[0] !== '(') {
1360
+                $filter = '('.$filter.')';
1361
+            }
1362
+            $combinedFilter.=$filter;
1363
+        }
1364
+        $combinedFilter.=')';
1365
+        return $combinedFilter;
1366
+    }
1367
+
1368
+    /**
1369
+     * creates a filter part for to perform search for users
1370
+     * @param string $search the search term
1371
+     * @return string the final filter part to use in LDAP searches
1372
+     */
1373
+    public function getFilterPartForUserSearch($search) {
1374
+        return $this->getFilterPartForSearch($search,
1375
+            $this->connection->ldapAttributesForUserSearch,
1376
+            $this->connection->ldapUserDisplayName);
1377
+    }
1378
+
1379
+    /**
1380
+     * creates a filter part for to perform search for groups
1381
+     * @param string $search the search term
1382
+     * @return string the final filter part to use in LDAP searches
1383
+     */
1384
+    public function getFilterPartForGroupSearch($search) {
1385
+        return $this->getFilterPartForSearch($search,
1386
+            $this->connection->ldapAttributesForGroupSearch,
1387
+            $this->connection->ldapGroupDisplayName);
1388
+    }
1389
+
1390
+    /**
1391
+     * creates a filter part for searches by splitting up the given search
1392
+     * string into single words
1393
+     * @param string $search the search term
1394
+     * @param string[] $searchAttributes needs to have at least two attributes,
1395
+     * otherwise it does not make sense :)
1396
+     * @return string the final filter part to use in LDAP searches
1397
+     * @throws \Exception
1398
+     */
1399
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1400
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1401
+            throw new \Exception('searchAttributes must be an array with at least two string');
1402
+        }
1403
+        $searchWords = explode(' ', trim($search));
1404
+        $wordFilters = array();
1405
+        foreach($searchWords as $word) {
1406
+            $word = $this->prepareSearchTerm($word);
1407
+            //every word needs to appear at least once
1408
+            $wordMatchOneAttrFilters = array();
1409
+            foreach($searchAttributes as $attr) {
1410
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1411
+            }
1412
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1413
+        }
1414
+        return $this->combineFilterWithAnd($wordFilters);
1415
+    }
1416
+
1417
+    /**
1418
+     * creates a filter part for searches
1419
+     * @param string $search the search term
1420
+     * @param string[]|null $searchAttributes
1421
+     * @param string $fallbackAttribute a fallback attribute in case the user
1422
+     * did not define search attributes. Typically the display name attribute.
1423
+     * @return string the final filter part to use in LDAP searches
1424
+     */
1425
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1426
+        $filter = array();
1427
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1428
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1429
+            try {
1430
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1431
+            } catch(\Exception $e) {
1432
+                \OCP\Util::writeLog(
1433
+                    'user_ldap',
1434
+                    'Creating advanced filter for search failed, falling back to simple method.',
1435
+                    \OCP\Util::INFO
1436
+                );
1437
+            }
1438
+        }
1439
+
1440
+        $search = $this->prepareSearchTerm($search);
1441
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1442
+            if ($fallbackAttribute === '') {
1443
+                return '';
1444
+            }
1445
+            $filter[] = $fallbackAttribute . '=' . $search;
1446
+        } else {
1447
+            foreach($searchAttributes as $attribute) {
1448
+                $filter[] = $attribute . '=' . $search;
1449
+            }
1450
+        }
1451
+        if(count($filter) === 1) {
1452
+            return '('.$filter[0].')';
1453
+        }
1454
+        return $this->combineFilterWithOr($filter);
1455
+    }
1456
+
1457
+    /**
1458
+     * returns the search term depending on whether we are allowed
1459
+     * list users found by ldap with the current input appended by
1460
+     * a *
1461
+     * @return string
1462
+     */
1463
+    private function prepareSearchTerm($term) {
1464
+        $config = \OC::$server->getConfig();
1465
+
1466
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1467
+
1468
+        $result = $term;
1469
+        if ($term === '') {
1470
+            $result = '*';
1471
+        } else if ($allowEnum !== 'no') {
1472
+            $result = $term . '*';
1473
+        }
1474
+        return $result;
1475
+    }
1476
+
1477
+    /**
1478
+     * returns the filter used for counting users
1479
+     * @return string
1480
+     */
1481
+    public function getFilterForUserCount() {
1482
+        $filter = $this->combineFilterWithAnd(array(
1483
+            $this->connection->ldapUserFilter,
1484
+            $this->connection->ldapUserDisplayName . '=*'
1485
+        ));
1486
+
1487
+        return $filter;
1488
+    }
1489
+
1490
+    /**
1491
+     * @param string $name
1492
+     * @param string $password
1493
+     * @return bool
1494
+     */
1495
+    public function areCredentialsValid($name, $password) {
1496
+        $name = $this->helper->DNasBaseParameter($name);
1497
+        $testConnection = clone $this->connection;
1498
+        $credentials = array(
1499
+            'ldapAgentName' => $name,
1500
+            'ldapAgentPassword' => $password
1501
+        );
1502
+        if(!$testConnection->setConfiguration($credentials)) {
1503
+            return false;
1504
+        }
1505
+        return $testConnection->bind();
1506
+    }
1507
+
1508
+    /**
1509
+     * reverse lookup of a DN given a known UUID
1510
+     *
1511
+     * @param string $uuid
1512
+     * @return string
1513
+     * @throws \Exception
1514
+     */
1515
+    public function getUserDnByUuid($uuid) {
1516
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1517
+        $filter       = $this->connection->ldapUserFilter;
1518
+        $base         = $this->connection->ldapBaseUsers;
1519
+
1520
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1521
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1522
+            // existing DN to be able to reliably detect it.
1523
+            $result = $this->search($filter, $base, ['dn'], 1);
1524
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1525
+                throw new \Exception('Cannot determine UUID attribute');
1526
+            }
1527
+            $dn = $result[0]['dn'][0];
1528
+            if(!$this->detectUuidAttribute($dn, true)) {
1529
+                throw new \Exception('Cannot determine UUID attribute');
1530
+            }
1531
+        } else {
1532
+            // The UUID attribute is either known or an override is given.
1533
+            // By calling this method we ensure that $this->connection->$uuidAttr
1534
+            // is definitely set
1535
+            if(!$this->detectUuidAttribute('', true)) {
1536
+                throw new \Exception('Cannot determine UUID attribute');
1537
+            }
1538
+        }
1539
+
1540
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1541
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1542
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1543
+        }
1544
+
1545
+        $filter = $uuidAttr . '=' . $uuid;
1546
+        $result = $this->searchUsers($filter, ['dn'], 2);
1547
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1548
+            // we put the count into account to make sure that this is
1549
+            // really unique
1550
+            return $result[0]['dn'][0];
1551
+        }
1552
+
1553
+        throw new \Exception('Cannot determine UUID attribute');
1554
+    }
1555
+
1556
+    /**
1557
+     * auto-detects the directory's UUID attribute
1558
+     *
1559
+     * @param string $dn a known DN used to check against
1560
+     * @param bool $isUser
1561
+     * @param bool $force the detection should be run, even if it is not set to auto
1562
+     * @param array|null $ldapRecord
1563
+     * @return bool true on success, false otherwise
1564
+     */
1565
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1566
+        if($isUser) {
1567
+            $uuidAttr     = 'ldapUuidUserAttribute';
1568
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1569
+        } else {
1570
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1571
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1572
+        }
1573
+
1574
+        if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1575
+            return true;
1576
+        }
1577
+
1578
+        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1579
+            $this->connection->$uuidAttr = $uuidOverride;
1580
+            return true;
1581
+        }
1582
+
1583
+        foreach(self::UUID_ATTRIBUTES as $attribute) {
1584
+            if($ldapRecord !== null) {
1585
+                // we have the info from LDAP already, we don't need to talk to the server again
1586
+                if(isset($ldapRecord[$attribute])) {
1587
+                    $this->connection->$uuidAttr = $attribute;
1588
+                    return true;
1589
+                } else {
1590
+                    continue;
1591
+                }
1592
+            }
1593
+
1594
+            $value = $this->readAttribute($dn, $attribute);
1595
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1596
+                \OCP\Util::writeLog('user_ldap',
1597
+                                    'Setting '.$attribute.' as '.$uuidAttr,
1598
+                                    \OCP\Util::DEBUG);
1599
+                $this->connection->$uuidAttr = $attribute;
1600
+                return true;
1601
+            }
1602
+        }
1603
+        \OCP\Util::writeLog('user_ldap',
1604
+                            'Could not autodetect the UUID attribute',
1605
+                            \OCP\Util::ERROR);
1606
+
1607
+        return false;
1608
+    }
1609
+
1610
+    /**
1611
+     * @param string $dn
1612
+     * @param bool $isUser
1613
+     * @param null $ldapRecord
1614
+     * @return bool|string
1615
+     */
1616
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1617
+        if($isUser) {
1618
+            $uuidAttr     = 'ldapUuidUserAttribute';
1619
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1620
+        } else {
1621
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1622
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1623
+        }
1624
+
1625
+        $uuid = false;
1626
+        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1627
+            $attr = $this->connection->$uuidAttr;
1628
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1629
+            if( !is_array($uuid)
1630
+                && $uuidOverride !== ''
1631
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1632
+            {
1633
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1634
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1635
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1636
+            }
1637
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1638
+                $uuid = $uuid[0];
1639
+            }
1640
+        }
1641
+
1642
+        return $uuid;
1643
+    }
1644
+
1645
+    /**
1646
+     * converts a binary ObjectGUID into a string representation
1647
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1648
+     * @return string
1649
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1650
+     */
1651
+    private function convertObjectGUID2Str($oguid) {
1652
+        $hex_guid = bin2hex($oguid);
1653
+        $hex_guid_to_guid_str = '';
1654
+        for($k = 1; $k <= 4; ++$k) {
1655
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1656
+        }
1657
+        $hex_guid_to_guid_str .= '-';
1658
+        for($k = 1; $k <= 2; ++$k) {
1659
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1660
+        }
1661
+        $hex_guid_to_guid_str .= '-';
1662
+        for($k = 1; $k <= 2; ++$k) {
1663
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1664
+        }
1665
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1666
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1667
+
1668
+        return strtoupper($hex_guid_to_guid_str);
1669
+    }
1670
+
1671
+    /**
1672
+     * the first three blocks of the string-converted GUID happen to be in
1673
+     * reverse order. In order to use it in a filter, this needs to be
1674
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1675
+     * to every two hax figures.
1676
+     *
1677
+     * If an invalid string is passed, it will be returned without change.
1678
+     *
1679
+     * @param string $guid
1680
+     * @return string
1681
+     */
1682
+    public function formatGuid2ForFilterUser($guid) {
1683
+        if(!is_string($guid)) {
1684
+            throw new \InvalidArgumentException('String expected');
1685
+        }
1686
+        $blocks = explode('-', $guid);
1687
+        if(count($blocks) !== 5) {
1688
+            /*
1689 1689
 			 * Why not throw an Exception instead? This method is a utility
1690 1690
 			 * called only when trying to figure out whether a "missing" known
1691 1691
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1696,270 +1696,270 @@  discard block
 block discarded – undo
1696 1696
 			 * an exception here would kill the experience for a valid, acting
1697 1697
 			 * user. Instead we write a log message.
1698 1698
 			 */
1699
-			\OC::$server->getLogger()->info(
1700
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1701
-				'({uuid}) probably does not match UUID configuration.',
1702
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1703
-			);
1704
-			return $guid;
1705
-		}
1706
-		for($i=0; $i < 3; $i++) {
1707
-			$pairs = str_split($blocks[$i], 2);
1708
-			$pairs = array_reverse($pairs);
1709
-			$blocks[$i] = implode('', $pairs);
1710
-		}
1711
-		for($i=0; $i < 5; $i++) {
1712
-			$pairs = str_split($blocks[$i], 2);
1713
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1714
-		}
1715
-		return implode('', $blocks);
1716
-	}
1717
-
1718
-	/**
1719
-	 * gets a SID of the domain of the given dn
1720
-	 * @param string $dn
1721
-	 * @return string|bool
1722
-	 */
1723
-	public function getSID($dn) {
1724
-		$domainDN = $this->getDomainDNFromDN($dn);
1725
-		$cacheKey = 'getSID-'.$domainDN;
1726
-		$sid = $this->connection->getFromCache($cacheKey);
1727
-		if(!is_null($sid)) {
1728
-			return $sid;
1729
-		}
1730
-
1731
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1732
-		if(!is_array($objectSid) || empty($objectSid)) {
1733
-			$this->connection->writeToCache($cacheKey, false);
1734
-			return false;
1735
-		}
1736
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1737
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1738
-
1739
-		return $domainObjectSid;
1740
-	}
1741
-
1742
-	/**
1743
-	 * converts a binary SID into a string representation
1744
-	 * @param string $sid
1745
-	 * @return string
1746
-	 */
1747
-	public function convertSID2Str($sid) {
1748
-		// The format of a SID binary string is as follows:
1749
-		// 1 byte for the revision level
1750
-		// 1 byte for the number n of variable sub-ids
1751
-		// 6 bytes for identifier authority value
1752
-		// n*4 bytes for n sub-ids
1753
-		//
1754
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1755
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1756
-		$revision = ord($sid[0]);
1757
-		$numberSubID = ord($sid[1]);
1758
-
1759
-		$subIdStart = 8; // 1 + 1 + 6
1760
-		$subIdLength = 4;
1761
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1762
-			// Incorrect number of bytes present.
1763
-			return '';
1764
-		}
1765
-
1766
-		// 6 bytes = 48 bits can be represented using floats without loss of
1767
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1768
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1769
-
1770
-		$subIDs = array();
1771
-		for ($i = 0; $i < $numberSubID; $i++) {
1772
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1773
-			$subIDs[] = sprintf('%u', $subID[1]);
1774
-		}
1775
-
1776
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1777
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1778
-	}
1779
-
1780
-	/**
1781
-	 * checks if the given DN is part of the given base DN(s)
1782
-	 * @param string $dn the DN
1783
-	 * @param string[] $bases array containing the allowed base DN or DNs
1784
-	 * @return bool
1785
-	 */
1786
-	public function isDNPartOfBase($dn, $bases) {
1787
-		$belongsToBase = false;
1788
-		$bases = $this->helper->sanitizeDN($bases);
1789
-
1790
-		foreach($bases as $base) {
1791
-			$belongsToBase = true;
1792
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1793
-				$belongsToBase = false;
1794
-			}
1795
-			if($belongsToBase) {
1796
-				break;
1797
-			}
1798
-		}
1799
-		return $belongsToBase;
1800
-	}
1801
-
1802
-	/**
1803
-	 * resets a running Paged Search operation
1804
-	 */
1805
-	private function abandonPagedSearch() {
1806
-		if($this->connection->hasPagedResultSupport) {
1807
-			$cr = $this->connection->getConnectionResource();
1808
-			$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1809
-			$this->getPagedSearchResultState();
1810
-			$this->lastCookie = '';
1811
-			$this->cookies = array();
1812
-		}
1813
-	}
1814
-
1815
-	/**
1816
-	 * get a cookie for the next LDAP paged search
1817
-	 * @param string $base a string with the base DN for the search
1818
-	 * @param string $filter the search filter to identify the correct search
1819
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1820
-	 * @param int $offset the offset for the new search to identify the correct search really good
1821
-	 * @return string containing the key or empty if none is cached
1822
-	 */
1823
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1824
-		if($offset === 0) {
1825
-			return '';
1826
-		}
1827
-		$offset -= $limit;
1828
-		//we work with cache here
1829
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1830
-		$cookie = '';
1831
-		if(isset($this->cookies[$cacheKey])) {
1832
-			$cookie = $this->cookies[$cacheKey];
1833
-			if(is_null($cookie)) {
1834
-				$cookie = '';
1835
-			}
1836
-		}
1837
-		return $cookie;
1838
-	}
1839
-
1840
-	/**
1841
-	 * checks whether an LDAP paged search operation has more pages that can be
1842
-	 * retrieved, typically when offset and limit are provided.
1843
-	 *
1844
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1845
-	 * be reset by other operations. Best, call it immediately after a search(),
1846
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1847
-	 * well. Don't rely on it with any fetchList-method.
1848
-	 * @return bool
1849
-	 */
1850
-	public function hasMoreResults() {
1851
-		if(!$this->connection->hasPagedResultSupport) {
1852
-			return false;
1853
-		}
1854
-
1855
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1856
-			// as in RFC 2696, when all results are returned, the cookie will
1857
-			// be empty.
1858
-			return false;
1859
-		}
1860
-
1861
-		return true;
1862
-	}
1863
-
1864
-	/**
1865
-	 * set a cookie for LDAP paged search run
1866
-	 * @param string $base a string with the base DN for the search
1867
-	 * @param string $filter the search filter to identify the correct search
1868
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1869
-	 * @param int $offset the offset for the run search to identify the correct search really good
1870
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1871
-	 * @return void
1872
-	 */
1873
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1874
-		// allow '0' for 389ds
1875
-		if(!empty($cookie) || $cookie === '0') {
1876
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1877
-			$this->cookies[$cacheKey] = $cookie;
1878
-			$this->lastCookie = $cookie;
1879
-		}
1880
-	}
1881
-
1882
-	/**
1883
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1884
-	 * @return boolean|null true on success, null or false otherwise
1885
-	 */
1886
-	public function getPagedSearchResultState() {
1887
-		$result = $this->pagedSearchedSuccessful;
1888
-		$this->pagedSearchedSuccessful = null;
1889
-		return $result;
1890
-	}
1891
-
1892
-	/**
1893
-	 * Prepares a paged search, if possible
1894
-	 * @param string $filter the LDAP filter for the search
1895
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1896
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
1897
-	 * @param int $limit
1898
-	 * @param int $offset
1899
-	 * @return bool|true
1900
-	 */
1901
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1902
-		$pagedSearchOK = false;
1903
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1904
-			$offset = intval($offset); //can be null
1905
-			\OCP\Util::writeLog('user_ldap',
1906
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1907
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1908
-				\OCP\Util::DEBUG);
1909
-			//get the cookie from the search for the previous search, required by LDAP
1910
-			foreach($bases as $base) {
1911
-
1912
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1913
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1914
-					// no cookie known from a potential previous search. We need
1915
-					// to start from 0 to come to the desired page. cookie value
1916
-					// of '0' is valid, because 389ds
1917
-					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1918
-					$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1919
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1920
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1921
-					// '0' is valid, because 389ds
1922
-					//TODO: remember this, probably does not change in the next request...
1923
-					if(empty($cookie) && $cookie !== '0') {
1924
-						$cookie = null;
1925
-					}
1926
-				}
1927
-				if(!is_null($cookie)) {
1928
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1929
-					$this->abandonPagedSearch();
1930
-					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1931
-						$this->connection->getConnectionResource(), $limit,
1932
-						false, $cookie);
1933
-					if(!$pagedSearchOK) {
1934
-						return false;
1935
-					}
1936
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1937
-				} else {
1938
-					$e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
1939
-					\OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG]);
1940
-				}
1941
-
1942
-			}
1943
-		/* ++ Fixing RHDS searches with pages with zero results ++
1699
+            \OC::$server->getLogger()->info(
1700
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1701
+                '({uuid}) probably does not match UUID configuration.',
1702
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1703
+            );
1704
+            return $guid;
1705
+        }
1706
+        for($i=0; $i < 3; $i++) {
1707
+            $pairs = str_split($blocks[$i], 2);
1708
+            $pairs = array_reverse($pairs);
1709
+            $blocks[$i] = implode('', $pairs);
1710
+        }
1711
+        for($i=0; $i < 5; $i++) {
1712
+            $pairs = str_split($blocks[$i], 2);
1713
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1714
+        }
1715
+        return implode('', $blocks);
1716
+    }
1717
+
1718
+    /**
1719
+     * gets a SID of the domain of the given dn
1720
+     * @param string $dn
1721
+     * @return string|bool
1722
+     */
1723
+    public function getSID($dn) {
1724
+        $domainDN = $this->getDomainDNFromDN($dn);
1725
+        $cacheKey = 'getSID-'.$domainDN;
1726
+        $sid = $this->connection->getFromCache($cacheKey);
1727
+        if(!is_null($sid)) {
1728
+            return $sid;
1729
+        }
1730
+
1731
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1732
+        if(!is_array($objectSid) || empty($objectSid)) {
1733
+            $this->connection->writeToCache($cacheKey, false);
1734
+            return false;
1735
+        }
1736
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1737
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1738
+
1739
+        return $domainObjectSid;
1740
+    }
1741
+
1742
+    /**
1743
+     * converts a binary SID into a string representation
1744
+     * @param string $sid
1745
+     * @return string
1746
+     */
1747
+    public function convertSID2Str($sid) {
1748
+        // The format of a SID binary string is as follows:
1749
+        // 1 byte for the revision level
1750
+        // 1 byte for the number n of variable sub-ids
1751
+        // 6 bytes for identifier authority value
1752
+        // n*4 bytes for n sub-ids
1753
+        //
1754
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1755
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1756
+        $revision = ord($sid[0]);
1757
+        $numberSubID = ord($sid[1]);
1758
+
1759
+        $subIdStart = 8; // 1 + 1 + 6
1760
+        $subIdLength = 4;
1761
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1762
+            // Incorrect number of bytes present.
1763
+            return '';
1764
+        }
1765
+
1766
+        // 6 bytes = 48 bits can be represented using floats without loss of
1767
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1768
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1769
+
1770
+        $subIDs = array();
1771
+        for ($i = 0; $i < $numberSubID; $i++) {
1772
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1773
+            $subIDs[] = sprintf('%u', $subID[1]);
1774
+        }
1775
+
1776
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1777
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1778
+    }
1779
+
1780
+    /**
1781
+     * checks if the given DN is part of the given base DN(s)
1782
+     * @param string $dn the DN
1783
+     * @param string[] $bases array containing the allowed base DN or DNs
1784
+     * @return bool
1785
+     */
1786
+    public function isDNPartOfBase($dn, $bases) {
1787
+        $belongsToBase = false;
1788
+        $bases = $this->helper->sanitizeDN($bases);
1789
+
1790
+        foreach($bases as $base) {
1791
+            $belongsToBase = true;
1792
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1793
+                $belongsToBase = false;
1794
+            }
1795
+            if($belongsToBase) {
1796
+                break;
1797
+            }
1798
+        }
1799
+        return $belongsToBase;
1800
+    }
1801
+
1802
+    /**
1803
+     * resets a running Paged Search operation
1804
+     */
1805
+    private function abandonPagedSearch() {
1806
+        if($this->connection->hasPagedResultSupport) {
1807
+            $cr = $this->connection->getConnectionResource();
1808
+            $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1809
+            $this->getPagedSearchResultState();
1810
+            $this->lastCookie = '';
1811
+            $this->cookies = array();
1812
+        }
1813
+    }
1814
+
1815
+    /**
1816
+     * get a cookie for the next LDAP paged search
1817
+     * @param string $base a string with the base DN for the search
1818
+     * @param string $filter the search filter to identify the correct search
1819
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1820
+     * @param int $offset the offset for the new search to identify the correct search really good
1821
+     * @return string containing the key or empty if none is cached
1822
+     */
1823
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1824
+        if($offset === 0) {
1825
+            return '';
1826
+        }
1827
+        $offset -= $limit;
1828
+        //we work with cache here
1829
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1830
+        $cookie = '';
1831
+        if(isset($this->cookies[$cacheKey])) {
1832
+            $cookie = $this->cookies[$cacheKey];
1833
+            if(is_null($cookie)) {
1834
+                $cookie = '';
1835
+            }
1836
+        }
1837
+        return $cookie;
1838
+    }
1839
+
1840
+    /**
1841
+     * checks whether an LDAP paged search operation has more pages that can be
1842
+     * retrieved, typically when offset and limit are provided.
1843
+     *
1844
+     * Be very careful to use it: the last cookie value, which is inspected, can
1845
+     * be reset by other operations. Best, call it immediately after a search(),
1846
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1847
+     * well. Don't rely on it with any fetchList-method.
1848
+     * @return bool
1849
+     */
1850
+    public function hasMoreResults() {
1851
+        if(!$this->connection->hasPagedResultSupport) {
1852
+            return false;
1853
+        }
1854
+
1855
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1856
+            // as in RFC 2696, when all results are returned, the cookie will
1857
+            // be empty.
1858
+            return false;
1859
+        }
1860
+
1861
+        return true;
1862
+    }
1863
+
1864
+    /**
1865
+     * set a cookie for LDAP paged search run
1866
+     * @param string $base a string with the base DN for the search
1867
+     * @param string $filter the search filter to identify the correct search
1868
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1869
+     * @param int $offset the offset for the run search to identify the correct search really good
1870
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1871
+     * @return void
1872
+     */
1873
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1874
+        // allow '0' for 389ds
1875
+        if(!empty($cookie) || $cookie === '0') {
1876
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1877
+            $this->cookies[$cacheKey] = $cookie;
1878
+            $this->lastCookie = $cookie;
1879
+        }
1880
+    }
1881
+
1882
+    /**
1883
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1884
+     * @return boolean|null true on success, null or false otherwise
1885
+     */
1886
+    public function getPagedSearchResultState() {
1887
+        $result = $this->pagedSearchedSuccessful;
1888
+        $this->pagedSearchedSuccessful = null;
1889
+        return $result;
1890
+    }
1891
+
1892
+    /**
1893
+     * Prepares a paged search, if possible
1894
+     * @param string $filter the LDAP filter for the search
1895
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1896
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
1897
+     * @param int $limit
1898
+     * @param int $offset
1899
+     * @return bool|true
1900
+     */
1901
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1902
+        $pagedSearchOK = false;
1903
+        if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1904
+            $offset = intval($offset); //can be null
1905
+            \OCP\Util::writeLog('user_ldap',
1906
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1907
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1908
+                \OCP\Util::DEBUG);
1909
+            //get the cookie from the search for the previous search, required by LDAP
1910
+            foreach($bases as $base) {
1911
+
1912
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1913
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1914
+                    // no cookie known from a potential previous search. We need
1915
+                    // to start from 0 to come to the desired page. cookie value
1916
+                    // of '0' is valid, because 389ds
1917
+                    $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1918
+                    $this->search($filter, array($base), $attr, $limit, $reOffset, true);
1919
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1920
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1921
+                    // '0' is valid, because 389ds
1922
+                    //TODO: remember this, probably does not change in the next request...
1923
+                    if(empty($cookie) && $cookie !== '0') {
1924
+                        $cookie = null;
1925
+                    }
1926
+                }
1927
+                if(!is_null($cookie)) {
1928
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1929
+                    $this->abandonPagedSearch();
1930
+                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1931
+                        $this->connection->getConnectionResource(), $limit,
1932
+                        false, $cookie);
1933
+                    if(!$pagedSearchOK) {
1934
+                        return false;
1935
+                    }
1936
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1937
+                } else {
1938
+                    $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
1939
+                    \OC::$server->getLogger()->logException($e, ['level' => Util::DEBUG]);
1940
+                }
1941
+
1942
+            }
1943
+        /* ++ Fixing RHDS searches with pages with zero results ++
1944 1944
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
1945 1945
 		 * due to pages with zero results.
1946 1946
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1947 1947
 		 * if we don't have a previous paged search.
1948 1948
 		 */
1949
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1950
-			// a search without limit was requested. However, if we do use
1951
-			// Paged Search once, we always must do it. This requires us to
1952
-			// initialize it with the configured page size.
1953
-			$this->abandonPagedSearch();
1954
-			// in case someone set it to 0 … use 500, otherwise no results will
1955
-			// be returned.
1956
-			$pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1957
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1958
-				$this->connection->getConnectionResource(),
1959
-				$pageSize, false, '');
1960
-		}
1961
-
1962
-		return $pagedSearchOK;
1963
-	}
1949
+        } else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1950
+            // a search without limit was requested. However, if we do use
1951
+            // Paged Search once, we always must do it. This requires us to
1952
+            // initialize it with the configured page size.
1953
+            $this->abandonPagedSearch();
1954
+            // in case someone set it to 0 … use 500, otherwise no results will
1955
+            // be returned.
1956
+            $pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1957
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1958
+                $this->connection->getConnectionResource(),
1959
+                $pageSize, false, '');
1960
+        }
1961
+
1962
+        return $pagedSearchOK;
1963
+    }
1964 1964
 
1965 1965
 }
Please login to merge, or discard this patch.
Spacing   +171 added lines, -171 removed lines patch added patch discarded remove patch
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 	 * @return AbstractMapping
126 126
 	 */
127 127
 	public function getUserMapper() {
128
-		if(is_null($this->userMapper)) {
128
+		if (is_null($this->userMapper)) {
129 129
 			throw new \Exception('UserMapper was not assigned to this Access instance.');
130 130
 		}
131 131
 		return $this->userMapper;
@@ -145,7 +145,7 @@  discard block
 block discarded – undo
145 145
 	 * @return AbstractMapping
146 146
 	 */
147 147
 	public function getGroupMapper() {
148
-		if(is_null($this->groupMapper)) {
148
+		if (is_null($this->groupMapper)) {
149 149
 			throw new \Exception('GroupMapper was not assigned to this Access instance.');
150 150
 		}
151 151
 		return $this->groupMapper;
@@ -176,14 +176,14 @@  discard block
 block discarded – undo
176 176
 	 *          array if $attr is empty, false otherwise
177 177
 	 */
178 178
 	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
179
-		if(!$this->checkConnection()) {
179
+		if (!$this->checkConnection()) {
180 180
 			\OCP\Util::writeLog('user_ldap',
181 181
 				'No LDAP Connector assigned, access impossible for readAttribute.',
182 182
 				\OCP\Util::WARN);
183 183
 			return false;
184 184
 		}
185 185
 		$cr = $this->connection->getConnectionResource();
186
-		if(!$this->ldap->isResource($cr)) {
186
+		if (!$this->ldap->isResource($cr)) {
187 187
 			//LDAP not available
188 188
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
189 189
 			return false;
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 		$isRangeRequest = false;
207 207
 		do {
208 208
 			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
209
-			if(is_bool($result)) {
209
+			if (is_bool($result)) {
210 210
 				// when an exists request was run and it was successful, an empty
211 211
 				// array must be returned
212 212
 				return $result ? [] : false;
@@ -223,22 +223,22 @@  discard block
 block discarded – undo
223 223
 			$result = $this->extractRangeData($result, $attr);
224 224
 			if (!empty($result)) {
225 225
 				$normalizedResult = $this->extractAttributeValuesFromResult(
226
-					[ $attr => $result['values'] ],
226
+					[$attr => $result['values']],
227 227
 					$attr
228 228
 				);
229 229
 				$values = array_merge($values, $normalizedResult);
230 230
 
231
-				if($result['rangeHigh'] === '*') {
231
+				if ($result['rangeHigh'] === '*') {
232 232
 					// when server replies with * as high range value, there are
233 233
 					// no more results left
234 234
 					return $values;
235 235
 				} else {
236
-					$low  = $result['rangeHigh'] + 1;
237
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
236
+					$low = $result['rangeHigh'] + 1;
237
+					$attrToRead = $result['attributeName'].';range='.$low.'-*';
238 238
 					$isRangeRequest = true;
239 239
 				}
240 240
 			}
241
-		} while($isRangeRequest);
241
+		} while ($isRangeRequest);
242 242
 
243 243
 		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
244 244
 		return false;
@@ -263,13 +263,13 @@  discard block
 block discarded – undo
263 263
 		if (!$this->ldap->isResource($rr)) {
264 264
 			if ($attribute !== '') {
265 265
 				//do not throw this message on userExists check, irritates
266
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
266
+				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, \OCP\Util::DEBUG);
267 267
 			}
268 268
 			//in case an error occurs , e.g. object does not exist
269 269
 			return false;
270 270
 		}
271 271
 		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
272
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
272
+			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', \OCP\Util::DEBUG);
273 273
 			return true;
274 274
 		}
275 275
 		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
@@ -294,12 +294,12 @@  discard block
 block discarded – undo
294 294
 	 */
295 295
 	public function extractAttributeValuesFromResult($result, $attribute) {
296 296
 		$values = [];
297
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
297
+		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
298 298
 			$lowercaseAttribute = strtolower($attribute);
299
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
300
-				if($this->resemblesDN($attribute)) {
299
+			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
300
+				if ($this->resemblesDN($attribute)) {
301 301
 					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
302
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
302
+				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
303 303
 					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
304 304
 				} else {
305 305
 					$values[] = $result[$attribute][$i];
@@ -321,10 +321,10 @@  discard block
 block discarded – undo
321 321
 	 */
322 322
 	public function extractRangeData($result, $attribute) {
323 323
 		$keys = array_keys($result);
324
-		foreach($keys as $key) {
325
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
324
+		foreach ($keys as $key) {
325
+			if ($key !== $attribute && strpos($key, $attribute) === 0) {
326 326
 				$queryData = explode(';', $key);
327
-				if(strpos($queryData[1], 'range=') === 0) {
327
+				if (strpos($queryData[1], 'range=') === 0) {
328 328
 					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
329 329
 					$data = [
330 330
 						'values' => $result[$key],
@@ -349,18 +349,18 @@  discard block
 block discarded – undo
349 349
 	 * @throws \Exception
350 350
 	 */
351 351
 	public function setPassword($userDN, $password) {
352
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
352
+		if (intval($this->connection->turnOnPasswordChange) !== 1) {
353 353
 			throw new \Exception('LDAP password changes are disabled.');
354 354
 		}
355 355
 		$cr = $this->connection->getConnectionResource();
356
-		if(!$this->ldap->isResource($cr)) {
356
+		if (!$this->ldap->isResource($cr)) {
357 357
 			//LDAP not available
358 358
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
359 359
 			return false;
360 360
 		}
361 361
 		try {
362 362
 			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
363
-		} catch(ConstraintViolationException $e) {
363
+		} catch (ConstraintViolationException $e) {
364 364
 			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
365 365
 		}
366 366
 	}
@@ -402,17 +402,17 @@  discard block
 block discarded – undo
402 402
 	 */
403 403
 	public function getDomainDNFromDN($dn) {
404 404
 		$allParts = $this->ldap->explodeDN($dn, 0);
405
-		if($allParts === false) {
405
+		if ($allParts === false) {
406 406
 			//not a valid DN
407 407
 			return '';
408 408
 		}
409 409
 		$domainParts = array();
410 410
 		$dcFound = false;
411
-		foreach($allParts as $part) {
412
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
411
+		foreach ($allParts as $part) {
412
+			if (!$dcFound && strpos($part, 'dc=') === 0) {
413 413
 				$dcFound = true;
414 414
 			}
415
-			if($dcFound) {
415
+			if ($dcFound) {
416 416
 				$domainParts[] = $part;
417 417
 			}
418 418
 		}
@@ -439,7 +439,7 @@  discard block
 block discarded – undo
439 439
 
440 440
 		//Check whether the DN belongs to the Base, to avoid issues on multi-
441 441
 		//server setups
442
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
442
+		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
443 443
 			return $fdn;
444 444
 		}
445 445
 
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
 		//To avoid bypassing the base DN settings under certain circumstances
457 457
 		//with the group support, check whether the provided DN matches one of
458 458
 		//the given Bases
459
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
459
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
460 460
 			return false;
461 461
 		}
462 462
 
@@ -473,11 +473,11 @@  discard block
 block discarded – undo
473 473
 	 */
474 474
 	public function groupsMatchFilter($groupDNs) {
475 475
 		$validGroupDNs = [];
476
-		foreach($groupDNs as $dn) {
476
+		foreach ($groupDNs as $dn) {
477 477
 			$cacheKey = 'groupsMatchFilter-'.$dn;
478 478
 			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
479
-			if(!is_null($groupMatchFilter)) {
480
-				if($groupMatchFilter) {
479
+			if (!is_null($groupMatchFilter)) {
480
+				if ($groupMatchFilter) {
481 481
 					$validGroupDNs[] = $dn;
482 482
 				}
483 483
 				continue;
@@ -485,13 +485,13 @@  discard block
 block discarded – undo
485 485
 
486 486
 			// Check the base DN first. If this is not met already, we don't
487 487
 			// need to ask the server at all.
488
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
488
+			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
489 489
 				$this->connection->writeToCache($cacheKey, false);
490 490
 				continue;
491 491
 			}
492 492
 
493 493
 			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
494
-			if(is_array($result)) {
494
+			if (is_array($result)) {
495 495
 				$this->connection->writeToCache($cacheKey, true);
496 496
 				$validGroupDNs[] = $dn;
497 497
 			} else {
@@ -512,7 +512,7 @@  discard block
 block discarded – undo
512 512
 		//To avoid bypassing the base DN settings under certain circumstances
513 513
 		//with the group support, check whether the provided DN matches one of
514 514
 		//the given Bases
515
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
515
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
516 516
 			return false;
517 517
 		}
518 518
 
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
 	 */
533 533
 	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
534 534
 		$newlyMapped = false;
535
-		if($isUser) {
535
+		if ($isUser) {
536 536
 			$mapper = $this->getUserMapper();
537 537
 			$nameAttribute = $this->connection->ldapUserDisplayName;
538 538
 		} else {
@@ -542,15 +542,15 @@  discard block
 block discarded – undo
542 542
 
543 543
 		//let's try to retrieve the Nextcloud name from the mappings table
544 544
 		$ncName = $mapper->getNameByDN($fdn);
545
-		if(is_string($ncName)) {
545
+		if (is_string($ncName)) {
546 546
 			return $ncName;
547 547
 		}
548 548
 
549 549
 		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
550 550
 		$uuid = $this->getUUID($fdn, $isUser, $record);
551
-		if(is_string($uuid)) {
551
+		if (is_string($uuid)) {
552 552
 			$ncName = $mapper->getNameByUUID($uuid);
553
-			if(is_string($ncName)) {
553
+			if (is_string($ncName)) {
554 554
 				$mapper->setDNbyUUID($fdn, $uuid);
555 555
 				return $ncName;
556 556
 			}
@@ -560,16 +560,16 @@  discard block
 block discarded – undo
560 560
 			return false;
561 561
 		}
562 562
 
563
-		if(is_null($ldapName)) {
563
+		if (is_null($ldapName)) {
564 564
 			$ldapName = $this->readAttribute($fdn, $nameAttribute);
565
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
565
+			if (!isset($ldapName[0]) && empty($ldapName[0])) {
566 566
 				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
567 567
 				return false;
568 568
 			}
569 569
 			$ldapName = $ldapName[0];
570 570
 		}
571 571
 
572
-		if($isUser) {
572
+		if ($isUser) {
573 573
 			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
574 574
 			if ($usernameAttribute !== '') {
575 575
 				$username = $this->readAttribute($fdn, $usernameAttribute);
@@ -588,9 +588,9 @@  discard block
 block discarded – undo
588 588
 		// outside of core user management will still cache the user as non-existing.
589 589
 		$originalTTL = $this->connection->ldapCacheTTL;
590 590
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
591
-		if(($isUser && $intName !== '' && !\OC::$server->getUserManager()->userExists($intName))
591
+		if (($isUser && $intName !== '' && !\OC::$server->getUserManager()->userExists($intName))
592 592
 			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
593
-			if($mapper->map($fdn, $intName, $uuid)) {
593
+			if ($mapper->map($fdn, $intName, $uuid)) {
594 594
 				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
595 595
 				$newlyMapped = true;
596 596
 				return $intName;
@@ -599,7 +599,7 @@  discard block
 block discarded – undo
599 599
 		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
600 600
 
601 601
 		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
602
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
602
+		if (is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
603 603
 			$newlyMapped = true;
604 604
 			return $altName;
605 605
 		}
@@ -637,7 +637,7 @@  discard block
 block discarded – undo
637 637
 	 * @return array
638 638
 	 */
639 639
 	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
640
-		if($isUsers) {
640
+		if ($isUsers) {
641 641
 			$nameAttribute = $this->connection->ldapUserDisplayName;
642 642
 			$sndAttribute  = $this->connection->ldapUserDisplayName2;
643 643
 		} else {
@@ -645,9 +645,9 @@  discard block
 block discarded – undo
645 645
 		}
646 646
 		$nextcloudNames = array();
647 647
 
648
-		foreach($ldapObjects as $ldapObject) {
648
+		foreach ($ldapObjects as $ldapObject) {
649 649
 			$nameByLDAP = null;
650
-			if(    isset($ldapObject[$nameAttribute])
650
+			if (isset($ldapObject[$nameAttribute])
651 651
 				&& is_array($ldapObject[$nameAttribute])
652 652
 				&& isset($ldapObject[$nameAttribute][0])
653 653
 			) {
@@ -656,12 +656,12 @@  discard block
 block discarded – undo
656 656
 			}
657 657
 
658 658
 			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
659
-			if($ncName) {
659
+			if ($ncName) {
660 660
 				$nextcloudNames[] = $ncName;
661
-				if($isUsers) {
661
+				if ($isUsers) {
662 662
 					//cache the user names so it does not need to be retrieved
663 663
 					//again later (e.g. sharing dialogue).
664
-					if(is_null($nameByLDAP)) {
664
+					if (is_null($nameByLDAP)) {
665 665
 						continue;
666 666
 					}
667 667
 					$sndName = isset($ldapObject[$sndAttribute][0])
@@ -699,7 +699,7 @@  discard block
 block discarded – undo
699 699
 	 */
700 700
 	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
701 701
 		$user = $this->userManager->get($ocName);
702
-		if($user === null) {
702
+		if ($user === null) {
703 703
 			return;
704 704
 		}
705 705
 		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
@@ -719,9 +719,9 @@  discard block
 block discarded – undo
719 719
 		$attempts = 0;
720 720
 		//while loop is just a precaution. If a name is not generated within
721 721
 		//20 attempts, something else is very wrong. Avoids infinite loop.
722
-		while($attempts < 20){
723
-			$altName = $name . '_' . rand(1000,9999);
724
-			if(!\OC::$server->getUserManager()->userExists($altName)) {
722
+		while ($attempts < 20) {
723
+			$altName = $name.'_'.rand(1000, 9999);
724
+			if (!\OC::$server->getUserManager()->userExists($altName)) {
725 725
 				return $altName;
726 726
 			}
727 727
 			$attempts++;
@@ -743,25 +743,25 @@  discard block
 block discarded – undo
743 743
 	 */
744 744
 	private function _createAltInternalOwnCloudNameForGroups($name) {
745 745
 		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
746
-		if(!($usedNames) || count($usedNames) === 0) {
746
+		if (!($usedNames) || count($usedNames) === 0) {
747 747
 			$lastNo = 1; //will become name_2
748 748
 		} else {
749 749
 			natsort($usedNames);
750 750
 			$lastName = array_pop($usedNames);
751 751
 			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
752 752
 		}
753
-		$altName = $name.'_'.strval($lastNo+1);
753
+		$altName = $name.'_'.strval($lastNo + 1);
754 754
 		unset($usedNames);
755 755
 
756 756
 		$attempts = 1;
757
-		while($attempts < 21){
757
+		while ($attempts < 21) {
758 758
 			// Check to be really sure it is unique
759 759
 			// while loop is just a precaution. If a name is not generated within
760 760
 			// 20 attempts, something else is very wrong. Avoids infinite loop.
761
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
761
+			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
762 762
 				return $altName;
763 763
 			}
764
-			$altName = $name . '_' . ($lastNo + $attempts);
764
+			$altName = $name.'_'.($lastNo + $attempts);
765 765
 			$attempts++;
766 766
 		}
767 767
 		return false;
@@ -776,7 +776,7 @@  discard block
 block discarded – undo
776 776
 	private function createAltInternalOwnCloudName($name, $isUser) {
777 777
 		$originalTTL = $this->connection->ldapCacheTTL;
778 778
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
779
-		if($isUser) {
779
+		if ($isUser) {
780 780
 			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
781 781
 		} else {
782 782
 			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
@@ -826,13 +826,13 @@  discard block
 block discarded – undo
826 826
 	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
827 827
 		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
828 828
 		$recordsToUpdate = $ldapRecords;
829
-		if(!$forceApplyAttributes) {
829
+		if (!$forceApplyAttributes) {
830 830
 			$isBackgroundJobModeAjax = $this->config
831 831
 					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
832 832
 			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
833 833
 				$newlyMapped = false;
834 834
 				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
835
-				if(is_string($uid)) {
835
+				if (is_string($uid)) {
836 836
 					$this->cacheUserExists($uid);
837 837
 				}
838 838
 				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
@@ -848,19 +848,19 @@  discard block
 block discarded – undo
848 848
 	 * and their values
849 849
 	 * @param array $ldapRecords
850 850
 	 */
851
-	public function batchApplyUserAttributes(array $ldapRecords){
851
+	public function batchApplyUserAttributes(array $ldapRecords) {
852 852
 		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
853
-		foreach($ldapRecords as $userRecord) {
854
-			if(!isset($userRecord[$displayNameAttribute])) {
853
+		foreach ($ldapRecords as $userRecord) {
854
+			if (!isset($userRecord[$displayNameAttribute])) {
855 855
 				// displayName is obligatory
856 856
 				continue;
857 857
 			}
858
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
859
-			if($ocName === false) {
858
+			$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
859
+			if ($ocName === false) {
860 860
 				continue;
861 861
 			}
862 862
 			$user = $this->userManager->get($ocName);
863
-			if($user instanceof OfflineUser) {
863
+			if ($user instanceof OfflineUser) {
864 864
 				$user->unmark();
865 865
 				$user = $this->userManager->get($ocName);
866 866
 			}
@@ -892,8 +892,8 @@  discard block
 block discarded – undo
892 892
 	 * @return array
893 893
 	 */
894 894
 	private function fetchList($list, $manyAttributes) {
895
-		if(is_array($list)) {
896
-			if($manyAttributes) {
895
+		if (is_array($list)) {
896
+			if ($manyAttributes) {
897 897
 				return $list;
898 898
 			} else {
899 899
 				$list = array_reduce($list, function($carry, $item) {
@@ -991,7 +991,7 @@  discard block
 block discarded – undo
991 991
 		// php no longer supports call-time pass-by-reference
992 992
 		// thus cannot support controlPagedResultResponse as the third argument
993 993
 		// is a reference
994
-		$doMethod = function () use ($command, &$arguments) {
994
+		$doMethod = function() use ($command, &$arguments) {
995 995
 			if ($command == 'controlPagedResultResponse') {
996 996
 				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
997 997
 			} else {
@@ -1009,7 +1009,7 @@  discard block
 block discarded – undo
1009 1009
 			$this->connection->resetConnectionResource();
1010 1010
 			$cr = $this->connection->getConnectionResource();
1011 1011
 
1012
-			if(!$this->ldap->isResource($cr)) {
1012
+			if (!$this->ldap->isResource($cr)) {
1013 1013
 				// Seems like we didn't find any resource.
1014 1014
 				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1015 1015
 				throw $e;
@@ -1034,13 +1034,13 @@  discard block
 block discarded – undo
1034 1034
 	 * @throws ServerNotAvailableException
1035 1035
 	 */
1036 1036
 	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1037
-		if(!is_null($attr) && !is_array($attr)) {
1037
+		if (!is_null($attr) && !is_array($attr)) {
1038 1038
 			$attr = array(mb_strtolower($attr, 'UTF-8'));
1039 1039
 		}
1040 1040
 
1041 1041
 		// See if we have a resource, in case not cancel with message
1042 1042
 		$cr = $this->connection->getConnectionResource();
1043
-		if(!$this->ldap->isResource($cr)) {
1043
+		if (!$this->ldap->isResource($cr)) {
1044 1044
 			// Seems like we didn't find any resource.
1045 1045
 			// Return an empty array just like before.
1046 1046
 			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
@@ -1054,7 +1054,7 @@  discard block
 block discarded – undo
1054 1054
 		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1055 1055
 		// cannot use $cr anymore, might have changed in the previous call!
1056 1056
 		$error = $this->ldap->errno($this->connection->getConnectionResource());
1057
-		if(!is_array($sr) || $error !== 0) {
1057
+		if (!is_array($sr) || $error !== 0) {
1058 1058
 			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1059 1059
 			return false;
1060 1060
 		}
@@ -1077,29 +1077,29 @@  discard block
 block discarded – undo
1077 1077
 	 */
1078 1078
 	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1079 1079
 		$cookie = null;
1080
-		if($pagedSearchOK) {
1080
+		if ($pagedSearchOK) {
1081 1081
 			$cr = $this->connection->getConnectionResource();
1082
-			foreach($sr as $key => $res) {
1083
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1082
+			foreach ($sr as $key => $res) {
1083
+				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1084 1084
 					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1085 1085
 				}
1086 1086
 			}
1087 1087
 
1088 1088
 			//browsing through prior pages to get the cookie for the new one
1089
-			if($skipHandling) {
1089
+			if ($skipHandling) {
1090 1090
 				return false;
1091 1091
 			}
1092 1092
 			// if count is bigger, then the server does not support
1093 1093
 			// paged search. Instead, he did a normal search. We set a
1094 1094
 			// flag here, so the callee knows how to deal with it.
1095
-			if($iFoundItems <= $limit) {
1095
+			if ($iFoundItems <= $limit) {
1096 1096
 				$this->pagedSearchedSuccessful = true;
1097 1097
 			}
1098 1098
 		} else {
1099
-			if(!is_null($limit) && intval($this->connection->ldapPagingSize) !== 0) {
1099
+			if (!is_null($limit) && intval($this->connection->ldapPagingSize) !== 0) {
1100 1100
 				\OC::$server->getLogger()->debug(
1101 1101
 					'Paged search was not available',
1102
-					[ 'app' => 'user_ldap' ]
1102
+					['app' => 'user_ldap']
1103 1103
 				);
1104 1104
 			}
1105 1105
 		}
@@ -1129,7 +1129,7 @@  discard block
 block discarded – undo
1129 1129
 		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1130 1130
 
1131 1131
 		$limitPerPage = intval($this->connection->ldapPagingSize);
1132
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1132
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1133 1133
 			$limitPerPage = $limit;
1134 1134
 		}
1135 1135
 
@@ -1139,7 +1139,7 @@  discard block
 block discarded – undo
1139 1139
 
1140 1140
 		do {
1141 1141
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1142
-			if($search === false) {
1142
+			if ($search === false) {
1143 1143
 				return $counter > 0 ? $counter : false;
1144 1144
 			}
1145 1145
 			list($sr, $pagedSearchOK) = $search;
@@ -1158,7 +1158,7 @@  discard block
 block discarded – undo
1158 1158
 			 * Continue now depends on $hasMorePages value
1159 1159
 			 */
1160 1160
 			$continue = $pagedSearchOK && $hasMorePages;
1161
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1161
+		} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1162 1162
 
1163 1163
 		return $counter;
1164 1164
 	}
@@ -1170,7 +1170,7 @@  discard block
 block discarded – undo
1170 1170
 	private function countEntriesInSearchResults($searchResults) {
1171 1171
 		$counter = 0;
1172 1172
 
1173
-		foreach($searchResults as $res) {
1173
+		foreach ($searchResults as $res) {
1174 1174
 			$count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1175 1175
 			$counter += $count;
1176 1176
 		}
@@ -1192,7 +1192,7 @@  discard block
 block discarded – undo
1192 1192
 	 */
1193 1193
 	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1194 1194
 		$limitPerPage = intval($this->connection->ldapPagingSize);
1195
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1195
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1196 1196
 			$limitPerPage = $limit;
1197 1197
 		}
1198 1198
 
@@ -1206,13 +1206,13 @@  discard block
 block discarded – undo
1206 1206
 		$savedoffset = $offset;
1207 1207
 		do {
1208 1208
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1209
-			if($search === false) {
1209
+			if ($search === false) {
1210 1210
 				return [];
1211 1211
 			}
1212 1212
 			list($sr, $pagedSearchOK) = $search;
1213 1213
 			$cr = $this->connection->getConnectionResource();
1214 1214
 
1215
-			if($skipHandling) {
1215
+			if ($skipHandling) {
1216 1216
 				//i.e. result do not need to be fetched, we just need the cookie
1217 1217
 				//thus pass 1 or any other value as $iFoundItems because it is not
1218 1218
 				//used
@@ -1223,7 +1223,7 @@  discard block
 block discarded – undo
1223 1223
 			}
1224 1224
 
1225 1225
 			$iFoundItems = 0;
1226
-			foreach($sr as $res) {
1226
+			foreach ($sr as $res) {
1227 1227
 				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1228 1228
 				$iFoundItems = max($iFoundItems, $findings['count']);
1229 1229
 				unset($findings['count']);
@@ -1239,27 +1239,27 @@  discard block
 block discarded – undo
1239 1239
 
1240 1240
 		// if we're here, probably no connection resource is returned.
1241 1241
 		// to make Nextcloud behave nicely, we simply give back an empty array.
1242
-		if(is_null($findings)) {
1242
+		if (is_null($findings)) {
1243 1243
 			return array();
1244 1244
 		}
1245 1245
 
1246
-		if(!is_null($attr)) {
1246
+		if (!is_null($attr)) {
1247 1247
 			$selection = [];
1248 1248
 			$i = 0;
1249
-			foreach($findings as $item) {
1250
-				if(!is_array($item)) {
1249
+			foreach ($findings as $item) {
1250
+				if (!is_array($item)) {
1251 1251
 					continue;
1252 1252
 				}
1253 1253
 				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1254
-				foreach($attr as $key) {
1255
-					if(isset($item[$key])) {
1256
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1254
+				foreach ($attr as $key) {
1255
+					if (isset($item[$key])) {
1256
+						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1257 1257
 							unset($item[$key]['count']);
1258 1258
 						}
1259
-						if($key !== 'dn') {
1260
-							if($this->resemblesDN($key)) {
1259
+						if ($key !== 'dn') {
1260
+							if ($this->resemblesDN($key)) {
1261 1261
 								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1262
-							} else if($key === 'objectguid' || $key === 'guid') {
1262
+							} else if ($key === 'objectguid' || $key === 'guid') {
1263 1263
 								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1264 1264
 							} else {
1265 1265
 								$selection[$i][$key] = $item[$key];
@@ -1277,7 +1277,7 @@  discard block
 block discarded – undo
1277 1277
 		//we slice the findings, when
1278 1278
 		//a) paged search unsuccessful, though attempted
1279 1279
 		//b) no paged search, but limit set
1280
-		if((!$this->getPagedSearchResultState()
1280
+		if ((!$this->getPagedSearchResultState()
1281 1281
 			&& $pagedSearchOK)
1282 1282
 			|| (
1283 1283
 				!$pagedSearchOK
@@ -1294,7 +1294,7 @@  discard block
 block discarded – undo
1294 1294
 	 * @return bool|mixed|string
1295 1295
 	 */
1296 1296
 	public function sanitizeUsername($name) {
1297
-		if($this->connection->ldapIgnoreNamingRules) {
1297
+		if ($this->connection->ldapIgnoreNamingRules) {
1298 1298
 			return trim($name);
1299 1299
 		}
1300 1300
 
@@ -1319,13 +1319,13 @@  discard block
 block discarded – undo
1319 1319
 	*/
1320 1320
 	public function escapeFilterPart($input, $allowAsterisk = false) {
1321 1321
 		$asterisk = '';
1322
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1322
+		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1323 1323
 			$asterisk = '*';
1324 1324
 			$input = mb_substr($input, 1, null, 'UTF-8');
1325 1325
 		}
1326 1326
 		$search  = array('*', '\\', '(', ')');
1327 1327
 		$replace = array('\\*', '\\\\', '\\(', '\\)');
1328
-		return $asterisk . str_replace($search, $replace, $input);
1328
+		return $asterisk.str_replace($search, $replace, $input);
1329 1329
 	}
1330 1330
 
1331 1331
 	/**
@@ -1355,13 +1355,13 @@  discard block
 block discarded – undo
1355 1355
 	 */
1356 1356
 	private function combineFilter($filters, $operator) {
1357 1357
 		$combinedFilter = '('.$operator;
1358
-		foreach($filters as $filter) {
1358
+		foreach ($filters as $filter) {
1359 1359
 			if ($filter !== '' && $filter[0] !== '(') {
1360 1360
 				$filter = '('.$filter.')';
1361 1361
 			}
1362
-			$combinedFilter.=$filter;
1362
+			$combinedFilter .= $filter;
1363 1363
 		}
1364
-		$combinedFilter.=')';
1364
+		$combinedFilter .= ')';
1365 1365
 		return $combinedFilter;
1366 1366
 	}
1367 1367
 
@@ -1397,17 +1397,17 @@  discard block
 block discarded – undo
1397 1397
 	 * @throws \Exception
1398 1398
 	 */
1399 1399
 	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1400
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1400
+		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1401 1401
 			throw new \Exception('searchAttributes must be an array with at least two string');
1402 1402
 		}
1403 1403
 		$searchWords = explode(' ', trim($search));
1404 1404
 		$wordFilters = array();
1405
-		foreach($searchWords as $word) {
1405
+		foreach ($searchWords as $word) {
1406 1406
 			$word = $this->prepareSearchTerm($word);
1407 1407
 			//every word needs to appear at least once
1408 1408
 			$wordMatchOneAttrFilters = array();
1409
-			foreach($searchAttributes as $attr) {
1410
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1409
+			foreach ($searchAttributes as $attr) {
1410
+				$wordMatchOneAttrFilters[] = $attr.'='.$word;
1411 1411
 			}
1412 1412
 			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1413 1413
 		}
@@ -1425,10 +1425,10 @@  discard block
 block discarded – undo
1425 1425
 	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1426 1426
 		$filter = array();
1427 1427
 		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1428
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1428
+		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1429 1429
 			try {
1430 1430
 				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1431
-			} catch(\Exception $e) {
1431
+			} catch (\Exception $e) {
1432 1432
 				\OCP\Util::writeLog(
1433 1433
 					'user_ldap',
1434 1434
 					'Creating advanced filter for search failed, falling back to simple method.',
@@ -1438,17 +1438,17 @@  discard block
 block discarded – undo
1438 1438
 		}
1439 1439
 
1440 1440
 		$search = $this->prepareSearchTerm($search);
1441
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1441
+		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1442 1442
 			if ($fallbackAttribute === '') {
1443 1443
 				return '';
1444 1444
 			}
1445
-			$filter[] = $fallbackAttribute . '=' . $search;
1445
+			$filter[] = $fallbackAttribute.'='.$search;
1446 1446
 		} else {
1447
-			foreach($searchAttributes as $attribute) {
1448
-				$filter[] = $attribute . '=' . $search;
1447
+			foreach ($searchAttributes as $attribute) {
1448
+				$filter[] = $attribute.'='.$search;
1449 1449
 			}
1450 1450
 		}
1451
-		if(count($filter) === 1) {
1451
+		if (count($filter) === 1) {
1452 1452
 			return '('.$filter[0].')';
1453 1453
 		}
1454 1454
 		return $this->combineFilterWithOr($filter);
@@ -1469,7 +1469,7 @@  discard block
 block discarded – undo
1469 1469
 		if ($term === '') {
1470 1470
 			$result = '*';
1471 1471
 		} else if ($allowEnum !== 'no') {
1472
-			$result = $term . '*';
1472
+			$result = $term.'*';
1473 1473
 		}
1474 1474
 		return $result;
1475 1475
 	}
@@ -1481,7 +1481,7 @@  discard block
 block discarded – undo
1481 1481
 	public function getFilterForUserCount() {
1482 1482
 		$filter = $this->combineFilterWithAnd(array(
1483 1483
 			$this->connection->ldapUserFilter,
1484
-			$this->connection->ldapUserDisplayName . '=*'
1484
+			$this->connection->ldapUserDisplayName.'=*'
1485 1485
 		));
1486 1486
 
1487 1487
 		return $filter;
@@ -1499,7 +1499,7 @@  discard block
 block discarded – undo
1499 1499
 			'ldapAgentName' => $name,
1500 1500
 			'ldapAgentPassword' => $password
1501 1501
 		);
1502
-		if(!$testConnection->setConfiguration($credentials)) {
1502
+		if (!$testConnection->setConfiguration($credentials)) {
1503 1503
 			return false;
1504 1504
 		}
1505 1505
 		return $testConnection->bind();
@@ -1521,30 +1521,30 @@  discard block
 block discarded – undo
1521 1521
 			// Sacrebleu! The UUID attribute is unknown :( We need first an
1522 1522
 			// existing DN to be able to reliably detect it.
1523 1523
 			$result = $this->search($filter, $base, ['dn'], 1);
1524
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1524
+			if (!isset($result[0]) || !isset($result[0]['dn'])) {
1525 1525
 				throw new \Exception('Cannot determine UUID attribute');
1526 1526
 			}
1527 1527
 			$dn = $result[0]['dn'][0];
1528
-			if(!$this->detectUuidAttribute($dn, true)) {
1528
+			if (!$this->detectUuidAttribute($dn, true)) {
1529 1529
 				throw new \Exception('Cannot determine UUID attribute');
1530 1530
 			}
1531 1531
 		} else {
1532 1532
 			// The UUID attribute is either known or an override is given.
1533 1533
 			// By calling this method we ensure that $this->connection->$uuidAttr
1534 1534
 			// is definitely set
1535
-			if(!$this->detectUuidAttribute('', true)) {
1535
+			if (!$this->detectUuidAttribute('', true)) {
1536 1536
 				throw new \Exception('Cannot determine UUID attribute');
1537 1537
 			}
1538 1538
 		}
1539 1539
 
1540 1540
 		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1541
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1541
+		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1542 1542
 			$uuid = $this->formatGuid2ForFilterUser($uuid);
1543 1543
 		}
1544 1544
 
1545
-		$filter = $uuidAttr . '=' . $uuid;
1545
+		$filter = $uuidAttr.'='.$uuid;
1546 1546
 		$result = $this->searchUsers($filter, ['dn'], 2);
1547
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1547
+		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1548 1548
 			// we put the count into account to make sure that this is
1549 1549
 			// really unique
1550 1550
 			return $result[0]['dn'][0];
@@ -1563,7 +1563,7 @@  discard block
 block discarded – undo
1563 1563
 	 * @return bool true on success, false otherwise
1564 1564
 	 */
1565 1565
 	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1566
-		if($isUser) {
1566
+		if ($isUser) {
1567 1567
 			$uuidAttr     = 'ldapUuidUserAttribute';
1568 1568
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1569 1569
 		} else {
@@ -1571,7 +1571,7 @@  discard block
 block discarded – undo
1571 1571
 			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1572 1572
 		}
1573 1573
 
1574
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1574
+		if (($this->connection->$uuidAttr !== 'auto') && !$force) {
1575 1575
 			return true;
1576 1576
 		}
1577 1577
 
@@ -1580,10 +1580,10 @@  discard block
 block discarded – undo
1580 1580
 			return true;
1581 1581
 		}
1582 1582
 
1583
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1584
-			if($ldapRecord !== null) {
1583
+		foreach (self::UUID_ATTRIBUTES as $attribute) {
1584
+			if ($ldapRecord !== null) {
1585 1585
 				// we have the info from LDAP already, we don't need to talk to the server again
1586
-				if(isset($ldapRecord[$attribute])) {
1586
+				if (isset($ldapRecord[$attribute])) {
1587 1587
 					$this->connection->$uuidAttr = $attribute;
1588 1588
 					return true;
1589 1589
 				} else {
@@ -1592,7 +1592,7 @@  discard block
 block discarded – undo
1592 1592
 			}
1593 1593
 
1594 1594
 			$value = $this->readAttribute($dn, $attribute);
1595
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1595
+			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1596 1596
 				\OCP\Util::writeLog('user_ldap',
1597 1597
 									'Setting '.$attribute.' as '.$uuidAttr,
1598 1598
 									\OCP\Util::DEBUG);
@@ -1614,7 +1614,7 @@  discard block
 block discarded – undo
1614 1614
 	 * @return bool|string
1615 1615
 	 */
1616 1616
 	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1617
-		if($isUser) {
1617
+		if ($isUser) {
1618 1618
 			$uuidAttr     = 'ldapUuidUserAttribute';
1619 1619
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1620 1620
 		} else {
@@ -1623,10 +1623,10 @@  discard block
 block discarded – undo
1623 1623
 		}
1624 1624
 
1625 1625
 		$uuid = false;
1626
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1626
+		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1627 1627
 			$attr = $this->connection->$uuidAttr;
1628 1628
 			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1629
-			if( !is_array($uuid)
1629
+			if (!is_array($uuid)
1630 1630
 				&& $uuidOverride !== ''
1631 1631
 				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1632 1632
 			{
@@ -1634,7 +1634,7 @@  discard block
 block discarded – undo
1634 1634
 					? $ldapRecord[$this->connection->$uuidAttr]
1635 1635
 					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1636 1636
 			}
1637
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1637
+			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1638 1638
 				$uuid = $uuid[0];
1639 1639
 			}
1640 1640
 		}
@@ -1651,19 +1651,19 @@  discard block
 block discarded – undo
1651 1651
 	private function convertObjectGUID2Str($oguid) {
1652 1652
 		$hex_guid = bin2hex($oguid);
1653 1653
 		$hex_guid_to_guid_str = '';
1654
-		for($k = 1; $k <= 4; ++$k) {
1654
+		for ($k = 1; $k <= 4; ++$k) {
1655 1655
 			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1656 1656
 		}
1657 1657
 		$hex_guid_to_guid_str .= '-';
1658
-		for($k = 1; $k <= 2; ++$k) {
1658
+		for ($k = 1; $k <= 2; ++$k) {
1659 1659
 			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1660 1660
 		}
1661 1661
 		$hex_guid_to_guid_str .= '-';
1662
-		for($k = 1; $k <= 2; ++$k) {
1662
+		for ($k = 1; $k <= 2; ++$k) {
1663 1663
 			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1664 1664
 		}
1665
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1666
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1665
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4);
1666
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 20);
1667 1667
 
1668 1668
 		return strtoupper($hex_guid_to_guid_str);
1669 1669
 	}
@@ -1680,11 +1680,11 @@  discard block
 block discarded – undo
1680 1680
 	 * @return string
1681 1681
 	 */
1682 1682
 	public function formatGuid2ForFilterUser($guid) {
1683
-		if(!is_string($guid)) {
1683
+		if (!is_string($guid)) {
1684 1684
 			throw new \InvalidArgumentException('String expected');
1685 1685
 		}
1686 1686
 		$blocks = explode('-', $guid);
1687
-		if(count($blocks) !== 5) {
1687
+		if (count($blocks) !== 5) {
1688 1688
 			/*
1689 1689
 			 * Why not throw an Exception instead? This method is a utility
1690 1690
 			 * called only when trying to figure out whether a "missing" known
@@ -1697,20 +1697,20 @@  discard block
 block discarded – undo
1697 1697
 			 * user. Instead we write a log message.
1698 1698
 			 */
1699 1699
 			\OC::$server->getLogger()->info(
1700
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1700
+				'Passed string does not resemble a valid GUID. Known UUID '.
1701 1701
 				'({uuid}) probably does not match UUID configuration.',
1702
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1702
+				['app' => 'user_ldap', 'uuid' => $guid]
1703 1703
 			);
1704 1704
 			return $guid;
1705 1705
 		}
1706
-		for($i=0; $i < 3; $i++) {
1706
+		for ($i = 0; $i < 3; $i++) {
1707 1707
 			$pairs = str_split($blocks[$i], 2);
1708 1708
 			$pairs = array_reverse($pairs);
1709 1709
 			$blocks[$i] = implode('', $pairs);
1710 1710
 		}
1711
-		for($i=0; $i < 5; $i++) {
1711
+		for ($i = 0; $i < 5; $i++) {
1712 1712
 			$pairs = str_split($blocks[$i], 2);
1713
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1713
+			$blocks[$i] = '\\'.implode('\\', $pairs);
1714 1714
 		}
1715 1715
 		return implode('', $blocks);
1716 1716
 	}
@@ -1724,12 +1724,12 @@  discard block
 block discarded – undo
1724 1724
 		$domainDN = $this->getDomainDNFromDN($dn);
1725 1725
 		$cacheKey = 'getSID-'.$domainDN;
1726 1726
 		$sid = $this->connection->getFromCache($cacheKey);
1727
-		if(!is_null($sid)) {
1727
+		if (!is_null($sid)) {
1728 1728
 			return $sid;
1729 1729
 		}
1730 1730
 
1731 1731
 		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1732
-		if(!is_array($objectSid) || empty($objectSid)) {
1732
+		if (!is_array($objectSid) || empty($objectSid)) {
1733 1733
 			$this->connection->writeToCache($cacheKey, false);
1734 1734
 			return false;
1735 1735
 		}
@@ -1787,12 +1787,12 @@  discard block
 block discarded – undo
1787 1787
 		$belongsToBase = false;
1788 1788
 		$bases = $this->helper->sanitizeDN($bases);
1789 1789
 
1790
-		foreach($bases as $base) {
1790
+		foreach ($bases as $base) {
1791 1791
 			$belongsToBase = true;
1792
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1792
+			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1793 1793
 				$belongsToBase = false;
1794 1794
 			}
1795
-			if($belongsToBase) {
1795
+			if ($belongsToBase) {
1796 1796
 				break;
1797 1797
 			}
1798 1798
 		}
@@ -1803,7 +1803,7 @@  discard block
 block discarded – undo
1803 1803
 	 * resets a running Paged Search operation
1804 1804
 	 */
1805 1805
 	private function abandonPagedSearch() {
1806
-		if($this->connection->hasPagedResultSupport) {
1806
+		if ($this->connection->hasPagedResultSupport) {
1807 1807
 			$cr = $this->connection->getConnectionResource();
1808 1808
 			$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1809 1809
 			$this->getPagedSearchResultState();
@@ -1821,16 +1821,16 @@  discard block
 block discarded – undo
1821 1821
 	 * @return string containing the key or empty if none is cached
1822 1822
 	 */
1823 1823
 	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1824
-		if($offset === 0) {
1824
+		if ($offset === 0) {
1825 1825
 			return '';
1826 1826
 		}
1827 1827
 		$offset -= $limit;
1828 1828
 		//we work with cache here
1829
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1829
+		$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1830 1830
 		$cookie = '';
1831
-		if(isset($this->cookies[$cacheKey])) {
1831
+		if (isset($this->cookies[$cacheKey])) {
1832 1832
 			$cookie = $this->cookies[$cacheKey];
1833
-			if(is_null($cookie)) {
1833
+			if (is_null($cookie)) {
1834 1834
 				$cookie = '';
1835 1835
 			}
1836 1836
 		}
@@ -1848,11 +1848,11 @@  discard block
 block discarded – undo
1848 1848
 	 * @return bool
1849 1849
 	 */
1850 1850
 	public function hasMoreResults() {
1851
-		if(!$this->connection->hasPagedResultSupport) {
1851
+		if (!$this->connection->hasPagedResultSupport) {
1852 1852
 			return false;
1853 1853
 		}
1854 1854
 
1855
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1855
+		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1856 1856
 			// as in RFC 2696, when all results are returned, the cookie will
1857 1857
 			// be empty.
1858 1858
 			return false;
@@ -1872,8 +1872,8 @@  discard block
 block discarded – undo
1872 1872
 	 */
1873 1873
 	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1874 1874
 		// allow '0' for 389ds
1875
-		if(!empty($cookie) || $cookie === '0') {
1876
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1875
+		if (!empty($cookie) || $cookie === '0') {
1876
+			$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1877 1877
 			$this->cookies[$cacheKey] = $cookie;
1878 1878
 			$this->lastCookie = $cookie;
1879 1879
 		}
@@ -1900,17 +1900,17 @@  discard block
 block discarded – undo
1900 1900
 	 */
1901 1901
 	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1902 1902
 		$pagedSearchOK = false;
1903
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1903
+		if ($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1904 1904
 			$offset = intval($offset); //can be null
1905 1905
 			\OCP\Util::writeLog('user_ldap',
1906 1906
 				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1907
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1907
+				.' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset,
1908 1908
 				\OCP\Util::DEBUG);
1909 1909
 			//get the cookie from the search for the previous search, required by LDAP
1910
-			foreach($bases as $base) {
1910
+			foreach ($bases as $base) {
1911 1911
 
1912 1912
 				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1913
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1913
+				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1914 1914
 					// no cookie known from a potential previous search. We need
1915 1915
 					// to start from 0 to come to the desired page. cookie value
1916 1916
 					// of '0' is valid, because 389ds
@@ -1920,17 +1920,17 @@  discard block
 block discarded – undo
1920 1920
 					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1921 1921
 					// '0' is valid, because 389ds
1922 1922
 					//TODO: remember this, probably does not change in the next request...
1923
-					if(empty($cookie) && $cookie !== '0') {
1923
+					if (empty($cookie) && $cookie !== '0') {
1924 1924
 						$cookie = null;
1925 1925
 					}
1926 1926
 				}
1927
-				if(!is_null($cookie)) {
1927
+				if (!is_null($cookie)) {
1928 1928
 					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1929 1929
 					$this->abandonPagedSearch();
1930 1930
 					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1931 1931
 						$this->connection->getConnectionResource(), $limit,
1932 1932
 						false, $cookie);
1933
-					if(!$pagedSearchOK) {
1933
+					if (!$pagedSearchOK) {
1934 1934
 						return false;
1935 1935
 					}
1936 1936
 					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
@@ -1946,7 +1946,7 @@  discard block
 block discarded – undo
1946 1946
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1947 1947
 		 * if we don't have a previous paged search.
1948 1948
 		 */
1949
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1949
+		} else if ($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1950 1950
 			// a search without limit was requested. However, if we do use
1951 1951
 			// Paged Search once, we always must do it. This requires us to
1952 1952
 			// initialize it with the configured page size.
Please login to merge, or discard this patch.
apps/federatedfilesharing/lib/Controller/RequestHandlerController.php 2 patches
Indentation   +607 added lines, -607 removed lines patch added patch discarded remove patch
@@ -50,611 +50,611 @@
 block discarded – undo
50 50
 
51 51
 class RequestHandlerController extends OCSController {
52 52
 
53
-	/** @var FederatedShareProvider */
54
-	private $federatedShareProvider;
55
-
56
-	/** @var IDBConnection */
57
-	private $connection;
58
-
59
-	/** @var Share\IManager */
60
-	private $shareManager;
61
-
62
-	/** @var Notifications */
63
-	private $notifications;
64
-
65
-	/** @var AddressHandler */
66
-	private $addressHandler;
67
-
68
-	/** @var  IUserManager */
69
-	private $userManager;
70
-
71
-	/** @var string */
72
-	private $shareTable = 'share';
73
-
74
-	/** @var ICloudIdManager */
75
-	private $cloudIdManager;
76
-
77
-	/**
78
-	 * Server2Server constructor.
79
-	 *
80
-	 * @param string $appName
81
-	 * @param IRequest $request
82
-	 * @param FederatedShareProvider $federatedShareProvider
83
-	 * @param IDBConnection $connection
84
-	 * @param Share\IManager $shareManager
85
-	 * @param Notifications $notifications
86
-	 * @param AddressHandler $addressHandler
87
-	 * @param IUserManager $userManager
88
-	 * @param ICloudIdManager $cloudIdManager
89
-	 */
90
-	public function __construct($appName,
91
-								IRequest $request,
92
-								FederatedShareProvider $federatedShareProvider,
93
-								IDBConnection $connection,
94
-								Share\IManager $shareManager,
95
-								Notifications $notifications,
96
-								AddressHandler $addressHandler,
97
-								IUserManager $userManager,
98
-								ICloudIdManager $cloudIdManager
99
-	) {
100
-		parent::__construct($appName, $request);
101
-
102
-		$this->federatedShareProvider = $federatedShareProvider;
103
-		$this->connection = $connection;
104
-		$this->shareManager = $shareManager;
105
-		$this->notifications = $notifications;
106
-		$this->addressHandler = $addressHandler;
107
-		$this->userManager = $userManager;
108
-		$this->cloudIdManager = $cloudIdManager;
109
-	}
110
-
111
-	/**
112
-	 * @NoCSRFRequired
113
-	 * @PublicPage
114
-	 *
115
-	 * create a new share
116
-	 *
117
-	 * @return Http\DataResponse
118
-	 * @throws OCSException
119
-	 */
120
-	public function createShare() {
121
-
122
-		if (!$this->isS2SEnabled(true)) {
123
-			throw new OCSException('Server does not support federated cloud sharing', 503);
124
-		}
125
-
126
-		$remote = isset($_POST['remote']) ? $_POST['remote'] : null;
127
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
128
-		$name = isset($_POST['name']) ? $_POST['name'] : null;
129
-		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
130
-		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
131
-		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
132
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
133
-		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
134
-		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
135
-
136
-		if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
137
-
138
-			if (!\OCP\Util::isValidFileName($name)) {
139
-				throw new OCSException('The mountpoint name contains invalid characters.', 400);
140
-			}
141
-
142
-			// FIXME this should be a method in the user management instead
143
-			\OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
144
-			\OCP\Util::emitHook(
145
-				'\OCA\Files_Sharing\API\Server2Server',
146
-				'preLoginNameUsedAsUserName',
147
-				array('uid' => &$shareWith)
148
-			);
149
-			\OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
150
-
151
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
152
-				throw new OCSException('User does not exists', 400);
153
-			}
154
-
155
-			\OC_Util::setupFS($shareWith);
156
-
157
-			$externalManager = new \OCA\Files_Sharing\External\Manager(
158
-					\OC::$server->getDatabaseConnection(),
159
-					\OC\Files\Filesystem::getMountManager(),
160
-					\OC\Files\Filesystem::getLoader(),
161
-					\OC::$server->getHTTPClientService(),
162
-					\OC::$server->getNotificationManager(),
163
-					\OC::$server->query(\OCP\OCS\IDiscoveryService::class),
164
-					$shareWith
165
-				);
166
-
167
-			try {
168
-				$externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
169
-				$shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
170
-
171
-				if ($ownerFederatedId === null) {
172
-					$ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
173
-				}
174
-				// if the owner of the share and the initiator are the same user
175
-				// we also complete the federated share ID for the initiator
176
-				if ($sharedByFederatedId === null && $owner === $sharedBy) {
177
-					$sharedByFederatedId = $ownerFederatedId;
178
-				}
179
-
180
-				$event = \OC::$server->getActivityManager()->generateEvent();
181
-				$event->setApp('files_sharing')
182
-					->setType('remote_share')
183
-					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
184
-					->setAffectedUser($shareWith)
185
-					->setObject('remote_share', (int)$shareId, $name);
186
-				\OC::$server->getActivityManager()->publish($event);
187
-
188
-				$urlGenerator = \OC::$server->getURLGenerator();
189
-
190
-				$notificationManager = \OC::$server->getNotificationManager();
191
-				$notification = $notificationManager->createNotification();
192
-				$notification->setApp('files_sharing')
193
-					->setUser($shareWith)
194
-					->setDateTime(new \DateTime())
195
-					->setObject('remote_share', $shareId)
196
-					->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
197
-
198
-				$declineAction = $notification->createAction();
199
-				$declineAction->setLabel('decline')
200
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
201
-				$notification->addAction($declineAction);
202
-
203
-				$acceptAction = $notification->createAction();
204
-				$acceptAction->setLabel('accept')
205
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
206
-				$notification->addAction($acceptAction);
207
-
208
-				$notificationManager->notify($notification);
209
-
210
-				return new Http\DataResponse();
211
-			} catch (\Exception $e) {
212
-				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
213
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
214
-			}
215
-		}
216
-
217
-		throw new OCSException('server can not add remote share, missing parameter', 400);
218
-	}
219
-
220
-	/**
221
-	 * @NoCSRFRequired
222
-	 * @PublicPage
223
-	 *
224
-	 * create re-share on behalf of another user
225
-	 *
226
-	 * @param int $id
227
-	 * @return Http\DataResponse
228
-	 * @throws OCSBadRequestException
229
-	 * @throws OCSForbiddenException
230
-	 * @throws OCSNotFoundException
231
-	 */
232
-	public function reShare($id) {
233
-
234
-		$token = $this->request->getParam('token', null);
235
-		$shareWith = $this->request->getParam('shareWith', null);
236
-		$permission = (int)$this->request->getParam('permission', null);
237
-		$remoteId = (int)$this->request->getParam('remoteId', null);
238
-
239
-		if ($id === null ||
240
-			$token === null ||
241
-			$shareWith === null ||
242
-			$permission === null ||
243
-			$remoteId === null
244
-		) {
245
-			throw new OCSBadRequestException();
246
-		}
247
-
248
-		try {
249
-			$share = $this->federatedShareProvider->getShareById($id);
250
-		} catch (Share\Exceptions\ShareNotFound $e) {
251
-			throw new OCSNotFoundException();
252
-		}
253
-
254
-		// don't allow to share a file back to the owner
255
-		list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
256
-		$owner = $share->getShareOwner();
257
-		$currentServer = $this->addressHandler->generateRemoteURL();
258
-		if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
259
-			throw new OCSForbiddenException();
260
-		}
261
-
262
-		if ($this->verifyShare($share, $token)) {
263
-
264
-			// check if re-sharing is allowed
265
-			if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
266
-				$share->setPermissions($share->getPermissions() & $permission);
267
-				// the recipient of the initial share is now the initiator for the re-share
268
-				$share->setSharedBy($share->getSharedWith());
269
-				$share->setSharedWith($shareWith);
270
-				try {
271
-					$result = $this->federatedShareProvider->create($share);
272
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
273
-					return new Http\DataResponse([
274
-						'token' => $result->getToken(),
275
-						'remoteId' => $result->getId()
276
-					]);
277
-				} catch (\Exception $e) {
278
-					throw new OCSBadRequestException();
279
-				}
280
-			} else {
281
-				throw new OCSForbiddenException();
282
-			}
283
-		}
284
-		throw new OCSBadRequestException();
285
-	}
286
-
287
-	/**
288
-	 * @NoCSRFRequired
289
-	 * @PublicPage
290
-	 *
291
-	 * accept server-to-server share
292
-	 *
293
-	 * @param int $id
294
-	 * @return Http\DataResponse
295
-	 * @throws OCSException
296
-	 */
297
-	public function acceptShare($id) {
298
-
299
-		if (!$this->isS2SEnabled()) {
300
-			throw new OCSException('Server does not support federated cloud sharing', 503);
301
-		}
302
-
303
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
304
-
305
-		try {
306
-			$share = $this->federatedShareProvider->getShareById($id);
307
-		} catch (Share\Exceptions\ShareNotFound $e) {
308
-			return new Http\DataResponse();
309
-		}
310
-
311
-		if ($this->verifyShare($share, $token)) {
312
-			$this->executeAcceptShare($share);
313
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
314
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
315
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
316
-				$this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
317
-			}
318
-		}
319
-
320
-		return new Http\DataResponse();
321
-	}
322
-
323
-	protected function executeAcceptShare(Share\IShare $share) {
324
-		$fileId = (int) $share->getNode()->getId();
325
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
326
-
327
-		$event = \OC::$server->getActivityManager()->generateEvent();
328
-		$event->setApp('files_sharing')
329
-			->setType('remote_share')
330
-			->setAffectedUser($this->getCorrectUid($share))
331
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
332
-			->setObject('files', $fileId, $file)
333
-			->setLink($link);
334
-		\OC::$server->getActivityManager()->publish($event);
335
-	}
336
-
337
-	/**
338
-	 * @NoCSRFRequired
339
-	 * @PublicPage
340
-	 *
341
-	 * decline server-to-server share
342
-	 *
343
-	 * @param int $id
344
-	 * @return Http\DataResponse
345
-	 * @throws OCSException
346
-	 */
347
-	public function declineShare($id) {
348
-
349
-		if (!$this->isS2SEnabled()) {
350
-			throw new OCSException('Server does not support federated cloud sharing', 503);
351
-		}
352
-
353
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
354
-
355
-		try {
356
-			$share = $this->federatedShareProvider->getShareById($id);
357
-		} catch (Share\Exceptions\ShareNotFound $e) {
358
-			return new Http\DataResponse();
359
-		}
360
-
361
-		if ($this->verifyShare($share, $token)) {
362
-			if ($share->getShareOwner() !== $share->getSharedBy()) {
363
-				list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
364
-				$remoteId = $this->federatedShareProvider->getRemoteId($share);
365
-				$this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
366
-			}
367
-			$this->executeDeclineShare($share);
368
-		}
369
-
370
-		return new Http\DataResponse();
371
-	}
372
-
373
-	/**
374
-	 * delete declined share and create a activity
375
-	 *
376
-	 * @param Share\IShare $share
377
-	 */
378
-	protected function executeDeclineShare(Share\IShare $share) {
379
-		$this->federatedShareProvider->removeShareFromTable($share);
380
-		$fileId = (int) $share->getNode()->getId();
381
-		list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
382
-
383
-		$event = \OC::$server->getActivityManager()->generateEvent();
384
-		$event->setApp('files_sharing')
385
-			->setType('remote_share')
386
-			->setAffectedUser($this->getCorrectUid($share))
387
-			->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
388
-			->setObject('files', $fileId, $file)
389
-			->setLink($link);
390
-		\OC::$server->getActivityManager()->publish($event);
391
-
392
-	}
393
-
394
-	/**
395
-	 * check if we are the initiator or the owner of a re-share and return the correct UID
396
-	 *
397
-	 * @param Share\IShare $share
398
-	 * @return string
399
-	 */
400
-	protected function getCorrectUid(Share\IShare $share) {
401
-		if ($this->userManager->userExists($share->getShareOwner())) {
402
-			return $share->getShareOwner();
403
-		}
404
-
405
-		return $share->getSharedBy();
406
-	}
407
-
408
-	/**
409
-	 * @NoCSRFRequired
410
-	 * @PublicPage
411
-	 *
412
-	 * remove server-to-server share if it was unshared by the owner
413
-	 *
414
-	 * @param int $id
415
-	 * @return Http\DataResponse
416
-	 * @throws OCSException
417
-	 */
418
-	public function unshare($id) {
419
-
420
-		if (!$this->isS2SEnabled()) {
421
-			throw new OCSException('Server does not support federated cloud sharing', 503);
422
-		}
423
-
424
-		$token = isset($_POST['token']) ? $_POST['token'] : null;
425
-
426
-		$query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
427
-		$query->execute(array($id, $token));
428
-		$share = $query->fetchRow();
429
-
430
-		if ($token && $id && !empty($share)) {
431
-
432
-			$remote = $this->cleanupRemote($share['remote']);
433
-
434
-			$owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
435
-			$mountpoint = $share['mountpoint'];
436
-			$user = $share['user'];
437
-
438
-			$query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
439
-			$query->execute(array($id, $token));
440
-
441
-			if ($share['accepted']) {
442
-				$path = trim($mountpoint, '/');
443
-			} else {
444
-				$path = trim($share['name'], '/');
445
-			}
446
-
447
-			$notificationManager = \OC::$server->getNotificationManager();
448
-			$notification = $notificationManager->createNotification();
449
-			$notification->setApp('files_sharing')
450
-				->setUser($share['user'])
451
-				->setObject('remote_share', (int)$share['id']);
452
-			$notificationManager->markProcessed($notification);
453
-
454
-			$event = \OC::$server->getActivityManager()->generateEvent();
455
-			$event->setApp('files_sharing')
456
-				->setType('remote_share')
457
-				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
458
-				->setAffectedUser($user)
459
-				->setObject('remote_share', (int)$share['id'], $path);
460
-			\OC::$server->getActivityManager()->publish($event);
461
-		}
462
-
463
-		return new Http\DataResponse();
464
-	}
465
-
466
-	private function cleanupRemote($remote) {
467
-		$remote = substr($remote, strpos($remote, '://') + 3);
468
-
469
-		return rtrim($remote, '/');
470
-	}
471
-
472
-
473
-	/**
474
-	 * @NoCSRFRequired
475
-	 * @PublicPage
476
-	 *
477
-	 * federated share was revoked, either by the owner or the re-sharer
478
-	 *
479
-	 * @param int $id
480
-	 * @return Http\DataResponse
481
-	 * @throws OCSBadRequestException
482
-	 */
483
-	public function revoke($id) {
484
-		$token = $this->request->getParam('token');
485
-
486
-		$share = $this->federatedShareProvider->getShareById($id);
487
-
488
-		if ($this->verifyShare($share, $token)) {
489
-			$this->federatedShareProvider->removeShareFromTable($share);
490
-			return new Http\DataResponse();
491
-		}
492
-
493
-		throw new OCSBadRequestException();
494
-	}
495
-
496
-	/**
497
-	 * get share
498
-	 *
499
-	 * @param int $id
500
-	 * @param string $token
501
-	 * @return array|bool
502
-	 */
503
-	protected function getShare($id, $token) {
504
-		$query = $this->connection->getQueryBuilder();
505
-		$query->select('*')->from($this->shareTable)
506
-			->where($query->expr()->eq('token', $query->createNamedParameter($token)))
507
-			->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
508
-			->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
509
-
510
-		$result = $query->execute()->fetchAll();
511
-
512
-		if (!empty($result) && isset($result[0])) {
513
-			return $result[0];
514
-		}
515
-
516
-		return false;
517
-	}
518
-
519
-	/**
520
-	 * get file
521
-	 *
522
-	 * @param string $user
523
-	 * @param int $fileSource
524
-	 * @return array with internal path of the file and a absolute link to it
525
-	 */
526
-	private function getFile($user, $fileSource) {
527
-		\OC_Util::setupFS($user);
528
-
529
-		try {
530
-			$file = \OC\Files\Filesystem::getPath($fileSource);
531
-		} catch (NotFoundException $e) {
532
-			$file = null;
533
-		}
534
-		$args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
535
-		$link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
536
-
537
-		return array($file, $link);
538
-
539
-	}
540
-
541
-	/**
542
-	 * check if server-to-server sharing is enabled
543
-	 *
544
-	 * @param bool $incoming
545
-	 * @return bool
546
-	 */
547
-	private function isS2SEnabled($incoming = false) {
548
-
549
-		$result = \OCP\App::isEnabled('files_sharing');
550
-
551
-		if ($incoming) {
552
-			$result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
553
-		} else {
554
-			$result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
555
-		}
556
-
557
-		return $result;
558
-	}
559
-
560
-	/**
561
-	 * check if we got the right share
562
-	 *
563
-	 * @param Share\IShare $share
564
-	 * @param string $token
565
-	 * @return bool
566
-	 */
567
-	protected function verifyShare(Share\IShare $share, $token) {
568
-		if (
569
-			$share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
570
-			$share->getToken() === $token
571
-		) {
572
-			return true;
573
-		}
574
-
575
-		return false;
576
-	}
577
-
578
-	/**
579
-	 * @NoCSRFRequired
580
-	 * @PublicPage
581
-	 *
582
-	 * update share information to keep federated re-shares in sync
583
-	 *
584
-	 * @param int $id
585
-	 * @return Http\DataResponse
586
-	 * @throws OCSBadRequestException
587
-	 */
588
-	public function updatePermissions($id) {
589
-		$token = $this->request->getParam('token', null);
590
-		$permissions = $this->request->getParam('permissions', null);
591
-
592
-		try {
593
-			$share = $this->federatedShareProvider->getShareById($id);
594
-		} catch (Share\Exceptions\ShareNotFound $e) {
595
-			throw new OCSBadRequestException();
596
-		}
597
-
598
-		$validPermission = ctype_digit($permissions);
599
-		$validToken = $this->verifyShare($share, $token);
600
-		if ($validPermission && $validToken) {
601
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
602
-		} else {
603
-			throw new OCSBadRequestException();
604
-		}
605
-
606
-		return new Http\DataResponse();
607
-	}
608
-
609
-	/**
610
-	 * update permissions in database
611
-	 *
612
-	 * @param IShare $share
613
-	 * @param int $permissions
614
-	 */
615
-	protected function updatePermissionsInDatabase(IShare $share, $permissions) {
616
-		$query = $this->connection->getQueryBuilder();
617
-		$query->update('share')
618
-			->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
619
-			->set('permissions', $query->createNamedParameter($permissions))
620
-			->execute();
621
-	}
622
-
623
-	/**
624
-	 * @NoCSRFRequired
625
-	 * @PublicPage
626
-	 *
627
-	 * change the owner of a server-to-server share
628
-	 *
629
-	 * @param int $id
630
-	 * @return Http\DataResponse
631
-	 * @throws \InvalidArgumentException
632
-	 * @throws OCSException
633
-	 */
634
-	public function move($id) {
635
-
636
-		if (!$this->isS2SEnabled()) {
637
-			throw new OCSException('Server does not support federated cloud sharing', 503);
638
-		}
639
-
640
-		$token = $this->request->getParam('token');
641
-		$remote = $this->request->getParam('remote');
642
-		$newRemoteId = $this->request->getParam('remote_id', $id);
643
-		$cloudId = $this->cloudIdManager->resolveCloudId($remote);
644
-
645
-		$qb = $this->connection->getQueryBuilder();
646
-		$query = $qb->update('share_external')
647
-			->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
648
-			->set('owner', $qb->createNamedParameter($cloudId->getUser()))
649
-			->set('remote_id', $qb->createNamedParameter($newRemoteId))
650
-			->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
651
-			->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
652
-		$affected = $query->execute();
653
-
654
-		if ($affected > 0) {
655
-			return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
656
-		} else {
657
-			throw new OCSBadRequestException('Share not found or token invalid');
658
-		}
659
-	}
53
+    /** @var FederatedShareProvider */
54
+    private $federatedShareProvider;
55
+
56
+    /** @var IDBConnection */
57
+    private $connection;
58
+
59
+    /** @var Share\IManager */
60
+    private $shareManager;
61
+
62
+    /** @var Notifications */
63
+    private $notifications;
64
+
65
+    /** @var AddressHandler */
66
+    private $addressHandler;
67
+
68
+    /** @var  IUserManager */
69
+    private $userManager;
70
+
71
+    /** @var string */
72
+    private $shareTable = 'share';
73
+
74
+    /** @var ICloudIdManager */
75
+    private $cloudIdManager;
76
+
77
+    /**
78
+     * Server2Server constructor.
79
+     *
80
+     * @param string $appName
81
+     * @param IRequest $request
82
+     * @param FederatedShareProvider $federatedShareProvider
83
+     * @param IDBConnection $connection
84
+     * @param Share\IManager $shareManager
85
+     * @param Notifications $notifications
86
+     * @param AddressHandler $addressHandler
87
+     * @param IUserManager $userManager
88
+     * @param ICloudIdManager $cloudIdManager
89
+     */
90
+    public function __construct($appName,
91
+                                IRequest $request,
92
+                                FederatedShareProvider $federatedShareProvider,
93
+                                IDBConnection $connection,
94
+                                Share\IManager $shareManager,
95
+                                Notifications $notifications,
96
+                                AddressHandler $addressHandler,
97
+                                IUserManager $userManager,
98
+                                ICloudIdManager $cloudIdManager
99
+    ) {
100
+        parent::__construct($appName, $request);
101
+
102
+        $this->federatedShareProvider = $federatedShareProvider;
103
+        $this->connection = $connection;
104
+        $this->shareManager = $shareManager;
105
+        $this->notifications = $notifications;
106
+        $this->addressHandler = $addressHandler;
107
+        $this->userManager = $userManager;
108
+        $this->cloudIdManager = $cloudIdManager;
109
+    }
110
+
111
+    /**
112
+     * @NoCSRFRequired
113
+     * @PublicPage
114
+     *
115
+     * create a new share
116
+     *
117
+     * @return Http\DataResponse
118
+     * @throws OCSException
119
+     */
120
+    public function createShare() {
121
+
122
+        if (!$this->isS2SEnabled(true)) {
123
+            throw new OCSException('Server does not support federated cloud sharing', 503);
124
+        }
125
+
126
+        $remote = isset($_POST['remote']) ? $_POST['remote'] : null;
127
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
128
+        $name = isset($_POST['name']) ? $_POST['name'] : null;
129
+        $owner = isset($_POST['owner']) ? $_POST['owner'] : null;
130
+        $sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
131
+        $shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
132
+        $remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
133
+        $sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
134
+        $ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
135
+
136
+        if ($remote && $token && $name && $owner && $remoteId && $shareWith) {
137
+
138
+            if (!\OCP\Util::isValidFileName($name)) {
139
+                throw new OCSException('The mountpoint name contains invalid characters.', 400);
140
+            }
141
+
142
+            // FIXME this should be a method in the user management instead
143
+            \OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
144
+            \OCP\Util::emitHook(
145
+                '\OCA\Files_Sharing\API\Server2Server',
146
+                'preLoginNameUsedAsUserName',
147
+                array('uid' => &$shareWith)
148
+            );
149
+            \OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
150
+
151
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
152
+                throw new OCSException('User does not exists', 400);
153
+            }
154
+
155
+            \OC_Util::setupFS($shareWith);
156
+
157
+            $externalManager = new \OCA\Files_Sharing\External\Manager(
158
+                    \OC::$server->getDatabaseConnection(),
159
+                    \OC\Files\Filesystem::getMountManager(),
160
+                    \OC\Files\Filesystem::getLoader(),
161
+                    \OC::$server->getHTTPClientService(),
162
+                    \OC::$server->getNotificationManager(),
163
+                    \OC::$server->query(\OCP\OCS\IDiscoveryService::class),
164
+                    $shareWith
165
+                );
166
+
167
+            try {
168
+                $externalManager->addShare($remote, $token, '', $name, $owner, false, $shareWith, $remoteId);
169
+                $shareId = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share_external');
170
+
171
+                if ($ownerFederatedId === null) {
172
+                    $ownerFederatedId = $this->cloudIdManager->getCloudId($owner, $this->cleanupRemote($remote))->getId();
173
+                }
174
+                // if the owner of the share and the initiator are the same user
175
+                // we also complete the federated share ID for the initiator
176
+                if ($sharedByFederatedId === null && $owner === $sharedBy) {
177
+                    $sharedByFederatedId = $ownerFederatedId;
178
+                }
179
+
180
+                $event = \OC::$server->getActivityManager()->generateEvent();
181
+                $event->setApp('files_sharing')
182
+                    ->setType('remote_share')
183
+                    ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
184
+                    ->setAffectedUser($shareWith)
185
+                    ->setObject('remote_share', (int)$shareId, $name);
186
+                \OC::$server->getActivityManager()->publish($event);
187
+
188
+                $urlGenerator = \OC::$server->getURLGenerator();
189
+
190
+                $notificationManager = \OC::$server->getNotificationManager();
191
+                $notification = $notificationManager->createNotification();
192
+                $notification->setApp('files_sharing')
193
+                    ->setUser($shareWith)
194
+                    ->setDateTime(new \DateTime())
195
+                    ->setObject('remote_share', $shareId)
196
+                    ->setSubject('remote_share', [$ownerFederatedId, $sharedByFederatedId, trim($name, '/')]);
197
+
198
+                $declineAction = $notification->createAction();
199
+                $declineAction->setLabel('decline')
200
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
201
+                $notification->addAction($declineAction);
202
+
203
+                $acceptAction = $notification->createAction();
204
+                $acceptAction->setLabel('accept')
205
+                    ->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
206
+                $notification->addAction($acceptAction);
207
+
208
+                $notificationManager->notify($notification);
209
+
210
+                return new Http\DataResponse();
211
+            } catch (\Exception $e) {
212
+                \OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
213
+                throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
214
+            }
215
+        }
216
+
217
+        throw new OCSException('server can not add remote share, missing parameter', 400);
218
+    }
219
+
220
+    /**
221
+     * @NoCSRFRequired
222
+     * @PublicPage
223
+     *
224
+     * create re-share on behalf of another user
225
+     *
226
+     * @param int $id
227
+     * @return Http\DataResponse
228
+     * @throws OCSBadRequestException
229
+     * @throws OCSForbiddenException
230
+     * @throws OCSNotFoundException
231
+     */
232
+    public function reShare($id) {
233
+
234
+        $token = $this->request->getParam('token', null);
235
+        $shareWith = $this->request->getParam('shareWith', null);
236
+        $permission = (int)$this->request->getParam('permission', null);
237
+        $remoteId = (int)$this->request->getParam('remoteId', null);
238
+
239
+        if ($id === null ||
240
+            $token === null ||
241
+            $shareWith === null ||
242
+            $permission === null ||
243
+            $remoteId === null
244
+        ) {
245
+            throw new OCSBadRequestException();
246
+        }
247
+
248
+        try {
249
+            $share = $this->federatedShareProvider->getShareById($id);
250
+        } catch (Share\Exceptions\ShareNotFound $e) {
251
+            throw new OCSNotFoundException();
252
+        }
253
+
254
+        // don't allow to share a file back to the owner
255
+        list($user, $remote) = $this->addressHandler->splitUserRemote($shareWith);
256
+        $owner = $share->getShareOwner();
257
+        $currentServer = $this->addressHandler->generateRemoteURL();
258
+        if ($this->addressHandler->compareAddresses($user, $remote, $owner, $currentServer)) {
259
+            throw new OCSForbiddenException();
260
+        }
261
+
262
+        if ($this->verifyShare($share, $token)) {
263
+
264
+            // check if re-sharing is allowed
265
+            if ($share->getPermissions() | ~Constants::PERMISSION_SHARE) {
266
+                $share->setPermissions($share->getPermissions() & $permission);
267
+                // the recipient of the initial share is now the initiator for the re-share
268
+                $share->setSharedBy($share->getSharedWith());
269
+                $share->setSharedWith($shareWith);
270
+                try {
271
+                    $result = $this->federatedShareProvider->create($share);
272
+                    $this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
273
+                    return new Http\DataResponse([
274
+                        'token' => $result->getToken(),
275
+                        'remoteId' => $result->getId()
276
+                    ]);
277
+                } catch (\Exception $e) {
278
+                    throw new OCSBadRequestException();
279
+                }
280
+            } else {
281
+                throw new OCSForbiddenException();
282
+            }
283
+        }
284
+        throw new OCSBadRequestException();
285
+    }
286
+
287
+    /**
288
+     * @NoCSRFRequired
289
+     * @PublicPage
290
+     *
291
+     * accept server-to-server share
292
+     *
293
+     * @param int $id
294
+     * @return Http\DataResponse
295
+     * @throws OCSException
296
+     */
297
+    public function acceptShare($id) {
298
+
299
+        if (!$this->isS2SEnabled()) {
300
+            throw new OCSException('Server does not support federated cloud sharing', 503);
301
+        }
302
+
303
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
304
+
305
+        try {
306
+            $share = $this->federatedShareProvider->getShareById($id);
307
+        } catch (Share\Exceptions\ShareNotFound $e) {
308
+            return new Http\DataResponse();
309
+        }
310
+
311
+        if ($this->verifyShare($share, $token)) {
312
+            $this->executeAcceptShare($share);
313
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
314
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
315
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
316
+                $this->notifications->sendAcceptShare($remote, $remoteId, $share->getToken());
317
+            }
318
+        }
319
+
320
+        return new Http\DataResponse();
321
+    }
322
+
323
+    protected function executeAcceptShare(Share\IShare $share) {
324
+        $fileId = (int) $share->getNode()->getId();
325
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
326
+
327
+        $event = \OC::$server->getActivityManager()->generateEvent();
328
+        $event->setApp('files_sharing')
329
+            ->setType('remote_share')
330
+            ->setAffectedUser($this->getCorrectUid($share))
331
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_ACCEPTED, [$share->getSharedWith(), [$fileId => $file]])
332
+            ->setObject('files', $fileId, $file)
333
+            ->setLink($link);
334
+        \OC::$server->getActivityManager()->publish($event);
335
+    }
336
+
337
+    /**
338
+     * @NoCSRFRequired
339
+     * @PublicPage
340
+     *
341
+     * decline server-to-server share
342
+     *
343
+     * @param int $id
344
+     * @return Http\DataResponse
345
+     * @throws OCSException
346
+     */
347
+    public function declineShare($id) {
348
+
349
+        if (!$this->isS2SEnabled()) {
350
+            throw new OCSException('Server does not support federated cloud sharing', 503);
351
+        }
352
+
353
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
354
+
355
+        try {
356
+            $share = $this->federatedShareProvider->getShareById($id);
357
+        } catch (Share\Exceptions\ShareNotFound $e) {
358
+            return new Http\DataResponse();
359
+        }
360
+
361
+        if ($this->verifyShare($share, $token)) {
362
+            if ($share->getShareOwner() !== $share->getSharedBy()) {
363
+                list(, $remote) = $this->addressHandler->splitUserRemote($share->getSharedBy());
364
+                $remoteId = $this->federatedShareProvider->getRemoteId($share);
365
+                $this->notifications->sendDeclineShare($remote, $remoteId, $share->getToken());
366
+            }
367
+            $this->executeDeclineShare($share);
368
+        }
369
+
370
+        return new Http\DataResponse();
371
+    }
372
+
373
+    /**
374
+     * delete declined share and create a activity
375
+     *
376
+     * @param Share\IShare $share
377
+     */
378
+    protected function executeDeclineShare(Share\IShare $share) {
379
+        $this->federatedShareProvider->removeShareFromTable($share);
380
+        $fileId = (int) $share->getNode()->getId();
381
+        list($file, $link) = $this->getFile($this->getCorrectUid($share), $fileId);
382
+
383
+        $event = \OC::$server->getActivityManager()->generateEvent();
384
+        $event->setApp('files_sharing')
385
+            ->setType('remote_share')
386
+            ->setAffectedUser($this->getCorrectUid($share))
387
+            ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_DECLINED, [$share->getSharedWith(), [$fileId => $file]])
388
+            ->setObject('files', $fileId, $file)
389
+            ->setLink($link);
390
+        \OC::$server->getActivityManager()->publish($event);
391
+
392
+    }
393
+
394
+    /**
395
+     * check if we are the initiator or the owner of a re-share and return the correct UID
396
+     *
397
+     * @param Share\IShare $share
398
+     * @return string
399
+     */
400
+    protected function getCorrectUid(Share\IShare $share) {
401
+        if ($this->userManager->userExists($share->getShareOwner())) {
402
+            return $share->getShareOwner();
403
+        }
404
+
405
+        return $share->getSharedBy();
406
+    }
407
+
408
+    /**
409
+     * @NoCSRFRequired
410
+     * @PublicPage
411
+     *
412
+     * remove server-to-server share if it was unshared by the owner
413
+     *
414
+     * @param int $id
415
+     * @return Http\DataResponse
416
+     * @throws OCSException
417
+     */
418
+    public function unshare($id) {
419
+
420
+        if (!$this->isS2SEnabled()) {
421
+            throw new OCSException('Server does not support federated cloud sharing', 503);
422
+        }
423
+
424
+        $token = isset($_POST['token']) ? $_POST['token'] : null;
425
+
426
+        $query = \OCP\DB::prepare('SELECT * FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
427
+        $query->execute(array($id, $token));
428
+        $share = $query->fetchRow();
429
+
430
+        if ($token && $id && !empty($share)) {
431
+
432
+            $remote = $this->cleanupRemote($share['remote']);
433
+
434
+            $owner = $this->cloudIdManager->getCloudId($share['owner'], $remote);
435
+            $mountpoint = $share['mountpoint'];
436
+            $user = $share['user'];
437
+
438
+            $query = \OCP\DB::prepare('DELETE FROM `*PREFIX*share_external` WHERE `remote_id` = ? AND `share_token` = ?');
439
+            $query->execute(array($id, $token));
440
+
441
+            if ($share['accepted']) {
442
+                $path = trim($mountpoint, '/');
443
+            } else {
444
+                $path = trim($share['name'], '/');
445
+            }
446
+
447
+            $notificationManager = \OC::$server->getNotificationManager();
448
+            $notification = $notificationManager->createNotification();
449
+            $notification->setApp('files_sharing')
450
+                ->setUser($share['user'])
451
+                ->setObject('remote_share', (int)$share['id']);
452
+            $notificationManager->markProcessed($notification);
453
+
454
+            $event = \OC::$server->getActivityManager()->generateEvent();
455
+            $event->setApp('files_sharing')
456
+                ->setType('remote_share')
457
+                ->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
458
+                ->setAffectedUser($user)
459
+                ->setObject('remote_share', (int)$share['id'], $path);
460
+            \OC::$server->getActivityManager()->publish($event);
461
+        }
462
+
463
+        return new Http\DataResponse();
464
+    }
465
+
466
+    private function cleanupRemote($remote) {
467
+        $remote = substr($remote, strpos($remote, '://') + 3);
468
+
469
+        return rtrim($remote, '/');
470
+    }
471
+
472
+
473
+    /**
474
+     * @NoCSRFRequired
475
+     * @PublicPage
476
+     *
477
+     * federated share was revoked, either by the owner or the re-sharer
478
+     *
479
+     * @param int $id
480
+     * @return Http\DataResponse
481
+     * @throws OCSBadRequestException
482
+     */
483
+    public function revoke($id) {
484
+        $token = $this->request->getParam('token');
485
+
486
+        $share = $this->federatedShareProvider->getShareById($id);
487
+
488
+        if ($this->verifyShare($share, $token)) {
489
+            $this->federatedShareProvider->removeShareFromTable($share);
490
+            return new Http\DataResponse();
491
+        }
492
+
493
+        throw new OCSBadRequestException();
494
+    }
495
+
496
+    /**
497
+     * get share
498
+     *
499
+     * @param int $id
500
+     * @param string $token
501
+     * @return array|bool
502
+     */
503
+    protected function getShare($id, $token) {
504
+        $query = $this->connection->getQueryBuilder();
505
+        $query->select('*')->from($this->shareTable)
506
+            ->where($query->expr()->eq('token', $query->createNamedParameter($token)))
507
+            ->andWhere($query->expr()->eq('share_type', $query->createNamedParameter(FederatedShareProvider::SHARE_TYPE_REMOTE)))
508
+            ->andWhere($query->expr()->eq('id', $query->createNamedParameter($id)));
509
+
510
+        $result = $query->execute()->fetchAll();
511
+
512
+        if (!empty($result) && isset($result[0])) {
513
+            return $result[0];
514
+        }
515
+
516
+        return false;
517
+    }
518
+
519
+    /**
520
+     * get file
521
+     *
522
+     * @param string $user
523
+     * @param int $fileSource
524
+     * @return array with internal path of the file and a absolute link to it
525
+     */
526
+    private function getFile($user, $fileSource) {
527
+        \OC_Util::setupFS($user);
528
+
529
+        try {
530
+            $file = \OC\Files\Filesystem::getPath($fileSource);
531
+        } catch (NotFoundException $e) {
532
+            $file = null;
533
+        }
534
+        $args = \OC\Files\Filesystem::is_dir($file) ? array('dir' => $file) : array('dir' => dirname($file), 'scrollto' => $file);
535
+        $link = \OCP\Util::linkToAbsolute('files', 'index.php', $args);
536
+
537
+        return array($file, $link);
538
+
539
+    }
540
+
541
+    /**
542
+     * check if server-to-server sharing is enabled
543
+     *
544
+     * @param bool $incoming
545
+     * @return bool
546
+     */
547
+    private function isS2SEnabled($incoming = false) {
548
+
549
+        $result = \OCP\App::isEnabled('files_sharing');
550
+
551
+        if ($incoming) {
552
+            $result = $result && $this->federatedShareProvider->isIncomingServer2serverShareEnabled();
553
+        } else {
554
+            $result = $result && $this->federatedShareProvider->isOutgoingServer2serverShareEnabled();
555
+        }
556
+
557
+        return $result;
558
+    }
559
+
560
+    /**
561
+     * check if we got the right share
562
+     *
563
+     * @param Share\IShare $share
564
+     * @param string $token
565
+     * @return bool
566
+     */
567
+    protected function verifyShare(Share\IShare $share, $token) {
568
+        if (
569
+            $share->getShareType() === FederatedShareProvider::SHARE_TYPE_REMOTE &&
570
+            $share->getToken() === $token
571
+        ) {
572
+            return true;
573
+        }
574
+
575
+        return false;
576
+    }
577
+
578
+    /**
579
+     * @NoCSRFRequired
580
+     * @PublicPage
581
+     *
582
+     * update share information to keep federated re-shares in sync
583
+     *
584
+     * @param int $id
585
+     * @return Http\DataResponse
586
+     * @throws OCSBadRequestException
587
+     */
588
+    public function updatePermissions($id) {
589
+        $token = $this->request->getParam('token', null);
590
+        $permissions = $this->request->getParam('permissions', null);
591
+
592
+        try {
593
+            $share = $this->federatedShareProvider->getShareById($id);
594
+        } catch (Share\Exceptions\ShareNotFound $e) {
595
+            throw new OCSBadRequestException();
596
+        }
597
+
598
+        $validPermission = ctype_digit($permissions);
599
+        $validToken = $this->verifyShare($share, $token);
600
+        if ($validPermission && $validToken) {
601
+            $this->updatePermissionsInDatabase($share, (int)$permissions);
602
+        } else {
603
+            throw new OCSBadRequestException();
604
+        }
605
+
606
+        return new Http\DataResponse();
607
+    }
608
+
609
+    /**
610
+     * update permissions in database
611
+     *
612
+     * @param IShare $share
613
+     * @param int $permissions
614
+     */
615
+    protected function updatePermissionsInDatabase(IShare $share, $permissions) {
616
+        $query = $this->connection->getQueryBuilder();
617
+        $query->update('share')
618
+            ->where($query->expr()->eq('id', $query->createNamedParameter($share->getId())))
619
+            ->set('permissions', $query->createNamedParameter($permissions))
620
+            ->execute();
621
+    }
622
+
623
+    /**
624
+     * @NoCSRFRequired
625
+     * @PublicPage
626
+     *
627
+     * change the owner of a server-to-server share
628
+     *
629
+     * @param int $id
630
+     * @return Http\DataResponse
631
+     * @throws \InvalidArgumentException
632
+     * @throws OCSException
633
+     */
634
+    public function move($id) {
635
+
636
+        if (!$this->isS2SEnabled()) {
637
+            throw new OCSException('Server does not support federated cloud sharing', 503);
638
+        }
639
+
640
+        $token = $this->request->getParam('token');
641
+        $remote = $this->request->getParam('remote');
642
+        $newRemoteId = $this->request->getParam('remote_id', $id);
643
+        $cloudId = $this->cloudIdManager->resolveCloudId($remote);
644
+
645
+        $qb = $this->connection->getQueryBuilder();
646
+        $query = $qb->update('share_external')
647
+            ->set('remote', $qb->createNamedParameter($cloudId->getRemote()))
648
+            ->set('owner', $qb->createNamedParameter($cloudId->getUser()))
649
+            ->set('remote_id', $qb->createNamedParameter($newRemoteId))
650
+            ->where($qb->expr()->eq('remote_id', $qb->createNamedParameter($id)))
651
+            ->andWhere($qb->expr()->eq('share_token', $qb->createNamedParameter($token)));
652
+        $affected = $query->execute();
653
+
654
+        if ($affected > 0) {
655
+            return new Http\DataResponse(['remote' => $cloudId->getRemote(), 'owner' => $cloudId->getUser()]);
656
+        } else {
657
+            throw new OCSBadRequestException('Share not found or token invalid');
658
+        }
659
+    }
660 660
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
 		$owner = isset($_POST['owner']) ? $_POST['owner'] : null;
130 130
 		$sharedBy = isset($_POST['sharedBy']) ? $_POST['sharedBy'] : null;
131 131
 		$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
132
-		$remoteId = isset($_POST['remoteId']) ? (int)$_POST['remoteId'] : null;
132
+		$remoteId = isset($_POST['remoteId']) ? (int) $_POST['remoteId'] : null;
133 133
 		$sharedByFederatedId = isset($_POST['sharedByFederatedId']) ? $_POST['sharedByFederatedId'] : null;
134 134
 		$ownerFederatedId = isset($_POST['ownerFederatedId']) ? $_POST['ownerFederatedId'] : null;
135 135
 
@@ -140,13 +140,13 @@  discard block
 block discarded – undo
140 140
 			}
141 141
 
142 142
 			// FIXME this should be a method in the user management instead
143
-			\OCP\Util::writeLog('files_sharing', 'shareWith before, ' . $shareWith, \OCP\Util::DEBUG);
143
+			\OCP\Util::writeLog('files_sharing', 'shareWith before, '.$shareWith, \OCP\Util::DEBUG);
144 144
 			\OCP\Util::emitHook(
145 145
 				'\OCA\Files_Sharing\API\Server2Server',
146 146
 				'preLoginNameUsedAsUserName',
147 147
 				array('uid' => &$shareWith)
148 148
 			);
149
-			\OCP\Util::writeLog('files_sharing', 'shareWith after, ' . $shareWith, \OCP\Util::DEBUG);
149
+			\OCP\Util::writeLog('files_sharing', 'shareWith after, '.$shareWith, \OCP\Util::DEBUG);
150 150
 
151 151
 			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
152 152
 				throw new OCSException('User does not exists', 400);
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 					->setType('remote_share')
183 183
 					->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_RECEIVED, [$ownerFederatedId, trim($name, '/')])
184 184
 					->setAffectedUser($shareWith)
185
-					->setObject('remote_share', (int)$shareId, $name);
185
+					->setObject('remote_share', (int) $shareId, $name);
186 186
 				\OC::$server->getActivityManager()->publish($event);
187 187
 
188 188
 				$urlGenerator = \OC::$server->getURLGenerator();
@@ -197,20 +197,20 @@  discard block
 block discarded – undo
197 197
 
198 198
 				$declineAction = $notification->createAction();
199 199
 				$declineAction->setLabel('decline')
200
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'DELETE');
200
+					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'DELETE');
201 201
 				$notification->addAction($declineAction);
202 202
 
203 203
 				$acceptAction = $notification->createAction();
204 204
 				$acceptAction->setLabel('accept')
205
-					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/' . $shareId)), 'POST');
205
+					->setLink($urlGenerator->getAbsoluteURL($urlGenerator->linkTo('', 'ocs/v2.php/apps/files_sharing/api/v1/remote_shares/pending/'.$shareId)), 'POST');
206 206
 				$notification->addAction($acceptAction);
207 207
 
208 208
 				$notificationManager->notify($notification);
209 209
 
210 210
 				return new Http\DataResponse();
211 211
 			} catch (\Exception $e) {
212
-				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, ' . $e->getMessage(), \OCP\Util::ERROR);
213
-				throw new OCSException('internal server error, was not able to add share from ' . $remote, 500);
212
+				\OCP\Util::writeLog('files_sharing', 'server can not add remote share, '.$e->getMessage(), \OCP\Util::ERROR);
213
+				throw new OCSException('internal server error, was not able to add share from '.$remote, 500);
214 214
 			}
215 215
 		}
216 216
 
@@ -233,8 +233,8 @@  discard block
 block discarded – undo
233 233
 
234 234
 		$token = $this->request->getParam('token', null);
235 235
 		$shareWith = $this->request->getParam('shareWith', null);
236
-		$permission = (int)$this->request->getParam('permission', null);
237
-		$remoteId = (int)$this->request->getParam('remoteId', null);
236
+		$permission = (int) $this->request->getParam('permission', null);
237
+		$remoteId = (int) $this->request->getParam('remoteId', null);
238 238
 
239 239
 		if ($id === null ||
240 240
 			$token === null ||
@@ -269,7 +269,7 @@  discard block
 block discarded – undo
269 269
 				$share->setSharedWith($shareWith);
270 270
 				try {
271 271
 					$result = $this->federatedShareProvider->create($share);
272
-					$this->federatedShareProvider->storeRemoteId((int)$result->getId(), $remoteId);
272
+					$this->federatedShareProvider->storeRemoteId((int) $result->getId(), $remoteId);
273 273
 					return new Http\DataResponse([
274 274
 						'token' => $result->getToken(),
275 275
 						'remoteId' => $result->getId()
@@ -448,7 +448,7 @@  discard block
 block discarded – undo
448 448
 			$notification = $notificationManager->createNotification();
449 449
 			$notification->setApp('files_sharing')
450 450
 				->setUser($share['user'])
451
-				->setObject('remote_share', (int)$share['id']);
451
+				->setObject('remote_share', (int) $share['id']);
452 452
 			$notificationManager->markProcessed($notification);
453 453
 
454 454
 			$event = \OC::$server->getActivityManager()->generateEvent();
@@ -456,7 +456,7 @@  discard block
 block discarded – undo
456 456
 				->setType('remote_share')
457 457
 				->setSubject(RemoteShares::SUBJECT_REMOTE_SHARE_UNSHARED, [$owner->getId(), $path])
458 458
 				->setAffectedUser($user)
459
-				->setObject('remote_share', (int)$share['id'], $path);
459
+				->setObject('remote_share', (int) $share['id'], $path);
460 460
 			\OC::$server->getActivityManager()->publish($event);
461 461
 		}
462 462
 
@@ -598,7 +598,7 @@  discard block
 block discarded – undo
598 598
 		$validPermission = ctype_digit($permissions);
599 599
 		$validToken = $this->verifyShare($share, $token);
600 600
 		if ($validPermission && $validToken) {
601
-			$this->updatePermissionsInDatabase($share, (int)$permissions);
601
+			$this->updatePermissionsInDatabase($share, (int) $permissions);
602 602
 		} else {
603 603
 			throw new OCSBadRequestException();
604 604
 		}
Please login to merge, or discard this patch.
lib/public/User.php 2 patches
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -47,93 +47,93 @@
 block discarded – undo
47 47
  * @deprecated 13.0.0
48 48
  */
49 49
 class User {
50
-	/**
51
-	 * Get the user id of the user currently logged in.
52
-	 * @return string uid or false
53
-	 * @deprecated 8.0.0 Use \OC::$server->getUserSession()->getUser()->getUID()
54
-	 * @since 5.0.0
55
-	 */
56
-	public static function getUser() {
57
-		return \OC_User::getUser();
58
-	}
50
+    /**
51
+     * Get the user id of the user currently logged in.
52
+     * @return string uid or false
53
+     * @deprecated 8.0.0 Use \OC::$server->getUserSession()->getUser()->getUID()
54
+     * @since 5.0.0
55
+     */
56
+    public static function getUser() {
57
+        return \OC_User::getUser();
58
+    }
59 59
 
60
-	/**
61
-	 * Get a list of all users
62
-	 * @param string $search search pattern
63
-	 * @param int|null $limit
64
-	 * @param int|null $offset
65
-	 * @return array an array of all uids
66
-	 * @deprecated 8.1.0 use method search() of \OCP\IUserManager - \OC::$server->getUserManager()
67
-	 * @since 5.0.0
68
-	 */
69
-	public static function getUsers( $search = '', $limit = null, $offset = null ) {
70
-		return \OC_User::getUsers( $search, $limit, $offset );
71
-	}
60
+    /**
61
+     * Get a list of all users
62
+     * @param string $search search pattern
63
+     * @param int|null $limit
64
+     * @param int|null $offset
65
+     * @return array an array of all uids
66
+     * @deprecated 8.1.0 use method search() of \OCP\IUserManager - \OC::$server->getUserManager()
67
+     * @since 5.0.0
68
+     */
69
+    public static function getUsers( $search = '', $limit = null, $offset = null ) {
70
+        return \OC_User::getUsers( $search, $limit, $offset );
71
+    }
72 72
 
73
-	/**
74
-	 * Get the user display name of the user currently logged in.
75
-	 * @param string|null $user user id or null for current user
76
-	 * @return string display name
77
-	 * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
78
-	 *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
79
-	 * @since 5.0.0
80
-	 */
81
-	public static function getDisplayName( $user = null ) {
82
-		return \OC_User::getDisplayName( $user );
83
-	}
73
+    /**
74
+     * Get the user display name of the user currently logged in.
75
+     * @param string|null $user user id or null for current user
76
+     * @return string display name
77
+     * @deprecated 8.1.0 fetch \OCP\IUser (has getDisplayName()) by using method
78
+     *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
79
+     * @since 5.0.0
80
+     */
81
+    public static function getDisplayName( $user = null ) {
82
+        return \OC_User::getDisplayName( $user );
83
+    }
84 84
 
85
-	/**
86
-	 * Get a list of all display names and user ids.
87
-	 * @param string $search search pattern
88
-	 * @param int|null $limit
89
-	 * @param int|null $offset
90
-	 * @return array an array of all display names (value) and the correspondig uids (key)
91
-	 * @deprecated 8.1.0 use method searchDisplayName() of \OCP\IUserManager - \OC::$server->getUserManager()
92
-	 * @since 5.0.0
93
-	 * @suppress PhanDeprecatedFunction
94
-	 */
95
-	public static function getDisplayNames( $search = '', $limit = null, $offset = null ) {
96
-		return \OC_User::getDisplayNames( $search, $limit, $offset );
97
-	}
85
+    /**
86
+     * Get a list of all display names and user ids.
87
+     * @param string $search search pattern
88
+     * @param int|null $limit
89
+     * @param int|null $offset
90
+     * @return array an array of all display names (value) and the correspondig uids (key)
91
+     * @deprecated 8.1.0 use method searchDisplayName() of \OCP\IUserManager - \OC::$server->getUserManager()
92
+     * @since 5.0.0
93
+     * @suppress PhanDeprecatedFunction
94
+     */
95
+    public static function getDisplayNames( $search = '', $limit = null, $offset = null ) {
96
+        return \OC_User::getDisplayNames( $search, $limit, $offset );
97
+    }
98 98
 
99
-	/**
100
-	 * Check if the user is logged in
101
-	 * @return boolean
102
-	 * @since 5.0.0
103
-	 * @deprecated 13.0.0 Use annotation based ACLs from the AppFramework instead
104
-	 */
105
-	public static function isLoggedIn() {
106
-		return \OC::$server->getUserSession()->isLoggedIn();
107
-	}
99
+    /**
100
+     * Check if the user is logged in
101
+     * @return boolean
102
+     * @since 5.0.0
103
+     * @deprecated 13.0.0 Use annotation based ACLs from the AppFramework instead
104
+     */
105
+    public static function isLoggedIn() {
106
+        return \OC::$server->getUserSession()->isLoggedIn();
107
+    }
108 108
 
109
-	/**
110
-	 * Check if a user exists
111
-	 * @param string $uid the username
112
-	 * @param string $excludingBackend (default none)
113
-	 * @return boolean
114
-	 * @deprecated 8.1.0 use method userExists() of \OCP\IUserManager - \OC::$server->getUserManager()
115
-	 * @since 5.0.0
116
-	 */
117
-	public static function userExists($uid, $excludingBackend = null) {
118
-		return \OC::$server->getUserManager()->userExists($uid);
119
-	}
109
+    /**
110
+     * Check if a user exists
111
+     * @param string $uid the username
112
+     * @param string $excludingBackend (default none)
113
+     * @return boolean
114
+     * @deprecated 8.1.0 use method userExists() of \OCP\IUserManager - \OC::$server->getUserManager()
115
+     * @since 5.0.0
116
+     */
117
+    public static function userExists($uid, $excludingBackend = null) {
118
+        return \OC::$server->getUserManager()->userExists($uid);
119
+    }
120 120
 
121
-	/**
122
-	 * Check if the user is a admin, redirects to home if not
123
-	 * @since 5.0.0
124
-	 * @deprecated 13.0.0 Use annotation based ACLs from the AppFramework instead
125
-	 */
126
-	public static function checkAdminUser() {
127
-		\OC_Util::checkAdminUser();
128
-	}
121
+    /**
122
+     * Check if the user is a admin, redirects to home if not
123
+     * @since 5.0.0
124
+     * @deprecated 13.0.0 Use annotation based ACLs from the AppFramework instead
125
+     */
126
+    public static function checkAdminUser() {
127
+        \OC_Util::checkAdminUser();
128
+    }
129 129
 
130
-	/**
131
-	 * Check if the user is logged in, redirects to home if not. With
132
-	 * redirect URL parameter to the request URI.
133
-	 * @since 5.0.0
134
-	 * @deprecated 13.0.0 Use annotation based ACLs from the AppFramework instead
135
-	 */
136
-	public static function checkLoggedIn() {
137
-		\OC_Util::checkLoggedIn();
138
-	}
130
+    /**
131
+     * Check if the user is logged in, redirects to home if not. With
132
+     * redirect URL parameter to the request URI.
133
+     * @since 5.0.0
134
+     * @deprecated 13.0.0 Use annotation based ACLs from the AppFramework instead
135
+     */
136
+    public static function checkLoggedIn() {
137
+        \OC_Util::checkLoggedIn();
138
+    }
139 139
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -66,8 +66,8 @@  discard block
 block discarded – undo
66 66
 	 * @deprecated 8.1.0 use method search() of \OCP\IUserManager - \OC::$server->getUserManager()
67 67
 	 * @since 5.0.0
68 68
 	 */
69
-	public static function getUsers( $search = '', $limit = null, $offset = null ) {
70
-		return \OC_User::getUsers( $search, $limit, $offset );
69
+	public static function getUsers($search = '', $limit = null, $offset = null) {
70
+		return \OC_User::getUsers($search, $limit, $offset);
71 71
 	}
72 72
 
73 73
 	/**
@@ -78,8 +78,8 @@  discard block
 block discarded – undo
78 78
 	 *                   get() of \OCP\IUserManager - \OC::$server->getUserManager()
79 79
 	 * @since 5.0.0
80 80
 	 */
81
-	public static function getDisplayName( $user = null ) {
82
-		return \OC_User::getDisplayName( $user );
81
+	public static function getDisplayName($user = null) {
82
+		return \OC_User::getDisplayName($user);
83 83
 	}
84 84
 
85 85
 	/**
@@ -92,8 +92,8 @@  discard block
 block discarded – undo
92 92
 	 * @since 5.0.0
93 93
 	 * @suppress PhanDeprecatedFunction
94 94
 	 */
95
-	public static function getDisplayNames( $search = '', $limit = null, $offset = null ) {
96
-		return \OC_User::getDisplayNames( $search, $limit, $offset );
95
+	public static function getDisplayNames($search = '', $limit = null, $offset = null) {
96
+		return \OC_User::getDisplayNames($search, $limit, $offset);
97 97
 	}
98 98
 
99 99
 	/**
Please login to merge, or discard this patch.
lib/private/Share/Share.php 1 patch
Indentation   +2180 added lines, -2180 removed lines patch added patch discarded remove patch
@@ -57,2194 +57,2194 @@
 block discarded – undo
57 57
  */
58 58
 class Share extends Constants {
59 59
 
60
-	/** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
61
-	 * Construct permissions for share() and setPermissions with Or (|) e.g.
62
-	 * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
63
-	 *
64
-	 * Check if permission is granted with And (&) e.g. Check if delete is
65
-	 * granted: if ($permissions & PERMISSION_DELETE)
66
-	 *
67
-	 * Remove permissions with And (&) and Not (~) e.g. Remove the update
68
-	 * permission: $permissions &= ~PERMISSION_UPDATE
69
-	 *
70
-	 * Apps are required to handle permissions on their own, this class only
71
-	 * stores and manages the permissions of shares
72
-	 * @see lib/public/constants.php
73
-	 */
74
-
75
-	/**
76
-	 * Register a sharing backend class that implements OCP\Share_Backend for an item type
77
-	 * @param string $itemType Item type
78
-	 * @param string $class Backend class
79
-	 * @param string $collectionOf (optional) Depends on item type
80
-	 * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
81
-	 * @return boolean true if backend is registered or false if error
82
-	 */
83
-	public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
84
-		if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
85
-			if (!isset(self::$backendTypes[$itemType])) {
86
-				self::$backendTypes[$itemType] = array(
87
-					'class' => $class,
88
-					'collectionOf' => $collectionOf,
89
-					'supportedFileExtensions' => $supportedFileExtensions
90
-				);
91
-				if(count(self::$backendTypes) === 1) {
92
-					Util::addScript('core', 'merged-share-backend');
93
-					\OC_Util::addStyle('core', 'share');
94
-				}
95
-				return true;
96
-			}
97
-			\OCP\Util::writeLog('OCP\Share',
98
-				'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
99
-				.' is already registered for '.$itemType,
100
-				\OCP\Util::WARN);
101
-		}
102
-		return false;
103
-	}
104
-
105
-	/**
106
-	 * Get the items of item type shared with the current user
107
-	 * @param string $itemType
108
-	 * @param int $format (optional) Format type must be defined by the backend
109
-	 * @param mixed $parameters (optional)
110
-	 * @param int $limit Number of items to return (optional) Returns all by default
111
-	 * @param boolean $includeCollections (optional)
112
-	 * @return mixed Return depends on format
113
-	 */
114
-	public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
115
-											  $parameters = null, $limit = -1, $includeCollections = false) {
116
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
117
-			$parameters, $limit, $includeCollections);
118
-	}
119
-
120
-	/**
121
-	 * Get the items of item type shared with a user
122
-	 * @param string $itemType
123
-	 * @param string $user id for which user we want the shares
124
-	 * @param int $format (optional) Format type must be defined by the backend
125
-	 * @param mixed $parameters (optional)
126
-	 * @param int $limit Number of items to return (optional) Returns all by default
127
-	 * @param boolean $includeCollections (optional)
128
-	 * @return mixed Return depends on format
129
-	 */
130
-	public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
131
-												  $parameters = null, $limit = -1, $includeCollections = false) {
132
-		return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
133
-			$parameters, $limit, $includeCollections);
134
-	}
135
-
136
-	/**
137
-	 * Get the item of item type shared with a given user by source
138
-	 * @param string $itemType
139
-	 * @param string $itemSource
140
-	 * @param string $user User to whom the item was shared
141
-	 * @param string $owner Owner of the share
142
-	 * @param int $shareType only look for a specific share type
143
-	 * @return array Return list of items with file_target, permissions and expiration
144
-	 */
145
-	public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
146
-		$shares = array();
147
-		$fileDependent = false;
148
-
149
-		$where = 'WHERE';
150
-		$fileDependentWhere = '';
151
-		if ($itemType === 'file' || $itemType === 'folder') {
152
-			$fileDependent = true;
153
-			$column = 'file_source';
154
-			$fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
155
-			$fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
156
-		} else {
157
-			$column = 'item_source';
158
-		}
159
-
160
-		$select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
161
-
162
-		$where .= ' `' . $column . '` = ? AND `item_type` = ? ';
163
-		$arguments = array($itemSource, $itemType);
164
-		// for link shares $user === null
165
-		if ($user !== null) {
166
-			$where .= ' AND `share_with` = ? ';
167
-			$arguments[] = $user;
168
-		}
169
-
170
-		if ($shareType !== null) {
171
-			$where .= ' AND `share_type` = ? ';
172
-			$arguments[] = $shareType;
173
-		}
174
-
175
-		if ($owner !== null) {
176
-			$where .= ' AND `uid_owner` = ? ';
177
-			$arguments[] = $owner;
178
-		}
179
-
180
-		$query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
181
-
182
-		$result = \OC_DB::executeAudited($query, $arguments);
183
-
184
-		while ($row = $result->fetchRow()) {
185
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
186
-				continue;
187
-			}
188
-			if ($fileDependent && (int)$row['file_parent'] === -1) {
189
-				// if it is a mount point we need to get the path from the mount manager
190
-				$mountManager = \OC\Files\Filesystem::getMountManager();
191
-				$mountPoint = $mountManager->findByStorageId($row['storage_id']);
192
-				if (!empty($mountPoint)) {
193
-					$path = $mountPoint[0]->getMountPoint();
194
-					$path = trim($path, '/');
195
-					$path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
196
-					$row['path'] = $path;
197
-				} else {
198
-					\OC::$server->getLogger()->warning(
199
-						'Could not resolve mount point for ' . $row['storage_id'],
200
-						['app' => 'OCP\Share']
201
-					);
202
-				}
203
-			}
204
-			$shares[] = $row;
205
-		}
206
-
207
-		//if didn't found a result than let's look for a group share.
208
-		if(empty($shares) && $user !== null) {
209
-			$userObject = \OC::$server->getUserManager()->get($user);
210
-			$groups = [];
211
-			if ($userObject) {
212
-				$groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
213
-			}
214
-
215
-			if (!empty($groups)) {
216
-				$where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
217
-				$arguments = array($itemSource, $itemType, $groups);
218
-				$types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
219
-
220
-				if ($owner !== null) {
221
-					$where .= ' AND `uid_owner` = ?';
222
-					$arguments[] = $owner;
223
-					$types[] = null;
224
-				}
225
-
226
-				// TODO: inject connection, hopefully one day in the future when this
227
-				// class isn't static anymore...
228
-				$conn = \OC::$server->getDatabaseConnection();
229
-				$result = $conn->executeQuery(
230
-					'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
231
-					$arguments,
232
-					$types
233
-				);
234
-
235
-				while ($row = $result->fetch()) {
236
-					$shares[] = $row;
237
-				}
238
-			}
239
-		}
240
-
241
-		return $shares;
242
-
243
-	}
244
-
245
-	/**
246
-	 * Get the item of item type shared with the current user by source
247
-	 * @param string $itemType
248
-	 * @param string $itemSource
249
-	 * @param int $format (optional) Format type must be defined by the backend
250
-	 * @param mixed $parameters
251
-	 * @param boolean $includeCollections
252
-	 * @param string $shareWith (optional) define against which user should be checked, default: current user
253
-	 * @return array
254
-	 */
255
-	public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
256
-													 $parameters = null, $includeCollections = false, $shareWith = null) {
257
-		$shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
258
-		return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
259
-			$parameters, 1, $includeCollections, true);
260
-	}
261
-
262
-	/**
263
-	 * Based on the given token the share information will be returned - password protected shares will be verified
264
-	 * @param string $token
265
-	 * @param bool $checkPasswordProtection
266
-	 * @return array|boolean false will be returned in case the token is unknown or unauthorized
267
-	 */
268
-	public static function getShareByToken($token, $checkPasswordProtection = true) {
269
-		$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
270
-		$result = $query->execute(array($token));
271
-		if ($result === false) {
272
-			\OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
273
-		}
274
-		$row = $result->fetchRow();
275
-		if ($row === false) {
276
-			return false;
277
-		}
278
-		if (is_array($row) and self::expireItem($row)) {
279
-			return false;
280
-		}
281
-
282
-		// password protected shares need to be authenticated
283
-		if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
284
-			return false;
285
-		}
286
-
287
-		return $row;
288
-	}
289
-
290
-	/**
291
-	 * resolves reshares down to the last real share
292
-	 * @param array $linkItem
293
-	 * @return array file owner
294
-	 */
295
-	public static function resolveReShare($linkItem)
296
-	{
297
-		if (isset($linkItem['parent'])) {
298
-			$parent = $linkItem['parent'];
299
-			while (isset($parent)) {
300
-				$query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
301
-				$item = $query->execute(array($parent))->fetchRow();
302
-				if (isset($item['parent'])) {
303
-					$parent = $item['parent'];
304
-				} else {
305
-					return $item;
306
-				}
307
-			}
308
-		}
309
-		return $linkItem;
310
-	}
311
-
312
-
313
-	/**
314
-	 * Get the shared items of item type owned by the current user
315
-	 * @param string $itemType
316
-	 * @param int $format (optional) Format type must be defined by the backend
317
-	 * @param mixed $parameters
318
-	 * @param int $limit Number of items to return (optional) Returns all by default
319
-	 * @param boolean $includeCollections
320
-	 * @return mixed Return depends on format
321
-	 */
322
-	public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
323
-										  $limit = -1, $includeCollections = false) {
324
-		return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
325
-			$parameters, $limit, $includeCollections);
326
-	}
327
-
328
-	/**
329
-	 * Get the shared item of item type owned by the current user
330
-	 * @param string $itemType
331
-	 * @param string $itemSource
332
-	 * @param int $format (optional) Format type must be defined by the backend
333
-	 * @param mixed $parameters
334
-	 * @param boolean $includeCollections
335
-	 * @return mixed Return depends on format
336
-	 */
337
-	public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
338
-										 $parameters = null, $includeCollections = false) {
339
-		return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
340
-			$parameters, -1, $includeCollections);
341
-	}
342
-
343
-	/**
344
-	 * Share an item with a user, group, or via private link
345
-	 * @param string $itemType
346
-	 * @param string $itemSource
347
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
348
-	 * @param string $shareWith User or group the item is being shared with
349
-	 * @param int $permissions CRUDS
350
-	 * @param string $itemSourceName
351
-	 * @param \DateTime|null $expirationDate
352
-	 * @param bool|null $passwordChanged
353
-	 * @return boolean|string Returns true on success or false on failure, Returns token on success for links
354
-	 * @throws \OC\HintException when the share type is remote and the shareWith is invalid
355
-	 * @throws \Exception
356
-	 * @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
357
-	 */
358
-	public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
359
-
360
-		$backend = self::getBackend($itemType);
361
-		$l = \OC::$server->getL10N('lib');
362
-
363
-		if ($backend->isShareTypeAllowed($shareType) === false) {
364
-			$message = 'Sharing %s failed, because the backend does not allow shares from type %i';
365
-			$message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
366
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
367
-			throw new \Exception($message_t);
368
-		}
369
-
370
-		$uidOwner = \OC_User::getUser();
371
-		$shareWithinGroupOnly = self::shareWithGroupMembersOnly();
372
-
373
-		if (is_null($itemSourceName)) {
374
-			$itemSourceName = $itemSource;
375
-		}
376
-		$itemName = $itemSourceName;
377
-
378
-		// check if file can be shared
379
-		if ($itemType === 'file' or $itemType === 'folder') {
380
-			$path = \OC\Files\Filesystem::getPath($itemSource);
381
-			$itemName = $path;
382
-
383
-			// verify that the file exists before we try to share it
384
-			if (!$path) {
385
-				$message = 'Sharing %s failed, because the file does not exist';
386
-				$message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
387
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
388
-				throw new \Exception($message_t);
389
-			}
390
-			// verify that the user has share permission
391
-			if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
392
-				$message = 'You are not allowed to share %s';
393
-				$message_t = $l->t('You are not allowed to share %s', [$path]);
394
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
395
-				throw new \Exception($message_t);
396
-			}
397
-		}
398
-
399
-		//verify that we don't share a folder which already contains a share mount point
400
-		if ($itemType === 'folder') {
401
-			$path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
402
-			$mountManager = \OC\Files\Filesystem::getMountManager();
403
-			$mounts = $mountManager->findIn($path);
404
-			foreach ($mounts as $mount) {
405
-				if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
406
-					$message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
407
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
408
-					throw new \Exception($message);
409
-				}
410
-
411
-			}
412
-		}
413
-
414
-		// single file shares should never have delete permissions
415
-		if ($itemType === 'file') {
416
-			$permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
417
-		}
418
-
419
-		//Validate expirationDate
420
-		if ($expirationDate !== null) {
421
-			try {
422
-				/*
60
+    /** CRUDS permissions (Create, Read, Update, Delete, Share) using a bitmask
61
+     * Construct permissions for share() and setPermissions with Or (|) e.g.
62
+     * Give user read and update permissions: PERMISSION_READ | PERMISSION_UPDATE
63
+     *
64
+     * Check if permission is granted with And (&) e.g. Check if delete is
65
+     * granted: if ($permissions & PERMISSION_DELETE)
66
+     *
67
+     * Remove permissions with And (&) and Not (~) e.g. Remove the update
68
+     * permission: $permissions &= ~PERMISSION_UPDATE
69
+     *
70
+     * Apps are required to handle permissions on their own, this class only
71
+     * stores and manages the permissions of shares
72
+     * @see lib/public/constants.php
73
+     */
74
+
75
+    /**
76
+     * Register a sharing backend class that implements OCP\Share_Backend for an item type
77
+     * @param string $itemType Item type
78
+     * @param string $class Backend class
79
+     * @param string $collectionOf (optional) Depends on item type
80
+     * @param array $supportedFileExtensions (optional) List of supported file extensions if this item type depends on files
81
+     * @return boolean true if backend is registered or false if error
82
+     */
83
+    public static function registerBackend($itemType, $class, $collectionOf = null, $supportedFileExtensions = null) {
84
+        if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') == 'yes') {
85
+            if (!isset(self::$backendTypes[$itemType])) {
86
+                self::$backendTypes[$itemType] = array(
87
+                    'class' => $class,
88
+                    'collectionOf' => $collectionOf,
89
+                    'supportedFileExtensions' => $supportedFileExtensions
90
+                );
91
+                if(count(self::$backendTypes) === 1) {
92
+                    Util::addScript('core', 'merged-share-backend');
93
+                    \OC_Util::addStyle('core', 'share');
94
+                }
95
+                return true;
96
+            }
97
+            \OCP\Util::writeLog('OCP\Share',
98
+                'Sharing backend '.$class.' not registered, '.self::$backendTypes[$itemType]['class']
99
+                .' is already registered for '.$itemType,
100
+                \OCP\Util::WARN);
101
+        }
102
+        return false;
103
+    }
104
+
105
+    /**
106
+     * Get the items of item type shared with the current user
107
+     * @param string $itemType
108
+     * @param int $format (optional) Format type must be defined by the backend
109
+     * @param mixed $parameters (optional)
110
+     * @param int $limit Number of items to return (optional) Returns all by default
111
+     * @param boolean $includeCollections (optional)
112
+     * @return mixed Return depends on format
113
+     */
114
+    public static function getItemsSharedWith($itemType, $format = self::FORMAT_NONE,
115
+                                                $parameters = null, $limit = -1, $includeCollections = false) {
116
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, \OC_User::getUser(), null, $format,
117
+            $parameters, $limit, $includeCollections);
118
+    }
119
+
120
+    /**
121
+     * Get the items of item type shared with a user
122
+     * @param string $itemType
123
+     * @param string $user id for which user we want the shares
124
+     * @param int $format (optional) Format type must be defined by the backend
125
+     * @param mixed $parameters (optional)
126
+     * @param int $limit Number of items to return (optional) Returns all by default
127
+     * @param boolean $includeCollections (optional)
128
+     * @return mixed Return depends on format
129
+     */
130
+    public static function getItemsSharedWithUser($itemType, $user, $format = self::FORMAT_NONE,
131
+                                                    $parameters = null, $limit = -1, $includeCollections = false) {
132
+        return self::getItems($itemType, null, self::$shareTypeUserAndGroups, $user, null, $format,
133
+            $parameters, $limit, $includeCollections);
134
+    }
135
+
136
+    /**
137
+     * Get the item of item type shared with a given user by source
138
+     * @param string $itemType
139
+     * @param string $itemSource
140
+     * @param string $user User to whom the item was shared
141
+     * @param string $owner Owner of the share
142
+     * @param int $shareType only look for a specific share type
143
+     * @return array Return list of items with file_target, permissions and expiration
144
+     */
145
+    public static function getItemSharedWithUser($itemType, $itemSource, $user, $owner = null, $shareType = null) {
146
+        $shares = array();
147
+        $fileDependent = false;
148
+
149
+        $where = 'WHERE';
150
+        $fileDependentWhere = '';
151
+        if ($itemType === 'file' || $itemType === 'folder') {
152
+            $fileDependent = true;
153
+            $column = 'file_source';
154
+            $fileDependentWhere = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
155
+            $fileDependentWhere .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
156
+        } else {
157
+            $column = 'item_source';
158
+        }
159
+
160
+        $select = self::createSelectStatement(self::FORMAT_NONE, $fileDependent);
161
+
162
+        $where .= ' `' . $column . '` = ? AND `item_type` = ? ';
163
+        $arguments = array($itemSource, $itemType);
164
+        // for link shares $user === null
165
+        if ($user !== null) {
166
+            $where .= ' AND `share_with` = ? ';
167
+            $arguments[] = $user;
168
+        }
169
+
170
+        if ($shareType !== null) {
171
+            $where .= ' AND `share_type` = ? ';
172
+            $arguments[] = $shareType;
173
+        }
174
+
175
+        if ($owner !== null) {
176
+            $where .= ' AND `uid_owner` = ? ';
177
+            $arguments[] = $owner;
178
+        }
179
+
180
+        $query = \OC_DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` '. $fileDependentWhere . $where);
181
+
182
+        $result = \OC_DB::executeAudited($query, $arguments);
183
+
184
+        while ($row = $result->fetchRow()) {
185
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
186
+                continue;
187
+            }
188
+            if ($fileDependent && (int)$row['file_parent'] === -1) {
189
+                // if it is a mount point we need to get the path from the mount manager
190
+                $mountManager = \OC\Files\Filesystem::getMountManager();
191
+                $mountPoint = $mountManager->findByStorageId($row['storage_id']);
192
+                if (!empty($mountPoint)) {
193
+                    $path = $mountPoint[0]->getMountPoint();
194
+                    $path = trim($path, '/');
195
+                    $path = substr($path, strlen($owner) + 1); //normalize path to 'files/foo.txt`
196
+                    $row['path'] = $path;
197
+                } else {
198
+                    \OC::$server->getLogger()->warning(
199
+                        'Could not resolve mount point for ' . $row['storage_id'],
200
+                        ['app' => 'OCP\Share']
201
+                    );
202
+                }
203
+            }
204
+            $shares[] = $row;
205
+        }
206
+
207
+        //if didn't found a result than let's look for a group share.
208
+        if(empty($shares) && $user !== null) {
209
+            $userObject = \OC::$server->getUserManager()->get($user);
210
+            $groups = [];
211
+            if ($userObject) {
212
+                $groups = \OC::$server->getGroupManager()->getUserGroupIds($userObject);
213
+            }
214
+
215
+            if (!empty($groups)) {
216
+                $where = $fileDependentWhere . ' WHERE `' . $column . '` = ? AND `item_type` = ? AND `share_with` in (?)';
217
+                $arguments = array($itemSource, $itemType, $groups);
218
+                $types = array(null, null, IQueryBuilder::PARAM_STR_ARRAY);
219
+
220
+                if ($owner !== null) {
221
+                    $where .= ' AND `uid_owner` = ?';
222
+                    $arguments[] = $owner;
223
+                    $types[] = null;
224
+                }
225
+
226
+                // TODO: inject connection, hopefully one day in the future when this
227
+                // class isn't static anymore...
228
+                $conn = \OC::$server->getDatabaseConnection();
229
+                $result = $conn->executeQuery(
230
+                    'SELECT ' . $select . ' FROM `*PREFIX*share` ' . $where,
231
+                    $arguments,
232
+                    $types
233
+                );
234
+
235
+                while ($row = $result->fetch()) {
236
+                    $shares[] = $row;
237
+                }
238
+            }
239
+        }
240
+
241
+        return $shares;
242
+
243
+    }
244
+
245
+    /**
246
+     * Get the item of item type shared with the current user by source
247
+     * @param string $itemType
248
+     * @param string $itemSource
249
+     * @param int $format (optional) Format type must be defined by the backend
250
+     * @param mixed $parameters
251
+     * @param boolean $includeCollections
252
+     * @param string $shareWith (optional) define against which user should be checked, default: current user
253
+     * @return array
254
+     */
255
+    public static function getItemSharedWithBySource($itemType, $itemSource, $format = self::FORMAT_NONE,
256
+                                                        $parameters = null, $includeCollections = false, $shareWith = null) {
257
+        $shareWith = ($shareWith === null) ? \OC_User::getUser() : $shareWith;
258
+        return self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups, $shareWith, null, $format,
259
+            $parameters, 1, $includeCollections, true);
260
+    }
261
+
262
+    /**
263
+     * Based on the given token the share information will be returned - password protected shares will be verified
264
+     * @param string $token
265
+     * @param bool $checkPasswordProtection
266
+     * @return array|boolean false will be returned in case the token is unknown or unauthorized
267
+     */
268
+    public static function getShareByToken($token, $checkPasswordProtection = true) {
269
+        $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `token` = ?', 1);
270
+        $result = $query->execute(array($token));
271
+        if ($result === false) {
272
+            \OCP\Util::writeLog('OCP\Share', \OC_DB::getErrorMessage() . ', token=' . $token, \OCP\Util::ERROR);
273
+        }
274
+        $row = $result->fetchRow();
275
+        if ($row === false) {
276
+            return false;
277
+        }
278
+        if (is_array($row) and self::expireItem($row)) {
279
+            return false;
280
+        }
281
+
282
+        // password protected shares need to be authenticated
283
+        if ($checkPasswordProtection && !\OC\Share\Share::checkPasswordProtectedShare($row)) {
284
+            return false;
285
+        }
286
+
287
+        return $row;
288
+    }
289
+
290
+    /**
291
+     * resolves reshares down to the last real share
292
+     * @param array $linkItem
293
+     * @return array file owner
294
+     */
295
+    public static function resolveReShare($linkItem)
296
+    {
297
+        if (isset($linkItem['parent'])) {
298
+            $parent = $linkItem['parent'];
299
+            while (isset($parent)) {
300
+                $query = \OC_DB::prepare('SELECT * FROM `*PREFIX*share` WHERE `id` = ?', 1);
301
+                $item = $query->execute(array($parent))->fetchRow();
302
+                if (isset($item['parent'])) {
303
+                    $parent = $item['parent'];
304
+                } else {
305
+                    return $item;
306
+                }
307
+            }
308
+        }
309
+        return $linkItem;
310
+    }
311
+
312
+
313
+    /**
314
+     * Get the shared items of item type owned by the current user
315
+     * @param string $itemType
316
+     * @param int $format (optional) Format type must be defined by the backend
317
+     * @param mixed $parameters
318
+     * @param int $limit Number of items to return (optional) Returns all by default
319
+     * @param boolean $includeCollections
320
+     * @return mixed Return depends on format
321
+     */
322
+    public static function getItemsShared($itemType, $format = self::FORMAT_NONE, $parameters = null,
323
+                                            $limit = -1, $includeCollections = false) {
324
+        return self::getItems($itemType, null, null, null, \OC_User::getUser(), $format,
325
+            $parameters, $limit, $includeCollections);
326
+    }
327
+
328
+    /**
329
+     * Get the shared item of item type owned by the current user
330
+     * @param string $itemType
331
+     * @param string $itemSource
332
+     * @param int $format (optional) Format type must be defined by the backend
333
+     * @param mixed $parameters
334
+     * @param boolean $includeCollections
335
+     * @return mixed Return depends on format
336
+     */
337
+    public static function getItemShared($itemType, $itemSource, $format = self::FORMAT_NONE,
338
+                                            $parameters = null, $includeCollections = false) {
339
+        return self::getItems($itemType, $itemSource, null, null, \OC_User::getUser(), $format,
340
+            $parameters, -1, $includeCollections);
341
+    }
342
+
343
+    /**
344
+     * Share an item with a user, group, or via private link
345
+     * @param string $itemType
346
+     * @param string $itemSource
347
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
348
+     * @param string $shareWith User or group the item is being shared with
349
+     * @param int $permissions CRUDS
350
+     * @param string $itemSourceName
351
+     * @param \DateTime|null $expirationDate
352
+     * @param bool|null $passwordChanged
353
+     * @return boolean|string Returns true on success or false on failure, Returns token on success for links
354
+     * @throws \OC\HintException when the share type is remote and the shareWith is invalid
355
+     * @throws \Exception
356
+     * @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
357
+     */
358
+    public static function shareItem($itemType, $itemSource, $shareType, $shareWith, $permissions, $itemSourceName = null, \DateTime $expirationDate = null, $passwordChanged = null) {
359
+
360
+        $backend = self::getBackend($itemType);
361
+        $l = \OC::$server->getL10N('lib');
362
+
363
+        if ($backend->isShareTypeAllowed($shareType) === false) {
364
+            $message = 'Sharing %s failed, because the backend does not allow shares from type %i';
365
+            $message_t = $l->t('Sharing %s failed, because the backend does not allow shares from type %i', array($itemSourceName, $shareType));
366
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareType), \OCP\Util::DEBUG);
367
+            throw new \Exception($message_t);
368
+        }
369
+
370
+        $uidOwner = \OC_User::getUser();
371
+        $shareWithinGroupOnly = self::shareWithGroupMembersOnly();
372
+
373
+        if (is_null($itemSourceName)) {
374
+            $itemSourceName = $itemSource;
375
+        }
376
+        $itemName = $itemSourceName;
377
+
378
+        // check if file can be shared
379
+        if ($itemType === 'file' or $itemType === 'folder') {
380
+            $path = \OC\Files\Filesystem::getPath($itemSource);
381
+            $itemName = $path;
382
+
383
+            // verify that the file exists before we try to share it
384
+            if (!$path) {
385
+                $message = 'Sharing %s failed, because the file does not exist';
386
+                $message_t = $l->t('Sharing %s failed, because the file does not exist', array($itemSourceName));
387
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
388
+                throw new \Exception($message_t);
389
+            }
390
+            // verify that the user has share permission
391
+            if (!\OC\Files\Filesystem::isSharable($path) || \OCP\Util::isSharingDisabledForUser()) {
392
+                $message = 'You are not allowed to share %s';
393
+                $message_t = $l->t('You are not allowed to share %s', [$path]);
394
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $path), \OCP\Util::DEBUG);
395
+                throw new \Exception($message_t);
396
+            }
397
+        }
398
+
399
+        //verify that we don't share a folder which already contains a share mount point
400
+        if ($itemType === 'folder') {
401
+            $path = '/' . $uidOwner . '/files' . \OC\Files\Filesystem::getPath($itemSource) . '/';
402
+            $mountManager = \OC\Files\Filesystem::getMountManager();
403
+            $mounts = $mountManager->findIn($path);
404
+            foreach ($mounts as $mount) {
405
+                if ($mount->getStorage()->instanceOfStorage('\OCA\Files_Sharing\ISharedStorage')) {
406
+                    $message = 'Sharing "' . $itemSourceName . '" failed, because it contains files shared with you!';
407
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
408
+                    throw new \Exception($message);
409
+                }
410
+
411
+            }
412
+        }
413
+
414
+        // single file shares should never have delete permissions
415
+        if ($itemType === 'file') {
416
+            $permissions = (int)$permissions & ~\OCP\Constants::PERMISSION_DELETE;
417
+        }
418
+
419
+        //Validate expirationDate
420
+        if ($expirationDate !== null) {
421
+            try {
422
+                /*
423 423
 				 * Reuse the validateExpireDate.
424 424
 				 * We have to pass time() since the second arg is the time
425 425
 				 * the file was shared, since it is not shared yet we just use
426 426
 				 * the current time.
427 427
 				 */
428
-				$expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
429
-			} catch (\Exception $e) {
430
-				throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
431
-			}
432
-		}
433
-
434
-		// Verify share type and sharing conditions are met
435
-		if ($shareType === self::SHARE_TYPE_USER) {
436
-			if ($shareWith == $uidOwner) {
437
-				$message = 'Sharing %s failed, because you can not share with yourself';
438
-				$message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
439
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
440
-				throw new \Exception($message_t);
441
-			}
442
-			if (!\OC::$server->getUserManager()->userExists($shareWith)) {
443
-				$message = 'Sharing %s failed, because the user %s does not exist';
444
-				$message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
445
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
446
-				throw new \Exception($message_t);
447
-			}
448
-			if ($shareWithinGroupOnly) {
449
-				$userManager = \OC::$server->getUserManager();
450
-				$groupManager = \OC::$server->getGroupManager();
451
-				$userOwner = $userManager->get($uidOwner);
452
-				$userShareWith = $userManager->get($shareWith);
453
-				$groupsOwner = [];
454
-				$groupsShareWith = [];
455
-				if ($userOwner) {
456
-					$groupsOwner = $groupManager->getUserGroupIds($userOwner);
457
-				}
458
-				if ($userShareWith) {
459
-					$groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
460
-				}
461
-				$inGroup = array_intersect($groupsOwner, $groupsShareWith);
462
-				if (empty($inGroup)) {
463
-					$message = 'Sharing %s failed, because the user '
464
-						.'%s is not a member of any groups that %s is a member of';
465
-					$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));
466
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
467
-					throw new \Exception($message_t);
468
-				}
469
-			}
470
-			// Check if the item source is already shared with the user, either from the same owner or a different user
471
-			if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
472
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
473
-				// Only allow the same share to occur again if it is the same
474
-				// owner and is not a user share, this use case is for increasing
475
-				// permissions for a specific user
476
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
477
-					$message = 'Sharing %s failed, because this item is already shared with %s';
478
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
479
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
480
-					throw new \Exception($message_t);
481
-				}
482
-			}
483
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
484
-				$shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
485
-				// Only allow the same share to occur again if it is the same
486
-				// owner and is not a user share, this use case is for increasing
487
-				// permissions for a specific user
488
-				if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
489
-					$message = 'Sharing %s failed, because this item is already shared with user %s';
490
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
491
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
492
-					throw new \Exception($message_t);
493
-				}
494
-			}
495
-		} else if ($shareType === self::SHARE_TYPE_GROUP) {
496
-			if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
497
-				$message = 'Sharing %s failed, because the group %s does not exist';
498
-				$message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
499
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
500
-				throw new \Exception($message_t);
501
-			}
502
-			if ($shareWithinGroupOnly) {
503
-				$group = \OC::$server->getGroupManager()->get($shareWith);
504
-				$user = \OC::$server->getUserManager()->get($uidOwner);
505
-				if (!$group || !$user || !$group->inGroup($user)) {
506
-					$message = 'Sharing %s failed, because '
507
-						. '%s is not a member of the group %s';
508
-					$message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
509
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
510
-					throw new \Exception($message_t);
511
-				}
512
-			}
513
-			// Check if the item source is already shared with the group, either from the same owner or a different user
514
-			// The check for each user in the group is done inside the put() function
515
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
516
-				null, self::FORMAT_NONE, null, 1, true, true)) {
517
-
518
-				if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
519
-					$message = 'Sharing %s failed, because this item is already shared with %s';
520
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
521
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
522
-					throw new \Exception($message_t);
523
-				}
524
-			}
525
-			// Convert share with into an array with the keys group and users
526
-			$group = $shareWith;
527
-			$shareWith = array();
528
-			$shareWith['group'] = $group;
529
-
530
-
531
-			$groupObject = \OC::$server->getGroupManager()->get($group);
532
-			$userIds = [];
533
-			if ($groupObject) {
534
-				$users = $groupObject->searchUsers('', -1, 0);
535
-				foreach ($users as $user) {
536
-					$userIds[] = $user->getUID();
537
-				}
538
-			}
539
-
540
-			$shareWith['users'] = array_diff($userIds, array($uidOwner));
541
-		} else if ($shareType === self::SHARE_TYPE_LINK) {
542
-			$updateExistingShare = false;
543
-			if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
544
-
545
-				// IF the password is changed via the old ajax endpoint verify it before deleting the old share
546
-				if ($passwordChanged === true) {
547
-					self::verifyPassword($shareWith);
548
-				}
549
-
550
-				// when updating a link share
551
-				// FIXME Don't delete link if we update it
552
-				if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
553
-					$uidOwner, self::FORMAT_NONE, null, 1)) {
554
-					// remember old token
555
-					$oldToken = $checkExists['token'];
556
-					$oldPermissions = $checkExists['permissions'];
557
-					//delete the old share
558
-					Helper::delete($checkExists['id']);
559
-					$updateExistingShare = true;
560
-				}
561
-
562
-				if ($passwordChanged === null) {
563
-					// Generate hash of password - same method as user passwords
564
-					if (is_string($shareWith) && $shareWith !== '') {
565
-						self::verifyPassword($shareWith);
566
-						$shareWith = \OC::$server->getHasher()->hash($shareWith);
567
-					} else {
568
-						// reuse the already set password, but only if we change permissions
569
-						// otherwise the user disabled the password protection
570
-						if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
571
-							$shareWith = $checkExists['share_with'];
572
-						}
573
-					}
574
-				} else {
575
-					if ($passwordChanged === true) {
576
-						if (is_string($shareWith) && $shareWith !== '') {
577
-							self::verifyPassword($shareWith);
578
-							$shareWith = \OC::$server->getHasher()->hash($shareWith);
579
-						}
580
-					} else if ($updateExistingShare) {
581
-						$shareWith = $checkExists['share_with'];
582
-					}
583
-				}
584
-
585
-				if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
586
-					$message = 'You need to provide a password to create a public link, only protected links are allowed';
587
-					$message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
588
-					\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
589
-					throw new \Exception($message_t);
590
-				}
591
-
592
-				if ($updateExistingShare === false &&
593
-					self::isDefaultExpireDateEnabled() &&
594
-					empty($expirationDate)) {
595
-					$expirationDate = Helper::calcExpireDate();
596
-				}
597
-
598
-				// Generate token
599
-				if (isset($oldToken)) {
600
-					$token = $oldToken;
601
-				} else {
602
-					$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
603
-						\OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
604
-					);
605
-				}
606
-				$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
607
-					null, $token, $itemSourceName, $expirationDate);
608
-				if ($result) {
609
-					return $token;
610
-				} else {
611
-					return false;
612
-				}
613
-			}
614
-			$message = 'Sharing %s failed, because sharing with links is not allowed';
615
-			$message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
616
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
617
-			throw new \Exception($message_t);
618
-		} else if ($shareType === self::SHARE_TYPE_REMOTE) {
619
-
620
-			/*
428
+                $expirationDate = self::validateExpireDate($expirationDate->format('Y-m-d'), time(), $itemType, $itemSource);
429
+            } catch (\Exception $e) {
430
+                throw new \OC\HintException($e->getMessage(), $e->getMessage(), 404);
431
+            }
432
+        }
433
+
434
+        // Verify share type and sharing conditions are met
435
+        if ($shareType === self::SHARE_TYPE_USER) {
436
+            if ($shareWith == $uidOwner) {
437
+                $message = 'Sharing %s failed, because you can not share with yourself';
438
+                $message_t = $l->t('Sharing %s failed, because you can not share with yourself', [$itemName]);
439
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
440
+                throw new \Exception($message_t);
441
+            }
442
+            if (!\OC::$server->getUserManager()->userExists($shareWith)) {
443
+                $message = 'Sharing %s failed, because the user %s does not exist';
444
+                $message_t = $l->t('Sharing %s failed, because the user %s does not exist', array($itemSourceName, $shareWith));
445
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
446
+                throw new \Exception($message_t);
447
+            }
448
+            if ($shareWithinGroupOnly) {
449
+                $userManager = \OC::$server->getUserManager();
450
+                $groupManager = \OC::$server->getGroupManager();
451
+                $userOwner = $userManager->get($uidOwner);
452
+                $userShareWith = $userManager->get($shareWith);
453
+                $groupsOwner = [];
454
+                $groupsShareWith = [];
455
+                if ($userOwner) {
456
+                    $groupsOwner = $groupManager->getUserGroupIds($userOwner);
457
+                }
458
+                if ($userShareWith) {
459
+                    $groupsShareWith = $groupManager->getUserGroupIds($userShareWith);
460
+                }
461
+                $inGroup = array_intersect($groupsOwner, $groupsShareWith);
462
+                if (empty($inGroup)) {
463
+                    $message = 'Sharing %s failed, because the user '
464
+                        .'%s is not a member of any groups that %s is a member of';
465
+                    $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));
466
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemName, $shareWith, $uidOwner), \OCP\Util::DEBUG);
467
+                    throw new \Exception($message_t);
468
+                }
469
+            }
470
+            // Check if the item source is already shared with the user, either from the same owner or a different user
471
+            if ($checkExists = self::getItems($itemType, $itemSource, self::$shareTypeUserAndGroups,
472
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
473
+                // Only allow the same share to occur again if it is the same
474
+                // owner and is not a user share, this use case is for increasing
475
+                // permissions for a specific user
476
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
477
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
478
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
479
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
480
+                    throw new \Exception($message_t);
481
+                }
482
+            }
483
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_USER,
484
+                $shareWith, null, self::FORMAT_NONE, null, 1, true, true)) {
485
+                // Only allow the same share to occur again if it is the same
486
+                // owner and is not a user share, this use case is for increasing
487
+                // permissions for a specific user
488
+                if ($checkExists['uid_owner'] != $uidOwner || $checkExists['share_type'] == $shareType) {
489
+                    $message = 'Sharing %s failed, because this item is already shared with user %s';
490
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with user %s', array($itemSourceName, $shareWith));
491
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::ERROR);
492
+                    throw new \Exception($message_t);
493
+                }
494
+            }
495
+        } else if ($shareType === self::SHARE_TYPE_GROUP) {
496
+            if (!\OC::$server->getGroupManager()->groupExists($shareWith)) {
497
+                $message = 'Sharing %s failed, because the group %s does not exist';
498
+                $message_t = $l->t('Sharing %s failed, because the group %s does not exist', array($itemSourceName, $shareWith));
499
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
500
+                throw new \Exception($message_t);
501
+            }
502
+            if ($shareWithinGroupOnly) {
503
+                $group = \OC::$server->getGroupManager()->get($shareWith);
504
+                $user = \OC::$server->getUserManager()->get($uidOwner);
505
+                if (!$group || !$user || !$group->inGroup($user)) {
506
+                    $message = 'Sharing %s failed, because '
507
+                        . '%s is not a member of the group %s';
508
+                    $message_t = $l->t('Sharing %s failed, because %s is not a member of the group %s', array($itemSourceName, $uidOwner, $shareWith));
509
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner, $shareWith), \OCP\Util::DEBUG);
510
+                    throw new \Exception($message_t);
511
+                }
512
+            }
513
+            // Check if the item source is already shared with the group, either from the same owner or a different user
514
+            // The check for each user in the group is done inside the put() function
515
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_GROUP, $shareWith,
516
+                null, self::FORMAT_NONE, null, 1, true, true)) {
517
+
518
+                if ($checkExists['share_with'] === $shareWith && $checkExists['share_type'] === \OCP\Share::SHARE_TYPE_GROUP) {
519
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
520
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
521
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
522
+                    throw new \Exception($message_t);
523
+                }
524
+            }
525
+            // Convert share with into an array with the keys group and users
526
+            $group = $shareWith;
527
+            $shareWith = array();
528
+            $shareWith['group'] = $group;
529
+
530
+
531
+            $groupObject = \OC::$server->getGroupManager()->get($group);
532
+            $userIds = [];
533
+            if ($groupObject) {
534
+                $users = $groupObject->searchUsers('', -1, 0);
535
+                foreach ($users as $user) {
536
+                    $userIds[] = $user->getUID();
537
+                }
538
+            }
539
+
540
+            $shareWith['users'] = array_diff($userIds, array($uidOwner));
541
+        } else if ($shareType === self::SHARE_TYPE_LINK) {
542
+            $updateExistingShare = false;
543
+            if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') == 'yes') {
544
+
545
+                // IF the password is changed via the old ajax endpoint verify it before deleting the old share
546
+                if ($passwordChanged === true) {
547
+                    self::verifyPassword($shareWith);
548
+                }
549
+
550
+                // when updating a link share
551
+                // FIXME Don't delete link if we update it
552
+                if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_LINK, null,
553
+                    $uidOwner, self::FORMAT_NONE, null, 1)) {
554
+                    // remember old token
555
+                    $oldToken = $checkExists['token'];
556
+                    $oldPermissions = $checkExists['permissions'];
557
+                    //delete the old share
558
+                    Helper::delete($checkExists['id']);
559
+                    $updateExistingShare = true;
560
+                }
561
+
562
+                if ($passwordChanged === null) {
563
+                    // Generate hash of password - same method as user passwords
564
+                    if (is_string($shareWith) && $shareWith !== '') {
565
+                        self::verifyPassword($shareWith);
566
+                        $shareWith = \OC::$server->getHasher()->hash($shareWith);
567
+                    } else {
568
+                        // reuse the already set password, but only if we change permissions
569
+                        // otherwise the user disabled the password protection
570
+                        if ($checkExists && (int)$permissions !== (int)$oldPermissions) {
571
+                            $shareWith = $checkExists['share_with'];
572
+                        }
573
+                    }
574
+                } else {
575
+                    if ($passwordChanged === true) {
576
+                        if (is_string($shareWith) && $shareWith !== '') {
577
+                            self::verifyPassword($shareWith);
578
+                            $shareWith = \OC::$server->getHasher()->hash($shareWith);
579
+                        }
580
+                    } else if ($updateExistingShare) {
581
+                        $shareWith = $checkExists['share_with'];
582
+                    }
583
+                }
584
+
585
+                if (\OCP\Util::isPublicLinkPasswordRequired() && empty($shareWith)) {
586
+                    $message = 'You need to provide a password to create a public link, only protected links are allowed';
587
+                    $message_t = $l->t('You need to provide a password to create a public link, only protected links are allowed');
588
+                    \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
589
+                    throw new \Exception($message_t);
590
+                }
591
+
592
+                if ($updateExistingShare === false &&
593
+                    self::isDefaultExpireDateEnabled() &&
594
+                    empty($expirationDate)) {
595
+                    $expirationDate = Helper::calcExpireDate();
596
+                }
597
+
598
+                // Generate token
599
+                if (isset($oldToken)) {
600
+                    $token = $oldToken;
601
+                } else {
602
+                    $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH,
603
+                        \OCP\Security\ISecureRandom::CHAR_HUMAN_READABLE
604
+                    );
605
+                }
606
+                $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions,
607
+                    null, $token, $itemSourceName, $expirationDate);
608
+                if ($result) {
609
+                    return $token;
610
+                } else {
611
+                    return false;
612
+                }
613
+            }
614
+            $message = 'Sharing %s failed, because sharing with links is not allowed';
615
+            $message_t = $l->t('Sharing %s failed, because sharing with links is not allowed', array($itemSourceName));
616
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
617
+            throw new \Exception($message_t);
618
+        } else if ($shareType === self::SHARE_TYPE_REMOTE) {
619
+
620
+            /*
621 621
 			 * Check if file is not already shared with the remote user
622 622
 			 */
623
-			if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
624
-				$shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
625
-					$message = 'Sharing %s failed, because this item is already shared with %s';
626
-					$message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
627
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
628
-					throw new \Exception($message_t);
629
-			}
630
-
631
-			// don't allow federated shares if source and target server are the same
632
-			list($user, $remote) = Helper::splitUserRemote($shareWith);
633
-			$currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
634
-			$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
635
-			if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
636
-				$message = 'Not allowed to create a federated share with the same user.';
637
-				$message_t = $l->t('Not allowed to create a federated share with the same user');
638
-				\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
639
-				throw new \Exception($message_t);
640
-			}
641
-
642
-			$token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
643
-				\OCP\Security\ISecureRandom::CHAR_DIGITS);
644
-
645
-			$shareWith = $user . '@' . $remote;
646
-			$shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
647
-
648
-			$send = false;
649
-			if ($shareId) {
650
-				$send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
651
-			}
652
-
653
-			if ($send === false) {
654
-				$currentUser = \OC::$server->getUserSession()->getUser()->getUID();
655
-				self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
656
-				$message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
657
-				throw new \Exception($message_t);
658
-			}
659
-
660
-			return $send;
661
-		} else {
662
-			// Future share types need to include their own conditions
663
-			$message = 'Share type %s is not valid for %s';
664
-			$message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
665
-			\OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
666
-			throw new \Exception($message_t);
667
-		}
668
-
669
-		// Put the item into the database
670
-		$result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
671
-
672
-		return $result ? true : false;
673
-	}
674
-
675
-	/**
676
-	 * Unshare an item from a user, group, or delete a private link
677
-	 * @param string $itemType
678
-	 * @param string $itemSource
679
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
680
-	 * @param string $shareWith User or group the item is being shared with
681
-	 * @param string $owner owner of the share, if null the current user is used
682
-	 * @return boolean true on success or false on failure
683
-	 */
684
-	public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
685
-
686
-		// check if it is a valid itemType
687
-		self::getBackend($itemType);
688
-
689
-		$items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
690
-
691
-		$toDelete = array();
692
-		$newParent = null;
693
-		$currentUser = $owner ? $owner : \OC_User::getUser();
694
-		foreach ($items as $item) {
695
-			// delete the item with the expected share_type and owner
696
-			if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
697
-				$toDelete = $item;
698
-				// if there is more then one result we don't have to delete the children
699
-				// but update their parent. For group shares the new parent should always be
700
-				// the original group share and not the db entry with the unique name
701
-			} else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
702
-				$newParent = $item['parent'];
703
-			} else {
704
-				$newParent = $item['id'];
705
-			}
706
-		}
707
-
708
-		if (!empty($toDelete)) {
709
-			self::unshareItem($toDelete, $newParent);
710
-			return true;
711
-		}
712
-		return false;
713
-	}
714
-
715
-	/**
716
-	 * sent status if users got informed by mail about share
717
-	 * @param string $itemType
718
-	 * @param string $itemSource
719
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
720
-	 * @param string $recipient with whom was the file shared
721
-	 * @param boolean $status
722
-	 */
723
-	public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
724
-		$status = $status ? 1 : 0;
725
-
726
-		$query = \OC_DB::prepare(
727
-			'UPDATE `*PREFIX*share`
623
+            if ($checkExists = self::getItems($itemType, $itemSource, self::SHARE_TYPE_REMOTE,
624
+                $shareWith, $uidOwner, self::FORMAT_NONE, null, 1, true, true)) {
625
+                    $message = 'Sharing %s failed, because this item is already shared with %s';
626
+                    $message_t = $l->t('Sharing %s failed, because this item is already shared with %s', array($itemSourceName, $shareWith));
627
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
628
+                    throw new \Exception($message_t);
629
+            }
630
+
631
+            // don't allow federated shares if source and target server are the same
632
+            list($user, $remote) = Helper::splitUserRemote($shareWith);
633
+            $currentServer = self::removeProtocolFromUrl(\OC::$server->getURLGenerator()->getAbsoluteURL('/'));
634
+            $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
635
+            if (Helper::isSameUserOnSameServer($user, $remote, $currentUser, $currentServer)) {
636
+                $message = 'Not allowed to create a federated share with the same user.';
637
+                $message_t = $l->t('Not allowed to create a federated share with the same user');
638
+                \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::DEBUG);
639
+                throw new \Exception($message_t);
640
+            }
641
+
642
+            $token = \OC::$server->getSecureRandom()->generate(self::TOKEN_LENGTH, \OCP\Security\ISecureRandom::CHAR_LOWER . \OCP\Security\ISecureRandom::CHAR_UPPER .
643
+                \OCP\Security\ISecureRandom::CHAR_DIGITS);
644
+
645
+            $shareWith = $user . '@' . $remote;
646
+            $shareId = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, $token, $itemSourceName);
647
+
648
+            $send = false;
649
+            if ($shareId) {
650
+                $send = self::sendRemoteShare($token, $shareWith, $itemSourceName, $shareId, $uidOwner);
651
+            }
652
+
653
+            if ($send === false) {
654
+                $currentUser = \OC::$server->getUserSession()->getUser()->getUID();
655
+                self::unshare($itemType, $itemSource, $shareType, $shareWith, $currentUser);
656
+                $message_t = $l->t('Sharing %s failed, could not find %s, maybe the server is currently unreachable.', array($itemSourceName, $shareWith));
657
+                throw new \Exception($message_t);
658
+            }
659
+
660
+            return $send;
661
+        } else {
662
+            // Future share types need to include their own conditions
663
+            $message = 'Share type %s is not valid for %s';
664
+            $message_t = $l->t('Share type %s is not valid for %s', array($shareType, $itemSource));
665
+            \OCP\Util::writeLog('OCP\Share', sprintf($message, $shareType, $itemSource), \OCP\Util::DEBUG);
666
+            throw new \Exception($message_t);
667
+        }
668
+
669
+        // Put the item into the database
670
+        $result = self::put($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, null, null, $itemSourceName, $expirationDate);
671
+
672
+        return $result ? true : false;
673
+    }
674
+
675
+    /**
676
+     * Unshare an item from a user, group, or delete a private link
677
+     * @param string $itemType
678
+     * @param string $itemSource
679
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
680
+     * @param string $shareWith User or group the item is being shared with
681
+     * @param string $owner owner of the share, if null the current user is used
682
+     * @return boolean true on success or false on failure
683
+     */
684
+    public static function unshare($itemType, $itemSource, $shareType, $shareWith, $owner = null) {
685
+
686
+        // check if it is a valid itemType
687
+        self::getBackend($itemType);
688
+
689
+        $items = self::getItemSharedWithUser($itemType, $itemSource, $shareWith, $owner, $shareType);
690
+
691
+        $toDelete = array();
692
+        $newParent = null;
693
+        $currentUser = $owner ? $owner : \OC_User::getUser();
694
+        foreach ($items as $item) {
695
+            // delete the item with the expected share_type and owner
696
+            if ((int)$item['share_type'] === (int)$shareType && $item['uid_owner'] === $currentUser) {
697
+                $toDelete = $item;
698
+                // if there is more then one result we don't have to delete the children
699
+                // but update their parent. For group shares the new parent should always be
700
+                // the original group share and not the db entry with the unique name
701
+            } else if ((int)$item['share_type'] === self::$shareTypeGroupUserUnique) {
702
+                $newParent = $item['parent'];
703
+            } else {
704
+                $newParent = $item['id'];
705
+            }
706
+        }
707
+
708
+        if (!empty($toDelete)) {
709
+            self::unshareItem($toDelete, $newParent);
710
+            return true;
711
+        }
712
+        return false;
713
+    }
714
+
715
+    /**
716
+     * sent status if users got informed by mail about share
717
+     * @param string $itemType
718
+     * @param string $itemSource
719
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
720
+     * @param string $recipient with whom was the file shared
721
+     * @param boolean $status
722
+     */
723
+    public static function setSendMailStatus($itemType, $itemSource, $shareType, $recipient, $status) {
724
+        $status = $status ? 1 : 0;
725
+
726
+        $query = \OC_DB::prepare(
727
+            'UPDATE `*PREFIX*share`
728 728
 					SET `mail_send` = ?
729 729
 					WHERE `item_type` = ? AND `item_source` = ? AND `share_type` = ? AND `share_with` = ?');
730 730
 
731
-		$result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
732
-
733
-		if($result === false) {
734
-			\OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
735
-		}
736
-	}
737
-
738
-	/**
739
-	 * validate expiration date if it meets all constraints
740
-	 *
741
-	 * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
742
-	 * @param string $shareTime timestamp when the file was shared
743
-	 * @param string $itemType
744
-	 * @param string $itemSource
745
-	 * @return \DateTime validated date
746
-	 * @throws \Exception when the expire date is in the past or further in the future then the enforced date
747
-	 */
748
-	private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
749
-		$l = \OC::$server->getL10N('lib');
750
-		$date = new \DateTime($expireDate);
751
-		$today = new \DateTime('now');
752
-
753
-		// if the user doesn't provide a share time we need to get it from the database
754
-		// fall-back mode to keep API stable, because the $shareTime parameter was added later
755
-		$defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
756
-		if ($defaultExpireDateEnforced && $shareTime === null) {
757
-			$items = self::getItemShared($itemType, $itemSource);
758
-			$firstItem = reset($items);
759
-			$shareTime = (int)$firstItem['stime'];
760
-		}
761
-
762
-		if ($defaultExpireDateEnforced) {
763
-			// initialize max date with share time
764
-			$maxDate = new \DateTime();
765
-			$maxDate->setTimestamp($shareTime);
766
-			$maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
767
-			$maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
768
-			if ($date > $maxDate) {
769
-				$warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
770
-				$warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
771
-				\OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
772
-				throw new \Exception($warning_t);
773
-			}
774
-		}
775
-
776
-		if ($date < $today) {
777
-			$message = 'Cannot set expiration date. Expiration date is in the past';
778
-			$message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
779
-			\OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
780
-			throw new \Exception($message_t);
781
-		}
782
-
783
-		return $date;
784
-	}
785
-
786
-	/**
787
-	 * Retrieve the owner of a connection
788
-	 *
789
-	 * @param IDBConnection $connection
790
-	 * @param int $shareId
791
-	 * @throws \Exception
792
-	 * @return string uid of share owner
793
-	 */
794
-	private static function getShareOwner(IDBConnection $connection, $shareId) {
795
-		$qb = $connection->getQueryBuilder();
796
-
797
-		$qb->select('uid_owner')
798
-			->from('share')
799
-			->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
800
-			->setParameter(':shareId', $shareId);
801
-		$dbResult = $qb->execute();
802
-		$result = $dbResult->fetch();
803
-		$dbResult->closeCursor();
804
-
805
-		if (empty($result)) {
806
-			throw new \Exception('Share not found');
807
-		}
808
-
809
-		return $result['uid_owner'];
810
-	}
811
-
812
-	/**
813
-	 * Set password for a public link share
814
-	 *
815
-	 * @param IUserSession $userSession
816
-	 * @param IDBConnection $connection
817
-	 * @param IConfig $config
818
-	 * @param int $shareId
819
-	 * @param string $password
820
-	 * @throws \Exception
821
-	 * @return boolean
822
-	 */
823
-	public static function setPassword(IUserSession $userSession,
824
-	                                   IDBConnection $connection,
825
-	                                   IConfig $config,
826
-	                                   $shareId, $password) {
827
-		$user = $userSession->getUser();
828
-		if (is_null($user)) {
829
-			throw new \Exception("User not logged in");
830
-		}
831
-
832
-		$uid = self::getShareOwner($connection, $shareId);
833
-
834
-		if ($uid !== $user->getUID()) {
835
-			throw new \Exception('Cannot update share of a different user');
836
-		}
837
-
838
-		if ($password === '') {
839
-			$password = null;
840
-		}
841
-
842
-		//If passwords are enforced the password can't be null
843
-		if (self::enforcePassword($config) && is_null($password)) {
844
-			throw new \Exception('Cannot remove password');
845
-		}
846
-
847
-		self::verifyPassword($password);
848
-
849
-		$qb = $connection->getQueryBuilder();
850
-		$qb->update('share')
851
-			->set('share_with', $qb->createParameter('pass'))
852
-			->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
853
-			->setParameter(':pass', is_null($password) ? null : \OC::$server->getHasher()->hash($password))
854
-			->setParameter(':shareId', $shareId);
855
-
856
-		$qb->execute();
857
-
858
-		return true;
859
-	}
860
-
861
-	/**
862
-	 * Checks whether a share has expired, calls unshareItem() if yes.
863
-	 * @param array $item Share data (usually database row)
864
-	 * @return boolean True if item was expired, false otherwise.
865
-	 */
866
-	protected static function expireItem(array $item) {
867
-
868
-		$result = false;
869
-
870
-		// only use default expiration date for link shares
871
-		if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
872
-
873
-			// calculate expiration date
874
-			if (!empty($item['expiration'])) {
875
-				$userDefinedExpire = new \DateTime($item['expiration']);
876
-				$expires = $userDefinedExpire->getTimestamp();
877
-			} else {
878
-				$expires = null;
879
-			}
880
-
881
-
882
-			// get default expiration settings
883
-			$defaultSettings = Helper::getDefaultExpireSetting();
884
-			$expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
885
-
886
-
887
-			if (is_int($expires)) {
888
-				$now = time();
889
-				if ($now > $expires) {
890
-					self::unshareItem($item);
891
-					$result = true;
892
-				}
893
-			}
894
-		}
895
-		return $result;
896
-	}
897
-
898
-	/**
899
-	 * Unshares a share given a share data array
900
-	 * @param array $item Share data (usually database row)
901
-	 * @param int $newParent parent ID
902
-	 * @return null
903
-	 */
904
-	protected static function unshareItem(array $item, $newParent = null) {
905
-
906
-		$shareType = (int)$item['share_type'];
907
-		$shareWith = null;
908
-		if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
909
-			$shareWith = $item['share_with'];
910
-		}
911
-
912
-		// Pass all the vars we have for now, they may be useful
913
-		$hookParams = array(
914
-			'id'            => $item['id'],
915
-			'itemType'      => $item['item_type'],
916
-			'itemSource'    => $item['item_source'],
917
-			'shareType'     => $shareType,
918
-			'shareWith'     => $shareWith,
919
-			'itemParent'    => $item['parent'],
920
-			'uidOwner'      => $item['uid_owner'],
921
-		);
922
-		if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
923
-			$hookParams['fileSource'] = $item['file_source'];
924
-			$hookParams['fileTarget'] = $item['file_target'];
925
-		}
926
-
927
-		\OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
928
-		$deletedShares = Helper::delete($item['id'], false, null, $newParent);
929
-		$deletedShares[] = $hookParams;
930
-		$hookParams['deletedShares'] = $deletedShares;
931
-		\OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
932
-		if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
933
-			list(, $remote) = Helper::splitUserRemote($item['share_with']);
934
-			self::sendRemoteUnshare($remote, $item['id'], $item['token']);
935
-		}
936
-	}
937
-
938
-	/**
939
-	 * Get the backend class for the specified item type
940
-	 * @param string $itemType
941
-	 * @throws \Exception
942
-	 * @return \OCP\Share_Backend
943
-	 */
944
-	public static function getBackend($itemType) {
945
-		$l = \OC::$server->getL10N('lib');
946
-		if (isset(self::$backends[$itemType])) {
947
-			return self::$backends[$itemType];
948
-		} else if (isset(self::$backendTypes[$itemType]['class'])) {
949
-			$class = self::$backendTypes[$itemType]['class'];
950
-			if (class_exists($class)) {
951
-				self::$backends[$itemType] = new $class;
952
-				if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
953
-					$message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
954
-					$message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
955
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
956
-					throw new \Exception($message_t);
957
-				}
958
-				return self::$backends[$itemType];
959
-			} else {
960
-				$message = 'Sharing backend %s not found';
961
-				$message_t = $l->t('Sharing backend %s not found', array($class));
962
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
963
-				throw new \Exception($message_t);
964
-			}
965
-		}
966
-		$message = 'Sharing backend for %s not found';
967
-		$message_t = $l->t('Sharing backend for %s not found', array($itemType));
968
-		\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
969
-		throw new \Exception($message_t);
970
-	}
971
-
972
-	/**
973
-	 * Check if resharing is allowed
974
-	 * @return boolean true if allowed or false
975
-	 *
976
-	 * Resharing is allowed by default if not configured
977
-	 */
978
-	public static function isResharingAllowed() {
979
-		if (!isset(self::$isResharingAllowed)) {
980
-			if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
981
-				self::$isResharingAllowed = true;
982
-			} else {
983
-				self::$isResharingAllowed = false;
984
-			}
985
-		}
986
-		return self::$isResharingAllowed;
987
-	}
988
-
989
-	/**
990
-	 * Get a list of collection item types for the specified item type
991
-	 * @param string $itemType
992
-	 * @return array
993
-	 */
994
-	private static function getCollectionItemTypes($itemType) {
995
-		$collectionTypes = array($itemType);
996
-		foreach (self::$backendTypes as $type => $backend) {
997
-			if (in_array($backend['collectionOf'], $collectionTypes)) {
998
-				$collectionTypes[] = $type;
999
-			}
1000
-		}
1001
-		// TODO Add option for collections to be collection of themselves, only 'folder' does it now...
1002
-		if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
1003
-			unset($collectionTypes[0]);
1004
-		}
1005
-		// Return array if collections were found or the item type is a
1006
-		// collection itself - collections can be inside collections
1007
-		if (count($collectionTypes) > 0) {
1008
-			return $collectionTypes;
1009
-		}
1010
-		return false;
1011
-	}
1012
-
1013
-	/**
1014
-	 * Get the owners of items shared with a user.
1015
-	 *
1016
-	 * @param string $user The user the items are shared with.
1017
-	 * @param string $type The type of the items shared with the user.
1018
-	 * @param boolean $includeCollections Include collection item types (optional)
1019
-	 * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
1020
-	 * @return array
1021
-	 */
1022
-	public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
1023
-		// First, we find out if $type is part of a collection (and if that collection is part of
1024
-		// another one and so on).
1025
-		$collectionTypes = array();
1026
-		if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
1027
-			$collectionTypes[] = $type;
1028
-		}
1029
-
1030
-		// Of these collection types, along with our original $type, we make a
1031
-		// list of the ones for which a sharing backend has been registered.
1032
-		// FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
1033
-		// with its $includeCollections parameter set to true. Unfortunately, this fails currently.
1034
-		$allMaybeSharedItems = array();
1035
-		foreach ($collectionTypes as $collectionType) {
1036
-			if (isset(self::$backends[$collectionType])) {
1037
-				$allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
1038
-					$collectionType,
1039
-					$user,
1040
-					self::FORMAT_NONE
1041
-				);
1042
-			}
1043
-		}
1044
-
1045
-		$owners = array();
1046
-		if ($includeOwner) {
1047
-			$owners[] = $user;
1048
-		}
1049
-
1050
-		// We take a look at all shared items of the given $type (or of the collections it is part of)
1051
-		// and find out their owners. Then, we gather the tags for the original $type from all owners,
1052
-		// and return them as elements of a list that look like "Tag (owner)".
1053
-		foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
1054
-			foreach ($maybeSharedItems as $sharedItem) {
1055
-				if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
1056
-					$owners[] = $sharedItem['uid_owner'];
1057
-				}
1058
-			}
1059
-		}
1060
-
1061
-		return $owners;
1062
-	}
1063
-
1064
-	/**
1065
-	 * Get shared items from the database
1066
-	 * @param string $itemType
1067
-	 * @param string $item Item source or target (optional)
1068
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
1069
-	 * @param string $shareWith User or group the item is being shared with
1070
-	 * @param string $uidOwner User that is the owner of shared items (optional)
1071
-	 * @param int $format Format to convert items to with formatItems() (optional)
1072
-	 * @param mixed $parameters to pass to formatItems() (optional)
1073
-	 * @param int $limit Number of items to return, -1 to return all matches (optional)
1074
-	 * @param boolean $includeCollections Include collection item types (optional)
1075
-	 * @param boolean $itemShareWithBySource (optional)
1076
-	 * @param boolean $checkExpireDate
1077
-	 * @return array
1078
-	 *
1079
-	 * See public functions getItem(s)... for parameter usage
1080
-	 *
1081
-	 */
1082
-	public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1083
-									$uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1084
-									$includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1085
-		if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') != 'yes') {
1086
-			return array();
1087
-		}
1088
-		$backend = self::getBackend($itemType);
1089
-		$collectionTypes = false;
1090
-		// Get filesystem root to add it to the file target and remove from the
1091
-		// file source, match file_source with the file cache
1092
-		if ($itemType == 'file' || $itemType == 'folder') {
1093
-			if(!is_null($uidOwner)) {
1094
-				$root = \OC\Files\Filesystem::getRoot();
1095
-			} else {
1096
-				$root = '';
1097
-			}
1098
-			$where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1099
-			if (!isset($item)) {
1100
-				$where .= ' AND `file_target` IS NOT NULL ';
1101
-			}
1102
-			$where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1103
-			$fileDependent = true;
1104
-			$queryArgs = array();
1105
-		} else {
1106
-			$fileDependent = false;
1107
-			$root = '';
1108
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1109
-			if ($includeCollections && !isset($item) && $collectionTypes) {
1110
-				// If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1111
-				if (!in_array($itemType, $collectionTypes)) {
1112
-					$itemTypes = array_merge(array($itemType), $collectionTypes);
1113
-				} else {
1114
-					$itemTypes = $collectionTypes;
1115
-				}
1116
-				$placeholders = join(',', array_fill(0, count($itemTypes), '?'));
1117
-				$where = ' WHERE `item_type` IN ('.$placeholders.'))';
1118
-				$queryArgs = $itemTypes;
1119
-			} else {
1120
-				$where = ' WHERE `item_type` = ?';
1121
-				$queryArgs = array($itemType);
1122
-			}
1123
-		}
1124
-		if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1125
-			$where .= ' AND `share_type` != ?';
1126
-			$queryArgs[] = self::SHARE_TYPE_LINK;
1127
-		}
1128
-		if (isset($shareType)) {
1129
-			// Include all user and group items
1130
-			if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1131
-				$where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1132
-				$queryArgs[] = self::SHARE_TYPE_USER;
1133
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1134
-				$queryArgs[] = $shareWith;
1135
-
1136
-				$user = \OC::$server->getUserManager()->get($shareWith);
1137
-				$groups = [];
1138
-				if ($user) {
1139
-					$groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1140
-				}
1141
-				if (!empty($groups)) {
1142
-					$placeholders = join(',', array_fill(0, count($groups), '?'));
1143
-					$where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1144
-					$queryArgs[] = self::SHARE_TYPE_GROUP;
1145
-					$queryArgs = array_merge($queryArgs, $groups);
1146
-				}
1147
-				$where .= ')';
1148
-				// Don't include own group shares
1149
-				$where .= ' AND `uid_owner` != ?';
1150
-				$queryArgs[] = $shareWith;
1151
-			} else {
1152
-				$where .= ' AND `share_type` = ?';
1153
-				$queryArgs[] = $shareType;
1154
-				if (isset($shareWith)) {
1155
-					$where .= ' AND `share_with` = ?';
1156
-					$queryArgs[] = $shareWith;
1157
-				}
1158
-			}
1159
-		}
1160
-		if (isset($uidOwner)) {
1161
-			$where .= ' AND `uid_owner` = ?';
1162
-			$queryArgs[] = $uidOwner;
1163
-			if (!isset($shareType)) {
1164
-				// Prevent unique user targets for group shares from being selected
1165
-				$where .= ' AND `share_type` != ?';
1166
-				$queryArgs[] = self::$shareTypeGroupUserUnique;
1167
-			}
1168
-			if ($fileDependent) {
1169
-				$column = 'file_source';
1170
-			} else {
1171
-				$column = 'item_source';
1172
-			}
1173
-		} else {
1174
-			if ($fileDependent) {
1175
-				$column = 'file_target';
1176
-			} else {
1177
-				$column = 'item_target';
1178
-			}
1179
-		}
1180
-		if (isset($item)) {
1181
-			$collectionTypes = self::getCollectionItemTypes($itemType);
1182
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1183
-				$where .= ' AND (';
1184
-			} else {
1185
-				$where .= ' AND';
1186
-			}
1187
-			// If looking for own shared items, check item_source else check item_target
1188
-			if (isset($uidOwner) || $itemShareWithBySource) {
1189
-				// If item type is a file, file source needs to be checked in case the item was converted
1190
-				if ($fileDependent) {
1191
-					$where .= ' `file_source` = ?';
1192
-					$column = 'file_source';
1193
-				} else {
1194
-					$where .= ' `item_source` = ?';
1195
-					$column = 'item_source';
1196
-				}
1197
-			} else {
1198
-				if ($fileDependent) {
1199
-					$where .= ' `file_target` = ?';
1200
-					$item = \OC\Files\Filesystem::normalizePath($item);
1201
-				} else {
1202
-					$where .= ' `item_target` = ?';
1203
-				}
1204
-			}
1205
-			$queryArgs[] = $item;
1206
-			if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1207
-				$placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
1208
-				$where .= ' OR `item_type` IN ('.$placeholders.'))';
1209
-				$queryArgs = array_merge($queryArgs, $collectionTypes);
1210
-			}
1211
-		}
1212
-
1213
-		if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1214
-			// Make sure the unique user target is returned if it exists,
1215
-			// unique targets should follow the group share in the database
1216
-			// If the limit is not 1, the filtering can be done later
1217
-			$where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1218
-		} else {
1219
-			$where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1220
-		}
1221
-
1222
-		if ($limit != -1 && !$includeCollections) {
1223
-			// The limit must be at least 3, because filtering needs to be done
1224
-			if ($limit < 3) {
1225
-				$queryLimit = 3;
1226
-			} else {
1227
-				$queryLimit = $limit;
1228
-			}
1229
-		} else {
1230
-			$queryLimit = null;
1231
-		}
1232
-		$select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1233
-		$root = strlen($root);
1234
-		$query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1235
-		$result = $query->execute($queryArgs);
1236
-		if ($result === false) {
1237
-			\OCP\Util::writeLog('OCP\Share',
1238
-				\OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1239
-				\OCP\Util::ERROR);
1240
-		}
1241
-		$items = array();
1242
-		$targets = array();
1243
-		$switchedItems = array();
1244
-		$mounts = array();
1245
-		while ($row = $result->fetchRow()) {
1246
-			self::transformDBResults($row);
1247
-			// Filter out duplicate group shares for users with unique targets
1248
-			if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1249
-				continue;
1250
-			}
1251
-			if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1252
-				$row['share_type'] = self::SHARE_TYPE_GROUP;
1253
-				$row['unique_name'] = true; // remember that we use a unique name for this user
1254
-				$row['share_with'] = $items[$row['parent']]['share_with'];
1255
-				// if the group share was unshared from the user we keep the permission, otherwise
1256
-				// we take the permission from the parent because this is always the up-to-date
1257
-				// permission for the group share
1258
-				if ($row['permissions'] > 0) {
1259
-					$row['permissions'] = $items[$row['parent']]['permissions'];
1260
-				}
1261
-				// Remove the parent group share
1262
-				unset($items[$row['parent']]);
1263
-				if ($row['permissions'] == 0) {
1264
-					continue;
1265
-				}
1266
-			} else if (!isset($uidOwner)) {
1267
-				// Check if the same target already exists
1268
-				if (isset($targets[$row['id']])) {
1269
-					// Check if the same owner shared with the user twice
1270
-					// through a group and user share - this is allowed
1271
-					$id = $targets[$row['id']];
1272
-					if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1273
-						// Switch to group share type to ensure resharing conditions aren't bypassed
1274
-						if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1275
-							$items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1276
-							$items[$id]['share_with'] = $row['share_with'];
1277
-						}
1278
-						// Switch ids if sharing permission is granted on only
1279
-						// one share to ensure correct parent is used if resharing
1280
-						if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1281
-							&& (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1282
-							$items[$row['id']] = $items[$id];
1283
-							$switchedItems[$id] = $row['id'];
1284
-							unset($items[$id]);
1285
-							$id = $row['id'];
1286
-						}
1287
-						$items[$id]['permissions'] |= (int)$row['permissions'];
1288
-
1289
-					}
1290
-					continue;
1291
-				} elseif (!empty($row['parent'])) {
1292
-					$targets[$row['parent']] = $row['id'];
1293
-				}
1294
-			}
1295
-			// Remove root from file source paths if retrieving own shared items
1296
-			if (isset($uidOwner) && isset($row['path'])) {
1297
-				if (isset($row['parent'])) {
1298
-					$query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1299
-					$parentResult = $query->execute(array($row['parent']));
1300
-					if ($result === false) {
1301
-						\OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1302
-							\OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1303
-							\OCP\Util::ERROR);
1304
-					} else {
1305
-						$parentRow = $parentResult->fetchRow();
1306
-						$tmpPath = $parentRow['file_target'];
1307
-						// find the right position where the row path continues from the target path
1308
-						$pos = strrpos($row['path'], $parentRow['file_target']);
1309
-						$subPath = substr($row['path'], $pos);
1310
-						$splitPath = explode('/', $subPath);
1311
-						foreach (array_slice($splitPath, 2) as $pathPart) {
1312
-							$tmpPath = $tmpPath . '/' . $pathPart;
1313
-						}
1314
-						$row['path'] = $tmpPath;
1315
-					}
1316
-				} else {
1317
-					if (!isset($mounts[$row['storage']])) {
1318
-						$mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1319
-						if (is_array($mountPoints) && !empty($mountPoints)) {
1320
-							$mounts[$row['storage']] = current($mountPoints);
1321
-						}
1322
-					}
1323
-					if (!empty($mounts[$row['storage']])) {
1324
-						$path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1325
-						$relPath = substr($path, $root); // path relative to data/user
1326
-						$row['path'] = rtrim($relPath, '/');
1327
-					}
1328
-				}
1329
-			}
1330
-
1331
-			if($checkExpireDate) {
1332
-				if (self::expireItem($row)) {
1333
-					continue;
1334
-				}
1335
-			}
1336
-			// Check if resharing is allowed, if not remove share permission
1337
-			if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1338
-				$row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1339
-			}
1340
-			// Add display names to result
1341
-			$row['share_with_displayname'] = $row['share_with'];
1342
-			if ( isset($row['share_with']) && $row['share_with'] != '' &&
1343
-				$row['share_type'] === self::SHARE_TYPE_USER) {
1344
-				$row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
1345
-			} else if(isset($row['share_with']) && $row['share_with'] != '' &&
1346
-				$row['share_type'] === self::SHARE_TYPE_REMOTE) {
1347
-				$addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1348
-				foreach ($addressBookEntries as $entry) {
1349
-					foreach ($entry['CLOUD'] as $cloudID) {
1350
-						if ($cloudID === $row['share_with']) {
1351
-							$row['share_with_displayname'] = $entry['FN'];
1352
-						}
1353
-					}
1354
-				}
1355
-			}
1356
-			if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1357
-				$row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
1358
-			}
1359
-
1360
-			if ($row['permissions'] > 0) {
1361
-				$items[$row['id']] = $row;
1362
-			}
1363
-
1364
-		}
1365
-
1366
-		// group items if we are looking for items shared with the current user
1367
-		if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1368
-			$items = self::groupItems($items, $itemType);
1369
-		}
1370
-
1371
-		if (!empty($items)) {
1372
-			$collectionItems = array();
1373
-			foreach ($items as &$row) {
1374
-				// Return only the item instead of a 2-dimensional array
1375
-				if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1376
-					if ($format == self::FORMAT_NONE) {
1377
-						return $row;
1378
-					} else {
1379
-						break;
1380
-					}
1381
-				}
1382
-				// Check if this is a collection of the requested item type
1383
-				if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1384
-					if (($collectionBackend = self::getBackend($row['item_type']))
1385
-						&& $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1386
-						// Collections can be inside collections, check if the item is a collection
1387
-						if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1388
-							$collectionItems[] = $row;
1389
-						} else {
1390
-							$collection = array();
1391
-							$collection['item_type'] = $row['item_type'];
1392
-							if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1393
-								$collection['path'] = basename($row['path']);
1394
-							}
1395
-							$row['collection'] = $collection;
1396
-							// Fetch all of the children sources
1397
-							$children = $collectionBackend->getChildren($row[$column]);
1398
-							foreach ($children as $child) {
1399
-								$childItem = $row;
1400
-								$childItem['item_type'] = $itemType;
1401
-								if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1402
-									$childItem['item_source'] = $child['source'];
1403
-									$childItem['item_target'] = $child['target'];
1404
-								}
1405
-								if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1406
-									if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1407
-										$childItem['file_source'] = $child['source'];
1408
-									} else { // TODO is this really needed if we already know that we use the file backend?
1409
-										$meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1410
-										$childItem['file_source'] = $meta['fileid'];
1411
-									}
1412
-									$childItem['file_target'] =
1413
-										\OC\Files\Filesystem::normalizePath($child['file_path']);
1414
-								}
1415
-								if (isset($item)) {
1416
-									if ($childItem[$column] == $item) {
1417
-										// Return only the item instead of a 2-dimensional array
1418
-										if ($limit == 1) {
1419
-											if ($format == self::FORMAT_NONE) {
1420
-												return $childItem;
1421
-											} else {
1422
-												// Unset the items array and break out of both loops
1423
-												$items = array();
1424
-												$items[] = $childItem;
1425
-												break 2;
1426
-											}
1427
-										} else {
1428
-											$collectionItems[] = $childItem;
1429
-										}
1430
-									}
1431
-								} else {
1432
-									$collectionItems[] = $childItem;
1433
-								}
1434
-							}
1435
-						}
1436
-					}
1437
-					// Remove collection item
1438
-					$toRemove = $row['id'];
1439
-					if (array_key_exists($toRemove, $switchedItems)) {
1440
-						$toRemove = $switchedItems[$toRemove];
1441
-					}
1442
-					unset($items[$toRemove]);
1443
-				} elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1444
-					// FIXME: Thats a dirty hack to improve file sharing performance,
1445
-					// see github issue #10588 for more details
1446
-					// Need to find a solution which works for all back-ends
1447
-					$collectionBackend = self::getBackend($row['item_type']);
1448
-					$sharedParents = $collectionBackend->getParents($row['item_source']);
1449
-					foreach ($sharedParents as $parent) {
1450
-						$collectionItems[] = $parent;
1451
-					}
1452
-				}
1453
-			}
1454
-			if (!empty($collectionItems)) {
1455
-				$collectionItems = array_unique($collectionItems, SORT_REGULAR);
1456
-				$items = array_merge($items, $collectionItems);
1457
-			}
1458
-
1459
-			// filter out invalid items, these can appear when subshare entries exist
1460
-			// for a group in which the requested user isn't a member any more
1461
-			$items = array_filter($items, function($item) {
1462
-				return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1463
-			});
1464
-
1465
-			return self::formatResult($items, $column, $backend, $format, $parameters);
1466
-		} elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1467
-			// FIXME: Thats a dirty hack to improve file sharing performance,
1468
-			// see github issue #10588 for more details
1469
-			// Need to find a solution which works for all back-ends
1470
-			$collectionItems = array();
1471
-			$collectionBackend = self::getBackend('folder');
1472
-			$sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1473
-			foreach ($sharedParents as $parent) {
1474
-				$collectionItems[] = $parent;
1475
-			}
1476
-			if ($limit === 1) {
1477
-				return reset($collectionItems);
1478
-			}
1479
-			return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1480
-		}
1481
-
1482
-		return array();
1483
-	}
1484
-
1485
-	/**
1486
-	 * group items with link to the same source
1487
-	 *
1488
-	 * @param array $items
1489
-	 * @param string $itemType
1490
-	 * @return array of grouped items
1491
-	 */
1492
-	protected static function groupItems($items, $itemType) {
1493
-
1494
-		$fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
1495
-
1496
-		$result = array();
1497
-
1498
-		foreach ($items as $item) {
1499
-			$grouped = false;
1500
-			foreach ($result as $key => $r) {
1501
-				// for file/folder shares we need to compare file_source, otherwise we compare item_source
1502
-				// only group shares if they already point to the same target, otherwise the file where shared
1503
-				// before grouping of shares was added. In this case we don't group them toi avoid confusions
1504
-				if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1505
-					(!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1506
-					// add the first item to the list of grouped shares
1507
-					if (!isset($result[$key]['grouped'])) {
1508
-						$result[$key]['grouped'][] = $result[$key];
1509
-					}
1510
-					$result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1511
-					$result[$key]['grouped'][] = $item;
1512
-					$grouped = true;
1513
-					break;
1514
-				}
1515
-			}
1516
-
1517
-			if (!$grouped) {
1518
-				$result[] = $item;
1519
-			}
1520
-
1521
-		}
1522
-
1523
-		return $result;
1524
-	}
1525
-
1526
-	/**
1527
-	 * Put shared item into the database
1528
-	 * @param string $itemType Item type
1529
-	 * @param string $itemSource Item source
1530
-	 * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1531
-	 * @param string $shareWith User or group the item is being shared with
1532
-	 * @param string $uidOwner User that is the owner of shared item
1533
-	 * @param int $permissions CRUDS permissions
1534
-	 * @param boolean|array $parentFolder Parent folder target (optional)
1535
-	 * @param string $token (optional)
1536
-	 * @param string $itemSourceName name of the source item (optional)
1537
-	 * @param \DateTime $expirationDate (optional)
1538
-	 * @throws \Exception
1539
-	 * @return mixed id of the new share or false
1540
-	 */
1541
-	private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1542
-								$permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1543
-
1544
-		$queriesToExecute = array();
1545
-		$suggestedItemTarget = null;
1546
-		$groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1547
-		$groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1548
-
1549
-		$result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1550
-		if(!empty($result)) {
1551
-			$parent = $result['parent'];
1552
-			$itemSource = $result['itemSource'];
1553
-			$fileSource = $result['fileSource'];
1554
-			$suggestedItemTarget = $result['suggestedItemTarget'];
1555
-			$suggestedFileTarget = $result['suggestedFileTarget'];
1556
-			$filePath = $result['filePath'];
1557
-		}
1558
-
1559
-		$isGroupShare = false;
1560
-		if ($shareType == self::SHARE_TYPE_GROUP) {
1561
-			$isGroupShare = true;
1562
-			if (isset($shareWith['users'])) {
1563
-				$users = $shareWith['users'];
1564
-			} else {
1565
-				$group = \OC::$server->getGroupManager()->get($shareWith['group']);
1566
-				if ($group) {
1567
-					$users = $group->searchUsers('', -1, 0);
1568
-					$userIds = [];
1569
-					foreach ($users as $user) {
1570
-						$userIds[] = $user->getUID();
1571
-					}
1572
-					$users = $userIds;
1573
-				} else {
1574
-					$users = [];
1575
-				}
1576
-			}
1577
-			// remove current user from list
1578
-			if (in_array(\OCP\User::getUser(), $users)) {
1579
-				unset($users[array_search(\OCP\User::getUser(), $users)]);
1580
-			}
1581
-			$groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1582
-				$shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1583
-			$groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1584
-				$shareType, $shareWith['group'], $uidOwner, $filePath);
1585
-
1586
-			// add group share to table and remember the id as parent
1587
-			$queriesToExecute['groupShare'] = array(
1588
-				'itemType'			=> $itemType,
1589
-				'itemSource'		=> $itemSource,
1590
-				'itemTarget'		=> $groupItemTarget,
1591
-				'shareType'			=> $shareType,
1592
-				'shareWith'			=> $shareWith['group'],
1593
-				'uidOwner'			=> $uidOwner,
1594
-				'permissions'		=> $permissions,
1595
-				'shareTime'			=> time(),
1596
-				'fileSource'		=> $fileSource,
1597
-				'fileTarget'		=> $groupFileTarget,
1598
-				'token'				=> $token,
1599
-				'parent'			=> $parent,
1600
-				'expiration'		=> $expirationDate,
1601
-			);
1602
-
1603
-		} else {
1604
-			$users = array($shareWith);
1605
-			$itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1606
-				$suggestedItemTarget);
1607
-		}
1608
-
1609
-		$run = true;
1610
-		$error = '';
1611
-		$preHookData = array(
1612
-			'itemType' => $itemType,
1613
-			'itemSource' => $itemSource,
1614
-			'shareType' => $shareType,
1615
-			'uidOwner' => $uidOwner,
1616
-			'permissions' => $permissions,
1617
-			'fileSource' => $fileSource,
1618
-			'expiration' => $expirationDate,
1619
-			'token' => $token,
1620
-			'run' => &$run,
1621
-			'error' => &$error
1622
-		);
1623
-
1624
-		$preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
1625
-		$preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
1626
-
1627
-		\OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
1628
-
1629
-		if ($run === false) {
1630
-			throw new \Exception($error);
1631
-		}
1632
-
1633
-		foreach ($users as $user) {
1634
-			$sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1635
-			$sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1636
-
1637
-			$userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
1638
-
1639
-			if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1640
-				$fileTarget = $sourceExists['file_target'];
1641
-				$itemTarget = $sourceExists['item_target'];
1642
-
1643
-				// for group shares we don't need a additional entry if the target is the same
1644
-				if($isGroupShare && $groupItemTarget === $itemTarget) {
1645
-					continue;
1646
-				}
1647
-
1648
-			} elseif(!$sourceExists && !$isGroupShare)  {
1649
-
1650
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1651
-					$uidOwner, $suggestedItemTarget, $parent);
1652
-				if (isset($fileSource)) {
1653
-					if ($parentFolder) {
1654
-						if ($parentFolder === true) {
1655
-							$fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1656
-								$uidOwner, $suggestedFileTarget, $parent);
1657
-							if ($fileTarget != $groupFileTarget) {
1658
-								$parentFolders[$user]['folder'] = $fileTarget;
1659
-							}
1660
-						} else if (isset($parentFolder[$user])) {
1661
-							$fileTarget = $parentFolder[$user]['folder'].$itemSource;
1662
-							$parent = $parentFolder[$user]['id'];
1663
-						}
1664
-					} else {
1665
-						$fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1666
-							$user, $uidOwner, $suggestedFileTarget, $parent);
1667
-					}
1668
-				} else {
1669
-					$fileTarget = null;
1670
-				}
1671
-
1672
-			} else {
1673
-
1674
-				// group share which doesn't exists until now, check if we need a unique target for this user
1675
-
1676
-				$itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1677
-					$uidOwner, $suggestedItemTarget, $parent);
1678
-
1679
-				// do we also need a file target
1680
-				if (isset($fileSource)) {
1681
-					$fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1682
-						$uidOwner, $suggestedFileTarget, $parent);
1683
-				} else {
1684
-					$fileTarget = null;
1685
-				}
1686
-
1687
-				if (($itemTarget === $groupItemTarget) &&
1688
-					(!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1689
-					continue;
1690
-				}
1691
-			}
1692
-
1693
-			$queriesToExecute[] = array(
1694
-				'itemType'			=> $itemType,
1695
-				'itemSource'		=> $itemSource,
1696
-				'itemTarget'		=> $itemTarget,
1697
-				'shareType'			=> $userShareType,
1698
-				'shareWith'			=> $user,
1699
-				'uidOwner'			=> $uidOwner,
1700
-				'permissions'		=> $permissions,
1701
-				'shareTime'			=> time(),
1702
-				'fileSource'		=> $fileSource,
1703
-				'fileTarget'		=> $fileTarget,
1704
-				'token'				=> $token,
1705
-				'parent'			=> $parent,
1706
-				'expiration'		=> $expirationDate,
1707
-			);
1708
-
1709
-		}
1710
-
1711
-		$id = false;
1712
-		if ($isGroupShare) {
1713
-			$id = self::insertShare($queriesToExecute['groupShare']);
1714
-			// Save this id, any extra rows for this group share will need to reference it
1715
-			$parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1716
-			unset($queriesToExecute['groupShare']);
1717
-		}
1718
-
1719
-		foreach ($queriesToExecute as $shareQuery) {
1720
-			$shareQuery['parent'] = $parent;
1721
-			$id = self::insertShare($shareQuery);
1722
-		}
1723
-
1724
-		$postHookData = array(
1725
-			'itemType' => $itemType,
1726
-			'itemSource' => $itemSource,
1727
-			'parent' => $parent,
1728
-			'shareType' => $shareType,
1729
-			'uidOwner' => $uidOwner,
1730
-			'permissions' => $permissions,
1731
-			'fileSource' => $fileSource,
1732
-			'id' => $parent,
1733
-			'token' => $token,
1734
-			'expirationDate' => $expirationDate,
1735
-		);
1736
-
1737
-		$postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
1738
-		$postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
1739
-		$postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
1740
-
1741
-		\OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
1742
-
1743
-
1744
-		return $id ? $id : false;
1745
-	}
1746
-
1747
-	/**
1748
-	 * @param string $itemType
1749
-	 * @param string $itemSource
1750
-	 * @param int $shareType
1751
-	 * @param string $shareWith
1752
-	 * @param string $uidOwner
1753
-	 * @param int $permissions
1754
-	 * @param string|null $itemSourceName
1755
-	 * @param null|\DateTime $expirationDate
1756
-	 */
1757
-	private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1758
-		$backend = self::getBackend($itemType);
1759
-
1760
-		$l = \OC::$server->getL10N('lib');
1761
-		$result = array();
1762
-
1763
-		$column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1764
-
1765
-		$checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1766
-		if ($checkReshare) {
1767
-			// Check if attempting to share back to owner
1768
-			if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1769
-				$message = 'Sharing %s failed, because the user %s is the original sharer';
1770
-				$message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1771
-
1772
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
1773
-				throw new \Exception($message_t);
1774
-			}
1775
-		}
1776
-
1777
-		if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1778
-			// Check if share permissions is granted
1779
-			if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1780
-				if (~(int)$checkReshare['permissions'] & $permissions) {
1781
-					$message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1782
-					$message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1783
-
1784
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
1785
-					throw new \Exception($message_t);
1786
-				} else {
1787
-					// TODO Don't check if inside folder
1788
-					$result['parent'] = $checkReshare['id'];
1789
-
1790
-					$result['expirationDate'] = $expirationDate;
1791
-					// $checkReshare['expiration'] could be null and then is always less than any value
1792
-					if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1793
-						$result['expirationDate'] = $checkReshare['expiration'];
1794
-					}
1795
-
1796
-					// only suggest the same name as new target if it is a reshare of the
1797
-					// same file/folder and not the reshare of a child
1798
-					if ($checkReshare[$column] === $itemSource) {
1799
-						$result['filePath'] = $checkReshare['file_target'];
1800
-						$result['itemSource'] = $checkReshare['item_source'];
1801
-						$result['fileSource'] = $checkReshare['file_source'];
1802
-						$result['suggestedItemTarget'] = $checkReshare['item_target'];
1803
-						$result['suggestedFileTarget'] = $checkReshare['file_target'];
1804
-					} else {
1805
-						$result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1806
-						$result['suggestedItemTarget'] = null;
1807
-						$result['suggestedFileTarget'] = null;
1808
-						$result['itemSource'] = $itemSource;
1809
-						$result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1810
-					}
1811
-				}
1812
-			} else {
1813
-				$message = 'Sharing %s failed, because resharing is not allowed';
1814
-				$message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1815
-
1816
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
1817
-				throw new \Exception($message_t);
1818
-			}
1819
-		} else {
1820
-			$result['parent'] = null;
1821
-			$result['suggestedItemTarget'] = null;
1822
-			$result['suggestedFileTarget'] = null;
1823
-			$result['itemSource'] = $itemSource;
1824
-			$result['expirationDate'] = $expirationDate;
1825
-			if (!$backend->isValidSource($itemSource, $uidOwner)) {
1826
-				$message = 'Sharing %s failed, because the sharing backend for '
1827
-					.'%s could not find its source';
1828
-				$message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1829
-				\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
1830
-				throw new \Exception($message_t);
1831
-			}
1832
-			if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1833
-				$result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1834
-				if ($itemType == 'file' || $itemType == 'folder') {
1835
-					$result['fileSource'] = $itemSource;
1836
-				} else {
1837
-					$meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1838
-					$result['fileSource'] = $meta['fileid'];
1839
-				}
1840
-				if ($result['fileSource'] == -1) {
1841
-					$message = 'Sharing %s failed, because the file could not be found in the file cache';
1842
-					$message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1843
-
1844
-					\OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1845
-					throw new \Exception($message_t);
1846
-				}
1847
-			} else {
1848
-				$result['filePath'] = null;
1849
-				$result['fileSource'] = null;
1850
-			}
1851
-		}
1852
-
1853
-		return $result;
1854
-	}
1855
-
1856
-	/**
1857
-	 *
1858
-	 * @param array $shareData
1859
-	 * @return mixed false in case of a failure or the id of the new share
1860
-	 */
1861
-	private static function insertShare(array $shareData) {
1862
-
1863
-		$query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1864
-			.' `item_type`, `item_source`, `item_target`, `share_type`,'
1865
-			.' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1866
-			.' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1867
-		$query->bindValue(1, $shareData['itemType']);
1868
-		$query->bindValue(2, $shareData['itemSource']);
1869
-		$query->bindValue(3, $shareData['itemTarget']);
1870
-		$query->bindValue(4, $shareData['shareType']);
1871
-		$query->bindValue(5, $shareData['shareWith']);
1872
-		$query->bindValue(6, $shareData['uidOwner']);
1873
-		$query->bindValue(7, $shareData['permissions']);
1874
-		$query->bindValue(8, $shareData['shareTime']);
1875
-		$query->bindValue(9, $shareData['fileSource']);
1876
-		$query->bindValue(10, $shareData['fileTarget']);
1877
-		$query->bindValue(11, $shareData['token']);
1878
-		$query->bindValue(12, $shareData['parent']);
1879
-		$query->bindValue(13, $shareData['expiration'], 'datetime');
1880
-		$result = $query->execute();
1881
-
1882
-		$id = false;
1883
-		if ($result) {
1884
-			$id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1885
-		}
1886
-
1887
-		return $id;
1888
-
1889
-	}
1890
-
1891
-	/**
1892
-	 * In case a password protected link is not yet authenticated this function will return false
1893
-	 *
1894
-	 * @param array $linkItem
1895
-	 * @return boolean
1896
-	 */
1897
-	public static function checkPasswordProtectedShare(array $linkItem) {
1898
-		if (!isset($linkItem['share_with'])) {
1899
-			return true;
1900
-		}
1901
-		if (!isset($linkItem['share_type'])) {
1902
-			return true;
1903
-		}
1904
-		if (!isset($linkItem['id'])) {
1905
-			return true;
1906
-		}
1907
-
1908
-		if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1909
-			return true;
1910
-		}
1911
-
1912
-		if ( \OC::$server->getSession()->exists('public_link_authenticated')
1913
-			&& \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1914
-			return true;
1915
-		}
1916
-
1917
-		return false;
1918
-	}
1919
-
1920
-	/**
1921
-	 * construct select statement
1922
-	 * @param int $format
1923
-	 * @param boolean $fileDependent ist it a file/folder share or a generla share
1924
-	 * @param string $uidOwner
1925
-	 * @return string select statement
1926
-	 */
1927
-	private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1928
-		$select = '*';
1929
-		if ($format == self::FORMAT_STATUSES) {
1930
-			if ($fileDependent) {
1931
-				$select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1932
-					. '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1933
-					. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1934
-					. '`uid_initiator`';
1935
-			} else {
1936
-				$select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1937
-			}
1938
-		} else {
1939
-			if (isset($uidOwner)) {
1940
-				if ($fileDependent) {
1941
-					$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1942
-						. ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1943
-						. ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1944
-						. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1945
-				} else {
1946
-					$select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1947
-						. ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1948
-				}
1949
-			} else {
1950
-				if ($fileDependent) {
1951
-					if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1952
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1953
-							. '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1954
-							. '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1955
-							. '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1956
-					} else {
1957
-						$select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1958
-							. '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1959
-							. '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1960
-						    . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1961
-							. '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1962
-					}
1963
-				}
1964
-			}
1965
-		}
1966
-		return $select;
1967
-	}
1968
-
1969
-
1970
-	/**
1971
-	 * transform db results
1972
-	 * @param array $row result
1973
-	 */
1974
-	private static function transformDBResults(&$row) {
1975
-		if (isset($row['id'])) {
1976
-			$row['id'] = (int) $row['id'];
1977
-		}
1978
-		if (isset($row['share_type'])) {
1979
-			$row['share_type'] = (int) $row['share_type'];
1980
-		}
1981
-		if (isset($row['parent'])) {
1982
-			$row['parent'] = (int) $row['parent'];
1983
-		}
1984
-		if (isset($row['file_parent'])) {
1985
-			$row['file_parent'] = (int) $row['file_parent'];
1986
-		}
1987
-		if (isset($row['file_source'])) {
1988
-			$row['file_source'] = (int) $row['file_source'];
1989
-		}
1990
-		if (isset($row['permissions'])) {
1991
-			$row['permissions'] = (int) $row['permissions'];
1992
-		}
1993
-		if (isset($row['storage'])) {
1994
-			$row['storage'] = (int) $row['storage'];
1995
-		}
1996
-		if (isset($row['stime'])) {
1997
-			$row['stime'] = (int) $row['stime'];
1998
-		}
1999
-		if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
2000
-			// discard expiration date for non-link shares, which might have been
2001
-			// set by ancient bugs
2002
-			$row['expiration'] = null;
2003
-		}
2004
-	}
2005
-
2006
-	/**
2007
-	 * format result
2008
-	 * @param array $items result
2009
-	 * @param string $column is it a file share or a general share ('file_target' or 'item_target')
2010
-	 * @param \OCP\Share_Backend $backend sharing backend
2011
-	 * @param int $format
2012
-	 * @param array $parameters additional format parameters
2013
-	 * @return array format result
2014
-	 */
2015
-	private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2016
-		if ($format === self::FORMAT_NONE) {
2017
-			return $items;
2018
-		} else if ($format === self::FORMAT_STATUSES) {
2019
-			$statuses = array();
2020
-			foreach ($items as $item) {
2021
-				if ($item['share_type'] === self::SHARE_TYPE_LINK) {
2022
-					if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
2023
-						continue;
2024
-					}
2025
-					$statuses[$item[$column]]['link'] = true;
2026
-				} else if (!isset($statuses[$item[$column]])) {
2027
-					$statuses[$item[$column]]['link'] = false;
2028
-				}
2029
-				if (!empty($item['file_target'])) {
2030
-					$statuses[$item[$column]]['path'] = $item['path'];
2031
-				}
2032
-			}
2033
-			return $statuses;
2034
-		} else {
2035
-			return $backend->formatItems($items, $format, $parameters);
2036
-		}
2037
-	}
2038
-
2039
-	/**
2040
-	 * remove protocol from URL
2041
-	 *
2042
-	 * @param string $url
2043
-	 * @return string
2044
-	 */
2045
-	public static function removeProtocolFromUrl($url) {
2046
-		if (strpos($url, 'https://') === 0) {
2047
-			return substr($url, strlen('https://'));
2048
-		} else if (strpos($url, 'http://') === 0) {
2049
-			return substr($url, strlen('http://'));
2050
-		}
2051
-
2052
-		return $url;
2053
-	}
2054
-
2055
-	/**
2056
-	 * try http post first with https and then with http as a fallback
2057
-	 *
2058
-	 * @param string $remoteDomain
2059
-	 * @param string $urlSuffix
2060
-	 * @param array $fields post parameters
2061
-	 * @return array
2062
-	 */
2063
-	private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
2064
-		$protocol = 'https://';
2065
-		$result = [
2066
-			'success' => false,
2067
-			'result' => '',
2068
-		];
2069
-		$try = 0;
2070
-		$discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
2071
-		while ($result['success'] === false && $try < 2) {
2072
-			$federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
2073
-			$endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
2074
-			$result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2075
-			$try++;
2076
-			$protocol = 'http://';
2077
-		}
2078
-
2079
-		return $result;
2080
-	}
2081
-
2082
-	/**
2083
-	 * send server-to-server share to remote server
2084
-	 *
2085
-	 * @param string $token
2086
-	 * @param string $shareWith
2087
-	 * @param string $name
2088
-	 * @param int $remote_id
2089
-	 * @param string $owner
2090
-	 * @return bool
2091
-	 */
2092
-	private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2093
-
2094
-		list($user, $remote) = Helper::splitUserRemote($shareWith);
2095
-
2096
-		if ($user && $remote) {
2097
-			$url = $remote;
2098
-
2099
-			$local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2100
-
2101
-			$fields = array(
2102
-				'shareWith' => $user,
2103
-				'token' => $token,
2104
-				'name' => $name,
2105
-				'remoteId' => $remote_id,
2106
-				'owner' => $owner,
2107
-				'remote' => $local,
2108
-			);
2109
-
2110
-			$url = self::removeProtocolFromUrl($url);
2111
-			$result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2112
-			$status = json_decode($result['result'], true);
2113
-
2114
-			if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2115
-				\OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
2116
-				return true;
2117
-			}
2118
-
2119
-		}
2120
-
2121
-		return false;
2122
-	}
2123
-
2124
-	/**
2125
-	 * send server-to-server unshare to remote server
2126
-	 *
2127
-	 * @param string $remote url
2128
-	 * @param int $id share id
2129
-	 * @param string $token
2130
-	 * @return bool
2131
-	 */
2132
-	private static function sendRemoteUnshare($remote, $id, $token) {
2133
-		$url = rtrim($remote, '/');
2134
-		$fields = array('token' => $token, 'format' => 'json');
2135
-		$url = self::removeProtocolFromUrl($url);
2136
-		$result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2137
-		$status = json_decode($result['result'], true);
2138
-
2139
-		return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2140
-	}
2141
-
2142
-	/**
2143
-	 * check if user can only share with group members
2144
-	 * @return bool
2145
-	 */
2146
-	public static function shareWithGroupMembersOnly() {
2147
-		$value = \OC::$server->getAppConfig()->getValue('core', 'shareapi_only_share_with_group_members', 'no');
2148
-		return ($value === 'yes') ? true : false;
2149
-	}
2150
-
2151
-	/**
2152
-	 * @return bool
2153
-	 */
2154
-	public static function isDefaultExpireDateEnabled() {
2155
-		$defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2156
-		return ($defaultExpireDateEnabled === "yes") ? true : false;
2157
-	}
2158
-
2159
-	/**
2160
-	 * @return bool
2161
-	 */
2162
-	public static function enforceDefaultExpireDate() {
2163
-		$enforceDefaultExpireDate = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
2164
-		return ($enforceDefaultExpireDate === "yes") ? true : false;
2165
-	}
2166
-
2167
-	/**
2168
-	 * @return int
2169
-	 */
2170
-	public static function getExpireInterval() {
2171
-		return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2172
-	}
2173
-
2174
-	/**
2175
-	 * Checks whether the given path is reachable for the given owner
2176
-	 *
2177
-	 * @param string $path path relative to files
2178
-	 * @param string $ownerStorageId storage id of the owner
2179
-	 *
2180
-	 * @return boolean true if file is reachable, false otherwise
2181
-	 */
2182
-	private static function isFileReachable($path, $ownerStorageId) {
2183
-		// if outside the home storage, file is always considered reachable
2184
-		if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2185
-			substr($ownerStorageId, 0, 13) === 'object::user:'
2186
-		)) {
2187
-			return true;
2188
-		}
2189
-
2190
-		// if inside the home storage, the file has to be under "/files/"
2191
-		$path = ltrim($path, '/');
2192
-		if (substr($path, 0, 6) === 'files/') {
2193
-			return true;
2194
-		}
2195
-
2196
-		return false;
2197
-	}
2198
-
2199
-	/**
2200
-	 * @param IConfig $config
2201
-	 * @return bool
2202
-	 */
2203
-	public static function enforcePassword(IConfig $config) {
2204
-		$enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2205
-		return ($enforcePassword === "yes") ? true : false;
2206
-	}
2207
-
2208
-	/**
2209
-	 * Get all share entries, including non-unique group items
2210
-	 *
2211
-	 * @param string $owner
2212
-	 * @return array
2213
-	 */
2214
-	public static function getAllSharesForOwner($owner) {
2215
-		$query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
2216
-		$result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
2217
-		return $result->fetchAll();
2218
-	}
2219
-
2220
-	/**
2221
-	 * Get all share entries, including non-unique group items for a file
2222
-	 *
2223
-	 * @param int $id
2224
-	 * @return array
2225
-	 */
2226
-	public static function getAllSharesForFileId($id) {
2227
-		$query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
2228
-		$result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
2229
-		return $result->fetchAll();
2230
-	}
2231
-
2232
-	/**
2233
-	 * @param string $password
2234
-	 * @throws \Exception
2235
-	 */
2236
-	private static function verifyPassword($password) {
2237
-
2238
-		$accepted = true;
2239
-		$message = '';
2240
-		\OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2241
-			'password' => $password,
2242
-			'accepted' => &$accepted,
2243
-			'message' => &$message
2244
-		]);
2245
-
2246
-		if (!$accepted) {
2247
-			throw new \Exception($message);
2248
-		}
2249
-	}
731
+        $result = $query->execute(array($status, $itemType, $itemSource, $shareType, $recipient));
732
+
733
+        if($result === false) {
734
+            \OCP\Util::writeLog('OCP\Share', 'Couldn\'t set send mail status', \OCP\Util::ERROR);
735
+        }
736
+    }
737
+
738
+    /**
739
+     * validate expiration date if it meets all constraints
740
+     *
741
+     * @param string $expireDate well formatted date string, e.g. "DD-MM-YYYY"
742
+     * @param string $shareTime timestamp when the file was shared
743
+     * @param string $itemType
744
+     * @param string $itemSource
745
+     * @return \DateTime validated date
746
+     * @throws \Exception when the expire date is in the past or further in the future then the enforced date
747
+     */
748
+    private static function validateExpireDate($expireDate, $shareTime, $itemType, $itemSource) {
749
+        $l = \OC::$server->getL10N('lib');
750
+        $date = new \DateTime($expireDate);
751
+        $today = new \DateTime('now');
752
+
753
+        // if the user doesn't provide a share time we need to get it from the database
754
+        // fall-back mode to keep API stable, because the $shareTime parameter was added later
755
+        $defaultExpireDateEnforced = \OCP\Util::isDefaultExpireDateEnforced();
756
+        if ($defaultExpireDateEnforced && $shareTime === null) {
757
+            $items = self::getItemShared($itemType, $itemSource);
758
+            $firstItem = reset($items);
759
+            $shareTime = (int)$firstItem['stime'];
760
+        }
761
+
762
+        if ($defaultExpireDateEnforced) {
763
+            // initialize max date with share time
764
+            $maxDate = new \DateTime();
765
+            $maxDate->setTimestamp($shareTime);
766
+            $maxDays = \OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
767
+            $maxDate->add(new \DateInterval('P' . $maxDays . 'D'));
768
+            if ($date > $maxDate) {
769
+                $warning = 'Cannot set expiration date. Shares cannot expire later than ' . $maxDays . ' after they have been shared';
770
+                $warning_t = $l->t('Cannot set expiration date. Shares cannot expire later than %s after they have been shared', array($maxDays));
771
+                \OCP\Util::writeLog('OCP\Share', $warning, \OCP\Util::WARN);
772
+                throw new \Exception($warning_t);
773
+            }
774
+        }
775
+
776
+        if ($date < $today) {
777
+            $message = 'Cannot set expiration date. Expiration date is in the past';
778
+            $message_t = $l->t('Cannot set expiration date. Expiration date is in the past');
779
+            \OCP\Util::writeLog('OCP\Share', $message, \OCP\Util::WARN);
780
+            throw new \Exception($message_t);
781
+        }
782
+
783
+        return $date;
784
+    }
785
+
786
+    /**
787
+     * Retrieve the owner of a connection
788
+     *
789
+     * @param IDBConnection $connection
790
+     * @param int $shareId
791
+     * @throws \Exception
792
+     * @return string uid of share owner
793
+     */
794
+    private static function getShareOwner(IDBConnection $connection, $shareId) {
795
+        $qb = $connection->getQueryBuilder();
796
+
797
+        $qb->select('uid_owner')
798
+            ->from('share')
799
+            ->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
800
+            ->setParameter(':shareId', $shareId);
801
+        $dbResult = $qb->execute();
802
+        $result = $dbResult->fetch();
803
+        $dbResult->closeCursor();
804
+
805
+        if (empty($result)) {
806
+            throw new \Exception('Share not found');
807
+        }
808
+
809
+        return $result['uid_owner'];
810
+    }
811
+
812
+    /**
813
+     * Set password for a public link share
814
+     *
815
+     * @param IUserSession $userSession
816
+     * @param IDBConnection $connection
817
+     * @param IConfig $config
818
+     * @param int $shareId
819
+     * @param string $password
820
+     * @throws \Exception
821
+     * @return boolean
822
+     */
823
+    public static function setPassword(IUserSession $userSession,
824
+                                        IDBConnection $connection,
825
+                                        IConfig $config,
826
+                                        $shareId, $password) {
827
+        $user = $userSession->getUser();
828
+        if (is_null($user)) {
829
+            throw new \Exception("User not logged in");
830
+        }
831
+
832
+        $uid = self::getShareOwner($connection, $shareId);
833
+
834
+        if ($uid !== $user->getUID()) {
835
+            throw new \Exception('Cannot update share of a different user');
836
+        }
837
+
838
+        if ($password === '') {
839
+            $password = null;
840
+        }
841
+
842
+        //If passwords are enforced the password can't be null
843
+        if (self::enforcePassword($config) && is_null($password)) {
844
+            throw new \Exception('Cannot remove password');
845
+        }
846
+
847
+        self::verifyPassword($password);
848
+
849
+        $qb = $connection->getQueryBuilder();
850
+        $qb->update('share')
851
+            ->set('share_with', $qb->createParameter('pass'))
852
+            ->where($qb->expr()->eq('id', $qb->createParameter('shareId')))
853
+            ->setParameter(':pass', is_null($password) ? null : \OC::$server->getHasher()->hash($password))
854
+            ->setParameter(':shareId', $shareId);
855
+
856
+        $qb->execute();
857
+
858
+        return true;
859
+    }
860
+
861
+    /**
862
+     * Checks whether a share has expired, calls unshareItem() if yes.
863
+     * @param array $item Share data (usually database row)
864
+     * @return boolean True if item was expired, false otherwise.
865
+     */
866
+    protected static function expireItem(array $item) {
867
+
868
+        $result = false;
869
+
870
+        // only use default expiration date for link shares
871
+        if ((int) $item['share_type'] === self::SHARE_TYPE_LINK) {
872
+
873
+            // calculate expiration date
874
+            if (!empty($item['expiration'])) {
875
+                $userDefinedExpire = new \DateTime($item['expiration']);
876
+                $expires = $userDefinedExpire->getTimestamp();
877
+            } else {
878
+                $expires = null;
879
+            }
880
+
881
+
882
+            // get default expiration settings
883
+            $defaultSettings = Helper::getDefaultExpireSetting();
884
+            $expires = Helper::calculateExpireDate($defaultSettings, $item['stime'], $expires);
885
+
886
+
887
+            if (is_int($expires)) {
888
+                $now = time();
889
+                if ($now > $expires) {
890
+                    self::unshareItem($item);
891
+                    $result = true;
892
+                }
893
+            }
894
+        }
895
+        return $result;
896
+    }
897
+
898
+    /**
899
+     * Unshares a share given a share data array
900
+     * @param array $item Share data (usually database row)
901
+     * @param int $newParent parent ID
902
+     * @return null
903
+     */
904
+    protected static function unshareItem(array $item, $newParent = null) {
905
+
906
+        $shareType = (int)$item['share_type'];
907
+        $shareWith = null;
908
+        if ($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
909
+            $shareWith = $item['share_with'];
910
+        }
911
+
912
+        // Pass all the vars we have for now, they may be useful
913
+        $hookParams = array(
914
+            'id'            => $item['id'],
915
+            'itemType'      => $item['item_type'],
916
+            'itemSource'    => $item['item_source'],
917
+            'shareType'     => $shareType,
918
+            'shareWith'     => $shareWith,
919
+            'itemParent'    => $item['parent'],
920
+            'uidOwner'      => $item['uid_owner'],
921
+        );
922
+        if($item['item_type'] === 'file' || $item['item_type'] === 'folder') {
923
+            $hookParams['fileSource'] = $item['file_source'];
924
+            $hookParams['fileTarget'] = $item['file_target'];
925
+        }
926
+
927
+        \OC_Hook::emit('OCP\Share', 'pre_unshare', $hookParams);
928
+        $deletedShares = Helper::delete($item['id'], false, null, $newParent);
929
+        $deletedShares[] = $hookParams;
930
+        $hookParams['deletedShares'] = $deletedShares;
931
+        \OC_Hook::emit('OCP\Share', 'post_unshare', $hookParams);
932
+        if ((int)$item['share_type'] === \OCP\Share::SHARE_TYPE_REMOTE && \OC::$server->getUserSession()->getUser()) {
933
+            list(, $remote) = Helper::splitUserRemote($item['share_with']);
934
+            self::sendRemoteUnshare($remote, $item['id'], $item['token']);
935
+        }
936
+    }
937
+
938
+    /**
939
+     * Get the backend class for the specified item type
940
+     * @param string $itemType
941
+     * @throws \Exception
942
+     * @return \OCP\Share_Backend
943
+     */
944
+    public static function getBackend($itemType) {
945
+        $l = \OC::$server->getL10N('lib');
946
+        if (isset(self::$backends[$itemType])) {
947
+            return self::$backends[$itemType];
948
+        } else if (isset(self::$backendTypes[$itemType]['class'])) {
949
+            $class = self::$backendTypes[$itemType]['class'];
950
+            if (class_exists($class)) {
951
+                self::$backends[$itemType] = new $class;
952
+                if (!(self::$backends[$itemType] instanceof \OCP\Share_Backend)) {
953
+                    $message = 'Sharing backend %s must implement the interface OCP\Share_Backend';
954
+                    $message_t = $l->t('Sharing backend %s must implement the interface OCP\Share_Backend', array($class));
955
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
956
+                    throw new \Exception($message_t);
957
+                }
958
+                return self::$backends[$itemType];
959
+            } else {
960
+                $message = 'Sharing backend %s not found';
961
+                $message_t = $l->t('Sharing backend %s not found', array($class));
962
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $class), \OCP\Util::ERROR);
963
+                throw new \Exception($message_t);
964
+            }
965
+        }
966
+        $message = 'Sharing backend for %s not found';
967
+        $message_t = $l->t('Sharing backend for %s not found', array($itemType));
968
+        \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemType), \OCP\Util::ERROR);
969
+        throw new \Exception($message_t);
970
+    }
971
+
972
+    /**
973
+     * Check if resharing is allowed
974
+     * @return boolean true if allowed or false
975
+     *
976
+     * Resharing is allowed by default if not configured
977
+     */
978
+    public static function isResharingAllowed() {
979
+        if (!isset(self::$isResharingAllowed)) {
980
+            if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_resharing', 'yes') == 'yes') {
981
+                self::$isResharingAllowed = true;
982
+            } else {
983
+                self::$isResharingAllowed = false;
984
+            }
985
+        }
986
+        return self::$isResharingAllowed;
987
+    }
988
+
989
+    /**
990
+     * Get a list of collection item types for the specified item type
991
+     * @param string $itemType
992
+     * @return array
993
+     */
994
+    private static function getCollectionItemTypes($itemType) {
995
+        $collectionTypes = array($itemType);
996
+        foreach (self::$backendTypes as $type => $backend) {
997
+            if (in_array($backend['collectionOf'], $collectionTypes)) {
998
+                $collectionTypes[] = $type;
999
+            }
1000
+        }
1001
+        // TODO Add option for collections to be collection of themselves, only 'folder' does it now...
1002
+        if (isset(self::$backendTypes[$itemType]) && (!self::getBackend($itemType) instanceof \OCP\Share_Backend_Collection || $itemType != 'folder')) {
1003
+            unset($collectionTypes[0]);
1004
+        }
1005
+        // Return array if collections were found or the item type is a
1006
+        // collection itself - collections can be inside collections
1007
+        if (count($collectionTypes) > 0) {
1008
+            return $collectionTypes;
1009
+        }
1010
+        return false;
1011
+    }
1012
+
1013
+    /**
1014
+     * Get the owners of items shared with a user.
1015
+     *
1016
+     * @param string $user The user the items are shared with.
1017
+     * @param string $type The type of the items shared with the user.
1018
+     * @param boolean $includeCollections Include collection item types (optional)
1019
+     * @param boolean $includeOwner include owner in the list of users the item is shared with (optional)
1020
+     * @return array
1021
+     */
1022
+    public static function getSharedItemsOwners($user, $type, $includeCollections = false, $includeOwner = false) {
1023
+        // First, we find out if $type is part of a collection (and if that collection is part of
1024
+        // another one and so on).
1025
+        $collectionTypes = array();
1026
+        if (!$includeCollections || !$collectionTypes = self::getCollectionItemTypes($type)) {
1027
+            $collectionTypes[] = $type;
1028
+        }
1029
+
1030
+        // Of these collection types, along with our original $type, we make a
1031
+        // list of the ones for which a sharing backend has been registered.
1032
+        // FIXME: Ideally, we wouldn't need to nest getItemsSharedWith in this loop but just call it
1033
+        // with its $includeCollections parameter set to true. Unfortunately, this fails currently.
1034
+        $allMaybeSharedItems = array();
1035
+        foreach ($collectionTypes as $collectionType) {
1036
+            if (isset(self::$backends[$collectionType])) {
1037
+                $allMaybeSharedItems[$collectionType] = self::getItemsSharedWithUser(
1038
+                    $collectionType,
1039
+                    $user,
1040
+                    self::FORMAT_NONE
1041
+                );
1042
+            }
1043
+        }
1044
+
1045
+        $owners = array();
1046
+        if ($includeOwner) {
1047
+            $owners[] = $user;
1048
+        }
1049
+
1050
+        // We take a look at all shared items of the given $type (or of the collections it is part of)
1051
+        // and find out their owners. Then, we gather the tags for the original $type from all owners,
1052
+        // and return them as elements of a list that look like "Tag (owner)".
1053
+        foreach ($allMaybeSharedItems as $collectionType => $maybeSharedItems) {
1054
+            foreach ($maybeSharedItems as $sharedItem) {
1055
+                if (isset($sharedItem['id'])) { //workaround for https://github.com/owncloud/core/issues/2814
1056
+                    $owners[] = $sharedItem['uid_owner'];
1057
+                }
1058
+            }
1059
+        }
1060
+
1061
+        return $owners;
1062
+    }
1063
+
1064
+    /**
1065
+     * Get shared items from the database
1066
+     * @param string $itemType
1067
+     * @param string $item Item source or target (optional)
1068
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, SHARE_TYPE_LINK, $shareTypeUserAndGroups, or $shareTypeGroupUserUnique
1069
+     * @param string $shareWith User or group the item is being shared with
1070
+     * @param string $uidOwner User that is the owner of shared items (optional)
1071
+     * @param int $format Format to convert items to with formatItems() (optional)
1072
+     * @param mixed $parameters to pass to formatItems() (optional)
1073
+     * @param int $limit Number of items to return, -1 to return all matches (optional)
1074
+     * @param boolean $includeCollections Include collection item types (optional)
1075
+     * @param boolean $itemShareWithBySource (optional)
1076
+     * @param boolean $checkExpireDate
1077
+     * @return array
1078
+     *
1079
+     * See public functions getItem(s)... for parameter usage
1080
+     *
1081
+     */
1082
+    public static function getItems($itemType, $item = null, $shareType = null, $shareWith = null,
1083
+                                    $uidOwner = null, $format = self::FORMAT_NONE, $parameters = null, $limit = -1,
1084
+                                    $includeCollections = false, $itemShareWithBySource = false, $checkExpireDate  = true) {
1085
+        if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_enabled', 'yes') != 'yes') {
1086
+            return array();
1087
+        }
1088
+        $backend = self::getBackend($itemType);
1089
+        $collectionTypes = false;
1090
+        // Get filesystem root to add it to the file target and remove from the
1091
+        // file source, match file_source with the file cache
1092
+        if ($itemType == 'file' || $itemType == 'folder') {
1093
+            if(!is_null($uidOwner)) {
1094
+                $root = \OC\Files\Filesystem::getRoot();
1095
+            } else {
1096
+                $root = '';
1097
+            }
1098
+            $where = 'INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` ';
1099
+            if (!isset($item)) {
1100
+                $where .= ' AND `file_target` IS NOT NULL ';
1101
+            }
1102
+            $where .= 'INNER JOIN `*PREFIX*storages` ON `numeric_id` = `*PREFIX*filecache`.`storage` ';
1103
+            $fileDependent = true;
1104
+            $queryArgs = array();
1105
+        } else {
1106
+            $fileDependent = false;
1107
+            $root = '';
1108
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1109
+            if ($includeCollections && !isset($item) && $collectionTypes) {
1110
+                // If includeCollections is true, find collections of this item type, e.g. a music album contains songs
1111
+                if (!in_array($itemType, $collectionTypes)) {
1112
+                    $itemTypes = array_merge(array($itemType), $collectionTypes);
1113
+                } else {
1114
+                    $itemTypes = $collectionTypes;
1115
+                }
1116
+                $placeholders = join(',', array_fill(0, count($itemTypes), '?'));
1117
+                $where = ' WHERE `item_type` IN ('.$placeholders.'))';
1118
+                $queryArgs = $itemTypes;
1119
+            } else {
1120
+                $where = ' WHERE `item_type` = ?';
1121
+                $queryArgs = array($itemType);
1122
+            }
1123
+        }
1124
+        if (\OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_links', 'yes') !== 'yes') {
1125
+            $where .= ' AND `share_type` != ?';
1126
+            $queryArgs[] = self::SHARE_TYPE_LINK;
1127
+        }
1128
+        if (isset($shareType)) {
1129
+            // Include all user and group items
1130
+            if ($shareType == self::$shareTypeUserAndGroups && isset($shareWith)) {
1131
+                $where .= ' AND ((`share_type` in (?, ?) AND `share_with` = ?) ';
1132
+                $queryArgs[] = self::SHARE_TYPE_USER;
1133
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1134
+                $queryArgs[] = $shareWith;
1135
+
1136
+                $user = \OC::$server->getUserManager()->get($shareWith);
1137
+                $groups = [];
1138
+                if ($user) {
1139
+                    $groups = \OC::$server->getGroupManager()->getUserGroupIds($user);
1140
+                }
1141
+                if (!empty($groups)) {
1142
+                    $placeholders = join(',', array_fill(0, count($groups), '?'));
1143
+                    $where .= ' OR (`share_type` = ? AND `share_with` IN ('.$placeholders.')) ';
1144
+                    $queryArgs[] = self::SHARE_TYPE_GROUP;
1145
+                    $queryArgs = array_merge($queryArgs, $groups);
1146
+                }
1147
+                $where .= ')';
1148
+                // Don't include own group shares
1149
+                $where .= ' AND `uid_owner` != ?';
1150
+                $queryArgs[] = $shareWith;
1151
+            } else {
1152
+                $where .= ' AND `share_type` = ?';
1153
+                $queryArgs[] = $shareType;
1154
+                if (isset($shareWith)) {
1155
+                    $where .= ' AND `share_with` = ?';
1156
+                    $queryArgs[] = $shareWith;
1157
+                }
1158
+            }
1159
+        }
1160
+        if (isset($uidOwner)) {
1161
+            $where .= ' AND `uid_owner` = ?';
1162
+            $queryArgs[] = $uidOwner;
1163
+            if (!isset($shareType)) {
1164
+                // Prevent unique user targets for group shares from being selected
1165
+                $where .= ' AND `share_type` != ?';
1166
+                $queryArgs[] = self::$shareTypeGroupUserUnique;
1167
+            }
1168
+            if ($fileDependent) {
1169
+                $column = 'file_source';
1170
+            } else {
1171
+                $column = 'item_source';
1172
+            }
1173
+        } else {
1174
+            if ($fileDependent) {
1175
+                $column = 'file_target';
1176
+            } else {
1177
+                $column = 'item_target';
1178
+            }
1179
+        }
1180
+        if (isset($item)) {
1181
+            $collectionTypes = self::getCollectionItemTypes($itemType);
1182
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1183
+                $where .= ' AND (';
1184
+            } else {
1185
+                $where .= ' AND';
1186
+            }
1187
+            // If looking for own shared items, check item_source else check item_target
1188
+            if (isset($uidOwner) || $itemShareWithBySource) {
1189
+                // If item type is a file, file source needs to be checked in case the item was converted
1190
+                if ($fileDependent) {
1191
+                    $where .= ' `file_source` = ?';
1192
+                    $column = 'file_source';
1193
+                } else {
1194
+                    $where .= ' `item_source` = ?';
1195
+                    $column = 'item_source';
1196
+                }
1197
+            } else {
1198
+                if ($fileDependent) {
1199
+                    $where .= ' `file_target` = ?';
1200
+                    $item = \OC\Files\Filesystem::normalizePath($item);
1201
+                } else {
1202
+                    $where .= ' `item_target` = ?';
1203
+                }
1204
+            }
1205
+            $queryArgs[] = $item;
1206
+            if ($includeCollections && $collectionTypes && !in_array('folder', $collectionTypes)) {
1207
+                $placeholders = join(',', array_fill(0, count($collectionTypes), '?'));
1208
+                $where .= ' OR `item_type` IN ('.$placeholders.'))';
1209
+                $queryArgs = array_merge($queryArgs, $collectionTypes);
1210
+            }
1211
+        }
1212
+
1213
+        if ($shareType == self::$shareTypeUserAndGroups && $limit === 1) {
1214
+            // Make sure the unique user target is returned if it exists,
1215
+            // unique targets should follow the group share in the database
1216
+            // If the limit is not 1, the filtering can be done later
1217
+            $where .= ' ORDER BY `*PREFIX*share`.`id` DESC';
1218
+        } else {
1219
+            $where .= ' ORDER BY `*PREFIX*share`.`id` ASC';
1220
+        }
1221
+
1222
+        if ($limit != -1 && !$includeCollections) {
1223
+            // The limit must be at least 3, because filtering needs to be done
1224
+            if ($limit < 3) {
1225
+                $queryLimit = 3;
1226
+            } else {
1227
+                $queryLimit = $limit;
1228
+            }
1229
+        } else {
1230
+            $queryLimit = null;
1231
+        }
1232
+        $select = self::createSelectStatement($format, $fileDependent, $uidOwner);
1233
+        $root = strlen($root);
1234
+        $query = \OC_DB::prepare('SELECT '.$select.' FROM `*PREFIX*share` '.$where, $queryLimit);
1235
+        $result = $query->execute($queryArgs);
1236
+        if ($result === false) {
1237
+            \OCP\Util::writeLog('OCP\Share',
1238
+                \OC_DB::getErrorMessage() . ', select=' . $select . ' where=',
1239
+                \OCP\Util::ERROR);
1240
+        }
1241
+        $items = array();
1242
+        $targets = array();
1243
+        $switchedItems = array();
1244
+        $mounts = array();
1245
+        while ($row = $result->fetchRow()) {
1246
+            self::transformDBResults($row);
1247
+            // Filter out duplicate group shares for users with unique targets
1248
+            if ($fileDependent && !self::isFileReachable($row['path'], $row['storage_id'])) {
1249
+                continue;
1250
+            }
1251
+            if ($row['share_type'] == self::$shareTypeGroupUserUnique && isset($items[$row['parent']])) {
1252
+                $row['share_type'] = self::SHARE_TYPE_GROUP;
1253
+                $row['unique_name'] = true; // remember that we use a unique name for this user
1254
+                $row['share_with'] = $items[$row['parent']]['share_with'];
1255
+                // if the group share was unshared from the user we keep the permission, otherwise
1256
+                // we take the permission from the parent because this is always the up-to-date
1257
+                // permission for the group share
1258
+                if ($row['permissions'] > 0) {
1259
+                    $row['permissions'] = $items[$row['parent']]['permissions'];
1260
+                }
1261
+                // Remove the parent group share
1262
+                unset($items[$row['parent']]);
1263
+                if ($row['permissions'] == 0) {
1264
+                    continue;
1265
+                }
1266
+            } else if (!isset($uidOwner)) {
1267
+                // Check if the same target already exists
1268
+                if (isset($targets[$row['id']])) {
1269
+                    // Check if the same owner shared with the user twice
1270
+                    // through a group and user share - this is allowed
1271
+                    $id = $targets[$row['id']];
1272
+                    if (isset($items[$id]) && $items[$id]['uid_owner'] == $row['uid_owner']) {
1273
+                        // Switch to group share type to ensure resharing conditions aren't bypassed
1274
+                        if ($items[$id]['share_type'] != self::SHARE_TYPE_GROUP) {
1275
+                            $items[$id]['share_type'] = self::SHARE_TYPE_GROUP;
1276
+                            $items[$id]['share_with'] = $row['share_with'];
1277
+                        }
1278
+                        // Switch ids if sharing permission is granted on only
1279
+                        // one share to ensure correct parent is used if resharing
1280
+                        if (~(int)$items[$id]['permissions'] & \OCP\Constants::PERMISSION_SHARE
1281
+                            && (int)$row['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1282
+                            $items[$row['id']] = $items[$id];
1283
+                            $switchedItems[$id] = $row['id'];
1284
+                            unset($items[$id]);
1285
+                            $id = $row['id'];
1286
+                        }
1287
+                        $items[$id]['permissions'] |= (int)$row['permissions'];
1288
+
1289
+                    }
1290
+                    continue;
1291
+                } elseif (!empty($row['parent'])) {
1292
+                    $targets[$row['parent']] = $row['id'];
1293
+                }
1294
+            }
1295
+            // Remove root from file source paths if retrieving own shared items
1296
+            if (isset($uidOwner) && isset($row['path'])) {
1297
+                if (isset($row['parent'])) {
1298
+                    $query = \OC_DB::prepare('SELECT `file_target` FROM `*PREFIX*share` WHERE `id` = ?');
1299
+                    $parentResult = $query->execute(array($row['parent']));
1300
+                    if ($result === false) {
1301
+                        \OCP\Util::writeLog('OCP\Share', 'Can\'t select parent: ' .
1302
+                            \OC_DB::getErrorMessage() . ', select=' . $select . ' where=' . $where,
1303
+                            \OCP\Util::ERROR);
1304
+                    } else {
1305
+                        $parentRow = $parentResult->fetchRow();
1306
+                        $tmpPath = $parentRow['file_target'];
1307
+                        // find the right position where the row path continues from the target path
1308
+                        $pos = strrpos($row['path'], $parentRow['file_target']);
1309
+                        $subPath = substr($row['path'], $pos);
1310
+                        $splitPath = explode('/', $subPath);
1311
+                        foreach (array_slice($splitPath, 2) as $pathPart) {
1312
+                            $tmpPath = $tmpPath . '/' . $pathPart;
1313
+                        }
1314
+                        $row['path'] = $tmpPath;
1315
+                    }
1316
+                } else {
1317
+                    if (!isset($mounts[$row['storage']])) {
1318
+                        $mountPoints = \OC\Files\Filesystem::getMountByNumericId($row['storage']);
1319
+                        if (is_array($mountPoints) && !empty($mountPoints)) {
1320
+                            $mounts[$row['storage']] = current($mountPoints);
1321
+                        }
1322
+                    }
1323
+                    if (!empty($mounts[$row['storage']])) {
1324
+                        $path = $mounts[$row['storage']]->getMountPoint().$row['path'];
1325
+                        $relPath = substr($path, $root); // path relative to data/user
1326
+                        $row['path'] = rtrim($relPath, '/');
1327
+                    }
1328
+                }
1329
+            }
1330
+
1331
+            if($checkExpireDate) {
1332
+                if (self::expireItem($row)) {
1333
+                    continue;
1334
+                }
1335
+            }
1336
+            // Check if resharing is allowed, if not remove share permission
1337
+            if (isset($row['permissions']) && (!self::isResharingAllowed() | \OCP\Util::isSharingDisabledForUser())) {
1338
+                $row['permissions'] &= ~\OCP\Constants::PERMISSION_SHARE;
1339
+            }
1340
+            // Add display names to result
1341
+            $row['share_with_displayname'] = $row['share_with'];
1342
+            if ( isset($row['share_with']) && $row['share_with'] != '' &&
1343
+                $row['share_type'] === self::SHARE_TYPE_USER) {
1344
+                $row['share_with_displayname'] = \OCP\User::getDisplayName($row['share_with']);
1345
+            } else if(isset($row['share_with']) && $row['share_with'] != '' &&
1346
+                $row['share_type'] === self::SHARE_TYPE_REMOTE) {
1347
+                $addressBookEntries = \OC::$server->getContactsManager()->search($row['share_with'], ['CLOUD']);
1348
+                foreach ($addressBookEntries as $entry) {
1349
+                    foreach ($entry['CLOUD'] as $cloudID) {
1350
+                        if ($cloudID === $row['share_with']) {
1351
+                            $row['share_with_displayname'] = $entry['FN'];
1352
+                        }
1353
+                    }
1354
+                }
1355
+            }
1356
+            if ( isset($row['uid_owner']) && $row['uid_owner'] != '') {
1357
+                $row['displayname_owner'] = \OCP\User::getDisplayName($row['uid_owner']);
1358
+            }
1359
+
1360
+            if ($row['permissions'] > 0) {
1361
+                $items[$row['id']] = $row;
1362
+            }
1363
+
1364
+        }
1365
+
1366
+        // group items if we are looking for items shared with the current user
1367
+        if (isset($shareWith) && $shareWith === \OCP\User::getUser()) {
1368
+            $items = self::groupItems($items, $itemType);
1369
+        }
1370
+
1371
+        if (!empty($items)) {
1372
+            $collectionItems = array();
1373
+            foreach ($items as &$row) {
1374
+                // Return only the item instead of a 2-dimensional array
1375
+                if ($limit == 1 && $row[$column] == $item && ($row['item_type'] == $itemType || $itemType == 'file')) {
1376
+                    if ($format == self::FORMAT_NONE) {
1377
+                        return $row;
1378
+                    } else {
1379
+                        break;
1380
+                    }
1381
+                }
1382
+                // Check if this is a collection of the requested item type
1383
+                if ($includeCollections && $collectionTypes && $row['item_type'] !== 'folder' && in_array($row['item_type'], $collectionTypes)) {
1384
+                    if (($collectionBackend = self::getBackend($row['item_type']))
1385
+                        && $collectionBackend instanceof \OCP\Share_Backend_Collection) {
1386
+                        // Collections can be inside collections, check if the item is a collection
1387
+                        if (isset($item) && $row['item_type'] == $itemType && $row[$column] == $item) {
1388
+                            $collectionItems[] = $row;
1389
+                        } else {
1390
+                            $collection = array();
1391
+                            $collection['item_type'] = $row['item_type'];
1392
+                            if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1393
+                                $collection['path'] = basename($row['path']);
1394
+                            }
1395
+                            $row['collection'] = $collection;
1396
+                            // Fetch all of the children sources
1397
+                            $children = $collectionBackend->getChildren($row[$column]);
1398
+                            foreach ($children as $child) {
1399
+                                $childItem = $row;
1400
+                                $childItem['item_type'] = $itemType;
1401
+                                if ($row['item_type'] != 'file' && $row['item_type'] != 'folder') {
1402
+                                    $childItem['item_source'] = $child['source'];
1403
+                                    $childItem['item_target'] = $child['target'];
1404
+                                }
1405
+                                if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1406
+                                    if ($row['item_type'] == 'file' || $row['item_type'] == 'folder') {
1407
+                                        $childItem['file_source'] = $child['source'];
1408
+                                    } else { // TODO is this really needed if we already know that we use the file backend?
1409
+                                        $meta = \OC\Files\Filesystem::getFileInfo($child['file_path']);
1410
+                                        $childItem['file_source'] = $meta['fileid'];
1411
+                                    }
1412
+                                    $childItem['file_target'] =
1413
+                                        \OC\Files\Filesystem::normalizePath($child['file_path']);
1414
+                                }
1415
+                                if (isset($item)) {
1416
+                                    if ($childItem[$column] == $item) {
1417
+                                        // Return only the item instead of a 2-dimensional array
1418
+                                        if ($limit == 1) {
1419
+                                            if ($format == self::FORMAT_NONE) {
1420
+                                                return $childItem;
1421
+                                            } else {
1422
+                                                // Unset the items array and break out of both loops
1423
+                                                $items = array();
1424
+                                                $items[] = $childItem;
1425
+                                                break 2;
1426
+                                            }
1427
+                                        } else {
1428
+                                            $collectionItems[] = $childItem;
1429
+                                        }
1430
+                                    }
1431
+                                } else {
1432
+                                    $collectionItems[] = $childItem;
1433
+                                }
1434
+                            }
1435
+                        }
1436
+                    }
1437
+                    // Remove collection item
1438
+                    $toRemove = $row['id'];
1439
+                    if (array_key_exists($toRemove, $switchedItems)) {
1440
+                        $toRemove = $switchedItems[$toRemove];
1441
+                    }
1442
+                    unset($items[$toRemove]);
1443
+                } elseif ($includeCollections && $collectionTypes && in_array($row['item_type'], $collectionTypes)) {
1444
+                    // FIXME: Thats a dirty hack to improve file sharing performance,
1445
+                    // see github issue #10588 for more details
1446
+                    // Need to find a solution which works for all back-ends
1447
+                    $collectionBackend = self::getBackend($row['item_type']);
1448
+                    $sharedParents = $collectionBackend->getParents($row['item_source']);
1449
+                    foreach ($sharedParents as $parent) {
1450
+                        $collectionItems[] = $parent;
1451
+                    }
1452
+                }
1453
+            }
1454
+            if (!empty($collectionItems)) {
1455
+                $collectionItems = array_unique($collectionItems, SORT_REGULAR);
1456
+                $items = array_merge($items, $collectionItems);
1457
+            }
1458
+
1459
+            // filter out invalid items, these can appear when subshare entries exist
1460
+            // for a group in which the requested user isn't a member any more
1461
+            $items = array_filter($items, function($item) {
1462
+                return $item['share_type'] !== self::$shareTypeGroupUserUnique;
1463
+            });
1464
+
1465
+            return self::formatResult($items, $column, $backend, $format, $parameters);
1466
+        } elseif ($includeCollections && $collectionTypes && in_array('folder', $collectionTypes)) {
1467
+            // FIXME: Thats a dirty hack to improve file sharing performance,
1468
+            // see github issue #10588 for more details
1469
+            // Need to find a solution which works for all back-ends
1470
+            $collectionItems = array();
1471
+            $collectionBackend = self::getBackend('folder');
1472
+            $sharedParents = $collectionBackend->getParents($item, $shareWith, $uidOwner);
1473
+            foreach ($sharedParents as $parent) {
1474
+                $collectionItems[] = $parent;
1475
+            }
1476
+            if ($limit === 1) {
1477
+                return reset($collectionItems);
1478
+            }
1479
+            return self::formatResult($collectionItems, $column, $backend, $format, $parameters);
1480
+        }
1481
+
1482
+        return array();
1483
+    }
1484
+
1485
+    /**
1486
+     * group items with link to the same source
1487
+     *
1488
+     * @param array $items
1489
+     * @param string $itemType
1490
+     * @return array of grouped items
1491
+     */
1492
+    protected static function groupItems($items, $itemType) {
1493
+
1494
+        $fileSharing = ($itemType === 'file' || $itemType === 'folder') ? true : false;
1495
+
1496
+        $result = array();
1497
+
1498
+        foreach ($items as $item) {
1499
+            $grouped = false;
1500
+            foreach ($result as $key => $r) {
1501
+                // for file/folder shares we need to compare file_source, otherwise we compare item_source
1502
+                // only group shares if they already point to the same target, otherwise the file where shared
1503
+                // before grouping of shares was added. In this case we don't group them toi avoid confusions
1504
+                if (( $fileSharing && $item['file_source'] === $r['file_source'] && $item['file_target'] === $r['file_target']) ||
1505
+                    (!$fileSharing && $item['item_source'] === $r['item_source'] && $item['item_target'] === $r['item_target'])) {
1506
+                    // add the first item to the list of grouped shares
1507
+                    if (!isset($result[$key]['grouped'])) {
1508
+                        $result[$key]['grouped'][] = $result[$key];
1509
+                    }
1510
+                    $result[$key]['permissions'] = (int) $item['permissions'] | (int) $r['permissions'];
1511
+                    $result[$key]['grouped'][] = $item;
1512
+                    $grouped = true;
1513
+                    break;
1514
+                }
1515
+            }
1516
+
1517
+            if (!$grouped) {
1518
+                $result[] = $item;
1519
+            }
1520
+
1521
+        }
1522
+
1523
+        return $result;
1524
+    }
1525
+
1526
+    /**
1527
+     * Put shared item into the database
1528
+     * @param string $itemType Item type
1529
+     * @param string $itemSource Item source
1530
+     * @param int $shareType SHARE_TYPE_USER, SHARE_TYPE_GROUP, or SHARE_TYPE_LINK
1531
+     * @param string $shareWith User or group the item is being shared with
1532
+     * @param string $uidOwner User that is the owner of shared item
1533
+     * @param int $permissions CRUDS permissions
1534
+     * @param boolean|array $parentFolder Parent folder target (optional)
1535
+     * @param string $token (optional)
1536
+     * @param string $itemSourceName name of the source item (optional)
1537
+     * @param \DateTime $expirationDate (optional)
1538
+     * @throws \Exception
1539
+     * @return mixed id of the new share or false
1540
+     */
1541
+    private static function put($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1542
+                                $permissions, $parentFolder = null, $token = null, $itemSourceName = null, \DateTime $expirationDate = null) {
1543
+
1544
+        $queriesToExecute = array();
1545
+        $suggestedItemTarget = null;
1546
+        $groupFileTarget = $fileTarget = $suggestedFileTarget = $filePath = '';
1547
+        $groupItemTarget = $itemTarget = $fileSource = $parent = 0;
1548
+
1549
+        $result = self::checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate);
1550
+        if(!empty($result)) {
1551
+            $parent = $result['parent'];
1552
+            $itemSource = $result['itemSource'];
1553
+            $fileSource = $result['fileSource'];
1554
+            $suggestedItemTarget = $result['suggestedItemTarget'];
1555
+            $suggestedFileTarget = $result['suggestedFileTarget'];
1556
+            $filePath = $result['filePath'];
1557
+        }
1558
+
1559
+        $isGroupShare = false;
1560
+        if ($shareType == self::SHARE_TYPE_GROUP) {
1561
+            $isGroupShare = true;
1562
+            if (isset($shareWith['users'])) {
1563
+                $users = $shareWith['users'];
1564
+            } else {
1565
+                $group = \OC::$server->getGroupManager()->get($shareWith['group']);
1566
+                if ($group) {
1567
+                    $users = $group->searchUsers('', -1, 0);
1568
+                    $userIds = [];
1569
+                    foreach ($users as $user) {
1570
+                        $userIds[] = $user->getUID();
1571
+                    }
1572
+                    $users = $userIds;
1573
+                } else {
1574
+                    $users = [];
1575
+                }
1576
+            }
1577
+            // remove current user from list
1578
+            if (in_array(\OCP\User::getUser(), $users)) {
1579
+                unset($users[array_search(\OCP\User::getUser(), $users)]);
1580
+            }
1581
+            $groupItemTarget = Helper::generateTarget($itemType, $itemSource,
1582
+                $shareType, $shareWith['group'], $uidOwner, $suggestedItemTarget);
1583
+            $groupFileTarget = Helper::generateTarget($itemType, $itemSource,
1584
+                $shareType, $shareWith['group'], $uidOwner, $filePath);
1585
+
1586
+            // add group share to table and remember the id as parent
1587
+            $queriesToExecute['groupShare'] = array(
1588
+                'itemType'			=> $itemType,
1589
+                'itemSource'		=> $itemSource,
1590
+                'itemTarget'		=> $groupItemTarget,
1591
+                'shareType'			=> $shareType,
1592
+                'shareWith'			=> $shareWith['group'],
1593
+                'uidOwner'			=> $uidOwner,
1594
+                'permissions'		=> $permissions,
1595
+                'shareTime'			=> time(),
1596
+                'fileSource'		=> $fileSource,
1597
+                'fileTarget'		=> $groupFileTarget,
1598
+                'token'				=> $token,
1599
+                'parent'			=> $parent,
1600
+                'expiration'		=> $expirationDate,
1601
+            );
1602
+
1603
+        } else {
1604
+            $users = array($shareWith);
1605
+            $itemTarget = Helper::generateTarget($itemType, $itemSource, $shareType, $shareWith, $uidOwner,
1606
+                $suggestedItemTarget);
1607
+        }
1608
+
1609
+        $run = true;
1610
+        $error = '';
1611
+        $preHookData = array(
1612
+            'itemType' => $itemType,
1613
+            'itemSource' => $itemSource,
1614
+            'shareType' => $shareType,
1615
+            'uidOwner' => $uidOwner,
1616
+            'permissions' => $permissions,
1617
+            'fileSource' => $fileSource,
1618
+            'expiration' => $expirationDate,
1619
+            'token' => $token,
1620
+            'run' => &$run,
1621
+            'error' => &$error
1622
+        );
1623
+
1624
+        $preHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
1625
+        $preHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
1626
+
1627
+        \OC_Hook::emit('OCP\Share', 'pre_shared', $preHookData);
1628
+
1629
+        if ($run === false) {
1630
+            throw new \Exception($error);
1631
+        }
1632
+
1633
+        foreach ($users as $user) {
1634
+            $sourceId = ($itemType === 'file' || $itemType === 'folder') ? $fileSource : $itemSource;
1635
+            $sourceExists = self::getItemSharedWithBySource($itemType, $sourceId, self::FORMAT_NONE, null, true, $user);
1636
+
1637
+            $userShareType = ($isGroupShare) ? self::$shareTypeGroupUserUnique : $shareType;
1638
+
1639
+            if ($sourceExists && $sourceExists['item_source'] === $itemSource) {
1640
+                $fileTarget = $sourceExists['file_target'];
1641
+                $itemTarget = $sourceExists['item_target'];
1642
+
1643
+                // for group shares we don't need a additional entry if the target is the same
1644
+                if($isGroupShare && $groupItemTarget === $itemTarget) {
1645
+                    continue;
1646
+                }
1647
+
1648
+            } elseif(!$sourceExists && !$isGroupShare)  {
1649
+
1650
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, $userShareType, $user,
1651
+                    $uidOwner, $suggestedItemTarget, $parent);
1652
+                if (isset($fileSource)) {
1653
+                    if ($parentFolder) {
1654
+                        if ($parentFolder === true) {
1655
+                            $fileTarget = Helper::generateTarget('file', $filePath, $userShareType, $user,
1656
+                                $uidOwner, $suggestedFileTarget, $parent);
1657
+                            if ($fileTarget != $groupFileTarget) {
1658
+                                $parentFolders[$user]['folder'] = $fileTarget;
1659
+                            }
1660
+                        } else if (isset($parentFolder[$user])) {
1661
+                            $fileTarget = $parentFolder[$user]['folder'].$itemSource;
1662
+                            $parent = $parentFolder[$user]['id'];
1663
+                        }
1664
+                    } else {
1665
+                        $fileTarget = Helper::generateTarget('file', $filePath, $userShareType,
1666
+                            $user, $uidOwner, $suggestedFileTarget, $parent);
1667
+                    }
1668
+                } else {
1669
+                    $fileTarget = null;
1670
+                }
1671
+
1672
+            } else {
1673
+
1674
+                // group share which doesn't exists until now, check if we need a unique target for this user
1675
+
1676
+                $itemTarget = Helper::generateTarget($itemType, $itemSource, self::SHARE_TYPE_USER, $user,
1677
+                    $uidOwner, $suggestedItemTarget, $parent);
1678
+
1679
+                // do we also need a file target
1680
+                if (isset($fileSource)) {
1681
+                    $fileTarget = Helper::generateTarget('file', $filePath, self::SHARE_TYPE_USER, $user,
1682
+                        $uidOwner, $suggestedFileTarget, $parent);
1683
+                } else {
1684
+                    $fileTarget = null;
1685
+                }
1686
+
1687
+                if (($itemTarget === $groupItemTarget) &&
1688
+                    (!isset($fileSource) || $fileTarget === $groupFileTarget)) {
1689
+                    continue;
1690
+                }
1691
+            }
1692
+
1693
+            $queriesToExecute[] = array(
1694
+                'itemType'			=> $itemType,
1695
+                'itemSource'		=> $itemSource,
1696
+                'itemTarget'		=> $itemTarget,
1697
+                'shareType'			=> $userShareType,
1698
+                'shareWith'			=> $user,
1699
+                'uidOwner'			=> $uidOwner,
1700
+                'permissions'		=> $permissions,
1701
+                'shareTime'			=> time(),
1702
+                'fileSource'		=> $fileSource,
1703
+                'fileTarget'		=> $fileTarget,
1704
+                'token'				=> $token,
1705
+                'parent'			=> $parent,
1706
+                'expiration'		=> $expirationDate,
1707
+            );
1708
+
1709
+        }
1710
+
1711
+        $id = false;
1712
+        if ($isGroupShare) {
1713
+            $id = self::insertShare($queriesToExecute['groupShare']);
1714
+            // Save this id, any extra rows for this group share will need to reference it
1715
+            $parent = \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1716
+            unset($queriesToExecute['groupShare']);
1717
+        }
1718
+
1719
+        foreach ($queriesToExecute as $shareQuery) {
1720
+            $shareQuery['parent'] = $parent;
1721
+            $id = self::insertShare($shareQuery);
1722
+        }
1723
+
1724
+        $postHookData = array(
1725
+            'itemType' => $itemType,
1726
+            'itemSource' => $itemSource,
1727
+            'parent' => $parent,
1728
+            'shareType' => $shareType,
1729
+            'uidOwner' => $uidOwner,
1730
+            'permissions' => $permissions,
1731
+            'fileSource' => $fileSource,
1732
+            'id' => $parent,
1733
+            'token' => $token,
1734
+            'expirationDate' => $expirationDate,
1735
+        );
1736
+
1737
+        $postHookData['shareWith'] = ($isGroupShare) ? $shareWith['group'] : $shareWith;
1738
+        $postHookData['itemTarget'] = ($isGroupShare) ? $groupItemTarget : $itemTarget;
1739
+        $postHookData['fileTarget'] = ($isGroupShare) ? $groupFileTarget : $fileTarget;
1740
+
1741
+        \OC_Hook::emit('OCP\Share', 'post_shared', $postHookData);
1742
+
1743
+
1744
+        return $id ? $id : false;
1745
+    }
1746
+
1747
+    /**
1748
+     * @param string $itemType
1749
+     * @param string $itemSource
1750
+     * @param int $shareType
1751
+     * @param string $shareWith
1752
+     * @param string $uidOwner
1753
+     * @param int $permissions
1754
+     * @param string|null $itemSourceName
1755
+     * @param null|\DateTime $expirationDate
1756
+     */
1757
+    private static function checkReshare($itemType, $itemSource, $shareType, $shareWith, $uidOwner, $permissions, $itemSourceName, $expirationDate) {
1758
+        $backend = self::getBackend($itemType);
1759
+
1760
+        $l = \OC::$server->getL10N('lib');
1761
+        $result = array();
1762
+
1763
+        $column = ($itemType === 'file' || $itemType === 'folder') ? 'file_source' : 'item_source';
1764
+
1765
+        $checkReshare = self::getItemSharedWithBySource($itemType, $itemSource, self::FORMAT_NONE, null, true);
1766
+        if ($checkReshare) {
1767
+            // Check if attempting to share back to owner
1768
+            if ($checkReshare['uid_owner'] == $shareWith && $shareType == self::SHARE_TYPE_USER) {
1769
+                $message = 'Sharing %s failed, because the user %s is the original sharer';
1770
+                $message_t = $l->t('Sharing failed, because the user %s is the original sharer', [$shareWith]);
1771
+
1772
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $shareWith), \OCP\Util::DEBUG);
1773
+                throw new \Exception($message_t);
1774
+            }
1775
+        }
1776
+
1777
+        if ($checkReshare && $checkReshare['uid_owner'] !== \OC_User::getUser()) {
1778
+            // Check if share permissions is granted
1779
+            if (self::isResharingAllowed() && (int)$checkReshare['permissions'] & \OCP\Constants::PERMISSION_SHARE) {
1780
+                if (~(int)$checkReshare['permissions'] & $permissions) {
1781
+                    $message = 'Sharing %s failed, because the permissions exceed permissions granted to %s';
1782
+                    $message_t = $l->t('Sharing %s failed, because the permissions exceed permissions granted to %s', array($itemSourceName, $uidOwner));
1783
+
1784
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName, $uidOwner), \OCP\Util::DEBUG);
1785
+                    throw new \Exception($message_t);
1786
+                } else {
1787
+                    // TODO Don't check if inside folder
1788
+                    $result['parent'] = $checkReshare['id'];
1789
+
1790
+                    $result['expirationDate'] = $expirationDate;
1791
+                    // $checkReshare['expiration'] could be null and then is always less than any value
1792
+                    if(isset($checkReshare['expiration']) && $checkReshare['expiration'] < $expirationDate) {
1793
+                        $result['expirationDate'] = $checkReshare['expiration'];
1794
+                    }
1795
+
1796
+                    // only suggest the same name as new target if it is a reshare of the
1797
+                    // same file/folder and not the reshare of a child
1798
+                    if ($checkReshare[$column] === $itemSource) {
1799
+                        $result['filePath'] = $checkReshare['file_target'];
1800
+                        $result['itemSource'] = $checkReshare['item_source'];
1801
+                        $result['fileSource'] = $checkReshare['file_source'];
1802
+                        $result['suggestedItemTarget'] = $checkReshare['item_target'];
1803
+                        $result['suggestedFileTarget'] = $checkReshare['file_target'];
1804
+                    } else {
1805
+                        $result['filePath'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $backend->getFilePath($itemSource, $uidOwner) : null;
1806
+                        $result['suggestedItemTarget'] = null;
1807
+                        $result['suggestedFileTarget'] = null;
1808
+                        $result['itemSource'] = $itemSource;
1809
+                        $result['fileSource'] = ($backend instanceof \OCP\Share_Backend_File_Dependent) ? $itemSource : null;
1810
+                    }
1811
+                }
1812
+            } else {
1813
+                $message = 'Sharing %s failed, because resharing is not allowed';
1814
+                $message_t = $l->t('Sharing %s failed, because resharing is not allowed', array($itemSourceName));
1815
+
1816
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSourceName), \OCP\Util::DEBUG);
1817
+                throw new \Exception($message_t);
1818
+            }
1819
+        } else {
1820
+            $result['parent'] = null;
1821
+            $result['suggestedItemTarget'] = null;
1822
+            $result['suggestedFileTarget'] = null;
1823
+            $result['itemSource'] = $itemSource;
1824
+            $result['expirationDate'] = $expirationDate;
1825
+            if (!$backend->isValidSource($itemSource, $uidOwner)) {
1826
+                $message = 'Sharing %s failed, because the sharing backend for '
1827
+                    .'%s could not find its source';
1828
+                $message_t = $l->t('Sharing %s failed, because the sharing backend for %s could not find its source', array($itemSource, $itemType));
1829
+                \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource, $itemType), \OCP\Util::DEBUG);
1830
+                throw new \Exception($message_t);
1831
+            }
1832
+            if ($backend instanceof \OCP\Share_Backend_File_Dependent) {
1833
+                $result['filePath'] = $backend->getFilePath($itemSource, $uidOwner);
1834
+                if ($itemType == 'file' || $itemType == 'folder') {
1835
+                    $result['fileSource'] = $itemSource;
1836
+                } else {
1837
+                    $meta = \OC\Files\Filesystem::getFileInfo($result['filePath']);
1838
+                    $result['fileSource'] = $meta['fileid'];
1839
+                }
1840
+                if ($result['fileSource'] == -1) {
1841
+                    $message = 'Sharing %s failed, because the file could not be found in the file cache';
1842
+                    $message_t = $l->t('Sharing %s failed, because the file could not be found in the file cache', array($itemSource));
1843
+
1844
+                    \OCP\Util::writeLog('OCP\Share', sprintf($message, $itemSource), \OCP\Util::DEBUG);
1845
+                    throw new \Exception($message_t);
1846
+                }
1847
+            } else {
1848
+                $result['filePath'] = null;
1849
+                $result['fileSource'] = null;
1850
+            }
1851
+        }
1852
+
1853
+        return $result;
1854
+    }
1855
+
1856
+    /**
1857
+     *
1858
+     * @param array $shareData
1859
+     * @return mixed false in case of a failure or the id of the new share
1860
+     */
1861
+    private static function insertShare(array $shareData) {
1862
+
1863
+        $query = \OC_DB::prepare('INSERT INTO `*PREFIX*share` ('
1864
+            .' `item_type`, `item_source`, `item_target`, `share_type`,'
1865
+            .' `share_with`, `uid_owner`, `permissions`, `stime`, `file_source`,'
1866
+            .' `file_target`, `token`, `parent`, `expiration`) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)');
1867
+        $query->bindValue(1, $shareData['itemType']);
1868
+        $query->bindValue(2, $shareData['itemSource']);
1869
+        $query->bindValue(3, $shareData['itemTarget']);
1870
+        $query->bindValue(4, $shareData['shareType']);
1871
+        $query->bindValue(5, $shareData['shareWith']);
1872
+        $query->bindValue(6, $shareData['uidOwner']);
1873
+        $query->bindValue(7, $shareData['permissions']);
1874
+        $query->bindValue(8, $shareData['shareTime']);
1875
+        $query->bindValue(9, $shareData['fileSource']);
1876
+        $query->bindValue(10, $shareData['fileTarget']);
1877
+        $query->bindValue(11, $shareData['token']);
1878
+        $query->bindValue(12, $shareData['parent']);
1879
+        $query->bindValue(13, $shareData['expiration'], 'datetime');
1880
+        $result = $query->execute();
1881
+
1882
+        $id = false;
1883
+        if ($result) {
1884
+            $id =  \OC::$server->getDatabaseConnection()->lastInsertId('*PREFIX*share');
1885
+        }
1886
+
1887
+        return $id;
1888
+
1889
+    }
1890
+
1891
+    /**
1892
+     * In case a password protected link is not yet authenticated this function will return false
1893
+     *
1894
+     * @param array $linkItem
1895
+     * @return boolean
1896
+     */
1897
+    public static function checkPasswordProtectedShare(array $linkItem) {
1898
+        if (!isset($linkItem['share_with'])) {
1899
+            return true;
1900
+        }
1901
+        if (!isset($linkItem['share_type'])) {
1902
+            return true;
1903
+        }
1904
+        if (!isset($linkItem['id'])) {
1905
+            return true;
1906
+        }
1907
+
1908
+        if ($linkItem['share_type'] != \OCP\Share::SHARE_TYPE_LINK) {
1909
+            return true;
1910
+        }
1911
+
1912
+        if ( \OC::$server->getSession()->exists('public_link_authenticated')
1913
+            && \OC::$server->getSession()->get('public_link_authenticated') === (string)$linkItem['id'] ) {
1914
+            return true;
1915
+        }
1916
+
1917
+        return false;
1918
+    }
1919
+
1920
+    /**
1921
+     * construct select statement
1922
+     * @param int $format
1923
+     * @param boolean $fileDependent ist it a file/folder share or a generla share
1924
+     * @param string $uidOwner
1925
+     * @return string select statement
1926
+     */
1927
+    private static function createSelectStatement($format, $fileDependent, $uidOwner = null) {
1928
+        $select = '*';
1929
+        if ($format == self::FORMAT_STATUSES) {
1930
+            if ($fileDependent) {
1931
+                $select = '`*PREFIX*share`.`id`, `*PREFIX*share`.`parent`, `share_type`, `path`, `storage`, '
1932
+                    . '`share_with`, `uid_owner` , `file_source`, `stime`, `*PREFIX*share`.`permissions`, '
1933
+                    . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1934
+                    . '`uid_initiator`';
1935
+            } else {
1936
+                $select = '`id`, `parent`, `share_type`, `share_with`, `uid_owner`, `item_source`, `stime`, `*PREFIX*share`.`permissions`';
1937
+            }
1938
+        } else {
1939
+            if (isset($uidOwner)) {
1940
+                if ($fileDependent) {
1941
+                    $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`,'
1942
+                        . ' `share_type`, `share_with`, `file_source`, `file_target`, `path`, `*PREFIX*share`.`permissions`, `stime`,'
1943
+                        . ' `expiration`, `token`, `storage`, `mail_send`, `uid_owner`, '
1944
+                        . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1945
+                } else {
1946
+                    $select = '`id`, `item_type`, `item_source`, `parent`, `share_type`, `share_with`, `*PREFIX*share`.`permissions`,'
1947
+                        . ' `stime`, `file_source`, `expiration`, `token`, `mail_send`, `uid_owner`';
1948
+                }
1949
+            } else {
1950
+                if ($fileDependent) {
1951
+                    if ($format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_GET_FOLDER_CONTENTS || $format == \OCA\Files_Sharing\ShareBackend\File::FORMAT_FILE_APP_ROOT) {
1952
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `*PREFIX*share`.`parent`, `uid_owner`, '
1953
+                            . '`share_type`, `share_with`, `file_source`, `path`, `file_target`, `stime`, '
1954
+                            . '`*PREFIX*share`.`permissions`, `expiration`, `storage`, `*PREFIX*filecache`.`parent` as `file_parent`, '
1955
+                            . '`name`, `mtime`, `mimetype`, `mimepart`, `size`, `encrypted`, `etag`, `mail_send`';
1956
+                    } else {
1957
+                        $select = '`*PREFIX*share`.`id`, `item_type`, `item_source`, `item_target`,'
1958
+                            . '`*PREFIX*share`.`parent`, `share_type`, `share_with`, `uid_owner`,'
1959
+                            . '`file_source`, `path`, `file_target`, `*PREFIX*share`.`permissions`,'
1960
+                            . '`stime`, `expiration`, `token`, `storage`, `mail_send`,'
1961
+                            . '`*PREFIX*storages`.`id` AS `storage_id`, `*PREFIX*filecache`.`parent` as `file_parent`';
1962
+                    }
1963
+                }
1964
+            }
1965
+        }
1966
+        return $select;
1967
+    }
1968
+
1969
+
1970
+    /**
1971
+     * transform db results
1972
+     * @param array $row result
1973
+     */
1974
+    private static function transformDBResults(&$row) {
1975
+        if (isset($row['id'])) {
1976
+            $row['id'] = (int) $row['id'];
1977
+        }
1978
+        if (isset($row['share_type'])) {
1979
+            $row['share_type'] = (int) $row['share_type'];
1980
+        }
1981
+        if (isset($row['parent'])) {
1982
+            $row['parent'] = (int) $row['parent'];
1983
+        }
1984
+        if (isset($row['file_parent'])) {
1985
+            $row['file_parent'] = (int) $row['file_parent'];
1986
+        }
1987
+        if (isset($row['file_source'])) {
1988
+            $row['file_source'] = (int) $row['file_source'];
1989
+        }
1990
+        if (isset($row['permissions'])) {
1991
+            $row['permissions'] = (int) $row['permissions'];
1992
+        }
1993
+        if (isset($row['storage'])) {
1994
+            $row['storage'] = (int) $row['storage'];
1995
+        }
1996
+        if (isset($row['stime'])) {
1997
+            $row['stime'] = (int) $row['stime'];
1998
+        }
1999
+        if (isset($row['expiration']) && $row['share_type'] !== self::SHARE_TYPE_LINK) {
2000
+            // discard expiration date for non-link shares, which might have been
2001
+            // set by ancient bugs
2002
+            $row['expiration'] = null;
2003
+        }
2004
+    }
2005
+
2006
+    /**
2007
+     * format result
2008
+     * @param array $items result
2009
+     * @param string $column is it a file share or a general share ('file_target' or 'item_target')
2010
+     * @param \OCP\Share_Backend $backend sharing backend
2011
+     * @param int $format
2012
+     * @param array $parameters additional format parameters
2013
+     * @return array format result
2014
+     */
2015
+    private static function formatResult($items, $column, $backend, $format = self::FORMAT_NONE , $parameters = null) {
2016
+        if ($format === self::FORMAT_NONE) {
2017
+            return $items;
2018
+        } else if ($format === self::FORMAT_STATUSES) {
2019
+            $statuses = array();
2020
+            foreach ($items as $item) {
2021
+                if ($item['share_type'] === self::SHARE_TYPE_LINK) {
2022
+                    if ($item['uid_initiator'] !== \OC::$server->getUserSession()->getUser()->getUID()) {
2023
+                        continue;
2024
+                    }
2025
+                    $statuses[$item[$column]]['link'] = true;
2026
+                } else if (!isset($statuses[$item[$column]])) {
2027
+                    $statuses[$item[$column]]['link'] = false;
2028
+                }
2029
+                if (!empty($item['file_target'])) {
2030
+                    $statuses[$item[$column]]['path'] = $item['path'];
2031
+                }
2032
+            }
2033
+            return $statuses;
2034
+        } else {
2035
+            return $backend->formatItems($items, $format, $parameters);
2036
+        }
2037
+    }
2038
+
2039
+    /**
2040
+     * remove protocol from URL
2041
+     *
2042
+     * @param string $url
2043
+     * @return string
2044
+     */
2045
+    public static function removeProtocolFromUrl($url) {
2046
+        if (strpos($url, 'https://') === 0) {
2047
+            return substr($url, strlen('https://'));
2048
+        } else if (strpos($url, 'http://') === 0) {
2049
+            return substr($url, strlen('http://'));
2050
+        }
2051
+
2052
+        return $url;
2053
+    }
2054
+
2055
+    /**
2056
+     * try http post first with https and then with http as a fallback
2057
+     *
2058
+     * @param string $remoteDomain
2059
+     * @param string $urlSuffix
2060
+     * @param array $fields post parameters
2061
+     * @return array
2062
+     */
2063
+    private static function tryHttpPostToShareEndpoint($remoteDomain, $urlSuffix, array $fields) {
2064
+        $protocol = 'https://';
2065
+        $result = [
2066
+            'success' => false,
2067
+            'result' => '',
2068
+        ];
2069
+        $try = 0;
2070
+        $discoveryService = \OC::$server->query(\OCP\OCS\IDiscoveryService::class);
2071
+        while ($result['success'] === false && $try < 2) {
2072
+            $federationEndpoints = $discoveryService->discover($protocol . $remoteDomain, 'FEDERATED_SHARING');
2073
+            $endpoint = isset($federationEndpoints['share']) ? $federationEndpoints['share'] : '/ocs/v2.php/cloud/shares';
2074
+            $result = \OC::$server->getHTTPHelper()->post($protocol . $remoteDomain . $endpoint . $urlSuffix . '?format=' . self::RESPONSE_FORMAT, $fields);
2075
+            $try++;
2076
+            $protocol = 'http://';
2077
+        }
2078
+
2079
+        return $result;
2080
+    }
2081
+
2082
+    /**
2083
+     * send server-to-server share to remote server
2084
+     *
2085
+     * @param string $token
2086
+     * @param string $shareWith
2087
+     * @param string $name
2088
+     * @param int $remote_id
2089
+     * @param string $owner
2090
+     * @return bool
2091
+     */
2092
+    private static function sendRemoteShare($token, $shareWith, $name, $remote_id, $owner) {
2093
+
2094
+        list($user, $remote) = Helper::splitUserRemote($shareWith);
2095
+
2096
+        if ($user && $remote) {
2097
+            $url = $remote;
2098
+
2099
+            $local = \OC::$server->getURLGenerator()->getAbsoluteURL('/');
2100
+
2101
+            $fields = array(
2102
+                'shareWith' => $user,
2103
+                'token' => $token,
2104
+                'name' => $name,
2105
+                'remoteId' => $remote_id,
2106
+                'owner' => $owner,
2107
+                'remote' => $local,
2108
+            );
2109
+
2110
+            $url = self::removeProtocolFromUrl($url);
2111
+            $result = self::tryHttpPostToShareEndpoint($url, '', $fields);
2112
+            $status = json_decode($result['result'], true);
2113
+
2114
+            if ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200)) {
2115
+                \OC_Hook::emit('OCP\Share', 'federated_share_added', ['server' => $remote]);
2116
+                return true;
2117
+            }
2118
+
2119
+        }
2120
+
2121
+        return false;
2122
+    }
2123
+
2124
+    /**
2125
+     * send server-to-server unshare to remote server
2126
+     *
2127
+     * @param string $remote url
2128
+     * @param int $id share id
2129
+     * @param string $token
2130
+     * @return bool
2131
+     */
2132
+    private static function sendRemoteUnshare($remote, $id, $token) {
2133
+        $url = rtrim($remote, '/');
2134
+        $fields = array('token' => $token, 'format' => 'json');
2135
+        $url = self::removeProtocolFromUrl($url);
2136
+        $result = self::tryHttpPostToShareEndpoint($url, '/'.$id.'/unshare', $fields);
2137
+        $status = json_decode($result['result'], true);
2138
+
2139
+        return ($result['success'] && ($status['ocs']['meta']['statuscode'] === 100 || $status['ocs']['meta']['statuscode'] === 200));
2140
+    }
2141
+
2142
+    /**
2143
+     * check if user can only share with group members
2144
+     * @return bool
2145
+     */
2146
+    public static function shareWithGroupMembersOnly() {
2147
+        $value = \OC::$server->getAppConfig()->getValue('core', 'shareapi_only_share_with_group_members', 'no');
2148
+        return ($value === 'yes') ? true : false;
2149
+    }
2150
+
2151
+    /**
2152
+     * @return bool
2153
+     */
2154
+    public static function isDefaultExpireDateEnabled() {
2155
+        $defaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
2156
+        return ($defaultExpireDateEnabled === "yes") ? true : false;
2157
+    }
2158
+
2159
+    /**
2160
+     * @return bool
2161
+     */
2162
+    public static function enforceDefaultExpireDate() {
2163
+        $enforceDefaultExpireDate = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
2164
+        return ($enforceDefaultExpireDate === "yes") ? true : false;
2165
+    }
2166
+
2167
+    /**
2168
+     * @return int
2169
+     */
2170
+    public static function getExpireInterval() {
2171
+        return (int)\OC::$server->getConfig()->getAppValue('core', 'shareapi_expire_after_n_days', '7');
2172
+    }
2173
+
2174
+    /**
2175
+     * Checks whether the given path is reachable for the given owner
2176
+     *
2177
+     * @param string $path path relative to files
2178
+     * @param string $ownerStorageId storage id of the owner
2179
+     *
2180
+     * @return boolean true if file is reachable, false otherwise
2181
+     */
2182
+    private static function isFileReachable($path, $ownerStorageId) {
2183
+        // if outside the home storage, file is always considered reachable
2184
+        if (!(substr($ownerStorageId, 0, 6) === 'home::' ||
2185
+            substr($ownerStorageId, 0, 13) === 'object::user:'
2186
+        )) {
2187
+            return true;
2188
+        }
2189
+
2190
+        // if inside the home storage, the file has to be under "/files/"
2191
+        $path = ltrim($path, '/');
2192
+        if (substr($path, 0, 6) === 'files/') {
2193
+            return true;
2194
+        }
2195
+
2196
+        return false;
2197
+    }
2198
+
2199
+    /**
2200
+     * @param IConfig $config
2201
+     * @return bool
2202
+     */
2203
+    public static function enforcePassword(IConfig $config) {
2204
+        $enforcePassword = $config->getAppValue('core', 'shareapi_enforce_links_password', 'no');
2205
+        return ($enforcePassword === "yes") ? true : false;
2206
+    }
2207
+
2208
+    /**
2209
+     * Get all share entries, including non-unique group items
2210
+     *
2211
+     * @param string $owner
2212
+     * @return array
2213
+     */
2214
+    public static function getAllSharesForOwner($owner) {
2215
+        $query = 'SELECT * FROM `*PREFIX*share` WHERE `uid_owner` = ?';
2216
+        $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$owner]);
2217
+        return $result->fetchAll();
2218
+    }
2219
+
2220
+    /**
2221
+     * Get all share entries, including non-unique group items for a file
2222
+     *
2223
+     * @param int $id
2224
+     * @return array
2225
+     */
2226
+    public static function getAllSharesForFileId($id) {
2227
+        $query = 'SELECT * FROM `*PREFIX*share` WHERE `file_source` = ?';
2228
+        $result = \OC::$server->getDatabaseConnection()->executeQuery($query, [$id]);
2229
+        return $result->fetchAll();
2230
+    }
2231
+
2232
+    /**
2233
+     * @param string $password
2234
+     * @throws \Exception
2235
+     */
2236
+    private static function verifyPassword($password) {
2237
+
2238
+        $accepted = true;
2239
+        $message = '';
2240
+        \OCP\Util::emitHook('\OC\Share', 'verifyPassword', [
2241
+            'password' => $password,
2242
+            'accepted' => &$accepted,
2243
+            'message' => &$message
2244
+        ]);
2245
+
2246
+        if (!$accepted) {
2247
+            throw new \Exception($message);
2248
+        }
2249
+    }
2250 2250
 }
Please login to merge, or discard this patch.
lib/private/legacy/util.php 1 patch
Indentation   +1456 added lines, -1456 removed lines patch added patch discarded remove patch
@@ -65,1464 +65,1464 @@
 block discarded – undo
65 65
 use OCP\IUser;
66 66
 
67 67
 class OC_Util {
68
-	public static $scripts = array();
69
-	public static $styles = array();
70
-	public static $headers = array();
71
-	private static $rootMounted = false;
72
-	private static $fsSetup = false;
73
-
74
-	/** @var array Local cache of version.php */
75
-	private static $versionCache = null;
76
-
77
-	protected static function getAppManager() {
78
-		return \OC::$server->getAppManager();
79
-	}
80
-
81
-	private static function initLocalStorageRootFS() {
82
-		// mount local file backend as root
83
-		$configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
84
-		//first set up the local "root" storage
85
-		\OC\Files\Filesystem::initMountManager();
86
-		if (!self::$rootMounted) {
87
-			\OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
88
-			self::$rootMounted = true;
89
-		}
90
-	}
91
-
92
-	/**
93
-	 * mounting an object storage as the root fs will in essence remove the
94
-	 * necessity of a data folder being present.
95
-	 * TODO make home storage aware of this and use the object storage instead of local disk access
96
-	 *
97
-	 * @param array $config containing 'class' and optional 'arguments'
98
-	 * @suppress PhanDeprecatedFunction
99
-	 */
100
-	private static function initObjectStoreRootFS($config) {
101
-		// check misconfiguration
102
-		if (empty($config['class'])) {
103
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
104
-		}
105
-		if (!isset($config['arguments'])) {
106
-			$config['arguments'] = array();
107
-		}
108
-
109
-		// instantiate object store implementation
110
-		$name = $config['class'];
111
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
112
-			$segments = explode('\\', $name);
113
-			OC_App::loadApp(strtolower($segments[1]));
114
-		}
115
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
116
-		// mount with plain / root object store implementation
117
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
118
-
119
-		// mount object storage as root
120
-		\OC\Files\Filesystem::initMountManager();
121
-		if (!self::$rootMounted) {
122
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
123
-			self::$rootMounted = true;
124
-		}
125
-	}
126
-
127
-	/**
128
-	 * mounting an object storage as the root fs will in essence remove the
129
-	 * necessity of a data folder being present.
130
-	 *
131
-	 * @param array $config containing 'class' and optional 'arguments'
132
-	 * @suppress PhanDeprecatedFunction
133
-	 */
134
-	private static function initObjectStoreMultibucketRootFS($config) {
135
-		// check misconfiguration
136
-		if (empty($config['class'])) {
137
-			\OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
138
-		}
139
-		if (!isset($config['arguments'])) {
140
-			$config['arguments'] = array();
141
-		}
142
-
143
-		// instantiate object store implementation
144
-		$name = $config['class'];
145
-		if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
146
-			$segments = explode('\\', $name);
147
-			OC_App::loadApp(strtolower($segments[1]));
148
-		}
149
-
150
-		if (!isset($config['arguments']['bucket'])) {
151
-			$config['arguments']['bucket'] = '';
152
-		}
153
-		// put the root FS always in first bucket for multibucket configuration
154
-		$config['arguments']['bucket'] .= '0';
155
-
156
-		$config['arguments']['objectstore'] = new $config['class']($config['arguments']);
157
-		// mount with plain / root object store implementation
158
-		$config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
159
-
160
-		// mount object storage as root
161
-		\OC\Files\Filesystem::initMountManager();
162
-		if (!self::$rootMounted) {
163
-			\OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
164
-			self::$rootMounted = true;
165
-		}
166
-	}
167
-
168
-	/**
169
-	 * Can be set up
170
-	 *
171
-	 * @param string $user
172
-	 * @return boolean
173
-	 * @description configure the initial filesystem based on the configuration
174
-	 * @suppress PhanDeprecatedFunction
175
-	 * @suppress PhanAccessMethodInternal
176
-	 */
177
-	public static function setupFS($user = '') {
178
-		//setting up the filesystem twice can only lead to trouble
179
-		if (self::$fsSetup) {
180
-			return false;
181
-		}
182
-
183
-		\OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
184
-
185
-		// If we are not forced to load a specific user we load the one that is logged in
186
-		if ($user === null) {
187
-			$user = '';
188
-		} else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
189
-			$user = OC_User::getUser();
190
-		}
191
-
192
-		// load all filesystem apps before, so no setup-hook gets lost
193
-		OC_App::loadApps(array('filesystem'));
194
-
195
-		// the filesystem will finish when $user is not empty,
196
-		// mark fs setup here to avoid doing the setup from loading
197
-		// OC_Filesystem
198
-		if ($user != '') {
199
-			self::$fsSetup = true;
200
-		}
201
-
202
-		\OC\Files\Filesystem::initMountManager();
203
-
204
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
205
-		\OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
207
-				/** @var \OC\Files\Storage\Common $storage */
208
-				$storage->setMountOptions($mount->getOptions());
209
-			}
210
-			return $storage;
211
-		});
212
-
213
-		\OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
-			if (!$mount->getOption('enable_sharing', true)) {
215
-				return new \OC\Files\Storage\Wrapper\PermissionsMask([
216
-					'storage' => $storage,
217
-					'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
218
-				]);
219
-			}
220
-			return $storage;
221
-		});
222
-
223
-		// install storage availability wrapper, before most other wrappers
224
-		\OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
225
-			if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
226
-				return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
227
-			}
228
-			return $storage;
229
-		});
230
-
231
-		\OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
232
-			if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233
-				return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
234
-			}
235
-			return $storage;
236
-		});
237
-
238
-		\OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
239
-			// set up quota for home storages, even for other users
240
-			// which can happen when using sharing
241
-
242
-			/**
243
-			 * @var \OC\Files\Storage\Storage $storage
244
-			 */
245
-			if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
246
-				|| $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
247
-			) {
248
-				/** @var \OC\Files\Storage\Home $storage */
249
-				if (is_object($storage->getUser())) {
250
-					$user = $storage->getUser()->getUID();
251
-					$quota = OC_Util::getUserQuota($user);
252
-					if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
253
-						return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
254
-					}
255
-				}
256
-			}
257
-
258
-			return $storage;
259
-		});
260
-
261
-		OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
262
-		\OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
263
-
264
-		//check if we are using an object storage
265
-		$objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
266
-		$objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
267
-
268
-		// use the same order as in ObjectHomeMountProvider
269
-		if (isset($objectStoreMultibucket)) {
270
-			self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
271
-		} elseif (isset($objectStore)) {
272
-			self::initObjectStoreRootFS($objectStore);
273
-		} else {
274
-			self::initLocalStorageRootFS();
275
-		}
276
-
277
-		if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
278
-			\OC::$server->getEventLogger()->end('setup_fs');
279
-			return false;
280
-		}
281
-
282
-		//if we aren't logged in, there is no use to set up the filesystem
283
-		if ($user != "") {
284
-
285
-			$userDir = '/' . $user . '/files';
286
-
287
-			//jail the user into his "home" directory
288
-			\OC\Files\Filesystem::init($user, $userDir);
289
-
290
-			OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
291
-		}
292
-		\OC::$server->getEventLogger()->end('setup_fs');
293
-		return true;
294
-	}
295
-
296
-	/**
297
-	 * check if a password is required for each public link
298
-	 *
299
-	 * @return boolean
300
-	 * @suppress PhanDeprecatedFunction
301
-	 */
302
-	public static function isPublicLinkPasswordRequired() {
303
-		$appConfig = \OC::$server->getAppConfig();
304
-		$enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
305
-		return ($enforcePassword === 'yes') ? true : false;
306
-	}
307
-
308
-	/**
309
-	 * check if sharing is disabled for the current user
310
-	 * @param IConfig $config
311
-	 * @param IGroupManager $groupManager
312
-	 * @param IUser|null $user
313
-	 * @return bool
314
-	 */
315
-	public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
316
-		if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
317
-			$groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
318
-			$excludedGroups = json_decode($groupsList);
319
-			if (is_null($excludedGroups)) {
320
-				$excludedGroups = explode(',', $groupsList);
321
-				$newValue = json_encode($excludedGroups);
322
-				$config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
323
-			}
324
-			$usersGroups = $groupManager->getUserGroupIds($user);
325
-			if (!empty($usersGroups)) {
326
-				$remainingGroups = array_diff($usersGroups, $excludedGroups);
327
-				// if the user is only in groups which are disabled for sharing then
328
-				// sharing is also disabled for the user
329
-				if (empty($remainingGroups)) {
330
-					return true;
331
-				}
332
-			}
333
-		}
334
-		return false;
335
-	}
336
-
337
-	/**
338
-	 * check if share API enforces a default expire date
339
-	 *
340
-	 * @return boolean
341
-	 * @suppress PhanDeprecatedFunction
342
-	 */
343
-	public static function isDefaultExpireDateEnforced() {
344
-		$isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
345
-		$enforceDefaultExpireDate = false;
346
-		if ($isDefaultExpireDateEnabled === 'yes') {
347
-			$value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
348
-			$enforceDefaultExpireDate = ($value === 'yes') ? true : false;
349
-		}
350
-
351
-		return $enforceDefaultExpireDate;
352
-	}
353
-
354
-	/**
355
-	 * Get the quota of a user
356
-	 *
357
-	 * @param string $userId
358
-	 * @return float Quota bytes
359
-	 */
360
-	public static function getUserQuota($userId) {
361
-		$user = \OC::$server->getUserManager()->get($userId);
362
-		if (is_null($user)) {
363
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
364
-		}
365
-		$userQuota = $user->getQuota();
366
-		if($userQuota === 'none') {
367
-			return \OCP\Files\FileInfo::SPACE_UNLIMITED;
368
-		}
369
-		return OC_Helper::computerFileSize($userQuota);
370
-	}
371
-
372
-	/**
373
-	 * copies the skeleton to the users /files
374
-	 *
375
-	 * @param String $userId
376
-	 * @param \OCP\Files\Folder $userDirectory
377
-	 * @throws \RuntimeException
378
-	 * @suppress PhanDeprecatedFunction
379
-	 */
380
-	public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
381
-
382
-		$plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
383
-		$userLang = \OC::$server->getL10NFactory()->findLanguage();
384
-		$skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
385
-
386
-		if (!file_exists($skeletonDirectory)) {
387
-			$dialectStart = strpos($userLang, '_');
388
-			if ($dialectStart !== false) {
389
-				$skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
390
-			}
391
-			if ($dialectStart === false || !file_exists($skeletonDirectory)) {
392
-				$skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
393
-			}
394
-			if (!file_exists($skeletonDirectory)) {
395
-				$skeletonDirectory = '';
396
-			}
397
-		}
398
-
399
-		$instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
400
-
401
-		if ($instanceId === null) {
402
-			throw new \RuntimeException('no instance id!');
403
-		}
404
-		$appdata = 'appdata_' . $instanceId;
405
-		if ($userId === $appdata) {
406
-			throw new \RuntimeException('username is reserved name: ' . $appdata);
407
-		}
408
-
409
-		if (!empty($skeletonDirectory)) {
410
-			\OCP\Util::writeLog(
411
-				'files_skeleton',
412
-				'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
413
-				\OCP\Util::DEBUG
414
-			);
415
-			self::copyr($skeletonDirectory, $userDirectory);
416
-			// update the file cache
417
-			$userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
418
-		}
419
-	}
420
-
421
-	/**
422
-	 * copies a directory recursively by using streams
423
-	 *
424
-	 * @param string $source
425
-	 * @param \OCP\Files\Folder $target
426
-	 * @return void
427
-	 */
428
-	public static function copyr($source, \OCP\Files\Folder $target) {
429
-		$logger = \OC::$server->getLogger();
430
-
431
-		// Verify if folder exists
432
-		$dir = opendir($source);
433
-		if($dir === false) {
434
-			$logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
435
-			return;
436
-		}
437
-
438
-		// Copy the files
439
-		while (false !== ($file = readdir($dir))) {
440
-			if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
441
-				if (is_dir($source . '/' . $file)) {
442
-					$child = $target->newFolder($file);
443
-					self::copyr($source . '/' . $file, $child);
444
-				} else {
445
-					$child = $target->newFile($file);
446
-					$sourceStream = fopen($source . '/' . $file, 'r');
447
-					if($sourceStream === false) {
448
-						$logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
449
-						closedir($dir);
450
-						return;
451
-					}
452
-					stream_copy_to_stream($sourceStream, $child->fopen('w'));
453
-				}
454
-			}
455
-		}
456
-		closedir($dir);
457
-	}
458
-
459
-	/**
460
-	 * @return void
461
-	 * @suppress PhanUndeclaredMethod
462
-	 */
463
-	public static function tearDownFS() {
464
-		\OC\Files\Filesystem::tearDown();
465
-		\OC::$server->getRootFolder()->clearCache();
466
-		self::$fsSetup = false;
467
-		self::$rootMounted = false;
468
-	}
469
-
470
-	/**
471
-	 * get the current installed version of ownCloud
472
-	 *
473
-	 * @return array
474
-	 */
475
-	public static function getVersion() {
476
-		OC_Util::loadVersion();
477
-		return self::$versionCache['OC_Version'];
478
-	}
479
-
480
-	/**
481
-	 * get the current installed version string of ownCloud
482
-	 *
483
-	 * @return string
484
-	 */
485
-	public static function getVersionString() {
486
-		OC_Util::loadVersion();
487
-		return self::$versionCache['OC_VersionString'];
488
-	}
489
-
490
-	/**
491
-	 * @deprecated the value is of no use anymore
492
-	 * @return string
493
-	 */
494
-	public static function getEditionString() {
495
-		return '';
496
-	}
497
-
498
-	/**
499
-	 * @description get the update channel of the current installed of ownCloud.
500
-	 * @return string
501
-	 */
502
-	public static function getChannel() {
503
-		OC_Util::loadVersion();
504
-		return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
505
-	}
506
-
507
-	/**
508
-	 * @description get the build number of the current installed of ownCloud.
509
-	 * @return string
510
-	 */
511
-	public static function getBuild() {
512
-		OC_Util::loadVersion();
513
-		return self::$versionCache['OC_Build'];
514
-	}
515
-
516
-	/**
517
-	 * @description load the version.php into the session as cache
518
-	 * @suppress PhanUndeclaredVariable
519
-	 */
520
-	private static function loadVersion() {
521
-		if (self::$versionCache !== null) {
522
-			return;
523
-		}
524
-
525
-		$timestamp = filemtime(OC::$SERVERROOT . '/version.php');
526
-		require OC::$SERVERROOT . '/version.php';
527
-		/** @var $timestamp int */
528
-		self::$versionCache['OC_Version_Timestamp'] = $timestamp;
529
-		/** @var $OC_Version string */
530
-		self::$versionCache['OC_Version'] = $OC_Version;
531
-		/** @var $OC_VersionString string */
532
-		self::$versionCache['OC_VersionString'] = $OC_VersionString;
533
-		/** @var $OC_Build string */
534
-		self::$versionCache['OC_Build'] = $OC_Build;
535
-
536
-		/** @var $OC_Channel string */
537
-		self::$versionCache['OC_Channel'] = $OC_Channel;
538
-	}
539
-
540
-	/**
541
-	 * generates a path for JS/CSS files. If no application is provided it will create the path for core.
542
-	 *
543
-	 * @param string $application application to get the files from
544
-	 * @param string $directory directory within this application (css, js, vendor, etc)
545
-	 * @param string $file the file inside of the above folder
546
-	 * @return string the path
547
-	 */
548
-	private static function generatePath($application, $directory, $file) {
549
-		if (is_null($file)) {
550
-			$file = $application;
551
-			$application = "";
552
-		}
553
-		if (!empty($application)) {
554
-			return "$application/$directory/$file";
555
-		} else {
556
-			return "$directory/$file";
557
-		}
558
-	}
559
-
560
-	/**
561
-	 * add a javascript file
562
-	 *
563
-	 * @param string $application application id
564
-	 * @param string|null $file filename
565
-	 * @param bool $prepend prepend the Script to the beginning of the list
566
-	 * @return void
567
-	 */
568
-	public static function addScript($application, $file = null, $prepend = false) {
569
-		$path = OC_Util::generatePath($application, 'js', $file);
570
-
571
-		// core js files need separate handling
572
-		if ($application !== 'core' && $file !== null) {
573
-			self::addTranslations ( $application );
574
-		}
575
-		self::addExternalResource($application, $prepend, $path, "script");
576
-	}
577
-
578
-	/**
579
-	 * add a javascript file from the vendor sub folder
580
-	 *
581
-	 * @param string $application application id
582
-	 * @param string|null $file filename
583
-	 * @param bool $prepend prepend the Script to the beginning of the list
584
-	 * @return void
585
-	 */
586
-	public static function addVendorScript($application, $file = null, $prepend = false) {
587
-		$path = OC_Util::generatePath($application, 'vendor', $file);
588
-		self::addExternalResource($application, $prepend, $path, "script");
589
-	}
590
-
591
-	/**
592
-	 * add a translation JS file
593
-	 *
594
-	 * @param string $application application id
595
-	 * @param string|null $languageCode language code, defaults to the current language
596
-	 * @param bool|null $prepend prepend the Script to the beginning of the list
597
-	 */
598
-	public static function addTranslations($application, $languageCode = null, $prepend = false) {
599
-		if (is_null($languageCode)) {
600
-			$languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
601
-		}
602
-		if (!empty($application)) {
603
-			$path = "$application/l10n/$languageCode";
604
-		} else {
605
-			$path = "l10n/$languageCode";
606
-		}
607
-		self::addExternalResource($application, $prepend, $path, "script");
608
-	}
609
-
610
-	/**
611
-	 * add a css file
612
-	 *
613
-	 * @param string $application application id
614
-	 * @param string|null $file filename
615
-	 * @param bool $prepend prepend the Style to the beginning of the list
616
-	 * @return void
617
-	 */
618
-	public static function addStyle($application, $file = null, $prepend = false) {
619
-		$path = OC_Util::generatePath($application, 'css', $file);
620
-		self::addExternalResource($application, $prepend, $path, "style");
621
-	}
622
-
623
-	/**
624
-	 * add a css file from the vendor sub folder
625
-	 *
626
-	 * @param string $application application id
627
-	 * @param string|null $file filename
628
-	 * @param bool $prepend prepend the Style to the beginning of the list
629
-	 * @return void
630
-	 */
631
-	public static function addVendorStyle($application, $file = null, $prepend = false) {
632
-		$path = OC_Util::generatePath($application, 'vendor', $file);
633
-		self::addExternalResource($application, $prepend, $path, "style");
634
-	}
635
-
636
-	/**
637
-	 * add an external resource css/js file
638
-	 *
639
-	 * @param string $application application id
640
-	 * @param bool $prepend prepend the file to the beginning of the list
641
-	 * @param string $path
642
-	 * @param string $type (script or style)
643
-	 * @return void
644
-	 */
645
-	private static function addExternalResource($application, $prepend, $path, $type = "script") {
646
-
647
-		if ($type === "style") {
648
-			if (!in_array($path, self::$styles)) {
649
-				if ($prepend === true) {
650
-					array_unshift ( self::$styles, $path );
651
-				} else {
652
-					self::$styles[] = $path;
653
-				}
654
-			}
655
-		} elseif ($type === "script") {
656
-			if (!in_array($path, self::$scripts)) {
657
-				if ($prepend === true) {
658
-					array_unshift ( self::$scripts, $path );
659
-				} else {
660
-					self::$scripts [] = $path;
661
-				}
662
-			}
663
-		}
664
-	}
665
-
666
-	/**
667
-	 * Add a custom element to the header
668
-	 * If $text is null then the element will be written as empty element.
669
-	 * So use "" to get a closing tag.
670
-	 * @param string $tag tag name of the element
671
-	 * @param array $attributes array of attributes for the element
672
-	 * @param string $text the text content for the element
673
-	 */
674
-	public static function addHeader($tag, $attributes, $text=null) {
675
-		self::$headers[] = array(
676
-			'tag' => $tag,
677
-			'attributes' => $attributes,
678
-			'text' => $text
679
-		);
680
-	}
681
-
682
-	/**
683
-	 * formats a timestamp in the "right" way
684
-	 *
685
-	 * @param int $timestamp
686
-	 * @param bool $dateOnly option to omit time from the result
687
-	 * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
688
-	 * @return string timestamp
689
-	 *
690
-	 * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
691
-	 */
692
-	public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
693
-		if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
694
-			$timeZone = new \DateTimeZone($timeZone);
695
-		}
696
-
697
-		/** @var \OC\DateTimeFormatter $formatter */
698
-		$formatter = \OC::$server->query('DateTimeFormatter');
699
-		if ($dateOnly) {
700
-			return $formatter->formatDate($timestamp, 'long', $timeZone);
701
-		}
702
-		return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
703
-	}
704
-
705
-	/**
706
-	 * check if the current server configuration is suitable for ownCloud
707
-	 *
708
-	 * @param \OC\SystemConfig $config
709
-	 * @return array arrays with error messages and hints
710
-	 */
711
-	public static function checkServer(\OC\SystemConfig $config) {
712
-		$l = \OC::$server->getL10N('lib');
713
-		$errors = array();
714
-		$CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
715
-
716
-		if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
717
-			// this check needs to be done every time
718
-			$errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
719
-		}
720
-
721
-		// Assume that if checkServer() succeeded before in this session, then all is fine.
722
-		if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
723
-			return $errors;
724
-		}
725
-
726
-		$webServerRestart = false;
727
-		$setup = new \OC\Setup(
728
-			$config,
729
-			\OC::$server->getIniWrapper(),
730
-			\OC::$server->getL10N('lib'),
731
-			\OC::$server->query(\OCP\Defaults::class),
732
-			\OC::$server->getLogger(),
733
-			\OC::$server->getSecureRandom(),
734
-			\OC::$server->query(\OC\Installer::class)
735
-		);
736
-
737
-		$urlGenerator = \OC::$server->getURLGenerator();
738
-
739
-		$availableDatabases = $setup->getSupportedDatabases();
740
-		if (empty($availableDatabases)) {
741
-			$errors[] = array(
742
-				'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
743
-				'hint' => '' //TODO: sane hint
744
-			);
745
-			$webServerRestart = true;
746
-		}
747
-
748
-		// Check if config folder is writable.
749
-		if(!OC_Helper::isReadOnlyConfigEnabled()) {
750
-			if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
751
-				$errors[] = array(
752
-					'error' => $l->t('Cannot write into "config" directory'),
753
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
754
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
755
-				);
756
-			}
757
-		}
758
-
759
-		// Check if there is a writable install folder.
760
-		if ($config->getValue('appstoreenabled', true)) {
761
-			if (OC_App::getInstallPath() === null
762
-				|| !is_writable(OC_App::getInstallPath())
763
-				|| !is_readable(OC_App::getInstallPath())
764
-			) {
765
-				$errors[] = array(
766
-					'error' => $l->t('Cannot write into "apps" directory'),
767
-					'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
768
-						. ' or disabling the appstore in the config file. See %s',
769
-						[$urlGenerator->linkToDocs('admin-dir_permissions')])
770
-				);
771
-			}
772
-		}
773
-		// Create root dir.
774
-		if ($config->getValue('installed', false)) {
775
-			if (!is_dir($CONFIG_DATADIRECTORY)) {
776
-				$success = @mkdir($CONFIG_DATADIRECTORY);
777
-				if ($success) {
778
-					$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
779
-				} else {
780
-					$errors[] = [
781
-						'error' => $l->t('Cannot create "data" directory'),
782
-						'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
783
-							[$urlGenerator->linkToDocs('admin-dir_permissions')])
784
-					];
785
-				}
786
-			} else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
787
-				//common hint for all file permissions error messages
788
-				$permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
789
-					[$urlGenerator->linkToDocs('admin-dir_permissions')]);
790
-				$errors[] = [
791
-					'error' => 'Your data directory is not writable',
792
-					'hint' => $permissionsHint
793
-				];
794
-			} else {
795
-				$errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
796
-			}
797
-		}
798
-
799
-		if (!OC_Util::isSetLocaleWorking()) {
800
-			$errors[] = array(
801
-				'error' => $l->t('Setting locale to %s failed',
802
-					array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
803
-						. 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
804
-				'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
805
-			);
806
-		}
807
-
808
-		// Contains the dependencies that should be checked against
809
-		// classes = class_exists
810
-		// functions = function_exists
811
-		// defined = defined
812
-		// ini = ini_get
813
-		// If the dependency is not found the missing module name is shown to the EndUser
814
-		// When adding new checks always verify that they pass on Travis as well
815
-		// for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
816
-		$dependencies = array(
817
-			'classes' => array(
818
-				'ZipArchive' => 'zip',
819
-				'DOMDocument' => 'dom',
820
-				'XMLWriter' => 'XMLWriter',
821
-				'XMLReader' => 'XMLReader',
822
-			),
823
-			'functions' => [
824
-				'xml_parser_create' => 'libxml',
825
-				'mb_strcut' => 'mb multibyte',
826
-				'ctype_digit' => 'ctype',
827
-				'json_encode' => 'JSON',
828
-				'gd_info' => 'GD',
829
-				'gzencode' => 'zlib',
830
-				'iconv' => 'iconv',
831
-				'simplexml_load_string' => 'SimpleXML',
832
-				'hash' => 'HASH Message Digest Framework',
833
-				'curl_init' => 'cURL',
834
-				'openssl_verify' => 'OpenSSL',
835
-			],
836
-			'defined' => array(
837
-				'PDO::ATTR_DRIVER_NAME' => 'PDO'
838
-			),
839
-			'ini' => [
840
-				'default_charset' => 'UTF-8',
841
-			],
842
-		);
843
-		$missingDependencies = array();
844
-		$invalidIniSettings = [];
845
-		$moduleHint = $l->t('Please ask your server administrator to install the module.');
846
-
847
-		/**
848
-		 * FIXME: The dependency check does not work properly on HHVM on the moment
849
-		 *        and prevents installation. Once HHVM is more compatible with our
850
-		 *        approach to check for these values we should re-enable those
851
-		 *        checks.
852
-		 */
853
-		$iniWrapper = \OC::$server->getIniWrapper();
854
-		if (!self::runningOnHhvm()) {
855
-			foreach ($dependencies['classes'] as $class => $module) {
856
-				if (!class_exists($class)) {
857
-					$missingDependencies[] = $module;
858
-				}
859
-			}
860
-			foreach ($dependencies['functions'] as $function => $module) {
861
-				if (!function_exists($function)) {
862
-					$missingDependencies[] = $module;
863
-				}
864
-			}
865
-			foreach ($dependencies['defined'] as $defined => $module) {
866
-				if (!defined($defined)) {
867
-					$missingDependencies[] = $module;
868
-				}
869
-			}
870
-			foreach ($dependencies['ini'] as $setting => $expected) {
871
-				if (is_bool($expected)) {
872
-					if ($iniWrapper->getBool($setting) !== $expected) {
873
-						$invalidIniSettings[] = [$setting, $expected];
874
-					}
875
-				}
876
-				if (is_int($expected)) {
877
-					if ($iniWrapper->getNumeric($setting) !== $expected) {
878
-						$invalidIniSettings[] = [$setting, $expected];
879
-					}
880
-				}
881
-				if (is_string($expected)) {
882
-					if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
883
-						$invalidIniSettings[] = [$setting, $expected];
884
-					}
885
-				}
886
-			}
887
-		}
888
-
889
-		foreach($missingDependencies as $missingDependency) {
890
-			$errors[] = array(
891
-				'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
892
-				'hint' => $moduleHint
893
-			);
894
-			$webServerRestart = true;
895
-		}
896
-		foreach($invalidIniSettings as $setting) {
897
-			if(is_bool($setting[1])) {
898
-				$setting[1] = ($setting[1]) ? 'on' : 'off';
899
-			}
900
-			$errors[] = [
901
-				'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
902
-				'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
903
-			];
904
-			$webServerRestart = true;
905
-		}
906
-
907
-		/**
908
-		 * The mbstring.func_overload check can only be performed if the mbstring
909
-		 * module is installed as it will return null if the checking setting is
910
-		 * not available and thus a check on the boolean value fails.
911
-		 *
912
-		 * TODO: Should probably be implemented in the above generic dependency
913
-		 *       check somehow in the long-term.
914
-		 */
915
-		if($iniWrapper->getBool('mbstring.func_overload') !== null &&
916
-			$iniWrapper->getBool('mbstring.func_overload') === true) {
917
-			$errors[] = array(
918
-				'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
919
-				'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
920
-			);
921
-		}
922
-
923
-		if(function_exists('xml_parser_create') &&
924
-			LIBXML_LOADED_VERSION < 20700 ) {
925
-			$version = LIBXML_LOADED_VERSION;
926
-			$major = floor($version/10000);
927
-			$version -= ($major * 10000);
928
-			$minor = floor($version/100);
929
-			$version -= ($minor * 100);
930
-			$patch = $version;
931
-			$errors[] = array(
932
-				'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
933
-				'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
934
-			);
935
-		}
936
-
937
-		if (!self::isAnnotationsWorking()) {
938
-			$errors[] = array(
939
-				'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
940
-				'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
941
-			);
942
-		}
943
-
944
-		if (!\OC::$CLI && $webServerRestart) {
945
-			$errors[] = array(
946
-				'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
947
-				'hint' => $l->t('Please ask your server administrator to restart the web server.')
948
-			);
949
-		}
950
-
951
-		$errors = array_merge($errors, self::checkDatabaseVersion());
952
-
953
-		// Cache the result of this function
954
-		\OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
955
-
956
-		return $errors;
957
-	}
958
-
959
-	/**
960
-	 * Check the database version
961
-	 *
962
-	 * @return array errors array
963
-	 */
964
-	public static function checkDatabaseVersion() {
965
-		$l = \OC::$server->getL10N('lib');
966
-		$errors = array();
967
-		$dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
968
-		if ($dbType === 'pgsql') {
969
-			// check PostgreSQL version
970
-			try {
971
-				$result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
972
-				$data = $result->fetchRow();
973
-				if (isset($data['server_version'])) {
974
-					$version = $data['server_version'];
975
-					if (version_compare($version, '9.0.0', '<')) {
976
-						$errors[] = array(
977
-							'error' => $l->t('PostgreSQL >= 9 required'),
978
-							'hint' => $l->t('Please upgrade your database version')
979
-						);
980
-					}
981
-				}
982
-			} catch (\Doctrine\DBAL\DBALException $e) {
983
-				$logger = \OC::$server->getLogger();
984
-				$logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
985
-				$logger->logException($e);
986
-			}
987
-		}
988
-		return $errors;
989
-	}
990
-
991
-	/**
992
-	 * Check for correct file permissions of data directory
993
-	 *
994
-	 * @param string $dataDirectory
995
-	 * @return array arrays with error messages and hints
996
-	 */
997
-	public static function checkDataDirectoryPermissions($dataDirectory) {
998
-		if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
999
-			return  [];
1000
-		}
1001
-		$l = \OC::$server->getL10N('lib');
1002
-		$errors = [];
1003
-		$permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1004
-			. ' cannot be listed by other users.');
1005
-		$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1006
-		if (substr($perms, -1) !== '0') {
1007
-			chmod($dataDirectory, 0770);
1008
-			clearstatcache();
1009
-			$perms = substr(decoct(@fileperms($dataDirectory)), -3);
1010
-			if ($perms[2] !== '0') {
1011
-				$errors[] = [
1012
-					'error' => $l->t('Your data directory is readable by other users'),
1013
-					'hint' => $permissionsModHint
1014
-				];
1015
-			}
1016
-		}
1017
-		return $errors;
1018
-	}
1019
-
1020
-	/**
1021
-	 * Check that the data directory exists and is valid by
1022
-	 * checking the existence of the ".ocdata" file.
1023
-	 *
1024
-	 * @param string $dataDirectory data directory path
1025
-	 * @return array errors found
1026
-	 */
1027
-	public static function checkDataDirectoryValidity($dataDirectory) {
1028
-		$l = \OC::$server->getL10N('lib');
1029
-		$errors = [];
1030
-		if ($dataDirectory[0] !== '/') {
1031
-			$errors[] = [
1032
-				'error' => $l->t('Your data directory must be an absolute path'),
1033
-				'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1034
-			];
1035
-		}
1036
-		if (!file_exists($dataDirectory . '/.ocdata')) {
1037
-			$errors[] = [
1038
-				'error' => $l->t('Your data directory is invalid'),
1039
-				'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1040
-					' in the root of the data directory.')
1041
-			];
1042
-		}
1043
-		return $errors;
1044
-	}
1045
-
1046
-	/**
1047
-	 * Check if the user is logged in, redirects to home if not. With
1048
-	 * redirect URL parameter to the request URI.
1049
-	 *
1050
-	 * @return void
1051
-	 */
1052
-	public static function checkLoggedIn() {
1053
-		// Check if we are a user
1054
-		if (!\OC::$server->getUserSession()->isLoggedIn()) {
1055
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1056
-						'core.login.showLoginForm',
1057
-						[
1058
-							'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1059
-						]
1060
-					)
1061
-			);
1062
-			exit();
1063
-		}
1064
-		// Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1065
-		if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1066
-			header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1067
-			exit();
1068
-		}
1069
-	}
1070
-
1071
-	/**
1072
-	 * Check if the user is a admin, redirects to home if not
1073
-	 *
1074
-	 * @return void
1075
-	 */
1076
-	public static function checkAdminUser() {
1077
-		OC_Util::checkLoggedIn();
1078
-		if (!OC_User::isAdminUser(OC_User::getUser())) {
1079
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1080
-			exit();
1081
-		}
1082
-	}
1083
-
1084
-	/**
1085
-	 * Check if the user is a subadmin, redirects to home if not
1086
-	 *
1087
-	 * @return null|boolean $groups where the current user is subadmin
1088
-	 */
1089
-	public static function checkSubAdminUser() {
1090
-		OC_Util::checkLoggedIn();
1091
-		$userObject = \OC::$server->getUserSession()->getUser();
1092
-		$isSubAdmin = false;
1093
-		if($userObject !== null) {
1094
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1095
-		}
1096
-
1097
-		if (!$isSubAdmin) {
1098
-			header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1099
-			exit();
1100
-		}
1101
-		return true;
1102
-	}
1103
-
1104
-	/**
1105
-	 * Returns the URL of the default page
1106
-	 * based on the system configuration and
1107
-	 * the apps visible for the current user
1108
-	 *
1109
-	 * @return string URL
1110
-	 * @suppress PhanDeprecatedFunction
1111
-	 */
1112
-	public static function getDefaultPageUrl() {
1113
-		$urlGenerator = \OC::$server->getURLGenerator();
1114
-		// Deny the redirect if the URL contains a @
1115
-		// This prevents unvalidated redirects like ?redirect_url=:[email protected]
1116
-		if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1117
-			$location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1118
-		} else {
1119
-			$defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
1120
-			if ($defaultPage) {
1121
-				$location = $urlGenerator->getAbsoluteURL($defaultPage);
1122
-			} else {
1123
-				$appId = 'files';
1124
-				$config = \OC::$server->getConfig();
1125
-				$defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1126
-				// find the first app that is enabled for the current user
1127
-				foreach ($defaultApps as $defaultApp) {
1128
-					$defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1129
-					if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1130
-						$appId = $defaultApp;
1131
-						break;
1132
-					}
1133
-				}
1134
-
1135
-				if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1136
-					$location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1137
-				} else {
1138
-					$location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1139
-				}
1140
-			}
1141
-		}
1142
-		return $location;
1143
-	}
1144
-
1145
-	/**
1146
-	 * Redirect to the user default page
1147
-	 *
1148
-	 * @return void
1149
-	 */
1150
-	public static function redirectToDefaultPage() {
1151
-		$location = self::getDefaultPageUrl();
1152
-		header('Location: ' . $location);
1153
-		exit();
1154
-	}
1155
-
1156
-	/**
1157
-	 * get an id unique for this instance
1158
-	 *
1159
-	 * @return string
1160
-	 */
1161
-	public static function getInstanceId() {
1162
-		$id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1163
-		if (is_null($id)) {
1164
-			// We need to guarantee at least one letter in instanceid so it can be used as the session_name
1165
-			$id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1166
-			\OC::$server->getSystemConfig()->setValue('instanceid', $id);
1167
-		}
1168
-		return $id;
1169
-	}
1170
-
1171
-	/**
1172
-	 * Public function to sanitize HTML
1173
-	 *
1174
-	 * This function is used to sanitize HTML and should be applied on any
1175
-	 * string or array of strings before displaying it on a web page.
1176
-	 *
1177
-	 * @param string|array $value
1178
-	 * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1179
-	 */
1180
-	public static function sanitizeHTML($value) {
1181
-		if (is_array($value)) {
1182
-			$value = array_map(function($value) {
1183
-				return self::sanitizeHTML($value);
1184
-			}, $value);
1185
-		} else {
1186
-			// Specify encoding for PHP<5.4
1187
-			$value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1188
-		}
1189
-		return $value;
1190
-	}
1191
-
1192
-	/**
1193
-	 * Public function to encode url parameters
1194
-	 *
1195
-	 * This function is used to encode path to file before output.
1196
-	 * Encoding is done according to RFC 3986 with one exception:
1197
-	 * Character '/' is preserved as is.
1198
-	 *
1199
-	 * @param string $component part of URI to encode
1200
-	 * @return string
1201
-	 */
1202
-	public static function encodePath($component) {
1203
-		$encoded = rawurlencode($component);
1204
-		$encoded = str_replace('%2F', '/', $encoded);
1205
-		return $encoded;
1206
-	}
1207
-
1208
-
1209
-	public function createHtaccessTestFile(\OCP\IConfig $config) {
1210
-		// php dev server does not support htaccess
1211
-		if (php_sapi_name() === 'cli-server') {
1212
-			return false;
1213
-		}
1214
-
1215
-		// testdata
1216
-		$fileName = '/htaccesstest.txt';
1217
-		$testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1218
-
1219
-		// creating a test file
1220
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1221
-
1222
-		if (file_exists($testFile)) {// already running this test, possible recursive call
1223
-			return false;
1224
-		}
1225
-
1226
-		$fp = @fopen($testFile, 'w');
1227
-		if (!$fp) {
1228
-			throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1229
-				'Make sure it is possible for the webserver to write to ' . $testFile);
1230
-		}
1231
-		fwrite($fp, $testContent);
1232
-		fclose($fp);
1233
-
1234
-		return $testContent;
1235
-	}
1236
-
1237
-	/**
1238
-	 * Check if the .htaccess file is working
1239
-	 * @param \OCP\IConfig $config
1240
-	 * @return bool
1241
-	 * @throws Exception
1242
-	 * @throws \OC\HintException If the test file can't get written.
1243
-	 */
1244
-	public function isHtaccessWorking(\OCP\IConfig $config) {
1245
-
1246
-		if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1247
-			return true;
1248
-		}
1249
-
1250
-		$testContent = $this->createHtaccessTestFile($config);
1251
-		if ($testContent === false) {
1252
-			return false;
1253
-		}
1254
-
1255
-		$fileName = '/htaccesstest.txt';
1256
-		$testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1257
-
1258
-		// accessing the file via http
1259
-		$url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1260
-		try {
1261
-			$content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1262
-		} catch (\Exception $e) {
1263
-			$content = false;
1264
-		}
1265
-
1266
-		// cleanup
1267
-		@unlink($testFile);
1268
-
1269
-		/*
68
+    public static $scripts = array();
69
+    public static $styles = array();
70
+    public static $headers = array();
71
+    private static $rootMounted = false;
72
+    private static $fsSetup = false;
73
+
74
+    /** @var array Local cache of version.php */
75
+    private static $versionCache = null;
76
+
77
+    protected static function getAppManager() {
78
+        return \OC::$server->getAppManager();
79
+    }
80
+
81
+    private static function initLocalStorageRootFS() {
82
+        // mount local file backend as root
83
+        $configDataDirectory = \OC::$server->getSystemConfig()->getValue("datadirectory", OC::$SERVERROOT . "/data");
84
+        //first set up the local "root" storage
85
+        \OC\Files\Filesystem::initMountManager();
86
+        if (!self::$rootMounted) {
87
+            \OC\Files\Filesystem::mount('\OC\Files\Storage\Local', array('datadir' => $configDataDirectory), '/');
88
+            self::$rootMounted = true;
89
+        }
90
+    }
91
+
92
+    /**
93
+     * mounting an object storage as the root fs will in essence remove the
94
+     * necessity of a data folder being present.
95
+     * TODO make home storage aware of this and use the object storage instead of local disk access
96
+     *
97
+     * @param array $config containing 'class' and optional 'arguments'
98
+     * @suppress PhanDeprecatedFunction
99
+     */
100
+    private static function initObjectStoreRootFS($config) {
101
+        // check misconfiguration
102
+        if (empty($config['class'])) {
103
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
104
+        }
105
+        if (!isset($config['arguments'])) {
106
+            $config['arguments'] = array();
107
+        }
108
+
109
+        // instantiate object store implementation
110
+        $name = $config['class'];
111
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
112
+            $segments = explode('\\', $name);
113
+            OC_App::loadApp(strtolower($segments[1]));
114
+        }
115
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
116
+        // mount with plain / root object store implementation
117
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
118
+
119
+        // mount object storage as root
120
+        \OC\Files\Filesystem::initMountManager();
121
+        if (!self::$rootMounted) {
122
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
123
+            self::$rootMounted = true;
124
+        }
125
+    }
126
+
127
+    /**
128
+     * mounting an object storage as the root fs will in essence remove the
129
+     * necessity of a data folder being present.
130
+     *
131
+     * @param array $config containing 'class' and optional 'arguments'
132
+     * @suppress PhanDeprecatedFunction
133
+     */
134
+    private static function initObjectStoreMultibucketRootFS($config) {
135
+        // check misconfiguration
136
+        if (empty($config['class'])) {
137
+            \OCP\Util::writeLog('files', 'No class given for objectstore', \OCP\Util::ERROR);
138
+        }
139
+        if (!isset($config['arguments'])) {
140
+            $config['arguments'] = array();
141
+        }
142
+
143
+        // instantiate object store implementation
144
+        $name = $config['class'];
145
+        if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
146
+            $segments = explode('\\', $name);
147
+            OC_App::loadApp(strtolower($segments[1]));
148
+        }
149
+
150
+        if (!isset($config['arguments']['bucket'])) {
151
+            $config['arguments']['bucket'] = '';
152
+        }
153
+        // put the root FS always in first bucket for multibucket configuration
154
+        $config['arguments']['bucket'] .= '0';
155
+
156
+        $config['arguments']['objectstore'] = new $config['class']($config['arguments']);
157
+        // mount with plain / root object store implementation
158
+        $config['class'] = '\OC\Files\ObjectStore\ObjectStoreStorage';
159
+
160
+        // mount object storage as root
161
+        \OC\Files\Filesystem::initMountManager();
162
+        if (!self::$rootMounted) {
163
+            \OC\Files\Filesystem::mount($config['class'], $config['arguments'], '/');
164
+            self::$rootMounted = true;
165
+        }
166
+    }
167
+
168
+    /**
169
+     * Can be set up
170
+     *
171
+     * @param string $user
172
+     * @return boolean
173
+     * @description configure the initial filesystem based on the configuration
174
+     * @suppress PhanDeprecatedFunction
175
+     * @suppress PhanAccessMethodInternal
176
+     */
177
+    public static function setupFS($user = '') {
178
+        //setting up the filesystem twice can only lead to trouble
179
+        if (self::$fsSetup) {
180
+            return false;
181
+        }
182
+
183
+        \OC::$server->getEventLogger()->start('setup_fs', 'Setup filesystem');
184
+
185
+        // If we are not forced to load a specific user we load the one that is logged in
186
+        if ($user === null) {
187
+            $user = '';
188
+        } else if ($user == "" && \OC::$server->getUserSession()->isLoggedIn()) {
189
+            $user = OC_User::getUser();
190
+        }
191
+
192
+        // load all filesystem apps before, so no setup-hook gets lost
193
+        OC_App::loadApps(array('filesystem'));
194
+
195
+        // the filesystem will finish when $user is not empty,
196
+        // mark fs setup here to avoid doing the setup from loading
197
+        // OC_Filesystem
198
+        if ($user != '') {
199
+            self::$fsSetup = true;
200
+        }
201
+
202
+        \OC\Files\Filesystem::initMountManager();
203
+
204
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false);
205
+        \OC\Files\Filesystem::addStorageWrapper('mount_options', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
206
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Common')) {
207
+                /** @var \OC\Files\Storage\Common $storage */
208
+                $storage->setMountOptions($mount->getOptions());
209
+            }
210
+            return $storage;
211
+        });
212
+
213
+        \OC\Files\Filesystem::addStorageWrapper('enable_sharing', function ($mountPoint, \OCP\Files\Storage\IStorage $storage, \OCP\Files\Mount\IMountPoint $mount) {
214
+            if (!$mount->getOption('enable_sharing', true)) {
215
+                return new \OC\Files\Storage\Wrapper\PermissionsMask([
216
+                    'storage' => $storage,
217
+                    'mask' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE
218
+                ]);
219
+            }
220
+            return $storage;
221
+        });
222
+
223
+        // install storage availability wrapper, before most other wrappers
224
+        \OC\Files\Filesystem::addStorageWrapper('oc_availability', function ($mountPoint, \OCP\Files\Storage\IStorage $storage) {
225
+            if (!$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
226
+                return new \OC\Files\Storage\Wrapper\Availability(['storage' => $storage]);
227
+            }
228
+            return $storage;
229
+        });
230
+
231
+        \OC\Files\Filesystem::addStorageWrapper('oc_encoding', function ($mountPoint, \OCP\Files\Storage $storage, \OCP\Files\Mount\IMountPoint $mount) {
232
+            if ($mount->getOption('encoding_compatibility', false) && !$storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage') && !$storage->isLocal()) {
233
+                return new \OC\Files\Storage\Wrapper\Encoding(['storage' => $storage]);
234
+            }
235
+            return $storage;
236
+        });
237
+
238
+        \OC\Files\Filesystem::addStorageWrapper('oc_quota', function ($mountPoint, $storage) {
239
+            // set up quota for home storages, even for other users
240
+            // which can happen when using sharing
241
+
242
+            /**
243
+             * @var \OC\Files\Storage\Storage $storage
244
+             */
245
+            if ($storage->instanceOfStorage('\OC\Files\Storage\Home')
246
+                || $storage->instanceOfStorage('\OC\Files\ObjectStore\HomeObjectStoreStorage')
247
+            ) {
248
+                /** @var \OC\Files\Storage\Home $storage */
249
+                if (is_object($storage->getUser())) {
250
+                    $user = $storage->getUser()->getUID();
251
+                    $quota = OC_Util::getUserQuota($user);
252
+                    if ($quota !== \OCP\Files\FileInfo::SPACE_UNLIMITED) {
253
+                        return new \OC\Files\Storage\Wrapper\Quota(array('storage' => $storage, 'quota' => $quota, 'root' => 'files'));
254
+                    }
255
+                }
256
+            }
257
+
258
+            return $storage;
259
+        });
260
+
261
+        OC_Hook::emit('OC_Filesystem', 'preSetup', array('user' => $user));
262
+        \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(true);
263
+
264
+        //check if we are using an object storage
265
+        $objectStore = \OC::$server->getSystemConfig()->getValue('objectstore', null);
266
+        $objectStoreMultibucket = \OC::$server->getSystemConfig()->getValue('objectstore_multibucket', null);
267
+
268
+        // use the same order as in ObjectHomeMountProvider
269
+        if (isset($objectStoreMultibucket)) {
270
+            self::initObjectStoreMultibucketRootFS($objectStoreMultibucket);
271
+        } elseif (isset($objectStore)) {
272
+            self::initObjectStoreRootFS($objectStore);
273
+        } else {
274
+            self::initLocalStorageRootFS();
275
+        }
276
+
277
+        if ($user != '' && !\OC::$server->getUserManager()->userExists($user)) {
278
+            \OC::$server->getEventLogger()->end('setup_fs');
279
+            return false;
280
+        }
281
+
282
+        //if we aren't logged in, there is no use to set up the filesystem
283
+        if ($user != "") {
284
+
285
+            $userDir = '/' . $user . '/files';
286
+
287
+            //jail the user into his "home" directory
288
+            \OC\Files\Filesystem::init($user, $userDir);
289
+
290
+            OC_Hook::emit('OC_Filesystem', 'setup', array('user' => $user, 'user_dir' => $userDir));
291
+        }
292
+        \OC::$server->getEventLogger()->end('setup_fs');
293
+        return true;
294
+    }
295
+
296
+    /**
297
+     * check if a password is required for each public link
298
+     *
299
+     * @return boolean
300
+     * @suppress PhanDeprecatedFunction
301
+     */
302
+    public static function isPublicLinkPasswordRequired() {
303
+        $appConfig = \OC::$server->getAppConfig();
304
+        $enforcePassword = $appConfig->getValue('core', 'shareapi_enforce_links_password', 'no');
305
+        return ($enforcePassword === 'yes') ? true : false;
306
+    }
307
+
308
+    /**
309
+     * check if sharing is disabled for the current user
310
+     * @param IConfig $config
311
+     * @param IGroupManager $groupManager
312
+     * @param IUser|null $user
313
+     * @return bool
314
+     */
315
+    public static function isSharingDisabledForUser(IConfig $config, IGroupManager $groupManager, $user) {
316
+        if ($config->getAppValue('core', 'shareapi_exclude_groups', 'no') === 'yes') {
317
+            $groupsList = $config->getAppValue('core', 'shareapi_exclude_groups_list', '');
318
+            $excludedGroups = json_decode($groupsList);
319
+            if (is_null($excludedGroups)) {
320
+                $excludedGroups = explode(',', $groupsList);
321
+                $newValue = json_encode($excludedGroups);
322
+                $config->setAppValue('core', 'shareapi_exclude_groups_list', $newValue);
323
+            }
324
+            $usersGroups = $groupManager->getUserGroupIds($user);
325
+            if (!empty($usersGroups)) {
326
+                $remainingGroups = array_diff($usersGroups, $excludedGroups);
327
+                // if the user is only in groups which are disabled for sharing then
328
+                // sharing is also disabled for the user
329
+                if (empty($remainingGroups)) {
330
+                    return true;
331
+                }
332
+            }
333
+        }
334
+        return false;
335
+    }
336
+
337
+    /**
338
+     * check if share API enforces a default expire date
339
+     *
340
+     * @return boolean
341
+     * @suppress PhanDeprecatedFunction
342
+     */
343
+    public static function isDefaultExpireDateEnforced() {
344
+        $isDefaultExpireDateEnabled = \OC::$server->getConfig()->getAppValue('core', 'shareapi_default_expire_date', 'no');
345
+        $enforceDefaultExpireDate = false;
346
+        if ($isDefaultExpireDateEnabled === 'yes') {
347
+            $value = \OC::$server->getConfig()->getAppValue('core', 'shareapi_enforce_expire_date', 'no');
348
+            $enforceDefaultExpireDate = ($value === 'yes') ? true : false;
349
+        }
350
+
351
+        return $enforceDefaultExpireDate;
352
+    }
353
+
354
+    /**
355
+     * Get the quota of a user
356
+     *
357
+     * @param string $userId
358
+     * @return float Quota bytes
359
+     */
360
+    public static function getUserQuota($userId) {
361
+        $user = \OC::$server->getUserManager()->get($userId);
362
+        if (is_null($user)) {
363
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
364
+        }
365
+        $userQuota = $user->getQuota();
366
+        if($userQuota === 'none') {
367
+            return \OCP\Files\FileInfo::SPACE_UNLIMITED;
368
+        }
369
+        return OC_Helper::computerFileSize($userQuota);
370
+    }
371
+
372
+    /**
373
+     * copies the skeleton to the users /files
374
+     *
375
+     * @param String $userId
376
+     * @param \OCP\Files\Folder $userDirectory
377
+     * @throws \RuntimeException
378
+     * @suppress PhanDeprecatedFunction
379
+     */
380
+    public static function copySkeleton($userId, \OCP\Files\Folder $userDirectory) {
381
+
382
+        $plainSkeletonDirectory = \OC::$server->getConfig()->getSystemValue('skeletondirectory', \OC::$SERVERROOT . '/core/skeleton');
383
+        $userLang = \OC::$server->getL10NFactory()->findLanguage();
384
+        $skeletonDirectory = str_replace('{lang}', $userLang, $plainSkeletonDirectory);
385
+
386
+        if (!file_exists($skeletonDirectory)) {
387
+            $dialectStart = strpos($userLang, '_');
388
+            if ($dialectStart !== false) {
389
+                $skeletonDirectory = str_replace('{lang}', substr($userLang, 0, $dialectStart), $plainSkeletonDirectory);
390
+            }
391
+            if ($dialectStart === false || !file_exists($skeletonDirectory)) {
392
+                $skeletonDirectory = str_replace('{lang}', 'default', $plainSkeletonDirectory);
393
+            }
394
+            if (!file_exists($skeletonDirectory)) {
395
+                $skeletonDirectory = '';
396
+            }
397
+        }
398
+
399
+        $instanceId = \OC::$server->getConfig()->getSystemValue('instanceid', '');
400
+
401
+        if ($instanceId === null) {
402
+            throw new \RuntimeException('no instance id!');
403
+        }
404
+        $appdata = 'appdata_' . $instanceId;
405
+        if ($userId === $appdata) {
406
+            throw new \RuntimeException('username is reserved name: ' . $appdata);
407
+        }
408
+
409
+        if (!empty($skeletonDirectory)) {
410
+            \OCP\Util::writeLog(
411
+                'files_skeleton',
412
+                'copying skeleton for '.$userId.' from '.$skeletonDirectory.' to '.$userDirectory->getFullPath('/'),
413
+                \OCP\Util::DEBUG
414
+            );
415
+            self::copyr($skeletonDirectory, $userDirectory);
416
+            // update the file cache
417
+            $userDirectory->getStorage()->getScanner()->scan('', \OC\Files\Cache\Scanner::SCAN_RECURSIVE);
418
+        }
419
+    }
420
+
421
+    /**
422
+     * copies a directory recursively by using streams
423
+     *
424
+     * @param string $source
425
+     * @param \OCP\Files\Folder $target
426
+     * @return void
427
+     */
428
+    public static function copyr($source, \OCP\Files\Folder $target) {
429
+        $logger = \OC::$server->getLogger();
430
+
431
+        // Verify if folder exists
432
+        $dir = opendir($source);
433
+        if($dir === false) {
434
+            $logger->error(sprintf('Could not opendir "%s"', $source), ['app' => 'core']);
435
+            return;
436
+        }
437
+
438
+        // Copy the files
439
+        while (false !== ($file = readdir($dir))) {
440
+            if (!\OC\Files\Filesystem::isIgnoredDir($file)) {
441
+                if (is_dir($source . '/' . $file)) {
442
+                    $child = $target->newFolder($file);
443
+                    self::copyr($source . '/' . $file, $child);
444
+                } else {
445
+                    $child = $target->newFile($file);
446
+                    $sourceStream = fopen($source . '/' . $file, 'r');
447
+                    if($sourceStream === false) {
448
+                        $logger->error(sprintf('Could not fopen "%s"', $source . '/' . $file), ['app' => 'core']);
449
+                        closedir($dir);
450
+                        return;
451
+                    }
452
+                    stream_copy_to_stream($sourceStream, $child->fopen('w'));
453
+                }
454
+            }
455
+        }
456
+        closedir($dir);
457
+    }
458
+
459
+    /**
460
+     * @return void
461
+     * @suppress PhanUndeclaredMethod
462
+     */
463
+    public static function tearDownFS() {
464
+        \OC\Files\Filesystem::tearDown();
465
+        \OC::$server->getRootFolder()->clearCache();
466
+        self::$fsSetup = false;
467
+        self::$rootMounted = false;
468
+    }
469
+
470
+    /**
471
+     * get the current installed version of ownCloud
472
+     *
473
+     * @return array
474
+     */
475
+    public static function getVersion() {
476
+        OC_Util::loadVersion();
477
+        return self::$versionCache['OC_Version'];
478
+    }
479
+
480
+    /**
481
+     * get the current installed version string of ownCloud
482
+     *
483
+     * @return string
484
+     */
485
+    public static function getVersionString() {
486
+        OC_Util::loadVersion();
487
+        return self::$versionCache['OC_VersionString'];
488
+    }
489
+
490
+    /**
491
+     * @deprecated the value is of no use anymore
492
+     * @return string
493
+     */
494
+    public static function getEditionString() {
495
+        return '';
496
+    }
497
+
498
+    /**
499
+     * @description get the update channel of the current installed of ownCloud.
500
+     * @return string
501
+     */
502
+    public static function getChannel() {
503
+        OC_Util::loadVersion();
504
+        return \OC::$server->getConfig()->getSystemValue('updater.release.channel', self::$versionCache['OC_Channel']);
505
+    }
506
+
507
+    /**
508
+     * @description get the build number of the current installed of ownCloud.
509
+     * @return string
510
+     */
511
+    public static function getBuild() {
512
+        OC_Util::loadVersion();
513
+        return self::$versionCache['OC_Build'];
514
+    }
515
+
516
+    /**
517
+     * @description load the version.php into the session as cache
518
+     * @suppress PhanUndeclaredVariable
519
+     */
520
+    private static function loadVersion() {
521
+        if (self::$versionCache !== null) {
522
+            return;
523
+        }
524
+
525
+        $timestamp = filemtime(OC::$SERVERROOT . '/version.php');
526
+        require OC::$SERVERROOT . '/version.php';
527
+        /** @var $timestamp int */
528
+        self::$versionCache['OC_Version_Timestamp'] = $timestamp;
529
+        /** @var $OC_Version string */
530
+        self::$versionCache['OC_Version'] = $OC_Version;
531
+        /** @var $OC_VersionString string */
532
+        self::$versionCache['OC_VersionString'] = $OC_VersionString;
533
+        /** @var $OC_Build string */
534
+        self::$versionCache['OC_Build'] = $OC_Build;
535
+
536
+        /** @var $OC_Channel string */
537
+        self::$versionCache['OC_Channel'] = $OC_Channel;
538
+    }
539
+
540
+    /**
541
+     * generates a path for JS/CSS files. If no application is provided it will create the path for core.
542
+     *
543
+     * @param string $application application to get the files from
544
+     * @param string $directory directory within this application (css, js, vendor, etc)
545
+     * @param string $file the file inside of the above folder
546
+     * @return string the path
547
+     */
548
+    private static function generatePath($application, $directory, $file) {
549
+        if (is_null($file)) {
550
+            $file = $application;
551
+            $application = "";
552
+        }
553
+        if (!empty($application)) {
554
+            return "$application/$directory/$file";
555
+        } else {
556
+            return "$directory/$file";
557
+        }
558
+    }
559
+
560
+    /**
561
+     * add a javascript file
562
+     *
563
+     * @param string $application application id
564
+     * @param string|null $file filename
565
+     * @param bool $prepend prepend the Script to the beginning of the list
566
+     * @return void
567
+     */
568
+    public static function addScript($application, $file = null, $prepend = false) {
569
+        $path = OC_Util::generatePath($application, 'js', $file);
570
+
571
+        // core js files need separate handling
572
+        if ($application !== 'core' && $file !== null) {
573
+            self::addTranslations ( $application );
574
+        }
575
+        self::addExternalResource($application, $prepend, $path, "script");
576
+    }
577
+
578
+    /**
579
+     * add a javascript file from the vendor sub folder
580
+     *
581
+     * @param string $application application id
582
+     * @param string|null $file filename
583
+     * @param bool $prepend prepend the Script to the beginning of the list
584
+     * @return void
585
+     */
586
+    public static function addVendorScript($application, $file = null, $prepend = false) {
587
+        $path = OC_Util::generatePath($application, 'vendor', $file);
588
+        self::addExternalResource($application, $prepend, $path, "script");
589
+    }
590
+
591
+    /**
592
+     * add a translation JS file
593
+     *
594
+     * @param string $application application id
595
+     * @param string|null $languageCode language code, defaults to the current language
596
+     * @param bool|null $prepend prepend the Script to the beginning of the list
597
+     */
598
+    public static function addTranslations($application, $languageCode = null, $prepend = false) {
599
+        if (is_null($languageCode)) {
600
+            $languageCode = \OC::$server->getL10NFactory()->findLanguage($application);
601
+        }
602
+        if (!empty($application)) {
603
+            $path = "$application/l10n/$languageCode";
604
+        } else {
605
+            $path = "l10n/$languageCode";
606
+        }
607
+        self::addExternalResource($application, $prepend, $path, "script");
608
+    }
609
+
610
+    /**
611
+     * add a css file
612
+     *
613
+     * @param string $application application id
614
+     * @param string|null $file filename
615
+     * @param bool $prepend prepend the Style to the beginning of the list
616
+     * @return void
617
+     */
618
+    public static function addStyle($application, $file = null, $prepend = false) {
619
+        $path = OC_Util::generatePath($application, 'css', $file);
620
+        self::addExternalResource($application, $prepend, $path, "style");
621
+    }
622
+
623
+    /**
624
+     * add a css file from the vendor sub folder
625
+     *
626
+     * @param string $application application id
627
+     * @param string|null $file filename
628
+     * @param bool $prepend prepend the Style to the beginning of the list
629
+     * @return void
630
+     */
631
+    public static function addVendorStyle($application, $file = null, $prepend = false) {
632
+        $path = OC_Util::generatePath($application, 'vendor', $file);
633
+        self::addExternalResource($application, $prepend, $path, "style");
634
+    }
635
+
636
+    /**
637
+     * add an external resource css/js file
638
+     *
639
+     * @param string $application application id
640
+     * @param bool $prepend prepend the file to the beginning of the list
641
+     * @param string $path
642
+     * @param string $type (script or style)
643
+     * @return void
644
+     */
645
+    private static function addExternalResource($application, $prepend, $path, $type = "script") {
646
+
647
+        if ($type === "style") {
648
+            if (!in_array($path, self::$styles)) {
649
+                if ($prepend === true) {
650
+                    array_unshift ( self::$styles, $path );
651
+                } else {
652
+                    self::$styles[] = $path;
653
+                }
654
+            }
655
+        } elseif ($type === "script") {
656
+            if (!in_array($path, self::$scripts)) {
657
+                if ($prepend === true) {
658
+                    array_unshift ( self::$scripts, $path );
659
+                } else {
660
+                    self::$scripts [] = $path;
661
+                }
662
+            }
663
+        }
664
+    }
665
+
666
+    /**
667
+     * Add a custom element to the header
668
+     * If $text is null then the element will be written as empty element.
669
+     * So use "" to get a closing tag.
670
+     * @param string $tag tag name of the element
671
+     * @param array $attributes array of attributes for the element
672
+     * @param string $text the text content for the element
673
+     */
674
+    public static function addHeader($tag, $attributes, $text=null) {
675
+        self::$headers[] = array(
676
+            'tag' => $tag,
677
+            'attributes' => $attributes,
678
+            'text' => $text
679
+        );
680
+    }
681
+
682
+    /**
683
+     * formats a timestamp in the "right" way
684
+     *
685
+     * @param int $timestamp
686
+     * @param bool $dateOnly option to omit time from the result
687
+     * @param DateTimeZone|string $timeZone where the given timestamp shall be converted to
688
+     * @return string timestamp
689
+     *
690
+     * @deprecated Use \OC::$server->query('DateTimeFormatter') instead
691
+     */
692
+    public static function formatDate($timestamp, $dateOnly = false, $timeZone = null) {
693
+        if ($timeZone !== null && !$timeZone instanceof \DateTimeZone) {
694
+            $timeZone = new \DateTimeZone($timeZone);
695
+        }
696
+
697
+        /** @var \OC\DateTimeFormatter $formatter */
698
+        $formatter = \OC::$server->query('DateTimeFormatter');
699
+        if ($dateOnly) {
700
+            return $formatter->formatDate($timestamp, 'long', $timeZone);
701
+        }
702
+        return $formatter->formatDateTime($timestamp, 'long', 'long', $timeZone);
703
+    }
704
+
705
+    /**
706
+     * check if the current server configuration is suitable for ownCloud
707
+     *
708
+     * @param \OC\SystemConfig $config
709
+     * @return array arrays with error messages and hints
710
+     */
711
+    public static function checkServer(\OC\SystemConfig $config) {
712
+        $l = \OC::$server->getL10N('lib');
713
+        $errors = array();
714
+        $CONFIG_DATADIRECTORY = $config->getValue('datadirectory', OC::$SERVERROOT . '/data');
715
+
716
+        if (!self::needUpgrade($config) && $config->getValue('installed', false)) {
717
+            // this check needs to be done every time
718
+            $errors = self::checkDataDirectoryValidity($CONFIG_DATADIRECTORY);
719
+        }
720
+
721
+        // Assume that if checkServer() succeeded before in this session, then all is fine.
722
+        if (\OC::$server->getSession()->exists('checkServer_succeeded') && \OC::$server->getSession()->get('checkServer_succeeded')) {
723
+            return $errors;
724
+        }
725
+
726
+        $webServerRestart = false;
727
+        $setup = new \OC\Setup(
728
+            $config,
729
+            \OC::$server->getIniWrapper(),
730
+            \OC::$server->getL10N('lib'),
731
+            \OC::$server->query(\OCP\Defaults::class),
732
+            \OC::$server->getLogger(),
733
+            \OC::$server->getSecureRandom(),
734
+            \OC::$server->query(\OC\Installer::class)
735
+        );
736
+
737
+        $urlGenerator = \OC::$server->getURLGenerator();
738
+
739
+        $availableDatabases = $setup->getSupportedDatabases();
740
+        if (empty($availableDatabases)) {
741
+            $errors[] = array(
742
+                'error' => $l->t('No database drivers (sqlite, mysql, or postgresql) installed.'),
743
+                'hint' => '' //TODO: sane hint
744
+            );
745
+            $webServerRestart = true;
746
+        }
747
+
748
+        // Check if config folder is writable.
749
+        if(!OC_Helper::isReadOnlyConfigEnabled()) {
750
+            if (!is_writable(OC::$configDir) or !is_readable(OC::$configDir)) {
751
+                $errors[] = array(
752
+                    'error' => $l->t('Cannot write into "config" directory'),
753
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the config directory. See %s',
754
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
755
+                );
756
+            }
757
+        }
758
+
759
+        // Check if there is a writable install folder.
760
+        if ($config->getValue('appstoreenabled', true)) {
761
+            if (OC_App::getInstallPath() === null
762
+                || !is_writable(OC_App::getInstallPath())
763
+                || !is_readable(OC_App::getInstallPath())
764
+            ) {
765
+                $errors[] = array(
766
+                    'error' => $l->t('Cannot write into "apps" directory'),
767
+                    'hint' => $l->t('This can usually be fixed by giving the webserver write access to the apps directory'
768
+                        . ' or disabling the appstore in the config file. See %s',
769
+                        [$urlGenerator->linkToDocs('admin-dir_permissions')])
770
+                );
771
+            }
772
+        }
773
+        // Create root dir.
774
+        if ($config->getValue('installed', false)) {
775
+            if (!is_dir($CONFIG_DATADIRECTORY)) {
776
+                $success = @mkdir($CONFIG_DATADIRECTORY);
777
+                if ($success) {
778
+                    $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
779
+                } else {
780
+                    $errors[] = [
781
+                        'error' => $l->t('Cannot create "data" directory'),
782
+                        'hint' => $l->t('This can usually be fixed by giving the webserver write access to the root directory. See %s',
783
+                            [$urlGenerator->linkToDocs('admin-dir_permissions')])
784
+                    ];
785
+                }
786
+            } else if (!is_writable($CONFIG_DATADIRECTORY) or !is_readable($CONFIG_DATADIRECTORY)) {
787
+                //common hint for all file permissions error messages
788
+                $permissionsHint = $l->t('Permissions can usually be fixed by giving the webserver write access to the root directory. See %s.',
789
+                    [$urlGenerator->linkToDocs('admin-dir_permissions')]);
790
+                $errors[] = [
791
+                    'error' => 'Your data directory is not writable',
792
+                    'hint' => $permissionsHint
793
+                ];
794
+            } else {
795
+                $errors = array_merge($errors, self::checkDataDirectoryPermissions($CONFIG_DATADIRECTORY));
796
+            }
797
+        }
798
+
799
+        if (!OC_Util::isSetLocaleWorking()) {
800
+            $errors[] = array(
801
+                'error' => $l->t('Setting locale to %s failed',
802
+                    array('en_US.UTF-8/fr_FR.UTF-8/es_ES.UTF-8/de_DE.UTF-8/ru_RU.UTF-8/'
803
+                        . 'pt_BR.UTF-8/it_IT.UTF-8/ja_JP.UTF-8/zh_CN.UTF-8')),
804
+                'hint' => $l->t('Please install one of these locales on your system and restart your webserver.')
805
+            );
806
+        }
807
+
808
+        // Contains the dependencies that should be checked against
809
+        // classes = class_exists
810
+        // functions = function_exists
811
+        // defined = defined
812
+        // ini = ini_get
813
+        // If the dependency is not found the missing module name is shown to the EndUser
814
+        // When adding new checks always verify that they pass on Travis as well
815
+        // for ini settings, see https://github.com/owncloud/administration/blob/master/travis-ci/custom.ini
816
+        $dependencies = array(
817
+            'classes' => array(
818
+                'ZipArchive' => 'zip',
819
+                'DOMDocument' => 'dom',
820
+                'XMLWriter' => 'XMLWriter',
821
+                'XMLReader' => 'XMLReader',
822
+            ),
823
+            'functions' => [
824
+                'xml_parser_create' => 'libxml',
825
+                'mb_strcut' => 'mb multibyte',
826
+                'ctype_digit' => 'ctype',
827
+                'json_encode' => 'JSON',
828
+                'gd_info' => 'GD',
829
+                'gzencode' => 'zlib',
830
+                'iconv' => 'iconv',
831
+                'simplexml_load_string' => 'SimpleXML',
832
+                'hash' => 'HASH Message Digest Framework',
833
+                'curl_init' => 'cURL',
834
+                'openssl_verify' => 'OpenSSL',
835
+            ],
836
+            'defined' => array(
837
+                'PDO::ATTR_DRIVER_NAME' => 'PDO'
838
+            ),
839
+            'ini' => [
840
+                'default_charset' => 'UTF-8',
841
+            ],
842
+        );
843
+        $missingDependencies = array();
844
+        $invalidIniSettings = [];
845
+        $moduleHint = $l->t('Please ask your server administrator to install the module.');
846
+
847
+        /**
848
+         * FIXME: The dependency check does not work properly on HHVM on the moment
849
+         *        and prevents installation. Once HHVM is more compatible with our
850
+         *        approach to check for these values we should re-enable those
851
+         *        checks.
852
+         */
853
+        $iniWrapper = \OC::$server->getIniWrapper();
854
+        if (!self::runningOnHhvm()) {
855
+            foreach ($dependencies['classes'] as $class => $module) {
856
+                if (!class_exists($class)) {
857
+                    $missingDependencies[] = $module;
858
+                }
859
+            }
860
+            foreach ($dependencies['functions'] as $function => $module) {
861
+                if (!function_exists($function)) {
862
+                    $missingDependencies[] = $module;
863
+                }
864
+            }
865
+            foreach ($dependencies['defined'] as $defined => $module) {
866
+                if (!defined($defined)) {
867
+                    $missingDependencies[] = $module;
868
+                }
869
+            }
870
+            foreach ($dependencies['ini'] as $setting => $expected) {
871
+                if (is_bool($expected)) {
872
+                    if ($iniWrapper->getBool($setting) !== $expected) {
873
+                        $invalidIniSettings[] = [$setting, $expected];
874
+                    }
875
+                }
876
+                if (is_int($expected)) {
877
+                    if ($iniWrapper->getNumeric($setting) !== $expected) {
878
+                        $invalidIniSettings[] = [$setting, $expected];
879
+                    }
880
+                }
881
+                if (is_string($expected)) {
882
+                    if (strtolower($iniWrapper->getString($setting)) !== strtolower($expected)) {
883
+                        $invalidIniSettings[] = [$setting, $expected];
884
+                    }
885
+                }
886
+            }
887
+        }
888
+
889
+        foreach($missingDependencies as $missingDependency) {
890
+            $errors[] = array(
891
+                'error' => $l->t('PHP module %s not installed.', array($missingDependency)),
892
+                'hint' => $moduleHint
893
+            );
894
+            $webServerRestart = true;
895
+        }
896
+        foreach($invalidIniSettings as $setting) {
897
+            if(is_bool($setting[1])) {
898
+                $setting[1] = ($setting[1]) ? 'on' : 'off';
899
+            }
900
+            $errors[] = [
901
+                'error' => $l->t('PHP setting "%s" is not set to "%s".', [$setting[0], var_export($setting[1], true)]),
902
+                'hint' =>  $l->t('Adjusting this setting in php.ini will make Nextcloud run again')
903
+            ];
904
+            $webServerRestart = true;
905
+        }
906
+
907
+        /**
908
+         * The mbstring.func_overload check can only be performed if the mbstring
909
+         * module is installed as it will return null if the checking setting is
910
+         * not available and thus a check on the boolean value fails.
911
+         *
912
+         * TODO: Should probably be implemented in the above generic dependency
913
+         *       check somehow in the long-term.
914
+         */
915
+        if($iniWrapper->getBool('mbstring.func_overload') !== null &&
916
+            $iniWrapper->getBool('mbstring.func_overload') === true) {
917
+            $errors[] = array(
918
+                'error' => $l->t('mbstring.func_overload is set to "%s" instead of the expected value "0"', [$iniWrapper->getString('mbstring.func_overload')]),
919
+                'hint' => $l->t('To fix this issue set <code>mbstring.func_overload</code> to <code>0</code> in your php.ini')
920
+            );
921
+        }
922
+
923
+        if(function_exists('xml_parser_create') &&
924
+            LIBXML_LOADED_VERSION < 20700 ) {
925
+            $version = LIBXML_LOADED_VERSION;
926
+            $major = floor($version/10000);
927
+            $version -= ($major * 10000);
928
+            $minor = floor($version/100);
929
+            $version -= ($minor * 100);
930
+            $patch = $version;
931
+            $errors[] = array(
932
+                'error' => $l->t('libxml2 2.7.0 is at least required. Currently %s is installed.', [$major . '.' . $minor . '.' . $patch]),
933
+                'hint' => $l->t('To fix this issue update your libxml2 version and restart your web server.')
934
+            );
935
+        }
936
+
937
+        if (!self::isAnnotationsWorking()) {
938
+            $errors[] = array(
939
+                'error' => $l->t('PHP is apparently set up to strip inline doc blocks. This will make several core apps inaccessible.'),
940
+                'hint' => $l->t('This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator.')
941
+            );
942
+        }
943
+
944
+        if (!\OC::$CLI && $webServerRestart) {
945
+            $errors[] = array(
946
+                'error' => $l->t('PHP modules have been installed, but they are still listed as missing?'),
947
+                'hint' => $l->t('Please ask your server administrator to restart the web server.')
948
+            );
949
+        }
950
+
951
+        $errors = array_merge($errors, self::checkDatabaseVersion());
952
+
953
+        // Cache the result of this function
954
+        \OC::$server->getSession()->set('checkServer_succeeded', count($errors) == 0);
955
+
956
+        return $errors;
957
+    }
958
+
959
+    /**
960
+     * Check the database version
961
+     *
962
+     * @return array errors array
963
+     */
964
+    public static function checkDatabaseVersion() {
965
+        $l = \OC::$server->getL10N('lib');
966
+        $errors = array();
967
+        $dbType = \OC::$server->getSystemConfig()->getValue('dbtype', 'sqlite');
968
+        if ($dbType === 'pgsql') {
969
+            // check PostgreSQL version
970
+            try {
971
+                $result = \OC_DB::executeAudited('SHOW SERVER_VERSION');
972
+                $data = $result->fetchRow();
973
+                if (isset($data['server_version'])) {
974
+                    $version = $data['server_version'];
975
+                    if (version_compare($version, '9.0.0', '<')) {
976
+                        $errors[] = array(
977
+                            'error' => $l->t('PostgreSQL >= 9 required'),
978
+                            'hint' => $l->t('Please upgrade your database version')
979
+                        );
980
+                    }
981
+                }
982
+            } catch (\Doctrine\DBAL\DBALException $e) {
983
+                $logger = \OC::$server->getLogger();
984
+                $logger->warning('Error occurred while checking PostgreSQL version, assuming >= 9');
985
+                $logger->logException($e);
986
+            }
987
+        }
988
+        return $errors;
989
+    }
990
+
991
+    /**
992
+     * Check for correct file permissions of data directory
993
+     *
994
+     * @param string $dataDirectory
995
+     * @return array arrays with error messages and hints
996
+     */
997
+    public static function checkDataDirectoryPermissions($dataDirectory) {
998
+        if(\OC::$server->getConfig()->getSystemValue('check_data_directory_permissions', true) === false) {
999
+            return  [];
1000
+        }
1001
+        $l = \OC::$server->getL10N('lib');
1002
+        $errors = [];
1003
+        $permissionsModHint = $l->t('Please change the permissions to 0770 so that the directory'
1004
+            . ' cannot be listed by other users.');
1005
+        $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1006
+        if (substr($perms, -1) !== '0') {
1007
+            chmod($dataDirectory, 0770);
1008
+            clearstatcache();
1009
+            $perms = substr(decoct(@fileperms($dataDirectory)), -3);
1010
+            if ($perms[2] !== '0') {
1011
+                $errors[] = [
1012
+                    'error' => $l->t('Your data directory is readable by other users'),
1013
+                    'hint' => $permissionsModHint
1014
+                ];
1015
+            }
1016
+        }
1017
+        return $errors;
1018
+    }
1019
+
1020
+    /**
1021
+     * Check that the data directory exists and is valid by
1022
+     * checking the existence of the ".ocdata" file.
1023
+     *
1024
+     * @param string $dataDirectory data directory path
1025
+     * @return array errors found
1026
+     */
1027
+    public static function checkDataDirectoryValidity($dataDirectory) {
1028
+        $l = \OC::$server->getL10N('lib');
1029
+        $errors = [];
1030
+        if ($dataDirectory[0] !== '/') {
1031
+            $errors[] = [
1032
+                'error' => $l->t('Your data directory must be an absolute path'),
1033
+                'hint' => $l->t('Check the value of "datadirectory" in your configuration')
1034
+            ];
1035
+        }
1036
+        if (!file_exists($dataDirectory . '/.ocdata')) {
1037
+            $errors[] = [
1038
+                'error' => $l->t('Your data directory is invalid'),
1039
+                'hint' => $l->t('Ensure there is a file called ".ocdata"' .
1040
+                    ' in the root of the data directory.')
1041
+            ];
1042
+        }
1043
+        return $errors;
1044
+    }
1045
+
1046
+    /**
1047
+     * Check if the user is logged in, redirects to home if not. With
1048
+     * redirect URL parameter to the request URI.
1049
+     *
1050
+     * @return void
1051
+     */
1052
+    public static function checkLoggedIn() {
1053
+        // Check if we are a user
1054
+        if (!\OC::$server->getUserSession()->isLoggedIn()) {
1055
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute(
1056
+                        'core.login.showLoginForm',
1057
+                        [
1058
+                            'redirect_url' => \OC::$server->getRequest()->getRequestUri(),
1059
+                        ]
1060
+                    )
1061
+            );
1062
+            exit();
1063
+        }
1064
+        // Redirect to 2FA challenge selection if 2FA challenge was not solved yet
1065
+        if (\OC::$server->getTwoFactorAuthManager()->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
1066
+            header('Location: ' . \OC::$server->getURLGenerator()->linkToRoute('core.TwoFactorChallenge.selectChallenge'));
1067
+            exit();
1068
+        }
1069
+    }
1070
+
1071
+    /**
1072
+     * Check if the user is a admin, redirects to home if not
1073
+     *
1074
+     * @return void
1075
+     */
1076
+    public static function checkAdminUser() {
1077
+        OC_Util::checkLoggedIn();
1078
+        if (!OC_User::isAdminUser(OC_User::getUser())) {
1079
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1080
+            exit();
1081
+        }
1082
+    }
1083
+
1084
+    /**
1085
+     * Check if the user is a subadmin, redirects to home if not
1086
+     *
1087
+     * @return null|boolean $groups where the current user is subadmin
1088
+     */
1089
+    public static function checkSubAdminUser() {
1090
+        OC_Util::checkLoggedIn();
1091
+        $userObject = \OC::$server->getUserSession()->getUser();
1092
+        $isSubAdmin = false;
1093
+        if($userObject !== null) {
1094
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
1095
+        }
1096
+
1097
+        if (!$isSubAdmin) {
1098
+            header('Location: ' . \OCP\Util::linkToAbsolute('', 'index.php'));
1099
+            exit();
1100
+        }
1101
+        return true;
1102
+    }
1103
+
1104
+    /**
1105
+     * Returns the URL of the default page
1106
+     * based on the system configuration and
1107
+     * the apps visible for the current user
1108
+     *
1109
+     * @return string URL
1110
+     * @suppress PhanDeprecatedFunction
1111
+     */
1112
+    public static function getDefaultPageUrl() {
1113
+        $urlGenerator = \OC::$server->getURLGenerator();
1114
+        // Deny the redirect if the URL contains a @
1115
+        // This prevents unvalidated redirects like ?redirect_url=:[email protected]
1116
+        if (isset($_REQUEST['redirect_url']) && strpos($_REQUEST['redirect_url'], '@') === false) {
1117
+            $location = $urlGenerator->getAbsoluteURL(urldecode($_REQUEST['redirect_url']));
1118
+        } else {
1119
+            $defaultPage = \OC::$server->getAppConfig()->getValue('core', 'defaultpage');
1120
+            if ($defaultPage) {
1121
+                $location = $urlGenerator->getAbsoluteURL($defaultPage);
1122
+            } else {
1123
+                $appId = 'files';
1124
+                $config = \OC::$server->getConfig();
1125
+                $defaultApps = explode(',', $config->getSystemValue('defaultapp', 'files'));
1126
+                // find the first app that is enabled for the current user
1127
+                foreach ($defaultApps as $defaultApp) {
1128
+                    $defaultApp = OC_App::cleanAppId(strip_tags($defaultApp));
1129
+                    if (static::getAppManager()->isEnabledForUser($defaultApp)) {
1130
+                        $appId = $defaultApp;
1131
+                        break;
1132
+                    }
1133
+                }
1134
+
1135
+                if($config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true') {
1136
+                    $location = $urlGenerator->getAbsoluteURL('/apps/' . $appId . '/');
1137
+                } else {
1138
+                    $location = $urlGenerator->getAbsoluteURL('/index.php/apps/' . $appId . '/');
1139
+                }
1140
+            }
1141
+        }
1142
+        return $location;
1143
+    }
1144
+
1145
+    /**
1146
+     * Redirect to the user default page
1147
+     *
1148
+     * @return void
1149
+     */
1150
+    public static function redirectToDefaultPage() {
1151
+        $location = self::getDefaultPageUrl();
1152
+        header('Location: ' . $location);
1153
+        exit();
1154
+    }
1155
+
1156
+    /**
1157
+     * get an id unique for this instance
1158
+     *
1159
+     * @return string
1160
+     */
1161
+    public static function getInstanceId() {
1162
+        $id = \OC::$server->getSystemConfig()->getValue('instanceid', null);
1163
+        if (is_null($id)) {
1164
+            // We need to guarantee at least one letter in instanceid so it can be used as the session_name
1165
+            $id = 'oc' . \OC::$server->getSecureRandom()->generate(10, \OCP\Security\ISecureRandom::CHAR_LOWER.\OCP\Security\ISecureRandom::CHAR_DIGITS);
1166
+            \OC::$server->getSystemConfig()->setValue('instanceid', $id);
1167
+        }
1168
+        return $id;
1169
+    }
1170
+
1171
+    /**
1172
+     * Public function to sanitize HTML
1173
+     *
1174
+     * This function is used to sanitize HTML and should be applied on any
1175
+     * string or array of strings before displaying it on a web page.
1176
+     *
1177
+     * @param string|array $value
1178
+     * @return string|array an array of sanitized strings or a single sanitized string, depends on the input parameter.
1179
+     */
1180
+    public static function sanitizeHTML($value) {
1181
+        if (is_array($value)) {
1182
+            $value = array_map(function($value) {
1183
+                return self::sanitizeHTML($value);
1184
+            }, $value);
1185
+        } else {
1186
+            // Specify encoding for PHP<5.4
1187
+            $value = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
1188
+        }
1189
+        return $value;
1190
+    }
1191
+
1192
+    /**
1193
+     * Public function to encode url parameters
1194
+     *
1195
+     * This function is used to encode path to file before output.
1196
+     * Encoding is done according to RFC 3986 with one exception:
1197
+     * Character '/' is preserved as is.
1198
+     *
1199
+     * @param string $component part of URI to encode
1200
+     * @return string
1201
+     */
1202
+    public static function encodePath($component) {
1203
+        $encoded = rawurlencode($component);
1204
+        $encoded = str_replace('%2F', '/', $encoded);
1205
+        return $encoded;
1206
+    }
1207
+
1208
+
1209
+    public function createHtaccessTestFile(\OCP\IConfig $config) {
1210
+        // php dev server does not support htaccess
1211
+        if (php_sapi_name() === 'cli-server') {
1212
+            return false;
1213
+        }
1214
+
1215
+        // testdata
1216
+        $fileName = '/htaccesstest.txt';
1217
+        $testContent = 'This is used for testing whether htaccess is properly enabled to disallow access from the outside. This file can be safely removed.';
1218
+
1219
+        // creating a test file
1220
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1221
+
1222
+        if (file_exists($testFile)) {// already running this test, possible recursive call
1223
+            return false;
1224
+        }
1225
+
1226
+        $fp = @fopen($testFile, 'w');
1227
+        if (!$fp) {
1228
+            throw new OC\HintException('Can\'t create test file to check for working .htaccess file.',
1229
+                'Make sure it is possible for the webserver to write to ' . $testFile);
1230
+        }
1231
+        fwrite($fp, $testContent);
1232
+        fclose($fp);
1233
+
1234
+        return $testContent;
1235
+    }
1236
+
1237
+    /**
1238
+     * Check if the .htaccess file is working
1239
+     * @param \OCP\IConfig $config
1240
+     * @return bool
1241
+     * @throws Exception
1242
+     * @throws \OC\HintException If the test file can't get written.
1243
+     */
1244
+    public function isHtaccessWorking(\OCP\IConfig $config) {
1245
+
1246
+        if (\OC::$CLI || !$config->getSystemValue('check_for_working_htaccess', true)) {
1247
+            return true;
1248
+        }
1249
+
1250
+        $testContent = $this->createHtaccessTestFile($config);
1251
+        if ($testContent === false) {
1252
+            return false;
1253
+        }
1254
+
1255
+        $fileName = '/htaccesstest.txt';
1256
+        $testFile = $config->getSystemValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $fileName;
1257
+
1258
+        // accessing the file via http
1259
+        $url = \OC::$server->getURLGenerator()->getAbsoluteURL(OC::$WEBROOT . '/data' . $fileName);
1260
+        try {
1261
+            $content = \OC::$server->getHTTPClientService()->newClient()->get($url)->getBody();
1262
+        } catch (\Exception $e) {
1263
+            $content = false;
1264
+        }
1265
+
1266
+        // cleanup
1267
+        @unlink($testFile);
1268
+
1269
+        /*
1270 1270
 		 * If the content is not equal to test content our .htaccess
1271 1271
 		 * is working as required
1272 1272
 		 */
1273
-		return $content !== $testContent;
1274
-	}
1275
-
1276
-	/**
1277
-	 * Check if the setlocal call does not work. This can happen if the right
1278
-	 * local packages are not available on the server.
1279
-	 *
1280
-	 * @return bool
1281
-	 */
1282
-	public static function isSetLocaleWorking() {
1283
-		\Patchwork\Utf8\Bootup::initLocale();
1284
-		if ('' === basename('§')) {
1285
-			return false;
1286
-		}
1287
-		return true;
1288
-	}
1289
-
1290
-	/**
1291
-	 * Check if it's possible to get the inline annotations
1292
-	 *
1293
-	 * @return bool
1294
-	 */
1295
-	public static function isAnnotationsWorking() {
1296
-		$reflection = new \ReflectionMethod(__METHOD__);
1297
-		$docs = $reflection->getDocComment();
1298
-
1299
-		return (is_string($docs) && strlen($docs) > 50);
1300
-	}
1301
-
1302
-	/**
1303
-	 * Check if the PHP module fileinfo is loaded.
1304
-	 *
1305
-	 * @return bool
1306
-	 */
1307
-	public static function fileInfoLoaded() {
1308
-		return function_exists('finfo_open');
1309
-	}
1310
-
1311
-	/**
1312
-	 * clear all levels of output buffering
1313
-	 *
1314
-	 * @return void
1315
-	 */
1316
-	public static function obEnd() {
1317
-		while (ob_get_level()) {
1318
-			ob_end_clean();
1319
-		}
1320
-	}
1321
-
1322
-	/**
1323
-	 * Checks whether the server is running on Mac OS X
1324
-	 *
1325
-	 * @return bool true if running on Mac OS X, false otherwise
1326
-	 */
1327
-	public static function runningOnMac() {
1328
-		return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1329
-	}
1330
-
1331
-	/**
1332
-	 * Checks whether server is running on HHVM
1333
-	 *
1334
-	 * @return bool True if running on HHVM, false otherwise
1335
-	 */
1336
-	public static function runningOnHhvm() {
1337
-		return defined('HHVM_VERSION');
1338
-	}
1339
-
1340
-	/**
1341
-	 * Handles the case that there may not be a theme, then check if a "default"
1342
-	 * theme exists and take that one
1343
-	 *
1344
-	 * @return string the theme
1345
-	 */
1346
-	public static function getTheme() {
1347
-		$theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1348
-
1349
-		if ($theme === '') {
1350
-			if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1351
-				$theme = 'default';
1352
-			}
1353
-		}
1354
-
1355
-		return $theme;
1356
-	}
1357
-
1358
-	/**
1359
-	 * Clear a single file from the opcode cache
1360
-	 * This is useful for writing to the config file
1361
-	 * in case the opcode cache does not re-validate files
1362
-	 * Returns true if successful, false if unsuccessful:
1363
-	 * caller should fall back on clearing the entire cache
1364
-	 * with clearOpcodeCache() if unsuccessful
1365
-	 *
1366
-	 * @param string $path the path of the file to clear from the cache
1367
-	 * @return bool true if underlying function returns true, otherwise false
1368
-	 */
1369
-	public static function deleteFromOpcodeCache($path) {
1370
-		$ret = false;
1371
-		if ($path) {
1372
-			// APC >= 3.1.1
1373
-			if (function_exists('apc_delete_file')) {
1374
-				$ret = @apc_delete_file($path);
1375
-			}
1376
-			// Zend OpCache >= 7.0.0, PHP >= 5.5.0
1377
-			if (function_exists('opcache_invalidate')) {
1378
-				$ret = opcache_invalidate($path);
1379
-			}
1380
-		}
1381
-		return $ret;
1382
-	}
1383
-
1384
-	/**
1385
-	 * Clear the opcode cache if one exists
1386
-	 * This is necessary for writing to the config file
1387
-	 * in case the opcode cache does not re-validate files
1388
-	 *
1389
-	 * @return void
1390
-	 * @suppress PhanDeprecatedFunction
1391
-	 * @suppress PhanUndeclaredConstant
1392
-	 */
1393
-	public static function clearOpcodeCache() {
1394
-		// APC
1395
-		if (function_exists('apc_clear_cache')) {
1396
-			apc_clear_cache();
1397
-		}
1398
-		// Zend Opcache
1399
-		if (function_exists('accelerator_reset')) {
1400
-			accelerator_reset();
1401
-		}
1402
-		// XCache
1403
-		if (function_exists('xcache_clear_cache')) {
1404
-			if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1405
-				\OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1406
-			} else {
1407
-				@xcache_clear_cache(XC_TYPE_PHP, 0);
1408
-			}
1409
-		}
1410
-		// Opcache (PHP >= 5.5)
1411
-		if (function_exists('opcache_reset')) {
1412
-			opcache_reset();
1413
-		}
1414
-	}
1415
-
1416
-	/**
1417
-	 * Normalize a unicode string
1418
-	 *
1419
-	 * @param string $value a not normalized string
1420
-	 * @return bool|string
1421
-	 */
1422
-	public static function normalizeUnicode($value) {
1423
-		if(Normalizer::isNormalized($value)) {
1424
-			return $value;
1425
-		}
1426
-
1427
-		$normalizedValue = Normalizer::normalize($value);
1428
-		if ($normalizedValue === null || $normalizedValue === false) {
1429
-			\OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1430
-			return $value;
1431
-		}
1432
-
1433
-		return $normalizedValue;
1434
-	}
1435
-
1436
-	/**
1437
-	 * A human readable string is generated based on version and build number
1438
-	 *
1439
-	 * @return string
1440
-	 */
1441
-	public static function getHumanVersion() {
1442
-		$version = OC_Util::getVersionString();
1443
-		$build = OC_Util::getBuild();
1444
-		if (!empty($build) and OC_Util::getChannel() === 'daily') {
1445
-			$version .= ' Build:' . $build;
1446
-		}
1447
-		return $version;
1448
-	}
1449
-
1450
-	/**
1451
-	 * Returns whether the given file name is valid
1452
-	 *
1453
-	 * @param string $file file name to check
1454
-	 * @return bool true if the file name is valid, false otherwise
1455
-	 * @deprecated use \OC\Files\View::verifyPath()
1456
-	 */
1457
-	public static function isValidFileName($file) {
1458
-		$trimmed = trim($file);
1459
-		if ($trimmed === '') {
1460
-			return false;
1461
-		}
1462
-		if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1463
-			return false;
1464
-		}
1465
-
1466
-		// detect part files
1467
-		if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1468
-			return false;
1469
-		}
1470
-
1471
-		foreach (str_split($trimmed) as $char) {
1472
-			if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1473
-				return false;
1474
-			}
1475
-		}
1476
-		return true;
1477
-	}
1478
-
1479
-	/**
1480
-	 * Check whether the instance needs to perform an upgrade,
1481
-	 * either when the core version is higher or any app requires
1482
-	 * an upgrade.
1483
-	 *
1484
-	 * @param \OC\SystemConfig $config
1485
-	 * @return bool whether the core or any app needs an upgrade
1486
-	 * @throws \OC\HintException When the upgrade from the given version is not allowed
1487
-	 */
1488
-	public static function needUpgrade(\OC\SystemConfig $config) {
1489
-		if ($config->getValue('installed', false)) {
1490
-			$installedVersion = $config->getValue('version', '0.0.0');
1491
-			$currentVersion = implode('.', \OCP\Util::getVersion());
1492
-			$versionDiff = version_compare($currentVersion, $installedVersion);
1493
-			if ($versionDiff > 0) {
1494
-				return true;
1495
-			} else if ($config->getValue('debug', false) && $versionDiff < 0) {
1496
-				// downgrade with debug
1497
-				$installedMajor = explode('.', $installedVersion);
1498
-				$installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1499
-				$currentMajor = explode('.', $currentVersion);
1500
-				$currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1501
-				if ($installedMajor === $currentMajor) {
1502
-					// Same major, allow downgrade for developers
1503
-					return true;
1504
-				} else {
1505
-					// downgrade attempt, throw exception
1506
-					throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1507
-				}
1508
-			} else if ($versionDiff < 0) {
1509
-				// downgrade attempt, throw exception
1510
-				throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1511
-			}
1512
-
1513
-			// also check for upgrades for apps (independently from the user)
1514
-			$apps = \OC_App::getEnabledApps(false, true);
1515
-			$shouldUpgrade = false;
1516
-			foreach ($apps as $app) {
1517
-				if (\OC_App::shouldUpgrade($app)) {
1518
-					$shouldUpgrade = true;
1519
-					break;
1520
-				}
1521
-			}
1522
-			return $shouldUpgrade;
1523
-		} else {
1524
-			return false;
1525
-		}
1526
-	}
1273
+        return $content !== $testContent;
1274
+    }
1275
+
1276
+    /**
1277
+     * Check if the setlocal call does not work. This can happen if the right
1278
+     * local packages are not available on the server.
1279
+     *
1280
+     * @return bool
1281
+     */
1282
+    public static function isSetLocaleWorking() {
1283
+        \Patchwork\Utf8\Bootup::initLocale();
1284
+        if ('' === basename('§')) {
1285
+            return false;
1286
+        }
1287
+        return true;
1288
+    }
1289
+
1290
+    /**
1291
+     * Check if it's possible to get the inline annotations
1292
+     *
1293
+     * @return bool
1294
+     */
1295
+    public static function isAnnotationsWorking() {
1296
+        $reflection = new \ReflectionMethod(__METHOD__);
1297
+        $docs = $reflection->getDocComment();
1298
+
1299
+        return (is_string($docs) && strlen($docs) > 50);
1300
+    }
1301
+
1302
+    /**
1303
+     * Check if the PHP module fileinfo is loaded.
1304
+     *
1305
+     * @return bool
1306
+     */
1307
+    public static function fileInfoLoaded() {
1308
+        return function_exists('finfo_open');
1309
+    }
1310
+
1311
+    /**
1312
+     * clear all levels of output buffering
1313
+     *
1314
+     * @return void
1315
+     */
1316
+    public static function obEnd() {
1317
+        while (ob_get_level()) {
1318
+            ob_end_clean();
1319
+        }
1320
+    }
1321
+
1322
+    /**
1323
+     * Checks whether the server is running on Mac OS X
1324
+     *
1325
+     * @return bool true if running on Mac OS X, false otherwise
1326
+     */
1327
+    public static function runningOnMac() {
1328
+        return (strtoupper(substr(PHP_OS, 0, 6)) === 'DARWIN');
1329
+    }
1330
+
1331
+    /**
1332
+     * Checks whether server is running on HHVM
1333
+     *
1334
+     * @return bool True if running on HHVM, false otherwise
1335
+     */
1336
+    public static function runningOnHhvm() {
1337
+        return defined('HHVM_VERSION');
1338
+    }
1339
+
1340
+    /**
1341
+     * Handles the case that there may not be a theme, then check if a "default"
1342
+     * theme exists and take that one
1343
+     *
1344
+     * @return string the theme
1345
+     */
1346
+    public static function getTheme() {
1347
+        $theme = \OC::$server->getSystemConfig()->getValue("theme", '');
1348
+
1349
+        if ($theme === '') {
1350
+            if (is_dir(OC::$SERVERROOT . '/themes/default')) {
1351
+                $theme = 'default';
1352
+            }
1353
+        }
1354
+
1355
+        return $theme;
1356
+    }
1357
+
1358
+    /**
1359
+     * Clear a single file from the opcode cache
1360
+     * This is useful for writing to the config file
1361
+     * in case the opcode cache does not re-validate files
1362
+     * Returns true if successful, false if unsuccessful:
1363
+     * caller should fall back on clearing the entire cache
1364
+     * with clearOpcodeCache() if unsuccessful
1365
+     *
1366
+     * @param string $path the path of the file to clear from the cache
1367
+     * @return bool true if underlying function returns true, otherwise false
1368
+     */
1369
+    public static function deleteFromOpcodeCache($path) {
1370
+        $ret = false;
1371
+        if ($path) {
1372
+            // APC >= 3.1.1
1373
+            if (function_exists('apc_delete_file')) {
1374
+                $ret = @apc_delete_file($path);
1375
+            }
1376
+            // Zend OpCache >= 7.0.0, PHP >= 5.5.0
1377
+            if (function_exists('opcache_invalidate')) {
1378
+                $ret = opcache_invalidate($path);
1379
+            }
1380
+        }
1381
+        return $ret;
1382
+    }
1383
+
1384
+    /**
1385
+     * Clear the opcode cache if one exists
1386
+     * This is necessary for writing to the config file
1387
+     * in case the opcode cache does not re-validate files
1388
+     *
1389
+     * @return void
1390
+     * @suppress PhanDeprecatedFunction
1391
+     * @suppress PhanUndeclaredConstant
1392
+     */
1393
+    public static function clearOpcodeCache() {
1394
+        // APC
1395
+        if (function_exists('apc_clear_cache')) {
1396
+            apc_clear_cache();
1397
+        }
1398
+        // Zend Opcache
1399
+        if (function_exists('accelerator_reset')) {
1400
+            accelerator_reset();
1401
+        }
1402
+        // XCache
1403
+        if (function_exists('xcache_clear_cache')) {
1404
+            if (\OC::$server->getIniWrapper()->getBool('xcache.admin.enable_auth')) {
1405
+                \OCP\Util::writeLog('core', 'XCache opcode cache will not be cleared because "xcache.admin.enable_auth" is enabled.', \OCP\Util::WARN);
1406
+            } else {
1407
+                @xcache_clear_cache(XC_TYPE_PHP, 0);
1408
+            }
1409
+        }
1410
+        // Opcache (PHP >= 5.5)
1411
+        if (function_exists('opcache_reset')) {
1412
+            opcache_reset();
1413
+        }
1414
+    }
1415
+
1416
+    /**
1417
+     * Normalize a unicode string
1418
+     *
1419
+     * @param string $value a not normalized string
1420
+     * @return bool|string
1421
+     */
1422
+    public static function normalizeUnicode($value) {
1423
+        if(Normalizer::isNormalized($value)) {
1424
+            return $value;
1425
+        }
1426
+
1427
+        $normalizedValue = Normalizer::normalize($value);
1428
+        if ($normalizedValue === null || $normalizedValue === false) {
1429
+            \OC::$server->getLogger()->warning('normalizing failed for "' . $value . '"', ['app' => 'core']);
1430
+            return $value;
1431
+        }
1432
+
1433
+        return $normalizedValue;
1434
+    }
1435
+
1436
+    /**
1437
+     * A human readable string is generated based on version and build number
1438
+     *
1439
+     * @return string
1440
+     */
1441
+    public static function getHumanVersion() {
1442
+        $version = OC_Util::getVersionString();
1443
+        $build = OC_Util::getBuild();
1444
+        if (!empty($build) and OC_Util::getChannel() === 'daily') {
1445
+            $version .= ' Build:' . $build;
1446
+        }
1447
+        return $version;
1448
+    }
1449
+
1450
+    /**
1451
+     * Returns whether the given file name is valid
1452
+     *
1453
+     * @param string $file file name to check
1454
+     * @return bool true if the file name is valid, false otherwise
1455
+     * @deprecated use \OC\Files\View::verifyPath()
1456
+     */
1457
+    public static function isValidFileName($file) {
1458
+        $trimmed = trim($file);
1459
+        if ($trimmed === '') {
1460
+            return false;
1461
+        }
1462
+        if (\OC\Files\Filesystem::isIgnoredDir($trimmed)) {
1463
+            return false;
1464
+        }
1465
+
1466
+        // detect part files
1467
+        if (preg_match('/' . \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX . '/', $trimmed) !== 0) {
1468
+            return false;
1469
+        }
1470
+
1471
+        foreach (str_split($trimmed) as $char) {
1472
+            if (strpos(\OCP\Constants::FILENAME_INVALID_CHARS, $char) !== false) {
1473
+                return false;
1474
+            }
1475
+        }
1476
+        return true;
1477
+    }
1478
+
1479
+    /**
1480
+     * Check whether the instance needs to perform an upgrade,
1481
+     * either when the core version is higher or any app requires
1482
+     * an upgrade.
1483
+     *
1484
+     * @param \OC\SystemConfig $config
1485
+     * @return bool whether the core or any app needs an upgrade
1486
+     * @throws \OC\HintException When the upgrade from the given version is not allowed
1487
+     */
1488
+    public static function needUpgrade(\OC\SystemConfig $config) {
1489
+        if ($config->getValue('installed', false)) {
1490
+            $installedVersion = $config->getValue('version', '0.0.0');
1491
+            $currentVersion = implode('.', \OCP\Util::getVersion());
1492
+            $versionDiff = version_compare($currentVersion, $installedVersion);
1493
+            if ($versionDiff > 0) {
1494
+                return true;
1495
+            } else if ($config->getValue('debug', false) && $versionDiff < 0) {
1496
+                // downgrade with debug
1497
+                $installedMajor = explode('.', $installedVersion);
1498
+                $installedMajor = $installedMajor[0] . '.' . $installedMajor[1];
1499
+                $currentMajor = explode('.', $currentVersion);
1500
+                $currentMajor = $currentMajor[0] . '.' . $currentMajor[1];
1501
+                if ($installedMajor === $currentMajor) {
1502
+                    // Same major, allow downgrade for developers
1503
+                    return true;
1504
+                } else {
1505
+                    // downgrade attempt, throw exception
1506
+                    throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1507
+                }
1508
+            } else if ($versionDiff < 0) {
1509
+                // downgrade attempt, throw exception
1510
+                throw new \OC\HintException('Downgrading is not supported and is likely to cause unpredictable issues (from ' . $installedVersion . ' to ' . $currentVersion . ')');
1511
+            }
1512
+
1513
+            // also check for upgrades for apps (independently from the user)
1514
+            $apps = \OC_App::getEnabledApps(false, true);
1515
+            $shouldUpgrade = false;
1516
+            foreach ($apps as $app) {
1517
+                if (\OC_App::shouldUpgrade($app)) {
1518
+                    $shouldUpgrade = true;
1519
+                    break;
1520
+                }
1521
+            }
1522
+            return $shouldUpgrade;
1523
+        } else {
1524
+            return false;
1525
+        }
1526
+    }
1527 1527
 
1528 1528
 }
Please login to merge, or discard this patch.
lib/private/legacy/json.php 2 patches
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -37,163 +37,163 @@
 block discarded – undo
37 37
  * @deprecated Use a AppFramework JSONResponse instead
38 38
  */
39 39
 class OC_JSON{
40
-	static protected $send_content_type_header = false;
41
-	/**
42
-	 * set Content-Type header to jsonrequest
43
-	 * @deprecated Use a AppFramework JSONResponse instead
44
-	 */
45
-	public static function setContentTypeHeader($type='application/json') {
46
-		if (!self::$send_content_type_header) {
47
-			// We send json data
48
-			header( 'Content-Type: '.$type . '; charset=utf-8');
49
-			self::$send_content_type_header = true;
50
-		}
51
-	}
40
+    static protected $send_content_type_header = false;
41
+    /**
42
+     * set Content-Type header to jsonrequest
43
+     * @deprecated Use a AppFramework JSONResponse instead
44
+     */
45
+    public static function setContentTypeHeader($type='application/json') {
46
+        if (!self::$send_content_type_header) {
47
+            // We send json data
48
+            header( 'Content-Type: '.$type . '; charset=utf-8');
49
+            self::$send_content_type_header = true;
50
+        }
51
+    }
52 52
 
53
-	/**
54
-	 * Check if the app is enabled, send json error msg if not
55
-	 * @param string $app
56
-	 * @deprecated Use the AppFramework instead. It will automatically check if the app is enabled.
57
-	 * @suppress PhanDeprecatedFunction
58
-	 */
59
-	public static function checkAppEnabled($app) {
60
-		if( !\OC::$server->getAppManager()->isEnabledForUser($app)) {
61
-			$l = \OC::$server->getL10N('lib');
62
-			self::error(array( 'data' => array( 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' )));
63
-			exit();
64
-		}
65
-	}
53
+    /**
54
+     * Check if the app is enabled, send json error msg if not
55
+     * @param string $app
56
+     * @deprecated Use the AppFramework instead. It will automatically check if the app is enabled.
57
+     * @suppress PhanDeprecatedFunction
58
+     */
59
+    public static function checkAppEnabled($app) {
60
+        if( !\OC::$server->getAppManager()->isEnabledForUser($app)) {
61
+            $l = \OC::$server->getL10N('lib');
62
+            self::error(array( 'data' => array( 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' )));
63
+            exit();
64
+        }
65
+    }
66 66
 
67
-	/**
68
-	 * Check if the user is logged in, send json error msg if not
69
-	 * @deprecated Use annotation based ACLs from the AppFramework instead
70
-	 * @suppress PhanDeprecatedFunction
71
-	 */
72
-	public static function checkLoggedIn() {
73
-		$twoFactorAuthManger = \OC::$server->getTwoFactorAuthManager();
74
-		if( !\OC::$server->getUserSession()->isLoggedIn()
75
-			|| $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
76
-			$l = \OC::$server->getL10N('lib');
77
-			http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
78
-			self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
79
-			exit();
80
-		}
81
-	}
67
+    /**
68
+     * Check if the user is logged in, send json error msg if not
69
+     * @deprecated Use annotation based ACLs from the AppFramework instead
70
+     * @suppress PhanDeprecatedFunction
71
+     */
72
+    public static function checkLoggedIn() {
73
+        $twoFactorAuthManger = \OC::$server->getTwoFactorAuthManager();
74
+        if( !\OC::$server->getUserSession()->isLoggedIn()
75
+            || $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
76
+            $l = \OC::$server->getL10N('lib');
77
+            http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
78
+            self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
79
+            exit();
80
+        }
81
+    }
82 82
 
83
-	/**
84
-	 * Check an ajax get/post call if the request token is valid, send json error msg if not.
85
-	 * @deprecated Use annotation based CSRF checks from the AppFramework instead
86
-	 * @suppress PhanDeprecatedFunction
87
-	 */
88
-	public static function callCheck() {
89
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
90
-			header('Location: '.\OC::$WEBROOT);
91
-			exit();
92
-		}
83
+    /**
84
+     * Check an ajax get/post call if the request token is valid, send json error msg if not.
85
+     * @deprecated Use annotation based CSRF checks from the AppFramework instead
86
+     * @suppress PhanDeprecatedFunction
87
+     */
88
+    public static function callCheck() {
89
+        if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
90
+            header('Location: '.\OC::$WEBROOT);
91
+            exit();
92
+        }
93 93
 
94
-		if( !(\OC::$server->getRequest()->passesCSRFCheck())) {
95
-			$l = \OC::$server->getL10N('lib');
96
-			self::error(array( 'data' => array( 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' )));
97
-			exit();
98
-		}
99
-	}
94
+        if( !(\OC::$server->getRequest()->passesCSRFCheck())) {
95
+            $l = \OC::$server->getL10N('lib');
96
+            self::error(array( 'data' => array( 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' )));
97
+            exit();
98
+        }
99
+    }
100 100
 
101
-	/**
102
-	 * Check if the user is a admin, send json error msg if not.
103
-	 * @deprecated Use annotation based ACLs from the AppFramework instead
104
-	 * @suppress PhanDeprecatedFunction
105
-	 */
106
-	public static function checkAdminUser() {
107
-		if( !OC_User::isAdminUser(OC_User::getUser())) {
108
-			$l = \OC::$server->getL10N('lib');
109
-			self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
110
-			exit();
111
-		}
112
-	}
101
+    /**
102
+     * Check if the user is a admin, send json error msg if not.
103
+     * @deprecated Use annotation based ACLs from the AppFramework instead
104
+     * @suppress PhanDeprecatedFunction
105
+     */
106
+    public static function checkAdminUser() {
107
+        if( !OC_User::isAdminUser(OC_User::getUser())) {
108
+            $l = \OC::$server->getL10N('lib');
109
+            self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
110
+            exit();
111
+        }
112
+    }
113 113
 
114
-	/**
115
-	 * Check is a given user exists - send json error msg if not
116
-	 * @param string $user
117
-	 * @deprecated Use a AppFramework JSONResponse instead
118
-	 * @suppress PhanDeprecatedFunction
119
-	 */
120
-	public static function checkUserExists($user) {
121
-		if (!\OC::$server->getUserManager()->userExists($user)) {
122
-			$l = \OC::$server->getL10N('lib');
123
-			OCP\JSON::error(array('data' => array('message' => $l->t('Unknown user'), 'error' => 'unknown_user' )));
124
-			exit;
125
-		}
126
-	}
114
+    /**
115
+     * Check is a given user exists - send json error msg if not
116
+     * @param string $user
117
+     * @deprecated Use a AppFramework JSONResponse instead
118
+     * @suppress PhanDeprecatedFunction
119
+     */
120
+    public static function checkUserExists($user) {
121
+        if (!\OC::$server->getUserManager()->userExists($user)) {
122
+            $l = \OC::$server->getL10N('lib');
123
+            OCP\JSON::error(array('data' => array('message' => $l->t('Unknown user'), 'error' => 'unknown_user' )));
124
+            exit;
125
+        }
126
+    }
127 127
 
128 128
 
129
-	/**
130
-	 * Check if the user is a subadmin, send json error msg if not
131
-	 * @deprecated Use annotation based ACLs from the AppFramework instead
132
-	 * @suppress PhanDeprecatedFunction
133
-	 */
134
-	public static function checkSubAdminUser() {
135
-		$userObject = \OC::$server->getUserSession()->getUser();
136
-		$isSubAdmin = false;
137
-		if($userObject !== null) {
138
-			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
139
-		}
129
+    /**
130
+     * Check if the user is a subadmin, send json error msg if not
131
+     * @deprecated Use annotation based ACLs from the AppFramework instead
132
+     * @suppress PhanDeprecatedFunction
133
+     */
134
+    public static function checkSubAdminUser() {
135
+        $userObject = \OC::$server->getUserSession()->getUser();
136
+        $isSubAdmin = false;
137
+        if($userObject !== null) {
138
+            $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
139
+        }
140 140
 
141
-		if(!$isSubAdmin) {
142
-			$l = \OC::$server->getL10N('lib');
143
-			self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
144
-			exit();
145
-		}
146
-	}
141
+        if(!$isSubAdmin) {
142
+            $l = \OC::$server->getL10N('lib');
143
+            self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
144
+            exit();
145
+        }
146
+    }
147 147
 
148
-	/**
149
-	 * Send json error msg
150
-	 * @deprecated Use a AppFramework JSONResponse instead
151
-	 * @suppress PhanDeprecatedFunction
152
-	 */
153
-	public static function error($data = array()) {
154
-		$data['status'] = 'error';
155
-		self::encodedPrint($data);
156
-	}
148
+    /**
149
+     * Send json error msg
150
+     * @deprecated Use a AppFramework JSONResponse instead
151
+     * @suppress PhanDeprecatedFunction
152
+     */
153
+    public static function error($data = array()) {
154
+        $data['status'] = 'error';
155
+        self::encodedPrint($data);
156
+    }
157 157
 
158
-	/**
159
-	 * Send json success msg
160
-	 * @deprecated Use a AppFramework JSONResponse instead
161
-	 * @suppress PhanDeprecatedFunction
162
-	 */
163
-	public static function success($data = array()) {
164
-		$data['status'] = 'success';
165
-		self::encodedPrint($data);
166
-	}
158
+    /**
159
+     * Send json success msg
160
+     * @deprecated Use a AppFramework JSONResponse instead
161
+     * @suppress PhanDeprecatedFunction
162
+     */
163
+    public static function success($data = array()) {
164
+        $data['status'] = 'success';
165
+        self::encodedPrint($data);
166
+    }
167 167
 
168
-	/**
169
-	 * Convert OC_L10N_String to string, for use in json encodings
170
-	 */
171
-	protected static function to_string(&$value) {
172
-		if ($value instanceof \OC\L10N\L10NString) {
173
-			$value = (string)$value;
174
-		}
175
-	}
168
+    /**
169
+     * Convert OC_L10N_String to string, for use in json encodings
170
+     */
171
+    protected static function to_string(&$value) {
172
+        if ($value instanceof \OC\L10N\L10NString) {
173
+            $value = (string)$value;
174
+        }
175
+    }
176 176
 
177
-	/**
178
-	 * Encode and print $data in json format
179
-	 * @deprecated Use a AppFramework JSONResponse instead
180
-	 * @suppress PhanDeprecatedFunction
181
-	 */
182
-	public static function encodedPrint($data, $setContentType=true) {
183
-		if($setContentType) {
184
-			self::setContentTypeHeader();
185
-		}
186
-		echo self::encode($data);
187
-	}
177
+    /**
178
+     * Encode and print $data in json format
179
+     * @deprecated Use a AppFramework JSONResponse instead
180
+     * @suppress PhanDeprecatedFunction
181
+     */
182
+    public static function encodedPrint($data, $setContentType=true) {
183
+        if($setContentType) {
184
+            self::setContentTypeHeader();
185
+        }
186
+        echo self::encode($data);
187
+    }
188 188
 
189
-	/**
190
-	 * Encode JSON
191
-	 * @deprecated Use a AppFramework JSONResponse instead
192
-	 */
193
-	public static function encode($data) {
194
-		if (is_array($data)) {
195
-			array_walk_recursive($data, array('OC_JSON', 'to_string'));
196
-		}
197
-		return json_encode($data, JSON_HEX_TAG);
198
-	}
189
+    /**
190
+     * Encode JSON
191
+     * @deprecated Use a AppFramework JSONResponse instead
192
+     */
193
+    public static function encode($data) {
194
+        if (is_array($data)) {
195
+            array_walk_recursive($data, array('OC_JSON', 'to_string'));
196
+        }
197
+        return json_encode($data, JSON_HEX_TAG);
198
+    }
199 199
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -36,16 +36,16 @@  discard block
 block discarded – undo
36 36
  * Class OC_JSON
37 37
  * @deprecated Use a AppFramework JSONResponse instead
38 38
  */
39
-class OC_JSON{
39
+class OC_JSON {
40 40
 	static protected $send_content_type_header = false;
41 41
 	/**
42 42
 	 * set Content-Type header to jsonrequest
43 43
 	 * @deprecated Use a AppFramework JSONResponse instead
44 44
 	 */
45
-	public static function setContentTypeHeader($type='application/json') {
45
+	public static function setContentTypeHeader($type = 'application/json') {
46 46
 		if (!self::$send_content_type_header) {
47 47
 			// We send json data
48
-			header( 'Content-Type: '.$type . '; charset=utf-8');
48
+			header('Content-Type: '.$type.'; charset=utf-8');
49 49
 			self::$send_content_type_header = true;
50 50
 		}
51 51
 	}
@@ -57,9 +57,9 @@  discard block
 block discarded – undo
57 57
 	 * @suppress PhanDeprecatedFunction
58 58
 	 */
59 59
 	public static function checkAppEnabled($app) {
60
-		if( !\OC::$server->getAppManager()->isEnabledForUser($app)) {
60
+		if (!\OC::$server->getAppManager()->isEnabledForUser($app)) {
61 61
 			$l = \OC::$server->getL10N('lib');
62
-			self::error(array( 'data' => array( 'message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled' )));
62
+			self::error(array('data' => array('message' => $l->t('Application is not enabled'), 'error' => 'application_not_enabled')));
63 63
 			exit();
64 64
 		}
65 65
 	}
@@ -71,11 +71,11 @@  discard block
 block discarded – undo
71 71
 	 */
72 72
 	public static function checkLoggedIn() {
73 73
 		$twoFactorAuthManger = \OC::$server->getTwoFactorAuthManager();
74
-		if( !\OC::$server->getUserSession()->isLoggedIn()
74
+		if (!\OC::$server->getUserSession()->isLoggedIn()
75 75
 			|| $twoFactorAuthManger->needsSecondFactor(\OC::$server->getUserSession()->getUser())) {
76 76
 			$l = \OC::$server->getL10N('lib');
77 77
 			http_response_code(\OCP\AppFramework\Http::STATUS_UNAUTHORIZED);
78
-			self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
78
+			self::error(array('data' => array('message' => $l->t('Authentication error'), 'error' => 'authentication_error')));
79 79
 			exit();
80 80
 		}
81 81
 	}
@@ -86,14 +86,14 @@  discard block
 block discarded – undo
86 86
 	 * @suppress PhanDeprecatedFunction
87 87
 	 */
88 88
 	public static function callCheck() {
89
-		if(!\OC::$server->getRequest()->passesStrictCookieCheck()) {
89
+		if (!\OC::$server->getRequest()->passesStrictCookieCheck()) {
90 90
 			header('Location: '.\OC::$WEBROOT);
91 91
 			exit();
92 92
 		}
93 93
 
94
-		if( !(\OC::$server->getRequest()->passesCSRFCheck())) {
94
+		if (!(\OC::$server->getRequest()->passesCSRFCheck())) {
95 95
 			$l = \OC::$server->getL10N('lib');
96
-			self::error(array( 'data' => array( 'message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired' )));
96
+			self::error(array('data' => array('message' => $l->t('Token expired. Please reload page.'), 'error' => 'token_expired')));
97 97
 			exit();
98 98
 		}
99 99
 	}
@@ -104,9 +104,9 @@  discard block
 block discarded – undo
104 104
 	 * @suppress PhanDeprecatedFunction
105 105
 	 */
106 106
 	public static function checkAdminUser() {
107
-		if( !OC_User::isAdminUser(OC_User::getUser())) {
107
+		if (!OC_User::isAdminUser(OC_User::getUser())) {
108 108
 			$l = \OC::$server->getL10N('lib');
109
-			self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
109
+			self::error(array('data' => array('message' => $l->t('Authentication error'), 'error' => 'authentication_error')));
110 110
 			exit();
111 111
 		}
112 112
 	}
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 	public static function checkUserExists($user) {
121 121
 		if (!\OC::$server->getUserManager()->userExists($user)) {
122 122
 			$l = \OC::$server->getL10N('lib');
123
-			OCP\JSON::error(array('data' => array('message' => $l->t('Unknown user'), 'error' => 'unknown_user' )));
123
+			OCP\JSON::error(array('data' => array('message' => $l->t('Unknown user'), 'error' => 'unknown_user')));
124 124
 			exit;
125 125
 		}
126 126
 	}
@@ -134,13 +134,13 @@  discard block
 block discarded – undo
134 134
 	public static function checkSubAdminUser() {
135 135
 		$userObject = \OC::$server->getUserSession()->getUser();
136 136
 		$isSubAdmin = false;
137
-		if($userObject !== null) {
137
+		if ($userObject !== null) {
138 138
 			$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
139 139
 		}
140 140
 
141
-		if(!$isSubAdmin) {
141
+		if (!$isSubAdmin) {
142 142
 			$l = \OC::$server->getL10N('lib');
143
-			self::error(array( 'data' => array( 'message' => $l->t('Authentication error'), 'error' => 'authentication_error' )));
143
+			self::error(array('data' => array('message' => $l->t('Authentication error'), 'error' => 'authentication_error')));
144 144
 			exit();
145 145
 		}
146 146
 	}
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 	 */
171 171
 	protected static function to_string(&$value) {
172 172
 		if ($value instanceof \OC\L10N\L10NString) {
173
-			$value = (string)$value;
173
+			$value = (string) $value;
174 174
 		}
175 175
 	}
176 176
 
@@ -179,8 +179,8 @@  discard block
 block discarded – undo
179 179
 	 * @deprecated Use a AppFramework JSONResponse instead
180 180
 	 * @suppress PhanDeprecatedFunction
181 181
 	 */
182
-	public static function encodedPrint($data, $setContentType=true) {
183
-		if($setContentType) {
182
+	public static function encodedPrint($data, $setContentType = true) {
183
+		if ($setContentType) {
184 184
 			self::setContentTypeHeader();
185 185
 		}
186 186
 		echo self::encode($data);
Please login to merge, or discard this patch.
lib/private/legacy/user.php 1 patch
Indentation   +363 added lines, -363 removed lines patch added patch discarded remove patch
@@ -58,367 +58,367 @@
 block discarded – undo
58 58
  */
59 59
 class OC_User {
60 60
 
61
-	private static $_usedBackends = array();
62
-
63
-	private static $_setupedBackends = array();
64
-
65
-	// bool, stores if a user want to access a resource anonymously, e.g if they open a public link
66
-	private static $incognitoMode = false;
67
-
68
-	/**
69
-	 * Adds the backend to the list of used backends
70
-	 *
71
-	 * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
72
-	 * @return bool
73
-	 *
74
-	 * Set the User Authentication Module
75
-	 * @suppress PhanDeprecatedFunction
76
-	 */
77
-	public static function useBackend($backend = 'database') {
78
-		if ($backend instanceof \OCP\UserInterface) {
79
-			self::$_usedBackends[get_class($backend)] = $backend;
80
-			\OC::$server->getUserManager()->registerBackend($backend);
81
-		} else {
82
-			// You'll never know what happens
83
-			if (null === $backend OR !is_string($backend)) {
84
-				$backend = 'database';
85
-			}
86
-
87
-			// Load backend
88
-			switch ($backend) {
89
-				case 'database':
90
-				case 'mysql':
91
-				case 'sqlite':
92
-					\OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
93
-					self::$_usedBackends[$backend] = new \OC\User\Database();
94
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
95
-					break;
96
-				case 'dummy':
97
-					self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
98
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
99
-					break;
100
-				default:
101
-					\OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
102
-					$className = 'OC_USER_' . strtoupper($backend);
103
-					self::$_usedBackends[$backend] = new $className();
104
-					\OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
105
-					break;
106
-			}
107
-		}
108
-		return true;
109
-	}
110
-
111
-	/**
112
-	 * remove all used backends
113
-	 */
114
-	public static function clearBackends() {
115
-		self::$_usedBackends = array();
116
-		\OC::$server->getUserManager()->clearBackends();
117
-	}
118
-
119
-	/**
120
-	 * setup the configured backends in config.php
121
-	 * @suppress PhanDeprecatedFunction
122
-	 */
123
-	public static function setupBackends() {
124
-		OC_App::loadApps(['prelogin']);
125
-		$backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
126
-		if (isset($backends['default']) && !$backends['default']) {
127
-			// clear default backends
128
-			self::clearBackends();
129
-		}
130
-		foreach ($backends as $i => $config) {
131
-			if (!is_array($config)) {
132
-				continue;
133
-			}
134
-			$class = $config['class'];
135
-			$arguments = $config['arguments'];
136
-			if (class_exists($class)) {
137
-				if (array_search($i, self::$_setupedBackends) === false) {
138
-					// make a reflection object
139
-					$reflectionObj = new ReflectionClass($class);
140
-
141
-					// use Reflection to create a new instance, using the $args
142
-					$backend = $reflectionObj->newInstanceArgs($arguments);
143
-					self::useBackend($backend);
144
-					self::$_setupedBackends[] = $i;
145
-				} else {
146
-					\OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
147
-				}
148
-			} else {
149
-				\OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
150
-			}
151
-		}
152
-	}
153
-
154
-	/**
155
-	 * Try to login a user, assuming authentication
156
-	 * has already happened (e.g. via Single Sign On).
157
-	 *
158
-	 * Log in a user and regenerate a new session.
159
-	 *
160
-	 * @param \OCP\Authentication\IApacheBackend $backend
161
-	 * @return bool
162
-	 */
163
-	public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
164
-
165
-		$uid = $backend->getCurrentUserId();
166
-		$run = true;
167
-		OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
168
-
169
-		if ($uid) {
170
-			if (self::getUser() !== $uid) {
171
-				self::setUserId($uid);
172
-				$userSession = \OC::$server->getUserSession();
173
-				$userSession->setLoginName($uid);
174
-				$request = OC::$server->getRequest();
175
-				$userSession->createSessionToken($request, $uid, $uid);
176
-				// setup the filesystem
177
-				OC_Util::setupFS($uid);
178
-				// first call the post_login hooks, the login-process needs to be
179
-				// completed before we can safely create the users folder.
180
-				// For example encryption needs to initialize the users keys first
181
-				// before we can create the user folder with the skeleton files
182
-				OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
183
-				//trigger creation of user home and /files folder
184
-				\OC::$server->getUserFolder($uid);
185
-			}
186
-			return true;
187
-		}
188
-		return false;
189
-	}
190
-
191
-	/**
192
-	 * Verify with Apache whether user is authenticated.
193
-	 *
194
-	 * @return boolean|null
195
-	 *          true: authenticated
196
-	 *          false: not authenticated
197
-	 *          null: not handled / no backend available
198
-	 */
199
-	public static function handleApacheAuth() {
200
-		$backend = self::findFirstActiveUsedBackend();
201
-		if ($backend) {
202
-			OC_App::loadApps();
203
-
204
-			//setup extra user backends
205
-			self::setupBackends();
206
-			\OC::$server->getUserSession()->unsetMagicInCookie();
207
-
208
-			return self::loginWithApache($backend);
209
-		}
210
-
211
-		return null;
212
-	}
213
-
214
-
215
-	/**
216
-	 * Sets user id for session and triggers emit
217
-	 *
218
-	 * @param string $uid
219
-	 */
220
-	public static function setUserId($uid) {
221
-		$userSession = \OC::$server->getUserSession();
222
-		$userManager = \OC::$server->getUserManager();
223
-		if ($user = $userManager->get($uid)) {
224
-			$userSession->setUser($user);
225
-		} else {
226
-			\OC::$server->getSession()->set('user_id', $uid);
227
-		}
228
-	}
229
-
230
-	/**
231
-	 * Check if the user is logged in, considers also the HTTP basic credentials
232
-	 *
233
-	 * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
234
-	 * @return bool
235
-	 */
236
-	public static function isLoggedIn() {
237
-		return \OC::$server->getUserSession()->isLoggedIn();
238
-	}
239
-
240
-	/**
241
-	 * set incognito mode, e.g. if a user wants to open a public link
242
-	 *
243
-	 * @param bool $status
244
-	 */
245
-	public static function setIncognitoMode($status) {
246
-		self::$incognitoMode = $status;
247
-	}
248
-
249
-	/**
250
-	 * get incognito mode status
251
-	 *
252
-	 * @return bool
253
-	 */
254
-	public static function isIncognitoMode() {
255
-		return self::$incognitoMode;
256
-	}
257
-
258
-	/**
259
-	 * Returns the current logout URL valid for the currently logged-in user
260
-	 *
261
-	 * @param \OCP\IURLGenerator $urlGenerator
262
-	 * @return string
263
-	 */
264
-	public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
265
-		$backend = self::findFirstActiveUsedBackend();
266
-		if ($backend) {
267
-			return $backend->getLogoutUrl();
268
-		}
269
-
270
-		$logoutUrl = $urlGenerator->linkToRouteAbsolute(
271
-			'core.login.logout',
272
-			[
273
-				'requesttoken' => \OCP\Util::callRegister(),
274
-			]
275
-		);
276
-
277
-		return $logoutUrl;
278
-	}
279
-
280
-	/**
281
-	 * Check if the user is an admin user
282
-	 *
283
-	 * @param string $uid uid of the admin
284
-	 * @return bool
285
-	 */
286
-	public static function isAdminUser($uid) {
287
-		$group = \OC::$server->getGroupManager()->get('admin');
288
-		$user = \OC::$server->getUserManager()->get($uid);
289
-		if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
290
-			return true;
291
-		}
292
-		return false;
293
-	}
294
-
295
-
296
-	/**
297
-	 * get the user id of the user currently logged in.
298
-	 *
299
-	 * @return string|bool uid or false
300
-	 */
301
-	public static function getUser() {
302
-		$uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
303
-		if (!is_null($uid) && self::$incognitoMode === false) {
304
-			return $uid;
305
-		} else {
306
-			return false;
307
-		}
308
-	}
309
-
310
-	/**
311
-	 * get the display name of the user currently logged in.
312
-	 *
313
-	 * @param string $uid
314
-	 * @return string|bool uid or false
315
-	 */
316
-	public static function getDisplayName($uid = null) {
317
-		if ($uid) {
318
-			$user = \OC::$server->getUserManager()->get($uid);
319
-			if ($user) {
320
-				return $user->getDisplayName();
321
-			} else {
322
-				return $uid;
323
-			}
324
-		} else {
325
-			$user = \OC::$server->getUserSession()->getUser();
326
-			if ($user) {
327
-				return $user->getDisplayName();
328
-			} else {
329
-				return false;
330
-			}
331
-		}
332
-	}
333
-
334
-	/**
335
-	 * Set password
336
-	 *
337
-	 * @param string $uid The username
338
-	 * @param string $password The new password
339
-	 * @param string $recoveryPassword for the encryption app to reset encryption keys
340
-	 * @return bool
341
-	 *
342
-	 * Change the password of a user
343
-	 */
344
-	public static function setPassword($uid, $password, $recoveryPassword = null) {
345
-		$user = \OC::$server->getUserManager()->get($uid);
346
-		if ($user) {
347
-			return $user->setPassword($password, $recoveryPassword);
348
-		} else {
349
-			return false;
350
-		}
351
-	}
352
-
353
-	/**
354
-	 * @param string $uid The username
355
-	 * @return string
356
-	 *
357
-	 * returns the path to the users home directory
358
-	 * @deprecated Use \OC::$server->getUserManager->getHome()
359
-	 */
360
-	public static function getHome($uid) {
361
-		$user = \OC::$server->getUserManager()->get($uid);
362
-		if ($user) {
363
-			return $user->getHome();
364
-		} else {
365
-			return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
366
-		}
367
-	}
368
-
369
-	/**
370
-	 * Get a list of all users
371
-	 *
372
-	 * @return array an array of all uids
373
-	 *
374
-	 * Get a list of all users.
375
-	 * @param string $search
376
-	 * @param integer $limit
377
-	 * @param integer $offset
378
-	 */
379
-	public static function getUsers($search = '', $limit = null, $offset = null) {
380
-		$users = \OC::$server->getUserManager()->search($search, $limit, $offset);
381
-		$uids = array();
382
-		foreach ($users as $user) {
383
-			$uids[] = $user->getUID();
384
-		}
385
-		return $uids;
386
-	}
387
-
388
-	/**
389
-	 * Get a list of all users display name
390
-	 *
391
-	 * @param string $search
392
-	 * @param int $limit
393
-	 * @param int $offset
394
-	 * @return array associative array with all display names (value) and corresponding uids (key)
395
-	 *
396
-	 * Get a list of all display names and user ids.
397
-	 * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
398
-	 */
399
-	public static function getDisplayNames($search = '', $limit = null, $offset = null) {
400
-		$displayNames = array();
401
-		$users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
402
-		foreach ($users as $user) {
403
-			$displayNames[$user->getUID()] = $user->getDisplayName();
404
-		}
405
-		return $displayNames;
406
-	}
407
-
408
-	/**
409
-	 * Returns the first active backend from self::$_usedBackends.
410
-	 *
411
-	 * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
412
-	 */
413
-	private static function findFirstActiveUsedBackend() {
414
-		foreach (self::$_usedBackends as $backend) {
415
-			if ($backend instanceof OCP\Authentication\IApacheBackend) {
416
-				if ($backend->isSessionActive()) {
417
-					return $backend;
418
-				}
419
-			}
420
-		}
421
-
422
-		return null;
423
-	}
61
+    private static $_usedBackends = array();
62
+
63
+    private static $_setupedBackends = array();
64
+
65
+    // bool, stores if a user want to access a resource anonymously, e.g if they open a public link
66
+    private static $incognitoMode = false;
67
+
68
+    /**
69
+     * Adds the backend to the list of used backends
70
+     *
71
+     * @param string|\OCP\UserInterface $backend default: database The backend to use for user management
72
+     * @return bool
73
+     *
74
+     * Set the User Authentication Module
75
+     * @suppress PhanDeprecatedFunction
76
+     */
77
+    public static function useBackend($backend = 'database') {
78
+        if ($backend instanceof \OCP\UserInterface) {
79
+            self::$_usedBackends[get_class($backend)] = $backend;
80
+            \OC::$server->getUserManager()->registerBackend($backend);
81
+        } else {
82
+            // You'll never know what happens
83
+            if (null === $backend OR !is_string($backend)) {
84
+                $backend = 'database';
85
+            }
86
+
87
+            // Load backend
88
+            switch ($backend) {
89
+                case 'database':
90
+                case 'mysql':
91
+                case 'sqlite':
92
+                    \OCP\Util::writeLog('core', 'Adding user backend ' . $backend . '.', \OCP\Util::DEBUG);
93
+                    self::$_usedBackends[$backend] = new \OC\User\Database();
94
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
95
+                    break;
96
+                case 'dummy':
97
+                    self::$_usedBackends[$backend] = new \Test\Util\User\Dummy();
98
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
99
+                    break;
100
+                default:
101
+                    \OCP\Util::writeLog('core', 'Adding default user backend ' . $backend . '.', \OCP\Util::DEBUG);
102
+                    $className = 'OC_USER_' . strtoupper($backend);
103
+                    self::$_usedBackends[$backend] = new $className();
104
+                    \OC::$server->getUserManager()->registerBackend(self::$_usedBackends[$backend]);
105
+                    break;
106
+            }
107
+        }
108
+        return true;
109
+    }
110
+
111
+    /**
112
+     * remove all used backends
113
+     */
114
+    public static function clearBackends() {
115
+        self::$_usedBackends = array();
116
+        \OC::$server->getUserManager()->clearBackends();
117
+    }
118
+
119
+    /**
120
+     * setup the configured backends in config.php
121
+     * @suppress PhanDeprecatedFunction
122
+     */
123
+    public static function setupBackends() {
124
+        OC_App::loadApps(['prelogin']);
125
+        $backends = \OC::$server->getSystemConfig()->getValue('user_backends', []);
126
+        if (isset($backends['default']) && !$backends['default']) {
127
+            // clear default backends
128
+            self::clearBackends();
129
+        }
130
+        foreach ($backends as $i => $config) {
131
+            if (!is_array($config)) {
132
+                continue;
133
+            }
134
+            $class = $config['class'];
135
+            $arguments = $config['arguments'];
136
+            if (class_exists($class)) {
137
+                if (array_search($i, self::$_setupedBackends) === false) {
138
+                    // make a reflection object
139
+                    $reflectionObj = new ReflectionClass($class);
140
+
141
+                    // use Reflection to create a new instance, using the $args
142
+                    $backend = $reflectionObj->newInstanceArgs($arguments);
143
+                    self::useBackend($backend);
144
+                    self::$_setupedBackends[] = $i;
145
+                } else {
146
+                    \OCP\Util::writeLog('core', 'User backend ' . $class . ' already initialized.', \OCP\Util::DEBUG);
147
+                }
148
+            } else {
149
+                \OCP\Util::writeLog('core', 'User backend ' . $class . ' not found.', \OCP\Util::ERROR);
150
+            }
151
+        }
152
+    }
153
+
154
+    /**
155
+     * Try to login a user, assuming authentication
156
+     * has already happened (e.g. via Single Sign On).
157
+     *
158
+     * Log in a user and regenerate a new session.
159
+     *
160
+     * @param \OCP\Authentication\IApacheBackend $backend
161
+     * @return bool
162
+     */
163
+    public static function loginWithApache(\OCP\Authentication\IApacheBackend $backend) {
164
+
165
+        $uid = $backend->getCurrentUserId();
166
+        $run = true;
167
+        OC_Hook::emit("OC_User", "pre_login", array("run" => &$run, "uid" => $uid));
168
+
169
+        if ($uid) {
170
+            if (self::getUser() !== $uid) {
171
+                self::setUserId($uid);
172
+                $userSession = \OC::$server->getUserSession();
173
+                $userSession->setLoginName($uid);
174
+                $request = OC::$server->getRequest();
175
+                $userSession->createSessionToken($request, $uid, $uid);
176
+                // setup the filesystem
177
+                OC_Util::setupFS($uid);
178
+                // first call the post_login hooks, the login-process needs to be
179
+                // completed before we can safely create the users folder.
180
+                // For example encryption needs to initialize the users keys first
181
+                // before we can create the user folder with the skeleton files
182
+                OC_Hook::emit("OC_User", "post_login", array("uid" => $uid, 'password' => ''));
183
+                //trigger creation of user home and /files folder
184
+                \OC::$server->getUserFolder($uid);
185
+            }
186
+            return true;
187
+        }
188
+        return false;
189
+    }
190
+
191
+    /**
192
+     * Verify with Apache whether user is authenticated.
193
+     *
194
+     * @return boolean|null
195
+     *          true: authenticated
196
+     *          false: not authenticated
197
+     *          null: not handled / no backend available
198
+     */
199
+    public static function handleApacheAuth() {
200
+        $backend = self::findFirstActiveUsedBackend();
201
+        if ($backend) {
202
+            OC_App::loadApps();
203
+
204
+            //setup extra user backends
205
+            self::setupBackends();
206
+            \OC::$server->getUserSession()->unsetMagicInCookie();
207
+
208
+            return self::loginWithApache($backend);
209
+        }
210
+
211
+        return null;
212
+    }
213
+
214
+
215
+    /**
216
+     * Sets user id for session and triggers emit
217
+     *
218
+     * @param string $uid
219
+     */
220
+    public static function setUserId($uid) {
221
+        $userSession = \OC::$server->getUserSession();
222
+        $userManager = \OC::$server->getUserManager();
223
+        if ($user = $userManager->get($uid)) {
224
+            $userSession->setUser($user);
225
+        } else {
226
+            \OC::$server->getSession()->set('user_id', $uid);
227
+        }
228
+    }
229
+
230
+    /**
231
+     * Check if the user is logged in, considers also the HTTP basic credentials
232
+     *
233
+     * @deprecated use \OC::$server->getUserSession()->isLoggedIn()
234
+     * @return bool
235
+     */
236
+    public static function isLoggedIn() {
237
+        return \OC::$server->getUserSession()->isLoggedIn();
238
+    }
239
+
240
+    /**
241
+     * set incognito mode, e.g. if a user wants to open a public link
242
+     *
243
+     * @param bool $status
244
+     */
245
+    public static function setIncognitoMode($status) {
246
+        self::$incognitoMode = $status;
247
+    }
248
+
249
+    /**
250
+     * get incognito mode status
251
+     *
252
+     * @return bool
253
+     */
254
+    public static function isIncognitoMode() {
255
+        return self::$incognitoMode;
256
+    }
257
+
258
+    /**
259
+     * Returns the current logout URL valid for the currently logged-in user
260
+     *
261
+     * @param \OCP\IURLGenerator $urlGenerator
262
+     * @return string
263
+     */
264
+    public static function getLogoutUrl(\OCP\IURLGenerator $urlGenerator) {
265
+        $backend = self::findFirstActiveUsedBackend();
266
+        if ($backend) {
267
+            return $backend->getLogoutUrl();
268
+        }
269
+
270
+        $logoutUrl = $urlGenerator->linkToRouteAbsolute(
271
+            'core.login.logout',
272
+            [
273
+                'requesttoken' => \OCP\Util::callRegister(),
274
+            ]
275
+        );
276
+
277
+        return $logoutUrl;
278
+    }
279
+
280
+    /**
281
+     * Check if the user is an admin user
282
+     *
283
+     * @param string $uid uid of the admin
284
+     * @return bool
285
+     */
286
+    public static function isAdminUser($uid) {
287
+        $group = \OC::$server->getGroupManager()->get('admin');
288
+        $user = \OC::$server->getUserManager()->get($uid);
289
+        if ($group && $user && $group->inGroup($user) && self::$incognitoMode === false) {
290
+            return true;
291
+        }
292
+        return false;
293
+    }
294
+
295
+
296
+    /**
297
+     * get the user id of the user currently logged in.
298
+     *
299
+     * @return string|bool uid or false
300
+     */
301
+    public static function getUser() {
302
+        $uid = \OC::$server->getSession() ? \OC::$server->getSession()->get('user_id') : null;
303
+        if (!is_null($uid) && self::$incognitoMode === false) {
304
+            return $uid;
305
+        } else {
306
+            return false;
307
+        }
308
+    }
309
+
310
+    /**
311
+     * get the display name of the user currently logged in.
312
+     *
313
+     * @param string $uid
314
+     * @return string|bool uid or false
315
+     */
316
+    public static function getDisplayName($uid = null) {
317
+        if ($uid) {
318
+            $user = \OC::$server->getUserManager()->get($uid);
319
+            if ($user) {
320
+                return $user->getDisplayName();
321
+            } else {
322
+                return $uid;
323
+            }
324
+        } else {
325
+            $user = \OC::$server->getUserSession()->getUser();
326
+            if ($user) {
327
+                return $user->getDisplayName();
328
+            } else {
329
+                return false;
330
+            }
331
+        }
332
+    }
333
+
334
+    /**
335
+     * Set password
336
+     *
337
+     * @param string $uid The username
338
+     * @param string $password The new password
339
+     * @param string $recoveryPassword for the encryption app to reset encryption keys
340
+     * @return bool
341
+     *
342
+     * Change the password of a user
343
+     */
344
+    public static function setPassword($uid, $password, $recoveryPassword = null) {
345
+        $user = \OC::$server->getUserManager()->get($uid);
346
+        if ($user) {
347
+            return $user->setPassword($password, $recoveryPassword);
348
+        } else {
349
+            return false;
350
+        }
351
+    }
352
+
353
+    /**
354
+     * @param string $uid The username
355
+     * @return string
356
+     *
357
+     * returns the path to the users home directory
358
+     * @deprecated Use \OC::$server->getUserManager->getHome()
359
+     */
360
+    public static function getHome($uid) {
361
+        $user = \OC::$server->getUserManager()->get($uid);
362
+        if ($user) {
363
+            return $user->getHome();
364
+        } else {
365
+            return \OC::$server->getSystemConfig()->getValue('datadirectory', OC::$SERVERROOT . '/data') . '/' . $uid;
366
+        }
367
+    }
368
+
369
+    /**
370
+     * Get a list of all users
371
+     *
372
+     * @return array an array of all uids
373
+     *
374
+     * Get a list of all users.
375
+     * @param string $search
376
+     * @param integer $limit
377
+     * @param integer $offset
378
+     */
379
+    public static function getUsers($search = '', $limit = null, $offset = null) {
380
+        $users = \OC::$server->getUserManager()->search($search, $limit, $offset);
381
+        $uids = array();
382
+        foreach ($users as $user) {
383
+            $uids[] = $user->getUID();
384
+        }
385
+        return $uids;
386
+    }
387
+
388
+    /**
389
+     * Get a list of all users display name
390
+     *
391
+     * @param string $search
392
+     * @param int $limit
393
+     * @param int $offset
394
+     * @return array associative array with all display names (value) and corresponding uids (key)
395
+     *
396
+     * Get a list of all display names and user ids.
397
+     * @deprecated Use \OC::$server->getUserManager->searchDisplayName($search, $limit, $offset) instead.
398
+     */
399
+    public static function getDisplayNames($search = '', $limit = null, $offset = null) {
400
+        $displayNames = array();
401
+        $users = \OC::$server->getUserManager()->searchDisplayName($search, $limit, $offset);
402
+        foreach ($users as $user) {
403
+            $displayNames[$user->getUID()] = $user->getDisplayName();
404
+        }
405
+        return $displayNames;
406
+    }
407
+
408
+    /**
409
+     * Returns the first active backend from self::$_usedBackends.
410
+     *
411
+     * @return OCP\Authentication\IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend
412
+     */
413
+    private static function findFirstActiveUsedBackend() {
414
+        foreach (self::$_usedBackends as $backend) {
415
+            if ($backend instanceof OCP\Authentication\IApacheBackend) {
416
+                if ($backend->isSessionActive()) {
417
+                    return $backend;
418
+                }
419
+            }
420
+        }
421
+
422
+        return null;
423
+    }
424 424
 }
Please login to merge, or discard this patch.