Passed
Push — master ( 895e6a...a58b4c )
by Roeland
14:45 queued 11s
created
apps/files_external/lib/Service/UserGlobalStoragesService.php 1 patch
Indentation   +167 added lines, -167 removed lines patch added patch discarded remove patch
@@ -35,171 +35,171 @@
 block discarded – undo
35 35
  * Read-only access available, attempting to write will throw DomainException
36 36
  */
37 37
 class UserGlobalStoragesService extends GlobalStoragesService {
38
-	use UserTrait;
39
-
40
-	/** @var IGroupManager */
41
-	protected $groupManager;
42
-
43
-	/**
44
-	 * @param BackendService $backendService
45
-	 * @param DBConfigService $dbConfig
46
-	 * @param IUserSession $userSession
47
-	 * @param IGroupManager $groupManager
48
-	 * @param IUserMountCache $userMountCache
49
-	 */
50
-	public function __construct(
51
-		BackendService $backendService,
52
-		DBConfigService $dbConfig,
53
-		IUserSession $userSession,
54
-		IGroupManager $groupManager,
55
-		IUserMountCache $userMountCache
56
-	) {
57
-		parent::__construct($backendService, $dbConfig, $userMountCache);
58
-		$this->userSession = $userSession;
59
-		$this->groupManager = $groupManager;
60
-	}
61
-
62
-	/**
63
-	 * Replace config hash ID with real IDs, for migrating legacy storages
64
-	 *
65
-	 * @param StorageConfig[] $storages Storages with real IDs
66
-	 * @param StorageConfig[] $storagesWithConfigHash Storages with config hash IDs
67
-	 */
68
-	protected function setRealStorageIds(array &$storages, array $storagesWithConfigHash) {
69
-		// as a read-only view, storage IDs don't need to be real
70
-		foreach ($storagesWithConfigHash as $storage) {
71
-			$storages[$storage->getId()] = $storage;
72
-		}
73
-	}
74
-
75
-	protected function readDBConfig() {
76
-		$userMounts = $this->dbConfig->getAdminMountsFor(DBConfigService::APPLICABLE_TYPE_USER, $this->getUser()->getUID());
77
-		$globalMounts = $this->dbConfig->getAdminMountsFor(DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
78
-		$groups = $this->groupManager->getUserGroupIds($this->getUser());
79
-		if (count($groups) !== 0) {
80
-			$groupMounts = $this->dbConfig->getAdminMountsForMultiple(DBConfigService::APPLICABLE_TYPE_GROUP, $groups);
81
-		} else {
82
-			$groupMounts = [];
83
-		}
84
-		return array_merge($userMounts, $groupMounts, $globalMounts);
85
-	}
86
-
87
-	public function addStorage(StorageConfig $newStorage) {
88
-		throw new \DomainException('UserGlobalStoragesService writing disallowed');
89
-	}
90
-
91
-	public function updateStorage(StorageConfig $updatedStorage) {
92
-		throw new \DomainException('UserGlobalStoragesService writing disallowed');
93
-	}
94
-
95
-	/**
96
-	 * @param integer $id
97
-	 */
98
-	public function removeStorage($id) {
99
-		throw new \DomainException('UserGlobalStoragesService writing disallowed');
100
-	}
101
-
102
-	/**
103
-	 * Get unique storages, in case two are defined with the same mountpoint
104
-	 * Higher priority storages take precedence
105
-	 *
106
-	 * @return StorageConfig[]
107
-	 */
108
-	public function getUniqueStorages() {
109
-		$storages = $this->getStorages();
110
-
111
-		$storagesByMountpoint = [];
112
-		foreach ($storages as $storage) {
113
-			$storagesByMountpoint[$storage->getMountPoint()][] = $storage;
114
-		}
115
-
116
-		$result = [];
117
-		foreach ($storagesByMountpoint as $storageList) {
118
-			$storage = array_reduce($storageList, function ($carry, $item) {
119
-				if (isset($carry)) {
120
-					$carryPriorityType = $this->getPriorityType($carry);
121
-					$itemPriorityType = $this->getPriorityType($item);
122
-					if ($carryPriorityType > $itemPriorityType) {
123
-						return $carry;
124
-					} elseif ($carryPriorityType === $itemPriorityType) {
125
-						if ($carry->getPriority() > $item->getPriority()) {
126
-							return $carry;
127
-						}
128
-					}
129
-				}
130
-				return $item;
131
-			});
132
-			$result[$storage->getID()] = $storage;
133
-		}
134
-
135
-		return $result;
136
-	}
137
-
138
-	/**
139
-	 * Get a priority 'type', where a bigger number means higher priority
140
-	 * user applicable > group applicable > 'all'
141
-	 *
142
-	 * @param StorageConfig $storage
143
-	 * @return int
144
-	 */
145
-	protected function getPriorityType(StorageConfig $storage) {
146
-		$applicableUsers = $storage->getApplicableUsers();
147
-		$applicableGroups = $storage->getApplicableGroups();
148
-
149
-		if ($applicableUsers && $applicableUsers[0] !== 'all') {
150
-			return 2;
151
-		}
152
-		if ($applicableGroups) {
153
-			return 1;
154
-		}
155
-		return 0;
156
-	}
157
-
158
-	protected function isApplicable(StorageConfig $config) {
159
-		$applicableUsers = $config->getApplicableUsers();
160
-		$applicableGroups = $config->getApplicableGroups();
161
-
162
-		if (count($applicableUsers) === 0 && count($applicableGroups) === 0) {
163
-			return true;
164
-		}
165
-		if (in_array($this->getUser()->getUID(), $applicableUsers, true)) {
166
-			return true;
167
-		}
168
-		$groupIds = $this->groupManager->getUserGroupIds($this->getUser());
169
-		foreach ($groupIds as $groupId) {
170
-			if (in_array($groupId, $applicableGroups, true)) {
171
-				return true;
172
-			}
173
-		}
174
-		return false;
175
-	}
176
-
177
-
178
-	/**
179
-	 * Gets all storages for the user, admin, personal, global, etc
180
-	 *
181
-	 * @param IUser|null $user user to get the storages for, if not set the currently logged in user will be used
182
-	 * @return StorageConfig[] array of storage configs
183
-	 */
184
-	public function getAllStoragesForUser(IUser $user = null) {
185
-		if (is_null($user)) {
186
-			$user = $this->getUser();
187
-		}
188
-		if (is_null($user)) {
189
-			return [];
190
-		}
191
-		$groupIds = $this->groupManager->getUserGroupIds($user);
192
-		$mounts = $this->dbConfig->getMountsForUser($user->getUID(), $groupIds);
193
-		$configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
194
-		$configs = array_filter($configs, function ($config) {
195
-			return $config instanceof StorageConfig;
196
-		});
197
-
198
-		$keys = array_map(function (StorageConfig $config) {
199
-			return $config->getId();
200
-		}, $configs);
201
-
202
-		$storages = array_combine($keys, $configs);
203
-		return array_filter($storages, [$this, 'validateStorage']);
204
-	}
38
+    use UserTrait;
39
+
40
+    /** @var IGroupManager */
41
+    protected $groupManager;
42
+
43
+    /**
44
+     * @param BackendService $backendService
45
+     * @param DBConfigService $dbConfig
46
+     * @param IUserSession $userSession
47
+     * @param IGroupManager $groupManager
48
+     * @param IUserMountCache $userMountCache
49
+     */
50
+    public function __construct(
51
+        BackendService $backendService,
52
+        DBConfigService $dbConfig,
53
+        IUserSession $userSession,
54
+        IGroupManager $groupManager,
55
+        IUserMountCache $userMountCache
56
+    ) {
57
+        parent::__construct($backendService, $dbConfig, $userMountCache);
58
+        $this->userSession = $userSession;
59
+        $this->groupManager = $groupManager;
60
+    }
61
+
62
+    /**
63
+     * Replace config hash ID with real IDs, for migrating legacy storages
64
+     *
65
+     * @param StorageConfig[] $storages Storages with real IDs
66
+     * @param StorageConfig[] $storagesWithConfigHash Storages with config hash IDs
67
+     */
68
+    protected function setRealStorageIds(array &$storages, array $storagesWithConfigHash) {
69
+        // as a read-only view, storage IDs don't need to be real
70
+        foreach ($storagesWithConfigHash as $storage) {
71
+            $storages[$storage->getId()] = $storage;
72
+        }
73
+    }
74
+
75
+    protected function readDBConfig() {
76
+        $userMounts = $this->dbConfig->getAdminMountsFor(DBConfigService::APPLICABLE_TYPE_USER, $this->getUser()->getUID());
77
+        $globalMounts = $this->dbConfig->getAdminMountsFor(DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
78
+        $groups = $this->groupManager->getUserGroupIds($this->getUser());
79
+        if (count($groups) !== 0) {
80
+            $groupMounts = $this->dbConfig->getAdminMountsForMultiple(DBConfigService::APPLICABLE_TYPE_GROUP, $groups);
81
+        } else {
82
+            $groupMounts = [];
83
+        }
84
+        return array_merge($userMounts, $groupMounts, $globalMounts);
85
+    }
86
+
87
+    public function addStorage(StorageConfig $newStorage) {
88
+        throw new \DomainException('UserGlobalStoragesService writing disallowed');
89
+    }
90
+
91
+    public function updateStorage(StorageConfig $updatedStorage) {
92
+        throw new \DomainException('UserGlobalStoragesService writing disallowed');
93
+    }
94
+
95
+    /**
96
+     * @param integer $id
97
+     */
98
+    public function removeStorage($id) {
99
+        throw new \DomainException('UserGlobalStoragesService writing disallowed');
100
+    }
101
+
102
+    /**
103
+     * Get unique storages, in case two are defined with the same mountpoint
104
+     * Higher priority storages take precedence
105
+     *
106
+     * @return StorageConfig[]
107
+     */
108
+    public function getUniqueStorages() {
109
+        $storages = $this->getStorages();
110
+
111
+        $storagesByMountpoint = [];
112
+        foreach ($storages as $storage) {
113
+            $storagesByMountpoint[$storage->getMountPoint()][] = $storage;
114
+        }
115
+
116
+        $result = [];
117
+        foreach ($storagesByMountpoint as $storageList) {
118
+            $storage = array_reduce($storageList, function ($carry, $item) {
119
+                if (isset($carry)) {
120
+                    $carryPriorityType = $this->getPriorityType($carry);
121
+                    $itemPriorityType = $this->getPriorityType($item);
122
+                    if ($carryPriorityType > $itemPriorityType) {
123
+                        return $carry;
124
+                    } elseif ($carryPriorityType === $itemPriorityType) {
125
+                        if ($carry->getPriority() > $item->getPriority()) {
126
+                            return $carry;
127
+                        }
128
+                    }
129
+                }
130
+                return $item;
131
+            });
132
+            $result[$storage->getID()] = $storage;
133
+        }
134
+
135
+        return $result;
136
+    }
137
+
138
+    /**
139
+     * Get a priority 'type', where a bigger number means higher priority
140
+     * user applicable > group applicable > 'all'
141
+     *
142
+     * @param StorageConfig $storage
143
+     * @return int
144
+     */
145
+    protected function getPriorityType(StorageConfig $storage) {
146
+        $applicableUsers = $storage->getApplicableUsers();
147
+        $applicableGroups = $storage->getApplicableGroups();
148
+
149
+        if ($applicableUsers && $applicableUsers[0] !== 'all') {
150
+            return 2;
151
+        }
152
+        if ($applicableGroups) {
153
+            return 1;
154
+        }
155
+        return 0;
156
+    }
157
+
158
+    protected function isApplicable(StorageConfig $config) {
159
+        $applicableUsers = $config->getApplicableUsers();
160
+        $applicableGroups = $config->getApplicableGroups();
161
+
162
+        if (count($applicableUsers) === 0 && count($applicableGroups) === 0) {
163
+            return true;
164
+        }
165
+        if (in_array($this->getUser()->getUID(), $applicableUsers, true)) {
166
+            return true;
167
+        }
168
+        $groupIds = $this->groupManager->getUserGroupIds($this->getUser());
169
+        foreach ($groupIds as $groupId) {
170
+            if (in_array($groupId, $applicableGroups, true)) {
171
+                return true;
172
+            }
173
+        }
174
+        return false;
175
+    }
176
+
177
+
178
+    /**
179
+     * Gets all storages for the user, admin, personal, global, etc
180
+     *
181
+     * @param IUser|null $user user to get the storages for, if not set the currently logged in user will be used
182
+     * @return StorageConfig[] array of storage configs
183
+     */
184
+    public function getAllStoragesForUser(IUser $user = null) {
185
+        if (is_null($user)) {
186
+            $user = $this->getUser();
187
+        }
188
+        if (is_null($user)) {
189
+            return [];
190
+        }
191
+        $groupIds = $this->groupManager->getUserGroupIds($user);
192
+        $mounts = $this->dbConfig->getMountsForUser($user->getUID(), $groupIds);
193
+        $configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
194
+        $configs = array_filter($configs, function ($config) {
195
+            return $config instanceof StorageConfig;
196
+        });
197
+
198
+        $keys = array_map(function (StorageConfig $config) {
199
+            return $config->getId();
200
+        }, $configs);
201
+
202
+        $storages = array_combine($keys, $configs);
203
+        return array_filter($storages, [$this, 'validateStorage']);
204
+    }
205 205
 }
Please login to merge, or discard this patch.
lib/public/IGroupManager.php 1 patch
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -46,103 +46,103 @@
 block discarded – undo
46 46
  * @since 8.0.0
47 47
  */
48 48
 interface IGroupManager {
49
-	/**
50
-	 * Checks whether a given backend is used
51
-	 *
52
-	 * @param string $backendClass Full classname including complete namespace
53
-	 * @return bool
54
-	 * @since 8.1.0
55
-	 */
56
-	public function isBackendUsed($backendClass);
49
+    /**
50
+     * Checks whether a given backend is used
51
+     *
52
+     * @param string $backendClass Full classname including complete namespace
53
+     * @return bool
54
+     * @since 8.1.0
55
+     */
56
+    public function isBackendUsed($backendClass);
57 57
 
58
-	/**
59
-	 * @param \OCP\GroupInterface $backend
60
-	 * @since 8.0.0
61
-	 */
62
-	public function addBackend($backend);
58
+    /**
59
+     * @param \OCP\GroupInterface $backend
60
+     * @since 8.0.0
61
+     */
62
+    public function addBackend($backend);
63 63
 
64
-	/**
65
-	 * @since 8.0.0
66
-	 */
67
-	public function clearBackends();
64
+    /**
65
+     * @since 8.0.0
66
+     */
67
+    public function clearBackends();
68 68
 
69
-	/**
70
-	 * Get the active backends
71
-	 * @return \OCP\GroupInterface[]
72
-	 * @since 13.0.0
73
-	 */
74
-	public function getBackends();
69
+    /**
70
+     * Get the active backends
71
+     * @return \OCP\GroupInterface[]
72
+     * @since 13.0.0
73
+     */
74
+    public function getBackends();
75 75
 
76
-	/**
77
-	 * @param string $gid
78
-	 * @return \OCP\IGroup|null
79
-	 * @since 8.0.0
80
-	 */
81
-	public function get($gid);
76
+    /**
77
+     * @param string $gid
78
+     * @return \OCP\IGroup|null
79
+     * @since 8.0.0
80
+     */
81
+    public function get($gid);
82 82
 
83
-	/**
84
-	 * @param string $gid
85
-	 * @return bool
86
-	 * @since 8.0.0
87
-	 */
88
-	public function groupExists($gid);
83
+    /**
84
+     * @param string $gid
85
+     * @return bool
86
+     * @since 8.0.0
87
+     */
88
+    public function groupExists($gid);
89 89
 
90
-	/**
91
-	 * @param string $gid
92
-	 * @return \OCP\IGroup|null
93
-	 * @since 8.0.0
94
-	 */
95
-	public function createGroup($gid);
90
+    /**
91
+     * @param string $gid
92
+     * @return \OCP\IGroup|null
93
+     * @since 8.0.0
94
+     */
95
+    public function createGroup($gid);
96 96
 
97
-	/**
98
-	 * @param string $search
99
-	 * @param int $limit
100
-	 * @param int $offset
101
-	 * @return \OCP\IGroup[]
102
-	 * @since 8.0.0
103
-	 */
104
-	public function search($search, $limit = null, $offset = null);
97
+    /**
98
+     * @param string $search
99
+     * @param int $limit
100
+     * @param int $offset
101
+     * @return \OCP\IGroup[]
102
+     * @since 8.0.0
103
+     */
104
+    public function search($search, $limit = null, $offset = null);
105 105
 
106
-	/**
107
-	 * @param \OCP\IUser|null $user
108
-	 * @return \OCP\IGroup[]
109
-	 * @since 8.0.0
110
-	 */
111
-	public function getUserGroups(IUser $user = null);
106
+    /**
107
+     * @param \OCP\IUser|null $user
108
+     * @return \OCP\IGroup[]
109
+     * @since 8.0.0
110
+     */
111
+    public function getUserGroups(IUser $user = null);
112 112
 
113
-	/**
114
-	 * @param \OCP\IUser $user
115
-	 * @return string[] with group names
116
-	 * @since 8.0.0
117
-	 */
118
-	public function getUserGroupIds(IUser $user): array;
113
+    /**
114
+     * @param \OCP\IUser $user
115
+     * @return string[] with group names
116
+     * @since 8.0.0
117
+     */
118
+    public function getUserGroupIds(IUser $user): array;
119 119
 
120
-	/**
121
-	 * get a list of all display names in a group
122
-	 *
123
-	 * @param string $gid
124
-	 * @param string $search
125
-	 * @param int $limit
126
-	 * @param int $offset
127
-	 * @return array an array of display names (value) and user ids (key)
128
-	 * @since 8.0.0
129
-	 */
130
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0);
120
+    /**
121
+     * get a list of all display names in a group
122
+     *
123
+     * @param string $gid
124
+     * @param string $search
125
+     * @param int $limit
126
+     * @param int $offset
127
+     * @return array an array of display names (value) and user ids (key)
128
+     * @since 8.0.0
129
+     */
130
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0);
131 131
 
132
-	/**
133
-	 * Checks if a userId is in the admin group
134
-	 * @param string $userId
135
-	 * @return bool if admin
136
-	 * @since 8.0.0
137
-	 */
138
-	public function isAdmin($userId);
132
+    /**
133
+     * Checks if a userId is in the admin group
134
+     * @param string $userId
135
+     * @return bool if admin
136
+     * @since 8.0.0
137
+     */
138
+    public function isAdmin($userId);
139 139
 
140
-	/**
141
-	 * Checks if a userId is in a group
142
-	 * @param string $userId
143
-	 * @param string $group
144
-	 * @return bool if in group
145
-	 * @since 8.0.0
146
-	 */
147
-	public function isInGroup($userId, $group);
140
+    /**
141
+     * Checks if a userId is in a group
142
+     * @param string $userId
143
+     * @param string $group
144
+     * @return bool if in group
145
+     * @since 8.0.0
146
+     */
147
+    public function isInGroup($userId, $group);
148 148
 }
