Completed
Push — stable9 ( 11047b...318578 )
by Lukas
20:03 queued 09:36
created
apps/user_ldap/command/setconfig.php 3 patches
Doc Comments   -2 removed lines patch added patch discarded remove patch
@@ -74,8 +74,6 @@
 block discarded – undo
74 74
 	/**
75 75
 	 * save the configuration value as provided
76 76
 	 * @param string $configID
77
-	 * @param string $configKey
78
-	 * @param string $configValue
79 77
 	 */
80 78
 	protected function setValue($configID, $key, $value) {
81 79
 		$configHolder = new Configuration($configID);
Please login to merge, or discard this patch.
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -34,53 +34,53 @@
 block discarded – undo
34 34
 
35 35
 class SetConfig extends Command {
36 36
 
37
-	protected function configure() {
38
-		$this
39
-			->setName('ldap:set-config')
40
-			->setDescription('modifies an LDAP configuration')
41
-			->addArgument(
42
-					'configID',
43
-					InputArgument::REQUIRED,
44
-					'the configuration ID'
45
-				     )
46
-			->addArgument(
47
-					'configKey',
48
-					InputArgument::REQUIRED,
49
-					'the configuration key'
50
-				     )
51
-			->addArgument(
52
-					'configValue',
53
-					InputArgument::REQUIRED,
54
-					'the new configuration value'
55
-				     )
56
-		;
57
-	}
37
+    protected function configure() {
38
+        $this
39
+            ->setName('ldap:set-config')
40
+            ->setDescription('modifies an LDAP configuration')
41
+            ->addArgument(
42
+                    'configID',
43
+                    InputArgument::REQUIRED,
44
+                    'the configuration ID'
45
+                        )
46
+            ->addArgument(
47
+                    'configKey',
48
+                    InputArgument::REQUIRED,
49
+                    'the configuration key'
50
+                        )
51
+            ->addArgument(
52
+                    'configValue',
53
+                    InputArgument::REQUIRED,
54
+                    'the new configuration value'
55
+                        )
56
+        ;
57
+    }
58 58
 
59
-	protected function execute(InputInterface $input, OutputInterface $output) {
60
-		$helper = new Helper();
61
-		$availableConfigs = $helper->getServerConfigurationPrefixes();
62
-		$configID = $input->getArgument('configID');
63
-		if(!in_array($configID, $availableConfigs)) {
64
-			$output->writeln("Invalid configID");
65
-			return;
66
-		}
59
+    protected function execute(InputInterface $input, OutputInterface $output) {
60
+        $helper = new Helper();
61
+        $availableConfigs = $helper->getServerConfigurationPrefixes();
62
+        $configID = $input->getArgument('configID');
63
+        if(!in_array($configID, $availableConfigs)) {
64
+            $output->writeln("Invalid configID");
65
+            return;
66
+        }
67 67
 
68
-		$this->setValue(
69
-			$configID,
70
-			$input->getArgument('configKey'),
71
-			$input->getArgument('configValue')
72
-		);
73
-	}
68
+        $this->setValue(
69
+            $configID,
70
+            $input->getArgument('configKey'),
71
+            $input->getArgument('configValue')
72
+        );
73
+    }
74 74
 
75
-	/**
76
-	 * save the configuration value as provided
77
-	 * @param string $configID
78
-	 * @param string $configKey
79
-	 * @param string $configValue
80
-	 */
81
-	protected function setValue($configID, $key, $value) {
82
-		$configHolder = new Configuration($configID);
83
-		$configHolder->$key = $value;
84
-		$configHolder->saveConfiguration();
85
-	}
75
+    /**
76
+     * save the configuration value as provided
77
+     * @param string $configID
78
+     * @param string $configKey
79
+     * @param string $configValue
80
+     */
81
+    protected function setValue($configID, $key, $value) {
82
+        $configHolder = new Configuration($configID);
83
+        $configHolder->$key = $value;
84
+        $configHolder->saveConfiguration();
85
+    }
86 86
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@
 block discarded – undo
60 60
 		$helper = new Helper();
61 61
 		$availableConfigs = $helper->getServerConfigurationPrefixes();
62 62
 		$configID = $input->getArgument('configID');
63
-		if(!in_array($configID, $availableConfigs)) {
63
+		if (!in_array($configID, $availableConfigs)) {
64 64
 			$output->writeln("Invalid configID");
65 65
 			return;
66 66
 		}
Please login to merge, or discard this patch.
apps/user_ldap/lib/jobs.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -77,7 +77,7 @@
 block discarded – undo
77 77
 	}
78 78
 
79 79
 	/**
80
-	 * @return int
80
+	 * @return string
81 81
 	 */
82 82
 	static private function getRefreshInterval() {
83 83
 		//defaults to every hour
Please login to merge, or discard this patch.
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -33,183 +33,183 @@
 block discarded – undo
33 33
 use OCA\User_LDAP\Mapping\UserMapping;
34 34
 
35 35
 class Jobs extends \OC\BackgroundJob\TimedJob {
36
-	static private $groupsFromDB;
37
-
38
-	static private $groupBE;
39
-	static private $connector;
40
-
41
-	public function __construct(){
42
-		$this->interval = self::getRefreshInterval();
43
-	}
44
-
45
-	/**
46
-	 * @param mixed $argument
47
-	 */
48
-	public function run($argument){
49
-		Jobs::updateGroups();
50
-	}
51
-
52
-	static public function updateGroups() {
53
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
54
-
55
-		$knownGroups = array_keys(self::getKnownGroups());
56
-		$actualGroups = self::getGroupBE()->getGroups();
57
-
58
-		if(empty($actualGroups) && empty($knownGroups)) {
59
-			\OCP\Util::writeLog('user_ldap',
60
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
61
-				\OCP\Util::INFO);
62
-			return;
63
-		}
64
-
65
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
66
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
67
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
68
-
69
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
70
-	}
71
-
72
-	/**
73
-	 * @return int
74
-	 */
75
-	static private function getRefreshInterval() {
76
-		//defaults to every hour
77
-		return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
78
-	}
79
-
80
-	/**
81
-	 * @param string[] $groups
82
-	 */
83
-	static private function handleKnownGroups($groups) {
84
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
85
-		$query = \OCP\DB::prepare('
36
+    static private $groupsFromDB;
37
+
38
+    static private $groupBE;
39
+    static private $connector;
40
+
41
+    public function __construct(){
42
+        $this->interval = self::getRefreshInterval();
43
+    }
44
+
45
+    /**
46
+     * @param mixed $argument
47
+     */
48
+    public function run($argument){
49
+        Jobs::updateGroups();
50
+    }
51
+
52
+    static public function updateGroups() {
53
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
54
+
55
+        $knownGroups = array_keys(self::getKnownGroups());
56
+        $actualGroups = self::getGroupBE()->getGroups();
57
+
58
+        if(empty($actualGroups) && empty($knownGroups)) {
59
+            \OCP\Util::writeLog('user_ldap',
60
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
61
+                \OCP\Util::INFO);
62
+            return;
63
+        }
64
+
65
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
66
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
67
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
68
+
69
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
70
+    }
71
+
72
+    /**
73
+     * @return int
74
+     */
75
+    static private function getRefreshInterval() {
76
+        //defaults to every hour
77
+        return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
78
+    }
79
+
80
+    /**
81
+     * @param string[] $groups
82
+     */
83
+    static private function handleKnownGroups($groups) {
84
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
85
+        $query = \OCP\DB::prepare('
86 86
 			UPDATE `*PREFIX*ldap_group_members`
87 87
 			SET `owncloudusers` = ?
88 88
 			WHERE `owncloudname` = ?
89 89
 		');
90
-		foreach($groups as $group) {
91
-			//we assume, that self::$groupsFromDB has been retrieved already
92
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
93
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
94
-			$hasChanged = false;
95
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
96
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
97
-				\OCP\Util::writeLog('user_ldap',
98
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
99
-				\OCP\Util::INFO);
100
-				$hasChanged = true;
101
-			}
102
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
103
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
104
-				\OCP\Util::writeLog('user_ldap',
105
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
106
-				\OCP\Util::INFO);
107
-				$hasChanged = true;
108
-			}
109
-			if($hasChanged) {
110
-				$query->execute(array(serialize($actualUsers), $group));
111
-			}
112
-		}
113
-		\OCP\Util::writeLog('user_ldap',
114
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
115
-			\OCP\Util::DEBUG);
116
-	}
117
-
118
-	/**
119
-	 * @param string[] $createdGroups
120
-	 */
121
-	static private function handleCreatedGroups($createdGroups) {
122
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
123
-		$query = \OCP\DB::prepare('
90
+        foreach($groups as $group) {
91
+            //we assume, that self::$groupsFromDB has been retrieved already
92
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
93
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
94
+            $hasChanged = false;
95
+            foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
96
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
97
+                \OCP\Util::writeLog('user_ldap',
98
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
99
+                \OCP\Util::INFO);
100
+                $hasChanged = true;
101
+            }
102
+            foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
103
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
104
+                \OCP\Util::writeLog('user_ldap',
105
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
106
+                \OCP\Util::INFO);
107
+                $hasChanged = true;
108
+            }
109
+            if($hasChanged) {
110
+                $query->execute(array(serialize($actualUsers), $group));
111
+            }
112
+        }
113
+        \OCP\Util::writeLog('user_ldap',
114
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
115
+            \OCP\Util::DEBUG);
116
+    }
117
+
118
+    /**
119
+     * @param string[] $createdGroups
120
+     */
121
+    static private function handleCreatedGroups($createdGroups) {
122
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
123
+        $query = \OCP\DB::prepare('
124 124
 			INSERT
125 125
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
126 126
 			VALUES (?, ?)
127 127
 		');
128
-		foreach($createdGroups as $createdGroup) {
129
-			\OCP\Util::writeLog('user_ldap',
130
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
131
-				\OCP\Util::INFO);
132
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
133
-			$query->execute(array($createdGroup, $users));
134
-		}
135
-		\OCP\Util::writeLog('user_ldap',
136
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
137
-			\OCP\Util::DEBUG);
138
-	}
139
-
140
-	/**
141
-	 * @param string[] $removedGroups
142
-	 */
143
-	static private function handleRemovedGroups($removedGroups) {
144
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
145
-		$query = \OCP\DB::prepare('
128
+        foreach($createdGroups as $createdGroup) {
129
+            \OCP\Util::writeLog('user_ldap',
130
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
131
+                \OCP\Util::INFO);
132
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
133
+            $query->execute(array($createdGroup, $users));
134
+        }
135
+        \OCP\Util::writeLog('user_ldap',
136
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
137
+            \OCP\Util::DEBUG);
138
+    }
139
+
140
+    /**
141
+     * @param string[] $removedGroups
142
+     */
143
+    static private function handleRemovedGroups($removedGroups) {
144
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
145
+        $query = \OCP\DB::prepare('
146 146
 			DELETE
147 147
 			FROM `*PREFIX*ldap_group_members`
148 148
 			WHERE `owncloudname` = ?
149 149
 		');
150
-		foreach($removedGroups as $removedGroup) {
151
-			\OCP\Util::writeLog('user_ldap',
152
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
153
-				\OCP\Util::INFO);
154
-			$query->execute(array($removedGroup));
155
-		}
156
-		\OCP\Util::writeLog('user_ldap',
157
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
158
-			\OCP\Util::DEBUG);
159
-	}
160
-
161
-	/**
162
-	 * @return \OCA\user_ldap\GROUP_LDAP|\OCA\user_ldap\Group_Proxy
163
-	 */
164
-	static private function getGroupBE() {
165
-		if(!is_null(self::$groupBE)) {
166
-			return self::$groupBE;
167
-		}
168
-		$helper = new Helper();
169
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
170
-		$ldapWrapper = new LDAP();
171
-		if(count($configPrefixes) === 1) {
172
-			//avoid the proxy when there is only one LDAP server configured
173
-			$dbc = \OC::$server->getDatabaseConnection();
174
-			$userManager = new user\Manager(
175
-				\OC::$server->getConfig(),
176
-				new FilesystemHelper(),
177
-				new LogWrapper(),
178
-				\OC::$server->getAvatarManager(),
179
-				new \OCP\Image(),
180
-				$dbc,
181
-				\OC::$server->getUserManager());
182
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
183
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager);
184
-			$groupMapper = new GroupMapping($dbc);
185
-			$userMapper  = new UserMapping($dbc);
186
-			$ldapAccess->setGroupMapper($groupMapper);
187
-			$ldapAccess->setUserMapper($userMapper);
188
-			self::$groupBE = new \OCA\user_ldap\GROUP_LDAP($ldapAccess);
189
-		} else {
190
-			self::$groupBE = new \OCA\user_ldap\Group_Proxy($configPrefixes, $ldapWrapper);
191
-		}
192
-
193
-		return self::$groupBE;
194
-	}
195
-
196
-	/**
197
-	 * @return array
198
-	 */
199
-	static private function getKnownGroups() {
200
-		if(is_array(self::$groupsFromDB)) {
201
-			return self::$groupsFromDB;
202
-		}
203
-		$query = \OCP\DB::prepare('
150
+        foreach($removedGroups as $removedGroup) {
151
+            \OCP\Util::writeLog('user_ldap',
152
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
153
+                \OCP\Util::INFO);
154
+            $query->execute(array($removedGroup));
155
+        }
156
+        \OCP\Util::writeLog('user_ldap',
157
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
158
+            \OCP\Util::DEBUG);
159
+    }
160
+
161
+    /**
162
+     * @return \OCA\user_ldap\GROUP_LDAP|\OCA\user_ldap\Group_Proxy
163
+     */
164
+    static private function getGroupBE() {
165
+        if(!is_null(self::$groupBE)) {
166
+            return self::$groupBE;
167
+        }
168
+        $helper = new Helper();
169
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
170
+        $ldapWrapper = new LDAP();
171
+        if(count($configPrefixes) === 1) {
172
+            //avoid the proxy when there is only one LDAP server configured
173
+            $dbc = \OC::$server->getDatabaseConnection();
174
+            $userManager = new user\Manager(
175
+                \OC::$server->getConfig(),
176
+                new FilesystemHelper(),
177
+                new LogWrapper(),
178
+                \OC::$server->getAvatarManager(),
179
+                new \OCP\Image(),
180
+                $dbc,
181
+                \OC::$server->getUserManager());
182
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
183
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager);
184
+            $groupMapper = new GroupMapping($dbc);
185
+            $userMapper  = new UserMapping($dbc);
186
+            $ldapAccess->setGroupMapper($groupMapper);
187
+            $ldapAccess->setUserMapper($userMapper);
188
+            self::$groupBE = new \OCA\user_ldap\GROUP_LDAP($ldapAccess);
189
+        } else {
190
+            self::$groupBE = new \OCA\user_ldap\Group_Proxy($configPrefixes, $ldapWrapper);
191
+        }
192
+
193
+        return self::$groupBE;
194
+    }
195
+
196
+    /**
197
+     * @return array
198
+     */
199
+    static private function getKnownGroups() {
200
+        if(is_array(self::$groupsFromDB)) {
201
+            return self::$groupsFromDB;
202
+        }
203
+        $query = \OCP\DB::prepare('
204 204
 			SELECT `owncloudname`, `owncloudusers`
205 205
 			FROM `*PREFIX*ldap_group_members`
206 206
 		');
207
-		$result = $query->execute()->fetchAll();
208
-		self::$groupsFromDB = array();
209
-		foreach($result as $dataset) {
210
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
211
-		}
212
-
213
-		return self::$groupsFromDB;
214
-	}
207
+        $result = $query->execute()->fetchAll();
208
+        self::$groupsFromDB = array();
209
+        foreach($result as $dataset) {
210
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
211
+        }
212
+
213
+        return self::$groupsFromDB;
214
+    }
215 215
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -38,14 +38,14 @@  discard block
 block discarded – undo
38 38
 	static private $groupBE;
39 39
 	static private $connector;
40 40
 
41
-	public function __construct(){
41
+	public function __construct() {
42 42
 		$this->interval = self::getRefreshInterval();
43 43
 	}
44 44
 
45 45
 	/**
46 46
 	 * @param mixed $argument
47 47
 	 */
48
-	public function run($argument){
48
+	public function run($argument) {
49 49
 		Jobs::updateGroups();
50 50
 	}
51 51
 
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
 		$knownGroups = array_keys(self::getKnownGroups());
56 56
 		$actualGroups = self::getGroupBE()->getGroups();
57 57
 
58
-		if(empty($actualGroups) && empty($knownGroups)) {
58
+		if (empty($actualGroups) && empty($knownGroups)) {
59 59
 			\OCP\Util::writeLog('user_ldap',
60 60
 				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
61 61
 				\OCP\Util::INFO);
@@ -87,26 +87,26 @@  discard block
 block discarded – undo
87 87
 			SET `owncloudusers` = ?
88 88
 			WHERE `owncloudname` = ?
89 89
 		');
90
-		foreach($groups as $group) {
90
+		foreach ($groups as $group) {
91 91
 			//we assume, that self::$groupsFromDB has been retrieved already
92 92
 			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
93 93
 			$actualUsers = self::getGroupBE()->usersInGroup($group);
94 94
 			$hasChanged = false;
95
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
95
+			foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
96 96
 				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
97 97
 				\OCP\Util::writeLog('user_ldap',
98 98
 				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
99 99
 				\OCP\Util::INFO);
100 100
 				$hasChanged = true;
101 101
 			}
102
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
102
+			foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
103 103
 				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
104 104
 				\OCP\Util::writeLog('user_ldap',
105 105
 				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
106 106
 				\OCP\Util::INFO);
107 107
 				$hasChanged = true;
108 108
 			}
109
-			if($hasChanged) {
109
+			if ($hasChanged) {
110 110
 				$query->execute(array(serialize($actualUsers), $group));
111 111
 			}
112 112
 		}
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
126 126
 			VALUES (?, ?)
127 127
 		');
128
-		foreach($createdGroups as $createdGroup) {
128
+		foreach ($createdGroups as $createdGroup) {
129 129
 			\OCP\Util::writeLog('user_ldap',
130 130
 				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
131 131
 				\OCP\Util::INFO);
@@ -147,7 +147,7 @@  discard block
 block discarded – undo
147 147
 			FROM `*PREFIX*ldap_group_members`
148 148
 			WHERE `owncloudname` = ?
149 149
 		');
150
-		foreach($removedGroups as $removedGroup) {
150
+		foreach ($removedGroups as $removedGroup) {
151 151
 			\OCP\Util::writeLog('user_ldap',
152 152
 				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
153 153
 				\OCP\Util::INFO);
@@ -162,13 +162,13 @@  discard block
 block discarded – undo
162 162
 	 * @return \OCA\user_ldap\GROUP_LDAP|\OCA\user_ldap\Group_Proxy
163 163
 	 */
164 164
 	static private function getGroupBE() {
165
-		if(!is_null(self::$groupBE)) {
165
+		if (!is_null(self::$groupBE)) {
166 166
 			return self::$groupBE;
167 167
 		}
168 168
 		$helper = new Helper();
169 169
 		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
170 170
 		$ldapWrapper = new LDAP();
171
-		if(count($configPrefixes) === 1) {
171
+		if (count($configPrefixes) === 1) {
172 172
 			//avoid the proxy when there is only one LDAP server configured
173 173
 			$dbc = \OC::$server->getDatabaseConnection();
174 174
 			$userManager = new user\Manager(
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 	 * @return array
198 198
 	 */
199 199
 	static private function getKnownGroups() {
200
-		if(is_array(self::$groupsFromDB)) {
200
+		if (is_array(self::$groupsFromDB)) {
201 201
 			return self::$groupsFromDB;
202 202
 		}
203 203
 		$query = \OCP\DB::prepare('
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
 		');
207 207
 		$result = $query->execute()->fetchAll();
208 208
 		self::$groupsFromDB = array();
209
-		foreach($result as $dataset) {
209
+		foreach ($result as $dataset) {
210 210
 			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
211 211
 		}
212 212
 
Please login to merge, or discard this patch.
core/command/security/listcertificates.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -28,7 +28,6 @@
 block discarded – undo
28 28
 use Symfony\Component\Console\Command\Command;
29 29
 use Symfony\Component\Console\Helper\Table;
30 30
 use Symfony\Component\Console\Input\InputInterface;
31
-use Symfony\Component\Console\Input\InputOption;
32 31
 use Symfony\Component\Console\Output\OutputInterface;
33 32
 
34 33
 class ListCertificates extends Base {
Please login to merge, or discard this patch.
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -34,64 +34,64 @@
 block discarded – undo
34 34
 
35 35
 class ListCertificates extends Base {
36 36
 
37
-	/** @var ICertificateManager */
38
-	protected $certificateManager;
39
-	/** @var IL10N */
40
-	protected $l;
37
+    /** @var ICertificateManager */
38
+    protected $certificateManager;
39
+    /** @var IL10N */
40
+    protected $l;
41 41
 
42
-	public function __construct(ICertificateManager $certificateManager, IL10N $l) {
43
-		$this->certificateManager = $certificateManager;
44
-		$this->l = $l;
45
-		parent::__construct();
46
-	}
42
+    public function __construct(ICertificateManager $certificateManager, IL10N $l) {
43
+        $this->certificateManager = $certificateManager;
44
+        $this->l = $l;
45
+        parent::__construct();
46
+    }
47 47
 
48
-	protected function configure() {
49
-		$this
50
-			->setName('security:certificates')
51
-			->setDescription('list trusted certificates');
52
-		parent::configure();
53
-	}
48
+    protected function configure() {
49
+        $this
50
+            ->setName('security:certificates')
51
+            ->setDescription('list trusted certificates');
52
+        parent::configure();
53
+    }
54 54
 
55
-	protected function execute(InputInterface $input, OutputInterface $output) {
56
-		$outputType = $input->getOption('output');
57
-		if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
58
-			$certificates = array_map(function (ICertificate $certificate) {
59
-				return [
60
-					'name' => $certificate->getName(),
61
-					'common_name' => $certificate->getCommonName(),
62
-					'organization' => $certificate->getOrganization(),
63
-					'expire' => $certificate->getExpireDate()->format(\DateTime::ATOM),
64
-					'issuer' => $certificate->getIssuerName(),
65
-					'issuer_organization' => $certificate->getIssuerOrganization(),
66
-					'issue_date' => $certificate->getIssueDate()->format(\DateTime::ATOM)
67
-				];
68
-			}, $this->certificateManager->listCertificates());
69
-			if ($outputType === self::OUTPUT_FORMAT_JSON) {
70
-				$output->writeln(json_encode(array_values($certificates)));
71
-			} else {
72
-				$output->writeln(json_encode(array_values($certificates), JSON_PRETTY_PRINT));
73
-			}
74
-		} else {
75
-			$table = new Table($output);
76
-			$table->setHeaders([
77
-				'File Name',
78
-				'Common Name',
79
-				'Organization',
80
-				'Valid Until',
81
-				'Issued By'
82
-			]);
55
+    protected function execute(InputInterface $input, OutputInterface $output) {
56
+        $outputType = $input->getOption('output');
57
+        if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
58
+            $certificates = array_map(function (ICertificate $certificate) {
59
+                return [
60
+                    'name' => $certificate->getName(),
61
+                    'common_name' => $certificate->getCommonName(),
62
+                    'organization' => $certificate->getOrganization(),
63
+                    'expire' => $certificate->getExpireDate()->format(\DateTime::ATOM),
64
+                    'issuer' => $certificate->getIssuerName(),
65
+                    'issuer_organization' => $certificate->getIssuerOrganization(),
66
+                    'issue_date' => $certificate->getIssueDate()->format(\DateTime::ATOM)
67
+                ];
68
+            }, $this->certificateManager->listCertificates());
69
+            if ($outputType === self::OUTPUT_FORMAT_JSON) {
70
+                $output->writeln(json_encode(array_values($certificates)));
71
+            } else {
72
+                $output->writeln(json_encode(array_values($certificates), JSON_PRETTY_PRINT));
73
+            }
74
+        } else {
75
+            $table = new Table($output);
76
+            $table->setHeaders([
77
+                'File Name',
78
+                'Common Name',
79
+                'Organization',
80
+                'Valid Until',
81
+                'Issued By'
82
+            ]);
83 83
 
84
-			$rows = array_map(function (ICertificate $certificate) {
85
-				return [
86
-					$certificate->getName(),
87
-					$certificate->getCommonName(),
88
-					$certificate->getOrganization(),
89
-					$this->l->l('date', $certificate->getExpireDate()),
90
-					$certificate->getIssuerName()
91
-				];
92
-			}, $this->certificateManager->listCertificates());
93
-			$table->setRows($rows);
94
-			$table->render();
95
-		}
96
-	}
84
+            $rows = array_map(function (ICertificate $certificate) {
85
+                return [
86
+                    $certificate->getName(),
87
+                    $certificate->getCommonName(),
88
+                    $certificate->getOrganization(),
89
+                    $this->l->l('date', $certificate->getExpireDate()),
90
+                    $certificate->getIssuerName()
91
+                ];
92
+            }, $this->certificateManager->listCertificates());
93
+            $table->setRows($rows);
94
+            $table->render();
95
+        }
96
+    }
97 97
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
 	protected function execute(InputInterface $input, OutputInterface $output) {
56 56
 		$outputType = $input->getOption('output');
57 57
 		if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) {
58
-			$certificates = array_map(function (ICertificate $certificate) {
58
+			$certificates = array_map(function(ICertificate $certificate) {
59 59
 				return [
60 60
 					'name' => $certificate->getName(),
61 61
 					'common_name' => $certificate->getCommonName(),
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 				'Issued By'
82 82
 			]);
83 83
 
84
-			$rows = array_map(function (ICertificate $certificate) {
84
+			$rows = array_map(function(ICertificate $certificate) {
85 85
 				return [
86 86
 					$certificate->getName(),
87 87
 					$certificate->getCommonName(),
Please login to merge, or discard this patch.
core/controller/lostcontroller.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -132,7 +132,7 @@
 block discarded – undo
132 132
 	}
133 133
 
134 134
 	/**
135
-	 * @param $message
135
+	 * @param string $message
136 136
 	 * @param array $additional
137 137
 	 * @return array
138 138
 	 */
Please login to merge, or discard this patch.
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -50,209 +50,209 @@
 block discarded – undo
50 50
  */
51 51
 class LostController extends Controller {
52 52
 
53
-	/** @var IURLGenerator */
54
-	protected $urlGenerator;
55
-	/** @var IUserManager */
56
-	protected $userManager;
57
-	// FIXME: Inject a non-static factory of OC_Defaults for better unit-testing
58
-	/** @var OC_Defaults */
59
-	protected $defaults;
60
-	/** @var IL10N */
61
-	protected $l10n;
62
-	/** @var string */
63
-	protected $from;
64
-	/** @var bool */
65
-	protected $isDataEncrypted;
66
-	/** @var IConfig */
67
-	protected $config;
68
-	/** @var ISecureRandom */
69
-	protected $secureRandom;
70
-	/** @var IMailer */
71
-	protected $mailer;
72
-	/** @var ITimeFactory */
73
-	protected $timeFactory;
53
+    /** @var IURLGenerator */
54
+    protected $urlGenerator;
55
+    /** @var IUserManager */
56
+    protected $userManager;
57
+    // FIXME: Inject a non-static factory of OC_Defaults for better unit-testing
58
+    /** @var OC_Defaults */
59
+    protected $defaults;
60
+    /** @var IL10N */
61
+    protected $l10n;
62
+    /** @var string */
63
+    protected $from;
64
+    /** @var bool */
65
+    protected $isDataEncrypted;
66
+    /** @var IConfig */
67
+    protected $config;
68
+    /** @var ISecureRandom */
69
+    protected $secureRandom;
70
+    /** @var IMailer */
71
+    protected $mailer;
72
+    /** @var ITimeFactory */
73
+    protected $timeFactory;
74 74
 
75
-	/**
76
-	 * @param string $appName
77
-	 * @param IRequest $request
78
-	 * @param IURLGenerator $urlGenerator
79
-	 * @param IUserManager $userManager
80
-	 * @param OC_Defaults $defaults
81
-	 * @param IL10N $l10n
82
-	 * @param IConfig $config
83
-	 * @param ISecureRandom $secureRandom
84
-	 * @param string $from
85
-	 * @param string $isDataEncrypted
86
-	 * @param IMailer $mailer
87
-	 * @param ITimeFactory $timeFactory
88
-	 */
89
-	public function __construct($appName,
90
-								IRequest $request,
91
-								IURLGenerator $urlGenerator,
92
-								IUserManager $userManager,
93
-								OC_Defaults $defaults,
94
-								IL10N $l10n,
95
-								IConfig $config,
96
-								ISecureRandom $secureRandom,
97
-								$from,
98
-								$isDataEncrypted,
99
-								IMailer $mailer,
100
-								ITimeFactory $timeFactory) {
101
-		parent::__construct($appName, $request);
102
-		$this->urlGenerator = $urlGenerator;
103
-		$this->userManager = $userManager;
104
-		$this->defaults = $defaults;
105
-		$this->l10n = $l10n;
106
-		$this->secureRandom = $secureRandom;
107
-		$this->from = $from;
108
-		$this->isDataEncrypted = $isDataEncrypted;
109
-		$this->config = $config;
110
-		$this->mailer = $mailer;
111
-		$this->timeFactory = $timeFactory;
112
-	}
75
+    /**
76
+     * @param string $appName
77
+     * @param IRequest $request
78
+     * @param IURLGenerator $urlGenerator
79
+     * @param IUserManager $userManager
80
+     * @param OC_Defaults $defaults
81
+     * @param IL10N $l10n
82
+     * @param IConfig $config
83
+     * @param ISecureRandom $secureRandom
84
+     * @param string $from
85
+     * @param string $isDataEncrypted
86
+     * @param IMailer $mailer
87
+     * @param ITimeFactory $timeFactory
88
+     */
89
+    public function __construct($appName,
90
+                                IRequest $request,
91
+                                IURLGenerator $urlGenerator,
92
+                                IUserManager $userManager,
93
+                                OC_Defaults $defaults,
94
+                                IL10N $l10n,
95
+                                IConfig $config,
96
+                                ISecureRandom $secureRandom,
97
+                                $from,
98
+                                $isDataEncrypted,
99
+                                IMailer $mailer,
100
+                                ITimeFactory $timeFactory) {
101
+        parent::__construct($appName, $request);
102
+        $this->urlGenerator = $urlGenerator;
103
+        $this->userManager = $userManager;
104
+        $this->defaults = $defaults;
105
+        $this->l10n = $l10n;
106
+        $this->secureRandom = $secureRandom;
107
+        $this->from = $from;
108
+        $this->isDataEncrypted = $isDataEncrypted;
109
+        $this->config = $config;
110
+        $this->mailer = $mailer;
111
+        $this->timeFactory = $timeFactory;
112
+    }
113 113
 
114
-	/**
115
-	 * Someone wants to reset their password:
116
-	 *
117
-	 * @PublicPage
118
-	 * @NoCSRFRequired
119
-	 *
120
-	 * @param string $token
121
-	 * @param string $userId
122
-	 * @return TemplateResponse
123
-	 */
124
-	public function resetform($token, $userId) {
125
-		return new TemplateResponse(
126
-			'core',
127
-			'lostpassword/resetpassword',
128
-			array(
129
-				'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
130
-			),
131
-			'guest'
132
-		);
133
-	}
114
+    /**
115
+     * Someone wants to reset their password:
116
+     *
117
+     * @PublicPage
118
+     * @NoCSRFRequired
119
+     *
120
+     * @param string $token
121
+     * @param string $userId
122
+     * @return TemplateResponse
123
+     */
124
+    public function resetform($token, $userId) {
125
+        return new TemplateResponse(
126
+            'core',
127
+            'lostpassword/resetpassword',
128
+            array(
129
+                'link' => $this->urlGenerator->linkToRouteAbsolute('core.lost.setPassword', array('userId' => $userId, 'token' => $token)),
130
+            ),
131
+            'guest'
132
+        );
133
+    }
134 134
 
135
-	/**
136
-	 * @param $message
137
-	 * @param array $additional
138
-	 * @return array
139
-	 */
140
-	private function error($message, array $additional=array()) {
141
-		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
142
-	}
135
+    /**
136
+     * @param $message
137
+     * @param array $additional
138
+     * @return array
139
+     */
140
+    private function error($message, array $additional=array()) {
141
+        return array_merge(array('status' => 'error', 'msg' => $message), $additional);
142
+    }
143 143
 
144
-	/**
145
-	 * @return array
146
-	 */
147
-	private function success() {
148
-		return array('status'=>'success');
149
-	}
144
+    /**
145
+     * @return array
146
+     */
147
+    private function success() {
148
+        return array('status'=>'success');
149
+    }
150 150
 
151
-	/**
152
-	 * @PublicPage
153
-	 *
154
-	 * @param string $user
155
-	 * @return array
156
-	 */
157
-	public function email($user){
158
-		// FIXME: use HTTP error codes
159
-		try {
160
-			$this->sendEmail($user);
161
-		} catch (\Exception $e){
162
-			return $this->error($e->getMessage());
163
-		}
151
+    /**
152
+     * @PublicPage
153
+     *
154
+     * @param string $user
155
+     * @return array
156
+     */
157
+    public function email($user){
158
+        // FIXME: use HTTP error codes
159
+        try {
160
+            $this->sendEmail($user);
161
+        } catch (\Exception $e){
162
+            return $this->error($e->getMessage());
163
+        }
164 164
 
165
-		return $this->success();
166
-	}
165
+        return $this->success();
166
+    }
167 167
 
168
-	/**
169
-	 * @PublicPage
170
-	 * @param string $token
171
-	 * @param string $userId
172
-	 * @param string $password
173
-	 * @param boolean $proceed
174
-	 * @return array
175
-	 */
176
-	public function setPassword($token, $userId, $password, $proceed) {
177
-		if ($this->isDataEncrypted && !$proceed) {
178
-			return $this->error('', array('encryption' => true));
179
-		}
168
+    /**
169
+     * @PublicPage
170
+     * @param string $token
171
+     * @param string $userId
172
+     * @param string $password
173
+     * @param boolean $proceed
174
+     * @return array
175
+     */
176
+    public function setPassword($token, $userId, $password, $proceed) {
177
+        if ($this->isDataEncrypted && !$proceed) {
178
+            return $this->error('', array('encryption' => true));
179
+        }
180 180
 
181
-		try {
182
-			$user = $this->userManager->get($userId);
181
+        try {
182
+            $user = $this->userManager->get($userId);
183 183
 
184
-			$splittedToken = explode(':', $this->config->getUserValue($userId, 'owncloud', 'lostpassword', null));
185
-			if(count($splittedToken) !== 2) {
186
-				throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187
-			}
184
+            $splittedToken = explode(':', $this->config->getUserValue($userId, 'owncloud', 'lostpassword', null));
185
+            if(count($splittedToken) !== 2) {
186
+                throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187
+            }
188 188
 
189
-			if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
190
-				$user->getLastLogin() > $splittedToken[0]) {
191
-				throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
192
-			}
189
+            if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
190
+                $user->getLastLogin() > $splittedToken[0]) {
191
+                throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
192
+            }
193 193
 
194
-			if (!StringUtils::equals($splittedToken[1], $token)) {
195
-				throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
196
-			}
194
+            if (!StringUtils::equals($splittedToken[1], $token)) {
195
+                throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
196
+            }
197 197
 
198
-			if (!$user->setPassword($password)) {
199
-				throw new \Exception();
200
-			}
198
+            if (!$user->setPassword($password)) {
199
+                throw new \Exception();
200
+            }
201 201
 
202
-			\OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
202
+            \OC_Hook::emit('\OC\Core\LostPassword\Controller\LostController', 'post_passwordReset', array('uid' => $userId, 'password' => $password));
203 203
 
204
-			$this->config->deleteUserValue($userId, 'owncloud', 'lostpassword');
205
-			@\OC_User::unsetMagicInCookie();
204
+            $this->config->deleteUserValue($userId, 'owncloud', 'lostpassword');
205
+            @\OC_User::unsetMagicInCookie();
206 206
 
207
-		} catch (\Exception $e){
208
-			return $this->error($e->getMessage());
209
-		}
207
+        } catch (\Exception $e){
208
+            return $this->error($e->getMessage());
209
+        }
210 210
 
211
-		return $this->success();
212
-	}
211
+        return $this->success();
212
+    }
213 213
 
214
-	/**
215
-	 * @param string $user
216
-	 * @throws \Exception
217
-	 */
218
-	protected function sendEmail($user) {
219
-		if (!$this->userManager->userExists($user)) {
220
-			throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
221
-		}
214
+    /**
215
+     * @param string $user
216
+     * @throws \Exception
217
+     */
218
+    protected function sendEmail($user) {
219
+        if (!$this->userManager->userExists($user)) {
220
+            throw new \Exception($this->l10n->t('Couldn\'t send reset email. Please make sure your username is correct.'));
221
+        }
222 222
 
223
-		$userObject = $this->userManager->get($user);
224
-		$email = $userObject->getEMailAddress();
223
+        $userObject = $this->userManager->get($user);
224
+        $email = $userObject->getEMailAddress();
225 225
 
226
-		if (empty($email)) {
227
-			throw new \Exception(
228
-				$this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
229
-			);
230
-		}
226
+        if (empty($email)) {
227
+            throw new \Exception(
228
+                $this->l10n->t('Could not send reset email because there is no email address for this username. Please contact your administrator.')
229
+            );
230
+        }
231 231
 
232
-		$token = $this->secureRandom->generate(21,
233
-			ISecureRandom::CHAR_DIGITS.
234
-			ISecureRandom::CHAR_LOWER.
235
-			ISecureRandom::CHAR_UPPER);
236
-		$this->config->setUserValue($user, 'owncloud', 'lostpassword', $this->timeFactory->getTime() .':'. $token);
232
+        $token = $this->secureRandom->generate(21,
233
+            ISecureRandom::CHAR_DIGITS.
234
+            ISecureRandom::CHAR_LOWER.
235
+            ISecureRandom::CHAR_UPPER);
236
+        $this->config->setUserValue($user, 'owncloud', 'lostpassword', $this->timeFactory->getTime() .':'. $token);
237 237
 
238
-		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
238
+        $link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
239 239
 
240
-		$tmpl = new \OC_Template('core', 'lostpassword/email');
241
-		$tmpl->assign('link', $link);
242
-		$msg = $tmpl->fetchPage();
240
+        $tmpl = new \OC_Template('core', 'lostpassword/email');
241
+        $tmpl->assign('link', $link);
242
+        $msg = $tmpl->fetchPage();
243 243
 
244
-		try {
245
-			$message = $this->mailer->createMessage();
246
-			$message->setTo([$email => $user]);
247
-			$message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
248
-			$message->setPlainBody($msg);
249
-			$message->setFrom([$this->from => $this->defaults->getName()]);
250
-			$this->mailer->send($message);
251
-		} catch (\Exception $e) {
252
-			throw new \Exception($this->l10n->t(
253
-				'Couldn\'t send reset email. Please contact your administrator.'
254
-			));
255
-		}
256
-	}
244
+        try {
245
+            $message = $this->mailer->createMessage();
246
+            $message->setTo([$email => $user]);
247
+            $message->setSubject($this->l10n->t('%s password reset', [$this->defaults->getName()]));
248
+            $message->setPlainBody($msg);
249
+            $message->setFrom([$this->from => $this->defaults->getName()]);
250
+            $this->mailer->send($message);
251
+        } catch (\Exception $e) {
252
+            throw new \Exception($this->l10n->t(
253
+                'Couldn\'t send reset email. Please contact your administrator.'
254
+            ));
255
+        }
256
+    }
257 257
 
258 258
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @param array $additional
138 138
 	 * @return array
139 139
 	 */
140
-	private function error($message, array $additional=array()) {
140
+	private function error($message, array $additional = array()) {
141 141
 		return array_merge(array('status' => 'error', 'msg' => $message), $additional);
142 142
 	}
143 143
 
@@ -154,11 +154,11 @@  discard block
 block discarded – undo
154 154
 	 * @param string $user
155 155
 	 * @return array
156 156
 	 */
157
-	public function email($user){
157
+	public function email($user) {
158 158
 		// FIXME: use HTTP error codes
159 159
 		try {
160 160
 			$this->sendEmail($user);
161
-		} catch (\Exception $e){
161
+		} catch (\Exception $e) {
162 162
 			return $this->error($e->getMessage());
163 163
 		}
164 164
 
@@ -182,11 +182,11 @@  discard block
 block discarded – undo
182 182
 			$user = $this->userManager->get($userId);
183 183
 
184 184
 			$splittedToken = explode(':', $this->config->getUserValue($userId, 'owncloud', 'lostpassword', null));
185
-			if(count($splittedToken) !== 2) {
185
+			if (count($splittedToken) !== 2) {
186 186
 				throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is invalid'));
187 187
 			}
188 188
 
189
-			if ($splittedToken[0] < ($this->timeFactory->getTime() - 60*60*12) ||
189
+			if ($splittedToken[0] < ($this->timeFactory->getTime() - 60 * 60 * 12) ||
190 190
 				$user->getLastLogin() > $splittedToken[0]) {
191 191
 				throw new \Exception($this->l10n->t('Couldn\'t reset password because the token is expired'));
192 192
 			}
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 			$this->config->deleteUserValue($userId, 'owncloud', 'lostpassword');
205 205
 			@\OC_User::unsetMagicInCookie();
206 206
 
207
-		} catch (\Exception $e){
207
+		} catch (\Exception $e) {
208 208
 			return $this->error($e->getMessage());
209 209
 		}
210 210
 
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
 			ISecureRandom::CHAR_DIGITS.
234 234
 			ISecureRandom::CHAR_LOWER.
235 235
 			ISecureRandom::CHAR_UPPER);
236
-		$this->config->setUserValue($user, 'owncloud', 'lostpassword', $this->timeFactory->getTime() .':'. $token);
236
+		$this->config->setUserValue($user, 'owncloud', 'lostpassword', $this->timeFactory->getTime().':'.$token);
237 237
 
238 238
 		$link = $this->urlGenerator->linkToRouteAbsolute('core.lost.resetform', array('userId' => $user, 'token' => $token));
239 239
 
Please login to merge, or discard this patch.
lib/private/allconfig.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -112,7 +112,7 @@
 block discarded – undo
112 112
 	 * Looks up a system wide defined value
113 113
 	 *
114 114
 	 * @param string $key the key of the value, under which it was saved
115
-	 * @param mixed $default the default value to be returned if the value isn't set
115
+	 * @param string $default the default value to be returned if the value isn't set
116 116
 	 * @return mixed the value or $default
117 117
 	 */
118 118
 	public function getSystemValue($key, $default = '') {
Please login to merge, or discard this patch.
Indentation   +388 added lines, -388 removed lines patch added patch discarded remove patch
@@ -37,392 +37,392 @@
 block discarded – undo
37 37
  * Class to combine all the configuration options ownCloud offers
38 38
  */
39 39
 class AllConfig implements \OCP\IConfig {
40
-	/** @var SystemConfig */
41
-	private $systemConfig;
42
-
43
-	/** @var IDBConnection */
44
-	private $connection;
45
-
46
-	/**
47
-	 * 3 dimensional array with the following structure:
48
-	 * [ $userId =>
49
-	 *     [ $appId =>
50
-	 *         [ $key => $value ]
51
-	 *     ]
52
-	 * ]
53
-	 *
54
-	 * database table: preferences
55
-	 *
56
-	 * methods that use this:
57
-	 *   - setUserValue
58
-	 *   - getUserValue
59
-	 *   - getUserKeys
60
-	 *   - deleteUserValue
61
-	 *   - deleteAllUserValues
62
-	 *   - deleteAppFromAllUsers
63
-	 *
64
-	 * @var CappedMemoryCache $userCache
65
-	 */
66
-	private $userCache;
67
-
68
-	/**
69
-	 * @param SystemConfig $systemConfig
70
-	 */
71
-	function __construct(SystemConfig $systemConfig) {
72
-		$this->userCache = new CappedMemoryCache();
73
-		$this->systemConfig = $systemConfig;
74
-	}
75
-
76
-	/**
77
-	 * TODO - FIXME This fixes an issue with base.php that cause cyclic
78
-	 * dependencies, especially with autoconfig setup
79
-	 *
80
-	 * Replace this by properly injected database connection. Currently the
81
-	 * base.php triggers the getDatabaseConnection too early which causes in
82
-	 * autoconfig setup case a too early distributed database connection and
83
-	 * the autoconfig then needs to reinit all already initialized dependencies
84
-	 * that use the database connection.
85
-	 *
86
-	 * otherwise a SQLite database is created in the wrong directory
87
-	 * because the database connection was created with an uninitialized config
88
-	 */
89
-	private function fixDIInit() {
90
-		if($this->connection === null) {
91
-			$this->connection = \OC::$server->getDatabaseConnection();
92
-		}
93
-	}
94
-
95
-	/**
96
-	 * Sets and deletes system wide values
97
-	 *
98
-	 * @param array $configs Associative array with `key => value` pairs
99
-	 *                       If value is null, the config key will be deleted
100
-	 */
101
-	public function setSystemValues(array $configs) {
102
-		$this->systemConfig->setValues($configs);
103
-	}
104
-
105
-	/**
106
-	 * Sets a new system wide value
107
-	 *
108
-	 * @param string $key the key of the value, under which will be saved
109
-	 * @param mixed $value the value that should be stored
110
-	 */
111
-	public function setSystemValue($key, $value) {
112
-		$this->systemConfig->setValue($key, $value);
113
-	}
114
-
115
-	/**
116
-	 * Looks up a system wide defined value
117
-	 *
118
-	 * @param string $key the key of the value, under which it was saved
119
-	 * @param mixed $default the default value to be returned if the value isn't set
120
-	 * @return mixed the value or $default
121
-	 */
122
-	public function getSystemValue($key, $default = '') {
123
-		return $this->systemConfig->getValue($key, $default);
124
-	}
125
-
126
-	/**
127
-	 * Looks up a system wide defined value and filters out sensitive data
128
-	 *
129
-	 * @param string $key the key of the value, under which it was saved
130
-	 * @param mixed $default the default value to be returned if the value isn't set
131
-	 * @return mixed the value or $default
132
-	 */
133
-	public function getFilteredSystemValue($key, $default = '') {
134
-		return $this->systemConfig->getFilteredValue($key, $default);
135
-	}
136
-
137
-	/**
138
-	 * Delete a system wide defined value
139
-	 *
140
-	 * @param string $key the key of the value, under which it was saved
141
-	 */
142
-	public function deleteSystemValue($key) {
143
-		$this->systemConfig->deleteValue($key);
144
-	}
145
-
146
-	/**
147
-	 * Get all keys stored for an app
148
-	 *
149
-	 * @param string $appName the appName that we stored the value under
150
-	 * @return string[] the keys stored for the app
151
-	 */
152
-	public function getAppKeys($appName) {
153
-		return \OC::$server->getAppConfig()->getKeys($appName);
154
-	}
155
-
156
-	/**
157
-	 * Writes a new app wide value
158
-	 *
159
-	 * @param string $appName the appName that we want to store the value under
160
-	 * @param string $key the key of the value, under which will be saved
161
-	 * @param string $value the value that should be stored
162
-	 */
163
-	public function setAppValue($appName, $key, $value) {
164
-		\OC::$server->getAppConfig()->setValue($appName, $key, $value);
165
-	}
166
-
167
-	/**
168
-	 * Looks up an app wide defined value
169
-	 *
170
-	 * @param string $appName the appName that we stored the value under
171
-	 * @param string $key the key of the value, under which it was saved
172
-	 * @param string $default the default value to be returned if the value isn't set
173
-	 * @return string the saved value
174
-	 */
175
-	public function getAppValue($appName, $key, $default = '') {
176
-		return \OC::$server->getAppConfig()->getValue($appName, $key, $default);
177
-	}
178
-
179
-	/**
180
-	 * Delete an app wide defined value
181
-	 *
182
-	 * @param string $appName the appName that we stored the value under
183
-	 * @param string $key the key of the value, under which it was saved
184
-	 */
185
-	public function deleteAppValue($appName, $key) {
186
-		\OC::$server->getAppConfig()->deleteKey($appName, $key);
187
-	}
188
-
189
-	/**
190
-	 * Removes all keys in appconfig belonging to the app
191
-	 *
192
-	 * @param string $appName the appName the configs are stored under
193
-	 */
194
-	public function deleteAppValues($appName) {
195
-		\OC::$server->getAppConfig()->deleteApp($appName);
196
-	}
197
-
198
-
199
-	/**
200
-	 * Set a user defined value
201
-	 *
202
-	 * @param string $userId the userId of the user that we want to store the value under
203
-	 * @param string $appName the appName that we want to store the value under
204
-	 * @param string $key the key under which the value is being stored
205
-	 * @param string $value the value that you want to store
206
-	 * @param string $preCondition only update if the config value was previously the value passed as $preCondition
207
-	 * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
208
-	 */
209
-	public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
210
-		// TODO - FIXME
211
-		$this->fixDIInit();
212
-
213
-		$preconditionArray = [];
214
-		if (isset($preCondition)) {
215
-			$preconditionArray = [
216
-				'configvalue' => $preCondition,
217
-			];
218
-		}
219
-
220
-		$this->connection->setValues('preferences', [
221
-			'userid' => $userId,
222
-			'appid' => $appName,
223
-			'configkey' => $key,
224
-		], [
225
-			'configvalue' => $value,
226
-		], $preconditionArray);
227
-
228
-		// only add to the cache if we already loaded data for the user
229
-		if (isset($this->userCache[$userId])) {
230
-			if (!isset($this->userCache[$userId][$appName])) {
231
-				$this->userCache[$userId][$appName] = array();
232
-			}
233
-			$this->userCache[$userId][$appName][$key] = $value;
234
-		}
235
-	}
236
-
237
-	/**
238
-	 * Getting a user defined value
239
-	 *
240
-	 * @param string $userId the userId of the user that we want to store the value under
241
-	 * @param string $appName the appName that we stored the value under
242
-	 * @param string $key the key under which the value is being stored
243
-	 * @param mixed $default the default value to be returned if the value isn't set
244
-	 * @return string
245
-	 */
246
-	public function getUserValue($userId, $appName, $key, $default = '') {
247
-		$data = $this->getUserValues($userId);
248
-		if (isset($data[$appName]) and isset($data[$appName][$key])) {
249
-			return $data[$appName][$key];
250
-		} else {
251
-			return $default;
252
-		}
253
-	}
254
-
255
-	/**
256
-	 * Get the keys of all stored by an app for the user
257
-	 *
258
-	 * @param string $userId the userId of the user that we want to store the value under
259
-	 * @param string $appName the appName that we stored the value under
260
-	 * @return string[]
261
-	 */
262
-	public function getUserKeys($userId, $appName) {
263
-		$data = $this->getUserValues($userId);
264
-		if (isset($data[$appName])) {
265
-			return array_keys($data[$appName]);
266
-		} else {
267
-			return array();
268
-		}
269
-	}
270
-
271
-	/**
272
-	 * Delete a user value
273
-	 *
274
-	 * @param string $userId the userId of the user that we want to store the value under
275
-	 * @param string $appName the appName that we stored the value under
276
-	 * @param string $key the key under which the value is being stored
277
-	 */
278
-	public function deleteUserValue($userId, $appName, $key) {
279
-		// TODO - FIXME
280
-		$this->fixDIInit();
281
-
282
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
283
-				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
284
-		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
285
-
286
-		if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
287
-			unset($this->userCache[$userId][$appName][$key]);
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * Delete all user values
293
-	 *
294
-	 * @param string $userId the userId of the user that we want to remove all values from
295
-	 */
296
-	public function deleteAllUserValues($userId) {
297
-		// TODO - FIXME
298
-		$this->fixDIInit();
299
-
300
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
301
-			'WHERE `userid` = ?';
302
-		$this->connection->executeUpdate($sql, array($userId));
303
-
304
-		unset($this->userCache[$userId]);
305
-	}
306
-
307
-	/**
308
-	 * Delete all user related values of one app
309
-	 *
310
-	 * @param string $appName the appName of the app that we want to remove all values from
311
-	 */
312
-	public function deleteAppFromAllUsers($appName) {
313
-		// TODO - FIXME
314
-		$this->fixDIInit();
315
-
316
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
317
-				'WHERE `appid` = ?';
318
-		$this->connection->executeUpdate($sql, array($appName));
319
-
320
-		foreach ($this->userCache as &$userCache) {
321
-			unset($userCache[$appName]);
322
-		}
323
-	}
324
-
325
-	/**
326
-	 * Returns all user configs sorted by app of one user
327
-	 *
328
-	 * @param string $userId the user ID to get the app configs from
329
-	 * @return array[] - 2 dimensional array with the following structure:
330
-	 *     [ $appId =>
331
-	 *         [ $key => $value ]
332
-	 *     ]
333
-	 */
334
-	private function getUserValues($userId) {
335
-		// TODO - FIXME
336
-		$this->fixDIInit();
337
-
338
-		if (isset($this->userCache[$userId])) {
339
-			return $this->userCache[$userId];
340
-		}
341
-		$data = array();
342
-		$query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
343
-		$result = $this->connection->executeQuery($query, array($userId));
344
-		while ($row = $result->fetch()) {
345
-			$appId = $row['appid'];
346
-			if (!isset($data[$appId])) {
347
-				$data[$appId] = array();
348
-			}
349
-			$data[$appId][$row['configkey']] = $row['configvalue'];
350
-		}
351
-		$this->userCache[$userId] = $data;
352
-		return $data;
353
-	}
354
-
355
-	/**
356
-	 * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
357
-	 *
358
-	 * @param string $appName app to get the value for
359
-	 * @param string $key the key to get the value for
360
-	 * @param array $userIds the user IDs to fetch the values for
361
-	 * @return array Mapped values: userId => value
362
-	 */
363
-	public function getUserValueForUsers($appName, $key, $userIds) {
364
-		// TODO - FIXME
365
-		$this->fixDIInit();
366
-
367
-		if (empty($userIds) || !is_array($userIds)) {
368
-			return array();
369
-		}
370
-
371
-		$chunkedUsers = array_chunk($userIds, 50, true);
372
-		$placeholders50 = implode(',', array_fill(0, 50, '?'));
373
-
374
-		$userValues = array();
375
-		foreach ($chunkedUsers as $chunk) {
376
-			$queryParams = $chunk;
377
-			// create [$app, $key, $chunkedUsers]
378
-			array_unshift($queryParams, $key);
379
-			array_unshift($queryParams, $appName);
380
-
381
-			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
382
-
383
-			$query    = 'SELECT `userid`, `configvalue` ' .
384
-						'FROM `*PREFIX*preferences` ' .
385
-						'WHERE `appid` = ? AND `configkey` = ? ' .
386
-						'AND `userid` IN (' . $placeholders . ')';
387
-			$result = $this->connection->executeQuery($query, $queryParams);
388
-
389
-			while ($row = $result->fetch()) {
390
-				$userValues[$row['userid']] = $row['configvalue'];
391
-			}
392
-		}
393
-
394
-		return $userValues;
395
-	}
396
-
397
-	/**
398
-	 * Determines the users that have the given value set for a specific app-key-pair
399
-	 *
400
-	 * @param string $appName the app to get the user for
401
-	 * @param string $key the key to get the user for
402
-	 * @param string $value the value to get the user for
403
-	 * @return array of user IDs
404
-	 */
405
-	public function getUsersForUserValue($appName, $key, $value) {
406
-		// TODO - FIXME
407
-		$this->fixDIInit();
408
-
409
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
410
-				'WHERE `appid` = ? AND `configkey` = ? ';
411
-
412
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
413
-			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
414
-			$sql .= 'AND to_char(`configvalue`) = ?';
415
-		} else {
416
-			$sql .= 'AND `configvalue` = ?';
417
-		}
418
-
419
-		$result = $this->connection->executeQuery($sql, array($appName, $key, $value));
420
-
421
-		$userIDs = array();
422
-		while ($row = $result->fetch()) {
423
-			$userIDs[] = $row['userid'];
424
-		}
425
-
426
-		return $userIDs;
427
-	}
40
+    /** @var SystemConfig */
41
+    private $systemConfig;
42
+
43
+    /** @var IDBConnection */
44
+    private $connection;
45
+
46
+    /**
47
+     * 3 dimensional array with the following structure:
48
+     * [ $userId =>
49
+     *     [ $appId =>
50
+     *         [ $key => $value ]
51
+     *     ]
52
+     * ]
53
+     *
54
+     * database table: preferences
55
+     *
56
+     * methods that use this:
57
+     *   - setUserValue
58
+     *   - getUserValue
59
+     *   - getUserKeys
60
+     *   - deleteUserValue
61
+     *   - deleteAllUserValues
62
+     *   - deleteAppFromAllUsers
63
+     *
64
+     * @var CappedMemoryCache $userCache
65
+     */
66
+    private $userCache;
67
+
68
+    /**
69
+     * @param SystemConfig $systemConfig
70
+     */
71
+    function __construct(SystemConfig $systemConfig) {
72
+        $this->userCache = new CappedMemoryCache();
73
+        $this->systemConfig = $systemConfig;
74
+    }
75
+
76
+    /**
77
+     * TODO - FIXME This fixes an issue with base.php that cause cyclic
78
+     * dependencies, especially with autoconfig setup
79
+     *
80
+     * Replace this by properly injected database connection. Currently the
81
+     * base.php triggers the getDatabaseConnection too early which causes in
82
+     * autoconfig setup case a too early distributed database connection and
83
+     * the autoconfig then needs to reinit all already initialized dependencies
84
+     * that use the database connection.
85
+     *
86
+     * otherwise a SQLite database is created in the wrong directory
87
+     * because the database connection was created with an uninitialized config
88
+     */
89
+    private function fixDIInit() {
90
+        if($this->connection === null) {
91
+            $this->connection = \OC::$server->getDatabaseConnection();
92
+        }
93
+    }
94
+
95
+    /**
96
+     * Sets and deletes system wide values
97
+     *
98
+     * @param array $configs Associative array with `key => value` pairs
99
+     *                       If value is null, the config key will be deleted
100
+     */
101
+    public function setSystemValues(array $configs) {
102
+        $this->systemConfig->setValues($configs);
103
+    }
104
+
105
+    /**
106
+     * Sets a new system wide value
107
+     *
108
+     * @param string $key the key of the value, under which will be saved
109
+     * @param mixed $value the value that should be stored
110
+     */
111
+    public function setSystemValue($key, $value) {
112
+        $this->systemConfig->setValue($key, $value);
113
+    }
114
+
115
+    /**
116
+     * Looks up a system wide defined value
117
+     *
118
+     * @param string $key the key of the value, under which it was saved
119
+     * @param mixed $default the default value to be returned if the value isn't set
120
+     * @return mixed the value or $default
121
+     */
122
+    public function getSystemValue($key, $default = '') {
123
+        return $this->systemConfig->getValue($key, $default);
124
+    }
125
+
126
+    /**
127
+     * Looks up a system wide defined value and filters out sensitive data
128
+     *
129
+     * @param string $key the key of the value, under which it was saved
130
+     * @param mixed $default the default value to be returned if the value isn't set
131
+     * @return mixed the value or $default
132
+     */
133
+    public function getFilteredSystemValue($key, $default = '') {
134
+        return $this->systemConfig->getFilteredValue($key, $default);
135
+    }
136
+
137
+    /**
138
+     * Delete a system wide defined value
139
+     *
140
+     * @param string $key the key of the value, under which it was saved
141
+     */
142
+    public function deleteSystemValue($key) {
143
+        $this->systemConfig->deleteValue($key);
144
+    }
145
+
146
+    /**
147
+     * Get all keys stored for an app
148
+     *
149
+     * @param string $appName the appName that we stored the value under
150
+     * @return string[] the keys stored for the app
151
+     */
152
+    public function getAppKeys($appName) {
153
+        return \OC::$server->getAppConfig()->getKeys($appName);
154
+    }
155
+
156
+    /**
157
+     * Writes a new app wide value
158
+     *
159
+     * @param string $appName the appName that we want to store the value under
160
+     * @param string $key the key of the value, under which will be saved
161
+     * @param string $value the value that should be stored
162
+     */
163
+    public function setAppValue($appName, $key, $value) {
164
+        \OC::$server->getAppConfig()->setValue($appName, $key, $value);
165
+    }
166
+
167
+    /**
168
+     * Looks up an app wide defined value
169
+     *
170
+     * @param string $appName the appName that we stored the value under
171
+     * @param string $key the key of the value, under which it was saved
172
+     * @param string $default the default value to be returned if the value isn't set
173
+     * @return string the saved value
174
+     */
175
+    public function getAppValue($appName, $key, $default = '') {
176
+        return \OC::$server->getAppConfig()->getValue($appName, $key, $default);
177
+    }
178
+
179
+    /**
180
+     * Delete an app wide defined value
181
+     *
182
+     * @param string $appName the appName that we stored the value under
183
+     * @param string $key the key of the value, under which it was saved
184
+     */
185
+    public function deleteAppValue($appName, $key) {
186
+        \OC::$server->getAppConfig()->deleteKey($appName, $key);
187
+    }
188
+
189
+    /**
190
+     * Removes all keys in appconfig belonging to the app
191
+     *
192
+     * @param string $appName the appName the configs are stored under
193
+     */
194
+    public function deleteAppValues($appName) {
195
+        \OC::$server->getAppConfig()->deleteApp($appName);
196
+    }
197
+
198
+
199
+    /**
200
+     * Set a user defined value
201
+     *
202
+     * @param string $userId the userId of the user that we want to store the value under
203
+     * @param string $appName the appName that we want to store the value under
204
+     * @param string $key the key under which the value is being stored
205
+     * @param string $value the value that you want to store
206
+     * @param string $preCondition only update if the config value was previously the value passed as $preCondition
207
+     * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
208
+     */
209
+    public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
210
+        // TODO - FIXME
211
+        $this->fixDIInit();
212
+
213
+        $preconditionArray = [];
214
+        if (isset($preCondition)) {
215
+            $preconditionArray = [
216
+                'configvalue' => $preCondition,
217
+            ];
218
+        }
219
+
220
+        $this->connection->setValues('preferences', [
221
+            'userid' => $userId,
222
+            'appid' => $appName,
223
+            'configkey' => $key,
224
+        ], [
225
+            'configvalue' => $value,
226
+        ], $preconditionArray);
227
+
228
+        // only add to the cache if we already loaded data for the user
229
+        if (isset($this->userCache[$userId])) {
230
+            if (!isset($this->userCache[$userId][$appName])) {
231
+                $this->userCache[$userId][$appName] = array();
232
+            }
233
+            $this->userCache[$userId][$appName][$key] = $value;
234
+        }
235
+    }
236
+
237
+    /**
238
+     * Getting a user defined value
239
+     *
240
+     * @param string $userId the userId of the user that we want to store the value under
241
+     * @param string $appName the appName that we stored the value under
242
+     * @param string $key the key under which the value is being stored
243
+     * @param mixed $default the default value to be returned if the value isn't set
244
+     * @return string
245
+     */
246
+    public function getUserValue($userId, $appName, $key, $default = '') {
247
+        $data = $this->getUserValues($userId);
248
+        if (isset($data[$appName]) and isset($data[$appName][$key])) {
249
+            return $data[$appName][$key];
250
+        } else {
251
+            return $default;
252
+        }
253
+    }
254
+
255
+    /**
256
+     * Get the keys of all stored by an app for the user
257
+     *
258
+     * @param string $userId the userId of the user that we want to store the value under
259
+     * @param string $appName the appName that we stored the value under
260
+     * @return string[]
261
+     */
262
+    public function getUserKeys($userId, $appName) {
263
+        $data = $this->getUserValues($userId);
264
+        if (isset($data[$appName])) {
265
+            return array_keys($data[$appName]);
266
+        } else {
267
+            return array();
268
+        }
269
+    }
270
+
271
+    /**
272
+     * Delete a user value
273
+     *
274
+     * @param string $userId the userId of the user that we want to store the value under
275
+     * @param string $appName the appName that we stored the value under
276
+     * @param string $key the key under which the value is being stored
277
+     */
278
+    public function deleteUserValue($userId, $appName, $key) {
279
+        // TODO - FIXME
280
+        $this->fixDIInit();
281
+
282
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
283
+                'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
284
+        $this->connection->executeUpdate($sql, array($userId, $appName, $key));
285
+
286
+        if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
287
+            unset($this->userCache[$userId][$appName][$key]);
288
+        }
289
+    }
290
+
291
+    /**
292
+     * Delete all user values
293
+     *
294
+     * @param string $userId the userId of the user that we want to remove all values from
295
+     */
296
+    public function deleteAllUserValues($userId) {
297
+        // TODO - FIXME
298
+        $this->fixDIInit();
299
+
300
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
301
+            'WHERE `userid` = ?';
302
+        $this->connection->executeUpdate($sql, array($userId));
303
+
304
+        unset($this->userCache[$userId]);
305
+    }
306
+
307
+    /**
308
+     * Delete all user related values of one app
309
+     *
310
+     * @param string $appName the appName of the app that we want to remove all values from
311
+     */
312
+    public function deleteAppFromAllUsers($appName) {
313
+        // TODO - FIXME
314
+        $this->fixDIInit();
315
+
316
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
317
+                'WHERE `appid` = ?';
318
+        $this->connection->executeUpdate($sql, array($appName));
319
+
320
+        foreach ($this->userCache as &$userCache) {
321
+            unset($userCache[$appName]);
322
+        }
323
+    }
324
+
325
+    /**
326
+     * Returns all user configs sorted by app of one user
327
+     *
328
+     * @param string $userId the user ID to get the app configs from
329
+     * @return array[] - 2 dimensional array with the following structure:
330
+     *     [ $appId =>
331
+     *         [ $key => $value ]
332
+     *     ]
333
+     */
334
+    private function getUserValues($userId) {
335
+        // TODO - FIXME
336
+        $this->fixDIInit();
337
+
338
+        if (isset($this->userCache[$userId])) {
339
+            return $this->userCache[$userId];
340
+        }
341
+        $data = array();
342
+        $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
343
+        $result = $this->connection->executeQuery($query, array($userId));
344
+        while ($row = $result->fetch()) {
345
+            $appId = $row['appid'];
346
+            if (!isset($data[$appId])) {
347
+                $data[$appId] = array();
348
+            }
349
+            $data[$appId][$row['configkey']] = $row['configvalue'];
350
+        }
351
+        $this->userCache[$userId] = $data;
352
+        return $data;
353
+    }
354
+
355
+    /**
356
+     * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
357
+     *
358
+     * @param string $appName app to get the value for
359
+     * @param string $key the key to get the value for
360
+     * @param array $userIds the user IDs to fetch the values for
361
+     * @return array Mapped values: userId => value
362
+     */
363
+    public function getUserValueForUsers($appName, $key, $userIds) {
364
+        // TODO - FIXME
365
+        $this->fixDIInit();
366
+
367
+        if (empty($userIds) || !is_array($userIds)) {
368
+            return array();
369
+        }
370
+
371
+        $chunkedUsers = array_chunk($userIds, 50, true);
372
+        $placeholders50 = implode(',', array_fill(0, 50, '?'));
373
+
374
+        $userValues = array();
375
+        foreach ($chunkedUsers as $chunk) {
376
+            $queryParams = $chunk;
377
+            // create [$app, $key, $chunkedUsers]
378
+            array_unshift($queryParams, $key);
379
+            array_unshift($queryParams, $appName);
380
+
381
+            $placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
382
+
383
+            $query    = 'SELECT `userid`, `configvalue` ' .
384
+                        'FROM `*PREFIX*preferences` ' .
385
+                        'WHERE `appid` = ? AND `configkey` = ? ' .
386
+                        'AND `userid` IN (' . $placeholders . ')';
387
+            $result = $this->connection->executeQuery($query, $queryParams);
388
+
389
+            while ($row = $result->fetch()) {
390
+                $userValues[$row['userid']] = $row['configvalue'];
391
+            }
392
+        }
393
+
394
+        return $userValues;
395
+    }
396
+
397
+    /**
398
+     * Determines the users that have the given value set for a specific app-key-pair
399
+     *
400
+     * @param string $appName the app to get the user for
401
+     * @param string $key the key to get the user for
402
+     * @param string $value the value to get the user for
403
+     * @return array of user IDs
404
+     */
405
+    public function getUsersForUserValue($appName, $key, $value) {
406
+        // TODO - FIXME
407
+        $this->fixDIInit();
408
+
409
+        $sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
410
+                'WHERE `appid` = ? AND `configkey` = ? ';
411
+
412
+        if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
413
+            //oracle hack: need to explicitly cast CLOB to CHAR for comparison
414
+            $sql .= 'AND to_char(`configvalue`) = ?';
415
+        } else {
416
+            $sql .= 'AND `configvalue` = ?';
417
+        }
418
+
419
+        $result = $this->connection->executeQuery($sql, array($appName, $key, $value));
420
+
421
+        $userIDs = array();
422
+        while ($row = $result->fetch()) {
423
+            $userIDs[] = $row['userid'];
424
+        }
425
+
426
+        return $userIDs;
427
+    }
428 428
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	 * because the database connection was created with an uninitialized config
88 88
 	 */
89 89
 	private function fixDIInit() {
90
-		if($this->connection === null) {
90
+		if ($this->connection === null) {
91 91
 			$this->connection = \OC::$server->getDatabaseConnection();
92 92
 		}
93 93
 	}
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 		// TODO - FIXME
285 285
 		$this->fixDIInit();
286 286
 
287
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
287
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
288 288
 				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
289 289
 		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
290 290
 
@@ -302,7 +302,7 @@  discard block
 block discarded – undo
302 302
 		// TODO - FIXME
303 303
 		$this->fixDIInit();
304 304
 
305
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
305
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
306 306
 			'WHERE `userid` = ?';
307 307
 		$this->connection->executeUpdate($sql, array($userId));
308 308
 
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 		// TODO - FIXME
319 319
 		$this->fixDIInit();
320 320
 
321
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
321
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
322 322
 				'WHERE `appid` = ?';
323 323
 		$this->connection->executeUpdate($sql, array($appName));
324 324
 
@@ -383,12 +383,12 @@  discard block
 block discarded – undo
383 383
 			array_unshift($queryParams, $key);
384 384
 			array_unshift($queryParams, $appName);
385 385
 
386
-			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
386
+			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 : implode(',', array_fill(0, sizeof($chunk), '?'));
387 387
 
388
-			$query    = 'SELECT `userid`, `configvalue` ' .
389
-						'FROM `*PREFIX*preferences` ' .
390
-						'WHERE `appid` = ? AND `configkey` = ? ' .
391
-						'AND `userid` IN (' . $placeholders . ')';
388
+			$query = 'SELECT `userid`, `configvalue` '.
389
+						'FROM `*PREFIX*preferences` '.
390
+						'WHERE `appid` = ? AND `configkey` = ? '.
391
+						'AND `userid` IN ('.$placeholders.')';
392 392
 			$result = $this->connection->executeQuery($query, $queryParams);
393 393
 
394 394
 			while ($row = $result->fetch()) {
@@ -411,10 +411,10 @@  discard block
 block discarded – undo
411 411
 		// TODO - FIXME
412 412
 		$this->fixDIInit();
413 413
 
414
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
414
+		$sql = 'SELECT `userid` FROM `*PREFIX*preferences` '.
415 415
 				'WHERE `appid` = ? AND `configkey` = ? ';
416 416
 
417
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
417
+		if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
418 418
 			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
419 419
 			$sql .= 'AND to_char(`configvalue`) = ?';
420 420
 		} else {
Please login to merge, or discard this patch.
lib/private/api.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -331,7 +331,7 @@
 block discarded – undo
331 331
 
332 332
 	/**
333 333
 	 * http basic auth
334
-	 * @return string|false (username, or false on failure)
334
+	 * @return string (username, or false on failure)
335 335
 	 */
336 336
 	private static function loginUser() {
337 337
 		if(self::$isLoggedIn === true) {
Please login to merge, or discard this patch.
Indentation   +465 added lines, -465 removed lines patch added patch discarded remove patch
@@ -66,469 +66,469 @@
 block discarded – undo
66 66
 
67 67
 class OC_API {
68 68
 
69
-	/**
70
-	 * API authentication levels
71
-	 */
72
-
73
-	/** @deprecated Use \OCP\API::GUEST_AUTH instead */
74
-	const GUEST_AUTH = 0;
75
-
76
-	/** @deprecated Use \OCP\API::USER_AUTH instead */
77
-	const USER_AUTH = 1;
78
-
79
-	/** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
80
-	const SUBADMIN_AUTH = 2;
81
-
82
-	/** @deprecated Use \OCP\API::ADMIN_AUTH instead */
83
-	const ADMIN_AUTH = 3;
84
-
85
-	/**
86
-	 * API Response Codes
87
-	 */
88
-
89
-	/** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
90
-	const RESPOND_UNAUTHORISED = 997;
91
-
92
-	/** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
93
-	const RESPOND_SERVER_ERROR = 996;
94
-
95
-	/** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
96
-	const RESPOND_NOT_FOUND = 998;
97
-
98
-	/** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
99
-	const RESPOND_UNKNOWN_ERROR = 999;
100
-
101
-	/**
102
-	 * api actions
103
-	 */
104
-	protected static $actions = array();
105
-	private static $logoutRequired = false;
106
-	private static $isLoggedIn = false;
107
-
108
-	/**
109
-	 * registers an api call
110
-	 * @param string $method the http method
111
-	 * @param string $url the url to match
112
-	 * @param callable $action the function to run
113
-	 * @param string $app the id of the app registering the call
114
-	 * @param int $authLevel the level of authentication required for the call
115
-	 * @param array $defaults
116
-	 * @param array $requirements
117
-	 */
118
-	public static function register($method, $url, $action, $app,
119
-				$authLevel = API::USER_AUTH,
120
-				$defaults = array(),
121
-				$requirements = array()) {
122
-		$name = strtolower($method).$url;
123
-		$name = str_replace(array('/', '{', '}'), '_', $name);
124
-		if(!isset(self::$actions[$name])) {
125
-			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
126
-			OC::$server->getRouter()->useCollection('ocs');
127
-			OC::$server->getRouter()->create($name, $url)
128
-				->method($method)
129
-				->defaults($defaults)
130
-				->requirements($requirements)
131
-				->action('OC_API', 'call');
132
-			self::$actions[$name] = array();
133
-			OC::$server->getRouter()->useCollection($oldCollection);
134
-		}
135
-		self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
136
-	}
137
-
138
-	/**
139
-	 * handles an api call
140
-	 * @param array $parameters
141
-	 */
142
-	public static function call($parameters) {
143
-		$request = \OC::$server->getRequest();
144
-		$method = $request->getMethod();
145
-
146
-		// Prepare the request variables
147
-		if($method === 'PUT') {
148
-			$parameters['_put'] = $request->getParams();
149
-		} else if($method === 'DELETE') {
150
-			$parameters['_delete'] = $request->getParams();
151
-		}
152
-		$name = $parameters['_route'];
153
-		// Foreach registered action
154
-		$responses = array();
155
-		foreach(self::$actions[$name] as $action) {
156
-			// Check authentication and availability
157
-			if(!self::isAuthorised($action)) {
158
-				$responses[] = array(
159
-					'app' => $action['app'],
160
-					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
161
-					'shipped' => OC_App::isShipped($action['app']),
162
-					);
163
-				continue;
164
-			}
165
-			if(!is_callable($action['action'])) {
166
-				$responses[] = array(
167
-					'app' => $action['app'],
168
-					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
169
-					'shipped' => OC_App::isShipped($action['app']),
170
-					);
171
-				continue;
172
-			}
173
-			// Run the action
174
-			$responses[] = array(
175
-				'app' => $action['app'],
176
-				'response' => call_user_func($action['action'], $parameters),
177
-				'shipped' => OC_App::isShipped($action['app']),
178
-				);
179
-		}
180
-		$response = self::mergeResponses($responses);
181
-		$format = self::requestedFormat();
182
-		if (self::$logoutRequired) {
183
-			OC_User::logout();
184
-		}
185
-
186
-		self::respond($response, $format);
187
-	}
188
-
189
-	/**
190
-	 * merge the returned result objects into one response
191
-	 * @param array $responses
192
-	 * @return OC_OCS_Result
193
-	 */
194
-	public static function mergeResponses($responses) {
195
-		// Sort into shipped and third-party
196
-		$shipped = array(
197
-			'succeeded' => array(),
198
-			'failed' => array(),
199
-			);
200
-		$thirdparty = array(
201
-			'succeeded' => array(),
202
-			'failed' => array(),
203
-			);
204
-
205
-		foreach($responses as $response) {
206
-			if($response['shipped'] || ($response['app'] === 'core')) {
207
-				if($response['response']->succeeded()) {
208
-					$shipped['succeeded'][$response['app']] = $response;
209
-				} else {
210
-					$shipped['failed'][$response['app']] = $response;
211
-				}
212
-			} else {
213
-				if($response['response']->succeeded()) {
214
-					$thirdparty['succeeded'][$response['app']] = $response;
215
-				} else {
216
-					$thirdparty['failed'][$response['app']] = $response;
217
-				}
218
-			}
219
-		}
220
-
221
-		// Remove any error responses if there is one shipped response that succeeded
222
-		if(!empty($shipped['failed'])) {
223
-			// Which shipped response do we use if they all failed?
224
-			// They may have failed for different reasons (different status codes)
225
-			// Which response code should we return?
226
-			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
227
-			// Merge failed responses if more than one
228
-			$data = array();
229
-			foreach($shipped['failed'] as $failure) {
230
-				$data = array_merge_recursive($data, $failure['response']->getData());
231
-			}
232
-			$picked = reset($shipped['failed']);
233
-			$code = $picked['response']->getStatusCode();
234
-			$meta = $picked['response']->getMeta();
235
-			$headers = $picked['response']->getHeaders();
236
-			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
237
-			return $response;
238
-		} elseif(!empty($shipped['succeeded'])) {
239
-			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
240
-		} elseif(!empty($thirdparty['failed'])) {
241
-			// Merge failed responses if more than one
242
-			$data = array();
243
-			foreach($thirdparty['failed'] as $failure) {
244
-				$data = array_merge_recursive($data, $failure['response']->getData());
245
-			}
246
-			$picked = reset($thirdparty['failed']);
247
-			$code = $picked['response']->getStatusCode();
248
-			$meta = $picked['response']->getMeta();
249
-			$headers = $picked['response']->getHeaders();
250
-			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
251
-			return $response;
252
-		} else {
253
-			$responses = $thirdparty['succeeded'];
254
-		}
255
-		// Merge the successful responses
256
-		$data = [];
257
-		$codes = [];
258
-		$header = [];
259
-
260
-		foreach($responses as $response) {
261
-			if($response['shipped']) {
262
-				$data = array_merge_recursive($response['response']->getData(), $data);
263
-			} else {
264
-				$data = array_merge_recursive($data, $response['response']->getData());
265
-			}
266
-			$header = array_merge_recursive($header, $response['response']->getHeaders());
267
-			$codes[] = ['code' => $response['response']->getStatusCode(),
268
-				'meta' => $response['response']->getMeta()];
269
-		}
270
-
271
-		// Use any non 100 status codes
272
-		$statusCode = 100;
273
-		$statusMessage = null;
274
-		foreach($codes as $code) {
275
-			if($code['code'] != 100) {
276
-				$statusCode = $code['code'];
277
-				$statusMessage = $code['meta']['message'];
278
-				break;
279
-			}
280
-		}
281
-
282
-		return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
283
-	}
284
-
285
-	/**
286
-	 * authenticate the api call
287
-	 * @param array $action the action details as supplied to OC_API::register()
288
-	 * @return bool
289
-	 */
290
-	private static function isAuthorised($action) {
291
-		$level = $action['authlevel'];
292
-		switch($level) {
293
-			case API::GUEST_AUTH:
294
-				// Anyone can access
295
-				return true;
296
-			case API::USER_AUTH:
297
-				// User required
298
-				return self::loginUser();
299
-			case API::SUBADMIN_AUTH:
300
-				// Check for subadmin
301
-				$user = self::loginUser();
302
-				if(!$user) {
303
-					return false;
304
-				} else {
305
-					$userObject = \OC::$server->getUserSession()->getUser();
306
-					if($userObject === null) {
307
-						return false;
308
-					}
309
-					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
310
-					$admin = OC_User::isAdminUser($user);
311
-					if($isSubAdmin || $admin) {
312
-						return true;
313
-					} else {
314
-						return false;
315
-					}
316
-				}
317
-			case API::ADMIN_AUTH:
318
-				// Check for admin
319
-				$user = self::loginUser();
320
-				if(!$user) {
321
-					return false;
322
-				} else {
323
-					return OC_User::isAdminUser($user);
324
-				}
325
-			default:
326
-				// oops looks like invalid level supplied
327
-				return false;
328
-		}
329
-	}
330
-
331
-	/**
332
-	 * http basic auth
333
-	 * @return string|false (username, or false on failure)
334
-	 */
335
-	private static function loginUser() {
336
-		if(self::$isLoggedIn === true) {
337
-			return \OC_User::getUser();
338
-		}
339
-
340
-		// reuse existing login
341
-		$loggedIn = OC_User::isLoggedIn();
342
-		if ($loggedIn === true) {
343
-			$ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
344
-			if ($ocsApiRequest) {
345
-
346
-				// initialize the user's filesystem
347
-				\OC_Util::setUpFS(\OC_User::getUser());
348
-				self::$isLoggedIn = true;
349
-
350
-				return OC_User::getUser();
351
-			}
352
-			return false;
353
-		}
354
-
355
-		// basic auth - because OC_User::login will create a new session we shall only try to login
356
-		// if user and pass are set
357
-		if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) ) {
358
-			$authUser = $_SERVER['PHP_AUTH_USER'];
359
-			$authPw = $_SERVER['PHP_AUTH_PW'];
360
-			$return = OC_User::login($authUser, $authPw);
361
-			if ($return === true) {
362
-				self::$logoutRequired = true;
363
-
364
-				// initialize the user's filesystem
365
-				\OC_Util::setUpFS(\OC_User::getUser());
366
-				self::$isLoggedIn = true;
367
-
368
-				/**
369
-				 * Add DAV authenticated. This should in an ideal world not be
370
-				 * necessary but the iOS App reads cookies from anywhere instead
371
-				 * only the DAV endpoint.
372
-				 * This makes sure that the cookies will be valid for the whole scope
373
-				 * @see https://github.com/owncloud/core/issues/22893
374
-				 */
375
-				\OC::$server->getSession()->set(
376
-					\OCA\DAV\Connector\Sabre\Auth::DAV_AUTHENTICATED,
377
-					\OC::$server->getUserSession()->getUser()->getUID()
378
-				);
379
-
380
-				return \OC_User::getUser();
381
-			}
382
-		}
383
-
384
-		return false;
385
-	}
386
-
387
-	/**
388
-	 * respond to a call
389
-	 * @param OC_OCS_Result $result
390
-	 * @param string $format the format xml|json
391
-	 */
392
-	public static function respond($result, $format='xml') {
393
-		$request = \OC::$server->getRequest();
394
-
395
-		// Send 401 headers if unauthorised
396
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
397
-			// If request comes from JS return dummy auth request
398
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
399
-				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
400
-			} else {
401
-				header('WWW-Authenticate: Basic realm="Authorisation Required"');
402
-			}
403
-			header('HTTP/1.0 401 Unauthorized');
404
-		}
405
-
406
-		foreach($result->getHeaders() as $name => $value) {
407
-			header($name . ': ' . $value);
408
-		}
409
-
410
-		$meta = $result->getMeta();
411
-		$data = $result->getData();
412
-		if (self::isV2($request)) {
413
-			$statusCode = self::mapStatusCodes($result->getStatusCode());
414
-			if (!is_null($statusCode)) {
415
-				$meta['statuscode'] = $statusCode;
416
-				OC_Response::setStatus($statusCode);
417
-			}
418
-		}
419
-
420
-		self::setContentType($format);
421
-		$body = self::renderResult($format, $meta, $data);
422
-		echo $body;
423
-	}
424
-
425
-	/**
426
-	 * @param XMLWriter $writer
427
-	 */
428
-	private static function toXML($array, $writer) {
429
-		foreach($array as $k => $v) {
430
-			if ($k[0] === '@') {
431
-				$writer->writeAttribute(substr($k, 1), $v);
432
-				continue;
433
-			} else if (is_numeric($k)) {
434
-				$k = 'element';
435
-			}
436
-			if(is_array($v)) {
437
-				$writer->startElement($k);
438
-				self::toXML($v, $writer);
439
-				$writer->endElement();
440
-			} else {
441
-				$writer->writeElement($k, $v);
442
-			}
443
-		}
444
-	}
445
-
446
-	/**
447
-	 * @return string
448
-	 */
449
-	public static function requestedFormat() {
450
-		$formats = array('json', 'xml');
451
-
452
-		$format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
453
-		return $format;
454
-	}
455
-
456
-	/**
457
-	 * Based on the requested format the response content type is set
458
-	 * @param string $format
459
-	 */
460
-	public static function setContentType($format = null) {
461
-		$format = is_null($format) ? self::requestedFormat() : $format;
462
-		if ($format === 'xml') {
463
-			header('Content-type: text/xml; charset=UTF-8');
464
-			return;
465
-		}
466
-
467
-		if ($format === 'json') {
468
-			header('Content-Type: application/json; charset=utf-8');
469
-			return;
470
-		}
471
-
472
-		header('Content-Type: application/octet-stream; charset=utf-8');
473
-	}
474
-
475
-	/**
476
-	 * @param \OCP\IRequest $request
477
-	 * @return bool
478
-	 */
479
-	protected static function isV2(\OCP\IRequest $request) {
480
-		$script = $request->getScriptName();
481
-
482
-		return substr($script, -11) === '/ocs/v2.php';
483
-	}
484
-
485
-	/**
486
-	 * @param integer $sc
487
-	 * @return int
488
-	 */
489
-	public static function mapStatusCodes($sc) {
490
-		switch ($sc) {
491
-			case API::RESPOND_NOT_FOUND:
492
-				return Http::STATUS_NOT_FOUND;
493
-			case API::RESPOND_SERVER_ERROR:
494
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
495
-			case API::RESPOND_UNKNOWN_ERROR:
496
-				return Http::STATUS_INTERNAL_SERVER_ERROR;
497
-			case API::RESPOND_UNAUTHORISED:
498
-				// already handled for v1
499
-				return null;
500
-			case 100:
501
-				return Http::STATUS_OK;
502
-		}
503
-		// any 2xx, 4xx and 5xx will be used as is
504
-		if ($sc >= 200 && $sc < 600) {
505
-			return $sc;
506
-		}
507
-
508
-		return Http::STATUS_BAD_REQUEST;
509
-	}
510
-
511
-	/**
512
-	 * @param string $format
513
-	 * @return string
514
-	 */
515
-	public static function renderResult($format, $meta, $data) {
516
-		$response = array(
517
-			'ocs' => array(
518
-				'meta' => $meta,
519
-				'data' => $data,
520
-			),
521
-		);
522
-		if ($format == 'json') {
523
-			return OC_JSON::encode($response);
524
-		}
525
-
526
-		$writer = new XMLWriter();
527
-		$writer->openMemory();
528
-		$writer->setIndent(true);
529
-		$writer->startDocument();
530
-		self::toXML($response, $writer);
531
-		$writer->endDocument();
532
-		return $writer->outputMemory(true);
533
-	}
69
+    /**
70
+     * API authentication levels
71
+     */
72
+
73
+    /** @deprecated Use \OCP\API::GUEST_AUTH instead */
74
+    const GUEST_AUTH = 0;
75
+
76
+    /** @deprecated Use \OCP\API::USER_AUTH instead */
77
+    const USER_AUTH = 1;
78
+
79
+    /** @deprecated Use \OCP\API::SUBADMIN_AUTH instead */
80
+    const SUBADMIN_AUTH = 2;
81
+
82
+    /** @deprecated Use \OCP\API::ADMIN_AUTH instead */
83
+    const ADMIN_AUTH = 3;
84
+
85
+    /**
86
+     * API Response Codes
87
+     */
88
+
89
+    /** @deprecated Use \OCP\API::RESPOND_UNAUTHORISED instead */
90
+    const RESPOND_UNAUTHORISED = 997;
91
+
92
+    /** @deprecated Use \OCP\API::RESPOND_SERVER_ERROR instead */
93
+    const RESPOND_SERVER_ERROR = 996;
94
+
95
+    /** @deprecated Use \OCP\API::RESPOND_NOT_FOUND instead */
96
+    const RESPOND_NOT_FOUND = 998;
97
+
98
+    /** @deprecated Use \OCP\API::RESPOND_UNKNOWN_ERROR instead */
99
+    const RESPOND_UNKNOWN_ERROR = 999;
100
+
101
+    /**
102
+     * api actions
103
+     */
104
+    protected static $actions = array();
105
+    private static $logoutRequired = false;
106
+    private static $isLoggedIn = false;
107
+
108
+    /**
109
+     * registers an api call
110
+     * @param string $method the http method
111
+     * @param string $url the url to match
112
+     * @param callable $action the function to run
113
+     * @param string $app the id of the app registering the call
114
+     * @param int $authLevel the level of authentication required for the call
115
+     * @param array $defaults
116
+     * @param array $requirements
117
+     */
118
+    public static function register($method, $url, $action, $app,
119
+                $authLevel = API::USER_AUTH,
120
+                $defaults = array(),
121
+                $requirements = array()) {
122
+        $name = strtolower($method).$url;
123
+        $name = str_replace(array('/', '{', '}'), '_', $name);
124
+        if(!isset(self::$actions[$name])) {
125
+            $oldCollection = OC::$server->getRouter()->getCurrentCollection();
126
+            OC::$server->getRouter()->useCollection('ocs');
127
+            OC::$server->getRouter()->create($name, $url)
128
+                ->method($method)
129
+                ->defaults($defaults)
130
+                ->requirements($requirements)
131
+                ->action('OC_API', 'call');
132
+            self::$actions[$name] = array();
133
+            OC::$server->getRouter()->useCollection($oldCollection);
134
+        }
135
+        self::$actions[$name][] = array('app' => $app, 'action' => $action, 'authlevel' => $authLevel);
136
+    }
137
+
138
+    /**
139
+     * handles an api call
140
+     * @param array $parameters
141
+     */
142
+    public static function call($parameters) {
143
+        $request = \OC::$server->getRequest();
144
+        $method = $request->getMethod();
145
+
146
+        // Prepare the request variables
147
+        if($method === 'PUT') {
148
+            $parameters['_put'] = $request->getParams();
149
+        } else if($method === 'DELETE') {
150
+            $parameters['_delete'] = $request->getParams();
151
+        }
152
+        $name = $parameters['_route'];
153
+        // Foreach registered action
154
+        $responses = array();
155
+        foreach(self::$actions[$name] as $action) {
156
+            // Check authentication and availability
157
+            if(!self::isAuthorised($action)) {
158
+                $responses[] = array(
159
+                    'app' => $action['app'],
160
+                    'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
161
+                    'shipped' => OC_App::isShipped($action['app']),
162
+                    );
163
+                continue;
164
+            }
165
+            if(!is_callable($action['action'])) {
166
+                $responses[] = array(
167
+                    'app' => $action['app'],
168
+                    'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
169
+                    'shipped' => OC_App::isShipped($action['app']),
170
+                    );
171
+                continue;
172
+            }
173
+            // Run the action
174
+            $responses[] = array(
175
+                'app' => $action['app'],
176
+                'response' => call_user_func($action['action'], $parameters),
177
+                'shipped' => OC_App::isShipped($action['app']),
178
+                );
179
+        }
180
+        $response = self::mergeResponses($responses);
181
+        $format = self::requestedFormat();
182
+        if (self::$logoutRequired) {
183
+            OC_User::logout();
184
+        }
185
+
186
+        self::respond($response, $format);
187
+    }
188
+
189
+    /**
190
+     * merge the returned result objects into one response
191
+     * @param array $responses
192
+     * @return OC_OCS_Result
193
+     */
194
+    public static function mergeResponses($responses) {
195
+        // Sort into shipped and third-party
196
+        $shipped = array(
197
+            'succeeded' => array(),
198
+            'failed' => array(),
199
+            );
200
+        $thirdparty = array(
201
+            'succeeded' => array(),
202
+            'failed' => array(),
203
+            );
204
+
205
+        foreach($responses as $response) {
206
+            if($response['shipped'] || ($response['app'] === 'core')) {
207
+                if($response['response']->succeeded()) {
208
+                    $shipped['succeeded'][$response['app']] = $response;
209
+                } else {
210
+                    $shipped['failed'][$response['app']] = $response;
211
+                }
212
+            } else {
213
+                if($response['response']->succeeded()) {
214
+                    $thirdparty['succeeded'][$response['app']] = $response;
215
+                } else {
216
+                    $thirdparty['failed'][$response['app']] = $response;
217
+                }
218
+            }
219
+        }
220
+
221
+        // Remove any error responses if there is one shipped response that succeeded
222
+        if(!empty($shipped['failed'])) {
223
+            // Which shipped response do we use if they all failed?
224
+            // They may have failed for different reasons (different status codes)
225
+            // Which response code should we return?
226
+            // Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
227
+            // Merge failed responses if more than one
228
+            $data = array();
229
+            foreach($shipped['failed'] as $failure) {
230
+                $data = array_merge_recursive($data, $failure['response']->getData());
231
+            }
232
+            $picked = reset($shipped['failed']);
233
+            $code = $picked['response']->getStatusCode();
234
+            $meta = $picked['response']->getMeta();
235
+            $headers = $picked['response']->getHeaders();
236
+            $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
237
+            return $response;
238
+        } elseif(!empty($shipped['succeeded'])) {
239
+            $responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
240
+        } elseif(!empty($thirdparty['failed'])) {
241
+            // Merge failed responses if more than one
242
+            $data = array();
243
+            foreach($thirdparty['failed'] as $failure) {
244
+                $data = array_merge_recursive($data, $failure['response']->getData());
245
+            }
246
+            $picked = reset($thirdparty['failed']);
247
+            $code = $picked['response']->getStatusCode();
248
+            $meta = $picked['response']->getMeta();
249
+            $headers = $picked['response']->getHeaders();
250
+            $response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
251
+            return $response;
252
+        } else {
253
+            $responses = $thirdparty['succeeded'];
254
+        }
255
+        // Merge the successful responses
256
+        $data = [];
257
+        $codes = [];
258
+        $header = [];
259
+
260
+        foreach($responses as $response) {
261
+            if($response['shipped']) {
262
+                $data = array_merge_recursive($response['response']->getData(), $data);
263
+            } else {
264
+                $data = array_merge_recursive($data, $response['response']->getData());
265
+            }
266
+            $header = array_merge_recursive($header, $response['response']->getHeaders());
267
+            $codes[] = ['code' => $response['response']->getStatusCode(),
268
+                'meta' => $response['response']->getMeta()];
269
+        }
270
+
271
+        // Use any non 100 status codes
272
+        $statusCode = 100;
273
+        $statusMessage = null;
274
+        foreach($codes as $code) {
275
+            if($code['code'] != 100) {
276
+                $statusCode = $code['code'];
277
+                $statusMessage = $code['meta']['message'];
278
+                break;
279
+            }
280
+        }
281
+
282
+        return new OC_OCS_Result($data, $statusCode, $statusMessage, $header);
283
+    }
284
+
285
+    /**
286
+     * authenticate the api call
287
+     * @param array $action the action details as supplied to OC_API::register()
288
+     * @return bool
289
+     */
290
+    private static function isAuthorised($action) {
291
+        $level = $action['authlevel'];
292
+        switch($level) {
293
+            case API::GUEST_AUTH:
294
+                // Anyone can access
295
+                return true;
296
+            case API::USER_AUTH:
297
+                // User required
298
+                return self::loginUser();
299
+            case API::SUBADMIN_AUTH:
300
+                // Check for subadmin
301
+                $user = self::loginUser();
302
+                if(!$user) {
303
+                    return false;
304
+                } else {
305
+                    $userObject = \OC::$server->getUserSession()->getUser();
306
+                    if($userObject === null) {
307
+                        return false;
308
+                    }
309
+                    $isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
310
+                    $admin = OC_User::isAdminUser($user);
311
+                    if($isSubAdmin || $admin) {
312
+                        return true;
313
+                    } else {
314
+                        return false;
315
+                    }
316
+                }
317
+            case API::ADMIN_AUTH:
318
+                // Check for admin
319
+                $user = self::loginUser();
320
+                if(!$user) {
321
+                    return false;
322
+                } else {
323
+                    return OC_User::isAdminUser($user);
324
+                }
325
+            default:
326
+                // oops looks like invalid level supplied
327
+                return false;
328
+        }
329
+    }
330
+
331
+    /**
332
+     * http basic auth
333
+     * @return string|false (username, or false on failure)
334
+     */
335
+    private static function loginUser() {
336
+        if(self::$isLoggedIn === true) {
337
+            return \OC_User::getUser();
338
+        }
339
+
340
+        // reuse existing login
341
+        $loggedIn = OC_User::isLoggedIn();
342
+        if ($loggedIn === true) {
343
+            $ocsApiRequest = isset($_SERVER['HTTP_OCS_APIREQUEST']) ? $_SERVER['HTTP_OCS_APIREQUEST'] === 'true' : false;
344
+            if ($ocsApiRequest) {
345
+
346
+                // initialize the user's filesystem
347
+                \OC_Util::setUpFS(\OC_User::getUser());
348
+                self::$isLoggedIn = true;
349
+
350
+                return OC_User::getUser();
351
+            }
352
+            return false;
353
+        }
354
+
355
+        // basic auth - because OC_User::login will create a new session we shall only try to login
356
+        // if user and pass are set
357
+        if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) ) {
358
+            $authUser = $_SERVER['PHP_AUTH_USER'];
359
+            $authPw = $_SERVER['PHP_AUTH_PW'];
360
+            $return = OC_User::login($authUser, $authPw);
361
+            if ($return === true) {
362
+                self::$logoutRequired = true;
363
+
364
+                // initialize the user's filesystem
365
+                \OC_Util::setUpFS(\OC_User::getUser());
366
+                self::$isLoggedIn = true;
367
+
368
+                /**
369
+                 * Add DAV authenticated. This should in an ideal world not be
370
+                 * necessary but the iOS App reads cookies from anywhere instead
371
+                 * only the DAV endpoint.
372
+                 * This makes sure that the cookies will be valid for the whole scope
373
+                 * @see https://github.com/owncloud/core/issues/22893
374
+                 */
375
+                \OC::$server->getSession()->set(
376
+                    \OCA\DAV\Connector\Sabre\Auth::DAV_AUTHENTICATED,
377
+                    \OC::$server->getUserSession()->getUser()->getUID()
378
+                );
379
+
380
+                return \OC_User::getUser();
381
+            }
382
+        }
383
+
384
+        return false;
385
+    }
386
+
387
+    /**
388
+     * respond to a call
389
+     * @param OC_OCS_Result $result
390
+     * @param string $format the format xml|json
391
+     */
392
+    public static function respond($result, $format='xml') {
393
+        $request = \OC::$server->getRequest();
394
+
395
+        // Send 401 headers if unauthorised
396
+        if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
397
+            // If request comes from JS return dummy auth request
398
+            if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
399
+                header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
400
+            } else {
401
+                header('WWW-Authenticate: Basic realm="Authorisation Required"');
402
+            }
403
+            header('HTTP/1.0 401 Unauthorized');
404
+        }
405
+
406
+        foreach($result->getHeaders() as $name => $value) {
407
+            header($name . ': ' . $value);
408
+        }
409
+
410
+        $meta = $result->getMeta();
411
+        $data = $result->getData();
412
+        if (self::isV2($request)) {
413
+            $statusCode = self::mapStatusCodes($result->getStatusCode());
414
+            if (!is_null($statusCode)) {
415
+                $meta['statuscode'] = $statusCode;
416
+                OC_Response::setStatus($statusCode);
417
+            }
418
+        }
419
+
420
+        self::setContentType($format);
421
+        $body = self::renderResult($format, $meta, $data);
422
+        echo $body;
423
+    }
424
+
425
+    /**
426
+     * @param XMLWriter $writer
427
+     */
428
+    private static function toXML($array, $writer) {
429
+        foreach($array as $k => $v) {
430
+            if ($k[0] === '@') {
431
+                $writer->writeAttribute(substr($k, 1), $v);
432
+                continue;
433
+            } else if (is_numeric($k)) {
434
+                $k = 'element';
435
+            }
436
+            if(is_array($v)) {
437
+                $writer->startElement($k);
438
+                self::toXML($v, $writer);
439
+                $writer->endElement();
440
+            } else {
441
+                $writer->writeElement($k, $v);
442
+            }
443
+        }
444
+    }
445
+
446
+    /**
447
+     * @return string
448
+     */
449
+    public static function requestedFormat() {
450
+        $formats = array('json', 'xml');
451
+
452
+        $format = !empty($_GET['format']) && in_array($_GET['format'], $formats) ? $_GET['format'] : 'xml';
453
+        return $format;
454
+    }
455
+
456
+    /**
457
+     * Based on the requested format the response content type is set
458
+     * @param string $format
459
+     */
460
+    public static function setContentType($format = null) {
461
+        $format = is_null($format) ? self::requestedFormat() : $format;
462
+        if ($format === 'xml') {
463
+            header('Content-type: text/xml; charset=UTF-8');
464
+            return;
465
+        }
466
+
467
+        if ($format === 'json') {
468
+            header('Content-Type: application/json; charset=utf-8');
469
+            return;
470
+        }
471
+
472
+        header('Content-Type: application/octet-stream; charset=utf-8');
473
+    }
474
+
475
+    /**
476
+     * @param \OCP\IRequest $request
477
+     * @return bool
478
+     */
479
+    protected static function isV2(\OCP\IRequest $request) {
480
+        $script = $request->getScriptName();
481
+
482
+        return substr($script, -11) === '/ocs/v2.php';
483
+    }
484
+
485
+    /**
486
+     * @param integer $sc
487
+     * @return int
488
+     */
489
+    public static function mapStatusCodes($sc) {
490
+        switch ($sc) {
491
+            case API::RESPOND_NOT_FOUND:
492
+                return Http::STATUS_NOT_FOUND;
493
+            case API::RESPOND_SERVER_ERROR:
494
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
495
+            case API::RESPOND_UNKNOWN_ERROR:
496
+                return Http::STATUS_INTERNAL_SERVER_ERROR;
497
+            case API::RESPOND_UNAUTHORISED:
498
+                // already handled for v1
499
+                return null;
500
+            case 100:
501
+                return Http::STATUS_OK;
502
+        }
503
+        // any 2xx, 4xx and 5xx will be used as is
504
+        if ($sc >= 200 && $sc < 600) {
505
+            return $sc;
506
+        }
507
+
508
+        return Http::STATUS_BAD_REQUEST;
509
+    }
510
+
511
+    /**
512
+     * @param string $format
513
+     * @return string
514
+     */
515
+    public static function renderResult($format, $meta, $data) {
516
+        $response = array(
517
+            'ocs' => array(
518
+                'meta' => $meta,
519
+                'data' => $data,
520
+            ),
521
+        );
522
+        if ($format == 'json') {
523
+            return OC_JSON::encode($response);
524
+        }
525
+
526
+        $writer = new XMLWriter();
527
+        $writer->openMemory();
528
+        $writer->setIndent(true);
529
+        $writer->startDocument();
530
+        self::toXML($response, $writer);
531
+        $writer->endDocument();
532
+        return $writer->outputMemory(true);
533
+    }
534 534
 }
Please login to merge, or discard this patch.
Spacing   +33 added lines, -33 removed lines patch added patch discarded remove patch
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 				$requirements = array()) {
122 122
 		$name = strtolower($method).$url;
123 123
 		$name = str_replace(array('/', '{', '}'), '_', $name);
124
-		if(!isset(self::$actions[$name])) {
124
+		if (!isset(self::$actions[$name])) {
125 125
 			$oldCollection = OC::$server->getRouter()->getCurrentCollection();
126 126
 			OC::$server->getRouter()->useCollection('ocs');
127 127
 			OC::$server->getRouter()->create($name, $url)
@@ -144,17 +144,17 @@  discard block
 block discarded – undo
144 144
 		$method = $request->getMethod();
145 145
 
146 146
 		// Prepare the request variables
147
-		if($method === 'PUT') {
147
+		if ($method === 'PUT') {
148 148
 			$parameters['_put'] = $request->getParams();
149
-		} else if($method === 'DELETE') {
149
+		} else if ($method === 'DELETE') {
150 150
 			$parameters['_delete'] = $request->getParams();
151 151
 		}
152 152
 		$name = $parameters['_route'];
153 153
 		// Foreach registered action
154 154
 		$responses = array();
155
-		foreach(self::$actions[$name] as $action) {
155
+		foreach (self::$actions[$name] as $action) {
156 156
 			// Check authentication and availability
157
-			if(!self::isAuthorised($action)) {
157
+			if (!self::isAuthorised($action)) {
158 158
 				$responses[] = array(
159 159
 					'app' => $action['app'],
160 160
 					'response' => new OC_OCS_Result(null, API::RESPOND_UNAUTHORISED, 'Unauthorised'),
@@ -162,7 +162,7 @@  discard block
 block discarded – undo
162 162
 					);
163 163
 				continue;
164 164
 			}
165
-			if(!is_callable($action['action'])) {
165
+			if (!is_callable($action['action'])) {
166 166
 				$responses[] = array(
167 167
 					'app' => $action['app'],
168 168
 					'response' => new OC_OCS_Result(null, API::RESPOND_NOT_FOUND, 'Api method not found'),
@@ -202,15 +202,15 @@  discard block
 block discarded – undo
202 202
 			'failed' => array(),
203 203
 			);
204 204
 
205
-		foreach($responses as $response) {
206
-			if($response['shipped'] || ($response['app'] === 'core')) {
207
-				if($response['response']->succeeded()) {
205
+		foreach ($responses as $response) {
206
+			if ($response['shipped'] || ($response['app'] === 'core')) {
207
+				if ($response['response']->succeeded()) {
208 208
 					$shipped['succeeded'][$response['app']] = $response;
209 209
 				} else {
210 210
 					$shipped['failed'][$response['app']] = $response;
211 211
 				}
212 212
 			} else {
213
-				if($response['response']->succeeded()) {
213
+				if ($response['response']->succeeded()) {
214 214
 					$thirdparty['succeeded'][$response['app']] = $response;
215 215
 				} else {
216 216
 					$thirdparty['failed'][$response['app']] = $response;
@@ -219,14 +219,14 @@  discard block
 block discarded – undo
219 219
 		}
220 220
 
221 221
 		// Remove any error responses if there is one shipped response that succeeded
222
-		if(!empty($shipped['failed'])) {
222
+		if (!empty($shipped['failed'])) {
223 223
 			// Which shipped response do we use if they all failed?
224 224
 			// They may have failed for different reasons (different status codes)
225 225
 			// Which response code should we return?
226 226
 			// Maybe any that are not \OCP\API::RESPOND_SERVER_ERROR
227 227
 			// Merge failed responses if more than one
228 228
 			$data = array();
229
-			foreach($shipped['failed'] as $failure) {
229
+			foreach ($shipped['failed'] as $failure) {
230 230
 				$data = array_merge_recursive($data, $failure['response']->getData());
231 231
 			}
232 232
 			$picked = reset($shipped['failed']);
@@ -235,12 +235,12 @@  discard block
 block discarded – undo
235 235
 			$headers = $picked['response']->getHeaders();
236 236
 			$response = new OC_OCS_Result($data, $code, $meta['message'], $headers);
237 237
 			return $response;
238
-		} elseif(!empty($shipped['succeeded'])) {
238
+		} elseif (!empty($shipped['succeeded'])) {
239 239
 			$responses = array_merge($shipped['succeeded'], $thirdparty['succeeded']);
240
-		} elseif(!empty($thirdparty['failed'])) {
240
+		} elseif (!empty($thirdparty['failed'])) {
241 241
 			// Merge failed responses if more than one
242 242
 			$data = array();
243
-			foreach($thirdparty['failed'] as $failure) {
243
+			foreach ($thirdparty['failed'] as $failure) {
244 244
 				$data = array_merge_recursive($data, $failure['response']->getData());
245 245
 			}
246 246
 			$picked = reset($thirdparty['failed']);
@@ -257,8 +257,8 @@  discard block
 block discarded – undo
257 257
 		$codes = [];
258 258
 		$header = [];
259 259
 
260
-		foreach($responses as $response) {
261
-			if($response['shipped']) {
260
+		foreach ($responses as $response) {
261
+			if ($response['shipped']) {
262 262
 				$data = array_merge_recursive($response['response']->getData(), $data);
263 263
 			} else {
264 264
 				$data = array_merge_recursive($data, $response['response']->getData());
@@ -271,8 +271,8 @@  discard block
 block discarded – undo
271 271
 		// Use any non 100 status codes
272 272
 		$statusCode = 100;
273 273
 		$statusMessage = null;
274
-		foreach($codes as $code) {
275
-			if($code['code'] != 100) {
274
+		foreach ($codes as $code) {
275
+			if ($code['code'] != 100) {
276 276
 				$statusCode = $code['code'];
277 277
 				$statusMessage = $code['meta']['message'];
278 278
 				break;
@@ -289,7 +289,7 @@  discard block
 block discarded – undo
289 289
 	 */
290 290
 	private static function isAuthorised($action) {
291 291
 		$level = $action['authlevel'];
292
-		switch($level) {
292
+		switch ($level) {
293 293
 			case API::GUEST_AUTH:
294 294
 				// Anyone can access
295 295
 				return true;
@@ -299,16 +299,16 @@  discard block
 block discarded – undo
299 299
 			case API::SUBADMIN_AUTH:
300 300
 				// Check for subadmin
301 301
 				$user = self::loginUser();
302
-				if(!$user) {
302
+				if (!$user) {
303 303
 					return false;
304 304
 				} else {
305 305
 					$userObject = \OC::$server->getUserSession()->getUser();
306
-					if($userObject === null) {
306
+					if ($userObject === null) {
307 307
 						return false;
308 308
 					}
309 309
 					$isSubAdmin = \OC::$server->getGroupManager()->getSubAdmin()->isSubAdmin($userObject);
310 310
 					$admin = OC_User::isAdminUser($user);
311
-					if($isSubAdmin || $admin) {
311
+					if ($isSubAdmin || $admin) {
312 312
 						return true;
313 313
 					} else {
314 314
 						return false;
@@ -317,7 +317,7 @@  discard block
 block discarded – undo
317 317
 			case API::ADMIN_AUTH:
318 318
 				// Check for admin
319 319
 				$user = self::loginUser();
320
-				if(!$user) {
320
+				if (!$user) {
321 321
 					return false;
322 322
 				} else {
323 323
 					return OC_User::isAdminUser($user);
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
 	 * @return string|false (username, or false on failure)
334 334
 	 */
335 335
 	private static function loginUser() {
336
-		if(self::$isLoggedIn === true) {
336
+		if (self::$isLoggedIn === true) {
337 337
 			return \OC_User::getUser();
338 338
 		}
339 339
 
@@ -354,7 +354,7 @@  discard block
 block discarded – undo
354 354
 
355 355
 		// basic auth - because OC_User::login will create a new session we shall only try to login
356 356
 		// if user and pass are set
357
-		if(isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW']) ) {
357
+		if (isset($_SERVER['PHP_AUTH_USER']) && isset($_SERVER['PHP_AUTH_PW'])) {
358 358
 			$authUser = $_SERVER['PHP_AUTH_USER'];
359 359
 			$authPw = $_SERVER['PHP_AUTH_PW'];
360 360
 			$return = OC_User::login($authUser, $authPw);
@@ -389,13 +389,13 @@  discard block
 block discarded – undo
389 389
 	 * @param OC_OCS_Result $result
390 390
 	 * @param string $format the format xml|json
391 391
 	 */
392
-	public static function respond($result, $format='xml') {
392
+	public static function respond($result, $format = 'xml') {
393 393
 		$request = \OC::$server->getRequest();
394 394
 
395 395
 		// Send 401 headers if unauthorised
396
-		if($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
396
+		if ($result->getStatusCode() === API::RESPOND_UNAUTHORISED) {
397 397
 			// If request comes from JS return dummy auth request
398
-			if($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
398
+			if ($request->getHeader('X-Requested-With') === 'XMLHttpRequest') {
399 399
 				header('WWW-Authenticate: DummyBasic realm="Authorisation Required"');
400 400
 			} else {
401 401
 				header('WWW-Authenticate: Basic realm="Authorisation Required"');
@@ -403,8 +403,8 @@  discard block
 block discarded – undo
403 403
 			header('HTTP/1.0 401 Unauthorized');
404 404
 		}
405 405
 
406
-		foreach($result->getHeaders() as $name => $value) {
407
-			header($name . ': ' . $value);
406
+		foreach ($result->getHeaders() as $name => $value) {
407
+			header($name.': '.$value);
408 408
 		}
409 409
 
410 410
 		$meta = $result->getMeta();
@@ -426,14 +426,14 @@  discard block
 block discarded – undo
426 426
 	 * @param XMLWriter $writer
427 427
 	 */
428 428
 	private static function toXML($array, $writer) {
429
-		foreach($array as $k => $v) {
429
+		foreach ($array as $k => $v) {
430 430
 			if ($k[0] === '@') {
431 431
 				$writer->writeAttribute(substr($k, 1), $v);
432 432
 				continue;
433 433
 			} else if (is_numeric($k)) {
434 434
 				$k = 'element';
435 435
 			}
436
-			if(is_array($v)) {
436
+			if (is_array($v)) {
437 437
 				$writer->startElement($k);
438 438
 				self::toXML($v, $writer);
439 439
 				$writer->endElement();
Please login to merge, or discard this patch.
lib/private/app/appmanager.php 3 patches
Doc Comments   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 	/**
118 118
 	 * List all installed apps
119 119
 	 *
120
-	 * @return string[]
120
+	 * @return integer[]
121 121
 	 */
122 122
 	public function getInstalledApps() {
123 123
 		return array_keys($this->getInstalledAppsValues());
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 	/**
275 275
 	 * Returns a list of apps that need upgrade
276 276
 	 *
277
-	 * @param array $version ownCloud version as array of version components
277
+	 * @param array $ocVersion ownCloud version as array of version components
278 278
 	 * @return array list of app info from apps that need an upgrade
279 279
 	 *
280 280
 	 * @internal
@@ -344,6 +344,9 @@  discard block
 block discarded – undo
344 344
 		return in_array($appId, $this->shippedApps);
345 345
 	}
346 346
 
347
+	/**
348
+	 * @param string $appId
349
+	 */
347 350
 	private function isAlwaysEnabled($appId) {
348 351
 		$alwaysEnabled = $this->getAlwaysEnabledApps();
349 352
 		return in_array($appId, $alwaysEnabled);
Please login to merge, or discard this patch.
Indentation   +331 added lines, -331 removed lines patch added patch discarded remove patch
@@ -41,335 +41,335 @@
 block discarded – undo
41 41
 
42 42
 class AppManager implements IAppManager {
43 43
 
44
-	/**
45
-	 * Apps with these types can not be enabled for certain groups only
46
-	 * @var string[]
47
-	 */
48
-	protected $protectedAppTypes = [
49
-		'filesystem',
50
-		'prelogin',
51
-		'authentication',
52
-		'logging',
53
-		'prevent_group_restriction',
54
-	];
55
-
56
-	/** @var \OCP\IUserSession */
57
-	private $userSession;
58
-
59
-	/** @var \OCP\IAppConfig */
60
-	private $appConfig;
61
-
62
-	/** @var \OCP\IGroupManager */
63
-	private $groupManager;
64
-
65
-	/** @var \OCP\ICacheFactory */
66
-	private $memCacheFactory;
67
-
68
-	/** @var string[] $appId => $enabled */
69
-	private $installedAppsCache;
70
-
71
-	/** @var string[] */
72
-	private $shippedApps;
73
-
74
-	/** @var string[] */
75
-	private $alwaysEnabled;
76
-
77
-	/** @var EventDispatcherInterface */
78
-	private $dispatcher;
79
-
80
-	/**
81
-	 * @param \OCP\IUserSession $userSession
82
-	 * @param \OCP\IAppConfig $appConfig
83
-	 * @param \OCP\IGroupManager $groupManager
84
-	 * @param \OCP\ICacheFactory $memCacheFactory
85
-	 */
86
-	public function __construct(IUserSession $userSession,
87
-								IAppConfig $appConfig,
88
-								IGroupManager $groupManager,
89
-								ICacheFactory $memCacheFactory,
90
-								EventDispatcherInterface $dispatcher) {
91
-		$this->userSession = $userSession;
92
-		$this->appConfig = $appConfig;
93
-		$this->groupManager = $groupManager;
94
-		$this->memCacheFactory = $memCacheFactory;
95
-		$this->dispatcher = $dispatcher;
96
-	}
97
-
98
-	/**
99
-	 * @return string[] $appId => $enabled
100
-	 */
101
-	private function getInstalledAppsValues() {
102
-		if (!$this->installedAppsCache) {
103
-			$values = $this->appConfig->getValues(false, 'enabled');
104
-
105
-			$alwaysEnabledApps = $this->getAlwaysEnabledApps();
106
-			foreach($alwaysEnabledApps as $appId) {
107
-				$values[$appId] = 'yes';
108
-			}
109
-
110
-			$this->installedAppsCache = array_filter($values, function ($value) {
111
-				return $value !== 'no';
112
-			});
113
-			ksort($this->installedAppsCache);
114
-		}
115
-		return $this->installedAppsCache;
116
-	}
117
-
118
-	/**
119
-	 * List all installed apps
120
-	 *
121
-	 * @return string[]
122
-	 */
123
-	public function getInstalledApps() {
124
-		return array_keys($this->getInstalledAppsValues());
125
-	}
126
-
127
-	/**
128
-	 * List all apps enabled for a user
129
-	 *
130
-	 * @param \OCP\IUser $user
131
-	 * @return string[]
132
-	 */
133
-	public function getEnabledAppsForUser(IUser $user) {
134
-		$apps = $this->getInstalledAppsValues();
135
-		$appsForUser = array_filter($apps, function ($enabled) use ($user) {
136
-			return $this->checkAppForUser($enabled, $user);
137
-		});
138
-		return array_keys($appsForUser);
139
-	}
140
-
141
-	/**
142
-	 * Check if an app is enabled for user
143
-	 *
144
-	 * @param string $appId
145
-	 * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
146
-	 * @return bool
147
-	 */
148
-	public function isEnabledForUser($appId, $user = null) {
149
-		if ($this->isAlwaysEnabled($appId)) {
150
-			return true;
151
-		}
152
-		if (is_null($user)) {
153
-			$user = $this->userSession->getUser();
154
-		}
155
-		$installedApps = $this->getInstalledAppsValues();
156
-		if (isset($installedApps[$appId])) {
157
-			return $this->checkAppForUser($installedApps[$appId], $user);
158
-		} else {
159
-			return false;
160
-		}
161
-	}
162
-
163
-	/**
164
-	 * @param string $enabled
165
-	 * @param IUser $user
166
-	 * @return bool
167
-	 */
168
-	private function checkAppForUser($enabled, $user) {
169
-		if ($enabled === 'yes') {
170
-			return true;
171
-		} elseif (is_null($user)) {
172
-			return false;
173
-		} else {
174
-			if(empty($enabled)){
175
-				return false;
176
-			}
177
-
178
-			$groupIds = json_decode($enabled);
179
-
180
-			if (!is_array($groupIds)) {
181
-				$jsonError = json_last_error();
182
-				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
183
-				return false;
184
-			}
185
-
186
-			$userGroups = $this->groupManager->getUserGroupIds($user);
187
-			foreach ($userGroups as $groupId) {
188
-				if (array_search($groupId, $groupIds) !== false) {
189
-					return true;
190
-				}
191
-			}
192
-			return false;
193
-		}
194
-	}
195
-
196
-	/**
197
-	 * Check if an app is installed in the instance
198
-	 *
199
-	 * @param string $appId
200
-	 * @return bool
201
-	 */
202
-	public function isInstalled($appId) {
203
-		$installedApps = $this->getInstalledAppsValues();
204
-		return isset($installedApps[$appId]);
205
-	}
206
-
207
-	/**
208
-	 * Enable an app for every user
209
-	 *
210
-	 * @param string $appId
211
-	 */
212
-	public function enableApp($appId) {
213
-		$this->installedAppsCache[$appId] = 'yes';
214
-		$this->appConfig->setValue($appId, 'enabled', 'yes');
215
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
216
-			ManagerEvent::EVENT_APP_ENABLE, $appId
217
-		));
218
-		$this->clearAppsCache();
219
-	}
220
-
221
-	/**
222
-	 * Enable an app only for specific groups
223
-	 *
224
-	 * @param string $appId
225
-	 * @param \OCP\IGroup[] $groups
226
-	 * @throws \Exception if app can't be enabled for groups
227
-	 */
228
-	public function enableAppForGroups($appId, $groups) {
229
-		$info = $this->getAppInfo($appId);
230
-		if (!empty($info['types'])) {
231
-			$protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
232
-			if (!empty($protectedTypes)) {
233
-				throw new \Exception("$appId can't be enabled for groups.");
234
-			}
235
-		}
236
-
237
-		$groupIds = array_map(function ($group) {
238
-			/** @var \OCP\IGroup $group */
239
-			return $group->getGID();
240
-		}, $groups);
241
-		$this->installedAppsCache[$appId] = json_encode($groupIds);
242
-		$this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
243
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
244
-			ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
245
-		));
246
-		$this->clearAppsCache();
247
-	}
248
-
249
-	/**
250
-	 * Disable an app for every user
251
-	 *
252
-	 * @param string $appId
253
-	 * @throws \Exception if app can't be disabled
254
-	 */
255
-	public function disableApp($appId) {
256
-		if ($this->isAlwaysEnabled($appId)) {
257
-			throw new \Exception("$appId can't be disabled.");
258
-		}
259
-		unset($this->installedAppsCache[$appId]);
260
-		$this->appConfig->setValue($appId, 'enabled', 'no');
261
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
262
-			ManagerEvent::EVENT_APP_DISABLE, $appId
263
-		));
264
-		$this->clearAppsCache();
265
-	}
266
-
267
-	/**
268
-	 * Clear the cached list of apps when enabling/disabling an app
269
-	 */
270
-	public function clearAppsCache() {
271
-		$settingsMemCache = $this->memCacheFactory->create('settings');
272
-		$settingsMemCache->clear('listApps');
273
-	}
274
-
275
-	/**
276
-	 * Returns a list of apps that need upgrade
277
-	 *
278
-	 * @param array $version ownCloud version as array of version components
279
-	 * @return array list of app info from apps that need an upgrade
280
-	 *
281
-	 * @internal
282
-	 */
283
-	public function getAppsNeedingUpgrade($ocVersion) {
284
-		$appsToUpgrade = [];
285
-		$apps = $this->getInstalledApps();
286
-		foreach ($apps as $appId) {
287
-			$appInfo = $this->getAppInfo($appId);
288
-			$appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
289
-			if ($appDbVersion
290
-				&& isset($appInfo['version'])
291
-				&& version_compare($appInfo['version'], $appDbVersion, '>')
292
-				&& \OC_App::isAppCompatible($ocVersion, $appInfo)
293
-			) {
294
-				$appsToUpgrade[] = $appInfo;
295
-			}
296
-		}
297
-
298
-		return $appsToUpgrade;
299
-	}
300
-
301
-	/**
302
-	 * Returns the app information from "appinfo/info.xml".
303
-	 *
304
-	 * If no version was present in "appinfo/info.xml", reads it
305
-	 * from the external "appinfo/version" file instead.
306
-	 *
307
-	 * @param string $appId app id
308
-	 *
309
-	 * @return array app iinfo
310
-	 *
311
-	 * @internal
312
-	 */
313
-	public function getAppInfo($appId) {
314
-		$appInfo = \OC_App::getAppInfo($appId);
315
-		if (!isset($appInfo['version'])) {
316
-			// read version from separate file
317
-			$appInfo['version'] = \OC_App::getAppVersion($appId);
318
-		}
319
-		return $appInfo;
320
-	}
321
-
322
-	/**
323
-	 * Returns a list of apps incompatible with the given version
324
-	 *
325
-	 * @param array $version ownCloud version as array of version components
326
-	 *
327
-	 * @return array list of app info from incompatible apps
328
-	 *
329
-	 * @internal
330
-	 */
331
-	public function getIncompatibleApps($version) {
332
-		$apps = $this->getInstalledApps();
333
-		$incompatibleApps = array();
334
-		foreach ($apps as $appId) {
335
-			$info = $this->getAppInfo($appId);
336
-			if (!\OC_App::isAppCompatible($version, $info)) {
337
-				$incompatibleApps[] = $info;
338
-			}
339
-		}
340
-		return $incompatibleApps;
341
-	}
342
-
343
-	/**
344
-	 * @inheritdoc
345
-	 */
346
-	public function isShipped($appId) {
347
-		$this->loadShippedJson();
348
-		return in_array($appId, $this->shippedApps);
349
-	}
350
-
351
-	private function isAlwaysEnabled($appId) {
352
-		$alwaysEnabled = $this->getAlwaysEnabledApps();
353
-		return in_array($appId, $alwaysEnabled);
354
-	}
355
-
356
-	private function loadShippedJson() {
357
-		if (is_null($this->shippedApps)) {
358
-			$shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
359
-			if (!file_exists($shippedJson)) {
360
-				throw new \Exception("File not found: $shippedJson");
361
-			}
362
-			$content = json_decode(file_get_contents($shippedJson), true);
363
-			$this->shippedApps = $content['shippedApps'];
364
-			$this->alwaysEnabled = $content['alwaysEnabled'];
365
-		}
366
-	}
367
-
368
-	/**
369
-	 * @inheritdoc
370
-	 */
371
-	public function getAlwaysEnabledApps() {
372
-		$this->loadShippedJson();
373
-		return $this->alwaysEnabled;
374
-	}
44
+    /**
45
+     * Apps with these types can not be enabled for certain groups only
46
+     * @var string[]
47
+     */
48
+    protected $protectedAppTypes = [
49
+        'filesystem',
50
+        'prelogin',
51
+        'authentication',
52
+        'logging',
53
+        'prevent_group_restriction',
54
+    ];
55
+
56
+    /** @var \OCP\IUserSession */
57
+    private $userSession;
58
+
59
+    /** @var \OCP\IAppConfig */
60
+    private $appConfig;
61
+
62
+    /** @var \OCP\IGroupManager */
63
+    private $groupManager;
64
+
65
+    /** @var \OCP\ICacheFactory */
66
+    private $memCacheFactory;
67
+
68
+    /** @var string[] $appId => $enabled */
69
+    private $installedAppsCache;
70
+
71
+    /** @var string[] */
72
+    private $shippedApps;
73
+
74
+    /** @var string[] */
75
+    private $alwaysEnabled;
76
+
77
+    /** @var EventDispatcherInterface */
78
+    private $dispatcher;
79
+
80
+    /**
81
+     * @param \OCP\IUserSession $userSession
82
+     * @param \OCP\IAppConfig $appConfig
83
+     * @param \OCP\IGroupManager $groupManager
84
+     * @param \OCP\ICacheFactory $memCacheFactory
85
+     */
86
+    public function __construct(IUserSession $userSession,
87
+                                IAppConfig $appConfig,
88
+                                IGroupManager $groupManager,
89
+                                ICacheFactory $memCacheFactory,
90
+                                EventDispatcherInterface $dispatcher) {
91
+        $this->userSession = $userSession;
92
+        $this->appConfig = $appConfig;
93
+        $this->groupManager = $groupManager;
94
+        $this->memCacheFactory = $memCacheFactory;
95
+        $this->dispatcher = $dispatcher;
96
+    }
97
+
98
+    /**
99
+     * @return string[] $appId => $enabled
100
+     */
101
+    private function getInstalledAppsValues() {
102
+        if (!$this->installedAppsCache) {
103
+            $values = $this->appConfig->getValues(false, 'enabled');
104
+
105
+            $alwaysEnabledApps = $this->getAlwaysEnabledApps();
106
+            foreach($alwaysEnabledApps as $appId) {
107
+                $values[$appId] = 'yes';
108
+            }
109
+
110
+            $this->installedAppsCache = array_filter($values, function ($value) {
111
+                return $value !== 'no';
112
+            });
113
+            ksort($this->installedAppsCache);
114
+        }
115
+        return $this->installedAppsCache;
116
+    }
117
+
118
+    /**
119
+     * List all installed apps
120
+     *
121
+     * @return string[]
122
+     */
123
+    public function getInstalledApps() {
124
+        return array_keys($this->getInstalledAppsValues());
125
+    }
126
+
127
+    /**
128
+     * List all apps enabled for a user
129
+     *
130
+     * @param \OCP\IUser $user
131
+     * @return string[]
132
+     */
133
+    public function getEnabledAppsForUser(IUser $user) {
134
+        $apps = $this->getInstalledAppsValues();
135
+        $appsForUser = array_filter($apps, function ($enabled) use ($user) {
136
+            return $this->checkAppForUser($enabled, $user);
137
+        });
138
+        return array_keys($appsForUser);
139
+    }
140
+
141
+    /**
142
+     * Check if an app is enabled for user
143
+     *
144
+     * @param string $appId
145
+     * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
146
+     * @return bool
147
+     */
148
+    public function isEnabledForUser($appId, $user = null) {
149
+        if ($this->isAlwaysEnabled($appId)) {
150
+            return true;
151
+        }
152
+        if (is_null($user)) {
153
+            $user = $this->userSession->getUser();
154
+        }
155
+        $installedApps = $this->getInstalledAppsValues();
156
+        if (isset($installedApps[$appId])) {
157
+            return $this->checkAppForUser($installedApps[$appId], $user);
158
+        } else {
159
+            return false;
160
+        }
161
+    }
162
+
163
+    /**
164
+     * @param string $enabled
165
+     * @param IUser $user
166
+     * @return bool
167
+     */
168
+    private function checkAppForUser($enabled, $user) {
169
+        if ($enabled === 'yes') {
170
+            return true;
171
+        } elseif (is_null($user)) {
172
+            return false;
173
+        } else {
174
+            if(empty($enabled)){
175
+                return false;
176
+            }
177
+
178
+            $groupIds = json_decode($enabled);
179
+
180
+            if (!is_array($groupIds)) {
181
+                $jsonError = json_last_error();
182
+                \OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
183
+                return false;
184
+            }
185
+
186
+            $userGroups = $this->groupManager->getUserGroupIds($user);
187
+            foreach ($userGroups as $groupId) {
188
+                if (array_search($groupId, $groupIds) !== false) {
189
+                    return true;
190
+                }
191
+            }
192
+            return false;
193
+        }
194
+    }
195
+
196
+    /**
197
+     * Check if an app is installed in the instance
198
+     *
199
+     * @param string $appId
200
+     * @return bool
201
+     */
202
+    public function isInstalled($appId) {
203
+        $installedApps = $this->getInstalledAppsValues();
204
+        return isset($installedApps[$appId]);
205
+    }
206
+
207
+    /**
208
+     * Enable an app for every user
209
+     *
210
+     * @param string $appId
211
+     */
212
+    public function enableApp($appId) {
213
+        $this->installedAppsCache[$appId] = 'yes';
214
+        $this->appConfig->setValue($appId, 'enabled', 'yes');
215
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
216
+            ManagerEvent::EVENT_APP_ENABLE, $appId
217
+        ));
218
+        $this->clearAppsCache();
219
+    }
220
+
221
+    /**
222
+     * Enable an app only for specific groups
223
+     *
224
+     * @param string $appId
225
+     * @param \OCP\IGroup[] $groups
226
+     * @throws \Exception if app can't be enabled for groups
227
+     */
228
+    public function enableAppForGroups($appId, $groups) {
229
+        $info = $this->getAppInfo($appId);
230
+        if (!empty($info['types'])) {
231
+            $protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
232
+            if (!empty($protectedTypes)) {
233
+                throw new \Exception("$appId can't be enabled for groups.");
234
+            }
235
+        }
236
+
237
+        $groupIds = array_map(function ($group) {
238
+            /** @var \OCP\IGroup $group */
239
+            return $group->getGID();
240
+        }, $groups);
241
+        $this->installedAppsCache[$appId] = json_encode($groupIds);
242
+        $this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
243
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
244
+            ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
245
+        ));
246
+        $this->clearAppsCache();
247
+    }
248
+
249
+    /**
250
+     * Disable an app for every user
251
+     *
252
+     * @param string $appId
253
+     * @throws \Exception if app can't be disabled
254
+     */
255
+    public function disableApp($appId) {
256
+        if ($this->isAlwaysEnabled($appId)) {
257
+            throw new \Exception("$appId can't be disabled.");
258
+        }
259
+        unset($this->installedAppsCache[$appId]);
260
+        $this->appConfig->setValue($appId, 'enabled', 'no');
261
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
262
+            ManagerEvent::EVENT_APP_DISABLE, $appId
263
+        ));
264
+        $this->clearAppsCache();
265
+    }
266
+
267
+    /**
268
+     * Clear the cached list of apps when enabling/disabling an app
269
+     */
270
+    public function clearAppsCache() {
271
+        $settingsMemCache = $this->memCacheFactory->create('settings');
272
+        $settingsMemCache->clear('listApps');
273
+    }
274
+
275
+    /**
276
+     * Returns a list of apps that need upgrade
277
+     *
278
+     * @param array $version ownCloud version as array of version components
279
+     * @return array list of app info from apps that need an upgrade
280
+     *
281
+     * @internal
282
+     */
283
+    public function getAppsNeedingUpgrade($ocVersion) {
284
+        $appsToUpgrade = [];
285
+        $apps = $this->getInstalledApps();
286
+        foreach ($apps as $appId) {
287
+            $appInfo = $this->getAppInfo($appId);
288
+            $appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
289
+            if ($appDbVersion
290
+                && isset($appInfo['version'])
291
+                && version_compare($appInfo['version'], $appDbVersion, '>')
292
+                && \OC_App::isAppCompatible($ocVersion, $appInfo)
293
+            ) {
294
+                $appsToUpgrade[] = $appInfo;
295
+            }
296
+        }
297
+
298
+        return $appsToUpgrade;
299
+    }
300
+
301
+    /**
302
+     * Returns the app information from "appinfo/info.xml".
303
+     *
304
+     * If no version was present in "appinfo/info.xml", reads it
305
+     * from the external "appinfo/version" file instead.
306
+     *
307
+     * @param string $appId app id
308
+     *
309
+     * @return array app iinfo
310
+     *
311
+     * @internal
312
+     */
313
+    public function getAppInfo($appId) {
314
+        $appInfo = \OC_App::getAppInfo($appId);
315
+        if (!isset($appInfo['version'])) {
316
+            // read version from separate file
317
+            $appInfo['version'] = \OC_App::getAppVersion($appId);
318
+        }
319
+        return $appInfo;
320
+    }
321
+
322
+    /**
323
+     * Returns a list of apps incompatible with the given version
324
+     *
325
+     * @param array $version ownCloud version as array of version components
326
+     *
327
+     * @return array list of app info from incompatible apps
328
+     *
329
+     * @internal
330
+     */
331
+    public function getIncompatibleApps($version) {
332
+        $apps = $this->getInstalledApps();
333
+        $incompatibleApps = array();
334
+        foreach ($apps as $appId) {
335
+            $info = $this->getAppInfo($appId);
336
+            if (!\OC_App::isAppCompatible($version, $info)) {
337
+                $incompatibleApps[] = $info;
338
+            }
339
+        }
340
+        return $incompatibleApps;
341
+    }
342
+
343
+    /**
344
+     * @inheritdoc
345
+     */
346
+    public function isShipped($appId) {
347
+        $this->loadShippedJson();
348
+        return in_array($appId, $this->shippedApps);
349
+    }
350
+
351
+    private function isAlwaysEnabled($appId) {
352
+        $alwaysEnabled = $this->getAlwaysEnabledApps();
353
+        return in_array($appId, $alwaysEnabled);
354
+    }
355
+
356
+    private function loadShippedJson() {
357
+        if (is_null($this->shippedApps)) {
358
+            $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
359
+            if (!file_exists($shippedJson)) {
360
+                throw new \Exception("File not found: $shippedJson");
361
+            }
362
+            $content = json_decode(file_get_contents($shippedJson), true);
363
+            $this->shippedApps = $content['shippedApps'];
364
+            $this->alwaysEnabled = $content['alwaysEnabled'];
365
+        }
366
+    }
367
+
368
+    /**
369
+     * @inheritdoc
370
+     */
371
+    public function getAlwaysEnabledApps() {
372
+        $this->loadShippedJson();
373
+        return $this->alwaysEnabled;
374
+    }
375 375
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -104,11 +104,11 @@  discard block
 block discarded – undo
104 104
 			$values = $this->appConfig->getValues(false, 'enabled');
105 105
 
106 106
 			$alwaysEnabledApps = $this->getAlwaysEnabledApps();
107
-			foreach($alwaysEnabledApps as $appId) {
107
+			foreach ($alwaysEnabledApps as $appId) {
108 108
 				$values[$appId] = 'yes';
109 109
 			}
110 110
 
111
-			$this->installedAppsCache = array_filter($values, function ($value) {
111
+			$this->installedAppsCache = array_filter($values, function($value) {
112 112
 				return $value !== 'no';
113 113
 			});
114 114
 			ksort($this->installedAppsCache);
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 	 */
134 134
 	public function getEnabledAppsForUser(IUser $user) {
135 135
 		$apps = $this->getInstalledAppsValues();
136
-		$appsForUser = array_filter($apps, function ($enabled) use ($user) {
136
+		$appsForUser = array_filter($apps, function($enabled) use ($user) {
137 137
 			return $this->checkAppForUser($enabled, $user);
138 138
 		});
139 139
 		return array_keys($appsForUser);
@@ -172,7 +172,7 @@  discard block
 block discarded – undo
172 172
 		} elseif (is_null($user)) {
173 173
 			return false;
174 174
 		} else {
175
-			if(empty($enabled)){
175
+			if (empty($enabled)) {
176 176
 				return false;
177 177
 			}
178 178
 
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
 
181 181
 			if (!is_array($groupIds)) {
182 182
 				$jsonError = json_last_error();
183
-				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
183
+				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: '.print_r($enabled, true).' - json error code: '.$jsonError, ['app' => 'lib']);
184 184
 				return false;
185 185
 			}
186 186
 
@@ -235,7 +235,7 @@  discard block
 block discarded – undo
235 235
 			}
236 236
 		}
237 237
 
238
-		$groupIds = array_map(function ($group) {
238
+		$groupIds = array_map(function($group) {
239 239
 			/** @var \OCP\IGroup $group */
240 240
 			return $group->getGID();
241 241
 		}, $groups);
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
 
354 354
 	private function loadShippedJson() {
355 355
 		if (is_null($this->shippedApps)) {
356
-			$shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
356
+			$shippedJson = \OC::$SERVERROOT.'/core/shipped.json';
357 357
 			if (!file_exists($shippedJson)) {
358 358
 				throw new \Exception("File not found: $shippedJson");
359 359
 			}
Please login to merge, or discard this patch.
lib/private/app/codechecker/nodevisitor.php 3 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -296,6 +296,9 @@
 block discarded – undo
296 296
 		}
297 297
 	}
298 298
 
299
+	/**
300
+	 * @param string $name
301
+	 */
299 302
 	private function buildReason($name, $errorCode) {
300 303
 		if (isset($this->errorMessages[$errorCode])) {
301 304
 			$desc = $this->list->getDescription($errorCode, $name);
Please login to merge, or discard this patch.
Indentation   +276 added lines, -276 removed lines patch added patch discarded remove patch
@@ -29,280 +29,280 @@
 block discarded – undo
29 29
 use PhpParser\NodeVisitorAbstract;
30 30
 
31 31
 class NodeVisitor extends NodeVisitorAbstract {
32
-	/** @var ICheck */
33
-	protected $list;
34
-
35
-	/** @var string */
36
-	protected $blackListDescription;
37
-	/** @var string[] */
38
-	protected $blackListedClassNames;
39
-	/** @var string[] */
40
-	protected $blackListedConstants;
41
-	/** @var string[] */
42
-	protected $blackListedFunctions;
43
-	/** @var string[] */
44
-	protected $blackListedMethods;
45
-	/** @var bool */
46
-	protected $checkEqualOperatorUsage;
47
-	/** @var string[] */
48
-	protected $errorMessages;
49
-
50
-	/**
51
-	 * @param ICheck $list
52
-	 */
53
-	public function __construct(ICheck $list) {
54
-		$this->list = $list;
55
-
56
-		$this->blackListedClassNames = [];
57
-		foreach ($list->getClasses() as $class => $blackListInfo) {
58
-			if (is_numeric($class) && is_string($blackListInfo)) {
59
-				$class = $blackListInfo;
60
-				$blackListInfo = null;
61
-			}
62
-
63
-			$class = strtolower($class);
64
-			$this->blackListedClassNames[$class] = $class;
65
-		}
66
-
67
-		$this->blackListedConstants = [];
68
-		foreach ($list->getConstants() as $constantName => $blackListInfo) {
69
-			$constantName = strtolower($constantName);
70
-			$this->blackListedConstants[$constantName] = $constantName;
71
-		}
72
-
73
-		$this->blackListedFunctions = [];
74
-		foreach ($list->getFunctions() as $functionName => $blackListInfo) {
75
-			$functionName = strtolower($functionName);
76
-			$this->blackListedFunctions[$functionName] = $functionName;
77
-		}
78
-
79
-		$this->blackListedMethods = [];
80
-		foreach ($list->getMethods() as $functionName => $blackListInfo) {
81
-			$functionName = strtolower($functionName);
82
-			$this->blackListedMethods[$functionName] = $functionName;
83
-		}
84
-
85
-		$this->checkEqualOperatorUsage = $list->checkStrongComparisons();
86
-
87
-		$this->errorMessages = [
88
-			CodeChecker::CLASS_EXTENDS_NOT_ALLOWED => "%s class must not be extended",
89
-			CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED => "%s interface must not be implemented",
90
-			CodeChecker::STATIC_CALL_NOT_ALLOWED => "Static method of %s class must not be called",
91
-			CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED => "Constant of %s class must not not be fetched",
92
-			CodeChecker::CLASS_NEW_NOT_ALLOWED => "%s class must not be instantiated",
93
-			CodeChecker::CLASS_USE_NOT_ALLOWED => "%s class must not be imported with a use statement",
94
-			CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED => "Method of %s class must not be called",
95
-
96
-			CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED => "is discouraged",
97
-		];
98
-	}
99
-
100
-	/** @var array */
101
-	public $errors = [];
102
-
103
-	public function enterNode(Node $node) {
104
-		if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) {
105
-			$this->errors[]= [
106
-				'disallowedToken' => '==',
107
-				'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
108
-				'line' => $node->getLine(),
109
-				'reason' => $this->buildReason('==', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED)
110
-			];
111
-		}
112
-		if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) {
113
-			$this->errors[]= [
114
-				'disallowedToken' => '!=',
115
-				'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
116
-				'line' => $node->getLine(),
117
-				'reason' => $this->buildReason('!=', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED)
118
-			];
119
-		}
120
-		if ($node instanceof Node\Stmt\Class_) {
121
-			if (!is_null($node->extends)) {
122
-				$this->checkBlackList($node->extends->toString(), CodeChecker::CLASS_EXTENDS_NOT_ALLOWED, $node);
123
-			}
124
-			foreach ($node->implements as $implements) {
125
-				$this->checkBlackList($implements->toString(), CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED, $node);
126
-			}
127
-		}
128
-		if ($node instanceof Node\Expr\StaticCall) {
129
-			if (!is_null($node->class)) {
130
-				if ($node->class instanceof Name) {
131
-					$this->checkBlackList($node->class->toString(), CodeChecker::STATIC_CALL_NOT_ALLOWED, $node);
132
-
133
-					$this->checkBlackListFunction($node->class->toString(), $node->name, $node);
134
-					$this->checkBlackListMethod($node->class->toString(), $node->name, $node);
135
-				}
136
-
137
-				if ($node->class instanceof Node\Expr\Variable) {
138
-					/**
139
-					 * TODO: find a way to detect something like this:
140
-					 *       $c = "OC_API";
141
-					 *       $n = $c::call();
142
-					 */
143
-					// $this->checkBlackListMethod($node->class->..., $node->name, $node);
144
-				}
145
-			}
146
-		}
147
-		if ($node instanceof Node\Expr\MethodCall) {
148
-			if (!is_null($node->var)) {
149
-				if ($node->var instanceof Node\Expr\Variable) {
150
-					/**
151
-					 * TODO: find a way to detect something like this:
152
-					 *       $c = new OC_API();
153
-					 *       $n = $c::call();
154
-					 *       $n = $c->call();
155
-					 */
156
-					// $this->checkBlackListMethod($node->var->..., $node->name, $node);
157
-				}
158
-			}
159
-		}
160
-		if ($node instanceof Node\Expr\ClassConstFetch) {
161
-			if (!is_null($node->class)) {
162
-				if ($node->class instanceof Name) {
163
-					$this->checkBlackList($node->class->toString(), CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, $node);
164
-				}
165
-				if ($node->class instanceof Node\Expr\Variable) {
166
-					/**
167
-					 * TODO: find a way to detect something like this:
168
-					 *       $c = "OC_API";
169
-					 *       $n = $i::ADMIN_AUTH;
170
-					 */
171
-				} else {
172
-					$this->checkBlackListConstant($node->class->toString(), $node->name, $node);
173
-				}
174
-			}
175
-		}
176
-		if ($node instanceof Node\Expr\New_) {
177
-			if (!is_null($node->class)) {
178
-				if ($node->class instanceof Name) {
179
-					$this->checkBlackList($node->class->toString(), CodeChecker::CLASS_NEW_NOT_ALLOWED, $node);
180
-				}
181
-				if ($node->class instanceof Node\Expr\Variable) {
182
-					/**
183
-					 * TODO: find a way to detect something like this:
184
-					 *       $c = "OC_API";
185
-					 *       $n = new $i;
186
-					 */
187
-				}
188
-			}
189
-		}
190
-		if ($node instanceof Node\Stmt\UseUse) {
191
-			$this->checkBlackList($node->name->toString(), CodeChecker::CLASS_USE_NOT_ALLOWED, $node);
192
-			if ($node->alias) {
193
-				$this->addUseNameToBlackList($node->name->toString(), $node->alias);
194
-			} else {
195
-				$this->addUseNameToBlackList($node->name->toString(), $node->name->getLast());
196
-			}
197
-		}
198
-	}
199
-
200
-	/**
201
-	 * Check whether an alias was introduced for a namespace of a blacklisted class
202
-	 *
203
-	 * Example:
204
-	 * - Blacklist entry:      OCP\AppFramework\IApi
205
-	 * - Name:                 OCP\AppFramework
206
-	 * - Alias:                OAF
207
-	 * =>  new blacklist entry:  OAF\IApi
208
-	 *
209
-	 * @param string $name
210
-	 * @param string $alias
211
-	 */
212
-	private function addUseNameToBlackList($name, $alias) {
213
-		$name = strtolower($name);
214
-		$alias = strtolower($alias);
215
-
216
-		foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) {
217
-			if (strpos($blackListedClassName, $name . '\\') === 0) {
218
-				$aliasedClassName = str_replace($name, $alias, $blackListedClassName);
219
-				$this->blackListedClassNames[$aliasedClassName] = $blackListedClassName;
220
-			}
221
-		}
222
-
223
-		foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) {
224
-			if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) {
225
-				$aliasedConstantName = str_replace($name, $alias, $blackListedConstant);
226
-				$this->blackListedConstants[$aliasedConstantName] = $blackListedConstant;
227
-			}
228
-		}
229
-
230
-		foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) {
231
-			if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) {
232
-				$aliasedFunctionName = str_replace($name, $alias, $blackListedFunction);
233
-				$this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction;
234
-			}
235
-		}
236
-
237
-		foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) {
238
-			if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) {
239
-				$aliasedMethodName = str_replace($name, $alias, $blackListedMethod);
240
-				$this->blackListedMethods[$aliasedMethodName] = $blackListedMethod;
241
-			}
242
-		}
243
-	}
244
-
245
-	private function checkBlackList($name, $errorCode, Node $node) {
246
-		$lowerName = strtolower($name);
247
-
248
-		if (isset($this->blackListedClassNames[$lowerName])) {
249
-			$this->errors[]= [
250
-				'disallowedToken' => $name,
251
-				'errorCode' => $errorCode,
252
-				'line' => $node->getLine(),
253
-				'reason' => $this->buildReason($this->blackListedClassNames[$lowerName], $errorCode)
254
-			];
255
-		}
256
-	}
257
-
258
-	private function checkBlackListConstant($class, $constantName, Node $node) {
259
-		$name = $class . '::' . $constantName;
260
-		$lowerName = strtolower($name);
261
-
262
-		if (isset($this->blackListedConstants[$lowerName])) {
263
-			$this->errors[]= [
264
-				'disallowedToken' => $name,
265
-				'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED,
266
-				'line' => $node->getLine(),
267
-				'reason' => $this->buildReason($this->blackListedConstants[$lowerName], CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED)
268
-			];
269
-		}
270
-	}
271
-
272
-	private function checkBlackListFunction($class, $functionName, Node $node) {
273
-		$name = $class . '::' . $functionName;
274
-		$lowerName = strtolower($name);
275
-
276
-		if (isset($this->blackListedFunctions[$lowerName])) {
277
-			$this->errors[]= [
278
-				'disallowedToken' => $name,
279
-				'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED,
280
-				'line' => $node->getLine(),
281
-				'reason' => $this->buildReason($this->blackListedFunctions[$lowerName], CodeChecker::STATIC_CALL_NOT_ALLOWED)
282
-			];
283
-		}
284
-	}
285
-
286
-	private function checkBlackListMethod($class, $functionName, Node $node) {
287
-		$name = $class . '::' . $functionName;
288
-		$lowerName = strtolower($name);
289
-
290
-		if (isset($this->blackListedMethods[$lowerName])) {
291
-			$this->errors[]= [
292
-				'disallowedToken' => $name,
293
-				'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED,
294
-				'line' => $node->getLine(),
295
-				'reason' => $this->buildReason($this->blackListedMethods[$lowerName], CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED)
296
-			];
297
-		}
298
-	}
299
-
300
-	private function buildReason($name, $errorCode) {
301
-		if (isset($this->errorMessages[$errorCode])) {
302
-			$desc = $this->list->getDescription($errorCode, $name);
303
-			return sprintf($this->errorMessages[$errorCode], $desc);
304
-		}
305
-
306
-		return "$name usage not allowed - error: $errorCode";
307
-	}
32
+    /** @var ICheck */
33
+    protected $list;
34
+
35
+    /** @var string */
36
+    protected $blackListDescription;
37
+    /** @var string[] */
38
+    protected $blackListedClassNames;
39
+    /** @var string[] */
40
+    protected $blackListedConstants;
41
+    /** @var string[] */
42
+    protected $blackListedFunctions;
43
+    /** @var string[] */
44
+    protected $blackListedMethods;
45
+    /** @var bool */
46
+    protected $checkEqualOperatorUsage;
47
+    /** @var string[] */
48
+    protected $errorMessages;
49
+
50
+    /**
51
+     * @param ICheck $list
52
+     */
53
+    public function __construct(ICheck $list) {
54
+        $this->list = $list;
55
+
56
+        $this->blackListedClassNames = [];
57
+        foreach ($list->getClasses() as $class => $blackListInfo) {
58
+            if (is_numeric($class) && is_string($blackListInfo)) {
59
+                $class = $blackListInfo;
60
+                $blackListInfo = null;
61
+            }
62
+
63
+            $class = strtolower($class);
64
+            $this->blackListedClassNames[$class] = $class;
65
+        }
66
+
67
+        $this->blackListedConstants = [];
68
+        foreach ($list->getConstants() as $constantName => $blackListInfo) {
69
+            $constantName = strtolower($constantName);
70
+            $this->blackListedConstants[$constantName] = $constantName;
71
+        }
72
+
73
+        $this->blackListedFunctions = [];
74
+        foreach ($list->getFunctions() as $functionName => $blackListInfo) {
75
+            $functionName = strtolower($functionName);
76
+            $this->blackListedFunctions[$functionName] = $functionName;
77
+        }
78
+
79
+        $this->blackListedMethods = [];
80
+        foreach ($list->getMethods() as $functionName => $blackListInfo) {
81
+            $functionName = strtolower($functionName);
82
+            $this->blackListedMethods[$functionName] = $functionName;
83
+        }
84
+
85
+        $this->checkEqualOperatorUsage = $list->checkStrongComparisons();
86
+
87
+        $this->errorMessages = [
88
+            CodeChecker::CLASS_EXTENDS_NOT_ALLOWED => "%s class must not be extended",
89
+            CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED => "%s interface must not be implemented",
90
+            CodeChecker::STATIC_CALL_NOT_ALLOWED => "Static method of %s class must not be called",
91
+            CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED => "Constant of %s class must not not be fetched",
92
+            CodeChecker::CLASS_NEW_NOT_ALLOWED => "%s class must not be instantiated",
93
+            CodeChecker::CLASS_USE_NOT_ALLOWED => "%s class must not be imported with a use statement",
94
+            CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED => "Method of %s class must not be called",
95
+
96
+            CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED => "is discouraged",
97
+        ];
98
+    }
99
+
100
+    /** @var array */
101
+    public $errors = [];
102
+
103
+    public function enterNode(Node $node) {
104
+        if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) {
105
+            $this->errors[]= [
106
+                'disallowedToken' => '==',
107
+                'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
108
+                'line' => $node->getLine(),
109
+                'reason' => $this->buildReason('==', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED)
110
+            ];
111
+        }
112
+        if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) {
113
+            $this->errors[]= [
114
+                'disallowedToken' => '!=',
115
+                'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
116
+                'line' => $node->getLine(),
117
+                'reason' => $this->buildReason('!=', CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED)
118
+            ];
119
+        }
120
+        if ($node instanceof Node\Stmt\Class_) {
121
+            if (!is_null($node->extends)) {
122
+                $this->checkBlackList($node->extends->toString(), CodeChecker::CLASS_EXTENDS_NOT_ALLOWED, $node);
123
+            }
124
+            foreach ($node->implements as $implements) {
125
+                $this->checkBlackList($implements->toString(), CodeChecker::CLASS_IMPLEMENTS_NOT_ALLOWED, $node);
126
+            }
127
+        }
128
+        if ($node instanceof Node\Expr\StaticCall) {
129
+            if (!is_null($node->class)) {
130
+                if ($node->class instanceof Name) {
131
+                    $this->checkBlackList($node->class->toString(), CodeChecker::STATIC_CALL_NOT_ALLOWED, $node);
132
+
133
+                    $this->checkBlackListFunction($node->class->toString(), $node->name, $node);
134
+                    $this->checkBlackListMethod($node->class->toString(), $node->name, $node);
135
+                }
136
+
137
+                if ($node->class instanceof Node\Expr\Variable) {
138
+                    /**
139
+                     * TODO: find a way to detect something like this:
140
+                     *       $c = "OC_API";
141
+                     *       $n = $c::call();
142
+                     */
143
+                    // $this->checkBlackListMethod($node->class->..., $node->name, $node);
144
+                }
145
+            }
146
+        }
147
+        if ($node instanceof Node\Expr\MethodCall) {
148
+            if (!is_null($node->var)) {
149
+                if ($node->var instanceof Node\Expr\Variable) {
150
+                    /**
151
+                     * TODO: find a way to detect something like this:
152
+                     *       $c = new OC_API();
153
+                     *       $n = $c::call();
154
+                     *       $n = $c->call();
155
+                     */
156
+                    // $this->checkBlackListMethod($node->var->..., $node->name, $node);
157
+                }
158
+            }
159
+        }
160
+        if ($node instanceof Node\Expr\ClassConstFetch) {
161
+            if (!is_null($node->class)) {
162
+                if ($node->class instanceof Name) {
163
+                    $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED, $node);
164
+                }
165
+                if ($node->class instanceof Node\Expr\Variable) {
166
+                    /**
167
+                     * TODO: find a way to detect something like this:
168
+                     *       $c = "OC_API";
169
+                     *       $n = $i::ADMIN_AUTH;
170
+                     */
171
+                } else {
172
+                    $this->checkBlackListConstant($node->class->toString(), $node->name, $node);
173
+                }
174
+            }
175
+        }
176
+        if ($node instanceof Node\Expr\New_) {
177
+            if (!is_null($node->class)) {
178
+                if ($node->class instanceof Name) {
179
+                    $this->checkBlackList($node->class->toString(), CodeChecker::CLASS_NEW_NOT_ALLOWED, $node);
180
+                }
181
+                if ($node->class instanceof Node\Expr\Variable) {
182
+                    /**
183
+                     * TODO: find a way to detect something like this:
184
+                     *       $c = "OC_API";
185
+                     *       $n = new $i;
186
+                     */
187
+                }
188
+            }
189
+        }
190
+        if ($node instanceof Node\Stmt\UseUse) {
191
+            $this->checkBlackList($node->name->toString(), CodeChecker::CLASS_USE_NOT_ALLOWED, $node);
192
+            if ($node->alias) {
193
+                $this->addUseNameToBlackList($node->name->toString(), $node->alias);
194
+            } else {
195
+                $this->addUseNameToBlackList($node->name->toString(), $node->name->getLast());
196
+            }
197
+        }
198
+    }
199
+
200
+    /**
201
+     * Check whether an alias was introduced for a namespace of a blacklisted class
202
+     *
203
+     * Example:
204
+     * - Blacklist entry:      OCP\AppFramework\IApi
205
+     * - Name:                 OCP\AppFramework
206
+     * - Alias:                OAF
207
+     * =>  new blacklist entry:  OAF\IApi
208
+     *
209
+     * @param string $name
210
+     * @param string $alias
211
+     */
212
+    private function addUseNameToBlackList($name, $alias) {
213
+        $name = strtolower($name);
214
+        $alias = strtolower($alias);
215
+
216
+        foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) {
217
+            if (strpos($blackListedClassName, $name . '\\') === 0) {
218
+                $aliasedClassName = str_replace($name, $alias, $blackListedClassName);
219
+                $this->blackListedClassNames[$aliasedClassName] = $blackListedClassName;
220
+            }
221
+        }
222
+
223
+        foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) {
224
+            if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) {
225
+                $aliasedConstantName = str_replace($name, $alias, $blackListedConstant);
226
+                $this->blackListedConstants[$aliasedConstantName] = $blackListedConstant;
227
+            }
228
+        }
229
+
230
+        foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) {
231
+            if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) {
232
+                $aliasedFunctionName = str_replace($name, $alias, $blackListedFunction);
233
+                $this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction;
234
+            }
235
+        }
236
+
237
+        foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) {
238
+            if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) {
239
+                $aliasedMethodName = str_replace($name, $alias, $blackListedMethod);
240
+                $this->blackListedMethods[$aliasedMethodName] = $blackListedMethod;
241
+            }
242
+        }
243
+    }
244
+
245
+    private function checkBlackList($name, $errorCode, Node $node) {
246
+        $lowerName = strtolower($name);
247
+
248
+        if (isset($this->blackListedClassNames[$lowerName])) {
249
+            $this->errors[]= [
250
+                'disallowedToken' => $name,
251
+                'errorCode' => $errorCode,
252
+                'line' => $node->getLine(),
253
+                'reason' => $this->buildReason($this->blackListedClassNames[$lowerName], $errorCode)
254
+            ];
255
+        }
256
+    }
257
+
258
+    private function checkBlackListConstant($class, $constantName, Node $node) {
259
+        $name = $class . '::' . $constantName;
260
+        $lowerName = strtolower($name);
261
+
262
+        if (isset($this->blackListedConstants[$lowerName])) {
263
+            $this->errors[]= [
264
+                'disallowedToken' => $name,
265
+                'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED,
266
+                'line' => $node->getLine(),
267
+                'reason' => $this->buildReason($this->blackListedConstants[$lowerName], CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED)
268
+            ];
269
+        }
270
+    }
271
+
272
+    private function checkBlackListFunction($class, $functionName, Node $node) {
273
+        $name = $class . '::' . $functionName;
274
+        $lowerName = strtolower($name);
275
+
276
+        if (isset($this->blackListedFunctions[$lowerName])) {
277
+            $this->errors[]= [
278
+                'disallowedToken' => $name,
279
+                'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED,
280
+                'line' => $node->getLine(),
281
+                'reason' => $this->buildReason($this->blackListedFunctions[$lowerName], CodeChecker::STATIC_CALL_NOT_ALLOWED)
282
+            ];
283
+        }
284
+    }
285
+
286
+    private function checkBlackListMethod($class, $functionName, Node $node) {
287
+        $name = $class . '::' . $functionName;
288
+        $lowerName = strtolower($name);
289
+
290
+        if (isset($this->blackListedMethods[$lowerName])) {
291
+            $this->errors[]= [
292
+                'disallowedToken' => $name,
293
+                'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED,
294
+                'line' => $node->getLine(),
295
+                'reason' => $this->buildReason($this->blackListedMethods[$lowerName], CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED)
296
+            ];
297
+        }
298
+    }
299
+
300
+    private function buildReason($name, $errorCode) {
301
+        if (isset($this->errorMessages[$errorCode])) {
302
+            $desc = $this->list->getDescription($errorCode, $name);
303
+            return sprintf($this->errorMessages[$errorCode], $desc);
304
+        }
305
+
306
+        return "$name usage not allowed - error: $errorCode";
307
+    }
308 308
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
 
103 103
 	public function enterNode(Node $node) {
104 104
 		if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\Equal) {
105
-			$this->errors[]= [
105
+			$this->errors[] = [
106 106
 				'disallowedToken' => '==',
107 107
 				'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
108 108
 				'line' => $node->getLine(),
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 			];
111 111
 		}
112 112
 		if ($this->checkEqualOperatorUsage && $node instanceof Node\Expr\BinaryOp\NotEqual) {
113
-			$this->errors[]= [
113
+			$this->errors[] = [
114 114
 				'disallowedToken' => '!=',
115 115
 				'errorCode' => CodeChecker::OP_OPERATOR_USAGE_DISCOURAGED,
116 116
 				'line' => $node->getLine(),
@@ -214,28 +214,28 @@  discard block
 block discarded – undo
214 214
 		$alias = strtolower($alias);
215 215
 
216 216
 		foreach ($this->blackListedClassNames as $blackListedAlias => $blackListedClassName) {
217
-			if (strpos($blackListedClassName, $name . '\\') === 0) {
217
+			if (strpos($blackListedClassName, $name.'\\') === 0) {
218 218
 				$aliasedClassName = str_replace($name, $alias, $blackListedClassName);
219 219
 				$this->blackListedClassNames[$aliasedClassName] = $blackListedClassName;
220 220
 			}
221 221
 		}
222 222
 
223 223
 		foreach ($this->blackListedConstants as $blackListedAlias => $blackListedConstant) {
224
-			if (strpos($blackListedConstant, $name . '\\') === 0 || strpos($blackListedConstant, $name . '::') === 0) {
224
+			if (strpos($blackListedConstant, $name.'\\') === 0 || strpos($blackListedConstant, $name.'::') === 0) {
225 225
 				$aliasedConstantName = str_replace($name, $alias, $blackListedConstant);
226 226
 				$this->blackListedConstants[$aliasedConstantName] = $blackListedConstant;
227 227
 			}
228 228
 		}
229 229
 
230 230
 		foreach ($this->blackListedFunctions as $blackListedAlias => $blackListedFunction) {
231
-			if (strpos($blackListedFunction, $name . '\\') === 0 || strpos($blackListedFunction, $name . '::') === 0) {
231
+			if (strpos($blackListedFunction, $name.'\\') === 0 || strpos($blackListedFunction, $name.'::') === 0) {
232 232
 				$aliasedFunctionName = str_replace($name, $alias, $blackListedFunction);
233 233
 				$this->blackListedFunctions[$aliasedFunctionName] = $blackListedFunction;
234 234
 			}
235 235
 		}
236 236
 
237 237
 		foreach ($this->blackListedMethods as $blackListedAlias => $blackListedMethod) {
238
-			if (strpos($blackListedMethod, $name . '\\') === 0 || strpos($blackListedMethod, $name . '::') === 0) {
238
+			if (strpos($blackListedMethod, $name.'\\') === 0 || strpos($blackListedMethod, $name.'::') === 0) {
239 239
 				$aliasedMethodName = str_replace($name, $alias, $blackListedMethod);
240 240
 				$this->blackListedMethods[$aliasedMethodName] = $blackListedMethod;
241 241
 			}
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 		$lowerName = strtolower($name);
247 247
 
248 248
 		if (isset($this->blackListedClassNames[$lowerName])) {
249
-			$this->errors[]= [
249
+			$this->errors[] = [
250 250
 				'disallowedToken' => $name,
251 251
 				'errorCode' => $errorCode,
252 252
 				'line' => $node->getLine(),
@@ -256,11 +256,11 @@  discard block
 block discarded – undo
256 256
 	}
257 257
 
258 258
 	private function checkBlackListConstant($class, $constantName, Node $node) {
259
-		$name = $class . '::' . $constantName;
259
+		$name = $class.'::'.$constantName;
260 260
 		$lowerName = strtolower($name);
261 261
 
262 262
 		if (isset($this->blackListedConstants[$lowerName])) {
263
-			$this->errors[]= [
263
+			$this->errors[] = [
264 264
 				'disallowedToken' => $name,
265 265
 				'errorCode' => CodeChecker::CLASS_CONST_FETCH_NOT_ALLOWED,
266 266
 				'line' => $node->getLine(),
@@ -270,11 +270,11 @@  discard block
 block discarded – undo
270 270
 	}
271 271
 
272 272
 	private function checkBlackListFunction($class, $functionName, Node $node) {
273
-		$name = $class . '::' . $functionName;
273
+		$name = $class.'::'.$functionName;
274 274
 		$lowerName = strtolower($name);
275 275
 
276 276
 		if (isset($this->blackListedFunctions[$lowerName])) {
277
-			$this->errors[]= [
277
+			$this->errors[] = [
278 278
 				'disallowedToken' => $name,
279 279
 				'errorCode' => CodeChecker::STATIC_CALL_NOT_ALLOWED,
280 280
 				'line' => $node->getLine(),
@@ -284,11 +284,11 @@  discard block
 block discarded – undo
284 284
 	}
285 285
 
286 286
 	private function checkBlackListMethod($class, $functionName, Node $node) {
287
-		$name = $class . '::' . $functionName;
287
+		$name = $class.'::'.$functionName;
288 288
 		$lowerName = strtolower($name);
289 289
 
290 290
 		if (isset($this->blackListedMethods[$lowerName])) {
291
-			$this->errors[]= [
291
+			$this->errors[] = [
292 292
 				'disallowedToken' => $name,
293 293
 				'errorCode' => CodeChecker::CLASS_METHOD_CALL_NOT_ALLOWED,
294 294
 				'line' => $node->getLine(),
Please login to merge, or discard this patch.
lib/private/app/platform.php 2 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -23,7 +23,6 @@
 block discarded – undo
23 23
 
24 24
 namespace OC\App;
25 25
 
26
-use OC_Util;
27 26
 use OCP\IConfig;
28 27
 
29 28
 /**
Please login to merge, or discard this patch.
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -35,59 +35,59 @@
 block discarded – undo
35 35
  */
36 36
 class Platform {
37 37
 
38
-	/**
39
-	 * @param IConfig $config
40
-	 */
41
-	function __construct(IConfig $config) {
42
-		$this->config = $config;
43
-	}
38
+    /**
39
+     * @param IConfig $config
40
+     */
41
+    function __construct(IConfig $config) {
42
+        $this->config = $config;
43
+    }
44 44
 
45
-	/**
46
-	 * @return string
47
-	 */
48
-	public function getPhpVersion() {
49
-		return phpversion();
50
-	}
45
+    /**
46
+     * @return string
47
+     */
48
+    public function getPhpVersion() {
49
+        return phpversion();
50
+    }
51 51
 
52
-	/**
53
-	 * @return string
54
-	 */
55
-	public function getOcVersion() {
56
-		$v = \OCP\Util::getVersion();
57
-		return join('.', $v);
58
-	}
52
+    /**
53
+     * @return string
54
+     */
55
+    public function getOcVersion() {
56
+        $v = \OCP\Util::getVersion();
57
+        return join('.', $v);
58
+    }
59 59
 
60
-	/**
61
-	 * @return string
62
-	 */
63
-	public function getDatabase() {
64
-		$dbType = $this->config->getSystemValue('dbtype', 'sqlite');
65
-		if ($dbType === 'sqlite3') {
66
-			$dbType = 'sqlite';
67
-		}
60
+    /**
61
+     * @return string
62
+     */
63
+    public function getDatabase() {
64
+        $dbType = $this->config->getSystemValue('dbtype', 'sqlite');
65
+        if ($dbType === 'sqlite3') {
66
+            $dbType = 'sqlite';
67
+        }
68 68
 
69
-		return $dbType;
70
-	}
69
+        return $dbType;
70
+    }
71 71
 
72
-	/**
73
-	 * @return string
74
-	 */
75
-	public function getOS() {
76
-		return php_uname('s');
77
-	}
72
+    /**
73
+     * @return string
74
+     */
75
+    public function getOS() {
76
+        return php_uname('s');
77
+    }
78 78
 
79
-	/**
80
-	 * @param $command
81
-	 * @return bool
82
-	 */
83
-	public function isCommandKnown($command) {
84
-		$path = \OC_Helper::findBinaryPath($command);
85
-		return ($path !== null);
86
-	}
79
+    /**
80
+     * @param $command
81
+     * @return bool
82
+     */
83
+    public function isCommandKnown($command) {
84
+        $path = \OC_Helper::findBinaryPath($command);
85
+        return ($path !== null);
86
+    }
87 87
 
88
-	public function getLibraryVersion($name) {
89
-		$repo = new PlatformRepository();
90
-		$lib = $repo->findLibrary($name);
91
-		return $lib;
92
-	}
88
+    public function getLibraryVersion($name) {
89
+        $repo = new PlatformRepository();
90
+        $lib = $repo->findLibrary($name);
91
+        return $lib;
92
+    }
93 93
 }
Please login to merge, or discard this patch.