Completed
Pull Request — master (#3770)
by Thomas
38:05 queued 14:21
created
apps/user_ldap/lib/Jobs/UpdateGroups.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   +163 added lines, -163 removed lines patch added patch discarded remove patch
@@ -41,182 +41,182 @@
 block discarded – undo
41 41
 use OCA\User_LDAP\User\Manager;
42 42
 
43 43
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
44
-	static private $groupsFromDB;
45
-
46
-	static private $groupBE;
47
-
48
-	public function __construct(){
49
-		$this->interval = self::getRefreshInterval();
50
-	}
51
-
52
-	/**
53
-	 * @param mixed $argument
54
-	 */
55
-	public function run($argument){
56
-		self::updateGroups();
57
-	}
58
-
59
-	static public function updateGroups() {
60
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
61
-
62
-		$knownGroups = array_keys(self::getKnownGroups());
63
-		$actualGroups = self::getGroupBE()->getGroups();
64
-
65
-		if(empty($actualGroups) && empty($knownGroups)) {
66
-			\OCP\Util::writeLog('user_ldap',
67
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
68
-				\OCP\Util::INFO);
69
-			return;
70
-		}
71
-
72
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
73
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
74
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
75
-
76
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
77
-	}
78
-
79
-	/**
80
-	 * @return int
81
-	 */
82
-	static private function getRefreshInterval() {
83
-		//defaults to every hour
84
-		return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
85
-	}
86
-
87
-	/**
88
-	 * @param string[] $groups
89
-	 */
90
-	static private function handleKnownGroups($groups) {
91
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
92
-		$query = \OCP\DB::prepare('
44
+    static private $groupsFromDB;
45
+
46
+    static private $groupBE;
47
+
48
+    public function __construct(){
49
+        $this->interval = self::getRefreshInterval();
50
+    }
51
+
52
+    /**
53
+     * @param mixed $argument
54
+     */
55
+    public function run($argument){
56
+        self::updateGroups();
57
+    }
58
+
59
+    static public function updateGroups() {
60
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
61
+
62
+        $knownGroups = array_keys(self::getKnownGroups());
63
+        $actualGroups = self::getGroupBE()->getGroups();
64
+
65
+        if(empty($actualGroups) && empty($knownGroups)) {
66
+            \OCP\Util::writeLog('user_ldap',
67
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
68
+                \OCP\Util::INFO);
69
+            return;
70
+        }
71
+
72
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
73
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
74
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
75
+
76
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
77
+    }
78
+
79
+    /**
80
+     * @return int
81
+     */
82
+    static private function getRefreshInterval() {
83
+        //defaults to every hour
84
+        return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
85
+    }
86
+
87
+    /**
88
+     * @param string[] $groups
89
+     */
90
+    static private function handleKnownGroups($groups) {
91
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
92
+        $query = \OCP\DB::prepare('
93 93
 			UPDATE `*PREFIX*ldap_group_members`
94 94
 			SET `owncloudusers` = ?
95 95
 			WHERE `owncloudname` = ?
96 96
 		');
97
-		foreach($groups as $group) {
98
-			//we assume, that self::$groupsFromDB has been retrieved already
99
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
100
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
101
-			$hasChanged = false;
102
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
103
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
104
-				\OCP\Util::writeLog('user_ldap',
105
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
106
-				\OCP\Util::INFO);
107
-				$hasChanged = true;
108
-			}
109
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
110
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
111
-				\OCP\Util::writeLog('user_ldap',
112
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
113
-				\OCP\Util::INFO);
114
-				$hasChanged = true;
115
-			}
116
-			if($hasChanged) {
117
-				$query->execute(array(serialize($actualUsers), $group));
118
-			}
119
-		}
120
-		\OCP\Util::writeLog('user_ldap',
121
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
122
-			\OCP\Util::DEBUG);
123
-	}
124
-
125
-	/**
126
-	 * @param string[] $createdGroups
127
-	 */
128
-	static private function handleCreatedGroups($createdGroups) {
129
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
130
-		$query = \OCP\DB::prepare('
97
+        foreach($groups as $group) {
98
+            //we assume, that self::$groupsFromDB has been retrieved already
99
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
100
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
101
+            $hasChanged = false;
102
+            foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
103
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
104
+                \OCP\Util::writeLog('user_ldap',
105
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
106
+                \OCP\Util::INFO);
107
+                $hasChanged = true;
108
+            }
109
+            foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
110
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
111
+                \OCP\Util::writeLog('user_ldap',
112
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
113
+                \OCP\Util::INFO);
114
+                $hasChanged = true;
115
+            }
116
+            if($hasChanged) {
117
+                $query->execute(array(serialize($actualUsers), $group));
118
+            }
119
+        }
120
+        \OCP\Util::writeLog('user_ldap',
121
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
122
+            \OCP\Util::DEBUG);
123
+    }
124
+
125
+    /**
126
+     * @param string[] $createdGroups
127
+     */
128
+    static private function handleCreatedGroups($createdGroups) {
129
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
130
+        $query = \OCP\DB::prepare('
131 131
 			INSERT
132 132
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
133 133
 			VALUES (?, ?)
134 134
 		');
135
-		foreach($createdGroups as $createdGroup) {
136
-			\OCP\Util::writeLog('user_ldap',
137
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
138
-				\OCP\Util::INFO);
139
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
140
-			$query->execute(array($createdGroup, $users));
141
-		}
142
-		\OCP\Util::writeLog('user_ldap',
143
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
144
-			\OCP\Util::DEBUG);
145
-	}
146
-
147
-	/**
148
-	 * @param string[] $removedGroups
149
-	 */
150
-	static private function handleRemovedGroups($removedGroups) {
151
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
152
-		$query = \OCP\DB::prepare('
135
+        foreach($createdGroups as $createdGroup) {
136
+            \OCP\Util::writeLog('user_ldap',
137
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
138
+                \OCP\Util::INFO);
139
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
140
+            $query->execute(array($createdGroup, $users));
141
+        }
142
+        \OCP\Util::writeLog('user_ldap',
143
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
144
+            \OCP\Util::DEBUG);
145
+    }
146
+
147
+    /**
148
+     * @param string[] $removedGroups
149
+     */
150
+    static private function handleRemovedGroups($removedGroups) {
151
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
152
+        $query = \OCP\DB::prepare('
153 153
 			DELETE
154 154
 			FROM `*PREFIX*ldap_group_members`
155 155
 			WHERE `owncloudname` = ?
156 156
 		');
157
-		foreach($removedGroups as $removedGroup) {
158
-			\OCP\Util::writeLog('user_ldap',
159
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
160
-				\OCP\Util::INFO);
161
-			$query->execute(array($removedGroup));
162
-		}
163
-		\OCP\Util::writeLog('user_ldap',
164
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
165
-			\OCP\Util::DEBUG);
166
-	}
167
-
168
-	/**
169
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
170
-	 */
171
-	static private function getGroupBE() {
172
-		if(!is_null(self::$groupBE)) {
173
-			return self::$groupBE;
174
-		}
175
-		$helper = new Helper(\OC::$server->getConfig());
176
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
177
-		$ldapWrapper = new LDAP();
178
-		if(count($configPrefixes) === 1) {
179
-			//avoid the proxy when there is only one LDAP server configured
180
-			$dbc = \OC::$server->getDatabaseConnection();
181
-			$userManager = new Manager(
182
-				\OC::$server->getConfig(),
183
-				new FilesystemHelper(),
184
-				new LogWrapper(),
185
-				\OC::$server->getAvatarManager(),
186
-				new \OCP\Image(),
187
-				$dbc,
188
-				\OC::$server->getUserManager());
189
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
190
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper);
191
-			$groupMapper = new GroupMapping($dbc);
192
-			$userMapper  = new UserMapping($dbc);
193
-			$ldapAccess->setGroupMapper($groupMapper);
194
-			$ldapAccess->setUserMapper($userMapper);
195
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
196
-		} else {
197
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
198
-		}
199
-
200
-		return self::$groupBE;
201
-	}
202
-
203
-	/**
204
-	 * @return array
205
-	 */
206
-	static private function getKnownGroups() {
207
-		if(is_array(self::$groupsFromDB)) {
208
-			return self::$groupsFromDB;
209
-		}
210
-		$query = \OCP\DB::prepare('
157
+        foreach($removedGroups as $removedGroup) {
158
+            \OCP\Util::writeLog('user_ldap',
159
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
160
+                \OCP\Util::INFO);
161
+            $query->execute(array($removedGroup));
162
+        }
163
+        \OCP\Util::writeLog('user_ldap',
164
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
165
+            \OCP\Util::DEBUG);
166
+    }
167
+
168
+    /**
169
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
170
+     */
171
+    static private function getGroupBE() {
172
+        if(!is_null(self::$groupBE)) {
173
+            return self::$groupBE;
174
+        }
175
+        $helper = new Helper(\OC::$server->getConfig());
176
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
177
+        $ldapWrapper = new LDAP();
178
+        if(count($configPrefixes) === 1) {
179
+            //avoid the proxy when there is only one LDAP server configured
180
+            $dbc = \OC::$server->getDatabaseConnection();
181
+            $userManager = new Manager(
182
+                \OC::$server->getConfig(),
183
+                new FilesystemHelper(),
184
+                new LogWrapper(),
185
+                \OC::$server->getAvatarManager(),
186
+                new \OCP\Image(),
187
+                $dbc,
188
+                \OC::$server->getUserManager());
189
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
190
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper);
191
+            $groupMapper = new GroupMapping($dbc);
192
+            $userMapper  = new UserMapping($dbc);
193
+            $ldapAccess->setGroupMapper($groupMapper);
194
+            $ldapAccess->setUserMapper($userMapper);
195
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
196
+        } else {
197
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
198
+        }
199
+
200
+        return self::$groupBE;
201
+    }
202
+
203
+    /**
204
+     * @return array
205
+     */
206
+    static private function getKnownGroups() {
207
+        if(is_array(self::$groupsFromDB)) {
208
+            return self::$groupsFromDB;
209
+        }
210
+        $query = \OCP\DB::prepare('
211 211
 			SELECT `owncloudname`, `owncloudusers`
212 212
 			FROM `*PREFIX*ldap_group_members`
213 213
 		');
214
-		$result = $query->execute()->fetchAll();
215
-		self::$groupsFromDB = array();
216
-		foreach($result as $dataset) {
217
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
218
-		}
219
-
220
-		return self::$groupsFromDB;
221
-	}
214
+        $result = $query->execute()->fetchAll();
215
+        self::$groupsFromDB = array();
216
+        foreach($result as $dataset) {
217
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
218
+        }
219
+
220
+        return self::$groupsFromDB;
221
+    }
222 222
 }
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -45,14 +45,14 @@  discard block
 block discarded – undo
45 45
 
46 46
 	static private $groupBE;
47 47
 
48
-	public function __construct(){
48
+	public function __construct() {
49 49
 		$this->interval = self::getRefreshInterval();
50 50
 	}
51 51
 
52 52
 	/**
53 53
 	 * @param mixed $argument
54 54
 	 */
55
-	public function run($argument){
55
+	public function run($argument) {
56 56
 		self::updateGroups();
57 57
 	}
58 58
 
@@ -62,7 +62,7 @@  discard block
 block discarded – undo
62 62
 		$knownGroups = array_keys(self::getKnownGroups());
63 63
 		$actualGroups = self::getGroupBE()->getGroups();
64 64
 
65
-		if(empty($actualGroups) && empty($knownGroups)) {
65
+		if (empty($actualGroups) && empty($knownGroups)) {
66 66
 			\OCP\Util::writeLog('user_ldap',
67 67
 				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
68 68
 				\OCP\Util::INFO);
@@ -94,26 +94,26 @@  discard block
 block discarded – undo
94 94
 			SET `owncloudusers` = ?
95 95
 			WHERE `owncloudname` = ?
96 96
 		');
97
-		foreach($groups as $group) {
97
+		foreach ($groups as $group) {
98 98
 			//we assume, that self::$groupsFromDB has been retrieved already
99 99
 			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
100 100
 			$actualUsers = self::getGroupBE()->usersInGroup($group);
101 101
 			$hasChanged = false;
102
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
102
+			foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
103 103
 				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
104 104
 				\OCP\Util::writeLog('user_ldap',
105 105
 				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
106 106
 				\OCP\Util::INFO);
107 107
 				$hasChanged = true;
108 108
 			}
109
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
109
+			foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
110 110
 				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
111 111
 				\OCP\Util::writeLog('user_ldap',
112 112
 				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
113 113
 				\OCP\Util::INFO);
114 114
 				$hasChanged = true;
115 115
 			}
116
-			if($hasChanged) {
116
+			if ($hasChanged) {
117 117
 				$query->execute(array(serialize($actualUsers), $group));
118 118
 			}
119 119
 		}
@@ -132,7 +132,7 @@  discard block
 block discarded – undo
132 132
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
133 133
 			VALUES (?, ?)
134 134
 		');
135
-		foreach($createdGroups as $createdGroup) {
135
+		foreach ($createdGroups as $createdGroup) {
136 136
 			\OCP\Util::writeLog('user_ldap',
137 137
 				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
138 138
 				\OCP\Util::INFO);
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 			FROM `*PREFIX*ldap_group_members`
155 155
 			WHERE `owncloudname` = ?
156 156
 		');
157
-		foreach($removedGroups as $removedGroup) {
157
+		foreach ($removedGroups as $removedGroup) {
158 158
 			\OCP\Util::writeLog('user_ldap',
159 159
 				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
160 160
 				\OCP\Util::INFO);
@@ -169,13 +169,13 @@  discard block
 block discarded – undo
169 169
 	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
170 170
 	 */
171 171
 	static private function getGroupBE() {
172
-		if(!is_null(self::$groupBE)) {
172
+		if (!is_null(self::$groupBE)) {
173 173
 			return self::$groupBE;
174 174
 		}
175 175
 		$helper = new Helper(\OC::$server->getConfig());
176 176
 		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
177 177
 		$ldapWrapper = new LDAP();
178
-		if(count($configPrefixes) === 1) {
178
+		if (count($configPrefixes) === 1) {
179 179
 			//avoid the proxy when there is only one LDAP server configured
180 180
 			$dbc = \OC::$server->getDatabaseConnection();
181 181
 			$userManager = new Manager(
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 	 * @return array
205 205
 	 */
206 206
 	static private function getKnownGroups() {
207
-		if(is_array(self::$groupsFromDB)) {
207
+		if (is_array(self::$groupsFromDB)) {
208 208
 			return self::$groupsFromDB;
209 209
 		}
210 210
 		$query = \OCP\DB::prepare('
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 		');
214 214
 		$result = $query->execute()->fetchAll();
215 215
 		self::$groupsFromDB = array();
216
-		foreach($result as $dataset) {
216
+		foreach ($result as $dataset) {
217 217
 			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
218 218
 		}
219 219
 
Please login to merge, or discard this patch.
core/Command/Maintenance/Repair.php 3 patches
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -32,7 +32,6 @@
 block discarded – undo
32 32
 use Symfony\Component\Console\Input\InputInterface;
33 33
 use Symfony\Component\Console\Input\InputOption;
34 34
 use Symfony\Component\Console\Output\OutputInterface;
35
-use Symfony\Component\EventDispatcher\EventDispatcher;
36 35
 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
37 36
 use Symfony\Component\EventDispatcher\GenericEvent;
38 37
 
Please login to merge, or discard this patch.
Indentation   +98 added lines, -98 removed lines patch added patch discarded remove patch
@@ -38,111 +38,111 @@
 block discarded – undo
38 38
 use Symfony\Component\EventDispatcher\GenericEvent;
39 39
 
40 40
 class Repair extends Command {
41
-	/** @var \OC\Repair $repair */
42
-	protected $repair;
43
-	/** @var IConfig */
44
-	protected $config;
45
-	/** @var EventDispatcherInterface */
46
-	private $dispatcher;
47
-	/** @var ProgressBar */
48
-	private $progress;
49
-	/** @var OutputInterface */
50
-	private $output;
41
+    /** @var \OC\Repair $repair */
42
+    protected $repair;
43
+    /** @var IConfig */
44
+    protected $config;
45
+    /** @var EventDispatcherInterface */
46
+    private $dispatcher;
47
+    /** @var ProgressBar */
48
+    private $progress;
49
+    /** @var OutputInterface */
50
+    private $output;
51 51
 
52
-	/**
53
-	 * @param \OC\Repair $repair
54
-	 * @param IConfig $config
55
-	 */
56
-	public function __construct(\OC\Repair $repair, IConfig $config, EventDispatcherInterface $dispatcher) {
57
-		$this->repair = $repair;
58
-		$this->config = $config;
59
-		$this->dispatcher = $dispatcher;
60
-		parent::__construct();
61
-	}
52
+    /**
53
+     * @param \OC\Repair $repair
54
+     * @param IConfig $config
55
+     */
56
+    public function __construct(\OC\Repair $repair, IConfig $config, EventDispatcherInterface $dispatcher) {
57
+        $this->repair = $repair;
58
+        $this->config = $config;
59
+        $this->dispatcher = $dispatcher;
60
+        parent::__construct();
61
+    }
62 62
 
63
-	protected function configure() {
64
-		$this
65
-			->setName('maintenance:repair')
66
-			->setDescription('repair this installation')
67
-			->addOption(
68
-				'include-expensive',
69
-				null,
70
-				InputOption::VALUE_NONE,
71
-				'Use this option when you want to include resource and load expensive tasks');
72
-	}
63
+    protected function configure() {
64
+        $this
65
+            ->setName('maintenance:repair')
66
+            ->setDescription('repair this installation')
67
+            ->addOption(
68
+                'include-expensive',
69
+                null,
70
+                InputOption::VALUE_NONE,
71
+                'Use this option when you want to include resource and load expensive tasks');
72
+    }
73 73
 
74
-	protected function execute(InputInterface $input, OutputInterface $output) {
75
-		$includeExpensive = $input->getOption('include-expensive');
76
-		if ($includeExpensive) {
77
-			foreach ($this->repair->getExpensiveRepairSteps() as $step) {
78
-				$this->repair->addStep($step);
79
-			}
80
-		}
74
+    protected function execute(InputInterface $input, OutputInterface $output) {
75
+        $includeExpensive = $input->getOption('include-expensive');
76
+        if ($includeExpensive) {
77
+            foreach ($this->repair->getExpensiveRepairSteps() as $step) {
78
+                $this->repair->addStep($step);
79
+            }
80
+        }
81 81
 
82
-		$apps = \OC::$server->getAppManager()->getInstalledApps();
83
-		foreach ($apps as $app) {
84
-			if (!\OC_App::isEnabled($app)) {
85
-				continue;
86
-			}
87
-			$info = \OC_App::getAppInfo($app);
88
-			if (!is_array($info)) {
89
-				continue;
90
-			}
91
-			$steps = $info['repair-steps']['post-migration'];
92
-			foreach ($steps as $step) {
93
-				try {
94
-					$this->repair->addStep($step);
95
-				} catch (Exception $ex) {
96
-					$output->writeln("<error>Failed to load repair step for $app: {$ex->getMessage()}</error>");
97
-				}
98
-			}
99
-		}
82
+        $apps = \OC::$server->getAppManager()->getInstalledApps();
83
+        foreach ($apps as $app) {
84
+            if (!\OC_App::isEnabled($app)) {
85
+                continue;
86
+            }
87
+            $info = \OC_App::getAppInfo($app);
88
+            if (!is_array($info)) {
89
+                continue;
90
+            }
91
+            $steps = $info['repair-steps']['post-migration'];
92
+            foreach ($steps as $step) {
93
+                try {
94
+                    $this->repair->addStep($step);
95
+                } catch (Exception $ex) {
96
+                    $output->writeln("<error>Failed to load repair step for $app: {$ex->getMessage()}</error>");
97
+                }
98
+            }
99
+        }
100 100
 
101
-		$maintenanceMode = $this->config->getSystemValue('maintenance', false);
102
-		$this->config->setSystemValue('maintenance', true);
101
+        $maintenanceMode = $this->config->getSystemValue('maintenance', false);
102
+        $this->config->setSystemValue('maintenance', true);
103 103
 
104
-		$this->progress = new ProgressBar($output);
105
-		$this->output = $output;
106
-		$this->dispatcher->addListener('\OC\Repair::startProgress', [$this, 'handleRepairFeedBack']);
107
-		$this->dispatcher->addListener('\OC\Repair::advance', [$this, 'handleRepairFeedBack']);
108
-		$this->dispatcher->addListener('\OC\Repair::finishProgress', [$this, 'handleRepairFeedBack']);
109
-		$this->dispatcher->addListener('\OC\Repair::step', [$this, 'handleRepairFeedBack']);
110
-		$this->dispatcher->addListener('\OC\Repair::info', [$this, 'handleRepairFeedBack']);
111
-		$this->dispatcher->addListener('\OC\Repair::warning', [$this, 'handleRepairFeedBack']);
112
-		$this->dispatcher->addListener('\OC\Repair::error', [$this, 'handleRepairFeedBack']);
104
+        $this->progress = new ProgressBar($output);
105
+        $this->output = $output;
106
+        $this->dispatcher->addListener('\OC\Repair::startProgress', [$this, 'handleRepairFeedBack']);
107
+        $this->dispatcher->addListener('\OC\Repair::advance', [$this, 'handleRepairFeedBack']);
108
+        $this->dispatcher->addListener('\OC\Repair::finishProgress', [$this, 'handleRepairFeedBack']);
109
+        $this->dispatcher->addListener('\OC\Repair::step', [$this, 'handleRepairFeedBack']);
110
+        $this->dispatcher->addListener('\OC\Repair::info', [$this, 'handleRepairFeedBack']);
111
+        $this->dispatcher->addListener('\OC\Repair::warning', [$this, 'handleRepairFeedBack']);
112
+        $this->dispatcher->addListener('\OC\Repair::error', [$this, 'handleRepairFeedBack']);
113 113
 
114
-		$this->repair->run();
114
+        $this->repair->run();
115 115
 
116
-		$this->config->setSystemValue('maintenance', $maintenanceMode);
117
-	}
116
+        $this->config->setSystemValue('maintenance', $maintenanceMode);
117
+    }
118 118
 
119
-	public function handleRepairFeedBack($event) {
120
-		if (!$event instanceof GenericEvent) {
121
-			return;
122
-		}
123
-		switch ($event->getSubject()) {
124
-			case '\OC\Repair::startProgress':
125
-				$this->progress->start($event->getArgument(0));
126
-				break;
127
-			case '\OC\Repair::advance':
128
-				$this->progress->advance($event->getArgument(0));
129
-				break;
130
-			case '\OC\Repair::finishProgress':
131
-				$this->progress->finish();
132
-				$this->output->writeln('');
133
-				break;
134
-			case '\OC\Repair::step':
135
-				$this->output->writeln(' - ' . $event->getArgument(0));
136
-				break;
137
-			case '\OC\Repair::info':
138
-				$this->output->writeln('     - ' . $event->getArgument(0));
139
-				break;
140
-			case '\OC\Repair::warning':
141
-				$this->output->writeln('     - WARNING: ' . $event->getArgument(0));
142
-				break;
143
-			case '\OC\Repair::error':
144
-				$this->output->writeln('     - ERROR: ' . $event->getArgument(0));
145
-				break;
146
-		}
147
-	}
119
+    public function handleRepairFeedBack($event) {
120
+        if (!$event instanceof GenericEvent) {
121
+            return;
122
+        }
123
+        switch ($event->getSubject()) {
124
+            case '\OC\Repair::startProgress':
125
+                $this->progress->start($event->getArgument(0));
126
+                break;
127
+            case '\OC\Repair::advance':
128
+                $this->progress->advance($event->getArgument(0));
129
+                break;
130
+            case '\OC\Repair::finishProgress':
131
+                $this->progress->finish();
132
+                $this->output->writeln('');
133
+                break;
134
+            case '\OC\Repair::step':
135
+                $this->output->writeln(' - ' . $event->getArgument(0));
136
+                break;
137
+            case '\OC\Repair::info':
138
+                $this->output->writeln('     - ' . $event->getArgument(0));
139
+                break;
140
+            case '\OC\Repair::warning':
141
+                $this->output->writeln('     - WARNING: ' . $event->getArgument(0));
142
+                break;
143
+            case '\OC\Repair::error':
144
+                $this->output->writeln('     - ERROR: ' . $event->getArgument(0));
145
+                break;
146
+        }
147
+    }
148 148
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -132,16 +132,16 @@
 block discarded – undo
132 132
 				$this->output->writeln('');
133 133
 				break;
134 134
 			case '\OC\Repair::step':
135
-				$this->output->writeln(' - ' . $event->getArgument(0));
135
+				$this->output->writeln(' - '.$event->getArgument(0));
136 136
 				break;
137 137
 			case '\OC\Repair::info':
138
-				$this->output->writeln('     - ' . $event->getArgument(0));
138
+				$this->output->writeln('     - '.$event->getArgument(0));
139 139
 				break;
140 140
 			case '\OC\Repair::warning':
141
-				$this->output->writeln('     - WARNING: ' . $event->getArgument(0));
141
+				$this->output->writeln('     - WARNING: '.$event->getArgument(0));
142 142
 				break;
143 143
 			case '\OC\Repair::error':
144
-				$this->output->writeln('     - ERROR: ' . $event->getArgument(0));
144
+				$this->output->writeln('     - ERROR: '.$event->getArgument(0));
145 145
 				break;
146 146
 		}
147 147
 	}
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   +358 added lines, -358 removed lines patch added patch discarded remove patch
@@ -43,362 +43,362 @@
 block discarded – undo
43 43
 
44 44
 class AppManager implements IAppManager {
45 45
 
46
-	/**
47
-	 * Apps with these types can not be enabled for certain groups only
48
-	 * @var string[]
49
-	 */
50
-	protected $protectedAppTypes = [
51
-		'filesystem',
52
-		'prelogin',
53
-		'authentication',
54
-		'logging',
55
-		'prevent_group_restriction',
56
-	];
57
-
58
-	/** @var \OCP\IUserSession */
59
-	private $userSession;
60
-
61
-	/** @var \OCP\IAppConfig */
62
-	private $appConfig;
63
-
64
-	/** @var \OCP\IGroupManager */
65
-	private $groupManager;
66
-
67
-	/** @var \OCP\ICacheFactory */
68
-	private $memCacheFactory;
69
-
70
-	/** @var string[] $appId => $enabled */
71
-	private $installedAppsCache;
72
-
73
-	/** @var string[] */
74
-	private $shippedApps;
75
-
76
-	/** @var string[] */
77
-	private $alwaysEnabled;
78
-
79
-	/** @var EventDispatcherInterface */
80
-	private $dispatcher;
81
-
82
-	/**
83
-	 * @param \OCP\IUserSession $userSession
84
-	 * @param \OCP\IAppConfig $appConfig
85
-	 * @param \OCP\IGroupManager $groupManager
86
-	 * @param \OCP\ICacheFactory $memCacheFactory
87
-	 */
88
-	public function __construct(IUserSession $userSession,
89
-								IAppConfig $appConfig,
90
-								IGroupManager $groupManager,
91
-								ICacheFactory $memCacheFactory,
92
-								EventDispatcherInterface $dispatcher) {
93
-		$this->userSession = $userSession;
94
-		$this->appConfig = $appConfig;
95
-		$this->groupManager = $groupManager;
96
-		$this->memCacheFactory = $memCacheFactory;
97
-		$this->dispatcher = $dispatcher;
98
-	}
99
-
100
-	/**
101
-	 * @return string[] $appId => $enabled
102
-	 */
103
-	private function getInstalledAppsValues() {
104
-		if (!$this->installedAppsCache) {
105
-			$values = $this->appConfig->getValues(false, 'enabled');
106
-
107
-			$alwaysEnabledApps = $this->getAlwaysEnabledApps();
108
-			foreach($alwaysEnabledApps as $appId) {
109
-				$values[$appId] = 'yes';
110
-			}
111
-
112
-			$this->installedAppsCache = array_filter($values, function ($value) {
113
-				return $value !== 'no';
114
-			});
115
-			ksort($this->installedAppsCache);
116
-		}
117
-		return $this->installedAppsCache;
118
-	}
119
-
120
-	/**
121
-	 * List all installed apps
122
-	 *
123
-	 * @return string[]
124
-	 */
125
-	public function getInstalledApps() {
126
-		return array_keys($this->getInstalledAppsValues());
127
-	}
128
-
129
-	/**
130
-	 * List all apps enabled for a user
131
-	 *
132
-	 * @param \OCP\IUser $user
133
-	 * @return string[]
134
-	 */
135
-	public function getEnabledAppsForUser(IUser $user) {
136
-		$apps = $this->getInstalledAppsValues();
137
-		$appsForUser = array_filter($apps, function ($enabled) use ($user) {
138
-			return $this->checkAppForUser($enabled, $user);
139
-		});
140
-		return array_keys($appsForUser);
141
-	}
142
-
143
-	/**
144
-	 * Check if an app is enabled for user
145
-	 *
146
-	 * @param string $appId
147
-	 * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
148
-	 * @return bool
149
-	 */
150
-	public function isEnabledForUser($appId, $user = null) {
151
-		if ($this->isAlwaysEnabled($appId)) {
152
-			return true;
153
-		}
154
-		if (is_null($user)) {
155
-			$user = $this->userSession->getUser();
156
-		}
157
-		$installedApps = $this->getInstalledAppsValues();
158
-		if (isset($installedApps[$appId])) {
159
-			return $this->checkAppForUser($installedApps[$appId], $user);
160
-		} else {
161
-			return false;
162
-		}
163
-	}
164
-
165
-	/**
166
-	 * @param string $enabled
167
-	 * @param IUser $user
168
-	 * @return bool
169
-	 */
170
-	private function checkAppForUser($enabled, $user) {
171
-		if ($enabled === 'yes') {
172
-			return true;
173
-		} elseif (is_null($user)) {
174
-			return false;
175
-		} else {
176
-			if(empty($enabled)){
177
-				return false;
178
-			}
179
-
180
-			$groupIds = json_decode($enabled);
181
-
182
-			if (!is_array($groupIds)) {
183
-				$jsonError = json_last_error();
184
-				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
185
-				return false;
186
-			}
187
-
188
-			$userGroups = $this->groupManager->getUserGroupIds($user);
189
-			foreach ($userGroups as $groupId) {
190
-				if (array_search($groupId, $groupIds) !== false) {
191
-					return true;
192
-				}
193
-			}
194
-			return false;
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * Check if an app is installed in the instance
200
-	 *
201
-	 * @param string $appId
202
-	 * @return bool
203
-	 */
204
-	public function isInstalled($appId) {
205
-		$installedApps = $this->getInstalledAppsValues();
206
-		return isset($installedApps[$appId]);
207
-	}
208
-
209
-	/**
210
-	 * Enable an app for every user
211
-	 *
212
-	 * @param string $appId
213
-	 */
214
-	public function enableApp($appId) {
215
-		$this->installedAppsCache[$appId] = 'yes';
216
-		$this->appConfig->setValue($appId, 'enabled', 'yes');
217
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
218
-			ManagerEvent::EVENT_APP_ENABLE, $appId
219
-		));
220
-		$this->clearAppsCache();
221
-	}
222
-
223
-	/**
224
-	 * Whether a list of types contains a protected app type
225
-	 *
226
-	 * @param string[] $types
227
-	 * @return bool
228
-	 */
229
-	public function hasProtectedAppType($types) {
230
-		if (empty($types)) {
231
-			return false;
232
-		}
233
-
234
-		$protectedTypes = array_intersect($this->protectedAppTypes, $types);
235
-		return !empty($protectedTypes);
236
-	}
237
-
238
-	/**
239
-	 * Enable an app only for specific groups
240
-	 *
241
-	 * @param string $appId
242
-	 * @param \OCP\IGroup[] $groups
243
-	 * @throws \Exception if app can't be enabled for groups
244
-	 */
245
-	public function enableAppForGroups($appId, $groups) {
246
-		$info = $this->getAppInfo($appId);
247
-		if (!empty($info['types'])) {
248
-			$protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
249
-			if (!empty($protectedTypes)) {
250
-				throw new \Exception("$appId can't be enabled for groups.");
251
-			}
252
-		}
253
-
254
-		$groupIds = array_map(function ($group) {
255
-			/** @var \OCP\IGroup $group */
256
-			return $group->getGID();
257
-		}, $groups);
258
-		$this->installedAppsCache[$appId] = json_encode($groupIds);
259
-		$this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
260
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
261
-			ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
262
-		));
263
-		$this->clearAppsCache();
264
-	}
265
-
266
-	/**
267
-	 * Disable an app for every user
268
-	 *
269
-	 * @param string $appId
270
-	 * @throws \Exception if app can't be disabled
271
-	 */
272
-	public function disableApp($appId) {
273
-		if ($this->isAlwaysEnabled($appId)) {
274
-			throw new \Exception("$appId can't be disabled.");
275
-		}
276
-		unset($this->installedAppsCache[$appId]);
277
-		$this->appConfig->setValue($appId, 'enabled', 'no');
278
-		$this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
279
-			ManagerEvent::EVENT_APP_DISABLE, $appId
280
-		));
281
-		$this->clearAppsCache();
282
-	}
283
-
284
-	/**
285
-	 * Get the directory for the given app.
286
-	 *
287
-	 * @param string $appId
288
-	 * @return string
289
-	 * @throws AppPathNotFoundException if app folder can't be found
290
-	 */
291
-	public function getAppPath($appId) {
292
-		$appPath = \OC_App::getAppPath($appId);
293
-		if($appPath === false) {
294
-			throw new AppPathNotFoundException('Could not find path for ' . $appId);
295
-		}
296
-		return $appPath;
297
-	}
298
-
299
-	/**
300
-	 * Clear the cached list of apps when enabling/disabling an app
301
-	 */
302
-	public function clearAppsCache() {
303
-		$settingsMemCache = $this->memCacheFactory->create('settings');
304
-		$settingsMemCache->clear('listApps');
305
-	}
306
-
307
-	/**
308
-	 * Returns a list of apps that need upgrade
309
-	 *
310
-	 * @param array $version ownCloud version as array of version components
311
-	 * @return array list of app info from apps that need an upgrade
312
-	 *
313
-	 * @internal
314
-	 */
315
-	public function getAppsNeedingUpgrade($ocVersion) {
316
-		$appsToUpgrade = [];
317
-		$apps = $this->getInstalledApps();
318
-		foreach ($apps as $appId) {
319
-			$appInfo = $this->getAppInfo($appId);
320
-			$appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
321
-			if ($appDbVersion
322
-				&& isset($appInfo['version'])
323
-				&& version_compare($appInfo['version'], $appDbVersion, '>')
324
-				&& \OC_App::isAppCompatible($ocVersion, $appInfo)
325
-			) {
326
-				$appsToUpgrade[] = $appInfo;
327
-			}
328
-		}
329
-
330
-		return $appsToUpgrade;
331
-	}
332
-
333
-	/**
334
-	 * Returns the app information from "appinfo/info.xml".
335
-	 *
336
-	 * @param string $appId app id
337
-	 *
338
-	 * @return array app info
339
-	 *
340
-	 * @internal
341
-	 */
342
-	public function getAppInfo($appId) {
343
-		$appInfo = \OC_App::getAppInfo($appId);
344
-		if (!isset($appInfo['version'])) {
345
-			// read version from separate file
346
-			$appInfo['version'] = \OC_App::getAppVersion($appId);
347
-		}
348
-		return $appInfo;
349
-	}
350
-
351
-	/**
352
-	 * Returns a list of apps incompatible with the given version
353
-	 *
354
-	 * @param array $version ownCloud version as array of version components
355
-	 *
356
-	 * @return array list of app info from incompatible apps
357
-	 *
358
-	 * @internal
359
-	 */
360
-	public function getIncompatibleApps($version) {
361
-		$apps = $this->getInstalledApps();
362
-		$incompatibleApps = array();
363
-		foreach ($apps as $appId) {
364
-			$info = $this->getAppInfo($appId);
365
-			if (!\OC_App::isAppCompatible($version, $info)) {
366
-				$incompatibleApps[] = $info;
367
-			}
368
-		}
369
-		return $incompatibleApps;
370
-	}
371
-
372
-	/**
373
-	 * @inheritdoc
374
-	 */
375
-	public function isShipped($appId) {
376
-		$this->loadShippedJson();
377
-		return in_array($appId, $this->shippedApps);
378
-	}
379
-
380
-	private function isAlwaysEnabled($appId) {
381
-		$alwaysEnabled = $this->getAlwaysEnabledApps();
382
-		return in_array($appId, $alwaysEnabled);
383
-	}
384
-
385
-	private function loadShippedJson() {
386
-		if (is_null($this->shippedApps)) {
387
-			$shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
388
-			if (!file_exists($shippedJson)) {
389
-				throw new \Exception("File not found: $shippedJson");
390
-			}
391
-			$content = json_decode(file_get_contents($shippedJson), true);
392
-			$this->shippedApps = $content['shippedApps'];
393
-			$this->alwaysEnabled = $content['alwaysEnabled'];
394
-		}
395
-	}
396
-
397
-	/**
398
-	 * @inheritdoc
399
-	 */
400
-	public function getAlwaysEnabledApps() {
401
-		$this->loadShippedJson();
402
-		return $this->alwaysEnabled;
403
-	}
46
+    /**
47
+     * Apps with these types can not be enabled for certain groups only
48
+     * @var string[]
49
+     */
50
+    protected $protectedAppTypes = [
51
+        'filesystem',
52
+        'prelogin',
53
+        'authentication',
54
+        'logging',
55
+        'prevent_group_restriction',
56
+    ];
57
+
58
+    /** @var \OCP\IUserSession */
59
+    private $userSession;
60
+
61
+    /** @var \OCP\IAppConfig */
62
+    private $appConfig;
63
+
64
+    /** @var \OCP\IGroupManager */
65
+    private $groupManager;
66
+
67
+    /** @var \OCP\ICacheFactory */
68
+    private $memCacheFactory;
69
+
70
+    /** @var string[] $appId => $enabled */
71
+    private $installedAppsCache;
72
+
73
+    /** @var string[] */
74
+    private $shippedApps;
75
+
76
+    /** @var string[] */
77
+    private $alwaysEnabled;
78
+
79
+    /** @var EventDispatcherInterface */
80
+    private $dispatcher;
81
+
82
+    /**
83
+     * @param \OCP\IUserSession $userSession
84
+     * @param \OCP\IAppConfig $appConfig
85
+     * @param \OCP\IGroupManager $groupManager
86
+     * @param \OCP\ICacheFactory $memCacheFactory
87
+     */
88
+    public function __construct(IUserSession $userSession,
89
+                                IAppConfig $appConfig,
90
+                                IGroupManager $groupManager,
91
+                                ICacheFactory $memCacheFactory,
92
+                                EventDispatcherInterface $dispatcher) {
93
+        $this->userSession = $userSession;
94
+        $this->appConfig = $appConfig;
95
+        $this->groupManager = $groupManager;
96
+        $this->memCacheFactory = $memCacheFactory;
97
+        $this->dispatcher = $dispatcher;
98
+    }
99
+
100
+    /**
101
+     * @return string[] $appId => $enabled
102
+     */
103
+    private function getInstalledAppsValues() {
104
+        if (!$this->installedAppsCache) {
105
+            $values = $this->appConfig->getValues(false, 'enabled');
106
+
107
+            $alwaysEnabledApps = $this->getAlwaysEnabledApps();
108
+            foreach($alwaysEnabledApps as $appId) {
109
+                $values[$appId] = 'yes';
110
+            }
111
+
112
+            $this->installedAppsCache = array_filter($values, function ($value) {
113
+                return $value !== 'no';
114
+            });
115
+            ksort($this->installedAppsCache);
116
+        }
117
+        return $this->installedAppsCache;
118
+    }
119
+
120
+    /**
121
+     * List all installed apps
122
+     *
123
+     * @return string[]
124
+     */
125
+    public function getInstalledApps() {
126
+        return array_keys($this->getInstalledAppsValues());
127
+    }
128
+
129
+    /**
130
+     * List all apps enabled for a user
131
+     *
132
+     * @param \OCP\IUser $user
133
+     * @return string[]
134
+     */
135
+    public function getEnabledAppsForUser(IUser $user) {
136
+        $apps = $this->getInstalledAppsValues();
137
+        $appsForUser = array_filter($apps, function ($enabled) use ($user) {
138
+            return $this->checkAppForUser($enabled, $user);
139
+        });
140
+        return array_keys($appsForUser);
141
+    }
142
+
143
+    /**
144
+     * Check if an app is enabled for user
145
+     *
146
+     * @param string $appId
147
+     * @param \OCP\IUser $user (optional) if not defined, the currently logged in user will be used
148
+     * @return bool
149
+     */
150
+    public function isEnabledForUser($appId, $user = null) {
151
+        if ($this->isAlwaysEnabled($appId)) {
152
+            return true;
153
+        }
154
+        if (is_null($user)) {
155
+            $user = $this->userSession->getUser();
156
+        }
157
+        $installedApps = $this->getInstalledAppsValues();
158
+        if (isset($installedApps[$appId])) {
159
+            return $this->checkAppForUser($installedApps[$appId], $user);
160
+        } else {
161
+            return false;
162
+        }
163
+    }
164
+
165
+    /**
166
+     * @param string $enabled
167
+     * @param IUser $user
168
+     * @return bool
169
+     */
170
+    private function checkAppForUser($enabled, $user) {
171
+        if ($enabled === 'yes') {
172
+            return true;
173
+        } elseif (is_null($user)) {
174
+            return false;
175
+        } else {
176
+            if(empty($enabled)){
177
+                return false;
178
+            }
179
+
180
+            $groupIds = json_decode($enabled);
181
+
182
+            if (!is_array($groupIds)) {
183
+                $jsonError = json_last_error();
184
+                \OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
185
+                return false;
186
+            }
187
+
188
+            $userGroups = $this->groupManager->getUserGroupIds($user);
189
+            foreach ($userGroups as $groupId) {
190
+                if (array_search($groupId, $groupIds) !== false) {
191
+                    return true;
192
+                }
193
+            }
194
+            return false;
195
+        }
196
+    }
197
+
198
+    /**
199
+     * Check if an app is installed in the instance
200
+     *
201
+     * @param string $appId
202
+     * @return bool
203
+     */
204
+    public function isInstalled($appId) {
205
+        $installedApps = $this->getInstalledAppsValues();
206
+        return isset($installedApps[$appId]);
207
+    }
208
+
209
+    /**
210
+     * Enable an app for every user
211
+     *
212
+     * @param string $appId
213
+     */
214
+    public function enableApp($appId) {
215
+        $this->installedAppsCache[$appId] = 'yes';
216
+        $this->appConfig->setValue($appId, 'enabled', 'yes');
217
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE, new ManagerEvent(
218
+            ManagerEvent::EVENT_APP_ENABLE, $appId
219
+        ));
220
+        $this->clearAppsCache();
221
+    }
222
+
223
+    /**
224
+     * Whether a list of types contains a protected app type
225
+     *
226
+     * @param string[] $types
227
+     * @return bool
228
+     */
229
+    public function hasProtectedAppType($types) {
230
+        if (empty($types)) {
231
+            return false;
232
+        }
233
+
234
+        $protectedTypes = array_intersect($this->protectedAppTypes, $types);
235
+        return !empty($protectedTypes);
236
+    }
237
+
238
+    /**
239
+     * Enable an app only for specific groups
240
+     *
241
+     * @param string $appId
242
+     * @param \OCP\IGroup[] $groups
243
+     * @throws \Exception if app can't be enabled for groups
244
+     */
245
+    public function enableAppForGroups($appId, $groups) {
246
+        $info = $this->getAppInfo($appId);
247
+        if (!empty($info['types'])) {
248
+            $protectedTypes = array_intersect($this->protectedAppTypes, $info['types']);
249
+            if (!empty($protectedTypes)) {
250
+                throw new \Exception("$appId can't be enabled for groups.");
251
+            }
252
+        }
253
+
254
+        $groupIds = array_map(function ($group) {
255
+            /** @var \OCP\IGroup $group */
256
+            return $group->getGID();
257
+        }, $groups);
258
+        $this->installedAppsCache[$appId] = json_encode($groupIds);
259
+        $this->appConfig->setValue($appId, 'enabled', json_encode($groupIds));
260
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, new ManagerEvent(
261
+            ManagerEvent::EVENT_APP_ENABLE_FOR_GROUPS, $appId, $groups
262
+        ));
263
+        $this->clearAppsCache();
264
+    }
265
+
266
+    /**
267
+     * Disable an app for every user
268
+     *
269
+     * @param string $appId
270
+     * @throws \Exception if app can't be disabled
271
+     */
272
+    public function disableApp($appId) {
273
+        if ($this->isAlwaysEnabled($appId)) {
274
+            throw new \Exception("$appId can't be disabled.");
275
+        }
276
+        unset($this->installedAppsCache[$appId]);
277
+        $this->appConfig->setValue($appId, 'enabled', 'no');
278
+        $this->dispatcher->dispatch(ManagerEvent::EVENT_APP_DISABLE, new ManagerEvent(
279
+            ManagerEvent::EVENT_APP_DISABLE, $appId
280
+        ));
281
+        $this->clearAppsCache();
282
+    }
283
+
284
+    /**
285
+     * Get the directory for the given app.
286
+     *
287
+     * @param string $appId
288
+     * @return string
289
+     * @throws AppPathNotFoundException if app folder can't be found
290
+     */
291
+    public function getAppPath($appId) {
292
+        $appPath = \OC_App::getAppPath($appId);
293
+        if($appPath === false) {
294
+            throw new AppPathNotFoundException('Could not find path for ' . $appId);
295
+        }
296
+        return $appPath;
297
+    }
298
+
299
+    /**
300
+     * Clear the cached list of apps when enabling/disabling an app
301
+     */
302
+    public function clearAppsCache() {
303
+        $settingsMemCache = $this->memCacheFactory->create('settings');
304
+        $settingsMemCache->clear('listApps');
305
+    }
306
+
307
+    /**
308
+     * Returns a list of apps that need upgrade
309
+     *
310
+     * @param array $version ownCloud version as array of version components
311
+     * @return array list of app info from apps that need an upgrade
312
+     *
313
+     * @internal
314
+     */
315
+    public function getAppsNeedingUpgrade($ocVersion) {
316
+        $appsToUpgrade = [];
317
+        $apps = $this->getInstalledApps();
318
+        foreach ($apps as $appId) {
319
+            $appInfo = $this->getAppInfo($appId);
320
+            $appDbVersion = $this->appConfig->getValue($appId, 'installed_version');
321
+            if ($appDbVersion
322
+                && isset($appInfo['version'])
323
+                && version_compare($appInfo['version'], $appDbVersion, '>')
324
+                && \OC_App::isAppCompatible($ocVersion, $appInfo)
325
+            ) {
326
+                $appsToUpgrade[] = $appInfo;
327
+            }
328
+        }
329
+
330
+        return $appsToUpgrade;
331
+    }
332
+
333
+    /**
334
+     * Returns the app information from "appinfo/info.xml".
335
+     *
336
+     * @param string $appId app id
337
+     *
338
+     * @return array app info
339
+     *
340
+     * @internal
341
+     */
342
+    public function getAppInfo($appId) {
343
+        $appInfo = \OC_App::getAppInfo($appId);
344
+        if (!isset($appInfo['version'])) {
345
+            // read version from separate file
346
+            $appInfo['version'] = \OC_App::getAppVersion($appId);
347
+        }
348
+        return $appInfo;
349
+    }
350
+
351
+    /**
352
+     * Returns a list of apps incompatible with the given version
353
+     *
354
+     * @param array $version ownCloud version as array of version components
355
+     *
356
+     * @return array list of app info from incompatible apps
357
+     *
358
+     * @internal
359
+     */
360
+    public function getIncompatibleApps($version) {
361
+        $apps = $this->getInstalledApps();
362
+        $incompatibleApps = array();
363
+        foreach ($apps as $appId) {
364
+            $info = $this->getAppInfo($appId);
365
+            if (!\OC_App::isAppCompatible($version, $info)) {
366
+                $incompatibleApps[] = $info;
367
+            }
368
+        }
369
+        return $incompatibleApps;
370
+    }
371
+
372
+    /**
373
+     * @inheritdoc
374
+     */
375
+    public function isShipped($appId) {
376
+        $this->loadShippedJson();
377
+        return in_array($appId, $this->shippedApps);
378
+    }
379
+
380
+    private function isAlwaysEnabled($appId) {
381
+        $alwaysEnabled = $this->getAlwaysEnabledApps();
382
+        return in_array($appId, $alwaysEnabled);
383
+    }
384
+
385
+    private function loadShippedJson() {
386
+        if (is_null($this->shippedApps)) {
387
+            $shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
388
+            if (!file_exists($shippedJson)) {
389
+                throw new \Exception("File not found: $shippedJson");
390
+            }
391
+            $content = json_decode(file_get_contents($shippedJson), true);
392
+            $this->shippedApps = $content['shippedApps'];
393
+            $this->alwaysEnabled = $content['alwaysEnabled'];
394
+        }
395
+    }
396
+
397
+    /**
398
+     * @inheritdoc
399
+     */
400
+    public function getAlwaysEnabledApps() {
401
+        $this->loadShippedJson();
402
+        return $this->alwaysEnabled;
403
+    }
404 404
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -105,11 +105,11 @@  discard block
 block discarded – undo
105 105
 			$values = $this->appConfig->getValues(false, 'enabled');
106 106
 
107 107
 			$alwaysEnabledApps = $this->getAlwaysEnabledApps();
108
-			foreach($alwaysEnabledApps as $appId) {
108
+			foreach ($alwaysEnabledApps as $appId) {
109 109
 				$values[$appId] = 'yes';
110 110
 			}
111 111
 
112
-			$this->installedAppsCache = array_filter($values, function ($value) {
112
+			$this->installedAppsCache = array_filter($values, function($value) {
113 113
 				return $value !== 'no';
114 114
 			});
115 115
 			ksort($this->installedAppsCache);
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 	 */
135 135
 	public function getEnabledAppsForUser(IUser $user) {
136 136
 		$apps = $this->getInstalledAppsValues();
137
-		$appsForUser = array_filter($apps, function ($enabled) use ($user) {
137
+		$appsForUser = array_filter($apps, function($enabled) use ($user) {
138 138
 			return $this->checkAppForUser($enabled, $user);
139 139
 		});
140 140
 		return array_keys($appsForUser);
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 		} elseif (is_null($user)) {
174 174
 			return false;
175 175
 		} else {
176
-			if(empty($enabled)){
176
+			if (empty($enabled)) {
177 177
 				return false;
178 178
 			}
179 179
 
@@ -181,7 +181,7 @@  discard block
 block discarded – undo
181 181
 
182 182
 			if (!is_array($groupIds)) {
183 183
 				$jsonError = json_last_error();
184
-				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: ' . print_r($enabled, true) . ' - json error code: ' . $jsonError, ['app' => 'lib']);
184
+				\OC::$server->getLogger()->warning('AppManger::checkAppForUser - can\'t decode group IDs: '.print_r($enabled, true).' - json error code: '.$jsonError, ['app' => 'lib']);
185 185
 				return false;
186 186
 			}
187 187
 
@@ -251,7 +251,7 @@  discard block
 block discarded – undo
251 251
 			}
252 252
 		}
253 253
 
254
-		$groupIds = array_map(function ($group) {
254
+		$groupIds = array_map(function($group) {
255 255
 			/** @var \OCP\IGroup $group */
256 256
 			return $group->getGID();
257 257
 		}, $groups);
@@ -290,8 +290,8 @@  discard block
 block discarded – undo
290 290
 	 */
291 291
 	public function getAppPath($appId) {
292 292
 		$appPath = \OC_App::getAppPath($appId);
293
-		if($appPath === false) {
294
-			throw new AppPathNotFoundException('Could not find path for ' . $appId);
293
+		if ($appPath === false) {
294
+			throw new AppPathNotFoundException('Could not find path for '.$appId);
295 295
 		}
296 296
 		return $appPath;
297 297
 	}
@@ -384,7 +384,7 @@  discard block
 block discarded – undo
384 384
 
385 385
 	private function loadShippedJson() {
386 386
 		if (is_null($this->shippedApps)) {
387
-			$shippedJson = \OC::$SERVERROOT . '/core/shipped.json';
387
+			$shippedJson = \OC::$SERVERROOT.'/core/shipped.json';
388 388
 			if (!file_exists($shippedJson)) {
389 389
 				throw new \Exception("File not found: $shippedJson");
390 390
 			}
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   +54 added lines, -54 removed lines patch added patch discarded remove patch
@@ -36,66 +36,66 @@
 block discarded – undo
36 36
  */
37 37
 class Platform {
38 38
 
39
-	/**
40
-	 * @param IConfig $config
41
-	 */
42
-	function __construct(IConfig $config) {
43
-		$this->config = $config;
44
-	}
39
+    /**
40
+     * @param IConfig $config
41
+     */
42
+    function __construct(IConfig $config) {
43
+        $this->config = $config;
44
+    }
45 45
 
46
-	/**
47
-	 * @return string
48
-	 */
49
-	public function getPhpVersion() {
50
-		return phpversion();
51
-	}
46
+    /**
47
+     * @return string
48
+     */
49
+    public function getPhpVersion() {
50
+        return phpversion();
51
+    }
52 52
 
53
-	/**
54
-	 * @return int
55
-	 */
56
-	public function getIntSize() {
57
-		return PHP_INT_SIZE;
58
-	}
53
+    /**
54
+     * @return int
55
+     */
56
+    public function getIntSize() {
57
+        return PHP_INT_SIZE;
58
+    }
59 59
 
60
-	/**
61
-	 * @return string
62
-	 */
63
-	public function getOcVersion() {
64
-		$v = \OCP\Util::getVersion();
65
-		return join('.', $v);
66
-	}
60
+    /**
61
+     * @return string
62
+     */
63
+    public function getOcVersion() {
64
+        $v = \OCP\Util::getVersion();
65
+        return join('.', $v);
66
+    }
67 67
 
68
-	/**
69
-	 * @return string
70
-	 */
71
-	public function getDatabase() {
72
-		$dbType = $this->config->getSystemValue('dbtype', 'sqlite');
73
-		if ($dbType === 'sqlite3') {
74
-			$dbType = 'sqlite';
75
-		}
68
+    /**
69
+     * @return string
70
+     */
71
+    public function getDatabase() {
72
+        $dbType = $this->config->getSystemValue('dbtype', 'sqlite');
73
+        if ($dbType === 'sqlite3') {
74
+            $dbType = 'sqlite';
75
+        }
76 76
 
77
-		return $dbType;
78
-	}
77
+        return $dbType;
78
+    }
79 79
 
80
-	/**
81
-	 * @return string
82
-	 */
83
-	public function getOS() {
84
-		return php_uname('s');
85
-	}
80
+    /**
81
+     * @return string
82
+     */
83
+    public function getOS() {
84
+        return php_uname('s');
85
+    }
86 86
 
87
-	/**
88
-	 * @param $command
89
-	 * @return bool
90
-	 */
91
-	public function isCommandKnown($command) {
92
-		$path = \OC_Helper::findBinaryPath($command);
93
-		return ($path !== null);
94
-	}
87
+    /**
88
+     * @param $command
89
+     * @return bool
90
+     */
91
+    public function isCommandKnown($command) {
92
+        $path = \OC_Helper::findBinaryPath($command);
93
+        return ($path !== null);
94
+    }
95 95
 
96
-	public function getLibraryVersion($name) {
97
-		$repo = new PlatformRepository();
98
-		$lib = $repo->findLibrary($name);
99
-		return $lib;
100
-	}
96
+    public function getLibraryVersion($name) {
97
+        $repo = new PlatformRepository();
98
+        $lib = $repo->findLibrary($name);
99
+        return $lib;
100
+    }
101 101
 }
Please login to merge, or discard this patch.
lib/private/AppFramework/Http.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@
 block discarded – undo
110 110
 
111 111
 	/**
112 112
 	 * Gets the correct header
113
-	 * @param Http::CONSTANT $status the constant from the Http class
113
+	 * @param integer $status the constant from the Http class
114 114
 	 * @param \DateTime $lastModified formatted last modified date
115 115
 	 * @param string $ETag the etag
116 116
 	 * @return string
Please login to merge, or discard this patch.
Indentation   +115 added lines, -115 removed lines patch added patch discarded remove patch
@@ -33,121 +33,121 @@
 block discarded – undo
33 33
 
34 34
 class Http extends BaseHttp {
35 35
 
36
-	private $server;
37
-	private $protocolVersion;
38
-	protected $headers;
39
-
40
-	/**
41
-	 * @param array $server $_SERVER
42
-	 * @param string $protocolVersion the http version to use defaults to HTTP/1.1
43
-	 */
44
-	public function __construct($server, $protocolVersion='HTTP/1.1') {
45
-		$this->server = $server;
46
-		$this->protocolVersion = $protocolVersion;
47
-
48
-		$this->headers = array(
49
-			self::STATUS_CONTINUE => 'Continue',
50
-			self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols',
51
-			self::STATUS_PROCESSING => 'Processing',
52
-			self::STATUS_OK => 'OK',
53
-			self::STATUS_CREATED => 'Created',
54
-			self::STATUS_ACCEPTED => 'Accepted',
55
-			self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information',
56
-			self::STATUS_NO_CONTENT => 'No Content',
57
-			self::STATUS_RESET_CONTENT => 'Reset Content',
58
-			self::STATUS_PARTIAL_CONTENT => 'Partial Content',
59
-			self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918
60
-			self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842
61
-			self::STATUS_IM_USED => 'IM Used', // RFC 3229
62
-			self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices',
63
-			self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently',
64
-			self::STATUS_FOUND => 'Found',
65
-			self::STATUS_SEE_OTHER => 'See Other',
66
-			self::STATUS_NOT_MODIFIED => 'Not Modified',
67
-			self::STATUS_USE_PROXY => 'Use Proxy',
68
-			self::STATUS_RESERVED => 'Reserved',
69
-			self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect',
70
-			self::STATUS_BAD_REQUEST => 'Bad request',
71
-			self::STATUS_UNAUTHORIZED => 'Unauthorized',
72
-			self::STATUS_PAYMENT_REQUIRED => 'Payment Required',
73
-			self::STATUS_FORBIDDEN => 'Forbidden',
74
-			self::STATUS_NOT_FOUND => 'Not Found',
75
-			self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed',
76
-			self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable',
77
-			self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
78
-			self::STATUS_REQUEST_TIMEOUT => 'Request Timeout',
79
-			self::STATUS_CONFLICT => 'Conflict',
80
-			self::STATUS_GONE => 'Gone',
81
-			self::STATUS_LENGTH_REQUIRED => 'Length Required',
82
-			self::STATUS_PRECONDITION_FAILED => 'Precondition failed',
83
-			self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
84
-			self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long',
85
-			self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
86
-			self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable',
87
-			self::STATUS_EXPECTATION_FAILED => 'Expectation Failed',
88
-			self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324
89
-			self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918
90
-			self::STATUS_LOCKED => 'Locked', // RFC 4918
91
-			self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918
92
-			self::STATUS_UPGRADE_REQUIRED => 'Upgrade required',
93
-			self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status
94
-			self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status
95
-			self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status
96
-			self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error',
97
-			self::STATUS_NOT_IMPLEMENTED => 'Not Implemented',
98
-			self::STATUS_BAD_GATEWAY => 'Bad Gateway',
99
-			self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable',
100
-			self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout',
101
-			self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported',
102
-			self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates',
103
-			self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918
104
-			self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842
105
-			self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard
106
-			self::STATUS_NOT_EXTENDED => 'Not extended',
107
-			self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status
108
-		);
109
-	}
110
-
111
-
112
-	/**
113
-	 * Gets the correct header
114
-	 * @param Http::CONSTANT $status the constant from the Http class
115
-	 * @param \DateTime $lastModified formatted last modified date
116
-	 * @param string $ETag the etag
117
-	 * @return string
118
-	 */
119
-	public function getStatusHeader($status, \DateTime $lastModified=null, 
120
-	                                $ETag=null) {
121
-
122
-		if(!is_null($lastModified)) {
123
-			$lastModified = $lastModified->format(\DateTime::RFC2822);
124
-		}
125
-
126
-		// if etag or lastmodified have not changed, return a not modified
127
-		if ((isset($this->server['HTTP_IF_NONE_MATCH'])
128
-			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
129
-
130
-			||
131
-
132
-			(isset($this->server['HTTP_IF_MODIFIED_SINCE'])
133
-			&& trim($this->server['HTTP_IF_MODIFIED_SINCE']) === 
134
-				$lastModified)) {
135
-
136
-			$status = self::STATUS_NOT_MODIFIED;
137
-		}
138
-
139
-		// we have one change currently for the http 1.0 header that differs
140
-		// from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND
141
-		// if this differs any more, we want to create childclasses for this
142
-		if($status === self::STATUS_TEMPORARY_REDIRECT 
143
-			&& $this->protocolVersion === 'HTTP/1.0') {
144
-
145
-			$status = self::STATUS_FOUND;
146
-		}
147
-
148
-		return $this->protocolVersion . ' ' . $status . ' ' . 
149
-			$this->headers[$status];
150
-	}
36
+    private $server;
37
+    private $protocolVersion;
38
+    protected $headers;
39
+
40
+    /**
41
+     * @param array $server $_SERVER
42
+     * @param string $protocolVersion the http version to use defaults to HTTP/1.1
43
+     */
44
+    public function __construct($server, $protocolVersion='HTTP/1.1') {
45
+        $this->server = $server;
46
+        $this->protocolVersion = $protocolVersion;
47
+
48
+        $this->headers = array(
49
+            self::STATUS_CONTINUE => 'Continue',
50
+            self::STATUS_SWITCHING_PROTOCOLS => 'Switching Protocols',
51
+            self::STATUS_PROCESSING => 'Processing',
52
+            self::STATUS_OK => 'OK',
53
+            self::STATUS_CREATED => 'Created',
54
+            self::STATUS_ACCEPTED => 'Accepted',
55
+            self::STATUS_NON_AUTHORATIVE_INFORMATION => 'Non-Authorative Information',
56
+            self::STATUS_NO_CONTENT => 'No Content',
57
+            self::STATUS_RESET_CONTENT => 'Reset Content',
58
+            self::STATUS_PARTIAL_CONTENT => 'Partial Content',
59
+            self::STATUS_MULTI_STATUS => 'Multi-Status', // RFC 4918
60
+            self::STATUS_ALREADY_REPORTED => 'Already Reported', // RFC 5842
61
+            self::STATUS_IM_USED => 'IM Used', // RFC 3229
62
+            self::STATUS_MULTIPLE_CHOICES => 'Multiple Choices',
63
+            self::STATUS_MOVED_PERMANENTLY => 'Moved Permanently',
64
+            self::STATUS_FOUND => 'Found',
65
+            self::STATUS_SEE_OTHER => 'See Other',
66
+            self::STATUS_NOT_MODIFIED => 'Not Modified',
67
+            self::STATUS_USE_PROXY => 'Use Proxy',
68
+            self::STATUS_RESERVED => 'Reserved',
69
+            self::STATUS_TEMPORARY_REDIRECT => 'Temporary Redirect',
70
+            self::STATUS_BAD_REQUEST => 'Bad request',
71
+            self::STATUS_UNAUTHORIZED => 'Unauthorized',
72
+            self::STATUS_PAYMENT_REQUIRED => 'Payment Required',
73
+            self::STATUS_FORBIDDEN => 'Forbidden',
74
+            self::STATUS_NOT_FOUND => 'Not Found',
75
+            self::STATUS_METHOD_NOT_ALLOWED => 'Method Not Allowed',
76
+            self::STATUS_NOT_ACCEPTABLE => 'Not Acceptable',
77
+            self::STATUS_PROXY_AUTHENTICATION_REQUIRED => 'Proxy Authentication Required',
78
+            self::STATUS_REQUEST_TIMEOUT => 'Request Timeout',
79
+            self::STATUS_CONFLICT => 'Conflict',
80
+            self::STATUS_GONE => 'Gone',
81
+            self::STATUS_LENGTH_REQUIRED => 'Length Required',
82
+            self::STATUS_PRECONDITION_FAILED => 'Precondition failed',
83
+            self::STATUS_REQUEST_ENTITY_TOO_LARGE => 'Request Entity Too Large',
84
+            self::STATUS_REQUEST_URI_TOO_LONG => 'Request-URI Too Long',
85
+            self::STATUS_UNSUPPORTED_MEDIA_TYPE => 'Unsupported Media Type',
86
+            self::STATUS_REQUEST_RANGE_NOT_SATISFIABLE => 'Requested Range Not Satisfiable',
87
+            self::STATUS_EXPECTATION_FAILED => 'Expectation Failed',
88
+            self::STATUS_IM_A_TEAPOT => 'I\'m a teapot', // RFC 2324
89
+            self::STATUS_UNPROCESSABLE_ENTITY => 'Unprocessable Entity', // RFC 4918
90
+            self::STATUS_LOCKED => 'Locked', // RFC 4918
91
+            self::STATUS_FAILED_DEPENDENCY => 'Failed Dependency', // RFC 4918
92
+            self::STATUS_UPGRADE_REQUIRED => 'Upgrade required',
93
+            self::STATUS_PRECONDITION_REQUIRED => 'Precondition required', // draft-nottingham-http-new-status
94
+            self::STATUS_TOO_MANY_REQUESTS => 'Too Many Requests', // draft-nottingham-http-new-status
95
+            self::STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE => 'Request Header Fields Too Large', // draft-nottingham-http-new-status
96
+            self::STATUS_INTERNAL_SERVER_ERROR => 'Internal Server Error',
97
+            self::STATUS_NOT_IMPLEMENTED => 'Not Implemented',
98
+            self::STATUS_BAD_GATEWAY => 'Bad Gateway',
99
+            self::STATUS_SERVICE_UNAVAILABLE => 'Service Unavailable',
100
+            self::STATUS_GATEWAY_TIMEOUT => 'Gateway Timeout',
101
+            self::STATUS_HTTP_VERSION_NOT_SUPPORTED => 'HTTP Version not supported',
102
+            self::STATUS_VARIANT_ALSO_NEGOTIATES => 'Variant Also Negotiates',
103
+            self::STATUS_INSUFFICIENT_STORAGE => 'Insufficient Storage', // RFC 4918
104
+            self::STATUS_LOOP_DETECTED => 'Loop Detected', // RFC 5842
105
+            self::STATUS_BANDWIDTH_LIMIT_EXCEEDED => 'Bandwidth Limit Exceeded', // non-standard
106
+            self::STATUS_NOT_EXTENDED => 'Not extended',
107
+            self::STATUS_NETWORK_AUTHENTICATION_REQUIRED => 'Network Authentication Required', // draft-nottingham-http-new-status
108
+        );
109
+    }
110
+
111
+
112
+    /**
113
+     * Gets the correct header
114
+     * @param Http::CONSTANT $status the constant from the Http class
115
+     * @param \DateTime $lastModified formatted last modified date
116
+     * @param string $ETag the etag
117
+     * @return string
118
+     */
119
+    public function getStatusHeader($status, \DateTime $lastModified=null, 
120
+                                    $ETag=null) {
121
+
122
+        if(!is_null($lastModified)) {
123
+            $lastModified = $lastModified->format(\DateTime::RFC2822);
124
+        }
125
+
126
+        // if etag or lastmodified have not changed, return a not modified
127
+        if ((isset($this->server['HTTP_IF_NONE_MATCH'])
128
+            && trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
129
+
130
+            ||
131
+
132
+            (isset($this->server['HTTP_IF_MODIFIED_SINCE'])
133
+            && trim($this->server['HTTP_IF_MODIFIED_SINCE']) === 
134
+                $lastModified)) {
135
+
136
+            $status = self::STATUS_NOT_MODIFIED;
137
+        }
138
+
139
+        // we have one change currently for the http 1.0 header that differs
140
+        // from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND
141
+        // if this differs any more, we want to create childclasses for this
142
+        if($status === self::STATUS_TEMPORARY_REDIRECT 
143
+            && $this->protocolVersion === 'HTTP/1.0') {
144
+
145
+            $status = self::STATUS_FOUND;
146
+        }
147
+
148
+        return $this->protocolVersion . ' ' . $status . ' ' . 
149
+            $this->headers[$status];
150
+    }
151 151
 
152 152
 
153 153
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -41,7 +41,7 @@  discard block
 block discarded – undo
41 41
 	 * @param array $server $_SERVER
42 42
 	 * @param string $protocolVersion the http version to use defaults to HTTP/1.1
43 43
 	 */
44
-	public function __construct($server, $protocolVersion='HTTP/1.1') {
44
+	public function __construct($server, $protocolVersion = 'HTTP/1.1') {
45 45
 		$this->server = $server;
46 46
 		$this->protocolVersion = $protocolVersion;
47 47
 
@@ -116,16 +116,16 @@  discard block
 block discarded – undo
116 116
 	 * @param string $ETag the etag
117 117
 	 * @return string
118 118
 	 */
119
-	public function getStatusHeader($status, \DateTime $lastModified=null, 
120
-	                                $ETag=null) {
119
+	public function getStatusHeader($status, \DateTime $lastModified = null, 
120
+	                                $ETag = null) {
121 121
 
122
-		if(!is_null($lastModified)) {
122
+		if (!is_null($lastModified)) {
123 123
 			$lastModified = $lastModified->format(\DateTime::RFC2822);
124 124
 		}
125 125
 
126 126
 		// if etag or lastmodified have not changed, return a not modified
127 127
 		if ((isset($this->server['HTTP_IF_NONE_MATCH'])
128
-			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string)$ETag)
128
+			&& trim(trim($this->server['HTTP_IF_NONE_MATCH']), '"') === (string) $ETag)
129 129
 
130 130
 			||
131 131
 
@@ -139,13 +139,13 @@  discard block
 block discarded – undo
139 139
 		// we have one change currently for the http 1.0 header that differs
140 140
 		// from 1.1: STATUS_TEMPORARY_REDIRECT should be STATUS_FOUND
141 141
 		// if this differs any more, we want to create childclasses for this
142
-		if($status === self::STATUS_TEMPORARY_REDIRECT 
142
+		if ($status === self::STATUS_TEMPORARY_REDIRECT 
143 143
 			&& $this->protocolVersion === 'HTTP/1.0') {
144 144
 
145 145
 			$status = self::STATUS_FOUND;
146 146
 		}
147 147
 
148
-		return $this->protocolVersion . ' ' . $status . ' ' . 
148
+		return $this->protocolVersion.' '.$status.' '. 
149 149
 			$this->headers[$status];
150 150
 	}
151 151
 
Please login to merge, or discard this patch.
lib/private/AppFramework/Utility/ControllerMethodReflector.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -46,7 +46,7 @@
 block discarded – undo
46 46
 
47 47
 
48 48
 	/**
49
-	 * @param object $object an object or classname
49
+	 * @param \OCP\AppFramework\Controller $object an object or classname
50 50
 	 * @param string $method the method which we want to inspect
51 51
 	 */
52 52
 	public function reflect($object, $method){
Please login to merge, or discard this patch.
Indentation   +96 added lines, -96 removed lines patch added patch discarded remove patch
@@ -35,102 +35,102 @@
 block discarded – undo
35 35
  */
36 36
 class ControllerMethodReflector implements IControllerMethodReflector{
37 37
 
38
-	private $annotations;
39
-	private $types;
40
-	private $parameters;
41
-
42
-	public function __construct() {
43
-		$this->types = array();
44
-		$this->parameters = array();
45
-		$this->annotations = array();
46
-	}
47
-
48
-
49
-	/**
50
-	 * @param object $object an object or classname
51
-	 * @param string $method the method which we want to inspect
52
-	 */
53
-	public function reflect($object, $method){
54
-		$reflection = new \ReflectionMethod($object, $method);
55
-		$docs = $reflection->getDocComment();
56
-
57
-		// extract everything prefixed by @ and first letter uppercase
58
-		preg_match_all('/^\h+\*\h+@(?P<annotation>[A-Z]\w+)(\h+(?P<parameter>\w+))?$/m', $docs, $matches);
59
-		foreach($matches['annotation'] as $key => $annontation) {
60
-			$this->annotations[$annontation] = $matches['parameter'][$key];
61
-		}
62
-
63
-		// extract type parameter information
64
-		preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches);
65
-		$this->types = array_combine($matches['var'], $matches['type']);
66
-
67
-		foreach ($reflection->getParameters() as $param) {
68
-			// extract type information from PHP 7 scalar types and prefer them
69
-			// over phpdoc annotations
70
-			if (method_exists($param, 'getType')) {
71
-				$type = $param->getType();
72
-				if ($type !== null) {
73
-					$this->types[$param->getName()] = (string) $type;
74
-				}
75
-			}
76
-
77
-			if($param->isOptional()) {
78
-				$default = $param->getDefaultValue();
79
-			} else {
80
-				$default = null;
81
-			}
82
-			$this->parameters[$param->name] = $default;
83
-		}
84
-	}
85
-
86
-
87
-	/**
88
-	 * Inspects the PHPDoc parameters for types
89
-	 * @param string $parameter the parameter whose type comments should be
90
-	 * parsed
91
-	 * @return string|null type in the type parameters (@param int $something)
92
-	 * would return int or null if not existing
93
-	 */
94
-	public function getType($parameter) {
95
-		if(array_key_exists($parameter, $this->types)) {
96
-			return $this->types[$parameter];
97
-		} else {
98
-			return null;
99
-		}
100
-	}
101
-
102
-
103
-	/**
104
-	 * @return array the arguments of the method with key => default value
105
-	 */
106
-	public function getParameters() {
107
-		return $this->parameters;
108
-	}
109
-
110
-
111
-	/**
112
-	 * Check if a method contains an annotation
113
-	 * @param string $name the name of the annotation
114
-	 * @return bool true if the annotation is found
115
-	 */
116
-	public function hasAnnotation($name){
117
-		return array_key_exists($name, $this->annotations);
118
-	}
119
-
120
-
121
-	/**
122
-	 * Get optional annotation parameter
123
-	 * @param string $name the name of the annotation
124
-	 * @return string
125
-	 */
126
-	public function getAnnotationParameter($name){
127
-		$parameter = '';
128
-		if($this->hasAnnotation($name)) {
129
-			$parameter = $this->annotations[$name];
130
-		}
131
-
132
-		return $parameter;
133
-	}
38
+    private $annotations;
39
+    private $types;
40
+    private $parameters;
41
+
42
+    public function __construct() {
43
+        $this->types = array();
44
+        $this->parameters = array();
45
+        $this->annotations = array();
46
+    }
47
+
48
+
49
+    /**
50
+     * @param object $object an object or classname
51
+     * @param string $method the method which we want to inspect
52
+     */
53
+    public function reflect($object, $method){
54
+        $reflection = new \ReflectionMethod($object, $method);
55
+        $docs = $reflection->getDocComment();
56
+
57
+        // extract everything prefixed by @ and first letter uppercase
58
+        preg_match_all('/^\h+\*\h+@(?P<annotation>[A-Z]\w+)(\h+(?P<parameter>\w+))?$/m', $docs, $matches);
59
+        foreach($matches['annotation'] as $key => $annontation) {
60
+            $this->annotations[$annontation] = $matches['parameter'][$key];
61
+        }
62
+
63
+        // extract type parameter information
64
+        preg_match_all('/@param\h+(?P<type>\w+)\h+\$(?P<var>\w+)/', $docs, $matches);
65
+        $this->types = array_combine($matches['var'], $matches['type']);
66
+
67
+        foreach ($reflection->getParameters() as $param) {
68
+            // extract type information from PHP 7 scalar types and prefer them
69
+            // over phpdoc annotations
70
+            if (method_exists($param, 'getType')) {
71
+                $type = $param->getType();
72
+                if ($type !== null) {
73
+                    $this->types[$param->getName()] = (string) $type;
74
+                }
75
+            }
76
+
77
+            if($param->isOptional()) {
78
+                $default = $param->getDefaultValue();
79
+            } else {
80
+                $default = null;
81
+            }
82
+            $this->parameters[$param->name] = $default;
83
+        }
84
+    }
85
+
86
+
87
+    /**
88
+     * Inspects the PHPDoc parameters for types
89
+     * @param string $parameter the parameter whose type comments should be
90
+     * parsed
91
+     * @return string|null type in the type parameters (@param int $something)
92
+     * would return int or null if not existing
93
+     */
94
+    public function getType($parameter) {
95
+        if(array_key_exists($parameter, $this->types)) {
96
+            return $this->types[$parameter];
97
+        } else {
98
+            return null;
99
+        }
100
+    }
101
+
102
+
103
+    /**
104
+     * @return array the arguments of the method with key => default value
105
+     */
106
+    public function getParameters() {
107
+        return $this->parameters;
108
+    }
109
+
110
+
111
+    /**
112
+     * Check if a method contains an annotation
113
+     * @param string $name the name of the annotation
114
+     * @return bool true if the annotation is found
115
+     */
116
+    public function hasAnnotation($name){
117
+        return array_key_exists($name, $this->annotations);
118
+    }
119
+
120
+
121
+    /**
122
+     * Get optional annotation parameter
123
+     * @param string $name the name of the annotation
124
+     * @return string
125
+     */
126
+    public function getAnnotationParameter($name){
127
+        $parameter = '';
128
+        if($this->hasAnnotation($name)) {
129
+            $parameter = $this->annotations[$name];
130
+        }
131
+
132
+        return $parameter;
133
+    }
134 134
 
135 135
 
136 136
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
 /**
34 34
  * Reads and parses annotations from doc comments
35 35
  */
36
-class ControllerMethodReflector implements IControllerMethodReflector{
36
+class ControllerMethodReflector implements IControllerMethodReflector {
37 37
 
38 38
 	private $annotations;
39 39
 	private $types;
@@ -50,13 +50,13 @@  discard block
 block discarded – undo
50 50
 	 * @param object $object an object or classname
51 51
 	 * @param string $method the method which we want to inspect
52 52
 	 */
53
-	public function reflect($object, $method){
53
+	public function reflect($object, $method) {
54 54
 		$reflection = new \ReflectionMethod($object, $method);
55 55
 		$docs = $reflection->getDocComment();
56 56
 
57 57
 		// extract everything prefixed by @ and first letter uppercase
58 58
 		preg_match_all('/^\h+\*\h+@(?P<annotation>[A-Z]\w+)(\h+(?P<parameter>\w+))?$/m', $docs, $matches);
59
-		foreach($matches['annotation'] as $key => $annontation) {
59
+		foreach ($matches['annotation'] as $key => $annontation) {
60 60
 			$this->annotations[$annontation] = $matches['parameter'][$key];
61 61
 		}
62 62
 
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 				}
75 75
 			}
76 76
 
77
-			if($param->isOptional()) {
77
+			if ($param->isOptional()) {
78 78
 				$default = $param->getDefaultValue();
79 79
 			} else {
80 80
 				$default = null;
@@ -92,7 +92,7 @@  discard block
 block discarded – undo
92 92
 	 * would return int or null if not existing
93 93
 	 */
94 94
 	public function getType($parameter) {
95
-		if(array_key_exists($parameter, $this->types)) {
95
+		if (array_key_exists($parameter, $this->types)) {
96 96
 			return $this->types[$parameter];
97 97
 		} else {
98 98
 			return null;
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 	 * @param string $name the name of the annotation
114 114
 	 * @return bool true if the annotation is found
115 115
 	 */
116
-	public function hasAnnotation($name){
116
+	public function hasAnnotation($name) {
117 117
 		return array_key_exists($name, $this->annotations);
118 118
 	}
119 119
 
@@ -123,9 +123,9 @@  discard block
 block discarded – undo
123 123
 	 * @param string $name the name of the annotation
124 124
 	 * @return string
125 125
 	 */
126
-	public function getAnnotationParameter($name){
126
+	public function getAnnotationParameter($name) {
127 127
 		$parameter = '';
128
-		if($this->hasAnnotation($name)) {
128
+		if ($this->hasAnnotation($name)) {
129 129
 			$parameter = $this->annotations[$name];
130 130
 		}
131 131
 
Please login to merge, or discard this patch.
lib/private/Comments/Manager.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -205,7 +205,7 @@
 block discarded – undo
205 205
 	/**
206 206
 	 * removes an entry from the comments run time cache
207 207
 	 *
208
-	 * @param mixed $id the comment's id
208
+	 * @param string $id the comment's id
209 209
 	 */
210 210
 	protected function uncache($id) {
211 211
 		$id = strval($id);
Please login to merge, or discard this patch.
Indentation   +804 added lines, -804 removed lines patch added patch discarded remove patch
@@ -37,808 +37,808 @@
 block discarded – undo
37 37
 
38 38
 class Manager implements ICommentsManager {
39 39
 
40
-	/** @var  IDBConnection */
41
-	protected $dbConn;
42
-
43
-	/** @var  ILogger */
44
-	protected $logger;
45
-
46
-	/** @var IConfig */
47
-	protected $config;
48
-
49
-	/** @var IComment[]  */
50
-	protected $commentsCache = [];
51
-
52
-	/** @var  \Closure[] */
53
-	protected $eventHandlerClosures = [];
54
-
55
-	/** @var  ICommentsEventHandler[] */
56
-	protected $eventHandlers = [];
57
-
58
-	/** @var \Closure[] */
59
-	protected $displayNameResolvers = [];
60
-
61
-	/**
62
-	 * Manager constructor.
63
-	 *
64
-	 * @param IDBConnection $dbConn
65
-	 * @param ILogger $logger
66
-	 * @param IConfig $config
67
-	 */
68
-	public function __construct(
69
-		IDBConnection $dbConn,
70
-		ILogger $logger,
71
-		IConfig $config
72
-	) {
73
-		$this->dbConn = $dbConn;
74
-		$this->logger = $logger;
75
-		$this->config = $config;
76
-	}
77
-
78
-	/**
79
-	 * converts data base data into PHP native, proper types as defined by
80
-	 * IComment interface.
81
-	 *
82
-	 * @param array $data
83
-	 * @return array
84
-	 */
85
-	protected function normalizeDatabaseData(array $data) {
86
-		$data['id'] = strval($data['id']);
87
-		$data['parent_id'] = strval($data['parent_id']);
88
-		$data['topmost_parent_id'] = strval($data['topmost_parent_id']);
89
-		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
90
-		if (!is_null($data['latest_child_timestamp'])) {
91
-			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
92
-		}
93
-		$data['children_count'] = intval($data['children_count']);
94
-		return $data;
95
-	}
96
-
97
-	/**
98
-	 * prepares a comment for an insert or update operation after making sure
99
-	 * all necessary fields have a value assigned.
100
-	 *
101
-	 * @param IComment $comment
102
-	 * @return IComment returns the same updated IComment instance as provided
103
-	 *                  by parameter for convenience
104
-	 * @throws \UnexpectedValueException
105
-	 */
106
-	protected function prepareCommentForDatabaseWrite(IComment $comment) {
107
-		if(    !$comment->getActorType()
108
-			|| !$comment->getActorId()
109
-			|| !$comment->getObjectType()
110
-			|| !$comment->getObjectId()
111
-			|| !$comment->getVerb()
112
-		) {
113
-			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
114
-		}
115
-
116
-		if($comment->getId() === '') {
117
-			$comment->setChildrenCount(0);
118
-			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
119
-			$comment->setLatestChildDateTime(null);
120
-		}
121
-
122
-		if(is_null($comment->getCreationDateTime())) {
123
-			$comment->setCreationDateTime(new \DateTime());
124
-		}
125
-
126
-		if($comment->getParentId() !== '0') {
127
-			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
128
-		} else {
129
-			$comment->setTopmostParentId('0');
130
-		}
131
-
132
-		$this->cache($comment);
133
-
134
-		return $comment;
135
-	}
136
-
137
-	/**
138
-	 * returns the topmost parent id of a given comment identified by ID
139
-	 *
140
-	 * @param string $id
141
-	 * @return string
142
-	 * @throws NotFoundException
143
-	 */
144
-	protected function determineTopmostParentId($id) {
145
-		$comment = $this->get($id);
146
-		if($comment->getParentId() === '0') {
147
-			return $comment->getId();
148
-		} else {
149
-			return $this->determineTopmostParentId($comment->getId());
150
-		}
151
-	}
152
-
153
-	/**
154
-	 * updates child information of a comment
155
-	 *
156
-	 * @param string	$id
157
-	 * @param \DateTime	$cDateTime	the date time of the most recent child
158
-	 * @throws NotFoundException
159
-	 */
160
-	protected function updateChildrenInformation($id, \DateTime $cDateTime) {
161
-		$qb = $this->dbConn->getQueryBuilder();
162
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
163
-				->from('comments')
164
-				->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
165
-				->setParameter('id', $id);
166
-
167
-		$resultStatement = $query->execute();
168
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
169
-		$resultStatement->closeCursor();
170
-		$children = intval($data[0]);
171
-
172
-		$comment = $this->get($id);
173
-		$comment->setChildrenCount($children);
174
-		$comment->setLatestChildDateTime($cDateTime);
175
-		$this->save($comment);
176
-	}
177
-
178
-	/**
179
-	 * Tests whether actor or object type and id parameters are acceptable.
180
-	 * Throws exception if not.
181
-	 *
182
-	 * @param string $role
183
-	 * @param string $type
184
-	 * @param string $id
185
-	 * @throws \InvalidArgumentException
186
-	 */
187
-	protected function checkRoleParameters($role, $type, $id) {
188
-		if(
189
-			   !is_string($type) || empty($type)
190
-			|| !is_string($id) || empty($id)
191
-		) {
192
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
193
-		}
194
-	}
195
-
196
-	/**
197
-	 * run-time caches a comment
198
-	 *
199
-	 * @param IComment $comment
200
-	 */
201
-	protected function cache(IComment $comment) {
202
-		$id = $comment->getId();
203
-		if(empty($id)) {
204
-			return;
205
-		}
206
-		$this->commentsCache[strval($id)] = $comment;
207
-	}
208
-
209
-	/**
210
-	 * removes an entry from the comments run time cache
211
-	 *
212
-	 * @param mixed $id the comment's id
213
-	 */
214
-	protected function uncache($id) {
215
-		$id = strval($id);
216
-		if (isset($this->commentsCache[$id])) {
217
-			unset($this->commentsCache[$id]);
218
-		}
219
-	}
220
-
221
-	/**
222
-	 * returns a comment instance
223
-	 *
224
-	 * @param string $id the ID of the comment
225
-	 * @return IComment
226
-	 * @throws NotFoundException
227
-	 * @throws \InvalidArgumentException
228
-	 * @since 9.0.0
229
-	 */
230
-	public function get($id) {
231
-		if(intval($id) === 0) {
232
-			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
233
-		}
234
-
235
-		if(isset($this->commentsCache[$id])) {
236
-			return $this->commentsCache[$id];
237
-		}
238
-
239
-		$qb = $this->dbConn->getQueryBuilder();
240
-		$resultStatement = $qb->select('*')
241
-			->from('comments')
242
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
243
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT)
244
-			->execute();
245
-
246
-		$data = $resultStatement->fetch();
247
-		$resultStatement->closeCursor();
248
-		if(!$data) {
249
-			throw new NotFoundException();
250
-		}
251
-
252
-		$comment = new Comment($this->normalizeDatabaseData($data));
253
-		$this->cache($comment);
254
-		return $comment;
255
-	}
256
-
257
-	/**
258
-	 * returns the comment specified by the id and all it's child comments.
259
-	 * At this point of time, we do only support one level depth.
260
-	 *
261
-	 * @param string $id
262
-	 * @param int $limit max number of entries to return, 0 returns all
263
-	 * @param int $offset the start entry
264
-	 * @return array
265
-	 * @since 9.0.0
266
-	 *
267
-	 * The return array looks like this
268
-	 * [
269
-	 *   'comment' => IComment, // root comment
270
-	 *   'replies' =>
271
-	 *   [
272
-	 *     0 =>
273
-	 *     [
274
-	 *       'comment' => IComment,
275
-	 *       'replies' => []
276
-	 *     ]
277
-	 *     1 =>
278
-	 *     [
279
-	 *       'comment' => IComment,
280
-	 *       'replies'=> []
281
-	 *     ],
282
-	 *     …
283
-	 *   ]
284
-	 * ]
285
-	 */
286
-	public function getTree($id, $limit = 0, $offset = 0) {
287
-		$tree = [];
288
-		$tree['comment'] = $this->get($id);
289
-		$tree['replies'] = [];
290
-
291
-		$qb = $this->dbConn->getQueryBuilder();
292
-		$query = $qb->select('*')
293
-				->from('comments')
294
-				->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
295
-				->orderBy('creation_timestamp', 'DESC')
296
-				->setParameter('id', $id);
297
-
298
-		if($limit > 0) {
299
-			$query->setMaxResults($limit);
300
-		}
301
-		if($offset > 0) {
302
-			$query->setFirstResult($offset);
303
-		}
304
-
305
-		$resultStatement = $query->execute();
306
-		while($data = $resultStatement->fetch()) {
307
-			$comment = new Comment($this->normalizeDatabaseData($data));
308
-			$this->cache($comment);
309
-			$tree['replies'][] = [
310
-				'comment' => $comment,
311
-				'replies' => []
312
-			];
313
-		}
314
-		$resultStatement->closeCursor();
315
-
316
-		return $tree;
317
-	}
318
-
319
-	/**
320
-	 * returns comments for a specific object (e.g. a file).
321
-	 *
322
-	 * The sort order is always newest to oldest.
323
-	 *
324
-	 * @param string $objectType the object type, e.g. 'files'
325
-	 * @param string $objectId the id of the object
326
-	 * @param int $limit optional, number of maximum comments to be returned. if
327
-	 * not specified, all comments are returned.
328
-	 * @param int $offset optional, starting point
329
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
330
-	 * that may be returned
331
-	 * @return IComment[]
332
-	 * @since 9.0.0
333
-	 */
334
-	public function getForObject(
335
-			$objectType,
336
-			$objectId,
337
-			$limit = 0,
338
-			$offset = 0,
339
-			\DateTime $notOlderThan = null
340
-	) {
341
-		$comments = [];
342
-
343
-		$qb = $this->dbConn->getQueryBuilder();
344
-		$query = $qb->select('*')
345
-				->from('comments')
346
-				->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
347
-				->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
348
-				->orderBy('creation_timestamp', 'DESC')
349
-				->setParameter('type', $objectType)
350
-				->setParameter('id', $objectId);
351
-
352
-		if($limit > 0) {
353
-			$query->setMaxResults($limit);
354
-		}
355
-		if($offset > 0) {
356
-			$query->setFirstResult($offset);
357
-		}
358
-		if(!is_null($notOlderThan)) {
359
-			$query
360
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
361
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
362
-		}
363
-
364
-		$resultStatement = $query->execute();
365
-		while($data = $resultStatement->fetch()) {
366
-			$comment = new Comment($this->normalizeDatabaseData($data));
367
-			$this->cache($comment);
368
-			$comments[] = $comment;
369
-		}
370
-		$resultStatement->closeCursor();
371
-
372
-		return $comments;
373
-	}
374
-
375
-	/**
376
-	 * @param $objectType string the object type, e.g. 'files'
377
-	 * @param $objectId string the id of the object
378
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
379
-	 * that may be returned
380
-	 * @return Int
381
-	 * @since 9.0.0
382
-	 */
383
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
384
-		$qb = $this->dbConn->getQueryBuilder();
385
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
386
-				->from('comments')
387
-				->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
388
-				->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
389
-				->setParameter('type', $objectType)
390
-				->setParameter('id', $objectId);
391
-
392
-		if(!is_null($notOlderThan)) {
393
-			$query
394
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
395
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
396
-		}
397
-
398
-		$resultStatement = $query->execute();
399
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
400
-		$resultStatement->closeCursor();
401
-		return intval($data[0]);
402
-	}
403
-
404
-	/**
405
-	 * creates a new comment and returns it. At this point of time, it is not
406
-	 * saved in the used data storage. Use save() after setting other fields
407
-	 * of the comment (e.g. message or verb).
408
-	 *
409
-	 * @param string $actorType the actor type (e.g. 'users')
410
-	 * @param string $actorId a user id
411
-	 * @param string $objectType the object type the comment is attached to
412
-	 * @param string $objectId the object id the comment is attached to
413
-	 * @return IComment
414
-	 * @since 9.0.0
415
-	 */
416
-	public function create($actorType, $actorId, $objectType, $objectId) {
417
-		$comment = new Comment();
418
-		$comment
419
-			->setActor($actorType, $actorId)
420
-			->setObject($objectType, $objectId);
421
-		return $comment;
422
-	}
423
-
424
-	/**
425
-	 * permanently deletes the comment specified by the ID
426
-	 *
427
-	 * When the comment has child comments, their parent ID will be changed to
428
-	 * the parent ID of the item that is to be deleted.
429
-	 *
430
-	 * @param string $id
431
-	 * @return bool
432
-	 * @throws \InvalidArgumentException
433
-	 * @since 9.0.0
434
-	 */
435
-	public function delete($id) {
436
-		if(!is_string($id)) {
437
-			throw new \InvalidArgumentException('Parameter must be string');
438
-		}
439
-
440
-		try {
441
-			$comment = $this->get($id);
442
-		} catch (\Exception $e) {
443
-			// Ignore exceptions, we just don't fire a hook then
444
-			$comment = null;
445
-		}
446
-
447
-		$qb = $this->dbConn->getQueryBuilder();
448
-		$query = $qb->delete('comments')
449
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
450
-			->setParameter('id', $id);
451
-
452
-		try {
453
-			$affectedRows = $query->execute();
454
-			$this->uncache($id);
455
-		} catch (DriverException $e) {
456
-			$this->logger->logException($e, ['app' => 'core_comments']);
457
-			return false;
458
-		}
459
-
460
-		if ($affectedRows > 0 && $comment instanceof IComment) {
461
-			$this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
462
-		}
463
-
464
-		return ($affectedRows > 0);
465
-	}
466
-
467
-	/**
468
-	 * saves the comment permanently
469
-	 *
470
-	 * if the supplied comment has an empty ID, a new entry comment will be
471
-	 * saved and the instance updated with the new ID.
472
-	 *
473
-	 * Otherwise, an existing comment will be updated.
474
-	 *
475
-	 * Throws NotFoundException when a comment that is to be updated does not
476
-	 * exist anymore at this point of time.
477
-	 *
478
-	 * @param IComment $comment
479
-	 * @return bool
480
-	 * @throws NotFoundException
481
-	 * @since 9.0.0
482
-	 */
483
-	public function save(IComment $comment) {
484
-		if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
485
-			$result = $this->insert($comment);
486
-		} else {
487
-			$result = $this->update($comment);
488
-		}
489
-
490
-		if($result && !!$comment->getParentId()) {
491
-			$this->updateChildrenInformation(
492
-					$comment->getParentId(),
493
-					$comment->getCreationDateTime()
494
-			);
495
-			$this->cache($comment);
496
-		}
497
-
498
-		return $result;
499
-	}
500
-
501
-	/**
502
-	 * inserts the provided comment in the database
503
-	 *
504
-	 * @param IComment $comment
505
-	 * @return bool
506
-	 */
507
-	protected function insert(IComment &$comment) {
508
-		$qb = $this->dbConn->getQueryBuilder();
509
-		$affectedRows = $qb
510
-			->insert('comments')
511
-			->values([
512
-				'parent_id'					=> $qb->createNamedParameter($comment->getParentId()),
513
-				'topmost_parent_id' 		=> $qb->createNamedParameter($comment->getTopmostParentId()),
514
-				'children_count' 			=> $qb->createNamedParameter($comment->getChildrenCount()),
515
-				'actor_type' 				=> $qb->createNamedParameter($comment->getActorType()),
516
-				'actor_id' 					=> $qb->createNamedParameter($comment->getActorId()),
517
-				'message' 					=> $qb->createNamedParameter($comment->getMessage()),
518
-				'verb' 						=> $qb->createNamedParameter($comment->getVerb()),
519
-				'creation_timestamp' 		=> $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
520
-				'latest_child_timestamp'	=> $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
521
-				'object_type' 				=> $qb->createNamedParameter($comment->getObjectType()),
522
-				'object_id' 				=> $qb->createNamedParameter($comment->getObjectId()),
523
-			])
524
-			->execute();
525
-
526
-		if ($affectedRows > 0) {
527
-			$comment->setId(strval($qb->getLastInsertId()));
528
-			$this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
529
-		}
530
-
531
-		return $affectedRows > 0;
532
-	}
533
-
534
-	/**
535
-	 * updates a Comment data row
536
-	 *
537
-	 * @param IComment $comment
538
-	 * @return bool
539
-	 * @throws NotFoundException
540
-	 */
541
-	protected function update(IComment $comment) {
542
-		// for properly working preUpdate Events we need the old comments as is
543
-		// in the DB and overcome caching. Also avoid that outdated information stays.
544
-		$this->uncache($comment->getId());
545
-		$this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
546
-		$this->uncache($comment->getId());
547
-
548
-		$qb = $this->dbConn->getQueryBuilder();
549
-		$affectedRows = $qb
550
-			->update('comments')
551
-				->set('parent_id',				$qb->createNamedParameter($comment->getParentId()))
552
-				->set('topmost_parent_id', 		$qb->createNamedParameter($comment->getTopmostParentId()))
553
-				->set('children_count',			$qb->createNamedParameter($comment->getChildrenCount()))
554
-				->set('actor_type', 			$qb->createNamedParameter($comment->getActorType()))
555
-				->set('actor_id', 				$qb->createNamedParameter($comment->getActorId()))
556
-				->set('message',				$qb->createNamedParameter($comment->getMessage()))
557
-				->set('verb',					$qb->createNamedParameter($comment->getVerb()))
558
-				->set('creation_timestamp',		$qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
559
-				->set('latest_child_timestamp',	$qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
560
-				->set('object_type',			$qb->createNamedParameter($comment->getObjectType()))
561
-				->set('object_id',				$qb->createNamedParameter($comment->getObjectId()))
562
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
563
-			->setParameter('id', $comment->getId())
564
-			->execute();
565
-
566
-		if($affectedRows === 0) {
567
-			throw new NotFoundException('Comment to update does ceased to exist');
568
-		}
569
-
570
-		$this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
571
-
572
-		return $affectedRows > 0;
573
-	}
574
-
575
-	/**
576
-	 * removes references to specific actor (e.g. on user delete) of a comment.
577
-	 * The comment itself must not get lost/deleted.
578
-	 *
579
-	 * @param string $actorType the actor type (e.g. 'users')
580
-	 * @param string $actorId a user id
581
-	 * @return boolean
582
-	 * @since 9.0.0
583
-	 */
584
-	public function deleteReferencesOfActor($actorType, $actorId) {
585
-		$this->checkRoleParameters('Actor', $actorType, $actorId);
586
-
587
-		$qb = $this->dbConn->getQueryBuilder();
588
-		$affectedRows = $qb
589
-			->update('comments')
590
-			->set('actor_type',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
591
-			->set('actor_id',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
592
-			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
593
-			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
594
-			->setParameter('type', $actorType)
595
-			->setParameter('id', $actorId)
596
-			->execute();
597
-
598
-		$this->commentsCache = [];
599
-
600
-		return is_int($affectedRows);
601
-	}
602
-
603
-	/**
604
-	 * deletes all comments made of a specific object (e.g. on file delete)
605
-	 *
606
-	 * @param string $objectType the object type (e.g. 'files')
607
-	 * @param string $objectId e.g. the file id
608
-	 * @return boolean
609
-	 * @since 9.0.0
610
-	 */
611
-	public function deleteCommentsAtObject($objectType, $objectId) {
612
-		$this->checkRoleParameters('Object', $objectType, $objectId);
613
-
614
-		$qb = $this->dbConn->getQueryBuilder();
615
-		$affectedRows = $qb
616
-			->delete('comments')
617
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
618
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
619
-			->setParameter('type', $objectType)
620
-			->setParameter('id', $objectId)
621
-			->execute();
622
-
623
-		$this->commentsCache = [];
624
-
625
-		return is_int($affectedRows);
626
-	}
627
-
628
-	/**
629
-	 * deletes the read markers for the specified user
630
-	 *
631
-	 * @param \OCP\IUser $user
632
-	 * @return bool
633
-	 * @since 9.0.0
634
-	 */
635
-	public function deleteReadMarksFromUser(IUser $user) {
636
-		$qb = $this->dbConn->getQueryBuilder();
637
-		$query = $qb->delete('comments_read_markers')
638
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
639
-			->setParameter('user_id', $user->getUID());
640
-
641
-		try {
642
-			$affectedRows = $query->execute();
643
-		} catch (DriverException $e) {
644
-			$this->logger->logException($e, ['app' => 'core_comments']);
645
-			return false;
646
-		}
647
-		return ($affectedRows > 0);
648
-	}
649
-
650
-	/**
651
-	 * sets the read marker for a given file to the specified date for the
652
-	 * provided user
653
-	 *
654
-	 * @param string $objectType
655
-	 * @param string $objectId
656
-	 * @param \DateTime $dateTime
657
-	 * @param IUser $user
658
-	 * @since 9.0.0
659
-	 */
660
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
661
-		$this->checkRoleParameters('Object', $objectType, $objectId);
662
-
663
-		$qb = $this->dbConn->getQueryBuilder();
664
-		$values = [
665
-			'user_id'         => $qb->createNamedParameter($user->getUID()),
666
-			'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
667
-			'object_type'     => $qb->createNamedParameter($objectType),
668
-			'object_id'       => $qb->createNamedParameter($objectId),
669
-		];
670
-
671
-		// Strategy: try to update, if this does not return affected rows, do an insert.
672
-		$affectedRows = $qb
673
-			->update('comments_read_markers')
674
-			->set('user_id',         $values['user_id'])
675
-			->set('marker_datetime', $values['marker_datetime'])
676
-			->set('object_type',     $values['object_type'])
677
-			->set('object_id',       $values['object_id'])
678
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
679
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
680
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
681
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
682
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
683
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
684
-			->execute();
685
-
686
-		if ($affectedRows > 0) {
687
-			return;
688
-		}
689
-
690
-		$qb->insert('comments_read_markers')
691
-			->values($values)
692
-			->execute();
693
-	}
694
-
695
-	/**
696
-	 * returns the read marker for a given file to the specified date for the
697
-	 * provided user. It returns null, when the marker is not present, i.e.
698
-	 * no comments were marked as read.
699
-	 *
700
-	 * @param string $objectType
701
-	 * @param string $objectId
702
-	 * @param IUser $user
703
-	 * @return \DateTime|null
704
-	 * @since 9.0.0
705
-	 */
706
-	public function getReadMark($objectType, $objectId, IUser $user) {
707
-		$qb = $this->dbConn->getQueryBuilder();
708
-		$resultStatement = $qb->select('marker_datetime')
709
-			->from('comments_read_markers')
710
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
711
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
712
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
713
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
714
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
715
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
716
-			->execute();
717
-
718
-		$data = $resultStatement->fetch();
719
-		$resultStatement->closeCursor();
720
-		if(!$data || is_null($data['marker_datetime'])) {
721
-			return null;
722
-		}
723
-
724
-		return new \DateTime($data['marker_datetime']);
725
-	}
726
-
727
-	/**
728
-	 * deletes the read markers on the specified object
729
-	 *
730
-	 * @param string $objectType
731
-	 * @param string $objectId
732
-	 * @return bool
733
-	 * @since 9.0.0
734
-	 */
735
-	public function deleteReadMarksOnObject($objectType, $objectId) {
736
-		$this->checkRoleParameters('Object', $objectType, $objectId);
737
-
738
-		$qb = $this->dbConn->getQueryBuilder();
739
-		$query = $qb->delete('comments_read_markers')
740
-			->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
741
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
742
-			->setParameter('object_type', $objectType)
743
-			->setParameter('object_id', $objectId);
744
-
745
-		try {
746
-			$affectedRows = $query->execute();
747
-		} catch (DriverException $e) {
748
-			$this->logger->logException($e, ['app' => 'core_comments']);
749
-			return false;
750
-		}
751
-		return ($affectedRows > 0);
752
-	}
753
-
754
-	/**
755
-	 * registers an Entity to the manager, so event notifications can be send
756
-	 * to consumers of the comments infrastructure
757
-	 *
758
-	 * @param \Closure $closure
759
-	 */
760
-	public function registerEventHandler(\Closure $closure) {
761
-		$this->eventHandlerClosures[] = $closure;
762
-		$this->eventHandlers = [];
763
-	}
764
-
765
-	/**
766
-	 * registers a method that resolves an ID to a display name for a given type
767
-	 *
768
-	 * @param string $type
769
-	 * @param \Closure $closure
770
-	 * @throws \OutOfBoundsException
771
-	 * @since 11.0.0
772
-	 *
773
-	 * Only one resolver shall be registered per type. Otherwise a
774
-	 * \OutOfBoundsException has to thrown.
775
-	 */
776
-	public function registerDisplayNameResolver($type, \Closure $closure) {
777
-		if(!is_string($type)) {
778
-			throw new \InvalidArgumentException('String expected.');
779
-		}
780
-		if(isset($this->displayNameResolvers[$type])) {
781
-			throw new \OutOfBoundsException('Displayname resolver for this type already registered');
782
-		}
783
-		$this->displayNameResolvers[$type] = $closure;
784
-	}
785
-
786
-	/**
787
-	 * resolves a given ID of a given Type to a display name.
788
-	 *
789
-	 * @param string $type
790
-	 * @param string $id
791
-	 * @return string
792
-	 * @throws \OutOfBoundsException
793
-	 * @since 11.0.0
794
-	 *
795
-	 * If a provided type was not registered, an \OutOfBoundsException shall
796
-	 * be thrown. It is upon the resolver discretion what to return of the
797
-	 * provided ID is unknown. It must be ensured that a string is returned.
798
-	 */
799
-	public function resolveDisplayName($type, $id) {
800
-		if(!is_string($type)) {
801
-			throw new \InvalidArgumentException('String expected.');
802
-		}
803
-		if(!isset($this->displayNameResolvers[$type])) {
804
-			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
805
-		}
806
-		return (string)$this->displayNameResolvers[$type]($id);
807
-	}
808
-
809
-	/**
810
-	 * returns valid, registered entities
811
-	 *
812
-	 * @return \OCP\Comments\ICommentsEventHandler[]
813
-	 */
814
-	private function getEventHandlers() {
815
-		if(!empty($this->eventHandlers)) {
816
-			return $this->eventHandlers;
817
-		}
818
-
819
-		$this->eventHandlers = [];
820
-		foreach ($this->eventHandlerClosures as $name => $closure) {
821
-			$entity = $closure();
822
-			if (!($entity instanceof ICommentsEventHandler)) {
823
-				throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
824
-			}
825
-			$this->eventHandlers[$name] = $entity;
826
-		}
827
-
828
-		return $this->eventHandlers;
829
-	}
830
-
831
-	/**
832
-	 * sends notifications to the registered entities
833
-	 *
834
-	 * @param $eventType
835
-	 * @param IComment $comment
836
-	 */
837
-	private function sendEvent($eventType, IComment $comment) {
838
-		$entities = $this->getEventHandlers();
839
-		$event = new CommentsEvent($eventType, $comment);
840
-		foreach ($entities as $entity) {
841
-			$entity->handle($event);
842
-		}
843
-	}
40
+    /** @var  IDBConnection */
41
+    protected $dbConn;
42
+
43
+    /** @var  ILogger */
44
+    protected $logger;
45
+
46
+    /** @var IConfig */
47
+    protected $config;
48
+
49
+    /** @var IComment[]  */
50
+    protected $commentsCache = [];
51
+
52
+    /** @var  \Closure[] */
53
+    protected $eventHandlerClosures = [];
54
+
55
+    /** @var  ICommentsEventHandler[] */
56
+    protected $eventHandlers = [];
57
+
58
+    /** @var \Closure[] */
59
+    protected $displayNameResolvers = [];
60
+
61
+    /**
62
+     * Manager constructor.
63
+     *
64
+     * @param IDBConnection $dbConn
65
+     * @param ILogger $logger
66
+     * @param IConfig $config
67
+     */
68
+    public function __construct(
69
+        IDBConnection $dbConn,
70
+        ILogger $logger,
71
+        IConfig $config
72
+    ) {
73
+        $this->dbConn = $dbConn;
74
+        $this->logger = $logger;
75
+        $this->config = $config;
76
+    }
77
+
78
+    /**
79
+     * converts data base data into PHP native, proper types as defined by
80
+     * IComment interface.
81
+     *
82
+     * @param array $data
83
+     * @return array
84
+     */
85
+    protected function normalizeDatabaseData(array $data) {
86
+        $data['id'] = strval($data['id']);
87
+        $data['parent_id'] = strval($data['parent_id']);
88
+        $data['topmost_parent_id'] = strval($data['topmost_parent_id']);
89
+        $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
90
+        if (!is_null($data['latest_child_timestamp'])) {
91
+            $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
92
+        }
93
+        $data['children_count'] = intval($data['children_count']);
94
+        return $data;
95
+    }
96
+
97
+    /**
98
+     * prepares a comment for an insert or update operation after making sure
99
+     * all necessary fields have a value assigned.
100
+     *
101
+     * @param IComment $comment
102
+     * @return IComment returns the same updated IComment instance as provided
103
+     *                  by parameter for convenience
104
+     * @throws \UnexpectedValueException
105
+     */
106
+    protected function prepareCommentForDatabaseWrite(IComment $comment) {
107
+        if(    !$comment->getActorType()
108
+            || !$comment->getActorId()
109
+            || !$comment->getObjectType()
110
+            || !$comment->getObjectId()
111
+            || !$comment->getVerb()
112
+        ) {
113
+            throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
114
+        }
115
+
116
+        if($comment->getId() === '') {
117
+            $comment->setChildrenCount(0);
118
+            $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
119
+            $comment->setLatestChildDateTime(null);
120
+        }
121
+
122
+        if(is_null($comment->getCreationDateTime())) {
123
+            $comment->setCreationDateTime(new \DateTime());
124
+        }
125
+
126
+        if($comment->getParentId() !== '0') {
127
+            $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
128
+        } else {
129
+            $comment->setTopmostParentId('0');
130
+        }
131
+
132
+        $this->cache($comment);
133
+
134
+        return $comment;
135
+    }
136
+
137
+    /**
138
+     * returns the topmost parent id of a given comment identified by ID
139
+     *
140
+     * @param string $id
141
+     * @return string
142
+     * @throws NotFoundException
143
+     */
144
+    protected function determineTopmostParentId($id) {
145
+        $comment = $this->get($id);
146
+        if($comment->getParentId() === '0') {
147
+            return $comment->getId();
148
+        } else {
149
+            return $this->determineTopmostParentId($comment->getId());
150
+        }
151
+    }
152
+
153
+    /**
154
+     * updates child information of a comment
155
+     *
156
+     * @param string	$id
157
+     * @param \DateTime	$cDateTime	the date time of the most recent child
158
+     * @throws NotFoundException
159
+     */
160
+    protected function updateChildrenInformation($id, \DateTime $cDateTime) {
161
+        $qb = $this->dbConn->getQueryBuilder();
162
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
163
+                ->from('comments')
164
+                ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
165
+                ->setParameter('id', $id);
166
+
167
+        $resultStatement = $query->execute();
168
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
169
+        $resultStatement->closeCursor();
170
+        $children = intval($data[0]);
171
+
172
+        $comment = $this->get($id);
173
+        $comment->setChildrenCount($children);
174
+        $comment->setLatestChildDateTime($cDateTime);
175
+        $this->save($comment);
176
+    }
177
+
178
+    /**
179
+     * Tests whether actor or object type and id parameters are acceptable.
180
+     * Throws exception if not.
181
+     *
182
+     * @param string $role
183
+     * @param string $type
184
+     * @param string $id
185
+     * @throws \InvalidArgumentException
186
+     */
187
+    protected function checkRoleParameters($role, $type, $id) {
188
+        if(
189
+                !is_string($type) || empty($type)
190
+            || !is_string($id) || empty($id)
191
+        ) {
192
+            throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
193
+        }
194
+    }
195
+
196
+    /**
197
+     * run-time caches a comment
198
+     *
199
+     * @param IComment $comment
200
+     */
201
+    protected function cache(IComment $comment) {
202
+        $id = $comment->getId();
203
+        if(empty($id)) {
204
+            return;
205
+        }
206
+        $this->commentsCache[strval($id)] = $comment;
207
+    }
208
+
209
+    /**
210
+     * removes an entry from the comments run time cache
211
+     *
212
+     * @param mixed $id the comment's id
213
+     */
214
+    protected function uncache($id) {
215
+        $id = strval($id);
216
+        if (isset($this->commentsCache[$id])) {
217
+            unset($this->commentsCache[$id]);
218
+        }
219
+    }
220
+
221
+    /**
222
+     * returns a comment instance
223
+     *
224
+     * @param string $id the ID of the comment
225
+     * @return IComment
226
+     * @throws NotFoundException
227
+     * @throws \InvalidArgumentException
228
+     * @since 9.0.0
229
+     */
230
+    public function get($id) {
231
+        if(intval($id) === 0) {
232
+            throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
233
+        }
234
+
235
+        if(isset($this->commentsCache[$id])) {
236
+            return $this->commentsCache[$id];
237
+        }
238
+
239
+        $qb = $this->dbConn->getQueryBuilder();
240
+        $resultStatement = $qb->select('*')
241
+            ->from('comments')
242
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
243
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
244
+            ->execute();
245
+
246
+        $data = $resultStatement->fetch();
247
+        $resultStatement->closeCursor();
248
+        if(!$data) {
249
+            throw new NotFoundException();
250
+        }
251
+
252
+        $comment = new Comment($this->normalizeDatabaseData($data));
253
+        $this->cache($comment);
254
+        return $comment;
255
+    }
256
+
257
+    /**
258
+     * returns the comment specified by the id and all it's child comments.
259
+     * At this point of time, we do only support one level depth.
260
+     *
261
+     * @param string $id
262
+     * @param int $limit max number of entries to return, 0 returns all
263
+     * @param int $offset the start entry
264
+     * @return array
265
+     * @since 9.0.0
266
+     *
267
+     * The return array looks like this
268
+     * [
269
+     *   'comment' => IComment, // root comment
270
+     *   'replies' =>
271
+     *   [
272
+     *     0 =>
273
+     *     [
274
+     *       'comment' => IComment,
275
+     *       'replies' => []
276
+     *     ]
277
+     *     1 =>
278
+     *     [
279
+     *       'comment' => IComment,
280
+     *       'replies'=> []
281
+     *     ],
282
+     *     …
283
+     *   ]
284
+     * ]
285
+     */
286
+    public function getTree($id, $limit = 0, $offset = 0) {
287
+        $tree = [];
288
+        $tree['comment'] = $this->get($id);
289
+        $tree['replies'] = [];
290
+
291
+        $qb = $this->dbConn->getQueryBuilder();
292
+        $query = $qb->select('*')
293
+                ->from('comments')
294
+                ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
295
+                ->orderBy('creation_timestamp', 'DESC')
296
+                ->setParameter('id', $id);
297
+
298
+        if($limit > 0) {
299
+            $query->setMaxResults($limit);
300
+        }
301
+        if($offset > 0) {
302
+            $query->setFirstResult($offset);
303
+        }
304
+
305
+        $resultStatement = $query->execute();
306
+        while($data = $resultStatement->fetch()) {
307
+            $comment = new Comment($this->normalizeDatabaseData($data));
308
+            $this->cache($comment);
309
+            $tree['replies'][] = [
310
+                'comment' => $comment,
311
+                'replies' => []
312
+            ];
313
+        }
314
+        $resultStatement->closeCursor();
315
+
316
+        return $tree;
317
+    }
318
+
319
+    /**
320
+     * returns comments for a specific object (e.g. a file).
321
+     *
322
+     * The sort order is always newest to oldest.
323
+     *
324
+     * @param string $objectType the object type, e.g. 'files'
325
+     * @param string $objectId the id of the object
326
+     * @param int $limit optional, number of maximum comments to be returned. if
327
+     * not specified, all comments are returned.
328
+     * @param int $offset optional, starting point
329
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
330
+     * that may be returned
331
+     * @return IComment[]
332
+     * @since 9.0.0
333
+     */
334
+    public function getForObject(
335
+            $objectType,
336
+            $objectId,
337
+            $limit = 0,
338
+            $offset = 0,
339
+            \DateTime $notOlderThan = null
340
+    ) {
341
+        $comments = [];
342
+
343
+        $qb = $this->dbConn->getQueryBuilder();
344
+        $query = $qb->select('*')
345
+                ->from('comments')
346
+                ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
347
+                ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
348
+                ->orderBy('creation_timestamp', 'DESC')
349
+                ->setParameter('type', $objectType)
350
+                ->setParameter('id', $objectId);
351
+
352
+        if($limit > 0) {
353
+            $query->setMaxResults($limit);
354
+        }
355
+        if($offset > 0) {
356
+            $query->setFirstResult($offset);
357
+        }
358
+        if(!is_null($notOlderThan)) {
359
+            $query
360
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
361
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
362
+        }
363
+
364
+        $resultStatement = $query->execute();
365
+        while($data = $resultStatement->fetch()) {
366
+            $comment = new Comment($this->normalizeDatabaseData($data));
367
+            $this->cache($comment);
368
+            $comments[] = $comment;
369
+        }
370
+        $resultStatement->closeCursor();
371
+
372
+        return $comments;
373
+    }
374
+
375
+    /**
376
+     * @param $objectType string the object type, e.g. 'files'
377
+     * @param $objectId string the id of the object
378
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
379
+     * that may be returned
380
+     * @return Int
381
+     * @since 9.0.0
382
+     */
383
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
384
+        $qb = $this->dbConn->getQueryBuilder();
385
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
386
+                ->from('comments')
387
+                ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
388
+                ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
389
+                ->setParameter('type', $objectType)
390
+                ->setParameter('id', $objectId);
391
+
392
+        if(!is_null($notOlderThan)) {
393
+            $query
394
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
395
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
396
+        }
397
+
398
+        $resultStatement = $query->execute();
399
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
400
+        $resultStatement->closeCursor();
401
+        return intval($data[0]);
402
+    }
403
+
404
+    /**
405
+     * creates a new comment and returns it. At this point of time, it is not
406
+     * saved in the used data storage. Use save() after setting other fields
407
+     * of the comment (e.g. message or verb).
408
+     *
409
+     * @param string $actorType the actor type (e.g. 'users')
410
+     * @param string $actorId a user id
411
+     * @param string $objectType the object type the comment is attached to
412
+     * @param string $objectId the object id the comment is attached to
413
+     * @return IComment
414
+     * @since 9.0.0
415
+     */
416
+    public function create($actorType, $actorId, $objectType, $objectId) {
417
+        $comment = new Comment();
418
+        $comment
419
+            ->setActor($actorType, $actorId)
420
+            ->setObject($objectType, $objectId);
421
+        return $comment;
422
+    }
423
+
424
+    /**
425
+     * permanently deletes the comment specified by the ID
426
+     *
427
+     * When the comment has child comments, their parent ID will be changed to
428
+     * the parent ID of the item that is to be deleted.
429
+     *
430
+     * @param string $id
431
+     * @return bool
432
+     * @throws \InvalidArgumentException
433
+     * @since 9.0.0
434
+     */
435
+    public function delete($id) {
436
+        if(!is_string($id)) {
437
+            throw new \InvalidArgumentException('Parameter must be string');
438
+        }
439
+
440
+        try {
441
+            $comment = $this->get($id);
442
+        } catch (\Exception $e) {
443
+            // Ignore exceptions, we just don't fire a hook then
444
+            $comment = null;
445
+        }
446
+
447
+        $qb = $this->dbConn->getQueryBuilder();
448
+        $query = $qb->delete('comments')
449
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
450
+            ->setParameter('id', $id);
451
+
452
+        try {
453
+            $affectedRows = $query->execute();
454
+            $this->uncache($id);
455
+        } catch (DriverException $e) {
456
+            $this->logger->logException($e, ['app' => 'core_comments']);
457
+            return false;
458
+        }
459
+
460
+        if ($affectedRows > 0 && $comment instanceof IComment) {
461
+            $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
462
+        }
463
+
464
+        return ($affectedRows > 0);
465
+    }
466
+
467
+    /**
468
+     * saves the comment permanently
469
+     *
470
+     * if the supplied comment has an empty ID, a new entry comment will be
471
+     * saved and the instance updated with the new ID.
472
+     *
473
+     * Otherwise, an existing comment will be updated.
474
+     *
475
+     * Throws NotFoundException when a comment that is to be updated does not
476
+     * exist anymore at this point of time.
477
+     *
478
+     * @param IComment $comment
479
+     * @return bool
480
+     * @throws NotFoundException
481
+     * @since 9.0.0
482
+     */
483
+    public function save(IComment $comment) {
484
+        if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
485
+            $result = $this->insert($comment);
486
+        } else {
487
+            $result = $this->update($comment);
488
+        }
489
+
490
+        if($result && !!$comment->getParentId()) {
491
+            $this->updateChildrenInformation(
492
+                    $comment->getParentId(),
493
+                    $comment->getCreationDateTime()
494
+            );
495
+            $this->cache($comment);
496
+        }
497
+
498
+        return $result;
499
+    }
500
+
501
+    /**
502
+     * inserts the provided comment in the database
503
+     *
504
+     * @param IComment $comment
505
+     * @return bool
506
+     */
507
+    protected function insert(IComment &$comment) {
508
+        $qb = $this->dbConn->getQueryBuilder();
509
+        $affectedRows = $qb
510
+            ->insert('comments')
511
+            ->values([
512
+                'parent_id'					=> $qb->createNamedParameter($comment->getParentId()),
513
+                'topmost_parent_id' 		=> $qb->createNamedParameter($comment->getTopmostParentId()),
514
+                'children_count' 			=> $qb->createNamedParameter($comment->getChildrenCount()),
515
+                'actor_type' 				=> $qb->createNamedParameter($comment->getActorType()),
516
+                'actor_id' 					=> $qb->createNamedParameter($comment->getActorId()),
517
+                'message' 					=> $qb->createNamedParameter($comment->getMessage()),
518
+                'verb' 						=> $qb->createNamedParameter($comment->getVerb()),
519
+                'creation_timestamp' 		=> $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
520
+                'latest_child_timestamp'	=> $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
521
+                'object_type' 				=> $qb->createNamedParameter($comment->getObjectType()),
522
+                'object_id' 				=> $qb->createNamedParameter($comment->getObjectId()),
523
+            ])
524
+            ->execute();
525
+
526
+        if ($affectedRows > 0) {
527
+            $comment->setId(strval($qb->getLastInsertId()));
528
+            $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
529
+        }
530
+
531
+        return $affectedRows > 0;
532
+    }
533
+
534
+    /**
535
+     * updates a Comment data row
536
+     *
537
+     * @param IComment $comment
538
+     * @return bool
539
+     * @throws NotFoundException
540
+     */
541
+    protected function update(IComment $comment) {
542
+        // for properly working preUpdate Events we need the old comments as is
543
+        // in the DB and overcome caching. Also avoid that outdated information stays.
544
+        $this->uncache($comment->getId());
545
+        $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
546
+        $this->uncache($comment->getId());
547
+
548
+        $qb = $this->dbConn->getQueryBuilder();
549
+        $affectedRows = $qb
550
+            ->update('comments')
551
+                ->set('parent_id',				$qb->createNamedParameter($comment->getParentId()))
552
+                ->set('topmost_parent_id', 		$qb->createNamedParameter($comment->getTopmostParentId()))
553
+                ->set('children_count',			$qb->createNamedParameter($comment->getChildrenCount()))
554
+                ->set('actor_type', 			$qb->createNamedParameter($comment->getActorType()))
555
+                ->set('actor_id', 				$qb->createNamedParameter($comment->getActorId()))
556
+                ->set('message',				$qb->createNamedParameter($comment->getMessage()))
557
+                ->set('verb',					$qb->createNamedParameter($comment->getVerb()))
558
+                ->set('creation_timestamp',		$qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
559
+                ->set('latest_child_timestamp',	$qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
560
+                ->set('object_type',			$qb->createNamedParameter($comment->getObjectType()))
561
+                ->set('object_id',				$qb->createNamedParameter($comment->getObjectId()))
562
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
563
+            ->setParameter('id', $comment->getId())
564
+            ->execute();
565
+
566
+        if($affectedRows === 0) {
567
+            throw new NotFoundException('Comment to update does ceased to exist');
568
+        }
569
+
570
+        $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
571
+
572
+        return $affectedRows > 0;
573
+    }
574
+
575
+    /**
576
+     * removes references to specific actor (e.g. on user delete) of a comment.
577
+     * The comment itself must not get lost/deleted.
578
+     *
579
+     * @param string $actorType the actor type (e.g. 'users')
580
+     * @param string $actorId a user id
581
+     * @return boolean
582
+     * @since 9.0.0
583
+     */
584
+    public function deleteReferencesOfActor($actorType, $actorId) {
585
+        $this->checkRoleParameters('Actor', $actorType, $actorId);
586
+
587
+        $qb = $this->dbConn->getQueryBuilder();
588
+        $affectedRows = $qb
589
+            ->update('comments')
590
+            ->set('actor_type',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
591
+            ->set('actor_id',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
592
+            ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
593
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
594
+            ->setParameter('type', $actorType)
595
+            ->setParameter('id', $actorId)
596
+            ->execute();
597
+
598
+        $this->commentsCache = [];
599
+
600
+        return is_int($affectedRows);
601
+    }
602
+
603
+    /**
604
+     * deletes all comments made of a specific object (e.g. on file delete)
605
+     *
606
+     * @param string $objectType the object type (e.g. 'files')
607
+     * @param string $objectId e.g. the file id
608
+     * @return boolean
609
+     * @since 9.0.0
610
+     */
611
+    public function deleteCommentsAtObject($objectType, $objectId) {
612
+        $this->checkRoleParameters('Object', $objectType, $objectId);
613
+
614
+        $qb = $this->dbConn->getQueryBuilder();
615
+        $affectedRows = $qb
616
+            ->delete('comments')
617
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
618
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
619
+            ->setParameter('type', $objectType)
620
+            ->setParameter('id', $objectId)
621
+            ->execute();
622
+
623
+        $this->commentsCache = [];
624
+
625
+        return is_int($affectedRows);
626
+    }
627
+
628
+    /**
629
+     * deletes the read markers for the specified user
630
+     *
631
+     * @param \OCP\IUser $user
632
+     * @return bool
633
+     * @since 9.0.0
634
+     */
635
+    public function deleteReadMarksFromUser(IUser $user) {
636
+        $qb = $this->dbConn->getQueryBuilder();
637
+        $query = $qb->delete('comments_read_markers')
638
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
639
+            ->setParameter('user_id', $user->getUID());
640
+
641
+        try {
642
+            $affectedRows = $query->execute();
643
+        } catch (DriverException $e) {
644
+            $this->logger->logException($e, ['app' => 'core_comments']);
645
+            return false;
646
+        }
647
+        return ($affectedRows > 0);
648
+    }
649
+
650
+    /**
651
+     * sets the read marker for a given file to the specified date for the
652
+     * provided user
653
+     *
654
+     * @param string $objectType
655
+     * @param string $objectId
656
+     * @param \DateTime $dateTime
657
+     * @param IUser $user
658
+     * @since 9.0.0
659
+     */
660
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
661
+        $this->checkRoleParameters('Object', $objectType, $objectId);
662
+
663
+        $qb = $this->dbConn->getQueryBuilder();
664
+        $values = [
665
+            'user_id'         => $qb->createNamedParameter($user->getUID()),
666
+            'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
667
+            'object_type'     => $qb->createNamedParameter($objectType),
668
+            'object_id'       => $qb->createNamedParameter($objectId),
669
+        ];
670
+
671
+        // Strategy: try to update, if this does not return affected rows, do an insert.
672
+        $affectedRows = $qb
673
+            ->update('comments_read_markers')
674
+            ->set('user_id',         $values['user_id'])
675
+            ->set('marker_datetime', $values['marker_datetime'])
676
+            ->set('object_type',     $values['object_type'])
677
+            ->set('object_id',       $values['object_id'])
678
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
679
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
680
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
681
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
682
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
683
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
684
+            ->execute();
685
+
686
+        if ($affectedRows > 0) {
687
+            return;
688
+        }
689
+
690
+        $qb->insert('comments_read_markers')
691
+            ->values($values)
692
+            ->execute();
693
+    }
694
+
695
+    /**
696
+     * returns the read marker for a given file to the specified date for the
697
+     * provided user. It returns null, when the marker is not present, i.e.
698
+     * no comments were marked as read.
699
+     *
700
+     * @param string $objectType
701
+     * @param string $objectId
702
+     * @param IUser $user
703
+     * @return \DateTime|null
704
+     * @since 9.0.0
705
+     */
706
+    public function getReadMark($objectType, $objectId, IUser $user) {
707
+        $qb = $this->dbConn->getQueryBuilder();
708
+        $resultStatement = $qb->select('marker_datetime')
709
+            ->from('comments_read_markers')
710
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
711
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
712
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
713
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
714
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
715
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
716
+            ->execute();
717
+
718
+        $data = $resultStatement->fetch();
719
+        $resultStatement->closeCursor();
720
+        if(!$data || is_null($data['marker_datetime'])) {
721
+            return null;
722
+        }
723
+
724
+        return new \DateTime($data['marker_datetime']);
725
+    }
726
+
727
+    /**
728
+     * deletes the read markers on the specified object
729
+     *
730
+     * @param string $objectType
731
+     * @param string $objectId
732
+     * @return bool
733
+     * @since 9.0.0
734
+     */
735
+    public function deleteReadMarksOnObject($objectType, $objectId) {
736
+        $this->checkRoleParameters('Object', $objectType, $objectId);
737
+
738
+        $qb = $this->dbConn->getQueryBuilder();
739
+        $query = $qb->delete('comments_read_markers')
740
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
741
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
742
+            ->setParameter('object_type', $objectType)
743
+            ->setParameter('object_id', $objectId);
744
+
745
+        try {
746
+            $affectedRows = $query->execute();
747
+        } catch (DriverException $e) {
748
+            $this->logger->logException($e, ['app' => 'core_comments']);
749
+            return false;
750
+        }
751
+        return ($affectedRows > 0);
752
+    }
753
+
754
+    /**
755
+     * registers an Entity to the manager, so event notifications can be send
756
+     * to consumers of the comments infrastructure
757
+     *
758
+     * @param \Closure $closure
759
+     */
760
+    public function registerEventHandler(\Closure $closure) {
761
+        $this->eventHandlerClosures[] = $closure;
762
+        $this->eventHandlers = [];
763
+    }
764
+
765
+    /**
766
+     * registers a method that resolves an ID to a display name for a given type
767
+     *
768
+     * @param string $type
769
+     * @param \Closure $closure
770
+     * @throws \OutOfBoundsException
771
+     * @since 11.0.0
772
+     *
773
+     * Only one resolver shall be registered per type. Otherwise a
774
+     * \OutOfBoundsException has to thrown.
775
+     */
776
+    public function registerDisplayNameResolver($type, \Closure $closure) {
777
+        if(!is_string($type)) {
778
+            throw new \InvalidArgumentException('String expected.');
779
+        }
780
+        if(isset($this->displayNameResolvers[$type])) {
781
+            throw new \OutOfBoundsException('Displayname resolver for this type already registered');
782
+        }
783
+        $this->displayNameResolvers[$type] = $closure;
784
+    }
785
+
786
+    /**
787
+     * resolves a given ID of a given Type to a display name.
788
+     *
789
+     * @param string $type
790
+     * @param string $id
791
+     * @return string
792
+     * @throws \OutOfBoundsException
793
+     * @since 11.0.0
794
+     *
795
+     * If a provided type was not registered, an \OutOfBoundsException shall
796
+     * be thrown. It is upon the resolver discretion what to return of the
797
+     * provided ID is unknown. It must be ensured that a string is returned.
798
+     */
799
+    public function resolveDisplayName($type, $id) {
800
+        if(!is_string($type)) {
801
+            throw new \InvalidArgumentException('String expected.');
802
+        }
803
+        if(!isset($this->displayNameResolvers[$type])) {
804
+            throw new \OutOfBoundsException('No Displayname resolver for this type registered');
805
+        }
806
+        return (string)$this->displayNameResolvers[$type]($id);
807
+    }
808
+
809
+    /**
810
+     * returns valid, registered entities
811
+     *
812
+     * @return \OCP\Comments\ICommentsEventHandler[]
813
+     */
814
+    private function getEventHandlers() {
815
+        if(!empty($this->eventHandlers)) {
816
+            return $this->eventHandlers;
817
+        }
818
+
819
+        $this->eventHandlers = [];
820
+        foreach ($this->eventHandlerClosures as $name => $closure) {
821
+            $entity = $closure();
822
+            if (!($entity instanceof ICommentsEventHandler)) {
823
+                throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
824
+            }
825
+            $this->eventHandlers[$name] = $entity;
826
+        }
827
+
828
+        return $this->eventHandlers;
829
+    }
830
+
831
+    /**
832
+     * sends notifications to the registered entities
833
+     *
834
+     * @param $eventType
835
+     * @param IComment $comment
836
+     */
837
+    private function sendEvent($eventType, IComment $comment) {
838
+        $entities = $this->getEventHandlers();
839
+        $event = new CommentsEvent($eventType, $comment);
840
+        foreach ($entities as $entity) {
841
+            $entity->handle($event);
842
+        }
843
+    }
844 844
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 	 * @throws \UnexpectedValueException
105 105
 	 */
106 106
 	protected function prepareCommentForDatabaseWrite(IComment $comment) {
107
-		if(    !$comment->getActorType()
107
+		if (!$comment->getActorType()
108 108
 			|| !$comment->getActorId()
109 109
 			|| !$comment->getObjectType()
110 110
 			|| !$comment->getObjectId()
@@ -113,17 +113,17 @@  discard block
 block discarded – undo
113 113
 			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
114 114
 		}
115 115
 
116
-		if($comment->getId() === '') {
116
+		if ($comment->getId() === '') {
117 117
 			$comment->setChildrenCount(0);
118 118
 			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
119 119
 			$comment->setLatestChildDateTime(null);
120 120
 		}
121 121
 
122
-		if(is_null($comment->getCreationDateTime())) {
122
+		if (is_null($comment->getCreationDateTime())) {
123 123
 			$comment->setCreationDateTime(new \DateTime());
124 124
 		}
125 125
 
126
-		if($comment->getParentId() !== '0') {
126
+		if ($comment->getParentId() !== '0') {
127 127
 			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
128 128
 		} else {
129 129
 			$comment->setTopmostParentId('0');
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	 */
144 144
 	protected function determineTopmostParentId($id) {
145 145
 		$comment = $this->get($id);
146
-		if($comment->getParentId() === '0') {
146
+		if ($comment->getParentId() === '0') {
147 147
 			return $comment->getId();
148 148
 		} else {
149 149
 			return $this->determineTopmostParentId($comment->getId());
@@ -185,11 +185,11 @@  discard block
 block discarded – undo
185 185
 	 * @throws \InvalidArgumentException
186 186
 	 */
187 187
 	protected function checkRoleParameters($role, $type, $id) {
188
-		if(
188
+		if (
189 189
 			   !is_string($type) || empty($type)
190 190
 			|| !is_string($id) || empty($id)
191 191
 		) {
192
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
192
+			throw new \InvalidArgumentException($role.' parameters must be string and not empty');
193 193
 		}
194 194
 	}
195 195
 
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 */
201 201
 	protected function cache(IComment $comment) {
202 202
 		$id = $comment->getId();
203
-		if(empty($id)) {
203
+		if (empty($id)) {
204 204
 			return;
205 205
 		}
206 206
 		$this->commentsCache[strval($id)] = $comment;
@@ -228,11 +228,11 @@  discard block
 block discarded – undo
228 228
 	 * @since 9.0.0
229 229
 	 */
230 230
 	public function get($id) {
231
-		if(intval($id) === 0) {
231
+		if (intval($id) === 0) {
232 232
 			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
233 233
 		}
234 234
 
235
-		if(isset($this->commentsCache[$id])) {
235
+		if (isset($this->commentsCache[$id])) {
236 236
 			return $this->commentsCache[$id];
237 237
 		}
238 238
 
@@ -245,7 +245,7 @@  discard block
 block discarded – undo
245 245
 
246 246
 		$data = $resultStatement->fetch();
247 247
 		$resultStatement->closeCursor();
248
-		if(!$data) {
248
+		if (!$data) {
249 249
 			throw new NotFoundException();
250 250
 		}
251 251
 
@@ -295,15 +295,15 @@  discard block
 block discarded – undo
295 295
 				->orderBy('creation_timestamp', 'DESC')
296 296
 				->setParameter('id', $id);
297 297
 
298
-		if($limit > 0) {
298
+		if ($limit > 0) {
299 299
 			$query->setMaxResults($limit);
300 300
 		}
301
-		if($offset > 0) {
301
+		if ($offset > 0) {
302 302
 			$query->setFirstResult($offset);
303 303
 		}
304 304
 
305 305
 		$resultStatement = $query->execute();
306
-		while($data = $resultStatement->fetch()) {
306
+		while ($data = $resultStatement->fetch()) {
307 307
 			$comment = new Comment($this->normalizeDatabaseData($data));
308 308
 			$this->cache($comment);
309 309
 			$tree['replies'][] = [
@@ -349,20 +349,20 @@  discard block
 block discarded – undo
349 349
 				->setParameter('type', $objectType)
350 350
 				->setParameter('id', $objectId);
351 351
 
352
-		if($limit > 0) {
352
+		if ($limit > 0) {
353 353
 			$query->setMaxResults($limit);
354 354
 		}
355
-		if($offset > 0) {
355
+		if ($offset > 0) {
356 356
 			$query->setFirstResult($offset);
357 357
 		}
358
-		if(!is_null($notOlderThan)) {
358
+		if (!is_null($notOlderThan)) {
359 359
 			$query
360 360
 				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
361 361
 				->setParameter('notOlderThan', $notOlderThan, 'datetime');
362 362
 		}
363 363
 
364 364
 		$resultStatement = $query->execute();
365
-		while($data = $resultStatement->fetch()) {
365
+		while ($data = $resultStatement->fetch()) {
366 366
 			$comment = new Comment($this->normalizeDatabaseData($data));
367 367
 			$this->cache($comment);
368 368
 			$comments[] = $comment;
@@ -389,7 +389,7 @@  discard block
 block discarded – undo
389 389
 				->setParameter('type', $objectType)
390 390
 				->setParameter('id', $objectId);
391 391
 
392
-		if(!is_null($notOlderThan)) {
392
+		if (!is_null($notOlderThan)) {
393 393
 			$query
394 394
 				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
395 395
 				->setParameter('notOlderThan', $notOlderThan, 'datetime');
@@ -433,7 +433,7 @@  discard block
 block discarded – undo
433 433
 	 * @since 9.0.0
434 434
 	 */
435 435
 	public function delete($id) {
436
-		if(!is_string($id)) {
436
+		if (!is_string($id)) {
437 437
 			throw new \InvalidArgumentException('Parameter must be string');
438 438
 		}
439 439
 
@@ -481,13 +481,13 @@  discard block
 block discarded – undo
481 481
 	 * @since 9.0.0
482 482
 	 */
483 483
 	public function save(IComment $comment) {
484
-		if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
484
+		if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
485 485
 			$result = $this->insert($comment);
486 486
 		} else {
487 487
 			$result = $this->update($comment);
488 488
 		}
489 489
 
490
-		if($result && !!$comment->getParentId()) {
490
+		if ($result && !!$comment->getParentId()) {
491 491
 			$this->updateChildrenInformation(
492 492
 					$comment->getParentId(),
493 493
 					$comment->getCreationDateTime()
@@ -504,7 +504,7 @@  discard block
 block discarded – undo
504 504
 	 * @param IComment $comment
505 505
 	 * @return bool
506 506
 	 */
507
-	protected function insert(IComment &$comment) {
507
+	protected function insert(IComment & $comment) {
508 508
 		$qb = $this->dbConn->getQueryBuilder();
509 509
 		$affectedRows = $qb
510 510
 			->insert('comments')
@@ -548,22 +548,22 @@  discard block
 block discarded – undo
548 548
 		$qb = $this->dbConn->getQueryBuilder();
549 549
 		$affectedRows = $qb
550 550
 			->update('comments')
551
-				->set('parent_id',				$qb->createNamedParameter($comment->getParentId()))
552
-				->set('topmost_parent_id', 		$qb->createNamedParameter($comment->getTopmostParentId()))
553
-				->set('children_count',			$qb->createNamedParameter($comment->getChildrenCount()))
554
-				->set('actor_type', 			$qb->createNamedParameter($comment->getActorType()))
555
-				->set('actor_id', 				$qb->createNamedParameter($comment->getActorId()))
556
-				->set('message',				$qb->createNamedParameter($comment->getMessage()))
557
-				->set('verb',					$qb->createNamedParameter($comment->getVerb()))
558
-				->set('creation_timestamp',		$qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
559
-				->set('latest_child_timestamp',	$qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
560
-				->set('object_type',			$qb->createNamedParameter($comment->getObjectType()))
561
-				->set('object_id',				$qb->createNamedParameter($comment->getObjectId()))
551
+				->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
552
+				->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
553
+				->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
554
+				->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
555
+				->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
556
+				->set('message', $qb->createNamedParameter($comment->getMessage()))
557
+				->set('verb', $qb->createNamedParameter($comment->getVerb()))
558
+				->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
559
+				->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
560
+				->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
561
+				->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
562 562
 			->where($qb->expr()->eq('id', $qb->createParameter('id')))
563 563
 			->setParameter('id', $comment->getId())
564 564
 			->execute();
565 565
 
566
-		if($affectedRows === 0) {
566
+		if ($affectedRows === 0) {
567 567
 			throw new NotFoundException('Comment to update does ceased to exist');
568 568
 		}
569 569
 
@@ -587,8 +587,8 @@  discard block
 block discarded – undo
587 587
 		$qb = $this->dbConn->getQueryBuilder();
588 588
 		$affectedRows = $qb
589 589
 			->update('comments')
590
-			->set('actor_type',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
591
-			->set('actor_id',	$qb->createNamedParameter(ICommentsManager::DELETED_USER))
590
+			->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
591
+			->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
592 592
 			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
593 593
 			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
594 594
 			->setParameter('type', $actorType)
@@ -671,10 +671,10 @@  discard block
 block discarded – undo
671 671
 		// Strategy: try to update, if this does not return affected rows, do an insert.
672 672
 		$affectedRows = $qb
673 673
 			->update('comments_read_markers')
674
-			->set('user_id',         $values['user_id'])
674
+			->set('user_id', $values['user_id'])
675 675
 			->set('marker_datetime', $values['marker_datetime'])
676
-			->set('object_type',     $values['object_type'])
677
-			->set('object_id',       $values['object_id'])
676
+			->set('object_type', $values['object_type'])
677
+			->set('object_id', $values['object_id'])
678 678
 			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
679 679
 			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
680 680
 			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
@@ -717,7 +717,7 @@  discard block
 block discarded – undo
717 717
 
718 718
 		$data = $resultStatement->fetch();
719 719
 		$resultStatement->closeCursor();
720
-		if(!$data || is_null($data['marker_datetime'])) {
720
+		if (!$data || is_null($data['marker_datetime'])) {
721 721
 			return null;
722 722
 		}
723 723
 
@@ -774,10 +774,10 @@  discard block
 block discarded – undo
774 774
 	 * \OutOfBoundsException has to thrown.
775 775
 	 */
776 776
 	public function registerDisplayNameResolver($type, \Closure $closure) {
777
-		if(!is_string($type)) {
777
+		if (!is_string($type)) {
778 778
 			throw new \InvalidArgumentException('String expected.');
779 779
 		}
780
-		if(isset($this->displayNameResolvers[$type])) {
780
+		if (isset($this->displayNameResolvers[$type])) {
781 781
 			throw new \OutOfBoundsException('Displayname resolver for this type already registered');
782 782
 		}
783 783
 		$this->displayNameResolvers[$type] = $closure;
@@ -797,13 +797,13 @@  discard block
 block discarded – undo
797 797
 	 * provided ID is unknown. It must be ensured that a string is returned.
798 798
 	 */
799 799
 	public function resolveDisplayName($type, $id) {
800
-		if(!is_string($type)) {
800
+		if (!is_string($type)) {
801 801
 			throw new \InvalidArgumentException('String expected.');
802 802
 		}
803
-		if(!isset($this->displayNameResolvers[$type])) {
803
+		if (!isset($this->displayNameResolvers[$type])) {
804 804
 			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
805 805
 		}
806
-		return (string)$this->displayNameResolvers[$type]($id);
806
+		return (string) $this->displayNameResolvers[$type]($id);
807 807
 	}
808 808
 
809 809
 	/**
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
 	 * @return \OCP\Comments\ICommentsEventHandler[]
813 813
 	 */
814 814
 	private function getEventHandlers() {
815
-		if(!empty($this->eventHandlers)) {
815
+		if (!empty($this->eventHandlers)) {
816 816
 			return $this->eventHandlers;
817 817
 		}
818 818
 
Please login to merge, or discard this patch.
lib/private/DB/Connection.php 3 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
 	 * If an SQLLogger is configured, the execution is logged.
174 174
 	 *
175 175
 	 * @param string                                      $query  The SQL query to execute.
176
-	 * @param array                                       $params The parameters to bind to the query, if any.
176
+	 * @param string[]                                       $params The parameters to bind to the query, if any.
177 177
 	 * @param array                                       $types  The types the previous parameters are in.
178 178
 	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
179 179
 	 *
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
 	 * columns or sequences.
219 219
 	 *
220 220
 	 * @param string $seqName Name of the sequence object from which the ID should be returned.
221
-	 * @return string A string representation of the last inserted ID.
221
+	 * @return integer A string representation of the last inserted ID.
222 222
 	 */
223 223
 	public function lastInsertId($seqName = null) {
224 224
 		if ($seqName) {
Please login to merge, or discard this patch.
Indentation   +377 added lines, -377 removed lines patch added patch discarded remove patch
@@ -40,381 +40,381 @@
 block discarded – undo
40 40
 use OCP\PreConditionNotMetException;
41 41
 
42 42
 class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
43
-	/**
44
-	 * @var string $tablePrefix
45
-	 */
46
-	protected $tablePrefix;
47
-
48
-	/**
49
-	 * @var \OC\DB\Adapter $adapter
50
-	 */
51
-	protected $adapter;
52
-
53
-	protected $lockedTable = null;
54
-
55
-	public function connect() {
56
-		try {
57
-			return parent::connect();
58
-		} catch (DBALException $e) {
59
-			// throw a new exception to prevent leaking info from the stacktrace
60
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
61
-		}
62
-	}
63
-
64
-	/**
65
-	 * Returns a QueryBuilder for the connection.
66
-	 *
67
-	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
68
-	 */
69
-	public function getQueryBuilder() {
70
-		return new QueryBuilder(
71
-			$this,
72
-			\OC::$server->getSystemConfig(),
73
-			\OC::$server->getLogger()
74
-		);
75
-	}
76
-
77
-	/**
78
-	 * Gets the QueryBuilder for the connection.
79
-	 *
80
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
81
-	 * @deprecated please use $this->getQueryBuilder() instead
82
-	 */
83
-	public function createQueryBuilder() {
84
-		$backtrace = $this->getCallerBacktrace();
85
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
86
-		return parent::createQueryBuilder();
87
-	}
88
-
89
-	/**
90
-	 * Gets the ExpressionBuilder for the connection.
91
-	 *
92
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
93
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
94
-	 */
95
-	public function getExpressionBuilder() {
96
-		$backtrace = $this->getCallerBacktrace();
97
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
98
-		return parent::getExpressionBuilder();
99
-	}
100
-
101
-	/**
102
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
103
-	 *
104
-	 * @return string
105
-	 */
106
-	protected function getCallerBacktrace() {
107
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
108
-
109
-		// 0 is the method where we use `getCallerBacktrace`
110
-		// 1 is the target method which uses the method we want to log
111
-		if (isset($traces[1])) {
112
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
113
-		}
114
-
115
-		return '';
116
-	}
117
-
118
-	/**
119
-	 * @return string
120
-	 */
121
-	public function getPrefix() {
122
-		return $this->tablePrefix;
123
-	}
124
-
125
-	/**
126
-	 * Initializes a new instance of the Connection class.
127
-	 *
128
-	 * @param array $params  The connection parameters.
129
-	 * @param \Doctrine\DBAL\Driver $driver
130
-	 * @param \Doctrine\DBAL\Configuration $config
131
-	 * @param \Doctrine\Common\EventManager $eventManager
132
-	 * @throws \Exception
133
-	 */
134
-	public function __construct(array $params, Driver $driver, Configuration $config = null,
135
-		EventManager $eventManager = null)
136
-	{
137
-		if (!isset($params['adapter'])) {
138
-			throw new \Exception('adapter not set');
139
-		}
140
-		if (!isset($params['tablePrefix'])) {
141
-			throw new \Exception('tablePrefix not set');
142
-		}
143
-		parent::__construct($params, $driver, $config, $eventManager);
144
-		$this->adapter = new $params['adapter']($this);
145
-		$this->tablePrefix = $params['tablePrefix'];
146
-
147
-		parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
148
-	}
149
-
150
-	/**
151
-	 * Prepares an SQL statement.
152
-	 *
153
-	 * @param string $statement The SQL statement to prepare.
154
-	 * @param int $limit
155
-	 * @param int $offset
156
-	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
157
-	 */
158
-	public function prepare( $statement, $limit=null, $offset=null ) {
159
-		if ($limit === -1) {
160
-			$limit = null;
161
-		}
162
-		if (!is_null($limit)) {
163
-			$platform = $this->getDatabasePlatform();
164
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
165
-		}
166
-		$statement = $this->replaceTablePrefix($statement);
167
-		$statement = $this->adapter->fixupStatement($statement);
168
-
169
-		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
170
-			\OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
171
-		}
172
-		return parent::prepare($statement);
173
-	}
174
-
175
-	/**
176
-	 * Executes an, optionally parametrized, SQL query.
177
-	 *
178
-	 * If the query is parametrized, a prepared statement is used.
179
-	 * If an SQLLogger is configured, the execution is logged.
180
-	 *
181
-	 * @param string                                      $query  The SQL query to execute.
182
-	 * @param array                                       $params The parameters to bind to the query, if any.
183
-	 * @param array                                       $types  The types the previous parameters are in.
184
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
185
-	 *
186
-	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
187
-	 *
188
-	 * @throws \Doctrine\DBAL\DBALException
189
-	 */
190
-	public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
191
-	{
192
-		$query = $this->replaceTablePrefix($query);
193
-		$query = $this->adapter->fixupStatement($query);
194
-		return parent::executeQuery($query, $params, $types, $qcp);
195
-	}
196
-
197
-	/**
198
-	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
199
-	 * and returns the number of affected rows.
200
-	 *
201
-	 * This method supports PDO binding types as well as DBAL mapping types.
202
-	 *
203
-	 * @param string $query  The SQL query.
204
-	 * @param array  $params The query parameters.
205
-	 * @param array  $types  The parameter types.
206
-	 *
207
-	 * @return integer The number of affected rows.
208
-	 *
209
-	 * @throws \Doctrine\DBAL\DBALException
210
-	 */
211
-	public function executeUpdate($query, array $params = array(), array $types = array())
212
-	{
213
-		$query = $this->replaceTablePrefix($query);
214
-		$query = $this->adapter->fixupStatement($query);
215
-		return parent::executeUpdate($query, $params, $types);
216
-	}
217
-
218
-	/**
219
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
220
-	 * depending on the underlying driver.
221
-	 *
222
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
223
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
224
-	 * columns or sequences.
225
-	 *
226
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
227
-	 * @return string A string representation of the last inserted ID.
228
-	 */
229
-	public function lastInsertId($seqName = null) {
230
-		if ($seqName) {
231
-			$seqName = $this->replaceTablePrefix($seqName);
232
-		}
233
-		return $this->adapter->lastInsertId($seqName);
234
-	}
235
-
236
-	// internal use
237
-	public function realLastInsertId($seqName = null) {
238
-		return parent::lastInsertId($seqName);
239
-	}
240
-
241
-	/**
242
-	 * Insert a row if the matching row does not exists.
243
-	 *
244
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
245
-	 * @param array $input data that should be inserted into the table  (column name => value)
246
-	 * @param array|null $compare List of values that should be checked for "if not exists"
247
-	 *				If this is null or an empty array, all keys of $input will be compared
248
-	 *				Please note: text fields (clob) must not be used in the compare array
249
-	 * @return int number of inserted rows
250
-	 * @throws \Doctrine\DBAL\DBALException
251
-	 */
252
-	public function insertIfNotExist($table, $input, array $compare = null) {
253
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
254
-	}
255
-
256
-	private function getType($value) {
257
-		if (is_bool($value)) {
258
-			return IQueryBuilder::PARAM_BOOL;
259
-		} else if (is_int($value)) {
260
-			return IQueryBuilder::PARAM_INT;
261
-		} else {
262
-			return IQueryBuilder::PARAM_STR;
263
-		}
264
-	}
265
-
266
-	/**
267
-	 * Insert or update a row value
268
-	 *
269
-	 * @param string $table
270
-	 * @param array $keys (column name => value)
271
-	 * @param array $values (column name => value)
272
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
273
-	 * @return int number of new rows
274
-	 * @throws \Doctrine\DBAL\DBALException
275
-	 * @throws PreConditionNotMetException
276
-	 */
277
-	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
278
-		try {
279
-			$insertQb = $this->getQueryBuilder();
280
-			$insertQb->insert($table)
281
-				->values(
282
-					array_map(function($value) use ($insertQb) {
283
-						return $insertQb->createNamedParameter($value, $this->getType($value));
284
-					}, array_merge($keys, $values))
285
-				);
286
-			return $insertQb->execute();
287
-		} catch (\Doctrine\DBAL\Exception\ConstraintViolationException $e) {
288
-			// value already exists, try update
289
-			$updateQb = $this->getQueryBuilder();
290
-			$updateQb->update($table);
291
-			foreach ($values as $name => $value) {
292
-				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
293
-			}
294
-			$where = $updateQb->expr()->andX();
295
-			$whereValues = array_merge($keys, $updatePreconditionValues);
296
-			foreach ($whereValues as $name => $value) {
297
-				$where->add($updateQb->expr()->eq(
298
-					$name,
299
-					$updateQb->createNamedParameter($value, $this->getType($value)),
300
-					$this->getType($value)
301
-				));
302
-			}
303
-			$updateQb->where($where);
304
-			$affected = $updateQb->execute();
305
-
306
-			if ($affected === 0 && !empty($updatePreconditionValues)) {
307
-				throw new PreConditionNotMetException();
308
-			}
309
-
310
-			return 0;
311
-		}
312
-	}
313
-
314
-	/**
315
-	 * Create an exclusive read+write lock on a table
316
-	 *
317
-	 * @param string $tableName
318
-	 * @throws \BadMethodCallException When trying to acquire a second lock
319
-	 * @since 9.1.0
320
-	 */
321
-	public function lockTable($tableName) {
322
-		if ($this->lockedTable !== null) {
323
-			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
324
-		}
325
-
326
-		$tableName = $this->tablePrefix . $tableName;
327
-		$this->lockedTable = $tableName;
328
-		$this->adapter->lockTable($tableName);
329
-	}
330
-
331
-	/**
332
-	 * Release a previous acquired lock again
333
-	 *
334
-	 * @since 9.1.0
335
-	 */
336
-	public function unlockTable() {
337
-		$this->adapter->unlockTable();
338
-		$this->lockedTable = null;
339
-	}
340
-
341
-	/**
342
-	 * returns the error code and message as a string for logging
343
-	 * works with DoctrineException
344
-	 * @return string
345
-	 */
346
-	public function getError() {
347
-		$msg = $this->errorCode() . ': ';
348
-		$errorInfo = $this->errorInfo();
349
-		if (is_array($errorInfo)) {
350
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
351
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
352
-			$msg .= 'Driver Message = '.$errorInfo[2];
353
-		}
354
-		return $msg;
355
-	}
356
-
357
-	/**
358
-	 * Drop a table from the database if it exists
359
-	 *
360
-	 * @param string $table table name without the prefix
361
-	 */
362
-	public function dropTable($table) {
363
-		$table = $this->tablePrefix . trim($table);
364
-		$schema = $this->getSchemaManager();
365
-		if($schema->tablesExist(array($table))) {
366
-			$schema->dropTable($table);
367
-		}
368
-	}
369
-
370
-	/**
371
-	 * Check if a table exists
372
-	 *
373
-	 * @param string $table table name without the prefix
374
-	 * @return bool
375
-	 */
376
-	public function tableExists($table){
377
-		$table = $this->tablePrefix . trim($table);
378
-		$schema = $this->getSchemaManager();
379
-		return $schema->tablesExist(array($table));
380
-	}
381
-
382
-	// internal use
383
-	/**
384
-	 * @param string $statement
385
-	 * @return string
386
-	 */
387
-	protected function replaceTablePrefix($statement) {
388
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
389
-	}
390
-
391
-	/**
392
-	 * Check if a transaction is active
393
-	 *
394
-	 * @return bool
395
-	 * @since 8.2.0
396
-	 */
397
-	public function inTransaction() {
398
-		return $this->getTransactionNestingLevel() > 0;
399
-	}
400
-
401
-	/**
402
-	 * Espace a parameter to be used in a LIKE query
403
-	 *
404
-	 * @param string $param
405
-	 * @return string
406
-	 */
407
-	public function escapeLikeParameter($param) {
408
-		return addcslashes($param, '\\_%');
409
-	}
410
-
411
-	/**
412
-	 * Check whether or not the current database support 4byte wide unicode
413
-	 *
414
-	 * @return bool
415
-	 * @since 11.0.0
416
-	 */
417
-	public function supports4ByteText() {
418
-		return ! ($this->getDatabasePlatform() instanceof MySqlPlatform && $this->getParams()['charset'] !== 'utf8mb4');
419
-	}
43
+    /**
44
+     * @var string $tablePrefix
45
+     */
46
+    protected $tablePrefix;
47
+
48
+    /**
49
+     * @var \OC\DB\Adapter $adapter
50
+     */
51
+    protected $adapter;
52
+
53
+    protected $lockedTable = null;
54
+
55
+    public function connect() {
56
+        try {
57
+            return parent::connect();
58
+        } catch (DBALException $e) {
59
+            // throw a new exception to prevent leaking info from the stacktrace
60
+            throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
61
+        }
62
+    }
63
+
64
+    /**
65
+     * Returns a QueryBuilder for the connection.
66
+     *
67
+     * @return \OCP\DB\QueryBuilder\IQueryBuilder
68
+     */
69
+    public function getQueryBuilder() {
70
+        return new QueryBuilder(
71
+            $this,
72
+            \OC::$server->getSystemConfig(),
73
+            \OC::$server->getLogger()
74
+        );
75
+    }
76
+
77
+    /**
78
+     * Gets the QueryBuilder for the connection.
79
+     *
80
+     * @return \Doctrine\DBAL\Query\QueryBuilder
81
+     * @deprecated please use $this->getQueryBuilder() instead
82
+     */
83
+    public function createQueryBuilder() {
84
+        $backtrace = $this->getCallerBacktrace();
85
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
86
+        return parent::createQueryBuilder();
87
+    }
88
+
89
+    /**
90
+     * Gets the ExpressionBuilder for the connection.
91
+     *
92
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
93
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
94
+     */
95
+    public function getExpressionBuilder() {
96
+        $backtrace = $this->getCallerBacktrace();
97
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
98
+        return parent::getExpressionBuilder();
99
+    }
100
+
101
+    /**
102
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
103
+     *
104
+     * @return string
105
+     */
106
+    protected function getCallerBacktrace() {
107
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
108
+
109
+        // 0 is the method where we use `getCallerBacktrace`
110
+        // 1 is the target method which uses the method we want to log
111
+        if (isset($traces[1])) {
112
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
113
+        }
114
+
115
+        return '';
116
+    }
117
+
118
+    /**
119
+     * @return string
120
+     */
121
+    public function getPrefix() {
122
+        return $this->tablePrefix;
123
+    }
124
+
125
+    /**
126
+     * Initializes a new instance of the Connection class.
127
+     *
128
+     * @param array $params  The connection parameters.
129
+     * @param \Doctrine\DBAL\Driver $driver
130
+     * @param \Doctrine\DBAL\Configuration $config
131
+     * @param \Doctrine\Common\EventManager $eventManager
132
+     * @throws \Exception
133
+     */
134
+    public function __construct(array $params, Driver $driver, Configuration $config = null,
135
+        EventManager $eventManager = null)
136
+    {
137
+        if (!isset($params['adapter'])) {
138
+            throw new \Exception('adapter not set');
139
+        }
140
+        if (!isset($params['tablePrefix'])) {
141
+            throw new \Exception('tablePrefix not set');
142
+        }
143
+        parent::__construct($params, $driver, $config, $eventManager);
144
+        $this->adapter = new $params['adapter']($this);
145
+        $this->tablePrefix = $params['tablePrefix'];
146
+
147
+        parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
148
+    }
149
+
150
+    /**
151
+     * Prepares an SQL statement.
152
+     *
153
+     * @param string $statement The SQL statement to prepare.
154
+     * @param int $limit
155
+     * @param int $offset
156
+     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
157
+     */
158
+    public function prepare( $statement, $limit=null, $offset=null ) {
159
+        if ($limit === -1) {
160
+            $limit = null;
161
+        }
162
+        if (!is_null($limit)) {
163
+            $platform = $this->getDatabasePlatform();
164
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
165
+        }
166
+        $statement = $this->replaceTablePrefix($statement);
167
+        $statement = $this->adapter->fixupStatement($statement);
168
+
169
+        if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
170
+            \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
171
+        }
172
+        return parent::prepare($statement);
173
+    }
174
+
175
+    /**
176
+     * Executes an, optionally parametrized, SQL query.
177
+     *
178
+     * If the query is parametrized, a prepared statement is used.
179
+     * If an SQLLogger is configured, the execution is logged.
180
+     *
181
+     * @param string                                      $query  The SQL query to execute.
182
+     * @param array                                       $params The parameters to bind to the query, if any.
183
+     * @param array                                       $types  The types the previous parameters are in.
184
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
185
+     *
186
+     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
187
+     *
188
+     * @throws \Doctrine\DBAL\DBALException
189
+     */
190
+    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
191
+    {
192
+        $query = $this->replaceTablePrefix($query);
193
+        $query = $this->adapter->fixupStatement($query);
194
+        return parent::executeQuery($query, $params, $types, $qcp);
195
+    }
196
+
197
+    /**
198
+     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
199
+     * and returns the number of affected rows.
200
+     *
201
+     * This method supports PDO binding types as well as DBAL mapping types.
202
+     *
203
+     * @param string $query  The SQL query.
204
+     * @param array  $params The query parameters.
205
+     * @param array  $types  The parameter types.
206
+     *
207
+     * @return integer The number of affected rows.
208
+     *
209
+     * @throws \Doctrine\DBAL\DBALException
210
+     */
211
+    public function executeUpdate($query, array $params = array(), array $types = array())
212
+    {
213
+        $query = $this->replaceTablePrefix($query);
214
+        $query = $this->adapter->fixupStatement($query);
215
+        return parent::executeUpdate($query, $params, $types);
216
+    }
217
+
218
+    /**
219
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
220
+     * depending on the underlying driver.
221
+     *
222
+     * Note: This method may not return a meaningful or consistent result across different drivers,
223
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
224
+     * columns or sequences.
225
+     *
226
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
227
+     * @return string A string representation of the last inserted ID.
228
+     */
229
+    public function lastInsertId($seqName = null) {
230
+        if ($seqName) {
231
+            $seqName = $this->replaceTablePrefix($seqName);
232
+        }
233
+        return $this->adapter->lastInsertId($seqName);
234
+    }
235
+
236
+    // internal use
237
+    public function realLastInsertId($seqName = null) {
238
+        return parent::lastInsertId($seqName);
239
+    }
240
+
241
+    /**
242
+     * Insert a row if the matching row does not exists.
243
+     *
244
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
245
+     * @param array $input data that should be inserted into the table  (column name => value)
246
+     * @param array|null $compare List of values that should be checked for "if not exists"
247
+     *				If this is null or an empty array, all keys of $input will be compared
248
+     *				Please note: text fields (clob) must not be used in the compare array
249
+     * @return int number of inserted rows
250
+     * @throws \Doctrine\DBAL\DBALException
251
+     */
252
+    public function insertIfNotExist($table, $input, array $compare = null) {
253
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
254
+    }
255
+
256
+    private function getType($value) {
257
+        if (is_bool($value)) {
258
+            return IQueryBuilder::PARAM_BOOL;
259
+        } else if (is_int($value)) {
260
+            return IQueryBuilder::PARAM_INT;
261
+        } else {
262
+            return IQueryBuilder::PARAM_STR;
263
+        }
264
+    }
265
+
266
+    /**
267
+     * Insert or update a row value
268
+     *
269
+     * @param string $table
270
+     * @param array $keys (column name => value)
271
+     * @param array $values (column name => value)
272
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
273
+     * @return int number of new rows
274
+     * @throws \Doctrine\DBAL\DBALException
275
+     * @throws PreConditionNotMetException
276
+     */
277
+    public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
278
+        try {
279
+            $insertQb = $this->getQueryBuilder();
280
+            $insertQb->insert($table)
281
+                ->values(
282
+                    array_map(function($value) use ($insertQb) {
283
+                        return $insertQb->createNamedParameter($value, $this->getType($value));
284
+                    }, array_merge($keys, $values))
285
+                );
286
+            return $insertQb->execute();
287
+        } catch (\Doctrine\DBAL\Exception\ConstraintViolationException $e) {
288
+            // value already exists, try update
289
+            $updateQb = $this->getQueryBuilder();
290
+            $updateQb->update($table);
291
+            foreach ($values as $name => $value) {
292
+                $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
293
+            }
294
+            $where = $updateQb->expr()->andX();
295
+            $whereValues = array_merge($keys, $updatePreconditionValues);
296
+            foreach ($whereValues as $name => $value) {
297
+                $where->add($updateQb->expr()->eq(
298
+                    $name,
299
+                    $updateQb->createNamedParameter($value, $this->getType($value)),
300
+                    $this->getType($value)
301
+                ));
302
+            }
303
+            $updateQb->where($where);
304
+            $affected = $updateQb->execute();
305
+
306
+            if ($affected === 0 && !empty($updatePreconditionValues)) {
307
+                throw new PreConditionNotMetException();
308
+            }
309
+
310
+            return 0;
311
+        }
312
+    }
313
+
314
+    /**
315
+     * Create an exclusive read+write lock on a table
316
+     *
317
+     * @param string $tableName
318
+     * @throws \BadMethodCallException When trying to acquire a second lock
319
+     * @since 9.1.0
320
+     */
321
+    public function lockTable($tableName) {
322
+        if ($this->lockedTable !== null) {
323
+            throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
324
+        }
325
+
326
+        $tableName = $this->tablePrefix . $tableName;
327
+        $this->lockedTable = $tableName;
328
+        $this->adapter->lockTable($tableName);
329
+    }
330
+
331
+    /**
332
+     * Release a previous acquired lock again
333
+     *
334
+     * @since 9.1.0
335
+     */
336
+    public function unlockTable() {
337
+        $this->adapter->unlockTable();
338
+        $this->lockedTable = null;
339
+    }
340
+
341
+    /**
342
+     * returns the error code and message as a string for logging
343
+     * works with DoctrineException
344
+     * @return string
345
+     */
346
+    public function getError() {
347
+        $msg = $this->errorCode() . ': ';
348
+        $errorInfo = $this->errorInfo();
349
+        if (is_array($errorInfo)) {
350
+            $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
351
+            $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
352
+            $msg .= 'Driver Message = '.$errorInfo[2];
353
+        }
354
+        return $msg;
355
+    }
356
+
357
+    /**
358
+     * Drop a table from the database if it exists
359
+     *
360
+     * @param string $table table name without the prefix
361
+     */
362
+    public function dropTable($table) {
363
+        $table = $this->tablePrefix . trim($table);
364
+        $schema = $this->getSchemaManager();
365
+        if($schema->tablesExist(array($table))) {
366
+            $schema->dropTable($table);
367
+        }
368
+    }
369
+
370
+    /**
371
+     * Check if a table exists
372
+     *
373
+     * @param string $table table name without the prefix
374
+     * @return bool
375
+     */
376
+    public function tableExists($table){
377
+        $table = $this->tablePrefix . trim($table);
378
+        $schema = $this->getSchemaManager();
379
+        return $schema->tablesExist(array($table));
380
+    }
381
+
382
+    // internal use
383
+    /**
384
+     * @param string $statement
385
+     * @return string
386
+     */
387
+    protected function replaceTablePrefix($statement) {
388
+        return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
389
+    }
390
+
391
+    /**
392
+     * Check if a transaction is active
393
+     *
394
+     * @return bool
395
+     * @since 8.2.0
396
+     */
397
+    public function inTransaction() {
398
+        return $this->getTransactionNestingLevel() > 0;
399
+    }
400
+
401
+    /**
402
+     * Espace a parameter to be used in a LIKE query
403
+     *
404
+     * @param string $param
405
+     * @return string
406
+     */
407
+    public function escapeLikeParameter($param) {
408
+        return addcslashes($param, '\\_%');
409
+    }
410
+
411
+    /**
412
+     * Check whether or not the current database support 4byte wide unicode
413
+     *
414
+     * @return bool
415
+     * @since 11.0.0
416
+     */
417
+    public function supports4ByteText() {
418
+        return ! ($this->getDatabasePlatform() instanceof MySqlPlatform && $this->getParams()['charset'] !== 'utf8mb4');
419
+    }
420 420
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 			return parent::connect();
58 58
 		} catch (DBALException $e) {
59 59
 			// throw a new exception to prevent leaking info from the stacktrace
60
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
60
+			throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
61 61
 		}
62 62
 	}
63 63
 
@@ -109,7 +109,7 @@  discard block
 block discarded – undo
109 109
 		// 0 is the method where we use `getCallerBacktrace`
110 110
 		// 1 is the target method which uses the method we want to log
111 111
 		if (isset($traces[1])) {
112
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
112
+			return $traces[1]['file'].':'.$traces[1]['line'];
113 113
 		}
114 114
 
115 115
 		return '';
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 	 * @param int $offset
156 156
 	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
157 157
 	 */
158
-	public function prepare( $statement, $limit=null, $offset=null ) {
158
+	public function prepare($statement, $limit = null, $offset = null) {
159 159
 		if ($limit === -1) {
160 160
 			$limit = null;
161 161
 		}
@@ -166,7 +166,7 @@  discard block
 block discarded – undo
166 166
 		$statement = $this->replaceTablePrefix($statement);
167 167
 		$statement = $this->adapter->fixupStatement($statement);
168 168
 
169
-		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
169
+		if (\OC::$server->getSystemConfig()->getValue('log_query', false)) {
170 170
 			\OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
171 171
 		}
172 172
 		return parent::prepare($statement);
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
324 324
 		}
325 325
 
326
-		$tableName = $this->tablePrefix . $tableName;
326
+		$tableName = $this->tablePrefix.$tableName;
327 327
 		$this->lockedTable = $tableName;
328 328
 		$this->adapter->lockTable($tableName);
329 329
 	}
@@ -344,11 +344,11 @@  discard block
 block discarded – undo
344 344
 	 * @return string
345 345
 	 */
346 346
 	public function getError() {
347
-		$msg = $this->errorCode() . ': ';
347
+		$msg = $this->errorCode().': ';
348 348
 		$errorInfo = $this->errorInfo();
349 349
 		if (is_array($errorInfo)) {
350
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
351
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
350
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
351
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
352 352
 			$msg .= 'Driver Message = '.$errorInfo[2];
353 353
 		}
354 354
 		return $msg;
@@ -360,9 +360,9 @@  discard block
 block discarded – undo
360 360
 	 * @param string $table table name without the prefix
361 361
 	 */
362 362
 	public function dropTable($table) {
363
-		$table = $this->tablePrefix . trim($table);
363
+		$table = $this->tablePrefix.trim($table);
364 364
 		$schema = $this->getSchemaManager();
365
-		if($schema->tablesExist(array($table))) {
365
+		if ($schema->tablesExist(array($table))) {
366 366
 			$schema->dropTable($table);
367 367
 		}
368 368
 	}
@@ -373,8 +373,8 @@  discard block
 block discarded – undo
373 373
 	 * @param string $table table name without the prefix
374 374
 	 * @return bool
375 375
 	 */
376
-	public function tableExists($table){
377
-		$table = $this->tablePrefix . trim($table);
376
+	public function tableExists($table) {
377
+		$table = $this->tablePrefix.trim($table);
378 378
 		$schema = $this->getSchemaManager();
379 379
 		return $schema->tablesExist(array($table));
380 380
 	}
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 	 * @return string
386 386
 	 */
387 387
 	protected function replaceTablePrefix($statement) {
388
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
388
+		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
389 389
 	}
390 390
 
391 391
 	/**
@@ -415,6 +415,6 @@  discard block
 block discarded – undo
415 415
 	 * @since 11.0.0
416 416
 	 */
417 417
 	public function supports4ByteText() {
418
-		return ! ($this->getDatabasePlatform() instanceof MySqlPlatform && $this->getParams()['charset'] !== 'utf8mb4');
418
+		return !($this->getDatabasePlatform() instanceof MySqlPlatform && $this->getParams()['charset'] !== 'utf8mb4');
419 419
 	}
420 420
 }
Please login to merge, or discard this patch.