Completed
Push — master ( 5ca5eb...afb5d4 )
by Lukas
16:52
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/AllConfig.php 3 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -112,7 +112,7 @@
 block discarded – undo
112 112
 	 * Looks up a system wide defined value
113 113
 	 *
114 114
 	 * @param string $key the key of the value, under which it was saved
115
-	 * @param mixed $default the default value to be returned if the value isn't set
115
+	 * @param string $default the default value to be returned if the value isn't set
116 116
 	 * @return mixed the value or $default
117 117
 	 */
118 118
 	public function getSystemValue($key, $default = '') {
Please login to merge, or discard this patch.
Indentation   +423 added lines, -423 removed lines patch added patch discarded remove patch
@@ -37,427 +37,427 @@
 block discarded – undo
37 37
  * Class to combine all the configuration options ownCloud offers
38 38
  */
39 39
 class AllConfig implements \OCP\IConfig {
40
-	/** @var SystemConfig */
41
-	private $systemConfig;
42
-
43
-	/** @var IDBConnection */
44
-	private $connection;
45
-
46
-	/**
47
-	 * 3 dimensional array with the following structure:
48
-	 * [ $userId =>
49
-	 *     [ $appId =>
50
-	 *         [ $key => $value ]
51
-	 *     ]
52
-	 * ]
53
-	 *
54
-	 * database table: preferences
55
-	 *
56
-	 * methods that use this:
57
-	 *   - setUserValue
58
-	 *   - getUserValue
59
-	 *   - getUserKeys
60
-	 *   - deleteUserValue
61
-	 *   - deleteAllUserValues
62
-	 *   - deleteAppFromAllUsers
63
-	 *
64
-	 * @var CappedMemoryCache $userCache
65
-	 */
66
-	private $userCache;
67
-
68
-	/**
69
-	 * @param SystemConfig $systemConfig
70
-	 */
71
-	public function __construct(SystemConfig $systemConfig) {
72
-		$this->userCache = new CappedMemoryCache();
73
-		$this->systemConfig = $systemConfig;
74
-	}
75
-
76
-	/**
77
-	 * TODO - FIXME This fixes an issue with base.php that cause cyclic
78
-	 * dependencies, especially with autoconfig setup
79
-	 *
80
-	 * Replace this by properly injected database connection. Currently the
81
-	 * base.php triggers the getDatabaseConnection too early which causes in
82
-	 * autoconfig setup case a too early distributed database connection and
83
-	 * the autoconfig then needs to reinit all already initialized dependencies
84
-	 * that use the database connection.
85
-	 *
86
-	 * otherwise a SQLite database is created in the wrong directory
87
-	 * because the database connection was created with an uninitialized config
88
-	 */
89
-	private function fixDIInit() {
90
-		if($this->connection === null) {
91
-			$this->connection = \OC::$server->getDatabaseConnection();
92
-		}
93
-	}
94
-
95
-	/**
96
-	 * Sets and deletes system wide values
97
-	 *
98
-	 * @param array $configs Associative array with `key => value` pairs
99
-	 *                       If value is null, the config key will be deleted
100
-	 */
101
-	public function setSystemValues(array $configs) {
102
-		$this->systemConfig->setValues($configs);
103
-	}
104
-
105
-	/**
106
-	 * Sets a new system wide value
107
-	 *
108
-	 * @param string $key the key of the value, under which will be saved
109
-	 * @param mixed $value the value that should be stored
110
-	 */
111
-	public function setSystemValue($key, $value) {
112
-		$this->systemConfig->setValue($key, $value);
113
-	}
114
-
115
-	/**
116
-	 * Looks up a system wide defined value
117
-	 *
118
-	 * @param string $key the key of the value, under which it was saved
119
-	 * @param mixed $default the default value to be returned if the value isn't set
120
-	 * @return mixed the value or $default
121
-	 */
122
-	public function getSystemValue($key, $default = '') {
123
-		return $this->systemConfig->getValue($key, $default);
124
-	}
125
-
126
-	/**
127
-	 * Looks up a system wide defined value and filters out sensitive data
128
-	 *
129
-	 * @param string $key the key of the value, under which it was saved
130
-	 * @param mixed $default the default value to be returned if the value isn't set
131
-	 * @return mixed the value or $default
132
-	 */
133
-	public function getFilteredSystemValue($key, $default = '') {
134
-		return $this->systemConfig->getFilteredValue($key, $default);
135
-	}
136
-
137
-	/**
138
-	 * Delete a system wide defined value
139
-	 *
140
-	 * @param string $key the key of the value, under which it was saved
141
-	 */
142
-	public function deleteSystemValue($key) {
143
-		$this->systemConfig->deleteValue($key);
144
-	}
145
-
146
-	/**
147
-	 * Get all keys stored for an app
148
-	 *
149
-	 * @param string $appName the appName that we stored the value under
150
-	 * @return string[] the keys stored for the app
151
-	 */
152
-	public function getAppKeys($appName) {
153
-		return \OC::$server->getAppConfig()->getKeys($appName);
154
-	}
155
-
156
-	/**
157
-	 * Writes a new app wide value
158
-	 *
159
-	 * @param string $appName the appName that we want to store the value under
160
-	 * @param string $key the key of the value, under which will be saved
161
-	 * @param string|float|int $value the value that should be stored
162
-	 */
163
-	public function setAppValue($appName, $key, $value) {
164
-		\OC::$server->getAppConfig()->setValue($appName, $key, $value);
165
-	}
166
-
167
-	/**
168
-	 * Looks up an app wide defined value
169
-	 *
170
-	 * @param string $appName the appName that we stored the value under
171
-	 * @param string $key the key of the value, under which it was saved
172
-	 * @param string $default the default value to be returned if the value isn't set
173
-	 * @return string the saved value
174
-	 */
175
-	public function getAppValue($appName, $key, $default = '') {
176
-		return \OC::$server->getAppConfig()->getValue($appName, $key, $default);
177
-	}
178
-
179
-	/**
180
-	 * Delete an app wide defined value
181
-	 *
182
-	 * @param string $appName the appName that we stored the value under
183
-	 * @param string $key the key of the value, under which it was saved
184
-	 */
185
-	public function deleteAppValue($appName, $key) {
186
-		\OC::$server->getAppConfig()->deleteKey($appName, $key);
187
-	}
188
-
189
-	/**
190
-	 * Removes all keys in appconfig belonging to the app
191
-	 *
192
-	 * @param string $appName the appName the configs are stored under
193
-	 */
194
-	public function deleteAppValues($appName) {
195
-		\OC::$server->getAppConfig()->deleteApp($appName);
196
-	}
197
-
198
-
199
-	/**
200
-	 * Set a user defined value
201
-	 *
202
-	 * @param string $userId the userId of the user that we want to store the value under
203
-	 * @param string $appName the appName that we want to store the value under
204
-	 * @param string $key the key under which the value is being stored
205
-	 * @param string|float|int $value the value that you want to store
206
-	 * @param string $preCondition only update if the config value was previously the value passed as $preCondition
207
-	 * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
208
-	 * @throws \UnexpectedValueException when trying to store an unexpected value
209
-	 */
210
-	public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
211
-		if (!is_int($value) && !is_float($value) && !is_string($value)) {
212
-			throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
213
-		}
214
-
215
-		// TODO - FIXME
216
-		$this->fixDIInit();
217
-
218
-		$prevValue = $this->getUserValue($userId, $appName, $key, null);
219
-
220
-		if ($prevValue !== null) {
221
-			if ($prevValue === (string)$value) {
222
-				return;
223
-			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
224
-				throw new PreConditionNotMetException();
225
-			} else {
226
-				$qb = $this->connection->getQueryBuilder();
227
-				$qb->update('preferences')
228
-					->set('configvalue', $qb->createNamedParameter($value))
229
-					->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
230
-					->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
231
-					->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
232
-				$qb->execute();
233
-
234
-				$this->userCache[$userId][$appName][$key] = $value;
235
-				return;
236
-			}
237
-		}
238
-
239
-		$preconditionArray = [];
240
-		if (isset($preCondition)) {
241
-			$preconditionArray = [
242
-				'configvalue' => $preCondition,
243
-			];
244
-		}
245
-
246
-		$this->connection->setValues('preferences', [
247
-			'userid' => $userId,
248
-			'appid' => $appName,
249
-			'configkey' => $key,
250
-		], [
251
-			'configvalue' => $value,
252
-		], $preconditionArray);
253
-
254
-		// only add to the cache if we already loaded data for the user
255
-		if (isset($this->userCache[$userId])) {
256
-			if (!isset($this->userCache[$userId][$appName])) {
257
-				$this->userCache[$userId][$appName] = array();
258
-			}
259
-			$this->userCache[$userId][$appName][$key] = $value;
260
-		}
261
-	}
262
-
263
-	/**
264
-	 * Getting a user defined value
265
-	 *
266
-	 * @param string $userId the userId of the user that we want to store the value under
267
-	 * @param string $appName the appName that we stored the value under
268
-	 * @param string $key the key under which the value is being stored
269
-	 * @param mixed $default the default value to be returned if the value isn't set
270
-	 * @return string
271
-	 */
272
-	public function getUserValue($userId, $appName, $key, $default = '') {
273
-		$data = $this->getUserValues($userId);
274
-		if (isset($data[$appName]) and isset($data[$appName][$key])) {
275
-			return $data[$appName][$key];
276
-		} else {
277
-			return $default;
278
-		}
279
-	}
280
-
281
-	/**
282
-	 * Get the keys of all stored by an app for the user
283
-	 *
284
-	 * @param string $userId the userId of the user that we want to store the value under
285
-	 * @param string $appName the appName that we stored the value under
286
-	 * @return string[]
287
-	 */
288
-	public function getUserKeys($userId, $appName) {
289
-		$data = $this->getUserValues($userId);
290
-		if (isset($data[$appName])) {
291
-			return array_keys($data[$appName]);
292
-		} else {
293
-			return array();
294
-		}
295
-	}
296
-
297
-	/**
298
-	 * Delete a user value
299
-	 *
300
-	 * @param string $userId the userId of the user that we want to store the value under
301
-	 * @param string $appName the appName that we stored the value under
302
-	 * @param string $key the key under which the value is being stored
303
-	 */
304
-	public function deleteUserValue($userId, $appName, $key) {
305
-		// TODO - FIXME
306
-		$this->fixDIInit();
307
-
308
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
309
-				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
310
-		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
311
-
312
-		if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
313
-			unset($this->userCache[$userId][$appName][$key]);
314
-		}
315
-	}
316
-
317
-	/**
318
-	 * Delete all user values
319
-	 *
320
-	 * @param string $userId the userId of the user that we want to remove all values from
321
-	 */
322
-	public function deleteAllUserValues($userId) {
323
-		// TODO - FIXME
324
-		$this->fixDIInit();
325
-
326
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
327
-			'WHERE `userid` = ?';
328
-		$this->connection->executeUpdate($sql, array($userId));
329
-
330
-		unset($this->userCache[$userId]);
331
-	}
332
-
333
-	/**
334
-	 * Delete all user related values of one app
335
-	 *
336
-	 * @param string $appName the appName of the app that we want to remove all values from
337
-	 */
338
-	public function deleteAppFromAllUsers($appName) {
339
-		// TODO - FIXME
340
-		$this->fixDIInit();
341
-
342
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
343
-				'WHERE `appid` = ?';
344
-		$this->connection->executeUpdate($sql, array($appName));
345
-
346
-		foreach ($this->userCache as &$userCache) {
347
-			unset($userCache[$appName]);
348
-		}
349
-	}
350
-
351
-	/**
352
-	 * Returns all user configs sorted by app of one user
353
-	 *
354
-	 * @param string $userId the user ID to get the app configs from
355
-	 * @return array[] - 2 dimensional array with the following structure:
356
-	 *     [ $appId =>
357
-	 *         [ $key => $value ]
358
-	 *     ]
359
-	 */
360
-	private function getUserValues($userId) {
361
-		if (isset($this->userCache[$userId])) {
362
-			return $this->userCache[$userId];
363
-		}
364
-		if ($userId === null || $userId === '') {
365
-			$this->userCache[$userId]=array();
366
-			return $this->userCache[$userId];
367
-		}
368
-
369
-		// TODO - FIXME
370
-		$this->fixDIInit();
371
-
372
-		$data = array();
373
-		$query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
374
-		$result = $this->connection->executeQuery($query, array($userId));
375
-		while ($row = $result->fetch()) {
376
-			$appId = $row['appid'];
377
-			if (!isset($data[$appId])) {
378
-				$data[$appId] = array();
379
-			}
380
-			$data[$appId][$row['configkey']] = $row['configvalue'];
381
-		}
382
-		$this->userCache[$userId] = $data;
383
-		return $data;
384
-	}
385
-
386
-	/**
387
-	 * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
388
-	 *
389
-	 * @param string $appName app to get the value for
390
-	 * @param string $key the key to get the value for
391
-	 * @param array $userIds the user IDs to fetch the values for
392
-	 * @return array Mapped values: userId => value
393
-	 */
394
-	public function getUserValueForUsers($appName, $key, $userIds) {
395
-		// TODO - FIXME
396
-		$this->fixDIInit();
397
-
398
-		if (empty($userIds) || !is_array($userIds)) {
399
-			return array();
400
-		}
401
-
402
-		$chunkedUsers = array_chunk($userIds, 50, true);
403
-		$placeholders50 = implode(',', array_fill(0, 50, '?'));
404
-
405
-		$userValues = array();
406
-		foreach ($chunkedUsers as $chunk) {
407
-			$queryParams = $chunk;
408
-			// create [$app, $key, $chunkedUsers]
409
-			array_unshift($queryParams, $key);
410
-			array_unshift($queryParams, $appName);
411
-
412
-			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
413
-
414
-			$query    = 'SELECT `userid`, `configvalue` ' .
415
-						'FROM `*PREFIX*preferences` ' .
416
-						'WHERE `appid` = ? AND `configkey` = ? ' .
417
-						'AND `userid` IN (' . $placeholders . ')';
418
-			$result = $this->connection->executeQuery($query, $queryParams);
419
-
420
-			while ($row = $result->fetch()) {
421
-				$userValues[$row['userid']] = $row['configvalue'];
422
-			}
423
-		}
424
-
425
-		return $userValues;
426
-	}
427
-
428
-	/**
429
-	 * Determines the users that have the given value set for a specific app-key-pair
430
-	 *
431
-	 * @param string $appName the app to get the user for
432
-	 * @param string $key the key to get the user for
433
-	 * @param string $value the value to get the user for
434
-	 * @return array of user IDs
435
-	 */
436
-	public function getUsersForUserValue($appName, $key, $value) {
437
-		// TODO - FIXME
438
-		$this->fixDIInit();
439
-
440
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
441
-				'WHERE `appid` = ? AND `configkey` = ? ';
442
-
443
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
444
-			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
445
-			$sql .= 'AND to_char(`configvalue`) = ?';
446
-		} else {
447
-			$sql .= 'AND `configvalue` = ?';
448
-		}
449
-
450
-		$result = $this->connection->executeQuery($sql, array($appName, $key, $value));
451
-
452
-		$userIDs = array();
453
-		while ($row = $result->fetch()) {
454
-			$userIDs[] = $row['userid'];
455
-		}
456
-
457
-		return $userIDs;
458
-	}
459
-
460
-	public function getSystemConfig() {
461
-		return $this->systemConfig;
462
-	}
40
+    /** @var SystemConfig */
41
+    private $systemConfig;
42
+
43
+    /** @var IDBConnection */
44
+    private $connection;
45
+
46
+    /**
47
+     * 3 dimensional array with the following structure:
48
+     * [ $userId =>
49
+     *     [ $appId =>
50
+     *         [ $key => $value ]
51
+     *     ]
52
+     * ]
53
+     *
54
+     * database table: preferences
55
+     *
56
+     * methods that use this:
57
+     *   - setUserValue
58
+     *   - getUserValue
59
+     *   - getUserKeys
60
+     *   - deleteUserValue
61
+     *   - deleteAllUserValues
62
+     *   - deleteAppFromAllUsers
63
+     *
64
+     * @var CappedMemoryCache $userCache
65
+     */
66
+    private $userCache;
67
+
68
+    /**
69
+     * @param SystemConfig $systemConfig
70
+     */
71
+    public function __construct(SystemConfig $systemConfig) {
72
+        $this->userCache = new CappedMemoryCache();
73
+        $this->systemConfig = $systemConfig;
74
+    }
75
+
76
+    /**
77
+     * TODO - FIXME This fixes an issue with base.php that cause cyclic
78
+     * dependencies, especially with autoconfig setup
79
+     *
80
+     * Replace this by properly injected database connection. Currently the
81
+     * base.php triggers the getDatabaseConnection too early which causes in
82
+     * autoconfig setup case a too early distributed database connection and
83
+     * the autoconfig then needs to reinit all already initialized dependencies
84
+     * that use the database connection.
85
+     *
86
+     * otherwise a SQLite database is created in the wrong directory
87
+     * because the database connection was created with an uninitialized config
88
+     */
89
+    private function fixDIInit() {
90
+        if($this->connection === null) {
91
+            $this->connection = \OC::$server->getDatabaseConnection();
92
+        }
93
+    }
94
+
95
+    /**
96
+     * Sets and deletes system wide values
97
+     *
98
+     * @param array $configs Associative array with `key => value` pairs
99
+     *                       If value is null, the config key will be deleted
100
+     */
101
+    public function setSystemValues(array $configs) {
102
+        $this->systemConfig->setValues($configs);
103
+    }
104
+
105
+    /**
106
+     * Sets a new system wide value
107
+     *
108
+     * @param string $key the key of the value, under which will be saved
109
+     * @param mixed $value the value that should be stored
110
+     */
111
+    public function setSystemValue($key, $value) {
112
+        $this->systemConfig->setValue($key, $value);
113
+    }
114
+
115
+    /**
116
+     * Looks up a system wide defined value
117
+     *
118
+     * @param string $key the key of the value, under which it was saved
119
+     * @param mixed $default the default value to be returned if the value isn't set
120
+     * @return mixed the value or $default
121
+     */
122
+    public function getSystemValue($key, $default = '') {
123
+        return $this->systemConfig->getValue($key, $default);
124
+    }
125
+
126
+    /**
127
+     * Looks up a system wide defined value and filters out sensitive data
128
+     *
129
+     * @param string $key the key of the value, under which it was saved
130
+     * @param mixed $default the default value to be returned if the value isn't set
131
+     * @return mixed the value or $default
132
+     */
133
+    public function getFilteredSystemValue($key, $default = '') {
134
+        return $this->systemConfig->getFilteredValue($key, $default);
135
+    }
136
+
137
+    /**
138
+     * Delete a system wide defined value
139
+     *
140
+     * @param string $key the key of the value, under which it was saved
141
+     */
142
+    public function deleteSystemValue($key) {
143
+        $this->systemConfig->deleteValue($key);
144
+    }
145
+
146
+    /**
147
+     * Get all keys stored for an app
148
+     *
149
+     * @param string $appName the appName that we stored the value under
150
+     * @return string[] the keys stored for the app
151
+     */
152
+    public function getAppKeys($appName) {
153
+        return \OC::$server->getAppConfig()->getKeys($appName);
154
+    }
155
+
156
+    /**
157
+     * Writes a new app wide value
158
+     *
159
+     * @param string $appName the appName that we want to store the value under
160
+     * @param string $key the key of the value, under which will be saved
161
+     * @param string|float|int $value the value that should be stored
162
+     */
163
+    public function setAppValue($appName, $key, $value) {
164
+        \OC::$server->getAppConfig()->setValue($appName, $key, $value);
165
+    }
166
+
167
+    /**
168
+     * Looks up an app wide defined value
169
+     *
170
+     * @param string $appName the appName that we stored the value under
171
+     * @param string $key the key of the value, under which it was saved
172
+     * @param string $default the default value to be returned if the value isn't set
173
+     * @return string the saved value
174
+     */
175
+    public function getAppValue($appName, $key, $default = '') {
176
+        return \OC::$server->getAppConfig()->getValue($appName, $key, $default);
177
+    }
178
+
179
+    /**
180
+     * Delete an app wide defined value
181
+     *
182
+     * @param string $appName the appName that we stored the value under
183
+     * @param string $key the key of the value, under which it was saved
184
+     */
185
+    public function deleteAppValue($appName, $key) {
186
+        \OC::$server->getAppConfig()->deleteKey($appName, $key);
187
+    }
188
+
189
+    /**
190
+     * Removes all keys in appconfig belonging to the app
191
+     *
192
+     * @param string $appName the appName the configs are stored under
193
+     */
194
+    public function deleteAppValues($appName) {
195
+        \OC::$server->getAppConfig()->deleteApp($appName);
196
+    }
197
+
198
+
199
+    /**
200
+     * Set a user defined value
201
+     *
202
+     * @param string $userId the userId of the user that we want to store the value under
203
+     * @param string $appName the appName that we want to store the value under
204
+     * @param string $key the key under which the value is being stored
205
+     * @param string|float|int $value the value that you want to store
206
+     * @param string $preCondition only update if the config value was previously the value passed as $preCondition
207
+     * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
208
+     * @throws \UnexpectedValueException when trying to store an unexpected value
209
+     */
210
+    public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
211
+        if (!is_int($value) && !is_float($value) && !is_string($value)) {
212
+            throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
213
+        }
214
+
215
+        // TODO - FIXME
216
+        $this->fixDIInit();
217
+
218
+        $prevValue = $this->getUserValue($userId, $appName, $key, null);
219
+
220
+        if ($prevValue !== null) {
221
+            if ($prevValue === (string)$value) {
222
+                return;
223
+            } else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
224
+                throw new PreConditionNotMetException();
225
+            } else {
226
+                $qb = $this->connection->getQueryBuilder();
227
+                $qb->update('preferences')
228
+                    ->set('configvalue', $qb->createNamedParameter($value))
229
+                    ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
230
+                    ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
231
+                    ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
232
+                $qb->execute();
233
+
234
+                $this->userCache[$userId][$appName][$key] = $value;
235
+                return;
236
+            }
237
+        }
238
+
239
+        $preconditionArray = [];
240
+        if (isset($preCondition)) {
241
+            $preconditionArray = [
242
+                'configvalue' => $preCondition,
243
+            ];
244
+        }
245
+
246
+        $this->connection->setValues('preferences', [
247
+            'userid' => $userId,
248
+            'appid' => $appName,
249
+            'configkey' => $key,
250
+        ], [
251
+            'configvalue' => $value,
252
+        ], $preconditionArray);
253
+
254
+        // only add to the cache if we already loaded data for the user
255
+        if (isset($this->userCache[$userId])) {
256
+            if (!isset($this->userCache[$userId][$appName])) {
257
+                $this->userCache[$userId][$appName] = array();
258
+            }
259
+            $this->userCache[$userId][$appName][$key] = $value;
260
+        }
261
+    }
262
+
263
+    /**
264
+     * Getting a user defined value
265
+     *
266
+     * @param string $userId the userId of the user that we want to store the value under
267
+     * @param string $appName the appName that we stored the value under
268
+     * @param string $key the key under which the value is being stored
269
+     * @param mixed $default the default value to be returned if the value isn't set
270
+     * @return string
271
+     */
272
+    public function getUserValue($userId, $appName, $key, $default = '') {
273
+        $data = $this->getUserValues($userId);
274
+        if (isset($data[$appName]) and isset($data[$appName][$key])) {
275
+            return $data[$appName][$key];
276
+        } else {
277
+            return $default;
278
+        }
279
+    }
280
+
281
+    /**
282
+     * Get the keys of all stored by an app for the user
283
+     *
284
+     * @param string $userId the userId of the user that we want to store the value under
285
+     * @param string $appName the appName that we stored the value under
286
+     * @return string[]
287
+     */
288
+    public function getUserKeys($userId, $appName) {
289
+        $data = $this->getUserValues($userId);
290
+        if (isset($data[$appName])) {
291
+            return array_keys($data[$appName]);
292
+        } else {
293
+            return array();
294
+        }
295
+    }
296
+
297
+    /**
298
+     * Delete a user value
299
+     *
300
+     * @param string $userId the userId of the user that we want to store the value under
301
+     * @param string $appName the appName that we stored the value under
302
+     * @param string $key the key under which the value is being stored
303
+     */
304
+    public function deleteUserValue($userId, $appName, $key) {
305
+        // TODO - FIXME
306
+        $this->fixDIInit();
307
+
308
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
309
+                'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
310
+        $this->connection->executeUpdate($sql, array($userId, $appName, $key));
311
+
312
+        if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
313
+            unset($this->userCache[$userId][$appName][$key]);
314
+        }
315
+    }
316
+
317
+    /**
318
+     * Delete all user values
319
+     *
320
+     * @param string $userId the userId of the user that we want to remove all values from
321
+     */
322
+    public function deleteAllUserValues($userId) {
323
+        // TODO - FIXME
324
+        $this->fixDIInit();
325
+
326
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
327
+            'WHERE `userid` = ?';
328
+        $this->connection->executeUpdate($sql, array($userId));
329
+
330
+        unset($this->userCache[$userId]);
331
+    }
332
+
333
+    /**
334
+     * Delete all user related values of one app
335
+     *
336
+     * @param string $appName the appName of the app that we want to remove all values from
337
+     */
338
+    public function deleteAppFromAllUsers($appName) {
339
+        // TODO - FIXME
340
+        $this->fixDIInit();
341
+
342
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
343
+                'WHERE `appid` = ?';
344
+        $this->connection->executeUpdate($sql, array($appName));
345
+
346
+        foreach ($this->userCache as &$userCache) {
347
+            unset($userCache[$appName]);
348
+        }
349
+    }
350
+
351
+    /**
352
+     * Returns all user configs sorted by app of one user
353
+     *
354
+     * @param string $userId the user ID to get the app configs from
355
+     * @return array[] - 2 dimensional array with the following structure:
356
+     *     [ $appId =>
357
+     *         [ $key => $value ]
358
+     *     ]
359
+     */
360
+    private function getUserValues($userId) {
361
+        if (isset($this->userCache[$userId])) {
362
+            return $this->userCache[$userId];
363
+        }
364
+        if ($userId === null || $userId === '') {
365
+            $this->userCache[$userId]=array();
366
+            return $this->userCache[$userId];
367
+        }
368
+
369
+        // TODO - FIXME
370
+        $this->fixDIInit();
371
+
372
+        $data = array();
373
+        $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
374
+        $result = $this->connection->executeQuery($query, array($userId));
375
+        while ($row = $result->fetch()) {
376
+            $appId = $row['appid'];
377
+            if (!isset($data[$appId])) {
378
+                $data[$appId] = array();
379
+            }
380
+            $data[$appId][$row['configkey']] = $row['configvalue'];
381
+        }
382
+        $this->userCache[$userId] = $data;
383
+        return $data;
384
+    }
385
+
386
+    /**
387
+     * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
388
+     *
389
+     * @param string $appName app to get the value for
390
+     * @param string $key the key to get the value for
391
+     * @param array $userIds the user IDs to fetch the values for
392
+     * @return array Mapped values: userId => value
393
+     */
394
+    public function getUserValueForUsers($appName, $key, $userIds) {
395
+        // TODO - FIXME
396
+        $this->fixDIInit();
397
+
398
+        if (empty($userIds) || !is_array($userIds)) {
399
+            return array();
400
+        }
401
+
402
+        $chunkedUsers = array_chunk($userIds, 50, true);
403
+        $placeholders50 = implode(',', array_fill(0, 50, '?'));
404
+
405
+        $userValues = array();
406
+        foreach ($chunkedUsers as $chunk) {
407
+            $queryParams = $chunk;
408
+            // create [$app, $key, $chunkedUsers]
409
+            array_unshift($queryParams, $key);
410
+            array_unshift($queryParams, $appName);
411
+
412
+            $placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
413
+
414
+            $query    = 'SELECT `userid`, `configvalue` ' .
415
+                        'FROM `*PREFIX*preferences` ' .
416
+                        'WHERE `appid` = ? AND `configkey` = ? ' .
417
+                        'AND `userid` IN (' . $placeholders . ')';
418
+            $result = $this->connection->executeQuery($query, $queryParams);
419
+
420
+            while ($row = $result->fetch()) {
421
+                $userValues[$row['userid']] = $row['configvalue'];
422
+            }
423
+        }
424
+
425
+        return $userValues;
426
+    }
427
+
428
+    /**
429
+     * Determines the users that have the given value set for a specific app-key-pair
430
+     *
431
+     * @param string $appName the app to get the user for
432
+     * @param string $key the key to get the user for
433
+     * @param string $value the value to get the user for
434
+     * @return array of user IDs
435
+     */
436
+    public function getUsersForUserValue($appName, $key, $value) {
437
+        // TODO - FIXME
438
+        $this->fixDIInit();
439
+
440
+        $sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
441
+                'WHERE `appid` = ? AND `configkey` = ? ';
442
+
443
+        if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
444
+            //oracle hack: need to explicitly cast CLOB to CHAR for comparison
445
+            $sql .= 'AND to_char(`configvalue`) = ?';
446
+        } else {
447
+            $sql .= 'AND `configvalue` = ?';
448
+        }
449
+
450
+        $result = $this->connection->executeQuery($sql, array($appName, $key, $value));
451
+
452
+        $userIDs = array();
453
+        while ($row = $result->fetch()) {
454
+            $userIDs[] = $row['userid'];
455
+        }
456
+
457
+        return $userIDs;
458
+    }
459
+
460
+    public function getSystemConfig() {
461
+        return $this->systemConfig;
462
+    }
463 463
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
 	 * because the database connection was created with an uninitialized config