Please login to merge, or discard this patch.
lib/private/Template/JSConfigHelper.php 2 patches
Indentation   +273 added lines, -273 removed lines patch added patch discarded remove patch
@@ -47,277 +47,277 @@
 block discarded – undo
47 47
 
48 48
 class JSConfigHelper {
49 49
 
50
-	/** @var IL10N */
51
-	private $l;
52
-
53
-	/** @var Defaults */
54
-	private $defaults;
55
-
56
-	/** @var IAppManager */
57
-	private $appManager;
58
-
59
-	/** @var ISession */
60
-	private $session;
61
-
62
-	/** @var IUser|null */
63
-	private $currentUser;
64
-
65
-	/** @var IConfig */
66
-	private $config;
67
-
68
-	/** @var IGroupManager */
69
-	private $groupManager;
70
-
71
-	/** @var IniGetWrapper */
72
-	private $iniWrapper;
73
-
74
-	/** @var IURLGenerator */
75
-	private $urlGenerator;
76
-
77
-	/** @var CapabilitiesManager */
78
-	private $capabilitiesManager;
79
-
80
-	/** @var IInitialStateService */
81
-	private $initialStateService;
82
-
83
-	/** @var array user back-ends excluded from password verification */
84
-	private $excludedUserBackEnds = ['user_saml' => true, 'user_globalsiteselector' => true];
85
-
86
-	/**
87
-	 * @param IL10N $l
88
-	 * @param Defaults $defaults
89
-	 * @param IAppManager $appManager
90
-	 * @param ISession $session
91
-	 * @param IUser|null $currentUser
92
-	 * @param IConfig $config
93
-	 * @param IGroupManager $groupManager
94
-	 * @param IniGetWrapper $iniWrapper
95
-	 * @param IURLGenerator $urlGenerator
96
-	 * @param CapabilitiesManager $capabilitiesManager
97
-	 */
98
-	public function __construct(IL10N $l,
99
-								Defaults $defaults,
100
-								IAppManager $appManager,
101
-								ISession $session,
102
-								$currentUser,
103
-								IConfig $config,
104
-								IGroupManager $groupManager,
105
-								IniGetWrapper $iniWrapper,
106
-								IURLGenerator $urlGenerator,
107
-								CapabilitiesManager $capabilitiesManager,
108
-								IInitialStateService $initialStateService) {
109
-		$this->l = $l;
110
-		$this->defaults = $defaults;
111
-		$this->appManager = $appManager;
112
-		$this->session = $session;
113
-		$this->currentUser = $currentUser;
114
-		$this->config = $config;
115
-		$this->groupManager = $groupManager;
116
-		$this->iniWrapper = $iniWrapper;
117
-		$this->urlGenerator = $urlGenerator;
118
-		$this->capabilitiesManager = $capabilitiesManager;
119
-		$this->initialStateService = $initialStateService;
120
-	}
121
-
122
-	public function getConfig() {
123
-		$userBackendAllowsPasswordConfirmation = true;
124
-		if ($this->currentUser !== null) {
125
-			$uid = $this->currentUser->getUID();
126
-
127
-			$backend = $this->currentUser->getBackend();
128
-			if ($backend instanceof IPasswordConfirmationBackend) {
129
-				$userBackendAllowsPasswordConfirmation = $backend->canConfirmPassword($uid);
130
-			} elseif (isset($this->excludedUserBackEnds[$this->currentUser->getBackendClassName()])) {
131
-				$userBackendAllowsPasswordConfirmation = false;
132
-			}
133
-		} else {
134
-			$uid = null;
135
-		}
136
-
137
-		// Get the config
138
-		$apps_paths = [];
139
-
140
-		if ($this->currentUser === null) {
141
-			$apps = $this->appManager->getInstalledApps();
142
-		} else {
143
-			$apps = $this->appManager->getEnabledAppsForUser($this->currentUser);
144
-		}
145
-
146
-		foreach ($apps as $app) {
147
-			$apps_paths[$app] = \OC_App::getAppWebPath($app);
148
-		}
149
-
150
-
151
-		$enableLinkPasswordByDefault = $this->config->getAppValue('core', 'shareapi_enable_link_password_by_default', 'no');
152
-		$enableLinkPasswordByDefault = $enableLinkPasswordByDefault === 'yes';
153
-		$defaultExpireDateEnabled = $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
154
-		$defaultExpireDate = $enforceDefaultExpireDate = null;
155
-		if ($defaultExpireDateEnabled) {
156
-			$defaultExpireDate = (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
157
-			$enforceDefaultExpireDate = $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
158
-		}
159
-		$outgoingServer2serverShareEnabled = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
160
-
161
-		$defaultInternalExpireDateEnabled = $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
162
-		$defaultInternalExpireDate = $defaultInternalExpireDateEnforced = null;
163
-		if ($defaultInternalExpireDateEnabled) {
164
-			$defaultInternalExpireDate = (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
165
-			$defaultInternalExpireDateEnforced = $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
166
-		}
167
-
168
-		$countOfDataLocation = 0;
169
-		$dataLocation = str_replace(\OC::$SERVERROOT . '/', '', $this->config->getSystemValue('datadirectory', ''), $countOfDataLocation);
170
-		if ($countOfDataLocation !== 1 || $uid === null || !$this->groupManager->isAdmin($uid)) {
171
-			$dataLocation = false;
172
-		}
173
-
174
-		if ($this->currentUser instanceof IUser) {
175
-			$lastConfirmTimestamp = $this->session->get('last-password-confirm');
176
-			if (!is_int($lastConfirmTimestamp)) {
177
-				$lastConfirmTimestamp = 0;
178
-			}
179
-		} else {
180
-			$lastConfirmTimestamp = 0;
181
-		}
182
-
183
-		$capabilities = $this->capabilitiesManager->getCapabilities();
184
-
185
-		$config = [
186
-			'session_lifetime' => min($this->config->getSystemValue('session_lifetime', $this->iniWrapper->getNumeric('session.gc_maxlifetime')), $this->iniWrapper->getNumeric('session.gc_maxlifetime')),
187
-			'session_keepalive' => $this->config->getSystemValue('session_keepalive', true),
188
-			'auto_logout' => $this->config->getSystemValue('auto_logout', false),
189
-			'version' => implode('.', \OCP\Util::getVersion()),
190
-			'versionstring' => \OC_Util::getVersionString(),
191
-			'enable_avatars' => true, // here for legacy reasons - to not crash existing code that relies on this value
192
-			'lost_password_link' => $this->config->getSystemValue('lost_password_link', null),
193
-			'modRewriteWorking' => $this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true',
194
-			'sharing.maxAutocompleteResults' => max(0, $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT)),
195
-			'sharing.minSearchStringLength' => $this->config->getSystemValueInt('sharing.minSearchStringLength', 0),
196
-			'blacklist_files_regex' => \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX,
197
-		];
198
-
199
-		$array = [
200
-			"_oc_debug" => $this->config->getSystemValue('debug', false) ? 'true' : 'false',
201
-			"_oc_isadmin" => $uid !== null && $this->groupManager->isAdmin($uid) ? 'true' : 'false',
202
-			"backendAllowsPasswordConfirmation" => $userBackendAllowsPasswordConfirmation ? 'true' : 'false',
203
-			"oc_dataURL" => is_string($dataLocation) ? "\"" . $dataLocation . "\"" : 'false',
204
-			"_oc_webroot" => "\"" . \OC::$WEBROOT . "\"",
205
-			"_oc_appswebroots" => str_replace('\\/', '/', json_encode($apps_paths)), // Ugly unescape slashes waiting for better solution
206
-			"datepickerFormatDate" => json_encode($this->l->l('jsdate', null)),
207
-			'nc_lastLogin' => $lastConfirmTimestamp,
208
-			'nc_pageLoad' => time(),
209
-			"dayNames" => json_encode([
210
-				$this->l->t('Sunday'),
211
-				$this->l->t('Monday'),
212
-				$this->l->t('Tuesday'),
213
-				$this->l->t('Wednesday'),
214
-				$this->l->t('Thursday'),
215
-				$this->l->t('Friday'),
216
-				$this->l->t('Saturday')
217
-			]),
218
-			"dayNamesShort" => json_encode([
219
-				$this->l->t('Sun.'),
220
-				$this->l->t('Mon.'),
221
-				$this->l->t('Tue.'),
222
-				$this->l->t('Wed.'),
223
-				$this->l->t('Thu.'),
224
-				$this->l->t('Fri.'),
225
-				$this->l->t('Sat.')
226
-			]),
227
-			"dayNamesMin" => json_encode([
228
-				$this->l->t('Su'),
229
-				$this->l->t('Mo'),
230
-				$this->l->t('Tu'),
231
-				$this->l->t('We'),
232
-				$this->l->t('Th'),
233
-				$this->l->t('Fr'),
234
-				$this->l->t('Sa')
235
-			]),
236
-			"monthNames" => json_encode([
237
-				$this->l->t('January'),
238
-				$this->l->t('February'),
239
-				$this->l->t('March'),
240
-				$this->l->t('April'),
241
-				$this->l->t('May'),
242
-				$this->l->t('June'),
243
-				$this->l->t('July'),
244
-				$this->l->t('August'),
245
-				$this->l->t('September'),
246
-				$this->l->t('October'),
247
-				$this->l->t('November'),
248
-				$this->l->t('December')
249
-			]),
250
-			"monthNamesShort" => json_encode([
251
-				$this->l->t('Jan.'),
252
-				$this->l->t('Feb.'),
253
-				$this->l->t('Mar.'),
254
-				$this->l->t('Apr.'),
255
-				$this->l->t('May.'),
256
-				$this->l->t('Jun.'),
257
-				$this->l->t('Jul.'),
258
-				$this->l->t('Aug.'),
259
-				$this->l->t('Sep.'),
260
-				$this->l->t('Oct.'),
261
-				$this->l->t('Nov.'),
262
-				$this->l->t('Dec.')
263
-			]),
264
-			"firstDay" => json_encode($this->l->l('firstday', null)),
265
-			"_oc_config" => json_encode($config),
266
-			"oc_appconfig" => json_encode([
267
-				'core' => [
268
-					'defaultExpireDateEnabled' => $defaultExpireDateEnabled,
269
-					'defaultExpireDate' => $defaultExpireDate,
270
-					'defaultExpireDateEnforced' => $enforceDefaultExpireDate,
271
-					'enforcePasswordForPublicLink' => \OCP\Util::isPublicLinkPasswordRequired(),
272
-					'enableLinkPasswordByDefault' => $enableLinkPasswordByDefault,
273
-					'sharingDisabledForUser' => \OCP\Util::isSharingDisabledForUser(),
274
-					'resharingAllowed' => \OC\Share\Share::isResharingAllowed(),
275
-					'remoteShareAllowed' => $outgoingServer2serverShareEnabled,
276
-					'federatedCloudShareDoc' => $this->urlGenerator->linkToDocs('user-sharing-federated'),
277
-					'allowGroupSharing' => \OC::$server->getShareManager()->allowGroupSharing(),
278
-					'defaultInternalExpireDateEnabled' => $defaultInternalExpireDateEnabled,
279
-					'defaultInternalExpireDate' => $defaultInternalExpireDate,
280
-					'defaultInternalExpireDateEnforced' => $defaultInternalExpireDateEnforced,
281
-				]
282
-			]),
283
-			"_theme" => json_encode([
284
-				'entity' => $this->defaults->getEntity(),
285
-				'name' => $this->defaults->getName(),
286
-				'title' => $this->defaults->getTitle(),
287
-				'baseUrl' => $this->defaults->getBaseUrl(),
288
-				'syncClientUrl' => $this->defaults->getSyncClientUrl(),
289
-				'docBaseUrl' => $this->defaults->getDocBaseUrl(),
290
-				'docPlaceholderUrl' => $this->defaults->buildDocLinkToKey('PLACEHOLDER'),
291
-				'slogan' => $this->defaults->getSlogan(),
292
-				'logoClaim' => '',
293
-				'shortFooter' => $this->defaults->getShortFooter(),
294
-				'longFooter' => $this->defaults->getLongFooter(),
295
-				'folder' => \OC_Util::getTheme(),
296
-			]),
297
-		];
298
-
299
-		if ($this->currentUser !== null) {
300
-			$array['oc_userconfig'] = json_encode([
301
-				'avatar' => [
302
-					'version' => (int)$this->config->getUserValue($uid, 'avatar', 'version', 0),
303
-					'generated' => $this->config->getUserValue($uid, 'avatar', 'generated', 'true') === 'true',
304
-				]
305
-			]);
306
-		}
307
-
308
-		$this->initialStateService->provideInitialState('core', 'config', $config);
309
-		$this->initialStateService->provideInitialState('core', 'capabilities', $capabilities);
310
-
311
-		// Allow hooks to modify the output values
312
-		\OC_Hook::emit('\OCP\Config', 'js', ['array' => &$array]);
313
-
314
-		$result = '';
315
-
316
-		// Echo it
317
-		foreach ($array as  $setting => $value) {
318
-			$result .= 'var '. $setting . '='. $value . ';' . PHP_EOL;
319
-		}
320
-
321
-		return $result;
322
-	}
50
+    /** @var IL10N */
51
+    private $l;
52
+
53
+    /** @var Defaults */
54
+    private $defaults;
55
+
56
+    /** @var IAppManager */
57
+    private $appManager;
58
+
59
+    /** @var ISession */
60
+    private $session;
61
+
62
+    /** @var IUser|null */
63
+    private $currentUser;
64
+
65
+    /** @var IConfig */
66
+    private $config;
67
+
68
+    /** @var IGroupManager */
69
+    private $groupManager;
70
+
71
+    /** @var IniGetWrapper */
72
+    private $iniWrapper;
73
+
74
+    /** @var IURLGenerator */
75
+    private $urlGenerator;
76
+
77
+    /** @var CapabilitiesManager */
78
+    private $capabilitiesManager;
79
+
80
+    /** @var IInitialStateService */
81
+    private $initialStateService;
82
+
83
+    /** @var array user back-ends excluded from password verification */
84
+    private $excludedUserBackEnds = ['user_saml' => true, 'user_globalsiteselector' => true];
85
+
86
+    /**
87
+     * @param IL10N $l
88
+     * @param Defaults $defaults
89
+     * @param IAppManager $appManager
90
+     * @param ISession $session
91
+     * @param IUser|null $currentUser
92
+     * @param IConfig $config
93
+     * @param IGroupManager $groupManager
94
+     * @param IniGetWrapper $iniWrapper
95
+     * @param IURLGenerator $urlGenerator
96
+     * @param CapabilitiesManager $capabilitiesManager
97
+     */
98
+    public function __construct(IL10N $l,
99
+                                Defaults $defaults,
100
+                                IAppManager $appManager,
101
+                                ISession $session,
102
+                                $currentUser,
103
+                                IConfig $config,
104
+                                IGroupManager $groupManager,
105
+                                IniGetWrapper $iniWrapper,
106
+                                IURLGenerator $urlGenerator,
107
+                                CapabilitiesManager $capabilitiesManager,
108
+                                IInitialStateService $initialStateService) {
109
+        $this->l = $l;
110
+        $this->defaults = $defaults;
111
+        $this->appManager = $appManager;
112
+        $this->session = $session;
113
+        $this->currentUser = $currentUser;
114
+        $this->config = $config;
115
+        $this->groupManager = $groupManager;
116
+        $this->iniWrapper = $iniWrapper;
117
+        $this->urlGenerator = $urlGenerator;
118
+        $this->capabilitiesManager = $capabilitiesManager;
119
+        $this->initialStateService = $initialStateService;
120
+    }
121
+
122
+    public function getConfig() {
123
+        $userBackendAllowsPasswordConfirmation = true;
124
+        if ($this->currentUser !== null) {
125
+            $uid = $this->currentUser->getUID();
126
+
127
+            $backend = $this->currentUser->getBackend();
128
+            if ($backend instanceof IPasswordConfirmationBackend) {
129
+                $userBackendAllowsPasswordConfirmation = $backend->canConfirmPassword($uid);
130
+            } elseif (isset($this->excludedUserBackEnds[$this->currentUser->getBackendClassName()])) {
131
+                $userBackendAllowsPasswordConfirmation = false;
132
+            }
133
+        } else {
134
+            $uid = null;
135
+        }
136
+
137
+        // Get the config
138
+        $apps_paths = [];
139
+
140
+        if ($this->currentUser === null) {
141
+            $apps = $this->appManager->getInstalledApps();
142
+        } else {
143
+            $apps = $this->appManager->getEnabledAppsForUser($this->currentUser);
144
+        }
145
+
146
+        foreach ($apps as $app) {
147
+            $apps_paths[$app] = \OC_App::getAppWebPath($app);
148
+        }
149
+
150
+
151
+        $enableLinkPasswordByDefault = $this->config->getAppValue('core', 'shareapi_enable_link_password_by_default', 'no');
152
+        $enableLinkPasswordByDefault = $enableLinkPasswordByDefault === 'yes';
153
+        $defaultExpireDateEnabled = $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
154
+        $defaultExpireDate = $enforceDefaultExpireDate = null;
155
+        if ($defaultExpireDateEnabled) {
156
+            $defaultExpireDate = (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
157
+            $enforceDefaultExpireDate = $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
158
+        }
159
+        $outgoingServer2serverShareEnabled = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
160
+
161
+        $defaultInternalExpireDateEnabled = $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
162
+        $defaultInternalExpireDate = $defaultInternalExpireDateEnforced = null;
163
+        if ($defaultInternalExpireDateEnabled) {
164
+            $defaultInternalExpireDate = (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
165
+            $defaultInternalExpireDateEnforced = $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
166
+        }
167
+
168
+        $countOfDataLocation = 0;
169
+        $dataLocation = str_replace(\OC::$SERVERROOT . '/', '', $this->config->getSystemValue('datadirectory', ''), $countOfDataLocation);
170
+        if ($countOfDataLocation !== 1 || $uid === null || !$this->groupManager->isAdmin($uid)) {
171
+            $dataLocation = false;
172
+        }
173
+
174
+        if ($this->currentUser instanceof IUser) {
175
+            $lastConfirmTimestamp = $this->session->get('last-password-confirm');
176
+            if (!is_int($lastConfirmTimestamp)) {
177
+                $lastConfirmTimestamp = 0;
178
+            }
179
+        } else {
180
+            $lastConfirmTimestamp = 0;
181
+        }
182
+
183
+        $capabilities = $this->capabilitiesManager->getCapabilities();
184
+
185
+        $config = [
186
+            'session_lifetime' => min($this->config->getSystemValue('session_lifetime', $this->iniWrapper->getNumeric('session.gc_maxlifetime')), $this->iniWrapper->getNumeric('session.gc_maxlifetime')),
187
+            'session_keepalive' => $this->config->getSystemValue('session_keepalive', true),
188
+            'auto_logout' => $this->config->getSystemValue('auto_logout', false),
189
+            'version' => implode('.', \OCP\Util::getVersion()),
190
+            'versionstring' => \OC_Util::getVersionString(),
191
+            'enable_avatars' => true, // here for legacy reasons - to not crash existing code that relies on this value
192
+            'lost_password_link' => $this->config->getSystemValue('lost_password_link', null),
193
+            'modRewriteWorking' => $this->config->getSystemValue('htaccess.IgnoreFrontController', false) === true || getenv('front_controller_active') === 'true',
194
+            'sharing.maxAutocompleteResults' => max(0, $this->config->getSystemValueInt('sharing.maxAutocompleteResults', Constants::SHARING_MAX_AUTOCOMPLETE_RESULTS_DEFAULT)),
195
+            'sharing.minSearchStringLength' => $this->config->getSystemValueInt('sharing.minSearchStringLength', 0),
196
+            'blacklist_files_regex' => \OCP\Files\FileInfo::BLACKLIST_FILES_REGEX,
197
+        ];
198
+
199
+        $array = [
200
+            "_oc_debug" => $this->config->getSystemValue('debug', false) ? 'true' : 'false',
201
+            "_oc_isadmin" => $uid !== null && $this->groupManager->isAdmin($uid) ? 'true' : 'false',
202
+            "backendAllowsPasswordConfirmation" => $userBackendAllowsPasswordConfirmation ? 'true' : 'false',
203
+            "oc_dataURL" => is_string($dataLocation) ? "\"" . $dataLocation . "\"" : 'false',
204
+            "_oc_webroot" => "\"" . \OC::$WEBROOT . "\"",
205
+            "_oc_appswebroots" => str_replace('\\/', '/', json_encode($apps_paths)), // Ugly unescape slashes waiting for better solution
206
+            "datepickerFormatDate" => json_encode($this->l->l('jsdate', null)),
207
+            'nc_lastLogin' => $lastConfirmTimestamp,
208
+            'nc_pageLoad' => time(),
209
+            "dayNames" => json_encode([
210
+                $this->l->t('Sunday'),
211
+                $this->l->t('Monday'),
212
+                $this->l->t('Tuesday'),
213
+                $this->l->t('Wednesday'),
214
+                $this->l->t('Thursday'),
215
+                $this->l->t('Friday'),
216
+                $this->l->t('Saturday')
217
+            ]),
218
+            "dayNamesShort" => json_encode([
219
+                $this->l->t('Sun.'),
220
+                $this->l->t('Mon.'),
221
+                $this->l->t('Tue.'),
222
+                $this->l->t('Wed.'),
223
+                $this->l->t('Thu.'),
224
+                $this->l->t('Fri.'),
225
+                $this->l->t('Sat.')
226
+            ]),
227
+            "dayNamesMin" => json_encode([
228
+                $this->l->t('Su'),
229
+                $this->l->t('Mo'),
230
+                $this->l->t('Tu'),
231
+                $this->l->t('We'),
232
+                $this->l->t('Th'),
233
+                $this->l->t('Fr'),
234
+                $this->l->t('Sa')
235
+            ]),
236
+            "monthNames" => json_encode([
237
+                $this->l->t('January'),
238
+                $this->l->t('February'),
239
+                $this->l->t('March'),
240
+                $this->l->t('April'),
241
+                $this->l->t('May'),
242
+                $this->l->t('June'),
243
+                $this->l->t('July'),
244
+                $this->l->t('August'),
245
+                $this->l->t('September'),
246
+                $this->l->t('October'),
247
+                $this->l->t('November'),
248
+                $this->l->t('December')
249
+            ]),
250
+            "monthNamesShort" => json_encode([
251
+                $this->l->t('Jan.'),
252
+                $this->l->t('Feb.'),
253
+                $this->l->t('Mar.'),
254
+                $this->l->t('Apr.'),
255
+                $this->l->t('May.'),
256
+                $this->l->t('Jun.'),
257
+                $this->l->t('Jul.'),
258
+                $this->l->t('Aug.'),
259
+                $this->l->t('Sep.'),
260
+                $this->l->t('Oct.'),
261
+                $this->l->t('Nov.'),
262
+                $this->l->t('Dec.')
263
+            ]),
264
+            "firstDay" => json_encode($this->l->l('firstday', null)),
265
+            "_oc_config" => json_encode($config),
266
+            "oc_appconfig" => json_encode([
267
+                'core' => [
268
+                    'defaultExpireDateEnabled' => $defaultExpireDateEnabled,
269
+                    'defaultExpireDate' => $defaultExpireDate,
270
+                    'defaultExpireDateEnforced' => $enforceDefaultExpireDate,
271
+                    'enforcePasswordForPublicLink' => \OCP\Util::isPublicLinkPasswordRequired(),
272
+                    'enableLinkPasswordByDefault' => $enableLinkPasswordByDefault,
273
+                    'sharingDisabledForUser' => \OCP\Util::isSharingDisabledForUser(),
274
+                    'resharingAllowed' => \OC\Share\Share::isResharingAllowed(),
275
+                    'remoteShareAllowed' => $outgoingServer2serverShareEnabled,
276
+                    'federatedCloudShareDoc' => $this->urlGenerator->linkToDocs('user-sharing-federated'),
277
+                    'allowGroupSharing' => \OC::$server->getShareManager()->allowGroupSharing(),
278
+                    'defaultInternalExpireDateEnabled' => $defaultInternalExpireDateEnabled,
279
+                    'defaultInternalExpireDate' => $defaultInternalExpireDate,
280
+                    'defaultInternalExpireDateEnforced' => $defaultInternalExpireDateEnforced,
281
+                ]
282
+            ]),
283
+            "_theme" => json_encode([
284
+                'entity' => $this->defaults->getEntity(),
285
+                'name' => $this->defaults->getName(),
286
+                'title' => $this->defaults->getTitle(),
287
+                'baseUrl' => $this->defaults->getBaseUrl(),
288
+                'syncClientUrl' => $this->defaults->getSyncClientUrl(),
289
+                'docBaseUrl' => $this->defaults->getDocBaseUrl(),
290
+                'docPlaceholderUrl' => $this->defaults->buildDocLinkToKey('PLACEHOLDER'),
291
+                'slogan' => $this->defaults->getSlogan(),
292
+                'logoClaim' => '',
293
+                'shortFooter' => $this->defaults->getShortFooter(),
294
+                'longFooter' => $this->defaults->getLongFooter(),
295
+                'folder' => \OC_Util::getTheme(),
296
+            ]),
297
+        ];
298
+
299
+        if ($this->currentUser !== null) {
300
+            $array['oc_userconfig'] = json_encode([
301
+                'avatar' => [
302
+                    'version' => (int)$this->config->getUserValue($uid, 'avatar', 'version', 0),
303
+                    'generated' => $this->config->getUserValue($uid, 'avatar', 'generated', 'true') === 'true',
304
+                ]
305
+            ]);
306
+        }
307
+
308
+        $this->initialStateService->provideInitialState('core', 'config', $config);
309
+        $this->initialStateService->provideInitialState('core', 'capabilities', $capabilities);
310
+
311
+        // Allow hooks to modify the output values
312
+        \OC_Hook::emit('\OCP\Config', 'js', ['array' => &$array]);
313
+
314
+        $result = '';
315
+
316
+        // Echo it
317
+        foreach ($array as  $setting => $value) {
318
+            $result .= 'var '. $setting . '='. $value . ';' . PHP_EOL;
319
+        }
320
+
321
+        return $result;
322
+    }
323 323
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 		$defaultExpireDateEnabled = $this->config->getAppValue('core', 'shareapi_default_expire_date', 'no') === 'yes';
154 154
 		$defaultExpireDate = $enforceDefaultExpireDate = null;
155 155
 		if ($defaultExpireDateEnabled) {
156
-			$defaultExpireDate = (int)$this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
156
+			$defaultExpireDate = (int) $this->config->getAppValue('core', 'shareapi_expire_after_n_days', '7');
157 157
 			$enforceDefaultExpireDate = $this->config->getAppValue('core', 'shareapi_enforce_expire_date', 'no') === 'yes';
158 158
 		}
159 159
 		$outgoingServer2serverShareEnabled = $this->config->getAppValue('files_sharing', 'outgoing_server2server_share_enabled', 'yes') === 'yes';
@@ -161,12 +161,12 @@  discard block
 block discarded – undo
161 161
 		$defaultInternalExpireDateEnabled = $this->config->getAppValue('core', 'shareapi_default_internal_expire_date', 'no') === 'yes';
162 162
 		$defaultInternalExpireDate = $defaultInternalExpireDateEnforced = null;
163 163
 		if ($defaultInternalExpireDateEnabled) {
164
-			$defaultInternalExpireDate = (int)$this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
164
+			$defaultInternalExpireDate = (int) $this->config->getAppValue('core', 'shareapi_internal_expire_after_n_days', '7');
165 165
 			$defaultInternalExpireDateEnforced = $this->config->getAppValue('core', 'shareapi_enforce_internal_expire_date', 'no') === 'yes';
166 166
 		}
167 167
 
168 168
 		$countOfDataLocation = 0;
169
-		$dataLocation = str_replace(\OC::$SERVERROOT . '/', '', $this->config->getSystemValue('datadirectory', ''), $countOfDataLocation);
169
+		$dataLocation = str_replace(\OC::$SERVERROOT.'/', '', $this->config->getSystemValue('datadirectory', ''), $countOfDataLocation);
170 170
 		if ($countOfDataLocation !== 1 || $uid === null || !$this->groupManager->isAdmin($uid)) {
171 171
 			$dataLocation = false;
172 172
 		}
@@ -200,8 +200,8 @@  discard block
 block discarded – undo
200 200
 			"_oc_debug" => $this->config->getSystemValue('debug', false) ? 'true' : 'false',
201 201
 			"_oc_isadmin" => $uid !== null && $this->groupManager->isAdmin($uid) ? 'true' : 'false',
202 202
 			"backendAllowsPasswordConfirmation" => $userBackendAllowsPasswordConfirmation ? 'true' : 'false',
203
-			"oc_dataURL" => is_string($dataLocation) ? "\"" . $dataLocation . "\"" : 'false',
204
-			"_oc_webroot" => "\"" . \OC::$WEBROOT . "\"",
203
+			"oc_dataURL" => is_string($dataLocation) ? "\"".$dataLocation."\"" : 'false',
204
+			"_oc_webroot" => "\"".\OC::$WEBROOT."\"",
205 205
 			"_oc_appswebroots" => str_replace('\\/', '/', json_encode($apps_paths)), // Ugly unescape slashes waiting for better solution
206 206
 			"datepickerFormatDate" => json_encode($this->l->l('jsdate', null)),
207 207
 			'nc_lastLogin' => $lastConfirmTimestamp,
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
 		if ($this->currentUser !== null) {
300 300
 			$array['oc_userconfig'] = json_encode([
301 301
 				'avatar' => [
302
-					'version' => (int)$this->config->getUserValue($uid, 'avatar', 'version', 0),
302
+					'version' => (int) $this->config->getUserValue($uid, 'avatar', 'version', 0),
303 303
 					'generated' => $this->config->getUserValue($uid, 'avatar', 'generated', 'true') === 'true',
304 304
 				]
305 305
 			]);
@@ -315,7 +315,7 @@  discard block
 block discarded – undo
315 315
 
316 316
 		// Echo it
317 317
 		foreach ($array as  $setting => $value) {
318
-			$result .= 'var '. $setting . '='. $value . ';' . PHP_EOL;
318
+			$result .= 'var '.$setting.'='.$value.';'.PHP_EOL;
319 319
 		}
320 320
 
321 321
 		return $result;
Please login to merge, or discard this patch.
lib/private/Group/Manager.php 1 patch
Indentation   +359 added lines, -359 removed lines patch added patch discarded remove patch
@@ -65,363 +65,363 @@
 block discarded – undo
65 65
  * @package OC\Group
66 66
  */
67 67
 class Manager extends PublicEmitter implements IGroupManager {
68
-	/** @var GroupInterface[] */
69
-	private $backends = [];
70
-
71
-	/** @var \OC\User\Manager */
72
-	private $userManager;
73
-	/** @var EventDispatcherInterface */
74
-	private $dispatcher;
75
-	/** @var ILogger */
76
-	private $logger;
77
-
78
-	/** @var \OC\Group\Group[] */
79
-	private $cachedGroups = [];
80
-
81
-	/** @var (string[])[] */
82
-	private $cachedUserGroups = [];
83
-
84
-	/** @var \OC\SubAdmin */
85
-	private $subAdmin = null;
86
-
87
-	/**
88
-	 * @param \OC\User\Manager $userManager
89
-	 * @param EventDispatcherInterface $dispatcher
90
-	 * @param ILogger $logger
91
-	 */
92
-	public function __construct(\OC\User\Manager $userManager,
93
-								EventDispatcherInterface $dispatcher,
94
-								ILogger $logger) {
95
-		$this->userManager = $userManager;
96
-		$this->dispatcher = $dispatcher;
97
-		$this->logger = $logger;
98
-
99
-		$cachedGroups = &$this->cachedGroups;
100
-		$cachedUserGroups = &$this->cachedUserGroups;
101
-		$this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
102
-			/**
103
-			 * @var \OC\Group\Group $group
104
-			 */
105
-			unset($cachedGroups[$group->getGID()]);
106
-			$cachedUserGroups = [];
107
-		});
108
-		$this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
109
-			/**
110
-			 * @var \OC\Group\Group $group
111
-			 */
112
-			$cachedUserGroups = [];
113
-		});
114
-		$this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
115
-			/**
116
-			 * @var \OC\Group\Group $group
117
-			 */
118
-			$cachedUserGroups = [];
119
-		});
120
-	}
121
-
122
-	/**
123
-	 * Checks whether a given backend is used
124
-	 *
125
-	 * @param string $backendClass Full classname including complete namespace
126
-	 * @return bool
127
-	 */
128
-	public function isBackendUsed($backendClass) {
129
-		$backendClass = strtolower(ltrim($backendClass, '\\'));
130
-
131
-		foreach ($this->backends as $backend) {
132
-			if (strtolower(get_class($backend)) === $backendClass) {
133
-				return true;
134
-			}
135
-		}
136
-
137
-		return false;
138
-	}
139
-
140
-	/**
141
-	 * @param \OCP\GroupInterface $backend
142
-	 */
143
-	public function addBackend($backend) {
144
-		$this->backends[] = $backend;
145
-		$this->clearCaches();
146
-	}
147
-
148
-	public function clearBackends() {
149
-		$this->backends = [];
150
-		$this->clearCaches();
151
-	}
152
-
153
-	/**
154
-	 * Get the active backends
155
-	 *
156
-	 * @return \OCP\GroupInterface[]
157
-	 */
158
-	public function getBackends() {
159
-		return $this->backends;
160
-	}
161
-
162
-
163
-	protected function clearCaches() {
164
-		$this->cachedGroups = [];
165
-		$this->cachedUserGroups = [];
166
-	}
167
-
168
-	/**
169
-	 * @param string $gid
170
-	 * @return IGroup|null
171
-	 */
172
-	public function get($gid) {
173
-		if (isset($this->cachedGroups[$gid])) {
174
-			return $this->cachedGroups[$gid];
175
-		}
176
-		return $this->getGroupObject($gid);
177
-	}
178
-
179
-	/**
180
-	 * @param string $gid
181
-	 * @param string $displayName
182
-	 * @return \OCP\IGroup|null
183
-	 */
184
-	protected function getGroupObject($gid, $displayName = null) {
185
-		$backends = [];
186
-		foreach ($this->backends as $backend) {
187
-			if ($backend->implementsActions(Backend::GROUP_DETAILS)) {
188
-				$groupData = $backend->getGroupDetails($gid);
189
-				if (is_array($groupData) && !empty($groupData)) {
190
-					// take the display name from the first backend that has a non-null one
191
-					if (is_null($displayName) && isset($groupData['displayName'])) {
192
-						$displayName = $groupData['displayName'];
193
-					}
194
-					$backends[] = $backend;
195
-				}
196
-			} elseif ($backend->groupExists($gid)) {
197
-				$backends[] = $backend;
198
-			}
199
-		}
200
-		if (count($backends) === 0) {
201
-			return null;
202
-		}
203
-		$this->cachedGroups[$gid] = new Group($gid, $backends, $this->dispatcher, $this->userManager, $this, $displayName);
204
-		return $this->cachedGroups[$gid];
205
-	}
206
-
207
-	/**
208
-	 * @param string $gid
209
-	 * @return bool
210
-	 */
211
-	public function groupExists($gid) {
212
-		return $this->get($gid) instanceof IGroup;
213
-	}
214
-
215
-	/**
216
-	 * @param string $gid
217
-	 * @return IGroup|null
218
-	 */
219
-	public function createGroup($gid) {
220
-		if ($gid === '' || $gid === null) {
221
-			return null;
222
-		} elseif ($group = $this->get($gid)) {
223
-			return $group;
224
-		} else {
225
-			$this->emit('\OC\Group', 'preCreate', [$gid]);
226
-			foreach ($this->backends as $backend) {
227
-				if ($backend->implementsActions(Backend::CREATE_GROUP)) {
228
-					if ($backend->createGroup($gid)) {
229
-						$group = $this->getGroupObject($gid);
230
-						$this->emit('\OC\Group', 'postCreate', [$group]);
231
-						return $group;
232
-					}
233
-				}
234
-			}
235
-			return null;
236
-		}
237
-	}
238
-
239
-	/**
240
-	 * @param string $search
241
-	 * @param int $limit
242
-	 * @param int $offset
243
-	 * @return \OC\Group\Group[]
244
-	 */
245
-	public function search($search, $limit = null, $offset = null) {
246
-		$groups = [];
247
-		foreach ($this->backends as $backend) {
248
-			$groupIds = $backend->getGroups($search, $limit, $offset);
249
-			foreach ($groupIds as $groupId) {
250
-				$aGroup = $this->get($groupId);
251
-				if ($aGroup instanceof IGroup) {
252
-					$groups[$groupId] = $aGroup;
253
-				} else {
254
-					$this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
255
-				}
256
-			}
257
-			if (!is_null($limit) and $limit <= 0) {
258
-				return array_values($groups);
259
-			}
260
-		}
261
-		return array_values($groups);
262
-	}
263
-
264
-	/**
265
-	 * @param IUser|null $user
266
-	 * @return \OC\Group\Group[]
267
-	 */
268
-	public function getUserGroups(IUser $user = null) {
269
-		if (!$user instanceof IUser) {
270
-			return [];
271
-		}
272
-		return $this->getUserIdGroups($user->getUID());
273
-	}
274
-
275
-	/**
276
-	 * @param string $uid the user id
277
-	 * @return \OC\Group\Group[]
278
-	 */
279
-	public function getUserIdGroups(string $uid): array {
280
-		$groups = [];
281
-
282
-		foreach ($this->getUserIdGroupIds($uid) as $groupId) {
283
-			$aGroup = $this->get($groupId);
284
-			if ($aGroup instanceof IGroup) {
285
-				$groups[$groupId] = $aGroup;
286
-			} else {
287
-				$this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
288
-			}
289
-		}
290
-
291
-		return $groups;
292
-	}
293
-
294
-	/**
295
-	 * Checks if a userId is in the admin group
296
-	 *
297
-	 * @param string $userId
298
-	 * @return bool if admin
299
-	 */
300
-	public function isAdmin($userId) {
301
-		foreach ($this->backends as $backend) {
302
-			if ($backend->implementsActions(Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
303
-				return true;
304
-			}
305
-		}
306
-		return $this->isInGroup($userId, 'admin');
307
-	}
308
-
309
-	/**
310
-	 * Checks if a userId is in a group
311
-	 *
312
-	 * @param string $userId
313
-	 * @param string $group
314
-	 * @return bool if in group
315
-	 */
316
-	public function isInGroup($userId, $group) {
317
-		return array_search($group, $this->getUserIdGroupIds($userId)) !== false;
318
-	}
319
-
320
-	/**
321
-	 * get a list of group ids for a user
322
-	 *
323
-	 * @param IUser $user
324
-	 * @return string[] with group ids
325
-	 */
326
-	public function getUserGroupIds(IUser $user): array {
327
-		return $this->getUserIdGroupIds($user->getUID());
328
-	}
329
-
330
-	/**
331
-	 * @param string $uid the user id
332
-	 * @return string[]
333
-	 */
334
-	private function getUserIdGroupIds(string $uid): array {
335
-		if (!isset($this->cachedUserGroups[$uid])) {
336
-			$groups = [];
337
-			foreach ($this->backends as $backend) {
338
-				if ($groupIds = $backend->getUserGroups($uid)) {
339
-					$groups = array_merge($groups, $groupIds);
340
-				}
341
-			}
342
-			$this->cachedUserGroups[$uid] = $groups;
343
-		}
344
-
345
-		return $this->cachedUserGroups[$uid];
346
-	}
347
-
348
-	/**
349
-	 * get an array of groupid and displayName for a user
350
-	 *
351
-	 * @param IUser $user
352
-	 * @return array ['displayName' => displayname]
353
-	 */
354
-	public function getUserGroupNames(IUser $user) {
355
-		return array_map(function ($group) {
356
-			return ['displayName' => $group->getDisplayName()];
357
-		}, $this->getUserGroups($user));
358
-	}
359
-
360
-	/**
361
-	 * get a list of all display names in a group
362
-	 *
363
-	 * @param string $gid
364
-	 * @param string $search
365
-	 * @param int $limit
366
-	 * @param int $offset
367
-	 * @return array an array of display names (value) and user ids (key)
368
-	 */
369
-	public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
370
-		$group = $this->get($gid);
371
-		if (is_null($group)) {
372
-			return [];
373
-		}
374
-
375
-		$search = trim($search);
376
-		$groupUsers = [];
377
-
378
-		if (!empty($search)) {
379
-			// only user backends have the capability to do a complex search for users
380
-			$searchOffset = 0;
381
-			$searchLimit = $limit * 100;
382
-			if ($limit === -1) {
383
-				$searchLimit = 500;
384
-			}
385
-
386
-			do {
387
-				$filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
388
-				foreach ($filteredUsers as $filteredUser) {
389
-					if ($group->inGroup($filteredUser)) {
390
-						$groupUsers[] = $filteredUser;
391
-					}
392
-				}
393
-				$searchOffset += $searchLimit;
394
-			} while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
395
-
396
-			if ($limit === -1) {
397
-				$groupUsers = array_slice($groupUsers, $offset);
398
-			} else {
399
-				$groupUsers = array_slice($groupUsers, $offset, $limit);
400
-			}
401
-		} else {
402
-			$groupUsers = $group->searchUsers('', $limit, $offset);
403
-		}
404
-
405
-		$matchingUsers = [];
406
-		foreach ($groupUsers as $groupUser) {
407
-			$matchingUsers[(string) $groupUser->getUID()] = $groupUser->getDisplayName();
408
-		}
409
-		return $matchingUsers;
410
-	}
411
-
412
-	/**
413
-	 * @return \OC\SubAdmin
414
-	 */
415
-	public function getSubAdmin() {
416
-		if (!$this->subAdmin) {
417
-			$this->subAdmin = new \OC\SubAdmin(
418
-				$this->userManager,
419
-				$this,
420
-				\OC::$server->getDatabaseConnection(),
421
-				\OC::$server->get(IEventDispatcher::class)
422
-			);
423
-		}
424
-
425
-		return $this->subAdmin;
426
-	}
68
+    /** @var GroupInterface[] */
69
+    private $backends = [];
70
+
71
+    /** @var \OC\User\Manager */
72
+    private $userManager;
73
+    /** @var EventDispatcherInterface */
74
+    private $dispatcher;
75
+    /** @var ILogger */
76
+    private $logger;
77
+
78
+    /** @var \OC\Group\Group[] */
79
+    private $cachedGroups = [];
80
+
81
+    /** @var (string[])[] */
82
+    private $cachedUserGroups = [];
83
+
84
+    /** @var \OC\SubAdmin */
85
+    private $subAdmin = null;
86
+
87
+    /**
88
+     * @param \OC\User\Manager $userManager
89
+     * @param EventDispatcherInterface $dispatcher
90
+     * @param ILogger $logger
91
+     */
92
+    public function __construct(\OC\User\Manager $userManager,
93
+                                EventDispatcherInterface $dispatcher,
94
+                                ILogger $logger) {
95
+        $this->userManager = $userManager;
96
+        $this->dispatcher = $dispatcher;
97
+        $this->logger = $logger;
98
+
99
+        $cachedGroups = &$this->cachedGroups;
100
+        $cachedUserGroups = &$this->cachedUserGroups;
101
+        $this->listen('\OC\Group', 'postDelete', function ($group) use (&$cachedGroups, &$cachedUserGroups) {
102
+            /**
103
+             * @var \OC\Group\Group $group
104
+             */
105
+            unset($cachedGroups[$group->getGID()]);
106
+            $cachedUserGroups = [];
107
+        });
108
+        $this->listen('\OC\Group', 'postAddUser', function ($group) use (&$cachedUserGroups) {
109
+            /**
110
+             * @var \OC\Group\Group $group
111
+             */
112
+            $cachedUserGroups = [];
113
+        });
114
+        $this->listen('\OC\Group', 'postRemoveUser', function ($group) use (&$cachedUserGroups) {
115
+            /**
116
+             * @var \OC\Group\Group $group
117
+             */
118
+            $cachedUserGroups = [];
119
+        });
120
+    }
121
+
122
+    /**
123
+     * Checks whether a given backend is used
124
+     *
125
+     * @param string $backendClass Full classname including complete namespace
126
+     * @return bool
127
+     */
128
+    public function isBackendUsed($backendClass) {
129
+        $backendClass = strtolower(ltrim($backendClass, '\\'));
130
+
131
+        foreach ($this->backends as $backend) {
132
+            if (strtolower(get_class($backend)) === $backendClass) {
133
+                return true;
134
+            }
135
+        }
136
+
137
+        return false;
138
+    }
139
+
140
+    /**
141
+     * @param \OCP\GroupInterface $backend
142
+     */
143
+    public function addBackend($backend) {
144
+        $this->backends[] = $backend;
145
+        $this->clearCaches();
146
+    }
147
+
148
+    public function clearBackends() {
149
+        $this->backends = [];
150
+        $this->clearCaches();
151
+    }
152
+
153
+    /**
154
+     * Get the active backends
155
+     *
156
+     * @return \OCP\GroupInterface[]
157
+     */
158
+    public function getBackends() {
159
+        return $this->backends;
160
+    }
161
+
162
+
163
+    protected function clearCaches() {
164
+        $this->cachedGroups = [];
165
+        $this->cachedUserGroups = [];
166
+    }
167
+
168
+    /**
169
+     * @param string $gid
170
+     * @return IGroup|null
171
+     */
172
+    public function get($gid) {
173
+        if (isset($this->cachedGroups[$gid])) {
174
+            return $this->cachedGroups[$gid];
175
+        }
176
+        return $this->getGroupObject($gid);
177
+    }
178
+
179
+    /**
180
+     * @param string $gid
181
+     * @param string $displayName
182
+     * @return \OCP\IGroup|null
183
+     */
184
+    protected function getGroupObject($gid, $displayName = null) {
185
+        $backends = [];
186
+        foreach ($this->backends as $backend) {
187
+            if ($backend->implementsActions(Backend::GROUP_DETAILS)) {
188
+                $groupData = $backend->getGroupDetails($gid);
189
+                if (is_array($groupData) && !empty($groupData)) {
190
+                    // take the display name from the first backend that has a non-null one
191
+                    if (is_null($displayName) && isset($groupData['displayName'])) {
192
+                        $displayName = $groupData['displayName'];
193
+                    }
194
+                    $backends[] = $backend;
195
+                }
196
+            } elseif ($backend->groupExists($gid)) {
197
+                $backends[] = $backend;
198
+            }
199
+        }
200
+        if (count($backends) === 0) {
201
+            return null;
202
+        }
203
+        $this->cachedGroups[$gid] = new Group($gid, $backends, $this->dispatcher, $this->userManager, $this, $displayName);
204
+        return $this->cachedGroups[$gid];
205
+    }
206
+
207
+    /**
208
+     * @param string $gid
209
+     * @return bool
210
+     */
211
+    public function groupExists($gid) {
212
+        return $this->get($gid) instanceof IGroup;
213
+    }
214
+
215
+    /**
216
+     * @param string $gid
217
+     * @return IGroup|null
218
+     */
219
+    public function createGroup($gid) {
220
+        if ($gid === '' || $gid === null) {
221
+            return null;
222
+        } elseif ($group = $this->get($gid)) {
223
+            return $group;
224
+        } else {
225
+            $this->emit('\OC\Group', 'preCreate', [$gid]);
226
+            foreach ($this->backends as $backend) {
227
+                if ($backend->implementsActions(Backend::CREATE_GROUP)) {
228
+                    if ($backend->createGroup($gid)) {
229
+                        $group = $this->getGroupObject($gid);
230
+                        $this->emit('\OC\Group', 'postCreate', [$group]);
231
+                        return $group;
232
+                    }
233
+                }
234
+            }
235
+            return null;
236
+        }
237
+    }
238
+
239
+    /**
240
+     * @param string $search
241
+     * @param int $limit
242
+     * @param int $offset
243
+     * @return \OC\Group\Group[]
244
+     */
245
+    public function search($search, $limit = null, $offset = null) {
246
+        $groups = [];
247
+        foreach ($this->backends as $backend) {
248
+            $groupIds = $backend->getGroups($search, $limit, $offset);
249
+            foreach ($groupIds as $groupId) {
250
+                $aGroup = $this->get($groupId);
251
+                if ($aGroup instanceof IGroup) {
252
+                    $groups[$groupId] = $aGroup;
253
+                } else {
254
+                    $this->logger->debug('Group "' . $groupId . '" was returned by search but not found through direct access', ['app' => 'core']);
255
+                }
256
+            }
257
+            if (!is_null($limit) and $limit <= 0) {
258
+                return array_values($groups);
259
+            }
260
+        }
261
+        return array_values($groups);
262
+    }
263
+
264
+    /**
265
+     * @param IUser|null $user
266
+     * @return \OC\Group\Group[]
267
+     */
268
+    public function getUserGroups(IUser $user = null) {
269
+        if (!$user instanceof IUser) {
270
+            return [];
271
+        }
272
+        return $this->getUserIdGroups($user->getUID());
273
+    }
274
+
275
+    /**
276
+     * @param string $uid the user id
277
+     * @return \OC\Group\Group[]
278
+     */
279
+    public function getUserIdGroups(string $uid): array {
280
+        $groups = [];
281
+
282
+        foreach ($this->getUserIdGroupIds($uid) as $groupId) {
283
+            $aGroup = $this->get($groupId);
284
+            if ($aGroup instanceof IGroup) {
285
+                $groups[$groupId] = $aGroup;
286
+            } else {
287
+                $this->logger->debug('User "' . $uid . '" belongs to deleted group: "' . $groupId . '"', ['app' => 'core']);
288
+            }
289
+        }
290
+
291
+        return $groups;
292
+    }
293
+
294
+    /**
295
+     * Checks if a userId is in the admin group
296
+     *
297
+     * @param string $userId
298
+     * @return bool if admin
299
+     */
300
+    public function isAdmin($userId) {
301
+        foreach ($this->backends as $backend) {
302
+            if ($backend->implementsActions(Backend::IS_ADMIN) && $backend->isAdmin($userId)) {
303
+                return true;
304
+            }
305
+        }
306
+        return $this->isInGroup($userId, 'admin');
307
+    }
308
+
309
+    /**
310
+     * Checks if a userId is in a group
311
+     *
312
+     * @param string $userId
313
+     * @param string $group
314
+     * @return bool if in group
315
+     */
316
+    public function isInGroup($userId, $group) {
317
+        return array_search($group, $this->getUserIdGroupIds($userId)) !== false;
318
+    }
319
+
320
+    /**
321
+     * get a list of group ids for a user
322
+     *
323
+     * @param IUser $user
324
+     * @return string[] with group ids
325
+     */
326
+    public function getUserGroupIds(IUser $user): array {
327
+        return $this->getUserIdGroupIds($user->getUID());
328
+    }
329
+
330
+    /**
331
+     * @param string $uid the user id
332
+     * @return string[]
333
+     */
334
+    private function getUserIdGroupIds(string $uid): array {
335
+        if (!isset($this->cachedUserGroups[$uid])) {
336
+            $groups = [];
337
+            foreach ($this->backends as $backend) {
338
+                if ($groupIds = $backend->getUserGroups($uid)) {
339
+                    $groups = array_merge($groups, $groupIds);
340
+                }
341
+            }
342
+            $this->cachedUserGroups[$uid] = $groups;
343
+        }
344
+
345
+        return $this->cachedUserGroups[$uid];
346
+    }
347
+
348
+    /**
349
+     * get an array of groupid and displayName for a user
350
+     *
351
+     * @param IUser $user
352
+     * @return array ['displayName' => displayname]
353
+     */
354
+    public function getUserGroupNames(IUser $user) {
355
+        return array_map(function ($group) {
356
+            return ['displayName' => $group->getDisplayName()];
357
+        }, $this->getUserGroups($user));
358
+    }
359
+
360
+    /**
361
+     * get a list of all display names in a group
362
+     *
363
+     * @param string $gid
364
+     * @param string $search
365
+     * @param int $limit
366
+     * @param int $offset
367
+     * @return array an array of display names (value) and user ids (key)
368
+     */
369
+    public function displayNamesInGroup($gid, $search = '', $limit = -1, $offset = 0) {
370
+        $group = $this->get($gid);
371
+        if (is_null($group)) {
372
+            return [];
373
+        }
374
+
375
+        $search = trim($search);
376
+        $groupUsers = [];
377
+
378
+        if (!empty($search)) {
379
+            // only user backends have the capability to do a complex search for users
380
+            $searchOffset = 0;
381
+            $searchLimit = $limit * 100;
382
+            if ($limit === -1) {
383
+                $searchLimit = 500;
384
+            }
385
+
386
+            do {
387
+                $filteredUsers = $this->userManager->searchDisplayName($search, $searchLimit, $searchOffset);
388
+                foreach ($filteredUsers as $filteredUser) {
389
+                    if ($group->inGroup($filteredUser)) {
390
+                        $groupUsers[] = $filteredUser;
391
+                    }
392
+                }
393
+                $searchOffset += $searchLimit;
394
+            } while (count($groupUsers) < $searchLimit + $offset && count($filteredUsers) >= $searchLimit);
395
+
396
+            if ($limit === -1) {
397
+                $groupUsers = array_slice($groupUsers, $offset);
398
+            } else {
399
+                $groupUsers = array_slice($groupUsers, $offset, $limit);
400
+            }
401
+        } else {
402
+            $groupUsers = $group->searchUsers('', $limit, $offset);
403
+        }
404
+
405
+        $matchingUsers = [];
406
+        foreach ($groupUsers as $groupUser) {
407
+            $matchingUsers[(string) $groupUser->getUID()] = $groupUser->getDisplayName();
408
+        }
409
+        return $matchingUsers;
410
+    }
411
+
412
+    /**
413
+     * @return \OC\SubAdmin
414
+     */
415
+    public function getSubAdmin() {
416
+        if (!$this->subAdmin) {
417
+            $this->subAdmin = new \OC\SubAdmin(
418
+                $this->userManager,
419
+                $this,
420
+                \OC::$server->getDatabaseConnection(),
421
+                \OC::$server->get(IEventDispatcher::class)
422
+            );
423
+        }
424
+
425
+        return $this->subAdmin;
426
+    }
427 427
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/DependencyInjection/DIContainer.php 1 patch
Indentation   +385 added lines, -385 removed lines patch added patch discarded remove patch
@@ -79,389 +79,389 @@
 block discarded – undo
