@@ -77,7 +77,7 @@ |
||
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 |
@@ -41,182 +41,182 @@ |
||
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 | } |
@@ -45,14 +45,14 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
@@ -32,7 +32,6 @@ |
||
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 |
@@ -38,111 +38,111 @@ |
||
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 | } |
@@ -132,16 +132,16 @@ |
||
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 | } |
@@ -112,7 +112,7 @@ |
||
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 = '') { |
@@ -37,427 +37,427 @@ |
||
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 | } |
@@ -87,7 +87,7 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 { |
@@ -296,6 +296,9 @@ |
||
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); |
@@ -29,280 +29,280 @@ |
||
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 | } |
@@ -102,7 +102,7 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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(), |
@@ -23,7 +23,6 @@ |
||
23 | 23 | |
24 | 24 | namespace OC\App; |
25 | 25 | |
26 | -use OC_Util; |
|
27 | 26 | use OCP\IConfig; |
28 | 27 | |
29 | 28 | /** |
@@ -36,66 +36,66 @@ |
||
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 | } |
@@ -110,7 +110,7 @@ |
||
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 |
@@ -33,121 +33,121 @@ |
||
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 | } |
@@ -41,7 +41,7 @@ discard block |
||
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 |
||
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 |
||
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 |
@@ -46,7 +46,7 @@ |
||
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){ |
@@ -35,102 +35,102 @@ |
||
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 | } |
@@ -33,7 +33,7 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
@@ -205,7 +205,7 @@ |
||
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); |
@@ -37,808 +37,808 @@ |
||
37 | 37 | |
38 | 38 | class Manager implements ICommentsManager { |
39 | 39 | |
40 | - /** @var IDBConnection */ |
|
41 | - protected $dbConn; |
|
42 | - |
|
43 | - /** @var ILogger */ |
|
44 | - protected $logger; |
|
45 | - |
|
46 | - /** @var IConfig */ |
|
47 | - protected $config; |
|
48 | - |
|
49 | - /** @var IComment[] */ |
|
50 | - protected $commentsCache = []; |
|
51 | - |
|
52 | - /** @var \Closure[] */ |
|
53 | - protected $eventHandlerClosures = []; |
|
54 | - |
|
55 | - /** @var ICommentsEventHandler[] */ |
|
56 | - protected $eventHandlers = []; |
|
57 | - |
|
58 | - /** @var \Closure[] */ |
|
59 | - protected $displayNameResolvers = []; |
|
60 | - |
|
61 | - /** |
|
62 | - * Manager constructor. |
|
63 | - * |
|
64 | - * @param IDBConnection $dbConn |
|
65 | - * @param ILogger $logger |
|
66 | - * @param IConfig $config |
|
67 | - */ |
|
68 | - public function __construct( |
|
69 | - IDBConnection $dbConn, |
|
70 | - ILogger $logger, |
|
71 | - IConfig $config |
|
72 | - ) { |
|
73 | - $this->dbConn = $dbConn; |
|
74 | - $this->logger = $logger; |
|
75 | - $this->config = $config; |
|
76 | - } |
|
77 | - |
|
78 | - /** |
|
79 | - * converts data base data into PHP native, proper types as defined by |
|
80 | - * IComment interface. |
|
81 | - * |
|
82 | - * @param array $data |
|
83 | - * @return array |
|
84 | - */ |
|
85 | - protected function normalizeDatabaseData(array $data) { |
|
86 | - $data['id'] = strval($data['id']); |
|
87 | - $data['parent_id'] = strval($data['parent_id']); |
|
88 | - $data['topmost_parent_id'] = strval($data['topmost_parent_id']); |
|
89 | - $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']); |
|
90 | - if (!is_null($data['latest_child_timestamp'])) { |
|
91 | - $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); |
|
92 | - } |
|
93 | - $data['children_count'] = intval($data['children_count']); |
|
94 | - return $data; |
|
95 | - } |
|
96 | - |
|
97 | - /** |
|
98 | - * prepares a comment for an insert or update operation after making sure |
|
99 | - * all necessary fields have a value assigned. |
|
100 | - * |
|
101 | - * @param IComment $comment |
|
102 | - * @return IComment returns the same updated IComment instance as provided |
|
103 | - * by parameter for convenience |
|
104 | - * @throws \UnexpectedValueException |
|
105 | - */ |
|
106 | - protected function prepareCommentForDatabaseWrite(IComment $comment) { |
|
107 | - if( !$comment->getActorType() |
|
108 | - || !$comment->getActorId() |
|
109 | - || !$comment->getObjectType() |
|
110 | - || !$comment->getObjectId() |
|
111 | - || !$comment->getVerb() |
|
112 | - ) { |
|
113 | - throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
|
114 | - } |
|
115 | - |
|
116 | - if($comment->getId() === '') { |
|
117 | - $comment->setChildrenCount(0); |
|
118 | - $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
|
119 | - $comment->setLatestChildDateTime(null); |
|
120 | - } |
|
121 | - |
|
122 | - if(is_null($comment->getCreationDateTime())) { |
|
123 | - $comment->setCreationDateTime(new \DateTime()); |
|
124 | - } |
|
125 | - |
|
126 | - if($comment->getParentId() !== '0') { |
|
127 | - $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
|
128 | - } else { |
|
129 | - $comment->setTopmostParentId('0'); |
|
130 | - } |
|
131 | - |
|
132 | - $this->cache($comment); |
|
133 | - |
|
134 | - return $comment; |
|
135 | - } |
|
136 | - |
|
137 | - /** |
|
138 | - * returns the topmost parent id of a given comment identified by ID |
|
139 | - * |
|
140 | - * @param string $id |
|
141 | - * @return string |
|
142 | - * @throws NotFoundException |
|
143 | - */ |
|
144 | - protected function determineTopmostParentId($id) { |
|
145 | - $comment = $this->get($id); |
|
146 | - if($comment->getParentId() === '0') { |
|
147 | - return $comment->getId(); |
|
148 | - } else { |
|
149 | - return $this->determineTopmostParentId($comment->getId()); |
|
150 | - } |
|
151 | - } |
|
152 | - |
|
153 | - /** |
|
154 | - * updates child information of a comment |
|
155 | - * |
|
156 | - * @param string $id |
|
157 | - * @param \DateTime $cDateTime the date time of the most recent child |
|
158 | - * @throws NotFoundException |
|
159 | - */ |
|
160 | - protected function updateChildrenInformation($id, \DateTime $cDateTime) { |
|
161 | - $qb = $this->dbConn->getQueryBuilder(); |
|
162 | - $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
163 | - ->from('comments') |
|
164 | - ->where($qb->expr()->eq('parent_id', $qb->createParameter('id'))) |
|
165 | - ->setParameter('id', $id); |
|
166 | - |
|
167 | - $resultStatement = $query->execute(); |
|
168 | - $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
169 | - $resultStatement->closeCursor(); |
|
170 | - $children = intval($data[0]); |
|
171 | - |
|
172 | - $comment = $this->get($id); |
|
173 | - $comment->setChildrenCount($children); |
|
174 | - $comment->setLatestChildDateTime($cDateTime); |
|
175 | - $this->save($comment); |
|
176 | - } |
|
177 | - |
|
178 | - /** |
|
179 | - * Tests whether actor or object type and id parameters are acceptable. |
|
180 | - * Throws exception if not. |
|
181 | - * |
|
182 | - * @param string $role |
|
183 | - * @param string $type |
|
184 | - * @param string $id |
|
185 | - * @throws \InvalidArgumentException |
|
186 | - */ |
|
187 | - protected function checkRoleParameters($role, $type, $id) { |
|
188 | - if( |
|
189 | - !is_string($type) || empty($type) |
|
190 | - || !is_string($id) || empty($id) |
|
191 | - ) { |
|
192 | - throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
193 | - } |
|
194 | - } |
|
195 | - |
|
196 | - /** |
|
197 | - * run-time caches a comment |
|
198 | - * |
|
199 | - * @param IComment $comment |
|
200 | - */ |
|
201 | - protected function cache(IComment $comment) { |
|
202 | - $id = $comment->getId(); |
|
203 | - if(empty($id)) { |
|
204 | - return; |
|
205 | - } |
|
206 | - $this->commentsCache[strval($id)] = $comment; |
|
207 | - } |
|
208 | - |
|
209 | - /** |
|
210 | - * removes an entry from the comments run time cache |
|
211 | - * |
|
212 | - * @param mixed $id the comment's id |
|
213 | - */ |
|
214 | - protected function uncache($id) { |
|
215 | - $id = strval($id); |
|
216 | - if (isset($this->commentsCache[$id])) { |
|
217 | - unset($this->commentsCache[$id]); |
|
218 | - } |
|
219 | - } |
|
220 | - |
|
221 | - /** |
|
222 | - * returns a comment instance |
|
223 | - * |
|
224 | - * @param string $id the ID of the comment |
|
225 | - * @return IComment |
|
226 | - * @throws NotFoundException |
|
227 | - * @throws \InvalidArgumentException |
|
228 | - * @since 9.0.0 |
|
229 | - */ |
|
230 | - public function get($id) { |
|
231 | - if(intval($id) === 0) { |
|
232 | - throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
|
233 | - } |
|
234 | - |
|
235 | - if(isset($this->commentsCache[$id])) { |
|
236 | - return $this->commentsCache[$id]; |
|
237 | - } |
|
238 | - |
|
239 | - $qb = $this->dbConn->getQueryBuilder(); |
|
240 | - $resultStatement = $qb->select('*') |
|
241 | - ->from('comments') |
|
242 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
243 | - ->setParameter('id', $id, IQueryBuilder::PARAM_INT) |
|
244 | - ->execute(); |
|
245 | - |
|
246 | - $data = $resultStatement->fetch(); |
|
247 | - $resultStatement->closeCursor(); |
|
248 | - if(!$data) { |
|
249 | - throw new NotFoundException(); |
|
250 | - } |
|
251 | - |
|
252 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
253 | - $this->cache($comment); |
|
254 | - return $comment; |
|
255 | - } |
|
256 | - |
|
257 | - /** |
|
258 | - * returns the comment specified by the id and all it's child comments. |
|
259 | - * At this point of time, we do only support one level depth. |
|
260 | - * |
|
261 | - * @param string $id |
|
262 | - * @param int $limit max number of entries to return, 0 returns all |
|
263 | - * @param int $offset the start entry |
|
264 | - * @return array |
|
265 | - * @since 9.0.0 |
|
266 | - * |
|
267 | - * The return array looks like this |
|
268 | - * [ |
|
269 | - * 'comment' => IComment, // root comment |
|
270 | - * 'replies' => |
|
271 | - * [ |
|
272 | - * 0 => |
|
273 | - * [ |
|
274 | - * 'comment' => IComment, |
|
275 | - * 'replies' => [] |
|
276 | - * ] |
|
277 | - * 1 => |
|
278 | - * [ |
|
279 | - * 'comment' => IComment, |
|
280 | - * 'replies'=> [] |
|
281 | - * ], |
|
282 | - * … |
|
283 | - * ] |
|
284 | - * ] |
|
285 | - */ |
|
286 | - public function getTree($id, $limit = 0, $offset = 0) { |
|
287 | - $tree = []; |
|
288 | - $tree['comment'] = $this->get($id); |
|
289 | - $tree['replies'] = []; |
|
290 | - |
|
291 | - $qb = $this->dbConn->getQueryBuilder(); |
|
292 | - $query = $qb->select('*') |
|
293 | - ->from('comments') |
|
294 | - ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id'))) |
|
295 | - ->orderBy('creation_timestamp', 'DESC') |
|
296 | - ->setParameter('id', $id); |
|
297 | - |
|
298 | - if($limit > 0) { |
|
299 | - $query->setMaxResults($limit); |
|
300 | - } |
|
301 | - if($offset > 0) { |
|
302 | - $query->setFirstResult($offset); |
|
303 | - } |
|
304 | - |
|
305 | - $resultStatement = $query->execute(); |
|
306 | - while($data = $resultStatement->fetch()) { |
|
307 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
308 | - $this->cache($comment); |
|
309 | - $tree['replies'][] = [ |
|
310 | - 'comment' => $comment, |
|
311 | - 'replies' => [] |
|
312 | - ]; |
|
313 | - } |
|
314 | - $resultStatement->closeCursor(); |
|
315 | - |
|
316 | - return $tree; |
|
317 | - } |
|
318 | - |
|
319 | - /** |
|
320 | - * returns comments for a specific object (e.g. a file). |
|
321 | - * |
|
322 | - * The sort order is always newest to oldest. |
|
323 | - * |
|
324 | - * @param string $objectType the object type, e.g. 'files' |
|
325 | - * @param string $objectId the id of the object |
|
326 | - * @param int $limit optional, number of maximum comments to be returned. if |
|
327 | - * not specified, all comments are returned. |
|
328 | - * @param int $offset optional, starting point |
|
329 | - * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
330 | - * that may be returned |
|
331 | - * @return IComment[] |
|
332 | - * @since 9.0.0 |
|
333 | - */ |
|
334 | - public function getForObject( |
|
335 | - $objectType, |
|
336 | - $objectId, |
|
337 | - $limit = 0, |
|
338 | - $offset = 0, |
|
339 | - \DateTime $notOlderThan = null |
|
340 | - ) { |
|
341 | - $comments = []; |
|
342 | - |
|
343 | - $qb = $this->dbConn->getQueryBuilder(); |
|
344 | - $query = $qb->select('*') |
|
345 | - ->from('comments') |
|
346 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
347 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
348 | - ->orderBy('creation_timestamp', 'DESC') |
|
349 | - ->setParameter('type', $objectType) |
|
350 | - ->setParameter('id', $objectId); |
|
351 | - |
|
352 | - if($limit > 0) { |
|
353 | - $query->setMaxResults($limit); |
|
354 | - } |
|
355 | - if($offset > 0) { |
|
356 | - $query->setFirstResult($offset); |
|
357 | - } |
|
358 | - if(!is_null($notOlderThan)) { |
|
359 | - $query |
|
360 | - ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
361 | - ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
362 | - } |
|
363 | - |
|
364 | - $resultStatement = $query->execute(); |
|
365 | - while($data = $resultStatement->fetch()) { |
|
366 | - $comment = new Comment($this->normalizeDatabaseData($data)); |
|
367 | - $this->cache($comment); |
|
368 | - $comments[] = $comment; |
|
369 | - } |
|
370 | - $resultStatement->closeCursor(); |
|
371 | - |
|
372 | - return $comments; |
|
373 | - } |
|
374 | - |
|
375 | - /** |
|
376 | - * @param $objectType string the object type, e.g. 'files' |
|
377 | - * @param $objectId string the id of the object |
|
378 | - * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
379 | - * that may be returned |
|
380 | - * @return Int |
|
381 | - * @since 9.0.0 |
|
382 | - */ |
|
383 | - public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) { |
|
384 | - $qb = $this->dbConn->getQueryBuilder(); |
|
385 | - $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
386 | - ->from('comments') |
|
387 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
388 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
389 | - ->setParameter('type', $objectType) |
|
390 | - ->setParameter('id', $objectId); |
|
391 | - |
|
392 | - if(!is_null($notOlderThan)) { |
|
393 | - $query |
|
394 | - ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
395 | - ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
396 | - } |
|
397 | - |
|
398 | - $resultStatement = $query->execute(); |
|
399 | - $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
400 | - $resultStatement->closeCursor(); |
|
401 | - return intval($data[0]); |
|
402 | - } |
|
403 | - |
|
404 | - /** |
|
405 | - * creates a new comment and returns it. At this point of time, it is not |
|
406 | - * saved in the used data storage. Use save() after setting other fields |
|
407 | - * of the comment (e.g. message or verb). |
|
408 | - * |
|
409 | - * @param string $actorType the actor type (e.g. 'users') |
|
410 | - * @param string $actorId a user id |
|
411 | - * @param string $objectType the object type the comment is attached to |
|
412 | - * @param string $objectId the object id the comment is attached to |
|
413 | - * @return IComment |
|
414 | - * @since 9.0.0 |
|
415 | - */ |
|
416 | - public function create($actorType, $actorId, $objectType, $objectId) { |
|
417 | - $comment = new Comment(); |
|
418 | - $comment |
|
419 | - ->setActor($actorType, $actorId) |
|
420 | - ->setObject($objectType, $objectId); |
|
421 | - return $comment; |
|
422 | - } |
|
423 | - |
|
424 | - /** |
|
425 | - * permanently deletes the comment specified by the ID |
|
426 | - * |
|
427 | - * When the comment has child comments, their parent ID will be changed to |
|
428 | - * the parent ID of the item that is to be deleted. |
|
429 | - * |
|
430 | - * @param string $id |
|
431 | - * @return bool |
|
432 | - * @throws \InvalidArgumentException |
|
433 | - * @since 9.0.0 |
|
434 | - */ |
|
435 | - public function delete($id) { |
|
436 | - if(!is_string($id)) { |
|
437 | - throw new \InvalidArgumentException('Parameter must be string'); |
|
438 | - } |
|
439 | - |
|
440 | - try { |
|
441 | - $comment = $this->get($id); |
|
442 | - } catch (\Exception $e) { |
|
443 | - // Ignore exceptions, we just don't fire a hook then |
|
444 | - $comment = null; |
|
445 | - } |
|
446 | - |
|
447 | - $qb = $this->dbConn->getQueryBuilder(); |
|
448 | - $query = $qb->delete('comments') |
|
449 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
450 | - ->setParameter('id', $id); |
|
451 | - |
|
452 | - try { |
|
453 | - $affectedRows = $query->execute(); |
|
454 | - $this->uncache($id); |
|
455 | - } catch (DriverException $e) { |
|
456 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
457 | - return false; |
|
458 | - } |
|
459 | - |
|
460 | - if ($affectedRows > 0 && $comment instanceof IComment) { |
|
461 | - $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment); |
|
462 | - } |
|
463 | - |
|
464 | - return ($affectedRows > 0); |
|
465 | - } |
|
466 | - |
|
467 | - /** |
|
468 | - * saves the comment permanently |
|
469 | - * |
|
470 | - * if the supplied comment has an empty ID, a new entry comment will be |
|
471 | - * saved and the instance updated with the new ID. |
|
472 | - * |
|
473 | - * Otherwise, an existing comment will be updated. |
|
474 | - * |
|
475 | - * Throws NotFoundException when a comment that is to be updated does not |
|
476 | - * exist anymore at this point of time. |
|
477 | - * |
|
478 | - * @param IComment $comment |
|
479 | - * @return bool |
|
480 | - * @throws NotFoundException |
|
481 | - * @since 9.0.0 |
|
482 | - */ |
|
483 | - public function save(IComment $comment) { |
|
484 | - if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
485 | - $result = $this->insert($comment); |
|
486 | - } else { |
|
487 | - $result = $this->update($comment); |
|
488 | - } |
|
489 | - |
|
490 | - if($result && !!$comment->getParentId()) { |
|
491 | - $this->updateChildrenInformation( |
|
492 | - $comment->getParentId(), |
|
493 | - $comment->getCreationDateTime() |
|
494 | - ); |
|
495 | - $this->cache($comment); |
|
496 | - } |
|
497 | - |
|
498 | - return $result; |
|
499 | - } |
|
500 | - |
|
501 | - /** |
|
502 | - * inserts the provided comment in the database |
|
503 | - * |
|
504 | - * @param IComment $comment |
|
505 | - * @return bool |
|
506 | - */ |
|
507 | - protected function insert(IComment &$comment) { |
|
508 | - $qb = $this->dbConn->getQueryBuilder(); |
|
509 | - $affectedRows = $qb |
|
510 | - ->insert('comments') |
|
511 | - ->values([ |
|
512 | - 'parent_id' => $qb->createNamedParameter($comment->getParentId()), |
|
513 | - 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), |
|
514 | - 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), |
|
515 | - 'actor_type' => $qb->createNamedParameter($comment->getActorType()), |
|
516 | - 'actor_id' => $qb->createNamedParameter($comment->getActorId()), |
|
517 | - 'message' => $qb->createNamedParameter($comment->getMessage()), |
|
518 | - 'verb' => $qb->createNamedParameter($comment->getVerb()), |
|
519 | - 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), |
|
520 | - 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), |
|
521 | - 'object_type' => $qb->createNamedParameter($comment->getObjectType()), |
|
522 | - 'object_id' => $qb->createNamedParameter($comment->getObjectId()), |
|
523 | - ]) |
|
524 | - ->execute(); |
|
525 | - |
|
526 | - if ($affectedRows > 0) { |
|
527 | - $comment->setId(strval($qb->getLastInsertId())); |
|
528 | - $this->sendEvent(CommentsEvent::EVENT_ADD, $comment); |
|
529 | - } |
|
530 | - |
|
531 | - return $affectedRows > 0; |
|
532 | - } |
|
533 | - |
|
534 | - /** |
|
535 | - * updates a Comment data row |
|
536 | - * |
|
537 | - * @param IComment $comment |
|
538 | - * @return bool |
|
539 | - * @throws NotFoundException |
|
540 | - */ |
|
541 | - protected function update(IComment $comment) { |
|
542 | - // for properly working preUpdate Events we need the old comments as is |
|
543 | - // in the DB and overcome caching. Also avoid that outdated information stays. |
|
544 | - $this->uncache($comment->getId()); |
|
545 | - $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); |
|
546 | - $this->uncache($comment->getId()); |
|
547 | - |
|
548 | - $qb = $this->dbConn->getQueryBuilder(); |
|
549 | - $affectedRows = $qb |
|
550 | - ->update('comments') |
|
551 | - ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
552 | - ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
553 | - ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
554 | - ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
555 | - ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
556 | - ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
557 | - ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
558 | - ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
559 | - ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
560 | - ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
561 | - ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
562 | - ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
563 | - ->setParameter('id', $comment->getId()) |
|
564 | - ->execute(); |
|
565 | - |
|
566 | - if($affectedRows === 0) { |
|
567 | - throw new NotFoundException('Comment to update does ceased to exist'); |
|
568 | - } |
|
569 | - |
|
570 | - $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); |
|
571 | - |
|
572 | - return $affectedRows > 0; |
|
573 | - } |
|
574 | - |
|
575 | - /** |
|
576 | - * removes references to specific actor (e.g. on user delete) of a comment. |
|
577 | - * The comment itself must not get lost/deleted. |
|
578 | - * |
|
579 | - * @param string $actorType the actor type (e.g. 'users') |
|
580 | - * @param string $actorId a user id |
|
581 | - * @return boolean |
|
582 | - * @since 9.0.0 |
|
583 | - */ |
|
584 | - public function deleteReferencesOfActor($actorType, $actorId) { |
|
585 | - $this->checkRoleParameters('Actor', $actorType, $actorId); |
|
586 | - |
|
587 | - $qb = $this->dbConn->getQueryBuilder(); |
|
588 | - $affectedRows = $qb |
|
589 | - ->update('comments') |
|
590 | - ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
591 | - ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
592 | - ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
|
593 | - ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
|
594 | - ->setParameter('type', $actorType) |
|
595 | - ->setParameter('id', $actorId) |
|
596 | - ->execute(); |
|
597 | - |
|
598 | - $this->commentsCache = []; |
|
599 | - |
|
600 | - return is_int($affectedRows); |
|
601 | - } |
|
602 | - |
|
603 | - /** |
|
604 | - * deletes all comments made of a specific object (e.g. on file delete) |
|
605 | - * |
|
606 | - * @param string $objectType the object type (e.g. 'files') |
|
607 | - * @param string $objectId e.g. the file id |
|
608 | - * @return boolean |
|
609 | - * @since 9.0.0 |
|
610 | - */ |
|
611 | - public function deleteCommentsAtObject($objectType, $objectId) { |
|
612 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
613 | - |
|
614 | - $qb = $this->dbConn->getQueryBuilder(); |
|
615 | - $affectedRows = $qb |
|
616 | - ->delete('comments') |
|
617 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
618 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
619 | - ->setParameter('type', $objectType) |
|
620 | - ->setParameter('id', $objectId) |
|
621 | - ->execute(); |
|
622 | - |
|
623 | - $this->commentsCache = []; |
|
624 | - |
|
625 | - return is_int($affectedRows); |
|
626 | - } |
|
627 | - |
|
628 | - /** |
|
629 | - * deletes the read markers for the specified user |
|
630 | - * |
|
631 | - * @param \OCP\IUser $user |
|
632 | - * @return bool |
|
633 | - * @since 9.0.0 |
|
634 | - */ |
|
635 | - public function deleteReadMarksFromUser(IUser $user) { |
|
636 | - $qb = $this->dbConn->getQueryBuilder(); |
|
637 | - $query = $qb->delete('comments_read_markers') |
|
638 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
639 | - ->setParameter('user_id', $user->getUID()); |
|
640 | - |
|
641 | - try { |
|
642 | - $affectedRows = $query->execute(); |
|
643 | - } catch (DriverException $e) { |
|
644 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
645 | - return false; |
|
646 | - } |
|
647 | - return ($affectedRows > 0); |
|
648 | - } |
|
649 | - |
|
650 | - /** |
|
651 | - * sets the read marker for a given file to the specified date for the |
|
652 | - * provided user |
|
653 | - * |
|
654 | - * @param string $objectType |
|
655 | - * @param string $objectId |
|
656 | - * @param \DateTime $dateTime |
|
657 | - * @param IUser $user |
|
658 | - * @since 9.0.0 |
|
659 | - */ |
|
660 | - public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) { |
|
661 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
662 | - |
|
663 | - $qb = $this->dbConn->getQueryBuilder(); |
|
664 | - $values = [ |
|
665 | - 'user_id' => $qb->createNamedParameter($user->getUID()), |
|
666 | - 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'), |
|
667 | - 'object_type' => $qb->createNamedParameter($objectType), |
|
668 | - 'object_id' => $qb->createNamedParameter($objectId), |
|
669 | - ]; |
|
670 | - |
|
671 | - // Strategy: try to update, if this does not return affected rows, do an insert. |
|
672 | - $affectedRows = $qb |
|
673 | - ->update('comments_read_markers') |
|
674 | - ->set('user_id', $values['user_id']) |
|
675 | - ->set('marker_datetime', $values['marker_datetime']) |
|
676 | - ->set('object_type', $values['object_type']) |
|
677 | - ->set('object_id', $values['object_id']) |
|
678 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
679 | - ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
680 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
681 | - ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
682 | - ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
683 | - ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
684 | - ->execute(); |
|
685 | - |
|
686 | - if ($affectedRows > 0) { |
|
687 | - return; |
|
688 | - } |
|
689 | - |
|
690 | - $qb->insert('comments_read_markers') |
|
691 | - ->values($values) |
|
692 | - ->execute(); |
|
693 | - } |
|
694 | - |
|
695 | - /** |
|
696 | - * returns the read marker for a given file to the specified date for the |
|
697 | - * provided user. It returns null, when the marker is not present, i.e. |
|
698 | - * no comments were marked as read. |
|
699 | - * |
|
700 | - * @param string $objectType |
|
701 | - * @param string $objectId |
|
702 | - * @param IUser $user |
|
703 | - * @return \DateTime|null |
|
704 | - * @since 9.0.0 |
|
705 | - */ |
|
706 | - public function getReadMark($objectType, $objectId, IUser $user) { |
|
707 | - $qb = $this->dbConn->getQueryBuilder(); |
|
708 | - $resultStatement = $qb->select('marker_datetime') |
|
709 | - ->from('comments_read_markers') |
|
710 | - ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
711 | - ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
712 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
713 | - ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
714 | - ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
715 | - ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
716 | - ->execute(); |
|
717 | - |
|
718 | - $data = $resultStatement->fetch(); |
|
719 | - $resultStatement->closeCursor(); |
|
720 | - if(!$data || is_null($data['marker_datetime'])) { |
|
721 | - return null; |
|
722 | - } |
|
723 | - |
|
724 | - return new \DateTime($data['marker_datetime']); |
|
725 | - } |
|
726 | - |
|
727 | - /** |
|
728 | - * deletes the read markers on the specified object |
|
729 | - * |
|
730 | - * @param string $objectType |
|
731 | - * @param string $objectId |
|
732 | - * @return bool |
|
733 | - * @since 9.0.0 |
|
734 | - */ |
|
735 | - public function deleteReadMarksOnObject($objectType, $objectId) { |
|
736 | - $this->checkRoleParameters('Object', $objectType, $objectId); |
|
737 | - |
|
738 | - $qb = $this->dbConn->getQueryBuilder(); |
|
739 | - $query = $qb->delete('comments_read_markers') |
|
740 | - ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
741 | - ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
742 | - ->setParameter('object_type', $objectType) |
|
743 | - ->setParameter('object_id', $objectId); |
|
744 | - |
|
745 | - try { |
|
746 | - $affectedRows = $query->execute(); |
|
747 | - } catch (DriverException $e) { |
|
748 | - $this->logger->logException($e, ['app' => 'core_comments']); |
|
749 | - return false; |
|
750 | - } |
|
751 | - return ($affectedRows > 0); |
|
752 | - } |
|
753 | - |
|
754 | - /** |
|
755 | - * registers an Entity to the manager, so event notifications can be send |
|
756 | - * to consumers of the comments infrastructure |
|
757 | - * |
|
758 | - * @param \Closure $closure |
|
759 | - */ |
|
760 | - public function registerEventHandler(\Closure $closure) { |
|
761 | - $this->eventHandlerClosures[] = $closure; |
|
762 | - $this->eventHandlers = []; |
|
763 | - } |
|
764 | - |
|
765 | - /** |
|
766 | - * registers a method that resolves an ID to a display name for a given type |
|
767 | - * |
|
768 | - * @param string $type |
|
769 | - * @param \Closure $closure |
|
770 | - * @throws \OutOfBoundsException |
|
771 | - * @since 11.0.0 |
|
772 | - * |
|
773 | - * Only one resolver shall be registered per type. Otherwise a |
|
774 | - * \OutOfBoundsException has to thrown. |
|
775 | - */ |
|
776 | - public function registerDisplayNameResolver($type, \Closure $closure) { |
|
777 | - if(!is_string($type)) { |
|
778 | - throw new \InvalidArgumentException('String expected.'); |
|
779 | - } |
|
780 | - if(isset($this->displayNameResolvers[$type])) { |
|
781 | - throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
|
782 | - } |
|
783 | - $this->displayNameResolvers[$type] = $closure; |
|
784 | - } |
|
785 | - |
|
786 | - /** |
|
787 | - * resolves a given ID of a given Type to a display name. |
|
788 | - * |
|
789 | - * @param string $type |
|
790 | - * @param string $id |
|
791 | - * @return string |
|
792 | - * @throws \OutOfBoundsException |
|
793 | - * @since 11.0.0 |
|
794 | - * |
|
795 | - * If a provided type was not registered, an \OutOfBoundsException shall |
|
796 | - * be thrown. It is upon the resolver discretion what to return of the |
|
797 | - * provided ID is unknown. It must be ensured that a string is returned. |
|
798 | - */ |
|
799 | - public function resolveDisplayName($type, $id) { |
|
800 | - if(!is_string($type)) { |
|
801 | - throw new \InvalidArgumentException('String expected.'); |
|
802 | - } |
|
803 | - if(!isset($this->displayNameResolvers[$type])) { |
|
804 | - throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
|
805 | - } |
|
806 | - return (string)$this->displayNameResolvers[$type]($id); |
|
807 | - } |
|
808 | - |
|
809 | - /** |
|
810 | - * returns valid, registered entities |
|
811 | - * |
|
812 | - * @return \OCP\Comments\ICommentsEventHandler[] |
|
813 | - */ |
|
814 | - private function getEventHandlers() { |
|
815 | - if(!empty($this->eventHandlers)) { |
|
816 | - return $this->eventHandlers; |
|
817 | - } |
|
818 | - |
|
819 | - $this->eventHandlers = []; |
|
820 | - foreach ($this->eventHandlerClosures as $name => $closure) { |
|
821 | - $entity = $closure(); |
|
822 | - if (!($entity instanceof ICommentsEventHandler)) { |
|
823 | - throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface'); |
|
824 | - } |
|
825 | - $this->eventHandlers[$name] = $entity; |
|
826 | - } |
|
827 | - |
|
828 | - return $this->eventHandlers; |
|
829 | - } |
|
830 | - |
|
831 | - /** |
|
832 | - * sends notifications to the registered entities |
|
833 | - * |
|
834 | - * @param $eventType |
|
835 | - * @param IComment $comment |
|
836 | - */ |
|
837 | - private function sendEvent($eventType, IComment $comment) { |
|
838 | - $entities = $this->getEventHandlers(); |
|
839 | - $event = new CommentsEvent($eventType, $comment); |
|
840 | - foreach ($entities as $entity) { |
|
841 | - $entity->handle($event); |
|
842 | - } |
|
843 | - } |
|
40 | + /** @var IDBConnection */ |
|
41 | + protected $dbConn; |
|
42 | + |
|
43 | + /** @var ILogger */ |
|
44 | + protected $logger; |
|
45 | + |
|
46 | + /** @var IConfig */ |
|
47 | + protected $config; |
|
48 | + |
|
49 | + /** @var IComment[] */ |
|
50 | + protected $commentsCache = []; |
|
51 | + |
|
52 | + /** @var \Closure[] */ |
|
53 | + protected $eventHandlerClosures = []; |
|
54 | + |
|
55 | + /** @var ICommentsEventHandler[] */ |
|
56 | + protected $eventHandlers = []; |
|
57 | + |
|
58 | + /** @var \Closure[] */ |
|
59 | + protected $displayNameResolvers = []; |
|
60 | + |
|
61 | + /** |
|
62 | + * Manager constructor. |
|
63 | + * |
|
64 | + * @param IDBConnection $dbConn |
|
65 | + * @param ILogger $logger |
|
66 | + * @param IConfig $config |
|
67 | + */ |
|
68 | + public function __construct( |
|
69 | + IDBConnection $dbConn, |
|
70 | + ILogger $logger, |
|
71 | + IConfig $config |
|
72 | + ) { |
|
73 | + $this->dbConn = $dbConn; |
|
74 | + $this->logger = $logger; |
|
75 | + $this->config = $config; |
|
76 | + } |
|
77 | + |
|
78 | + /** |
|
79 | + * converts data base data into PHP native, proper types as defined by |
|
80 | + * IComment interface. |
|
81 | + * |
|
82 | + * @param array $data |
|
83 | + * @return array |
|
84 | + */ |
|
85 | + protected function normalizeDatabaseData(array $data) { |
|
86 | + $data['id'] = strval($data['id']); |
|
87 | + $data['parent_id'] = strval($data['parent_id']); |
|
88 | + $data['topmost_parent_id'] = strval($data['topmost_parent_id']); |
|
89 | + $data['creation_timestamp'] = new \DateTime($data['creation_timestamp']); |
|
90 | + if (!is_null($data['latest_child_timestamp'])) { |
|
91 | + $data['latest_child_timestamp'] = new \DateTime($data['latest_child_timestamp']); |
|
92 | + } |
|
93 | + $data['children_count'] = intval($data['children_count']); |
|
94 | + return $data; |
|
95 | + } |
|
96 | + |
|
97 | + /** |
|
98 | + * prepares a comment for an insert or update operation after making sure |
|
99 | + * all necessary fields have a value assigned. |
|
100 | + * |
|
101 | + * @param IComment $comment |
|
102 | + * @return IComment returns the same updated IComment instance as provided |
|
103 | + * by parameter for convenience |
|
104 | + * @throws \UnexpectedValueException |
|
105 | + */ |
|
106 | + protected function prepareCommentForDatabaseWrite(IComment $comment) { |
|
107 | + if( !$comment->getActorType() |
|
108 | + || !$comment->getActorId() |
|
109 | + || !$comment->getObjectType() |
|
110 | + || !$comment->getObjectId() |
|
111 | + || !$comment->getVerb() |
|
112 | + ) { |
|
113 | + throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
|
114 | + } |
|
115 | + |
|
116 | + if($comment->getId() === '') { |
|
117 | + $comment->setChildrenCount(0); |
|
118 | + $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
|
119 | + $comment->setLatestChildDateTime(null); |
|
120 | + } |
|
121 | + |
|
122 | + if(is_null($comment->getCreationDateTime())) { |
|
123 | + $comment->setCreationDateTime(new \DateTime()); |
|
124 | + } |
|
125 | + |
|
126 | + if($comment->getParentId() !== '0') { |
|
127 | + $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
|
128 | + } else { |
|
129 | + $comment->setTopmostParentId('0'); |
|
130 | + } |
|
131 | + |
|
132 | + $this->cache($comment); |
|
133 | + |
|
134 | + return $comment; |
|
135 | + } |
|
136 | + |
|
137 | + /** |
|
138 | + * returns the topmost parent id of a given comment identified by ID |
|
139 | + * |
|
140 | + * @param string $id |
|
141 | + * @return string |
|
142 | + * @throws NotFoundException |
|
143 | + */ |
|
144 | + protected function determineTopmostParentId($id) { |
|
145 | + $comment = $this->get($id); |
|
146 | + if($comment->getParentId() === '0') { |
|
147 | + return $comment->getId(); |
|
148 | + } else { |
|
149 | + return $this->determineTopmostParentId($comment->getId()); |
|
150 | + } |
|
151 | + } |
|
152 | + |
|
153 | + /** |
|
154 | + * updates child information of a comment |
|
155 | + * |
|
156 | + * @param string $id |
|
157 | + * @param \DateTime $cDateTime the date time of the most recent child |
|
158 | + * @throws NotFoundException |
|
159 | + */ |
|
160 | + protected function updateChildrenInformation($id, \DateTime $cDateTime) { |
|
161 | + $qb = $this->dbConn->getQueryBuilder(); |
|
162 | + $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
163 | + ->from('comments') |
|
164 | + ->where($qb->expr()->eq('parent_id', $qb->createParameter('id'))) |
|
165 | + ->setParameter('id', $id); |
|
166 | + |
|
167 | + $resultStatement = $query->execute(); |
|
168 | + $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
169 | + $resultStatement->closeCursor(); |
|
170 | + $children = intval($data[0]); |
|
171 | + |
|
172 | + $comment = $this->get($id); |
|
173 | + $comment->setChildrenCount($children); |
|
174 | + $comment->setLatestChildDateTime($cDateTime); |
|
175 | + $this->save($comment); |
|
176 | + } |
|
177 | + |
|
178 | + /** |
|
179 | + * Tests whether actor or object type and id parameters are acceptable. |
|
180 | + * Throws exception if not. |
|
181 | + * |
|
182 | + * @param string $role |
|
183 | + * @param string $type |
|
184 | + * @param string $id |
|
185 | + * @throws \InvalidArgumentException |
|
186 | + */ |
|
187 | + protected function checkRoleParameters($role, $type, $id) { |
|
188 | + if( |
|
189 | + !is_string($type) || empty($type) |
|
190 | + || !is_string($id) || empty($id) |
|
191 | + ) { |
|
192 | + throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
193 | + } |
|
194 | + } |
|
195 | + |
|
196 | + /** |
|
197 | + * run-time caches a comment |
|
198 | + * |
|
199 | + * @param IComment $comment |
|
200 | + */ |
|
201 | + protected function cache(IComment $comment) { |
|
202 | + $id = $comment->getId(); |
|
203 | + if(empty($id)) { |
|
204 | + return; |
|
205 | + } |
|
206 | + $this->commentsCache[strval($id)] = $comment; |
|
207 | + } |
|
208 | + |
|
209 | + /** |
|
210 | + * removes an entry from the comments run time cache |
|
211 | + * |
|
212 | + * @param mixed $id the comment's id |
|
213 | + */ |
|
214 | + protected function uncache($id) { |
|
215 | + $id = strval($id); |
|
216 | + if (isset($this->commentsCache[$id])) { |
|
217 | + unset($this->commentsCache[$id]); |
|
218 | + } |
|
219 | + } |
|
220 | + |
|
221 | + /** |
|
222 | + * returns a comment instance |
|
223 | + * |
|
224 | + * @param string $id the ID of the comment |
|
225 | + * @return IComment |
|
226 | + * @throws NotFoundException |
|
227 | + * @throws \InvalidArgumentException |
|
228 | + * @since 9.0.0 |
|
229 | + */ |
|
230 | + public function get($id) { |
|
231 | + if(intval($id) === 0) { |
|
232 | + throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
|
233 | + } |
|
234 | + |
|
235 | + if(isset($this->commentsCache[$id])) { |
|
236 | + return $this->commentsCache[$id]; |
|
237 | + } |
|
238 | + |
|
239 | + $qb = $this->dbConn->getQueryBuilder(); |
|
240 | + $resultStatement = $qb->select('*') |
|
241 | + ->from('comments') |
|
242 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
243 | + ->setParameter('id', $id, IQueryBuilder::PARAM_INT) |
|
244 | + ->execute(); |
|
245 | + |
|
246 | + $data = $resultStatement->fetch(); |
|
247 | + $resultStatement->closeCursor(); |
|
248 | + if(!$data) { |
|
249 | + throw new NotFoundException(); |
|
250 | + } |
|
251 | + |
|
252 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
253 | + $this->cache($comment); |
|
254 | + return $comment; |
|
255 | + } |
|
256 | + |
|
257 | + /** |
|
258 | + * returns the comment specified by the id and all it's child comments. |
|
259 | + * At this point of time, we do only support one level depth. |
|
260 | + * |
|
261 | + * @param string $id |
|
262 | + * @param int $limit max number of entries to return, 0 returns all |
|
263 | + * @param int $offset the start entry |
|
264 | + * @return array |
|
265 | + * @since 9.0.0 |
|
266 | + * |
|
267 | + * The return array looks like this |
|
268 | + * [ |
|
269 | + * 'comment' => IComment, // root comment |
|
270 | + * 'replies' => |
|
271 | + * [ |
|
272 | + * 0 => |
|
273 | + * [ |
|
274 | + * 'comment' => IComment, |
|
275 | + * 'replies' => [] |
|
276 | + * ] |
|
277 | + * 1 => |
|
278 | + * [ |
|
279 | + * 'comment' => IComment, |
|
280 | + * 'replies'=> [] |
|
281 | + * ], |
|
282 | + * … |
|
283 | + * ] |
|
284 | + * ] |
|
285 | + */ |
|
286 | + public function getTree($id, $limit = 0, $offset = 0) { |
|
287 | + $tree = []; |
|
288 | + $tree['comment'] = $this->get($id); |
|
289 | + $tree['replies'] = []; |
|
290 | + |
|
291 | + $qb = $this->dbConn->getQueryBuilder(); |
|
292 | + $query = $qb->select('*') |
|
293 | + ->from('comments') |
|
294 | + ->where($qb->expr()->eq('topmost_parent_id', $qb->createParameter('id'))) |
|
295 | + ->orderBy('creation_timestamp', 'DESC') |
|
296 | + ->setParameter('id', $id); |
|
297 | + |
|
298 | + if($limit > 0) { |
|
299 | + $query->setMaxResults($limit); |
|
300 | + } |
|
301 | + if($offset > 0) { |
|
302 | + $query->setFirstResult($offset); |
|
303 | + } |
|
304 | + |
|
305 | + $resultStatement = $query->execute(); |
|
306 | + while($data = $resultStatement->fetch()) { |
|
307 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
308 | + $this->cache($comment); |
|
309 | + $tree['replies'][] = [ |
|
310 | + 'comment' => $comment, |
|
311 | + 'replies' => [] |
|
312 | + ]; |
|
313 | + } |
|
314 | + $resultStatement->closeCursor(); |
|
315 | + |
|
316 | + return $tree; |
|
317 | + } |
|
318 | + |
|
319 | + /** |
|
320 | + * returns comments for a specific object (e.g. a file). |
|
321 | + * |
|
322 | + * The sort order is always newest to oldest. |
|
323 | + * |
|
324 | + * @param string $objectType the object type, e.g. 'files' |
|
325 | + * @param string $objectId the id of the object |
|
326 | + * @param int $limit optional, number of maximum comments to be returned. if |
|
327 | + * not specified, all comments are returned. |
|
328 | + * @param int $offset optional, starting point |
|
329 | + * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
330 | + * that may be returned |
|
331 | + * @return IComment[] |
|
332 | + * @since 9.0.0 |
|
333 | + */ |
|
334 | + public function getForObject( |
|
335 | + $objectType, |
|
336 | + $objectId, |
|
337 | + $limit = 0, |
|
338 | + $offset = 0, |
|
339 | + \DateTime $notOlderThan = null |
|
340 | + ) { |
|
341 | + $comments = []; |
|
342 | + |
|
343 | + $qb = $this->dbConn->getQueryBuilder(); |
|
344 | + $query = $qb->select('*') |
|
345 | + ->from('comments') |
|
346 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
347 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
348 | + ->orderBy('creation_timestamp', 'DESC') |
|
349 | + ->setParameter('type', $objectType) |
|
350 | + ->setParameter('id', $objectId); |
|
351 | + |
|
352 | + if($limit > 0) { |
|
353 | + $query->setMaxResults($limit); |
|
354 | + } |
|
355 | + if($offset > 0) { |
|
356 | + $query->setFirstResult($offset); |
|
357 | + } |
|
358 | + if(!is_null($notOlderThan)) { |
|
359 | + $query |
|
360 | + ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
361 | + ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
362 | + } |
|
363 | + |
|
364 | + $resultStatement = $query->execute(); |
|
365 | + while($data = $resultStatement->fetch()) { |
|
366 | + $comment = new Comment($this->normalizeDatabaseData($data)); |
|
367 | + $this->cache($comment); |
|
368 | + $comments[] = $comment; |
|
369 | + } |
|
370 | + $resultStatement->closeCursor(); |
|
371 | + |
|
372 | + return $comments; |
|
373 | + } |
|
374 | + |
|
375 | + /** |
|
376 | + * @param $objectType string the object type, e.g. 'files' |
|
377 | + * @param $objectId string the id of the object |
|
378 | + * @param \DateTime $notOlderThan optional, timestamp of the oldest comments |
|
379 | + * that may be returned |
|
380 | + * @return Int |
|
381 | + * @since 9.0.0 |
|
382 | + */ |
|
383 | + public function getNumberOfCommentsForObject($objectType, $objectId, \DateTime $notOlderThan = null) { |
|
384 | + $qb = $this->dbConn->getQueryBuilder(); |
|
385 | + $query = $qb->select($qb->createFunction('COUNT(`id`)')) |
|
386 | + ->from('comments') |
|
387 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
388 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
389 | + ->setParameter('type', $objectType) |
|
390 | + ->setParameter('id', $objectId); |
|
391 | + |
|
392 | + if(!is_null($notOlderThan)) { |
|
393 | + $query |
|
394 | + ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
|
395 | + ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
|
396 | + } |
|
397 | + |
|
398 | + $resultStatement = $query->execute(); |
|
399 | + $data = $resultStatement->fetch(\PDO::FETCH_NUM); |
|
400 | + $resultStatement->closeCursor(); |
|
401 | + return intval($data[0]); |
|
402 | + } |
|
403 | + |
|
404 | + /** |
|
405 | + * creates a new comment and returns it. At this point of time, it is not |
|
406 | + * saved in the used data storage. Use save() after setting other fields |
|
407 | + * of the comment (e.g. message or verb). |
|
408 | + * |
|
409 | + * @param string $actorType the actor type (e.g. 'users') |
|
410 | + * @param string $actorId a user id |
|
411 | + * @param string $objectType the object type the comment is attached to |
|
412 | + * @param string $objectId the object id the comment is attached to |
|
413 | + * @return IComment |
|
414 | + * @since 9.0.0 |
|
415 | + */ |
|
416 | + public function create($actorType, $actorId, $objectType, $objectId) { |
|
417 | + $comment = new Comment(); |
|
418 | + $comment |
|
419 | + ->setActor($actorType, $actorId) |
|
420 | + ->setObject($objectType, $objectId); |
|
421 | + return $comment; |
|
422 | + } |
|
423 | + |
|
424 | + /** |
|
425 | + * permanently deletes the comment specified by the ID |
|
426 | + * |
|
427 | + * When the comment has child comments, their parent ID will be changed to |
|
428 | + * the parent ID of the item that is to be deleted. |
|
429 | + * |
|
430 | + * @param string $id |
|
431 | + * @return bool |
|
432 | + * @throws \InvalidArgumentException |
|
433 | + * @since 9.0.0 |
|
434 | + */ |
|
435 | + public function delete($id) { |
|
436 | + if(!is_string($id)) { |
|
437 | + throw new \InvalidArgumentException('Parameter must be string'); |
|
438 | + } |
|
439 | + |
|
440 | + try { |
|
441 | + $comment = $this->get($id); |
|
442 | + } catch (\Exception $e) { |
|
443 | + // Ignore exceptions, we just don't fire a hook then |
|
444 | + $comment = null; |
|
445 | + } |
|
446 | + |
|
447 | + $qb = $this->dbConn->getQueryBuilder(); |
|
448 | + $query = $qb->delete('comments') |
|
449 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
450 | + ->setParameter('id', $id); |
|
451 | + |
|
452 | + try { |
|
453 | + $affectedRows = $query->execute(); |
|
454 | + $this->uncache($id); |
|
455 | + } catch (DriverException $e) { |
|
456 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
457 | + return false; |
|
458 | + } |
|
459 | + |
|
460 | + if ($affectedRows > 0 && $comment instanceof IComment) { |
|
461 | + $this->sendEvent(CommentsEvent::EVENT_DELETE, $comment); |
|
462 | + } |
|
463 | + |
|
464 | + return ($affectedRows > 0); |
|
465 | + } |
|
466 | + |
|
467 | + /** |
|
468 | + * saves the comment permanently |
|
469 | + * |
|
470 | + * if the supplied comment has an empty ID, a new entry comment will be |
|
471 | + * saved and the instance updated with the new ID. |
|
472 | + * |
|
473 | + * Otherwise, an existing comment will be updated. |
|
474 | + * |
|
475 | + * Throws NotFoundException when a comment that is to be updated does not |
|
476 | + * exist anymore at this point of time. |
|
477 | + * |
|
478 | + * @param IComment $comment |
|
479 | + * @return bool |
|
480 | + * @throws NotFoundException |
|
481 | + * @since 9.0.0 |
|
482 | + */ |
|
483 | + public function save(IComment $comment) { |
|
484 | + if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
485 | + $result = $this->insert($comment); |
|
486 | + } else { |
|
487 | + $result = $this->update($comment); |
|
488 | + } |
|
489 | + |
|
490 | + if($result && !!$comment->getParentId()) { |
|
491 | + $this->updateChildrenInformation( |
|
492 | + $comment->getParentId(), |
|
493 | + $comment->getCreationDateTime() |
|
494 | + ); |
|
495 | + $this->cache($comment); |
|
496 | + } |
|
497 | + |
|
498 | + return $result; |
|
499 | + } |
|
500 | + |
|
501 | + /** |
|
502 | + * inserts the provided comment in the database |
|
503 | + * |
|
504 | + * @param IComment $comment |
|
505 | + * @return bool |
|
506 | + */ |
|
507 | + protected function insert(IComment &$comment) { |
|
508 | + $qb = $this->dbConn->getQueryBuilder(); |
|
509 | + $affectedRows = $qb |
|
510 | + ->insert('comments') |
|
511 | + ->values([ |
|
512 | + 'parent_id' => $qb->createNamedParameter($comment->getParentId()), |
|
513 | + 'topmost_parent_id' => $qb->createNamedParameter($comment->getTopmostParentId()), |
|
514 | + 'children_count' => $qb->createNamedParameter($comment->getChildrenCount()), |
|
515 | + 'actor_type' => $qb->createNamedParameter($comment->getActorType()), |
|
516 | + 'actor_id' => $qb->createNamedParameter($comment->getActorId()), |
|
517 | + 'message' => $qb->createNamedParameter($comment->getMessage()), |
|
518 | + 'verb' => $qb->createNamedParameter($comment->getVerb()), |
|
519 | + 'creation_timestamp' => $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime'), |
|
520 | + 'latest_child_timestamp' => $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime'), |
|
521 | + 'object_type' => $qb->createNamedParameter($comment->getObjectType()), |
|
522 | + 'object_id' => $qb->createNamedParameter($comment->getObjectId()), |
|
523 | + ]) |
|
524 | + ->execute(); |
|
525 | + |
|
526 | + if ($affectedRows > 0) { |
|
527 | + $comment->setId(strval($qb->getLastInsertId())); |
|
528 | + $this->sendEvent(CommentsEvent::EVENT_ADD, $comment); |
|
529 | + } |
|
530 | + |
|
531 | + return $affectedRows > 0; |
|
532 | + } |
|
533 | + |
|
534 | + /** |
|
535 | + * updates a Comment data row |
|
536 | + * |
|
537 | + * @param IComment $comment |
|
538 | + * @return bool |
|
539 | + * @throws NotFoundException |
|
540 | + */ |
|
541 | + protected function update(IComment $comment) { |
|
542 | + // for properly working preUpdate Events we need the old comments as is |
|
543 | + // in the DB and overcome caching. Also avoid that outdated information stays. |
|
544 | + $this->uncache($comment->getId()); |
|
545 | + $this->sendEvent(CommentsEvent::EVENT_PRE_UPDATE, $this->get($comment->getId())); |
|
546 | + $this->uncache($comment->getId()); |
|
547 | + |
|
548 | + $qb = $this->dbConn->getQueryBuilder(); |
|
549 | + $affectedRows = $qb |
|
550 | + ->update('comments') |
|
551 | + ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
552 | + ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
553 | + ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
554 | + ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
555 | + ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
556 | + ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
557 | + ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
558 | + ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
559 | + ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
560 | + ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
561 | + ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
562 | + ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
|
563 | + ->setParameter('id', $comment->getId()) |
|
564 | + ->execute(); |
|
565 | + |
|
566 | + if($affectedRows === 0) { |
|
567 | + throw new NotFoundException('Comment to update does ceased to exist'); |
|
568 | + } |
|
569 | + |
|
570 | + $this->sendEvent(CommentsEvent::EVENT_UPDATE, $comment); |
|
571 | + |
|
572 | + return $affectedRows > 0; |
|
573 | + } |
|
574 | + |
|
575 | + /** |
|
576 | + * removes references to specific actor (e.g. on user delete) of a comment. |
|
577 | + * The comment itself must not get lost/deleted. |
|
578 | + * |
|
579 | + * @param string $actorType the actor type (e.g. 'users') |
|
580 | + * @param string $actorId a user id |
|
581 | + * @return boolean |
|
582 | + * @since 9.0.0 |
|
583 | + */ |
|
584 | + public function deleteReferencesOfActor($actorType, $actorId) { |
|
585 | + $this->checkRoleParameters('Actor', $actorType, $actorId); |
|
586 | + |
|
587 | + $qb = $this->dbConn->getQueryBuilder(); |
|
588 | + $affectedRows = $qb |
|
589 | + ->update('comments') |
|
590 | + ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
591 | + ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
592 | + ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
|
593 | + ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
|
594 | + ->setParameter('type', $actorType) |
|
595 | + ->setParameter('id', $actorId) |
|
596 | + ->execute(); |
|
597 | + |
|
598 | + $this->commentsCache = []; |
|
599 | + |
|
600 | + return is_int($affectedRows); |
|
601 | + } |
|
602 | + |
|
603 | + /** |
|
604 | + * deletes all comments made of a specific object (e.g. on file delete) |
|
605 | + * |
|
606 | + * @param string $objectType the object type (e.g. 'files') |
|
607 | + * @param string $objectId e.g. the file id |
|
608 | + * @return boolean |
|
609 | + * @since 9.0.0 |
|
610 | + */ |
|
611 | + public function deleteCommentsAtObject($objectType, $objectId) { |
|
612 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
613 | + |
|
614 | + $qb = $this->dbConn->getQueryBuilder(); |
|
615 | + $affectedRows = $qb |
|
616 | + ->delete('comments') |
|
617 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('type'))) |
|
618 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('id'))) |
|
619 | + ->setParameter('type', $objectType) |
|
620 | + ->setParameter('id', $objectId) |
|
621 | + ->execute(); |
|
622 | + |
|
623 | + $this->commentsCache = []; |
|
624 | + |
|
625 | + return is_int($affectedRows); |
|
626 | + } |
|
627 | + |
|
628 | + /** |
|
629 | + * deletes the read markers for the specified user |
|
630 | + * |
|
631 | + * @param \OCP\IUser $user |
|
632 | + * @return bool |
|
633 | + * @since 9.0.0 |
|
634 | + */ |
|
635 | + public function deleteReadMarksFromUser(IUser $user) { |
|
636 | + $qb = $this->dbConn->getQueryBuilder(); |
|
637 | + $query = $qb->delete('comments_read_markers') |
|
638 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
639 | + ->setParameter('user_id', $user->getUID()); |
|
640 | + |
|
641 | + try { |
|
642 | + $affectedRows = $query->execute(); |
|
643 | + } catch (DriverException $e) { |
|
644 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
645 | + return false; |
|
646 | + } |
|
647 | + return ($affectedRows > 0); |
|
648 | + } |
|
649 | + |
|
650 | + /** |
|
651 | + * sets the read marker for a given file to the specified date for the |
|
652 | + * provided user |
|
653 | + * |
|
654 | + * @param string $objectType |
|
655 | + * @param string $objectId |
|
656 | + * @param \DateTime $dateTime |
|
657 | + * @param IUser $user |
|
658 | + * @since 9.0.0 |
|
659 | + */ |
|
660 | + public function setReadMark($objectType, $objectId, \DateTime $dateTime, IUser $user) { |
|
661 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
662 | + |
|
663 | + $qb = $this->dbConn->getQueryBuilder(); |
|
664 | + $values = [ |
|
665 | + 'user_id' => $qb->createNamedParameter($user->getUID()), |
|
666 | + 'marker_datetime' => $qb->createNamedParameter($dateTime, 'datetime'), |
|
667 | + 'object_type' => $qb->createNamedParameter($objectType), |
|
668 | + 'object_id' => $qb->createNamedParameter($objectId), |
|
669 | + ]; |
|
670 | + |
|
671 | + // Strategy: try to update, if this does not return affected rows, do an insert. |
|
672 | + $affectedRows = $qb |
|
673 | + ->update('comments_read_markers') |
|
674 | + ->set('user_id', $values['user_id']) |
|
675 | + ->set('marker_datetime', $values['marker_datetime']) |
|
676 | + ->set('object_type', $values['object_type']) |
|
677 | + ->set('object_id', $values['object_id']) |
|
678 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
679 | + ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
680 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
681 | + ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
682 | + ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
683 | + ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
684 | + ->execute(); |
|
685 | + |
|
686 | + if ($affectedRows > 0) { |
|
687 | + return; |
|
688 | + } |
|
689 | + |
|
690 | + $qb->insert('comments_read_markers') |
|
691 | + ->values($values) |
|
692 | + ->execute(); |
|
693 | + } |
|
694 | + |
|
695 | + /** |
|
696 | + * returns the read marker for a given file to the specified date for the |
|
697 | + * provided user. It returns null, when the marker is not present, i.e. |
|
698 | + * no comments were marked as read. |
|
699 | + * |
|
700 | + * @param string $objectType |
|
701 | + * @param string $objectId |
|
702 | + * @param IUser $user |
|
703 | + * @return \DateTime|null |
|
704 | + * @since 9.0.0 |
|
705 | + */ |
|
706 | + public function getReadMark($objectType, $objectId, IUser $user) { |
|
707 | + $qb = $this->dbConn->getQueryBuilder(); |
|
708 | + $resultStatement = $qb->select('marker_datetime') |
|
709 | + ->from('comments_read_markers') |
|
710 | + ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
|
711 | + ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
712 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
713 | + ->setParameter('user_id', $user->getUID(), IQueryBuilder::PARAM_STR) |
|
714 | + ->setParameter('object_type', $objectType, IQueryBuilder::PARAM_STR) |
|
715 | + ->setParameter('object_id', $objectId, IQueryBuilder::PARAM_STR) |
|
716 | + ->execute(); |
|
717 | + |
|
718 | + $data = $resultStatement->fetch(); |
|
719 | + $resultStatement->closeCursor(); |
|
720 | + if(!$data || is_null($data['marker_datetime'])) { |
|
721 | + return null; |
|
722 | + } |
|
723 | + |
|
724 | + return new \DateTime($data['marker_datetime']); |
|
725 | + } |
|
726 | + |
|
727 | + /** |
|
728 | + * deletes the read markers on the specified object |
|
729 | + * |
|
730 | + * @param string $objectType |
|
731 | + * @param string $objectId |
|
732 | + * @return bool |
|
733 | + * @since 9.0.0 |
|
734 | + */ |
|
735 | + public function deleteReadMarksOnObject($objectType, $objectId) { |
|
736 | + $this->checkRoleParameters('Object', $objectType, $objectId); |
|
737 | + |
|
738 | + $qb = $this->dbConn->getQueryBuilder(); |
|
739 | + $query = $qb->delete('comments_read_markers') |
|
740 | + ->where($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
|
741 | + ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
|
742 | + ->setParameter('object_type', $objectType) |
|
743 | + ->setParameter('object_id', $objectId); |
|
744 | + |
|
745 | + try { |
|
746 | + $affectedRows = $query->execute(); |
|
747 | + } catch (DriverException $e) { |
|
748 | + $this->logger->logException($e, ['app' => 'core_comments']); |
|
749 | + return false; |
|
750 | + } |
|
751 | + return ($affectedRows > 0); |
|
752 | + } |
|
753 | + |
|
754 | + /** |
|
755 | + * registers an Entity to the manager, so event notifications can be send |
|
756 | + * to consumers of the comments infrastructure |
|
757 | + * |
|
758 | + * @param \Closure $closure |
|
759 | + */ |
|
760 | + public function registerEventHandler(\Closure $closure) { |
|
761 | + $this->eventHandlerClosures[] = $closure; |
|
762 | + $this->eventHandlers = []; |
|
763 | + } |
|
764 | + |
|
765 | + /** |
|
766 | + * registers a method that resolves an ID to a display name for a given type |
|
767 | + * |
|
768 | + * @param string $type |
|
769 | + * @param \Closure $closure |
|
770 | + * @throws \OutOfBoundsException |
|
771 | + * @since 11.0.0 |
|
772 | + * |
|
773 | + * Only one resolver shall be registered per type. Otherwise a |
|
774 | + * \OutOfBoundsException has to thrown. |
|
775 | + */ |
|
776 | + public function registerDisplayNameResolver($type, \Closure $closure) { |
|
777 | + if(!is_string($type)) { |
|
778 | + throw new \InvalidArgumentException('String expected.'); |
|
779 | + } |
|
780 | + if(isset($this->displayNameResolvers[$type])) { |
|
781 | + throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
|
782 | + } |
|
783 | + $this->displayNameResolvers[$type] = $closure; |
|
784 | + } |
|
785 | + |
|
786 | + /** |
|
787 | + * resolves a given ID of a given Type to a display name. |
|
788 | + * |
|
789 | + * @param string $type |
|
790 | + * @param string $id |
|
791 | + * @return string |
|
792 | + * @throws \OutOfBoundsException |
|
793 | + * @since 11.0.0 |
|
794 | + * |
|
795 | + * If a provided type was not registered, an \OutOfBoundsException shall |
|
796 | + * be thrown. It is upon the resolver discretion what to return of the |
|
797 | + * provided ID is unknown. It must be ensured that a string is returned. |
|
798 | + */ |
|
799 | + public function resolveDisplayName($type, $id) { |
|
800 | + if(!is_string($type)) { |
|
801 | + throw new \InvalidArgumentException('String expected.'); |
|
802 | + } |
|
803 | + if(!isset($this->displayNameResolvers[$type])) { |
|
804 | + throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
|
805 | + } |
|
806 | + return (string)$this->displayNameResolvers[$type]($id); |
|
807 | + } |
|
808 | + |
|
809 | + /** |
|
810 | + * returns valid, registered entities |
|
811 | + * |
|
812 | + * @return \OCP\Comments\ICommentsEventHandler[] |
|
813 | + */ |
|
814 | + private function getEventHandlers() { |
|
815 | + if(!empty($this->eventHandlers)) { |
|
816 | + return $this->eventHandlers; |
|
817 | + } |
|
818 | + |
|
819 | + $this->eventHandlers = []; |
|
820 | + foreach ($this->eventHandlerClosures as $name => $closure) { |
|
821 | + $entity = $closure(); |
|
822 | + if (!($entity instanceof ICommentsEventHandler)) { |
|
823 | + throw new \InvalidArgumentException('The given entity does not implement the ICommentsEntity interface'); |
|
824 | + } |
|
825 | + $this->eventHandlers[$name] = $entity; |
|
826 | + } |
|
827 | + |
|
828 | + return $this->eventHandlers; |
|
829 | + } |
|
830 | + |
|
831 | + /** |
|
832 | + * sends notifications to the registered entities |
|
833 | + * |
|
834 | + * @param $eventType |
|
835 | + * @param IComment $comment |
|
836 | + */ |
|
837 | + private function sendEvent($eventType, IComment $comment) { |
|
838 | + $entities = $this->getEventHandlers(); |
|
839 | + $event = new CommentsEvent($eventType, $comment); |
|
840 | + foreach ($entities as $entity) { |
|
841 | + $entity->handle($event); |
|
842 | + } |
|
843 | + } |
|
844 | 844 | } |
@@ -104,7 +104,7 @@ discard block |
||
104 | 104 | * @throws \UnexpectedValueException |
105 | 105 | */ |
106 | 106 | protected function prepareCommentForDatabaseWrite(IComment $comment) { |
107 | - if( !$comment->getActorType() |
|
107 | + if (!$comment->getActorType() |
|
108 | 108 | || !$comment->getActorId() |
109 | 109 | || !$comment->getObjectType() |
110 | 110 | || !$comment->getObjectId() |
@@ -113,17 +113,17 @@ discard block |
||
113 | 113 | throw new \UnexpectedValueException('Actor, Object and Verb information must be provided for saving'); |
114 | 114 | } |
115 | 115 | |
116 | - if($comment->getId() === '') { |
|
116 | + if ($comment->getId() === '') { |
|
117 | 117 | $comment->setChildrenCount(0); |
118 | 118 | $comment->setLatestChildDateTime(new \DateTime('0000-00-00 00:00:00', new \DateTimeZone('UTC'))); |
119 | 119 | $comment->setLatestChildDateTime(null); |
120 | 120 | } |
121 | 121 | |
122 | - if(is_null($comment->getCreationDateTime())) { |
|
122 | + if (is_null($comment->getCreationDateTime())) { |
|
123 | 123 | $comment->setCreationDateTime(new \DateTime()); |
124 | 124 | } |
125 | 125 | |
126 | - if($comment->getParentId() !== '0') { |
|
126 | + if ($comment->getParentId() !== '0') { |
|
127 | 127 | $comment->setTopmostParentId($this->determineTopmostParentId($comment->getParentId())); |
128 | 128 | } else { |
129 | 129 | $comment->setTopmostParentId('0'); |
@@ -143,7 +143,7 @@ discard block |
||
143 | 143 | */ |
144 | 144 | protected function determineTopmostParentId($id) { |
145 | 145 | $comment = $this->get($id); |
146 | - if($comment->getParentId() === '0') { |
|
146 | + if ($comment->getParentId() === '0') { |
|
147 | 147 | return $comment->getId(); |
148 | 148 | } else { |
149 | 149 | return $this->determineTopmostParentId($comment->getId()); |
@@ -185,11 +185,11 @@ discard block |
||
185 | 185 | * @throws \InvalidArgumentException |
186 | 186 | */ |
187 | 187 | protected function checkRoleParameters($role, $type, $id) { |
188 | - if( |
|
188 | + if ( |
|
189 | 189 | !is_string($type) || empty($type) |
190 | 190 | || !is_string($id) || empty($id) |
191 | 191 | ) { |
192 | - throw new \InvalidArgumentException($role . ' parameters must be string and not empty'); |
|
192 | + throw new \InvalidArgumentException($role.' parameters must be string and not empty'); |
|
193 | 193 | } |
194 | 194 | } |
195 | 195 | |
@@ -200,7 +200,7 @@ discard block |
||
200 | 200 | */ |
201 | 201 | protected function cache(IComment $comment) { |
202 | 202 | $id = $comment->getId(); |
203 | - if(empty($id)) { |
|
203 | + if (empty($id)) { |
|
204 | 204 | return; |
205 | 205 | } |
206 | 206 | $this->commentsCache[strval($id)] = $comment; |
@@ -228,11 +228,11 @@ discard block |
||
228 | 228 | * @since 9.0.0 |
229 | 229 | */ |
230 | 230 | public function get($id) { |
231 | - if(intval($id) === 0) { |
|
231 | + if (intval($id) === 0) { |
|
232 | 232 | throw new \InvalidArgumentException('IDs must be translatable to a number in this implementation.'); |
233 | 233 | } |
234 | 234 | |
235 | - if(isset($this->commentsCache[$id])) { |
|
235 | + if (isset($this->commentsCache[$id])) { |
|
236 | 236 | return $this->commentsCache[$id]; |
237 | 237 | } |
238 | 238 | |
@@ -245,7 +245,7 @@ discard block |
||
245 | 245 | |
246 | 246 | $data = $resultStatement->fetch(); |
247 | 247 | $resultStatement->closeCursor(); |
248 | - if(!$data) { |
|
248 | + if (!$data) { |
|
249 | 249 | throw new NotFoundException(); |
250 | 250 | } |
251 | 251 | |
@@ -295,15 +295,15 @@ discard block |
||
295 | 295 | ->orderBy('creation_timestamp', 'DESC') |
296 | 296 | ->setParameter('id', $id); |
297 | 297 | |
298 | - if($limit > 0) { |
|
298 | + if ($limit > 0) { |
|
299 | 299 | $query->setMaxResults($limit); |
300 | 300 | } |
301 | - if($offset > 0) { |
|
301 | + if ($offset > 0) { |
|
302 | 302 | $query->setFirstResult($offset); |
303 | 303 | } |
304 | 304 | |
305 | 305 | $resultStatement = $query->execute(); |
306 | - while($data = $resultStatement->fetch()) { |
|
306 | + while ($data = $resultStatement->fetch()) { |
|
307 | 307 | $comment = new Comment($this->normalizeDatabaseData($data)); |
308 | 308 | $this->cache($comment); |
309 | 309 | $tree['replies'][] = [ |
@@ -349,20 +349,20 @@ discard block |
||
349 | 349 | ->setParameter('type', $objectType) |
350 | 350 | ->setParameter('id', $objectId); |
351 | 351 | |
352 | - if($limit > 0) { |
|
352 | + if ($limit > 0) { |
|
353 | 353 | $query->setMaxResults($limit); |
354 | 354 | } |
355 | - if($offset > 0) { |
|
355 | + if ($offset > 0) { |
|
356 | 356 | $query->setFirstResult($offset); |
357 | 357 | } |
358 | - if(!is_null($notOlderThan)) { |
|
358 | + if (!is_null($notOlderThan)) { |
|
359 | 359 | $query |
360 | 360 | ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
361 | 361 | ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
362 | 362 | } |
363 | 363 | |
364 | 364 | $resultStatement = $query->execute(); |
365 | - while($data = $resultStatement->fetch()) { |
|
365 | + while ($data = $resultStatement->fetch()) { |
|
366 | 366 | $comment = new Comment($this->normalizeDatabaseData($data)); |
367 | 367 | $this->cache($comment); |
368 | 368 | $comments[] = $comment; |
@@ -389,7 +389,7 @@ discard block |
||
389 | 389 | ->setParameter('type', $objectType) |
390 | 390 | ->setParameter('id', $objectId); |
391 | 391 | |
392 | - if(!is_null($notOlderThan)) { |
|
392 | + if (!is_null($notOlderThan)) { |
|
393 | 393 | $query |
394 | 394 | ->andWhere($qb->expr()->gt('creation_timestamp', $qb->createParameter('notOlderThan'))) |
395 | 395 | ->setParameter('notOlderThan', $notOlderThan, 'datetime'); |
@@ -433,7 +433,7 @@ discard block |
||
433 | 433 | * @since 9.0.0 |
434 | 434 | */ |
435 | 435 | public function delete($id) { |
436 | - if(!is_string($id)) { |
|
436 | + if (!is_string($id)) { |
|
437 | 437 | throw new \InvalidArgumentException('Parameter must be string'); |
438 | 438 | } |
439 | 439 | |
@@ -481,13 +481,13 @@ discard block |
||
481 | 481 | * @since 9.0.0 |
482 | 482 | */ |
483 | 483 | public function save(IComment $comment) { |
484 | - if($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
484 | + if ($this->prepareCommentForDatabaseWrite($comment)->getId() === '') { |
|
485 | 485 | $result = $this->insert($comment); |
486 | 486 | } else { |
487 | 487 | $result = $this->update($comment); |
488 | 488 | } |
489 | 489 | |
490 | - if($result && !!$comment->getParentId()) { |
|
490 | + if ($result && !!$comment->getParentId()) { |
|
491 | 491 | $this->updateChildrenInformation( |
492 | 492 | $comment->getParentId(), |
493 | 493 | $comment->getCreationDateTime() |
@@ -504,7 +504,7 @@ discard block |
||
504 | 504 | * @param IComment $comment |
505 | 505 | * @return bool |
506 | 506 | */ |
507 | - protected function insert(IComment &$comment) { |
|
507 | + protected function insert(IComment & $comment) { |
|
508 | 508 | $qb = $this->dbConn->getQueryBuilder(); |
509 | 509 | $affectedRows = $qb |
510 | 510 | ->insert('comments') |
@@ -548,22 +548,22 @@ discard block |
||
548 | 548 | $qb = $this->dbConn->getQueryBuilder(); |
549 | 549 | $affectedRows = $qb |
550 | 550 | ->update('comments') |
551 | - ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
552 | - ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
553 | - ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
554 | - ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
555 | - ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
556 | - ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
557 | - ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
558 | - ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
559 | - ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
560 | - ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
561 | - ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
551 | + ->set('parent_id', $qb->createNamedParameter($comment->getParentId())) |
|
552 | + ->set('topmost_parent_id', $qb->createNamedParameter($comment->getTopmostParentId())) |
|
553 | + ->set('children_count', $qb->createNamedParameter($comment->getChildrenCount())) |
|
554 | + ->set('actor_type', $qb->createNamedParameter($comment->getActorType())) |
|
555 | + ->set('actor_id', $qb->createNamedParameter($comment->getActorId())) |
|
556 | + ->set('message', $qb->createNamedParameter($comment->getMessage())) |
|
557 | + ->set('verb', $qb->createNamedParameter($comment->getVerb())) |
|
558 | + ->set('creation_timestamp', $qb->createNamedParameter($comment->getCreationDateTime(), 'datetime')) |
|
559 | + ->set('latest_child_timestamp', $qb->createNamedParameter($comment->getLatestChildDateTime(), 'datetime')) |
|
560 | + ->set('object_type', $qb->createNamedParameter($comment->getObjectType())) |
|
561 | + ->set('object_id', $qb->createNamedParameter($comment->getObjectId())) |
|
562 | 562 | ->where($qb->expr()->eq('id', $qb->createParameter('id'))) |
563 | 563 | ->setParameter('id', $comment->getId()) |
564 | 564 | ->execute(); |
565 | 565 | |
566 | - if($affectedRows === 0) { |
|
566 | + if ($affectedRows === 0) { |
|
567 | 567 | throw new NotFoundException('Comment to update does ceased to exist'); |
568 | 568 | } |
569 | 569 | |
@@ -587,8 +587,8 @@ discard block |
||
587 | 587 | $qb = $this->dbConn->getQueryBuilder(); |
588 | 588 | $affectedRows = $qb |
589 | 589 | ->update('comments') |
590 | - ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
591 | - ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
590 | + ->set('actor_type', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
591 | + ->set('actor_id', $qb->createNamedParameter(ICommentsManager::DELETED_USER)) |
|
592 | 592 | ->where($qb->expr()->eq('actor_type', $qb->createParameter('type'))) |
593 | 593 | ->andWhere($qb->expr()->eq('actor_id', $qb->createParameter('id'))) |
594 | 594 | ->setParameter('type', $actorType) |
@@ -671,10 +671,10 @@ discard block |
||
671 | 671 | // Strategy: try to update, if this does not return affected rows, do an insert. |
672 | 672 | $affectedRows = $qb |
673 | 673 | ->update('comments_read_markers') |
674 | - ->set('user_id', $values['user_id']) |
|
674 | + ->set('user_id', $values['user_id']) |
|
675 | 675 | ->set('marker_datetime', $values['marker_datetime']) |
676 | - ->set('object_type', $values['object_type']) |
|
677 | - ->set('object_id', $values['object_id']) |
|
676 | + ->set('object_type', $values['object_type']) |
|
677 | + ->set('object_id', $values['object_id']) |
|
678 | 678 | ->where($qb->expr()->eq('user_id', $qb->createParameter('user_id'))) |
679 | 679 | ->andWhere($qb->expr()->eq('object_type', $qb->createParameter('object_type'))) |
680 | 680 | ->andWhere($qb->expr()->eq('object_id', $qb->createParameter('object_id'))) |
@@ -717,7 +717,7 @@ discard block |
||
717 | 717 | |
718 | 718 | $data = $resultStatement->fetch(); |
719 | 719 | $resultStatement->closeCursor(); |
720 | - if(!$data || is_null($data['marker_datetime'])) { |
|
720 | + if (!$data || is_null($data['marker_datetime'])) { |
|
721 | 721 | return null; |
722 | 722 | } |
723 | 723 | |
@@ -774,10 +774,10 @@ discard block |
||
774 | 774 | * \OutOfBoundsException has to thrown. |
775 | 775 | */ |
776 | 776 | public function registerDisplayNameResolver($type, \Closure $closure) { |
777 | - if(!is_string($type)) { |
|
777 | + if (!is_string($type)) { |
|
778 | 778 | throw new \InvalidArgumentException('String expected.'); |
779 | 779 | } |
780 | - if(isset($this->displayNameResolvers[$type])) { |
|
780 | + if (isset($this->displayNameResolvers[$type])) { |
|
781 | 781 | throw new \OutOfBoundsException('Displayname resolver for this type already registered'); |
782 | 782 | } |
783 | 783 | $this->displayNameResolvers[$type] = $closure; |
@@ -797,13 +797,13 @@ discard block |
||
797 | 797 | * provided ID is unknown. It must be ensured that a string is returned. |
798 | 798 | */ |
799 | 799 | public function resolveDisplayName($type, $id) { |
800 | - if(!is_string($type)) { |
|
800 | + if (!is_string($type)) { |
|
801 | 801 | throw new \InvalidArgumentException('String expected.'); |
802 | 802 | } |
803 | - if(!isset($this->displayNameResolvers[$type])) { |
|
803 | + if (!isset($this->displayNameResolvers[$type])) { |
|
804 | 804 | throw new \OutOfBoundsException('No Displayname resolver for this type registered'); |
805 | 805 | } |
806 | - return (string)$this->displayNameResolvers[$type]($id); |
|
806 | + return (string) $this->displayNameResolvers[$type]($id); |
|
807 | 807 | } |
808 | 808 | |
809 | 809 | /** |
@@ -812,7 +812,7 @@ discard block |
||
812 | 812 | * @return \OCP\Comments\ICommentsEventHandler[] |
813 | 813 | */ |
814 | 814 | private function getEventHandlers() { |
815 | - if(!empty($this->eventHandlers)) { |
|
815 | + if (!empty($this->eventHandlers)) { |
|
816 | 816 | return $this->eventHandlers; |
817 | 817 | } |
818 | 818 |
@@ -173,7 +173,7 @@ discard block |
||
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 |
||
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) { |
@@ -56,7 +56,7 @@ discard block |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 |
||
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 | /** |
@@ -41,384 +41,384 @@ |
||
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 | } |