88 88
 	 */
89 89
 	private function fixDIInit() {
90
-		if($this->connection === null) {
90
+		if ($this->connection === null) {
91 91
 			$this->connection = \OC::$server->getDatabaseConnection();
92 92
 		}
93 93
 	}
@@ -218,9 +218,9 @@  discard block
 block discarded – undo
218 218
 		$prevValue = $this->getUserValue($userId, $appName, $key, null);
219 219
 
220 220
 		if ($prevValue !== null) {
221
-			if ($prevValue === (string)$value) {
221
+			if ($prevValue === (string) $value) {
222 222
 				return;
223
-			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
223
+			} else if ($preCondition !== null && $prevValue !== (string) $preCondition) {
224 224
 				throw new PreConditionNotMetException();
225 225
 			} else {
226 226
 				$qb = $this->connection->getQueryBuilder();
@@ -305,7 +305,7 @@  discard block
 block discarded – undo
305 305
 		// TODO - FIXME
306 306
 		$this->fixDIInit();
307 307
 
308
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
308
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
309 309
 				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
310 310
 		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
311 311
 
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
 		// TODO - FIXME
324 324
 		$this->fixDIInit();
325 325
 
326
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
326
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
327 327
 			'WHERE `userid` = ?';
328 328
 		$this->connection->executeUpdate($sql, array($userId));
329 329
 
@@ -339,7 +339,7 @@  discard block
 block discarded – undo
339 339
 		// TODO - FIXME
340 340
 		$this->fixDIInit();
341 341
 
342
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
342
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
343 343
 				'WHERE `appid` = ?';
344 344
 		$this->connection->executeUpdate($sql, array($appName));
345 345
 
@@ -362,7 +362,7 @@  discard block
 block discarded – undo
362 362
 			return $this->userCache[$userId];
363 363
 		}
364 364
 		if ($userId === null || $userId === '') {
365
-			$this->userCache[$userId]=array();
365
+			$this->userCache[$userId] = array();
366 366
 			return $this->userCache[$userId];
367 367
 		}
368 368
 
@@ -409,12 +409,12 @@  discard block
 block discarded – undo
409 409
 			array_unshift($queryParams, $key);
410 410
 			array_unshift($queryParams, $appName);
411 411
 
412
-			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
412
+			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 : implode(',', array_fill(0, sizeof($chunk), '?'));
413 413
 
414
-			$query    = 'SELECT `userid`, `configvalue` ' .
415
-						'FROM `*PREFIX*preferences` ' .
416
-						'WHERE `appid` = ? AND `configkey` = ? ' .
417
-						'AND `userid` IN (' . $placeholders . ')';
414
+			$query = 'SELECT `userid`, `configvalue` '.
415
+						'FROM `*PREFIX*preferences` '.
416
+						'WHERE `appid` = ? AND `configkey` = ? '.
417
+						'AND `userid` IN ('.$placeholders.')';
418 418
 			$result = $this->connection->executeQuery($query, $queryParams);
419 419
 
420 420
 			while ($row = $result->fetch()) {
@@ -437,10 +437,10 @@  discard block
 block discarded – undo
437 437
 		// TODO - FIXME
438 438
 		$this->fixDIInit();
439 439
 
440
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
440
+		$sql = 'SELECT `userid` FROM `*PREFIX*preferences` '.
441 441
 				'WHERE `appid` = ? AND `configkey` = ? ';
442 442
 
443
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
443
+		if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
444 444
 			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
445 445
 			$sql .= 'AND to_char(`configvalue`) = ?';
446 446
 		} else {
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 4 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.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -25,7 +25,6 @@
 block discarded – undo
25 25
 namespace OC\Comments;
26 26
 
27 27
 use Doctrine\DBAL\Exception\DriverException;
28
-use Doctrine\DBAL\Platforms\MySqlPlatform;
29 28
 use OCP\Comments\CommentsEvent;
30 29
 use OCP\Comments\IComment;
31 30
 use OCP\Comments\ICommentsEventHandler;
Please login to merge, or discard this patch.
Indentation   +838 added lines, -838 removed lines patch added patch discarded remove patch
@@ -39,842 +39,842 @@
 block discarded – undo
39 39
 
40 40
 class Manager implements ICommentsManager {
41 41
 
42
-	/** @var  IDBConnection */
43
-	protected $dbConn;
44
-
45
-	/** @var  ILogger */
46
-	protected $logger;
47
-
48
-	/** @var IConfig */
49
-	protected $config;
50
-
51
-	/** @var IComment[] */
52
-	protected $commentsCache = [];
53
-
54
-	/** @var  \Closure[] */
55
-	protected $eventHandlerClosures = [];
56
-
57
-	/** @var  ICommentsEventHandler[] */
58
-	protected $eventHandlers = [];
59
-
60
-	/** @var \Closure[] */
61
-	protected $displayNameResolvers = [];
62
-
63
-	/**
64
-	 * Manager constructor.
65
-	 *
66
-	 * @param IDBConnection $dbConn
67
-	 * @param ILogger $logger
68
-	 * @param IConfig $config
69
-	 */
70
-	public function __construct(
71
-		IDBConnection $dbConn,
72
-		ILogger $logger,
73
-		IConfig $config
74
-	) {
75
-		$this->dbConn = $dbConn;
76
-		$this->logger = $logger;
77
-		$this->config = $config;
78
-	}
79
-
80
-	/**
81
-	 * converts data base data into PHP native, proper types as defined by
82
-	 * IComment interface.
83
-	 *
84
-	 * @param array $data
85
-	 * @return array
86
-	 */
87
-	protected function normalizeDatabaseData(array $data) {
88
-		$data['id'] = strval($data['id']);
89
-		$data['parent_id'] = strval($data['parent_id']);
90
-		$data['topmost_parent_id'] = strval($data['topmost_parent_id']);
91
-		$data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
92
-		if (!is_null($data['latest_child_timestamp'])) {
93
-			$data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
94
-		}
95
-		$data['children_count'] = intval($data['children_count']);
96
-		return $data;
97
-	}
98
-
99
-	/**
100
-	 * prepares a comment for an insert or update operation after making sure
101
-	 * all necessary fields have a value assigned.
102
-	 *
103
-	 * @param IComment $comment
104
-	 * @return IComment returns the same updated IComment instance as provided
105
-	 *                  by parameter for convenience
106
-	 * @throws \UnexpectedValueException
107
-	 */
108
-	protected function prepareCommentForDatabaseWrite(IComment $comment) {
109
-		if (!$comment->getActorType()
110
-			|| !$comment->getActorId()
111
-			|| !$comment->getObjectType()
112
-			|| !$comment->getObjectId()
113
-			|| !$comment->getVerb()
114
-		) {
115
-			throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
116
-		}
117
-
118
-		if ($comment->getId() === '') {
119
-			$comment->setChildrenCount(0);
120
-			$comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
121
-			$comment->setLatestChildDateTime(null);
122
-		}
123
-
124
-		if (is_null($comment->getCreationDateTime())) {
125
-			$comment->setCreationDateTime(new \DateTime());
126
-		}
127
-
128
-		if ($comment->getParentId() !== '0') {
129
-			$comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
130
-		} else {
131
-			$comment->setTopmostParentId('0');
132
-		}
133
-
134
-		$this->cache($comment);
135
-
136
-		return $comment;
137
-	}
138
-
139
-	/**
140
-	 * returns the topmost parent id of a given comment identified by ID
141
-	 *
142
-	 * @param string $id
143
-	 * @return string
144
-	 * @throws NotFoundException
145
-	 */
146
-	protected function determineTopmostParentId($id) {
147
-		$comment = $this->get($id);
148
-		if ($comment->getParentId() === '0') {
149
-			return $comment->getId();
150
-		} else {
151
-			return $this->determineTopmostParentId($comment->getId());
152
-		}
153
-	}
154
-
155
-	/**
156
-	 * updates child information of a comment
157
-	 *
158
-	 * @param string $id
159
-	 * @param \DateTime $cDateTime the date time of the most recent child
160
-	 * @throws NotFoundException
161
-	 */
162
-	protected function updateChildrenInformation($id, \DateTime $cDateTime) {
163
-		$qb = $this->dbConn->getQueryBuilder();
164
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
165
-			->from('comments')
166
-			->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
167
-			->setParameter('id', $id);
168
-
169
-		$resultStatement = $query->execute();
170
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
171
-		$resultStatement->closeCursor();
172
-		$children = intval($data[0]);
173
-
174
-		$comment = $this->get($id);
175
-		$comment->setChildrenCount($children);
176
-		$comment->setLatestChildDateTime($cDateTime);
177
-		$this->save($comment);
178
-	}
179
-
180
-	/**
181
-	 * Tests whether actor or object type and id parameters are acceptable.
182
-	 * Throws exception if not.
183
-	 *
184
-	 * @param string $role
185
-	 * @param string $type
186
-	 * @param string $id
187
-	 * @throws \InvalidArgumentException
188
-	 */
189
-	protected function checkRoleParameters($role, $type, $id) {
190
-		if (
191
-			!is_string($type) || empty($type)
192
-			|| !is_string($id) || empty($id)
193
-		) {
194
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
195
-		}
196
-	}
197
-
198
-	/**
199
-	 * run-time caches a comment
200
-	 *
201
-	 * @param IComment $comment
202
-	 */
203
-	protected function cache(IComment $comment) {
204
-		$id = $comment->getId();
205
-		if (empty($id)) {
206
-			return;
207
-		}
208
-		$this->commentsCache[strval($id)] = $comment;
209
-	}
210
-
211
-	/**
212
-	 * removes an entry from the comments run time cache
213
-	 *
214
-	 * @param mixed $id the comment's id
215
-	 */
216
-	protected function uncache($id) {
217
-		$id = strval($id);
218
-		if (isset($this->commentsCache[$id])) {
219
-			unset($this->commentsCache[$id]);
220
-		}
221
-	}
222
-
223
-	/**
224
-	 * returns a comment instance
225
-	 *
226
-	 * @param string $id the ID of the comment
227
-	 * @return IComment
228
-	 * @throws NotFoundException
229
-	 * @throws \InvalidArgumentException
230
-	 * @since 9.0.0
231
-	 */
232
-	public function get($id) {
233
-		if (intval($id) === 0) {
234
-			throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
235
-		}
236
-
237
-		if (isset($this->commentsCache[$id])) {
238
-			return $this->commentsCache[$id];
239
-		}
240
-
241
-		$qb = $this->dbConn->getQueryBuilder();
242
-		$resultStatement = $qb->select('*')
243
-			->from('comments')
244
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
245
-			->setParameter('id', $id, IQueryBuilder::PARAM_INT)
246
-			->execute();
247
-
248
-		$data = $resultStatement->fetch();
249
-		$resultStatement->closeCursor();
250
-		if (!$data) {
251
-			throw new NotFoundException();
252
-		}
253
-
254
-		$comment = new Comment($this->normalizeDatabaseData($data));
255
-		$this->cache($comment);
256
-		return $comment;
257
-	}
258
-
259
-	/**
260
-	 * returns the comment specified by the id and all it's child comments.
261
-	 * At this point of time, we do only support one level depth.
262
-	 *
263
-	 * @param string $id
264
-	 * @param int $limit max number of entries to return, 0 returns all
265
-	 * @param int $offset the start entry
266
-	 * @return array
267
-	 * @since 9.0.0
268
-	 *
269
-	 * The return array looks like this
270
-	 * [
271
-	 *   'comment' => IComment, // root comment
272
-	 *   'replies' =>
273
-	 *   [
274
-	 *     0 =>
275
-	 *     [
276
-	 *       'comment' => IComment,
277
-	 *       'replies' => []
278
-	 *     ]
279
-	 *     1 =>
280
-	 *     [
281
-	 *       'comment' => IComment,
282
-	 *       'replies'=> []
283
-	 *     ],
284
-	 *     …
285
-	 *   ]
286
-	 * ]
287
-	 */
288
-	public function getTree($id, $limit = 0, $offset = 0) {
289
-		$tree = [];
290
-		$tree['comment'] = $this->get($id);
291
-		$tree['replies'] = [];
292
-
293
-		$qb = $this->dbConn->getQueryBuilder();
294
-		$query = $qb->select('*')
295
-			->from('comments')
296
-			->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
297
-			->orderBy('creation_timestamp', 'DESC')
298
-			->setParameter('id', $id);
299
-
300
-		if ($limit > 0) {
301
-			$query->setMaxResults($limit);
302
-		}
303
-		if ($offset > 0) {
304
-			$query->setFirstResult($offset);
305
-		}
306
-
307
-		$resultStatement = $query->execute();
308
-		while ($data = $resultStatement->fetch()) {
309
-			$comment = new Comment($this->normalizeDatabaseData($data));
310
-			$this->cache($comment);
311
-			$tree['replies'][] = [
312
-				'comment' => $comment,
313
-				'replies' => []
314
-			];
315
-		}
316
-		$resultStatement->closeCursor();
317
-
318
-		return $tree;
319
-	}
320
-
321
-	/**
322
-	 * returns comments for a specific object (e.g. a file).
323
-	 *
324
-	 * The sort order is always newest to oldest.
325
-	 *
326
-	 * @param string $objectType the object type, e.g. 'files'
327
-	 * @param string $objectId the id of the object
328
-	 * @param int $limit optional, number of maximum comments to be returned. if
329
-	 * not specified, all comments are returned.
330
-	 * @param int $offset optional, starting point
331
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
332
-	 * that may be returned
333
-	 * @return IComment[]
334
-	 * @since 9.0.0
335
-	 */
336
-	public function getForObject(
337
-		$objectType,
338
-		$objectId,
339
-		$limit = 0,
340
-		$offset = 0,
341
-		\DateTime $notOlderThan = null
342
-	) {
343
-		$comments = [];
344
-
345
-		$qb = $this->dbConn->getQueryBuilder();
346
-		$query = $qb->select('*')
347
-			->from('comments')
348
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
349
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
350
-			->orderBy('creation_timestamp', 'DESC')
351
-			->setParameter('type', $objectType)
352
-			->setParameter('id', $objectId);
353
-
354
-		if ($limit > 0) {
355
-			$query->setMaxResults($limit);
356
-		}
357
-		if ($offset > 0) {
358
-			$query->setFirstResult($offset);
359
-		}
360
-		if (!is_null($notOlderThan)) {
361
-			$query
362
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
363
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
364
-		}
365
-
366
-		$resultStatement = $query->execute();
367
-		while ($data = $resultStatement->fetch()) {
368
-			$comment = new Comment($this->normalizeDatabaseData($data));
369
-			$this->cache($comment);
370
-			$comments[] = $comment;
371
-		}
372
-		$resultStatement->closeCursor();
373
-
374
-		return $comments;
375
-	}
376
-
377
-	/**
378
-	 * @param $objectType string the object type, e.g. 'files'
379
-	 * @param $objectId string the id of the object
380
-	 * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
381
-	 * that may be returned
382
-	 * @return Int
383
-	 * @since 9.0.0
384
-	 */
385
-	public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
386
-		$qb = $this->dbConn->getQueryBuilder();
387
-		$query = $qb->select($qb->createFunction('COUNT(`id`)'))
388
-			->from('comments')
389
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
390
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
391
-			->setParameter('type', $objectType)
392
-			->setParameter('id', $objectId);
393
-
394
-		if (!is_null($notOlderThan)) {
395
-			$query
396
-				->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
397
-				->setParameter('notOlderThan', $notOlderThan, 'datetime');
398
-		}
399
-
400
-		$resultStatement = $query->execute();
401
-		$data = $resultStatement->fetch(\PDO::FETCH_NUM);
402
-		$resultStatement->closeCursor();
403
-		return intval($data[0]);
404
-	}
405
-
406
-	/**
407
-	 * Get the number of unread comments for all files in a folder
408
-	 *
409
-	 * @param int $folderId
410
-	 * @param IUser $user
411
-	 * @return array [$fileId => $unreadCount]
412
-	 */
413
-	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
414
-		$qb = $this->dbConn->getQueryBuilder();
415
-		$query = $qb->select('fileid', $qb->createFunction(
416
-			'COUNT(' . $qb->getColumnName('c.id') . ')')
417
-		)->from('comments', 'c')
418
-			->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
419
-				$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
420
-				$qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
421
-			))
422
-			->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
423
-				$qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
424
-				$qb->expr()->eq('m.object_id', 'c.object_id'),
425
-				$qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
426
-			))
427
-			->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
428
-			->andWhere($qb->expr()->orX(
429
-				$qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
430
-				$qb->expr()->isNull('marker_datetime')
431
-			))
432
-			->groupBy('f.fileid');
433
-
434
-		$resultStatement = $query->execute();
435
-		return array_map(function ($count) {
436
-			return (int)$count;
437
-		}, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR));
438
-	}
439
-
440
-	/**
441
-	 * creates a new comment and returns it. At this point of time, it is not
442
-	 * saved in the used data storage. Use save() after setting other fields
443
-	 * of the comment (e.g. message or verb).
444
-	 *
445
-	 * @param string $actorType the actor type (e.g. 'users')
446
-	 * @param string $actorId a user id
447
-	 * @param string $objectType the object type the comment is attached to
448
-	 * @param string $objectId the object id the comment is attached to
449
-	 * @return IComment
450
-	 * @since 9.0.0
451
-	 */
452
-	public function create($actorType, $actorId, $objectType, $objectId) {
453
-		$comment = new Comment();
454
-		$comment
455
-			->setActor($actorType, $actorId)
456
-			->setObject($objectType, $objectId);
457
-		return $comment;
458
-	}
459
-
460
-	/**
461
-	 * permanently deletes the comment specified by the ID
462
-	 *
463
-	 * When the comment has child comments, their parent ID will be changed to
464
-	 * the parent ID of the item that is to be deleted.
465
-	 *
466
-	 * @param string $id
467
-	 * @return bool
468
-	 * @throws \InvalidArgumentException
469
-	 * @since 9.0.0
470
-	 */
471
-	public function delete($id) {
472
-		if (!is_string($id)) {
473
-			throw new \InvalidArgumentException('Parameter must be string');
474
-		}
475
-
476
-		try {
477
-			$comment = $this->get($id);
478
-		} catch (\Exception $e) {
479
-			// Ignore exceptions, we just don't fire a hook then
480
-			$comment = null;
481
-		}
482
-
483
-		$qb = $this->dbConn->getQueryBuilder();
484
-		$query = $qb->delete('comments')
485
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
486
-			->setParameter('id', $id);
487
-
488
-		try {
489
-			$affectedRows = $query->execute();
490
-			$this->uncache($id);
491
-		} catch (DriverException $e) {
492
-			$this->logger->logException($e, ['app' => 'core_comments']);
493
-			return false;
494
-		}
495
-
496
-		if ($affectedRows > 0 && $comment instanceof IComment) {
497
-			$this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
498
-		}
499
-
500
-		return ($affectedRows > 0);
501
-	}
502
-
503
-	/**
504
-	 * saves the comment permanently
505
-	 *
506
-	 * if the supplied comment has an empty ID, a new entry comment will be
507
-	 * saved and the instance updated with the new ID.
508
-	 *
509
-	 * Otherwise, an existing comment will be updated.
510
-	 *
511
-	 * Throws NotFoundException when a comment that is to be updated does not
512
-	 * exist anymore at this point of time.
513
-	 *
514
-	 * @param IComment $comment
515
-	 * @return bool
516
-	 * @throws NotFoundException
517
-	 * @since 9.0.0
518
-	 */
519
-	public function save(IComment $comment) {
520
-		if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
521
-			$result = $this->insert($comment);
522
-		} else {
523
-			$result = $this->update($comment);
524
-		}
525
-
526
-		if ($result && !!$comment->getParentId()) {
527
-			$this->updateChildrenInformation(
528
-				$comment->getParentId(),
529
-				$comment->getCreationDateTime()
530
-			);
531
-			$this->cache($comment);
532
-		}
533
-
534
-		return $result;
535
-	}
536
-
537
-	/**
538
-	 * inserts the provided comment in the database
539
-	 *
540
-	 * @param IComment $comment
541
-	 * @return bool
542
-	 */
543
-	protected function insert(IComment &$comment) {
544
-		$qb = $this->dbConn->getQueryBuilder();
545
-		$affectedRows = $qb
546
-			->insert('comments')
547
-			->values([
548
-				'parent_id' => $qb->createNamedParameter($comment->getParentId()),
549
-				'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
550
-				'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
551
-				'actor_type' => $qb->createNamedParameter($comment->getActorType()),
552
-				'actor_id' => $qb->createNamedParameter($comment->getActorId()),
553
-				'message' => $qb->createNamedParameter($comment->getMessage()),
554
-				'verb' => $qb->createNamedParameter($comment->getVerb()),
555
-				'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
556
-				'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
557
-				'object_type' => $qb->createNamedParameter($comment->getObjectType()),
558
-				'object_id' => $qb->createNamedParameter($comment->getObjectId()),
559
-			])
560
-			->execute();
561
-
562
-		if ($affectedRows > 0) {
563
-			$comment->setId(strval($qb->getLastInsertId()));
564
-			$this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
565
-		}
566
-
567
-		return $affectedRows > 0;
568
-	}
569
-
570
-	/**
571
-	 * updates a Comment data row
572
-	 *
573
-	 * @param IComment $comment
574
-	 * @return bool
575
-	 * @throws NotFoundException
576
-	 */
577
-	protected function update(IComment $comment) {
578
-		// for properly working preUpdate Events we need the old comments as is
579
-		// in the DB and overcome caching. Also avoid that outdated information stays.
580
-		$this->uncache($comment->getId());
581
-		$this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
582
-		$this->uncache($comment->getId());
583
-
584
-		$qb = $this->dbConn->getQueryBuilder();
585
-		$affectedRows = $qb
586
-			->update('comments')
587
-			->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
588
-			->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
589
-			->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
590
-			->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
591
-			->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
592
-			->set('message', $qb->createNamedParameter($comment->getMessage()))
593
-			->set('verb', $qb->createNamedParameter($comment->getVerb()))
594
-			->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
595
-			->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
596
-			->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
597
-			->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
598
-			->where($qb->expr()->eq('id', $qb->createParameter('id')))
599
-			->setParameter('id', $comment->getId())
600
-			->execute();
601
-
602
-		if ($affectedRows === 0) {
603
-			throw new NotFoundException('Comment to update does ceased to exist');
604
-		}
605
-
606
-		$this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
607
-
608
-		return $affectedRows > 0;
609
-	}
610
-
611
-	/**
612
-	 * removes references to specific actor (e.g. on user delete) of a comment.
613
-	 * The comment itself must not get lost/deleted.
614
-	 *
615
-	 * @param string $actorType the actor type (e.g. 'users')
616
-	 * @param string $actorId a user id
617
-	 * @return boolean
618
-	 * @since 9.0.0
619
-	 */
620
-	public function deleteReferencesOfActor($actorType, $actorId) {
621
-		$this->checkRoleParameters('Actor', $actorType, $actorId);
622
-
623
-		$qb = $this->dbConn->getQueryBuilder();
624
-		$affectedRows = $qb
625
-			->update('comments')
626
-			->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
627
-			->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
628
-			->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
629
-			->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
630
-			->setParameter('type', $actorType)
631
-			->setParameter('id', $actorId)
632
-			->execute();
633
-
634
-		$this->commentsCache = [];
635
-
636
-		return is_int($affectedRows);
637
-	}
638
-
639
-	/**
640
-	 * deletes all comments made of a specific object (e.g. on file delete)
641
-	 *
642
-	 * @param string $objectType the object type (e.g. 'files')
643
-	 * @param string $objectId e.g. the file id
644
-	 * @return boolean
645
-	 * @since 9.0.0
646
-	 */
647
-	public function deleteCommentsAtObject($objectType, $objectId) {
648
-		$this->checkRoleParameters('Object', $objectType, $objectId);
649
-
650
-		$qb = $this->dbConn->getQueryBuilder();
651
-		$affectedRows = $qb
652
-			->delete('comments')
653
-			->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
654
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
655
-			->setParameter('type', $objectType)
656
-			->setParameter('id', $objectId)
657
-			->execute();
658
-
659
-		$this->commentsCache = [];
660
-
661
-		return is_int($affectedRows);
662
-	}
663
-
664
-	/**
665
-	 * deletes the read markers for the specified user
666
-	 *
667
-	 * @param \OCP\IUser $user
668
-	 * @return bool
669
-	 * @since 9.0.0
670
-	 */
671
-	public function deleteReadMarksFromUser(IUser $user) {
672
-		$qb = $this->dbConn->getQueryBuilder();
673
-		$query = $qb->delete('comments_read_markers')
674
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
675
-			->setParameter('user_id', $user->getUID());
676
-
677
-		try {
678
-			$affectedRows = $query->execute();
679
-		} catch (DriverException $e) {
680
-			$this->logger->logException($e, ['app' => 'core_comments']);
681
-			return false;
682
-		}
683
-		return ($affectedRows > 0);
684
-	}
685
-
686
-	/**
687
-	 * sets the read marker for a given file to the specified date for the
688
-	 * provided user
689
-	 *
690
-	 * @param string $objectType
691
-	 * @param string $objectId
692
-	 * @param \DateTime $dateTime
693
-	 * @param IUser $user
694
-	 * @since 9.0.0
695
-	 */
696
-	public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
697
-		$this->checkRoleParameters('Object', $objectType, $objectId);
698
-
699
-		$qb = $this->dbConn->getQueryBuilder();
700
-		$values = [
701
-			'user_id' => $qb->createNamedParameter($user->getUID()),
702
-			'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
703
-			'object_type' => $qb->createNamedParameter($objectType),
704
-			'object_id' => $qb->createNamedParameter($objectId),
705
-		];
706
-
707
-		// Strategy: try to update, if this does not return affected rows, do an insert.
708
-		$affectedRows = $qb
709
-			->update('comments_read_markers')
710
-			->set('user_id', $values['user_id'])
711
-			->set('marker_datetime', $values['marker_datetime'])
712
-			->set('object_type', $values['object_type'])
713
-			->set('object_id', $values['object_id'])
714
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
715
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
716
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
717
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
718
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
719
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
720
-			->execute();
721
-
722
-		if ($affectedRows > 0) {
723
-			return;
724
-		}
725
-
726
-		$qb->insert('comments_read_markers')
727
-			->values($values)
728
-			->execute();
729
-	}
730
-
731
-	/**
732
-	 * returns the read marker for a given file to the specified date for the
733
-	 * provided user. It returns null, when the marker is not present, i.e.
734
-	 * no comments were marked as read.
735
-	 *
736
-	 * @param string $objectType
737
-	 * @param string $objectId
738
-	 * @param IUser $user
739
-	 * @return \DateTime|null
740
-	 * @since 9.0.0
741
-	 */
742
-	public function getReadMark($objectType, $objectId, IUser $user) {
743
-		$qb = $this->dbConn->getQueryBuilder();
744
-		$resultStatement = $qb->select('marker_datetime')
745
-			->from('comments_read_markers')
746
-			->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
747
-			->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
748
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
749
-			->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
750
-			->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
751
-			->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
752
-			->execute();
753
-
754
-		$data = $resultStatement->fetch();
755
-		$resultStatement->closeCursor();
756
-		if (!$data || is_null($data['marker_datetime'])) {
757
-			return null;
758
-		}
759
-
760
-		return new \DateTime($data['marker_datetime']);
761
-	}
762
-
763
-	/**
764
-	 * deletes the read markers on the specified object
765
-	 *
766
-	 * @param string $objectType
767
-	 * @param string $objectId
768
-	 * @return bool
769
-	 * @since 9.0.0
770
-	 */
771
-	public function deleteReadMarksOnObject($objectType, $objectId) {
772
-		$this->checkRoleParameters('Object', $objectType, $objectId);
773
-
774
-		$qb = $this->dbConn->getQueryBuilder();
775
-		$query = $qb->delete('comments_read_markers')
776
-			->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
777
-			->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
778
-			->setParameter('object_type', $objectType)
779
-			->setParameter('object_id', $objectId);
780
-
781
-		try {
782
-			$affectedRows = $query->execute();
783
-		} catch (DriverException $e) {
784
-			$this->logger->logException($e, ['app' => 'core_comments']);
785
-			return false;
786
-		}
787
-		return ($affectedRows > 0);
788
-	}
789
-
790
-	/**
791
-	 * registers an Entity to the manager, so event notifications can be send
792
-	 * to consumers of the comments infrastructure
793
-	 *
794
-	 * @param \Closure $closure
795
-	 */
796
-	public function registerEventHandler(\Closure $closure) {
797
-		$this->eventHandlerClosures[] = $closure;
798
-		$this->eventHandlers = [];
799
-	}
800
-
801
-	/**
802
-	 * registers a method that resolves an ID to a display name for a given type
803
-	 *
804
-	 * @param string $type
805
-	 * @param \Closure $closure
806
-	 * @throws \OutOfBoundsException
807
-	 * @since 11.0.0
808
-	 *
809
-	 * Only one resolver shall be registered per type. Otherwise a
810
-	 * \OutOfBoundsException has to thrown.
811
-	 */
812
-	public function registerDisplayNameResolver($type, \Closure $closure) {
813
-		if (!is_string($type)) {
814
-			throw new \InvalidArgumentException('String expected.');
815
-		}
816
-		if (isset($this->displayNameResolvers[$type])) {
817
-			throw new \OutOfBoundsException('Displayname resolver for this type already registered');
818
-		}
819
-		$this->displayNameResolvers[$type] = $closure;
820
-	}
821
-
822
-	/**
823
-	 * resolves a given ID of a given Type to a display name.
824
-	 *
825
-	 * @param string $type
826
-	 * @param string $id
827
-	 * @return string
828
-	 * @throws \OutOfBoundsException
829
-	 * @since 11.0.0
830
-	 *
831
-	 * If a provided type was not registered, an \OutOfBoundsException shall
832
-	 * be thrown. It is upon the resolver discretion what to return of the
833
-	 * provided ID is unknown. It must be ensured that a string is returned.
834
-	 */
835
-	public function resolveDisplayName($type, $id) {
836
-		if (!is_string($type)) {
837
-			throw new \InvalidArgumentException('String expected.');
838
-		}
839
-		if (!isset($this->displayNameResolvers[$type])) {
840
-			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
841
-		}
842
-		return (string)$this->displayNameResolvers[$type]($id);
843
-	}
844
-
845
-	/**
846
-	 * returns valid, registered entities
847
-	 *
848
-	 * @return \OCP\Comments\ICommentsEventHandler[]
849
-	 */
850
-	private function getEventHandlers() {
851
-		if (!empty($this->eventHandlers)) {
852
-			return $this->eventHandlers;
853
-		}
854
-
855
-		$this->eventHandlers = [];
856
-		foreach ($this->eventHandlerClosures as $name => $closure) {
857
-			$entity = $closure();
858
-			if (!($entity instanceof ICommentsEventHandler)) {
859
-				throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
860
-			}
861
-			$this->eventHandlers[$name] = $entity;
862
-		}
863
-
864
-		return $this->eventHandlers;
865
-	}
866
-
867
-	/**
868
-	 * sends notifications to the registered entities
869
-	 *
870
-	 * @param $eventType
871
-	 * @param IComment $comment
872
-	 */
873
-	private function sendEvent($eventType, IComment $comment) {
874
-		$entities = $this->getEventHandlers();
875
-		$event = new CommentsEvent($eventType, $comment);
876
-		foreach ($entities as $entity) {
877
-			$entity->handle($event);
878
-		}
879
-	}
42
+    /** @var  IDBConnection */
43
+    protected $dbConn;
44
+
45
+    /** @var  ILogger */
46
+    protected $logger;
47
+
48
+    /** @var IConfig */
49
+    protected $config;
50
+
51
+    /** @var IComment[] */
52
+    protected $commentsCache = [];
53
+
54
+    /** @var  \Closure[] */
55
+    protected $eventHandlerClosures = [];
56
+
57
+    /** @var  ICommentsEventHandler[] */
58
+    protected $eventHandlers = [];
59
+
60
+    /** @var \Closure[] */
61
+    protected $displayNameResolvers = [];
62
+
63
+    /**
64
+     * Manager constructor.
65
+     *
66
+     * @param IDBConnection $dbConn
67
+     * @param ILogger $logger
68
+     * @param IConfig $config
69
+     */
70
+    public function __construct(
71
+        IDBConnection $dbConn,
72
+        ILogger $logger,
73
+        IConfig $config
74
+    ) {
75
+        $this->dbConn = $dbConn;
76
+        $this->logger = $logger;
77
+        $this->config = $config;
78
+    }
79
+
80
+    /**
81
+     * converts data base data into PHP native, proper types as defined by
82
+     * IComment interface.
83
+     *
84
+     * @param array $data
85
+     * @return array
86
+     */
87
+    protected function normalizeDatabaseData(array $data) {
88
+        $data['id'] = strval($data['id']);
89
+        $data['parent_id'] = strval($data['parent_id']);
90
+        $data['topmost_parent_id'] = strval($data['topmost_parent_id']);
91
+        $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']);
92
+        if (!is_null($data['latest_child_timestamp'])) {
93
+            $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']);
94
+        }
95
+        $data['children_count'] = intval($data['children_count']);
96
+        return $data;
97
+    }
98
+
99
+    /**
100
+     * prepares a comment for an insert or update operation after making sure
101
+     * all necessary fields have a value assigned.
102
+     *
103
+     * @param IComment $comment
104
+     * @return IComment returns the same updated IComment instance as provided
105
+     *                  by parameter for convenience
106
+     * @throws \UnexpectedValueException
107
+     */
108
+    protected function prepareCommentForDatabaseWrite(IComment $comment) {
109
+        if (!$comment->getActorType()
110
+            || !$comment->getActorId()
111
+            || !$comment->getObjectType()
112
+            || !$comment->getObjectId()
113
+            || !$comment->getVerb()
114
+        ) {
115
+            throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving');
116
+        }
117
+
118
+        if ($comment->getId() === '') {
119
+            $comment->setChildrenCount(0);
120
+            $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC')));
121
+            $comment->setLatestChildDateTime(null);
122
+        }
123
+
124
+        if (is_null($comment->getCreationDateTime())) {
125
+            $comment->setCreationDateTime(new \DateTime());
126
+        }
127
+
128
+        if ($comment->getParentId() !== '0') {
129
+            $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId()));
130
+        } else {
131
+            $comment->setTopmostParentId('0');
132
+        }
133
+
134
+        $this->cache($comment);
135
+
136
+        return $comment;
137
+    }
138
+
139
+    /**
140
+     * returns the topmost parent id of a given comment identified by ID
141
+     *
142
+     * @param string $id
143
+     * @return string
144
+     * @throws NotFoundException
145
+     */
146
+    protected function determineTopmostParentId($id) {
147
+        $comment = $this->get($id);
148
+        if ($comment->getParentId() === '0') {
149
+            return $comment->getId();
150
+        } else {
151
+            return $this->determineTopmostParentId($comment->getId());
152
+        }
153
+    }
154
+
155
+    /**
156
+     * updates child information of a comment
157
+     *
158
+     * @param string $id
159
+     * @param \DateTime $cDateTime the date time of the most recent child
160
+     * @throws NotFoundException
161
+     */
162
+    protected function updateChildrenInformation($id, \DateTime $cDateTime) {
163
+        $qb = $this->dbConn->getQueryBuilder();
164
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
165
+            ->from('comments')
166
+            ->where($qb->expr()->eq('parent_id', $qb->createParameter('id')))
167
+            ->setParameter('id', $id);
168
+
169
+        $resultStatement = $query->execute();
170
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
171
+        $resultStatement->closeCursor();
172
+        $children = intval($data[0]);
173
+
174
+        $comment = $this->get($id);
175
+        $comment->setChildrenCount($children);
176
+        $comment->setLatestChildDateTime($cDateTime);
177
+        $this->save($comment);
178
+    }
179
+
180
+    /**
181
+     * Tests whether actor or object type and id parameters are acceptable.
182
+     * Throws exception if not.
183
+     *
184
+     * @param string $role
185
+     * @param string $type
186
+     * @param string $id
187
+     * @throws \InvalidArgumentException
188
+     */
189
+    protected function checkRoleParameters($role, $type, $id) {
190
+        if (
191
+            !is_string($type) || empty($type)
192
+            || !is_string($id) || empty($id)
193
+        ) {
194
+            throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
195
+        }
196
+    }
197
+
198
+    /**
199
+     * run-time caches a comment
200
+     *
201
+     * @param IComment $comment
202
+     */
203
+    protected function cache(IComment $comment) {
204
+        $id = $comment->getId();
205
+        if (empty($id)) {
206
+            return;
207
+        }
208
+        $this->commentsCache[strval($id)] = $comment;
209
+    }
210
+
211
+    /**
212
+     * removes an entry from the comments run time cache
213
+     *
214
+     * @param mixed $id the comment's id
215
+     */
216
+    protected function uncache($id) {
217
+        $id = strval($id);
218
+        if (isset($this->commentsCache[$id])) {
219
+            unset($this->commentsCache[$id]);
220
+        }
221
+    }
222
+
223
+    /**
224
+     * returns a comment instance
225
+     *
226
+     * @param string $id the ID of the comment
227
+     * @return IComment
228
+     * @throws NotFoundException
229
+     * @throws \InvalidArgumentException
230
+     * @since 9.0.0
231
+     */
232
+    public function get($id) {
233
+        if (intval($id) === 0) {
234
+            throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.');
235
+        }
236
+
237
+        if (isset($this->commentsCache[$id])) {
238
+            return $this->commentsCache[$id];
239
+        }
240
+
241
+        $qb = $this->dbConn->getQueryBuilder();
242
+        $resultStatement = $qb->select('*')
243
+            ->from('comments')
244
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
245
+            ->setParameter('id', $id, IQueryBuilder::PARAM_INT)
246
+            ->execute();
247
+
248
+        $data = $resultStatement->fetch();
249
+        $resultStatement->closeCursor();
250
+        if (!$data) {
251
+            throw new NotFoundException();
252
+        }
253
+
254
+        $comment = new Comment($this->normalizeDatabaseData($data));
255
+        $this->cache($comment);
256
+        return $comment;
257
+    }
258
+
259
+    /**
260
+     * returns the comment specified by the id and all it's child comments.
261
+     * At this point of time, we do only support one level depth.
262
+     *
263
+     * @param string $id
264
+     * @param int $limit max number of entries to return, 0 returns all
265
+     * @param int $offset the start entry
266
+     * @return array
267
+     * @since 9.0.0
268
+     *
269
+     * The return array looks like this
270
+     * [
271
+     *   'comment' => IComment, // root comment
272
+     *   'replies' =>
273
+     *   [
274
+     *     0 =>
275
+     *     [
276
+     *       'comment' => IComment,
277
+     *       'replies' => []
278
+     *     ]
279
+     *     1 =>
280
+     *     [
281
+     *       'comment' => IComment,
282
+     *       'replies'=> []
283
+     *     ],
284
+     *     …
285
+     *   ]
286
+     * ]
287
+     */
288
+    public function getTree($id, $limit = 0, $offset = 0) {
289
+        $tree = [];
290
+        $tree['comment'] = $this->get($id);
291
+        $tree['replies'] = [];
292
+
293
+        $qb = $this->dbConn->getQueryBuilder();
294
+        $query = $qb->select('*')
295
+            ->from('comments')
296
+            ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id')))
297
+            ->orderBy('creation_timestamp', 'DESC')
298
+            ->setParameter('id', $id);
299
+
300
+        if ($limit > 0) {
301
+            $query->setMaxResults($limit);
302
+        }
303
+        if ($offset > 0) {
304
+            $query->setFirstResult($offset);
305
+        }
306
+
307
+        $resultStatement = $query->execute();
308
+        while ($data = $resultStatement->fetch()) {
309
+            $comment = new Comment($this->normalizeDatabaseData($data));
310
+            $this->cache($comment);
311
+            $tree['replies'][] = [
312
+                'comment' => $comment,
313
+                'replies' => []
314
+            ];
315
+        }
316
+        $resultStatement->closeCursor();
317
+
318
+        return $tree;
319
+    }
320
+
321
+    /**
322
+     * returns comments for a specific object (e.g. a file).
323
+     *
324
+     * The sort order is always newest to oldest.
325
+     *
326
+     * @param string $objectType the object type, e.g. 'files'
327
+     * @param string $objectId the id of the object
328
+     * @param int $limit optional, number of maximum comments to be returned. if
329
+     * not specified, all comments are returned.
330
+     * @param int $offset optional, starting point
331
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
332
+     * that may be returned
333
+     * @return IComment[]
334
+     * @since 9.0.0
335
+     */
336
+    public function getForObject(
337
+        $objectType,
338
+        $objectId,
339
+        $limit = 0,
340
+        $offset = 0,
341
+        \DateTime $notOlderThan = null
342
+    ) {
343
+        $comments = [];
344
+
345
+        $qb = $this->dbConn->getQueryBuilder();
346
+        $query = $qb->select('*')
347
+            ->from('comments')
348
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
349
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
350
+            ->orderBy('creation_timestamp', 'DESC')
351
+            ->setParameter('type', $objectType)
352
+            ->setParameter('id', $objectId);
353
+
354
+        if ($limit > 0) {
355
+            $query->setMaxResults($limit);
356
+        }
357
+        if ($offset > 0) {
358
+            $query->setFirstResult($offset);
359
+        }
360
+        if (!is_null($notOlderThan)) {
361
+            $query
362
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
363
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
364
+        }
365
+
366
+        $resultStatement = $query->execute();
367
+        while ($data = $resultStatement->fetch()) {
368
+            $comment = new Comment($this->normalizeDatabaseData($data));
369
+            $this->cache($comment);
370
+            $comments[] = $comment;
371
+        }
372
+        $resultStatement->closeCursor();
373
+
374
+        return $comments;
375
+    }
376
+
377
+    /**
378
+     * @param $objectType string the object type, e.g. 'files'
379
+     * @param $objectId string the id of the object
380
+     * @param \DateTime $notOlderThan optional, timestamp of the oldest comments
381
+     * that may be returned
382
+     * @return Int
383
+     * @since 9.0.0
384
+     */
385
+    public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) {
386
+        $qb = $this->dbConn->getQueryBuilder();
387
+        $query = $qb->select($qb->createFunction('COUNT(`id`)'))
388
+            ->from('comments')
389
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
390
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
391
+            ->setParameter('type', $objectType)
392
+            ->setParameter('id', $objectId);
393
+
394
+        if (!is_null($notOlderThan)) {
395
+            $query
396
+                ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan')))
397
+                ->setParameter('notOlderThan', $notOlderThan, 'datetime');
398
+        }
399
+
400
+        $resultStatement = $query->execute();
401
+        $data = $resultStatement->fetch(\PDO::FETCH_NUM);
402
+        $resultStatement->closeCursor();
403
+        return intval($data[0]);
404
+    }
405
+
406
+    /**
407
+     * Get the number of unread comments for all files in a folder
408
+     *
409
+     * @param int $folderId
410
+     * @param IUser $user
411
+     * @return array [$fileId => $unreadCount]
412
+     */
413
+    public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
414
+        $qb = $this->dbConn->getQueryBuilder();
415
+        $query = $qb->select('fileid', $qb->createFunction(
416
+            'COUNT(' . $qb->getColumnName('c.id') . ')')
417
+        )->from('comments', 'c')
418
+            ->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
419
+                $qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
420
+                $qb->expr()->eq('f.fileid', $qb->expr()->castColumn('c.object_id', IQueryBuilder::PARAM_INT))
421
+            ))
422
+            ->leftJoin('c', 'comments_read_markers', 'm', $qb->expr()->andX(
423
+                $qb->expr()->eq('m.object_type', $qb->createNamedParameter('files')),
424
+                $qb->expr()->eq('m.object_id', 'c.object_id'),
425
+                $qb->expr()->eq('m.user_id', $qb->createNamedParameter($user->getUID()))
426
+            ))
427
+            ->andWhere($qb->expr()->eq('f.parent', $qb->createNamedParameter($folderId)))
428
+            ->andWhere($qb->expr()->orX(
429
+                $qb->expr()->gt('c.creation_timestamp', 'marker_datetime'),
430
+                $qb->expr()->isNull('marker_datetime')
431
+            ))
432
+            ->groupBy('f.fileid');
433
+
434
+        $resultStatement = $query->execute();
435
+        return array_map(function ($count) {
436
+            return (int)$count;
437
+        }, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR));
438
+    }
439
+
440
+    /**
441
+     * creates a new comment and returns it. At this point of time, it is not
442
+     * saved in the used data storage. Use save() after setting other fields
443
+     * of the comment (e.g. message or verb).
444
+     *
445
+     * @param string $actorType the actor type (e.g. 'users')
446
+     * @param string $actorId a user id
447
+     * @param string $objectType the object type the comment is attached to
448
+     * @param string $objectId the object id the comment is attached to
449
+     * @return IComment
450
+     * @since 9.0.0
451
+     */
452
+    public function create($actorType, $actorId, $objectType, $objectId) {
453
+        $comment = new Comment();
454
+        $comment
455
+            ->setActor($actorType, $actorId)
456
+            ->setObject($objectType, $objectId);
457
+        return $comment;
458
+    }
459
+
460
+    /**
461
+     * permanently deletes the comment specified by the ID
462
+     *
463
+     * When the comment has child comments, their parent ID will be changed to
464
+     * the parent ID of the item that is to be deleted.
465
+     *
466
+     * @param string $id
467
+     * @return bool
468
+     * @throws \InvalidArgumentException
469
+     * @since 9.0.0
470
+     */
471
+    public function delete($id) {
472
+        if (!is_string($id)) {
473
+            throw new \InvalidArgumentException('Parameter must be string');
474
+        }
475
+
476
+        try {
477
+            $comment = $this->get($id);
478
+        } catch (\Exception $e) {
479
+            // Ignore exceptions, we just don't fire a hook then
480
+            $comment = null;
481
+        }
482
+
483
+        $qb = $this->dbConn->getQueryBuilder();
484
+        $query = $qb->delete('comments')
485
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
486
+            ->setParameter('id', $id);
487
+
488
+        try {
489
+            $affectedRows = $query->execute();
490
+            $this->uncache($id);
491
+        } catch (DriverException $e) {
492
+            $this->logger->logException($e, ['app' => 'core_comments']);
493
+            return false;
494
+        }
495
+
496
+        if ($affectedRows > 0 && $comment instanceof IComment) {
497
+            $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment);
498
+        }
499
+
500
+        return ($affectedRows > 0);
501
+    }
502
+
503
+    /**
504
+     * saves the comment permanently
505
+     *
506
+     * if the supplied comment has an empty ID, a new entry comment will be
507
+     * saved and the instance updated with the new ID.
508
+     *
509
+     * Otherwise, an existing comment will be updated.
510
+     *
511
+     * Throws NotFoundException when a comment that is to be updated does not
512
+     * exist anymore at this point of time.
513
+     *
514
+     * @param IComment $comment
515
+     * @return bool
516
+     * @throws NotFoundException
517
+     * @since 9.0.0
518
+     */
519
+    public function save(IComment $comment) {
520
+        if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') {
521
+            $result = $this->insert($comment);
522
+        } else {
523
+            $result = $this->update($comment);
524
+        }
525
+
526
+        if ($result && !!$comment->getParentId()) {
527
+            $this->updateChildrenInformation(
528
+                $comment->getParentId(),
529
+                $comment->getCreationDateTime()
530
+            );
531
+            $this->cache($comment);
532
+        }
533
+
534
+        return $result;
535
+    }
536
+
537
+    /**
538
+     * inserts the provided comment in the database
539
+     *
540
+     * @param IComment $comment
541
+     * @return bool
542
+     */
543
+    protected function insert(IComment &$comment) {
544
+        $qb = $this->dbConn->getQueryBuilder();
545
+        $affectedRows = $qb
546
+            ->insert('comments')
547
+            ->values([
548
+                'parent_id' => $qb->createNamedParameter($comment->getParentId()),
549
+                'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()),
550
+                'children_count' => $qb->createNamedParameter($comment->getChildrenCount()),
551
+                'actor_type' => $qb->createNamedParameter($comment->getActorType()),
552
+                'actor_id' => $qb->createNamedParameter($comment->getActorId()),
553
+                'message' => $qb->createNamedParameter($comment->getMessage()),
554
+                'verb' => $qb->createNamedParameter($comment->getVerb()),
555
+                'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'),
556
+                'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'),
557
+                'object_type' => $qb->createNamedParameter($comment->getObjectType()),
558
+                'object_id' => $qb->createNamedParameter($comment->getObjectId()),
559
+            ])
560
+            ->execute();
561
+
562
+        if ($affectedRows > 0) {
563
+            $comment->setId(strval($qb->getLastInsertId()));
564
+            $this->sendEvent(CommentsEvent::EVENT_ADD, $comment);
565
+        }
566
+
567
+        return $affectedRows > 0;
568
+    }
569
+
570
+    /**
571
+     * updates a Comment data row
572
+     *
573
+     * @param IComment $comment
574
+     * @return bool
575
+     * @throws NotFoundException
576
+     */
577
+    protected function update(IComment $comment) {
578
+        // for properly working preUpdate Events we need the old comments as is
579
+        // in the DB and overcome caching. Also avoid that outdated information stays.
580
+        $this->uncache($comment->getId());
581
+        $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId()));
582
+        $this->uncache($comment->getId());
583
+
584
+        $qb = $this->dbConn->getQueryBuilder();
585
+        $affectedRows = $qb
586
+            ->update('comments')
587
+            ->set('parent_id', $qb->createNamedParameter($comment->getParentId()))
588
+            ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId()))
589
+            ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount()))
590
+            ->set('actor_type', $qb->createNamedParameter($comment->getActorType()))
591
+            ->set('actor_id', $qb->createNamedParameter($comment->getActorId()))
592
+            ->set('message', $qb->createNamedParameter($comment->getMessage()))
593
+            ->set('verb', $qb->createNamedParameter($comment->getVerb()))
594
+            ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'))
595
+            ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'))
596
+            ->set('object_type', $qb->createNamedParameter($comment->getObjectType()))
597
+            ->set('object_id', $qb->createNamedParameter($comment->getObjectId()))
598
+            ->where($qb->expr()->eq('id', $qb->createParameter('id')))
599
+            ->setParameter('id', $comment->getId())
600
+            ->execute();
601
+
602
+        if ($affectedRows === 0) {
603
+            throw new NotFoundException('Comment to update does ceased to exist');
604
+        }
605
+
606
+        $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment);
607
+
608
+        return $affectedRows > 0;
609
+    }
610
+
611
+    /**
612
+     * removes references to specific actor (e.g. on user delete) of a comment.
613
+     * The comment itself must not get lost/deleted.
614
+     *
615
+     * @param string $actorType the actor type (e.g. 'users')
616
+     * @param string $actorId a user id
617
+     * @return boolean
618
+     * @since 9.0.0
619
+     */
620
+    public function deleteReferencesOfActor($actorType, $actorId) {
621
+        $this->checkRoleParameters('Actor', $actorType, $actorId);
622
+
623
+        $qb = $this->dbConn->getQueryBuilder();
624
+        $affectedRows = $qb
625
+            ->update('comments')
626
+            ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
627
+            ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER))
628
+            ->where($qb->expr()->eq('actor_type', $qb->createParameter('type')))
629
+            ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id')))
630
+            ->setParameter('type', $actorType)
631
+            ->setParameter('id', $actorId)
632
+            ->execute();
633
+
634
+        $this->commentsCache = [];
635
+
636
+        return is_int($affectedRows);
637
+    }
638
+
639
+    /**
640
+     * deletes all comments made of a specific object (e.g. on file delete)
641
+     *
642
+     * @param string $objectType the object type (e.g. 'files')
643
+     * @param string $objectId e.g. the file id
644
+     * @return boolean
645
+     * @since 9.0.0
646
+     */
647
+    public function deleteCommentsAtObject($objectType, $objectId) {
648
+        $this->checkRoleParameters('Object', $objectType, $objectId);
649
+
650
+        $qb = $this->dbConn->getQueryBuilder();
651
+        $affectedRows = $qb
652
+            ->delete('comments')
653
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('type')))
654
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id')))
655
+            ->setParameter('type', $objectType)
656
+            ->setParameter('id', $objectId)
657
+            ->execute();
658
+
659
+        $this->commentsCache = [];
660
+
661
+        return is_int($affectedRows);
662
+    }
663
+
664
+    /**
665
+     * deletes the read markers for the specified user
666
+     *
667
+     * @param \OCP\IUser $user
668
+     * @return bool
669
+     * @since 9.0.0
670
+     */
671
+    public function deleteReadMarksFromUser(IUser $user) {
672
+        $qb = $this->dbConn->getQueryBuilder();
673
+        $query = $qb->delete('comments_read_markers')
674
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
675
+            ->setParameter('user_id', $user->getUID());
676
+
677
+        try {
678
+            $affectedRows = $query->execute();
679
+        } catch (DriverException $e) {
680
+            $this->logger->logException($e, ['app' => 'core_comments']);
681
+            return false;
682
+        }
683
+        return ($affectedRows > 0);
684
+    }
685
+
686
+    /**
687
+     * sets the read marker for a given file to the specified date for the
688
+     * provided user
689
+     *
690
+     * @param string $objectType
691
+     * @param string $objectId
692
+     * @param \DateTime $dateTime
693
+     * @param IUser $user
694
+     * @since 9.0.0
695
+     */
696
+    public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) {
697
+        $this->checkRoleParameters('Object', $objectType, $objectId);
698
+
699
+        $qb = $this->dbConn->getQueryBuilder();
700
+        $values = [
701
+            'user_id' => $qb->createNamedParameter($user->getUID()),
702
+            'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'),
703
+            'object_type' => $qb->createNamedParameter($objectType),
704
+            'object_id' => $qb->createNamedParameter($objectId),
705
+        ];
706
+
707
+        // Strategy: try to update, if this does not return affected rows, do an insert.
708
+        $affectedRows = $qb
709
+            ->update('comments_read_markers')
710
+            ->set('user_id', $values['user_id'])
711
+            ->set('marker_datetime', $values['marker_datetime'])
712
+            ->set('object_type', $values['object_type'])
713
+            ->set('object_id', $values['object_id'])
714
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
715
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
716
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
717
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
718
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
719
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
720
+            ->execute();
721
+
722
+        if ($affectedRows > 0) {
723
+            return;
724
+        }
725
+
726
+        $qb->insert('comments_read_markers')
727
+            ->values($values)
728
+            ->execute();
729
+    }
730
+
731
+    /**
732
+     * returns the read marker for a given file to the specified date for the
733
+     * provided user. It returns null, when the marker is not present, i.e.
734
+     * no comments were marked as read.
735
+     *
736
+     * @param string $objectType
737
+     * @param string $objectId
738
+     * @param IUser $user
739
+     * @return \DateTime|null
740
+     * @since 9.0.0
741
+     */
742
+    public function getReadMark($objectType, $objectId, IUser $user) {
743
+        $qb = $this->dbConn->getQueryBuilder();
744
+        $resultStatement = $qb->select('marker_datetime')
745
+            ->from('comments_read_markers')
746
+            ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id')))
747
+            ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
748
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
749
+            ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR)
750
+            ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR)
751
+            ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR)
752
+            ->execute();
753
+
754
+        $data = $resultStatement->fetch();
755
+        $resultStatement->closeCursor();
756
+        if (!$data || is_null($data['marker_datetime'])) {
757
+            return null;
758
+        }
759
+
760
+        return new \DateTime($data['marker_datetime']);
761
+    }
762
+
763
+    /**
764
+     * deletes the read markers on the specified object
765
+     *
766
+     * @param string $objectType
767
+     * @param string $objectId
768
+     * @return bool
769
+     * @since 9.0.0
770
+     */
771
+    public function deleteReadMarksOnObject($objectType, $objectId) {
772
+        $this->checkRoleParameters('Object', $objectType, $objectId);
773
+
774
+        $qb = $this->dbConn->getQueryBuilder();
775
+        $query = $qb->delete('comments_read_markers')
776
+            ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type')))
777
+            ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id')))
778
+            ->setParameter('object_type', $objectType)
779
+            ->setParameter('object_id', $objectId);
780
+
781
+        try {
782
+            $affectedRows = $query->execute();
783
+        } catch (DriverException $e) {
784
+            $this->logger->logException($e, ['app' => 'core_comments']);
785
+            return false;
786
+        }
787
+        return ($affectedRows > 0);
788
+    }
789
+
790
+    /**
791
+     * registers an Entity to the manager, so event notifications can be send
792
+     * to consumers of the comments infrastructure
793
+     *
794
+     * @param \Closure $closure
795
+     */
796
+    public function registerEventHandler(\Closure $closure) {
797
+        $this->eventHandlerClosures[] = $closure;
798
+        $this->eventHandlers = [];
799
+    }
800
+
801
+    /**
802
+     * registers a method that resolves an ID to a display name for a given type
803
+     *
804
+     * @param string $type
805
+     * @param \Closure $closure
806
+     * @throws \OutOfBoundsException
807
+     * @since 11.0.0
808
+     *
809
+     * Only one resolver shall be registered per type. Otherwise a
810
+     * \OutOfBoundsException has to thrown.
811
+     */
812
+    public function registerDisplayNameResolver($type, \Closure $closure) {
813
+        if (!is_string($type)) {
814
+            throw new \InvalidArgumentException('String expected.');
815
+        }
816
+        if (isset($this->displayNameResolvers[$type])) {
817
+            throw new \OutOfBoundsException('Displayname resolver for this type already registered');
818
+        }
819
+        $this->displayNameResolvers[$type] = $closure;
820
+    }
821
+
822
+    /**
823
+     * resolves a given ID of a given Type to a display name.
824
+     *
825
+     * @param string $type
826
+     * @param string $id
827
+     * @return string
828
+     * @throws \OutOfBoundsException
829
+     * @since 11.0.0
830
+     *
831
+     * If a provided type was not registered, an \OutOfBoundsException shall
832
+     * be thrown. It is upon the resolver discretion what to return of the
833
+     * provided ID is unknown. It must be ensured that a string is returned.
834
+     */
835
+    public function resolveDisplayName($type, $id) {
836
+        if (!is_string($type)) {
837
+            throw new \InvalidArgumentException('String expected.');
838
+        }
839
+        if (!isset($this->displayNameResolvers[$type])) {
840
+            throw new \OutOfBoundsException('No Displayname resolver for this type registered');
841
+        }
842
+        return (string)$this->displayNameResolvers[$type]($id);
843
+    }
844
+
845
+    /**
846
+     * returns valid, registered entities
847
+     *
848
+     * @return \OCP\Comments\ICommentsEventHandler[]
849
+     */
850
+    private function getEventHandlers() {
851
+        if (!empty($this->eventHandlers)) {
852
+            return $this->eventHandlers;
853
+        }
854
+
855
+        $this->eventHandlers = [];
856
+        foreach ($this->eventHandlerClosures as $name => $closure) {
857
+            $entity = $closure();
858
+            if (!($entity instanceof ICommentsEventHandler)) {
859
+                throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface');
860
+            }
861
+            $this->eventHandlers[$name] = $entity;
862
+        }
863
+
864
+        return $this->eventHandlers;
865
+    }
866
+
867
+    /**
868
+     * sends notifications to the registered entities
869
+     *
870
+     * @param $eventType
871
+     * @param IComment $comment
872
+     */
873
+    private function sendEvent($eventType, IComment $comment) {
874
+        $entities = $this->getEventHandlers();
875
+        $event = new CommentsEvent($eventType, $comment);
876
+        foreach ($entities as $entity) {
877
+            $entity->handle($event);
878
+        }
879
+    }
880 880
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -191,7 +191,7 @@  discard block
 block discarded – undo