79 79
  */
80 80
 class DIContainer extends SimpleContainer implements IAppContainer {
81 81
 
82
-	/**
83
-	 * @var array
84
-	 */
85
-	private $middleWares = [];
86
-
87
-	/** @var ServerContainer */
88
-	private $server;
89
-
90
-	/**
91
-	 * Put your class dependencies in here
92
-	 * @param string $appName the name of the app
93
-	 * @param array $urlParams
94
-	 * @param ServerContainer|null $server
95
-	 */
96
-	public function __construct($appName, $urlParams = [], ServerContainer $server = null) {
97
-		parent::__construct();
98
-		$this['AppName'] = $appName;
99
-		$this['urlParams'] = $urlParams;
100
-
101
-		$this->registerAlias('Request', IRequest::class);
102
-
103
-		/** @var \OC\ServerContainer $server */
104
-		if ($server === null) {
105
-			$server = \OC::$server;
106
-		}
107
-		$this->server = $server;
108
-		$this->server->registerAppContainer($appName, $this);
109
-
110
-		// aliases
111
-		$this->registerAlias('appName', 'AppName');
112
-		$this->registerAlias('webRoot', 'WebRoot');
113
-		$this->registerAlias('userId', 'UserId');
114
-
115
-		/**
116
-		 * Core services
117
-		 */
118
-		$this->registerService(IOutput::class, function () {
119
-			return new Output($this->getServer()->getWebRoot());
120
-		});
121
-
122
-		$this->registerService(Folder::class, function () {
123
-			return $this->getServer()->getUserFolder();
124
-		});
125
-
126
-		$this->registerService(IAppData::class, function (ContainerInterface $c) {
127
-			return $this->getServer()->getAppDataDir($c->get('AppName'));
128
-		});
129
-
130
-		$this->registerService(IL10N::class, function (ContainerInterface $c) {
131
-			return $this->getServer()->getL10N($c->get('AppName'));
132
-		});
133
-
134
-		// Log wrappers
135
-		$this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
136
-			return new ScopedPsrLogger(
137
-				$c->get(PsrLoggerAdapter::class),
138
-				$c->get('AppName')
139
-			);
140
-		});
141
-		$this->registerService(ILogger::class, function (ContainerInterface $c) {
142
-			return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
143
-		});
144
-
145
-		$this->registerService(IServerContainer::class, function () {
146
-			return $this->getServer();
147
-		});
148
-		$this->registerAlias('ServerContainer', IServerContainer::class);
149
-
150
-		$this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
151
-			return $c->get(Manager::class);
152
-		});
153
-
154
-		$this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
155
-			return $c;
156
-		});
157
-		$this->registerAlias(IAppContainer::class, ContainerInterface::class);
158
-
159
-		// commonly used attributes
160
-		$this->registerService('UserId', function (ContainerInterface $c) {
161
-			return $c->get(IUserSession::class)->getSession()->get('user_id');
162
-		});
163
-
164
-		$this->registerService('WebRoot', function (ContainerInterface $c) {
165
-			return $c->get(IServerContainer::class)->getWebRoot();
166
-		});
167
-
168
-		$this->registerService('OC_Defaults', function (ContainerInterface $c) {
169
-			return $c->get(IServerContainer::class)->getThemingDefaults();
170
-		});
171
-
172
-		$this->registerService('Protocol', function (ContainerInterface $c) {
173
-			/** @var \OC\Server $server */
174
-			$server = $c->get(IServerContainer::class);
175
-			$protocol = $server->getRequest()->getHttpProtocol();
176
-			return new Http($_SERVER, $protocol);
177
-		});
178
-
179
-		$this->registerService('Dispatcher', function (ContainerInterface $c) {
180
-			return new Dispatcher(
181
-				$c->get('Protocol'),
182
-				$c->get(MiddlewareDispatcher::class),
183
-				$c->get(IControllerMethodReflector::class),
184
-				$c->get(IRequest::class),
185
-				$c->get(IConfig::class),
186
-				$c->get(IDBConnection::class),
187
-				$c->get(LoggerInterface::class)
188
-			);
189
-		});
190
-
191
-		/**
192
-		 * App Framework default arguments
193
-		 */
194
-		$this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
195
-		$this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
196
-		$this->registerParameter('corsMaxAge', 1728000);
197
-
198
-		/**
199
-		 * Middleware
200
-		 */
201
-		$this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
202
-		$this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
203
-			$server = $this->getServer();
204
-
205
-			$dispatcher = new MiddlewareDispatcher();
206
-
207
-			$dispatcher->registerMiddleware(
208
-				$c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
209
-			);
210
-
211
-			$dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
212
-
213
-			$dispatcher->registerMiddleware(
214
-				$c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
215
-			);
216
-
217
-			$dispatcher->registerMiddleware(
218
-				new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
219
-					$c->get(IRequest::class),
220
-					$c->get(IControllerMethodReflector::class)
221
-				)
222
-			);
223
-			$dispatcher->registerMiddleware(
224
-				new CORSMiddleware(
225
-					$c->get(IRequest::class),
226
-					$c->get(IControllerMethodReflector::class),
227
-					$c->get(IUserSession::class),
228
-					$c->get(OC\Security\Bruteforce\Throttler::class)
229
-				)
230
-			);
231
-			$dispatcher->registerMiddleware(
232
-				new OCSMiddleware(
233
-					$c->get(IRequest::class)
234
-				)
235
-			);
236
-
237
-
238
-
239
-			$securityMiddleware = new SecurityMiddleware(
240
-				$c->get(IRequest::class),
241
-				$c->get(IControllerMethodReflector::class),
242
-				$c->get(INavigationManager::class),
243
-				$c->get(IURLGenerator::class),
244
-				$server->query(ILogger::class),
245
-				$c->get('AppName'),
246
-				$server->getUserSession()->isLoggedIn(),
247
-				$this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
248
-				$server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
249
-				$server->getAppManager(),
250
-				$server->getL10N('lib')
251
-			);
252
-			$dispatcher->registerMiddleware($securityMiddleware);
253
-			$dispatcher->registerMiddleware(
254
-				new OC\AppFramework\Middleware\Security\CSPMiddleware(
255
-					$server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
256
-					$server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
257
-					$server->query(OC\Security\CSRF\CsrfTokenManager::class)
258
-				)
259
-			);
260
-			$dispatcher->registerMiddleware(
261
-				$server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
262
-			);
263
-			$dispatcher->registerMiddleware(
264
-				new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
265
-					$c->get(IControllerMethodReflector::class),
266
-					$c->get(ISession::class),
267
-					$c->get(IUserSession::class),
268
-					$c->get(ITimeFactory::class)
269
-				)
270
-			);
271
-			$dispatcher->registerMiddleware(
272
-				new TwoFactorMiddleware(
273
-					$c->get(OC\Authentication\TwoFactorAuth\Manager::class),
274
-					$c->get(IUserSession::class),
275
-					$c->get(ISession::class),
276
-					$c->get(IURLGenerator::class),
277
-					$c->get(IControllerMethodReflector::class),
278
-					$c->get(IRequest::class)
279
-				)
280
-			);
281
-			$dispatcher->registerMiddleware(
282
-				new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
283
-					$c->get(IControllerMethodReflector::class),
284
-					$c->get(OC\Security\Bruteforce\Throttler::class),
285
-					$c->get(IRequest::class)
286
-				)
287
-			);
288
-			$dispatcher->registerMiddleware(
289
-				new RateLimitingMiddleware(
290
-					$c->get(IRequest::class),
291
-					$c->get(IUserSession::class),
292
-					$c->get(IControllerMethodReflector::class),
293
-					$c->get(OC\Security\RateLimiting\Limiter::class)
294
-				)
295
-			);
296
-			$dispatcher->registerMiddleware(
297
-				new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
298
-					$c->get(IRequest::class),
299
-					$c->get(ISession::class),
300
-					$c->get(\OCP\IConfig::class)
301
-				)
302
-			);
303
-			$dispatcher->registerMiddleware(
304
-				$c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
305
-			);
306
-
307
-			foreach ($this->middleWares as $middleWare) {
308
-				$dispatcher->registerMiddleware($c->get($middleWare));
309
-			}
310
-
311
-			$dispatcher->registerMiddleware(
312
-				new SessionMiddleware(
313
-					$c->get(IControllerMethodReflector::class),
314
-					$c->get(ISession::class)
315
-				)
316
-			);
317
-			return $dispatcher;
318
-		});
319
-
320
-		$this->registerService(IAppConfig::class, function (ContainerInterface $c) {
321
-			return new OC\AppFramework\Services\AppConfig(
322
-				$c->get(IConfig::class),
323
-				$c->get('AppName')
324
-			);
325
-		});
326
-		$this->registerService(IInitialState::class, function (ContainerInterface $c) {
327
-			return new OC\AppFramework\Services\InitialState(
328
-				$c->get(IInitialStateService::class),
329
-				$c->get('AppName')
330
-			);
331
-		});
332
-	}
333
-
334
-	/**
335
-	 * @return \OCP\IServerContainer
336
-	 */
337
-	public function getServer() {
338
-		return $this->server;
339
-	}
340
-
341
-	/**
342
-	 * @param string $middleWare
343
-	 * @return boolean|null
344
-	 */
345
-	public function registerMiddleWare($middleWare) {
346
-		if (in_array($middleWare, $this->middleWares, true) !== false) {
347
-			return false;
348
-		}
349
-		$this->middleWares[] = $middleWare;
350
-	}
351
-
352
-	/**
353
-	 * used to return the appname of the set application
354
-	 * @return string the name of your application
355
-	 */
356
-	public function getAppName() {
357
-		return $this->query('AppName');
358
-	}
359
-
360
-	/**
361
-	 * @deprecated use IUserSession->isLoggedIn()
362
-	 * @return boolean
363
-	 */
364
-	public function isLoggedIn() {
365
-		return \OC::$server->getUserSession()->isLoggedIn();
366
-	}
367
-
368
-	/**
369
-	 * @deprecated use IGroupManager->isAdmin($userId)
370
-	 * @return boolean
371
-	 */
372
-	public function isAdminUser() {
373
-		$uid = $this->getUserId();
374
-		return \OC_User::isAdminUser($uid);
375
-	}
376
-
377
-	private function getUserId() {
378
-		return $this->getServer()->getSession()->get('user_id');
379
-	}
380
-
381
-	/**
382
-	 * @deprecated use the ILogger instead
383
-	 * @param string $message
384
-	 * @param string $level
385
-	 * @return mixed
386
-	 */
387
-	public function log($message, $level) {
388
-		switch ($level) {
389
-			case 'debug':
390
-				$level = ILogger::DEBUG;
391
-				break;
392
-			case 'info':
393
-				$level = ILogger::INFO;
394
-				break;
395
-			case 'warn':
396
-				$level = ILogger::WARN;
397
-				break;
398
-			case 'fatal':
399
-				$level = ILogger::FATAL;
400
-				break;
401
-			default:
402
-				$level = ILogger::ERROR;
403
-				break;
404
-		}
405
-		\OCP\Util::writeLog($this->getAppName(), $message, $level);
406
-	}
407
-
408
-	/**
409
-	 * Register a capability
410
-	 *
411
-	 * @param string $serviceName e.g. 'OCA\Files\Capabilities'
412
-	 */
413
-	public function registerCapability($serviceName) {
414
-		$this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
415
-			return $this->query($serviceName);
416
-		});
417
-	}
418
-
419
-	public function has($id): bool {
420
-		if (parent::has($id)) {
421
-			return true;
422
-		}
423
-
424
-		if ($this->server->has($id, true)) {
425
-			return true;
426
-		}
427
-
428
-		return false;
429
-	}
430
-
431
-	public function query(string $name, bool $autoload = true) {
432
-		try {
433
-			return $this->queryNoFallback($name);
434
-		} catch (QueryException $firstException) {
435
-			try {
436
-				return $this->getServer()->query($name, $autoload);
437
-			} catch (QueryException $secondException) {
438
-				if ($firstException->getCode() === 1) {
439
-					throw $secondException;
440
-				}
441
-				throw $firstException;
442
-			}
443
-		}
444
-	}
445
-
446
-	/**
447
-	 * @param string $name
448
-	 * @return mixed
449
-	 * @throws QueryException if the query could not be resolved
450
-	 */
451
-	public function queryNoFallback($name) {
452
-		$name = $this->sanitizeName($name);
453
-
454
-		if ($this->offsetExists($name)) {
455
-			return parent::query($name);
456
-		} elseif ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
457
-			return parent::query($name);
458
-		} elseif ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
459
-			return parent::query($name);
460
-		} elseif (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
461
-			return parent::query($name);
462
-		}
463
-
464
-		throw new QueryException('Could not resolve ' . $name . '!' .
465
-			' Class can not be instantiated', 1);
466
-	}
82
+    /**
83
+     * @var array
84
+     */
85
+    private $middleWares = [];
86
+
87
+    /** @var ServerContainer */
88
+    private $server;
89
+
90
+    /**
91
+     * Put your class dependencies in here
92
+     * @param string $appName the name of the app
93
+     * @param array $urlParams
94
+     * @param ServerContainer|null $server
95
+     */
96
+    public function __construct($appName, $urlParams = [], ServerContainer $server = null) {
97
+        parent::__construct();
98
+        $this['AppName'] = $appName;
99
+        $this['urlParams'] = $urlParams;
100
+
101
+        $this->registerAlias('Request', IRequest::class);
102
+
103
+        /** @var \OC\ServerContainer $server */
104
+        if ($server === null) {
105
+            $server = \OC::$server;
106
+        }
107
+        $this->server = $server;
108
+        $this->server->registerAppContainer($appName, $this);
109
+
110
+        // aliases
111
+        $this->registerAlias('appName', 'AppName');
112
+        $this->registerAlias('webRoot', 'WebRoot');
113
+        $this->registerAlias('userId', 'UserId');
114
+
115
+        /**
116
+         * Core services
117
+         */
118
+        $this->registerService(IOutput::class, function () {
119
+            return new Output($this->getServer()->getWebRoot());
120
+        });
121
+
122
+        $this->registerService(Folder::class, function () {
123
+            return $this->getServer()->getUserFolder();
124
+        });
125
+
126
+        $this->registerService(IAppData::class, function (ContainerInterface $c) {
127
+            return $this->getServer()->getAppDataDir($c->get('AppName'));
128
+        });
129
+
130
+        $this->registerService(IL10N::class, function (ContainerInterface $c) {
131
+            return $this->getServer()->getL10N($c->get('AppName'));
132
+        });
133
+
134
+        // Log wrappers
135
+        $this->registerService(LoggerInterface::class, function (ContainerInterface $c) {
136
+            return new ScopedPsrLogger(
137
+                $c->get(PsrLoggerAdapter::class),
138
+                $c->get('AppName')
139
+            );
140
+        });
141
+        $this->registerService(ILogger::class, function (ContainerInterface $c) {
142
+            return new OC\AppFramework\Logger($this->server->query(ILogger::class), $c->get('AppName'));
143
+        });
144
+
145
+        $this->registerService(IServerContainer::class, function () {
146
+            return $this->getServer();
147
+        });
148
+        $this->registerAlias('ServerContainer', IServerContainer::class);
149
+
150
+        $this->registerService(\OCP\WorkflowEngine\IManager::class, function (ContainerInterface $c) {
151
+            return $c->get(Manager::class);
152
+        });
153
+
154
+        $this->registerService(ContainerInterface::class, function (ContainerInterface $c) {
155
+            return $c;
156
+        });
157
+        $this->registerAlias(IAppContainer::class, ContainerInterface::class);
158
+
159
+        // commonly used attributes
160
+        $this->registerService('UserId', function (ContainerInterface $c) {
161
+            return $c->get(IUserSession::class)->getSession()->get('user_id');
162
+        });
163
+
164
+        $this->registerService('WebRoot', function (ContainerInterface $c) {
165
+            return $c->get(IServerContainer::class)->getWebRoot();
166
+        });
167
+
168
+        $this->registerService('OC_Defaults', function (ContainerInterface $c) {
169
+            return $c->get(IServerContainer::class)->getThemingDefaults();
170
+        });
171
+
172
+        $this->registerService('Protocol', function (ContainerInterface $c) {
173
+            /** @var \OC\Server $server */
174
+            $server = $c->get(IServerContainer::class);
175
+            $protocol = $server->getRequest()->getHttpProtocol();
176
+            return new Http($_SERVER, $protocol);
177
+        });
178
+
179
+        $this->registerService('Dispatcher', function (ContainerInterface $c) {
180
+            return new Dispatcher(
181
+                $c->get('Protocol'),
182
+                $c->get(MiddlewareDispatcher::class),
183
+                $c->get(IControllerMethodReflector::class),
184
+                $c->get(IRequest::class),
185
+                $c->get(IConfig::class),
186
+                $c->get(IDBConnection::class),
187
+                $c->get(LoggerInterface::class)
188
+            );
189
+        });
190
+
191
+        /**
192
+         * App Framework default arguments
193
+         */
194
+        $this->registerParameter('corsMethods', 'PUT, POST, GET, DELETE, PATCH');
195
+        $this->registerParameter('corsAllowedHeaders', 'Authorization, Content-Type, Accept');
196
+        $this->registerParameter('corsMaxAge', 1728000);
197
+
198
+        /**
199
+         * Middleware
200
+         */
201
+        $this->registerAlias('MiddlewareDispatcher', MiddlewareDispatcher::class);
202
+        $this->registerService(MiddlewareDispatcher::class, function (ContainerInterface $c) {
203
+            $server = $this->getServer();
204
+
205
+            $dispatcher = new MiddlewareDispatcher();
206
+
207
+            $dispatcher->registerMiddleware(
208
+                $c->get(OC\AppFramework\Middleware\CompressionMiddleware::class)
209
+            );
210
+
211
+            $dispatcher->registerMiddleware($c->get(OC\AppFramework\Middleware\NotModifiedMiddleware::class));
212
+
213
+            $dispatcher->registerMiddleware(
214
+                $c->get(OC\AppFramework\Middleware\Security\ReloadExecutionMiddleware::class)
215
+            );
216
+
217
+            $dispatcher->registerMiddleware(
218
+                new OC\AppFramework\Middleware\Security\SameSiteCookieMiddleware(
219
+                    $c->get(IRequest::class),
220
+                    $c->get(IControllerMethodReflector::class)
221
+                )
222
+            );
223
+            $dispatcher->registerMiddleware(
224
+                new CORSMiddleware(
225
+                    $c->get(IRequest::class),
226
+                    $c->get(IControllerMethodReflector::class),
227
+                    $c->get(IUserSession::class),
228
+                    $c->get(OC\Security\Bruteforce\Throttler::class)
229
+                )
230
+            );
231
+            $dispatcher->registerMiddleware(
232
+                new OCSMiddleware(
233
+                    $c->get(IRequest::class)
234
+                )
235
+            );
236
+
237
+
238
+
239
+            $securityMiddleware = new SecurityMiddleware(
240
+                $c->get(IRequest::class),
241
+                $c->get(IControllerMethodReflector::class),
242
+                $c->get(INavigationManager::class),
243
+                $c->get(IURLGenerator::class),
244
+                $server->query(ILogger::class),
245
+                $c->get('AppName'),
246
+                $server->getUserSession()->isLoggedIn(),
247
+                $this->getUserId() !== null && $server->getGroupManager()->isAdmin($this->getUserId()),
248
+                $server->getUserSession()->getUser() !== null && $server->query(ISubAdmin::class)->isSubAdmin($server->getUserSession()->getUser()),
249
+                $server->getAppManager(),
250
+                $server->getL10N('lib')
251
+            );
252
+            $dispatcher->registerMiddleware($securityMiddleware);
253
+            $dispatcher->registerMiddleware(
254
+                new OC\AppFramework\Middleware\Security\CSPMiddleware(
255
+                    $server->query(OC\Security\CSP\ContentSecurityPolicyManager::class),
256
+                    $server->query(OC\Security\CSP\ContentSecurityPolicyNonceManager::class),
257
+                    $server->query(OC\Security\CSRF\CsrfTokenManager::class)
258
+                )
259
+            );
260
+            $dispatcher->registerMiddleware(
261
+                $server->query(OC\AppFramework\Middleware\Security\FeaturePolicyMiddleware::class)
262
+            );
263
+            $dispatcher->registerMiddleware(
264
+                new OC\AppFramework\Middleware\Security\PasswordConfirmationMiddleware(
265
+                    $c->get(IControllerMethodReflector::class),
266
+                    $c->get(ISession::class),
267
+                    $c->get(IUserSession::class),
268
+                    $c->get(ITimeFactory::class)
269
+                )
270
+            );
271
+            $dispatcher->registerMiddleware(
272
+                new TwoFactorMiddleware(
273
+                    $c->get(OC\Authentication\TwoFactorAuth\Manager::class),
274
+                    $c->get(IUserSession::class),
275
+                    $c->get(ISession::class),
276
+                    $c->get(IURLGenerator::class),
277
+                    $c->get(IControllerMethodReflector::class),
278
+                    $c->get(IRequest::class)
279
+                )
280
+            );
281
+            $dispatcher->registerMiddleware(
282
+                new OC\AppFramework\Middleware\Security\BruteForceMiddleware(
283
+                    $c->get(IControllerMethodReflector::class),
284
+                    $c->get(OC\Security\Bruteforce\Throttler::class),
285
+                    $c->get(IRequest::class)
286
+                )
287
+            );
288
+            $dispatcher->registerMiddleware(
289
+                new RateLimitingMiddleware(
290
+                    $c->get(IRequest::class),
291
+                    $c->get(IUserSession::class),
292
+                    $c->get(IControllerMethodReflector::class),
293
+                    $c->get(OC\Security\RateLimiting\Limiter::class)
294
+                )
295
+            );
296
+            $dispatcher->registerMiddleware(
297
+                new OC\AppFramework\Middleware\PublicShare\PublicShareMiddleware(
298
+                    $c->get(IRequest::class),
299
+                    $c->get(ISession::class),
300
+                    $c->get(\OCP\IConfig::class)
301
+                )
302
+            );
303
+            $dispatcher->registerMiddleware(
304
+                $c->get(\OC\AppFramework\Middleware\AdditionalScriptsMiddleware::class)
305
+            );
306
+
307
+            foreach ($this->middleWares as $middleWare) {
308
+                $dispatcher->registerMiddleware($c->get($middleWare));
309
+            }
310
+
311
+            $dispatcher->registerMiddleware(
312
+                new SessionMiddleware(
313
+                    $c->get(IControllerMethodReflector::class),
314
+                    $c->get(ISession::class)
315
+                )
316
+            );
317
+            return $dispatcher;
318
+        });
319
+
320
+        $this->registerService(IAppConfig::class, function (ContainerInterface $c) {
321
+            return new OC\AppFramework\Services\AppConfig(
322
+                $c->get(IConfig::class),
323
+                $c->get('AppName')
324
+            );
325
+        });
326
+        $this->registerService(IInitialState::class, function (ContainerInterface $c) {
327
+            return new OC\AppFramework\Services\InitialState(
328
+                $c->get(IInitialStateService::class),
329
+                $c->get('AppName')
330
+            );
331
+        });
332
+    }
333
+
334
+    /**
335
+     * @return \OCP\IServerContainer
336
+     */
337
+    public function getServer() {
338
+        return $this->server;
339
+    }
340
+
341
+    /**
342
+     * @param string $middleWare
343
+     * @return boolean|null
344
+     */
345
+    public function registerMiddleWare($middleWare) {
346
+        if (in_array($middleWare, $this->middleWares, true) !== false) {
347
+            return false;
348
+        }
349
+        $this->middleWares[] = $middleWare;
350
+    }
351
+
352
+    /**
353
+     * used to return the appname of the set application
354
+     * @return string the name of your application
355
+     */
356
+    public function getAppName() {
357
+        return $this->query('AppName');
358
+    }
359
+
360
+    /**
361
+     * @deprecated use IUserSession->isLoggedIn()
362
+     * @return boolean
363
+     */
364
+    public function isLoggedIn() {
365
+        return \OC::$server->getUserSession()->isLoggedIn();
366
+    }
367
+
368
+    /**
369
+     * @deprecated use IGroupManager->isAdmin($userId)
370
+     * @return boolean
371
+     */
372
+    public function isAdminUser() {
373
+        $uid = $this->getUserId();
374
+        return \OC_User::isAdminUser($uid);
375
+    }
376
+
377
+    private function getUserId() {
378
+        return $this->getServer()->getSession()->get('user_id');
379
+    }
380
+
381
+    /**
382
+     * @deprecated use the ILogger instead
383
+     * @param string $message
384
+     * @param string $level
385
+     * @return mixed
386
+     */
387
+    public function log($message, $level) {
388
+        switch ($level) {
389
+            case 'debug':
390
+                $level = ILogger::DEBUG;
391
+                break;
392
+            case 'info':
393
+                $level = ILogger::INFO;
394
+                break;
395
+            case 'warn':
396
+                $level = ILogger::WARN;
397
+                break;
398
+            case 'fatal':
399
+                $level = ILogger::FATAL;
400
+                break;
401
+            default:
402
+                $level = ILogger::ERROR;
403
+                break;
404
+        }
405
+        \OCP\Util::writeLog($this->getAppName(), $message, $level);
406
+    }
407
+
408
+    /**
409
+     * Register a capability
410
+     *
411
+     * @param string $serviceName e.g. 'OCA\Files\Capabilities'
412
+     */
413
+    public function registerCapability($serviceName) {
414
+        $this->query('OC\CapabilitiesManager')->registerCapability(function () use ($serviceName) {
415
+            return $this->query($serviceName);
416
+        });
417
+    }
418
+
419
+    public function has($id): bool {
420
+        if (parent::has($id)) {
421
+            return true;
422
+        }
423
+
424
+        if ($this->server->has($id, true)) {
425
+            return true;
426
+        }
427
+
428
+        return false;
429
+    }
430
+
431
+    public function query(string $name, bool $autoload = true) {
432
+        try {
433
+            return $this->queryNoFallback($name);
434
+        } catch (QueryException $firstException) {
435
+            try {
436
+                return $this->getServer()->query($name, $autoload);
437
+            } catch (QueryException $secondException) {
438
+                if ($firstException->getCode() === 1) {
439
+                    throw $secondException;
440
+                }
441
+                throw $firstException;
442
+            }
443
+        }
444
+    }
445
+
446
+    /**
447
+     * @param string $name
448
+     * @return mixed
449
+     * @throws QueryException if the query could not be resolved
450
+     */
451
+    public function queryNoFallback($name) {
452
+        $name = $this->sanitizeName($name);
453
+
454
+        if ($this->offsetExists($name)) {
455
+            return parent::query($name);
456
+        } elseif ($this['AppName'] === 'settings' && strpos($name, 'OC\\Settings\\') === 0) {
457
+            return parent::query($name);
458
+        } elseif ($this['AppName'] === 'core' && strpos($name, 'OC\\Core\\') === 0) {
459
+            return parent::query($name);
460
+        } elseif (strpos($name, \OC\AppFramework\App::buildAppNamespace($this['AppName']) . '\\') === 0) {
461
+            return parent::query($name);
462
+        }
463
+
464
+        throw new QueryException('Could not resolve ' . $name . '!' .
465
+            ' Class can not be instantiated', 1);
466
+    }
467 467
 }
Please login to merge, or discard this patch.