191 191
 			!is_string($type) || empty($type)
192 192
 			|| !is_string($id) || empty($id)
193 193
 		) {
194
-			throw new \InvalidArgumentException($role . ' parameters must be string and not empty');
194
+			throw new \InvalidArgumentException($role.' parameters must be string and not empty');
195 195
 		}
196 196
 	}
197 197
 
@@ -413,7 +413,7 @@  discard block
 block discarded – undo
413 413
 	public function getNumberOfUnreadCommentsForFolder($folderId, IUser $user) {
414 414
 		$qb = $this->dbConn->getQueryBuilder();
415 415
 		$query = $qb->select('fileid', $qb->createFunction(
416
-			'COUNT(' . $qb->getColumnName('c.id') . ')')
416
+			'COUNT('.$qb->getColumnName('c.id').')')
417 417
 		)->from('comments', 'c')
418 418
 			->innerJoin('c', 'filecache', 'f', $qb->expr()->andX(
419 419
 				$qb->expr()->eq('c.object_type', $qb->createNamedParameter('files')),
@@ -432,8 +432,8 @@  discard block
 block discarded – undo
432 432
 			->groupBy('f.fileid');
433 433
 
434 434
 		$resultStatement = $query->execute();
435
-		return array_map(function ($count) {
436
-			return (int)$count;
435
+		return array_map(function($count) {
436
+			return (int) $count;
437 437
 		}, $resultStatement->fetchAll(\PDO::FETCH_KEY_PAIR));
438 438
 	}
439 439
 
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
 	 * @param IComment $comment
541 541
 	 * @return bool
542 542
 	 */
543
-	protected function insert(IComment &$comment) {
543
+	protected function insert(IComment & $comment) {
544 544
 		$qb = $this->dbConn->getQueryBuilder();
545 545
 		$affectedRows = $qb
546 546
 			->insert('comments')
@@ -839,7 +839,7 @@  discard block
 block discarded – undo
839 839
 		if (!isset($this->displayNameResolvers[$type])) {
840 840
 			throw new \OutOfBoundsException('No Displayname resolver for this type registered');
841 841
 		}
842
-		return (string)$this->displayNameResolvers[$type]($id);
842
+		return (string) $this->displayNameResolvers[$type]($id);
843 843
 	}
844 844
 
845 845
 	/**
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.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@  discard block
 block discarded – undo
56 56
 			return parent::connect();
57 57
 		} catch (DBALException $e) {
58 58
 			// throw a new exception to prevent leaking info from the stacktrace
59
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
59
+			throw new DBALException('Failed to connect to the database: '.$e->getMessage(), $e->getCode());
60 60
 		}
61 61
 	}
62 62
 
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		// 0 is the method where we use `getCallerBacktrace`
105 105
 		// 1 is the target method which uses the method we want to log
106 106
 		if (isset($traces[1])) {
107
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
107
+			return $traces[1]['file'].':'.$traces[1]['line'];
108 108
 		}
109 109
 
110 110
 		return '';
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	 * @param int $offset
151 151
 	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
152 152
 	 */
153
-	public function prepare( $statement, $limit=null, $offset=null ) {
153
+	public function prepare($statement, $limit = null, $offset = null) {
154 154
 		if ($limit === -1) {
155 155
 			$limit = null;
156 156
 		}
@@ -161,7 +161,7 @@  discard block
 block discarded – undo
161 161
 		$statement = $this->replaceTablePrefix($statement);
162 162
 		$statement = $this->adapter->fixupStatement($statement);
163 163
 
164
-		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
164
+		if (\OC::$server->getSystemConfig()->getValue('log_query', false)) {
165 165
 			\OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
166 166
 		}
167 167
 		return parent::prepare($statement);
@@ -318,7 +318,7 @@  discard block
 block discarded – undo
318 318
 			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
319 319
 		}
320 320
 
321
-		$tableName = $this->tablePrefix . $tableName;
321
+		$tableName = $this->tablePrefix.$tableName;
322 322
 		$this->lockedTable = $tableName;
323 323
 		$this->adapter->lockTable($tableName);
324 324
 	}
@@ -339,11 +339,11 @@  discard block
 block discarded – undo
339 339
 	 * @return string
340 340
 	 */
341 341
 	public function getError() {
342
-		$msg = $this->errorCode() . ': ';
342
+		$msg = $this->errorCode().': ';
343 343
 		$errorInfo = $this->errorInfo();
344 344
 		if (is_array($errorInfo)) {
345
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
346
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
345
+			$msg .= 'SQLSTATE = '.$errorInfo[0].', ';
346
+			$msg .= 'Driver Code = '.$errorInfo[1].', ';
347 347
 			$msg .= 'Driver Message = '.$errorInfo[2];
348 348
 		}
349 349
 		return $msg;
@@ -355,9 +355,9 @@  discard block
 block discarded – undo
355 355
 	 * @param string $table table name without the prefix
356 356
 	 */
357 357
 	public function dropTable($table) {
358
-		$table = $this->tablePrefix . trim($table);
358
+		$table = $this->tablePrefix.trim($table);
359 359
 		$schema = $this->getSchemaManager();
360
-		if($schema->tablesExist(array($table))) {
360
+		if ($schema->tablesExist(array($table))) {
361 361
 			$schema->dropTable($table);
362 362
 		}
363 363
 	}
@@ -368,8 +368,8 @@  discard block
 block discarded – undo
368 368
 	 * @param string $table table name without the prefix
369 369
 	 * @return bool
370 370
 	 */
371
-	public function tableExists($table){
372
-		$table = $this->tablePrefix . trim($table);
371
+	public function tableExists($table) {
372
+		$table = $this->tablePrefix.trim($table);
373 373
 		$schema = $this->getSchemaManager();
374 374
 		return $schema->tablesExist(array($table));
375 375
 	}
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 	 * @return string
381 381
 	 */
382 382
 	protected function replaceTablePrefix($statement) {
383
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
383
+		return str_replace('*PREFIX*', $this->tablePrefix, $statement);
384 384
 	}
385 385
 
386 386
 	/**
Please login to merge, or discard this patch.
Indentation   +380 added lines, -380 removed lines patch added patch discarded remove patch
@@ -41,384 +41,384 @@
 block discarded – undo
41 41
 use OCP\PreConditionNotMetException;
42 42
 
43 43
 class Connection extends \Doctrine\DBAL\Connection implements IDBConnection {
44
-	/**
45
-	 * @var string $tablePrefix
46
-	 */
47
-	protected $tablePrefix;
48
-
49
-	/**
50
-	 * @var \OC\DB\Adapter $adapter
51
-	 */
52
-	protected $adapter;
53
-
54
-	protected $lockedTable = null;
55
-
56
-	public function connect() {
57
-		try {
58
-			return parent::connect();
59
-		} catch (DBALException $e) {
60
-			// throw a new exception to prevent leaking info from the stacktrace
61
-			throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
62
-		}
63
-	}
64
-
65
-	/**
66
-	 * Returns a QueryBuilder for the connection.
67
-	 *
68
-	 * @return \OCP\DB\QueryBuilder\IQueryBuilder
69
-	 */
70
-	public function getQueryBuilder() {
71
-		return new QueryBuilder(
72
-			$this,
73
-			\OC::$server->getSystemConfig(),
74
-			\OC::$server->getLogger()
75
-		);
76
-	}
77
-
78
-	/**
79
-	 * Gets the QueryBuilder for the connection.
80
-	 *
81
-	 * @return \Doctrine\DBAL\Query\QueryBuilder
82
-	 * @deprecated please use $this->getQueryBuilder() instead
83
-	 */
84
-	public function createQueryBuilder() {
85
-		$backtrace = $this->getCallerBacktrace();
86
-		\OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
87
-		return parent::createQueryBuilder();
88
-	}
89
-
90
-	/**
91
-	 * Gets the ExpressionBuilder for the connection.
92
-	 *
93
-	 * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
94
-	 * @deprecated please use $this->getQueryBuilder()->expr() instead
95
-	 */
96
-	public function getExpressionBuilder() {
97
-		$backtrace = $this->getCallerBacktrace();
98
-		\OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
99
-		return parent::getExpressionBuilder();
100
-	}
101
-
102
-	/**
103
-	 * Get the file and line that called the method where `getCallerBacktrace()` was used
104
-	 *
105
-	 * @return string
106
-	 */
107
-	protected function getCallerBacktrace() {
108
-		$traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
109
-
110
-		// 0 is the method where we use `getCallerBacktrace`
111
-		// 1 is the target method which uses the method we want to log
112
-		if (isset($traces[1])) {
113
-			return $traces[1]['file'] . ':' . $traces[1]['line'];
114
-		}
115
-
116
-		return '';
117
-	}
118
-
119
-	/**
120
-	 * @return string
121
-	 */
122
-	public function getPrefix() {
123
-		return $this->tablePrefix;
124
-	}
125
-
126
-	/**
127
-	 * Initializes a new instance of the Connection class.
128
-	 *
129
-	 * @param array $params  The connection parameters.
130
-	 * @param \Doctrine\DBAL\Driver $driver
131
-	 * @param \Doctrine\DBAL\Configuration $config
132
-	 * @param \Doctrine\Common\EventManager $eventManager
133
-	 * @throws \Exception
134
-	 */
135
-	public function __construct(array $params, Driver $driver, Configuration $config = null,
136
-		EventManager $eventManager = null)
137
-	{
138
-		if (!isset($params['adapter'])) {
139
-			throw new \Exception('adapter not set');
140
-		}
141
-		if (!isset($params['tablePrefix'])) {
142
-			throw new \Exception('tablePrefix not set');
143
-		}
144
-		parent::__construct($params, $driver, $config, $eventManager);
145
-		$this->adapter = new $params['adapter']($this);
146
-		$this->tablePrefix = $params['tablePrefix'];
147
-
148
-		parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
149
-	}
150
-
151
-	/**
152
-	 * Prepares an SQL statement.
153
-	 *
154
-	 * @param string $statement The SQL statement to prepare.
155
-	 * @param int $limit
156
-	 * @param int $offset
157
-	 * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
158
-	 */
159
-	public function prepare( $statement, $limit=null, $offset=null ) {
160
-		if ($limit === -1) {
161
-			$limit = null;
162
-		}
163
-		if (!is_null($limit)) {
164
-			$platform = $this->getDatabasePlatform();
165
-			$statement = $platform->modifyLimitQuery($statement, $limit, $offset);
166
-		}
167
-		$statement = $this->replaceTablePrefix($statement);
168
-		$statement = $this->adapter->fixupStatement($statement);
169
-
170
-		if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
171
-			\OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
172
-		}
173
-		return parent::prepare($statement);
174
-	}
175
-
176
-	/**
177
-	 * Executes an, optionally parametrized, SQL query.
178
-	 *
179
-	 * If the query is parametrized, a prepared statement is used.
180
-	 * If an SQLLogger is configured, the execution is logged.
181
-	 *
182
-	 * @param string                                      $query  The SQL query to execute.
183
-	 * @param array                                       $params The parameters to bind to the query, if any.
184
-	 * @param array                                       $types  The types the previous parameters are in.
185
-	 * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
186
-	 *
187
-	 * @return \Doctrine\DBAL\Driver\Statement The executed statement.
188
-	 *
189
-	 * @throws \Doctrine\DBAL\DBALException
190
-	 */
191
-	public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
192
-	{
193
-		$query = $this->replaceTablePrefix($query);
194
-		$query = $this->adapter->fixupStatement($query);
195
-		return parent::executeQuery($query, $params, $types, $qcp);
196
-	}
197
-
198
-	/**
199
-	 * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
200
-	 * and returns the number of affected rows.
201
-	 *
202
-	 * This method supports PDO binding types as well as DBAL mapping types.
203
-	 *
204
-	 * @param string $query  The SQL query.
205
-	 * @param array  $params The query parameters.
206
-	 * @param array  $types  The parameter types.
207
-	 *
208
-	 * @return integer The number of affected rows.
209
-	 *
210
-	 * @throws \Doctrine\DBAL\DBALException
211
-	 */
212
-	public function executeUpdate($query, array $params = array(), array $types = array())
213
-	{
214
-		$query = $this->replaceTablePrefix($query);
215
-		$query = $this->adapter->fixupStatement($query);
216
-		return parent::executeUpdate($query, $params, $types);
217
-	}
218
-
219
-	/**
220
-	 * Returns the ID of the last inserted row, or the last value from a sequence object,
221
-	 * depending on the underlying driver.
222
-	 *
223
-	 * Note: This method may not return a meaningful or consistent result across different drivers,
224
-	 * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
225
-	 * columns or sequences.
226
-	 *
227
-	 * @param string $seqName Name of the sequence object from which the ID should be returned.
228
-	 * @return string A string representation of the last inserted ID.
229
-	 */
230
-	public function lastInsertId($seqName = null) {
231
-		if ($seqName) {
232
-			$seqName = $this->replaceTablePrefix($seqName);
233
-		}
234
-		return $this->adapter->lastInsertId($seqName);
235
-	}
236
-
237
-	// internal use
238
-	public function realLastInsertId($seqName = null) {
239
-		return parent::lastInsertId($seqName);
240
-	}
241
-
242
-	/**
243
-	 * Insert a row if the matching row does not exists.
244
-	 *
245
-	 * @param string $table The table name (will replace *PREFIX* with the actual prefix)
246
-	 * @param array $input data that should be inserted into the table  (column name => value)
247
-	 * @param array|null $compare List of values that should be checked for "if not exists"
248
-	 *				If this is null or an empty array, all keys of $input will be compared
249
-	 *				Please note: text fields (clob) must not be used in the compare array
250
-	 * @return int number of inserted rows
251
-	 * @throws \Doctrine\DBAL\DBALException
252
-	 */
253
-	public function insertIfNotExist($table, $input, array $compare = null) {
254
-		return $this->adapter->insertIfNotExist($table, $input, $compare);
255
-	}
256
-
257
-	private function getType($value) {
258
-		if (is_bool($value)) {
259
-			return IQueryBuilder::PARAM_BOOL;
260
-		} else if (is_int($value)) {
261
-			return IQueryBuilder::PARAM_INT;
262
-		} else {
263
-			return IQueryBuilder::PARAM_STR;
264
-		}
265
-	}
266
-
267
-	/**
268
-	 * Insert or update a row value
269
-	 *
270
-	 * @param string $table
271
-	 * @param array $keys (column name => value)
272
-	 * @param array $values (column name => value)
273
-	 * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
274
-	 * @return int number of new rows
275
-	 * @throws \Doctrine\DBAL\DBALException
276
-	 * @throws PreConditionNotMetException
277
-	 */
278
-	public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
279
-		try {
280
-			$insertQb = $this->getQueryBuilder();
281
-			$insertQb->insert($table)
282
-				->values(
283
-					array_map(function($value) use ($insertQb) {
284
-						return $insertQb->createNamedParameter($value, $this->getType($value));
285
-					}, array_merge($keys, $values))
286
-				);
287
-			return $insertQb->execute();
288
-		} catch (ConstraintViolationException $e) {
289
-			// value already exists, try update
290
-			$updateQb = $this->getQueryBuilder();
291
-			$updateQb->update($table);
292
-			foreach ($values as $name => $value) {
293
-				$updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
294
-			}
295
-			$where = $updateQb->expr()->andX();
296
-			$whereValues = array_merge($keys, $updatePreconditionValues);
297
-			foreach ($whereValues as $name => $value) {
298
-				$where->add($updateQb->expr()->eq(
299
-					$name,
300
-					$updateQb->createNamedParameter($value, $this->getType($value)),
301
-					$this->getType($value)
302
-				));
303
-			}
304
-			$updateQb->where($where);
305
-			$affected = $updateQb->execute();
306
-
307
-			if ($affected === 0 && !empty($updatePreconditionValues)) {
308
-				throw new PreConditionNotMetException();
309
-			}
310
-
311
-			return 0;
312
-		}
313
-	}
314
-
315
-	/**
316
-	 * Create an exclusive read+write lock on a table
317
-	 *
318
-	 * @param string $tableName
319
-	 * @throws \BadMethodCallException When trying to acquire a second lock
320
-	 * @since 9.1.0
321
-	 */
322
-	public function lockTable($tableName) {
323
-		if ($this->lockedTable !== null) {
324
-			throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
325
-		}
326
-
327
-		$tableName = $this->tablePrefix . $tableName;
328
-		$this->lockedTable = $tableName;
329
-		$this->adapter->lockTable($tableName);
330
-	}
331
-
332
-	/**
333
-	 * Release a previous acquired lock again
334
-	 *
335
-	 * @since 9.1.0
336
-	 */
337
-	public function unlockTable() {
338
-		$this->adapter->unlockTable();
339
-		$this->lockedTable = null;
340
-	}
341
-
342
-	/**
343
-	 * returns the error code and message as a string for logging
344
-	 * works with DoctrineException
345
-	 * @return string
346
-	 */
347
-	public function getError() {
348
-		$msg = $this->errorCode() . ': ';
349
-		$errorInfo = $this->errorInfo();
350
-		if (is_array($errorInfo)) {
351
-			$msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
352
-			$msg .= 'Driver Code = '.$errorInfo[1] . ', ';
353
-			$msg .= 'Driver Message = '.$errorInfo[2];
354
-		}
355
-		return $msg;
356
-	}
357
-
358
-	/**
359
-	 * Drop a table from the database if it exists
360
-	 *
361
-	 * @param string $table table name without the prefix
362
-	 */
363
-	public function dropTable($table) {
364
-		$table = $this->tablePrefix . trim($table);
365
-		$schema = $this->getSchemaManager();
366
-		if($schema->tablesExist(array($table))) {
367
-			$schema->dropTable($table);
368
-		}
369
-	}
370
-
371
-	/**
372
-	 * Check if a table exists
373
-	 *
374
-	 * @param string $table table name without the prefix
375
-	 * @return bool
376
-	 */
377
-	public function tableExists($table){
378
-		$table = $this->tablePrefix . trim($table);
379
-		$schema = $this->getSchemaManager();
380
-		return $schema->tablesExist(array($table));
381
-	}
382
-
383
-	// internal use
384
-	/**
385
-	 * @param string $statement
386
-	 * @return string
387
-	 */
388
-	protected function replaceTablePrefix($statement) {
389
-		return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
390
-	}
391
-
392
-	/**
393
-	 * Check if a transaction is active
394
-	 *
395
-	 * @return bool
396
-	 * @since 8.2.0
397
-	 */
398
-	public function inTransaction() {
399
-		return $this->getTransactionNestingLevel() > 0;
400
-	}
401
-
402
-	/**
403
-	 * Espace a parameter to be used in a LIKE query
404
-	 *
405
-	 * @param string $param
406
-	 * @return string
407
-	 */
408
-	public function escapeLikeParameter($param) {
409
-		return addcslashes($param, '\\_%');
410
-	}
411
-
412
-	/**
413
-	 * Check whether or not the current database support 4byte wide unicode
414
-	 *
415
-	 * @return bool
416
-	 * @since 11.0.0
417
-	 */
418
-	public function supports4ByteText() {
419
-		if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
420
-			return true;
421
-		}
422
-		return $this->getParams()['charset'] === 'utf8mb4';
423
-	}
44
+    /**
45
+     * @var string $tablePrefix
46
+     */
47
+    protected $tablePrefix;
48
+
49
+    /**
50
+     * @var \OC\DB\Adapter $adapter
51
+     */
52
+    protected $adapter;
53
+
54
+    protected $lockedTable = null;
55
+
56
+    public function connect() {
57
+        try {
58
+            return parent::connect();
59
+        } catch (DBALException $e) {
60
+            // throw a new exception to prevent leaking info from the stacktrace
61
+            throw new DBALException('Failed to connect to the database: ' . $e->getMessage(), $e->getCode());
62
+        }
63
+    }
64
+
65
+    /**
66
+     * Returns a QueryBuilder for the connection.
67
+     *
68
+     * @return \OCP\DB\QueryBuilder\IQueryBuilder
69
+     */
70
+    public function getQueryBuilder() {
71
+        return new QueryBuilder(
72
+            $this,
73
+            \OC::$server->getSystemConfig(),
74
+            \OC::$server->getLogger()
75
+        );
76
+    }
77
+
78
+    /**
79
+     * Gets the QueryBuilder for the connection.
80
+     *
81
+     * @return \Doctrine\DBAL\Query\QueryBuilder
82
+     * @deprecated please use $this->getQueryBuilder() instead
83
+     */
84
+    public function createQueryBuilder() {
85
+        $backtrace = $this->getCallerBacktrace();
86
+        \OC::$server->getLogger()->debug('Doctrine QueryBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
87
+        return parent::createQueryBuilder();
88
+    }
89
+
90
+    /**
91
+     * Gets the ExpressionBuilder for the connection.
92
+     *
93
+     * @return \Doctrine\DBAL\Query\Expression\ExpressionBuilder
94
+     * @deprecated please use $this->getQueryBuilder()->expr() instead
95
+     */
96
+    public function getExpressionBuilder() {
97
+        $backtrace = $this->getCallerBacktrace();
98
+        \OC::$server->getLogger()->debug('Doctrine ExpressionBuilder retrieved in {backtrace}', ['app' => 'core', 'backtrace' => $backtrace]);
99
+        return parent::getExpressionBuilder();
100
+    }
101
+
102
+    /**
103
+     * Get the file and line that called the method where `getCallerBacktrace()` was used
104
+     *
105
+     * @return string
106
+     */
107
+    protected function getCallerBacktrace() {
108
+        $traces = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
109
+
110
+        // 0 is the method where we use `getCallerBacktrace`
111
+        // 1 is the target method which uses the method we want to log
112
+        if (isset($traces[1])) {
113
+            return $traces[1]['file'] . ':' . $traces[1]['line'];
114
+        }
115
+
116
+        return '';
117
+    }
118
+
119
+    /**
120
+     * @return string
121
+     */
122
+    public function getPrefix() {
123
+        return $this->tablePrefix;
124
+    }
125
+
126
+    /**
127
+     * Initializes a new instance of the Connection class.
128
+     *
129
+     * @param array $params  The connection parameters.
130
+     * @param \Doctrine\DBAL\Driver $driver
131
+     * @param \Doctrine\DBAL\Configuration $config
132
+     * @param \Doctrine\Common\EventManager $eventManager
133
+     * @throws \Exception
134
+     */
135
+    public function __construct(array $params, Driver $driver, Configuration $config = null,
136
+        EventManager $eventManager = null)
137
+    {
138
+        if (!isset($params['adapter'])) {
139
+            throw new \Exception('adapter not set');
140
+        }
141
+        if (!isset($params['tablePrefix'])) {
142
+            throw new \Exception('tablePrefix not set');
143
+        }
144
+        parent::__construct($params, $driver, $config, $eventManager);
145
+        $this->adapter = new $params['adapter']($this);
146
+        $this->tablePrefix = $params['tablePrefix'];
147
+
148
+        parent::setTransactionIsolation(parent::TRANSACTION_READ_COMMITTED);
149
+    }
150
+
151
+    /**
152
+     * Prepares an SQL statement.
153
+     *
154
+     * @param string $statement The SQL statement to prepare.
155
+     * @param int $limit
156
+     * @param int $offset
157
+     * @return \Doctrine\DBAL\Driver\Statement The prepared statement.
158
+     */
159
+    public function prepare( $statement, $limit=null, $offset=null ) {
160
+        if ($limit === -1) {
161
+            $limit = null;
162
+        }
163
+        if (!is_null($limit)) {
164
+            $platform = $this->getDatabasePlatform();
165
+            $statement = $platform->modifyLimitQuery($statement, $limit, $offset);
166
+        }
167
+        $statement = $this->replaceTablePrefix($statement);
168
+        $statement = $this->adapter->fixupStatement($statement);
169
+
170
+        if(\OC::$server->getSystemConfig()->getValue( 'log_query', false)) {
171
+            \OCP\Util::writeLog('core', 'DB prepare : '.$statement, \OCP\Util::DEBUG);
172
+        }
173
+        return parent::prepare($statement);
174
+    }
175
+
176
+    /**
177
+     * Executes an, optionally parametrized, SQL query.
178
+     *
179
+     * If the query is parametrized, a prepared statement is used.
180
+     * If an SQLLogger is configured, the execution is logged.
181
+     *
182
+     * @param string                                      $query  The SQL query to execute.
183
+     * @param array                                       $params The parameters to bind to the query, if any.
184
+     * @param array                                       $types  The types the previous parameters are in.
185
+     * @param \Doctrine\DBAL\Cache\QueryCacheProfile|null $qcp    The query cache profile, optional.
186
+     *
187
+     * @return \Doctrine\DBAL\Driver\Statement The executed statement.
188
+     *
189
+     * @throws \Doctrine\DBAL\DBALException
190
+     */
191
+    public function executeQuery($query, array $params = array(), $types = array(), QueryCacheProfile $qcp = null)
192
+    {
193
+        $query = $this->replaceTablePrefix($query);
194
+        $query = $this->adapter->fixupStatement($query);
195
+        return parent::executeQuery($query, $params, $types, $qcp);
196
+    }
197
+
198
+    /**
199
+     * Executes an SQL INSERT/UPDATE/DELETE query with the given parameters
200
+     * and returns the number of affected rows.
201
+     *
202
+     * This method supports PDO binding types as well as DBAL mapping types.
203
+     *
204
+     * @param string $query  The SQL query.
205
+     * @param array  $params The query parameters.
206
+     * @param array  $types  The parameter types.
207
+     *
208
+     * @return integer The number of affected rows.
209
+     *
210
+     * @throws \Doctrine\DBAL\DBALException
211
+     */
212
+    public function executeUpdate($query, array $params = array(), array $types = array())
213
+    {
214
+        $query = $this->replaceTablePrefix($query);
215
+        $query = $this->adapter->fixupStatement($query);
216
+        return parent::executeUpdate($query, $params, $types);
217
+    }
218
+
219
+    /**
220
+     * Returns the ID of the last inserted row, or the last value from a sequence object,
221
+     * depending on the underlying driver.
222
+     *
223
+     * Note: This method may not return a meaningful or consistent result across different drivers,
224
+     * because the underlying database may not even support the notion of AUTO_INCREMENT/IDENTITY
225
+     * columns or sequences.
226
+     *
227
+     * @param string $seqName Name of the sequence object from which the ID should be returned.
228
+     * @return string A string representation of the last inserted ID.
229
+     */
230
+    public function lastInsertId($seqName = null) {
231
+        if ($seqName) {
232
+            $seqName = $this->replaceTablePrefix($seqName);
233
+        }
234
+        return $this->adapter->lastInsertId($seqName);
235
+    }
236
+
237
+    // internal use
238
+    public function realLastInsertId($seqName = null) {
239
+        return parent::lastInsertId($seqName);
240
+    }
241
+
242
+    /**
243
+     * Insert a row if the matching row does not exists.
244
+     *
245
+     * @param string $table The table name (will replace *PREFIX* with the actual prefix)
246
+     * @param array $input data that should be inserted into the table  (column name => value)
247
+     * @param array|null $compare List of values that should be checked for "if not exists"
248
+     *				If this is null or an empty array, all keys of $input will be compared
249
+     *				Please note: text fields (clob) must not be used in the compare array
250
+     * @return int number of inserted rows
251
+     * @throws \Doctrine\DBAL\DBALException
252
+     */
253
+    public function insertIfNotExist($table, $input, array $compare = null) {
254
+        return $this->adapter->insertIfNotExist($table, $input, $compare);
255
+    }
256
+
257
+    private function getType($value) {
258
+        if (is_bool($value)) {
259
+            return IQueryBuilder::PARAM_BOOL;
260
+        } else if (is_int($value)) {
261
+            return IQueryBuilder::PARAM_INT;
262
+        } else {
263
+            return IQueryBuilder::PARAM_STR;
264
+        }
265
+    }
266
+
267
+    /**
268
+     * Insert or update a row value
269
+     *
270
+     * @param string $table
271
+     * @param array $keys (column name => value)
272
+     * @param array $values (column name => value)
273
+     * @param array $updatePreconditionValues ensure values match preconditions (column name => value)
274
+     * @return int number of new rows
275
+     * @throws \Doctrine\DBAL\DBALException
276
+     * @throws PreConditionNotMetException
277
+     */
278
+    public function setValues($table, array $keys, array $values, array $updatePreconditionValues = []) {
279
+        try {
280
+            $insertQb = $this->getQueryBuilder();
281
+            $insertQb->insert($table)
282
+                ->values(
283
+                    array_map(function($value) use ($insertQb) {
284
+                        return $insertQb->createNamedParameter($value, $this->getType($value));
285
+                    }, array_merge($keys, $values))
286
+                );
287
+            return $insertQb->execute();
288
+        } catch (ConstraintViolationException $e) {
289
+            // value already exists, try update
290
+            $updateQb = $this->getQueryBuilder();
291
+            $updateQb->update($table);
292
+            foreach ($values as $name => $value) {
293
+                $updateQb->set($name, $updateQb->createNamedParameter($value, $this->getType($value)));
294
+            }
295
+            $where = $updateQb->expr()->andX();
296
+            $whereValues = array_merge($keys, $updatePreconditionValues);
297
+            foreach ($whereValues as $name => $value) {
298
+                $where->add($updateQb->expr()->eq(
299
+                    $name,
300
+                    $updateQb->createNamedParameter($value, $this->getType($value)),
301
+                    $this->getType($value)
302
+                ));
303
+            }
304
+            $updateQb->where($where);
305
+            $affected = $updateQb->execute();
306
+
307
+            if ($affected === 0 && !empty($updatePreconditionValues)) {
308
+                throw new PreConditionNotMetException();
309
+            }
310
+
311
+            return 0;
312
+        }
313
+    }
314
+
315
+    /**
316
+     * Create an exclusive read+write lock on a table
317
+     *
318
+     * @param string $tableName
319
+     * @throws \BadMethodCallException When trying to acquire a second lock
320
+     * @since 9.1.0
321
+     */
322
+    public function lockTable($tableName) {
323
+        if ($this->lockedTable !== null) {
324
+            throw new \BadMethodCallException('Can not lock a new table until the previous lock is released.');
325
+        }
326
+
327
+        $tableName = $this->tablePrefix . $tableName;
328
+        $this->lockedTable = $tableName;
329
+        $this->adapter->lockTable($tableName);
330
+    }
331
+
332
+    /**
333
+     * Release a previous acquired lock again
334
+     *
335
+     * @since 9.1.0
336
+     */
337
+    public function unlockTable() {
338
+        $this->adapter->unlockTable();
339
+        $this->lockedTable = null;
340
+    }
341
+
342
+    /**
343
+     * returns the error code and message as a string for logging
344
+     * works with DoctrineException
345
+     * @return string
346
+     */
347
+    public function getError() {
348
+        $msg = $this->errorCode() . ': ';
349
+        $errorInfo = $this->errorInfo();
350
+        if (is_array($errorInfo)) {
351
+            $msg .= 'SQLSTATE = '.$errorInfo[0] . ', ';
352
+            $msg .= 'Driver Code = '.$errorInfo[1] . ', ';
353
+            $msg .= 'Driver Message = '.$errorInfo[2];
354
+        }
355
+        return $msg;
356
+    }
357
+
358
+    /**
359
+     * Drop a table from the database if it exists
360
+     *
361
+     * @param string $table table name without the prefix
362
+     */
363
+    public function dropTable($table) {
364
+        $table = $this->tablePrefix . trim($table);
365
+        $schema = $this->getSchemaManager();
366
+        if($schema->tablesExist(array($table))) {
367
+            $schema->dropTable($table);
368
+        }
369
+    }
370
+
371
+    /**
372
+     * Check if a table exists
373
+     *
374
+     * @param string $table table name without the prefix
375
+     * @return bool
376
+     */
377
+    public function tableExists($table){
378
+        $table = $this->tablePrefix . trim($table);
379
+        $schema = $this->getSchemaManager();
380
+        return $schema->tablesExist(array($table));
381
+    }
382
+
383
+    // internal use
384
+    /**
385
+     * @param string $statement
386
+     * @return string
387
+     */
388
+    protected function replaceTablePrefix($statement) {
389
+        return str_replace( '*PREFIX*', $this->tablePrefix, $statement );
390
+    }
391
+
392
+    /**
393
+     * Check if a transaction is active
394
+     *
395
+     * @return bool
396
+     * @since 8.2.0
397
+     */
398
+    public function inTransaction() {
399
+        return $this->getTransactionNestingLevel() > 0;
400
+    }
401
+
402
+    /**
403
+     * Espace a parameter to be used in a LIKE query
404
+     *
405
+     * @param string $param
406
+     * @return string
407
+     */
408
+    public function escapeLikeParameter($param) {
409
+        return addcslashes($param, '\\_%');
410
+    }
411
+
412
+    /**
413
+     * Check whether or not the current database support 4byte wide unicode
414
+     *
415
+     * @return bool
416
+     * @since 11.0.0
417
+     */
418
+    public function supports4ByteText() {
419
+        if (!$this->getDatabasePlatform() instanceof MySqlPlatform) {
420
+            return true;
421
+        }
422
+        return $this->getParams()['charset'] === 'utf8mb4';
423
+    }
424 424
 }
Please login to merge, or discard this patch.