Failed Conditions
Push — newinternal ( b66232...216d62 )
by Simon
16:33 queued 06:35
created
includes/Helpers/Interfaces/IOAuthProtocolHelper.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -19,52 +19,52 @@
 block discarded – undo
19 19
 
20 20
 interface IOAuthProtocolHelper
21 21
 {
22
-    /**
23
-     * @return stdClass
24
-     *
25
-     * @throws Exception
26
-     * @throws CurlException
27
-     */
28
-    public function getRequestToken();
22
+	/**
23
+	 * @return stdClass
24
+	 *
25
+	 * @throws Exception
26
+	 * @throws CurlException
27
+	 */
28
+	public function getRequestToken();
29 29
 
30
-    /**
31
-     * @param string $requestToken
32
-     *
33
-     * @return string
34
-     */
35
-    public function getAuthoriseUrl($requestToken);
30
+	/**
31
+	 * @param string $requestToken
32
+	 *
33
+	 * @return string
34
+	 */
35
+	public function getAuthoriseUrl($requestToken);
36 36
 
37
-    /**
38
-     * @param string $oauthRequestToken
39
-     * @param string $oauthRequestSecret
40
-     * @param string $oauthVerifier
41
-     *
42
-     * @return stdClass
43
-     * @throws CurlException
44
-     * @throws Exception
45
-     */
46
-    public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
37
+	/**
38
+	 * @param string $oauthRequestToken
39
+	 * @param string $oauthRequestSecret
40
+	 * @param string $oauthVerifier
41
+	 *
42
+	 * @return stdClass
43
+	 * @throws CurlException
44
+	 * @throws Exception
45
+	 */
46
+	public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
47 47
 
48
-    /**
49
-     * @param string $oauthAccessToken
50
-     * @param string $oauthAccessSecret
51
-     *
52
-     * @return stdClass
53
-     * @throws CurlException
54
-     * @throws Exception
55
-     */
56
-    public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
48
+	/**
49
+	 * @param string $oauthAccessToken
50
+	 * @param string $oauthAccessSecret
51
+	 *
52
+	 * @return stdClass
53
+	 * @throws CurlException
54
+	 * @throws Exception
55
+	 */
56
+	public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
57 57
 
58
-    /**
59
-     * @param array  $apiParams    array of parameters to send to the API
60
-     * @param string $accessToken  user's access token
61
-     * @param string $accessSecret user's secret
62
-     * @param string $method       HTTP method
63
-     *
64
-     * @return stdClass
65
-     * @throws ApplicationLogicException
66
-     * @throws CurlException
67
-     * @throws Exception
68
-     */
69
-    public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
58
+	/**
59
+	 * @param array  $apiParams    array of parameters to send to the API
60
+	 * @param string $accessToken  user's access token
61
+	 * @param string $accessSecret user's secret
62
+	 * @param string $method       HTTP method
63
+	 *
64
+	 * @return stdClass
65
+	 * @throws ApplicationLogicException
66
+	 * @throws CurlException
67
+	 * @throws Exception
68
+	 */
69
+	public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
70 70
 }
71 71
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/HttpHelper.php 2 patches
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -12,109 +12,109 @@
 block discarded – undo
12 12
 
13 13
 class HttpHelper
14 14
 {
15
-    private $curlHandle;
16
-
17
-    /**
18
-     * HttpHelper constructor.
19
-     *
20
-     * @param string  $userAgent
21
-     * @param boolean $disableVerifyPeer
22
-     * @param string  $cookieJar
23
-     */
24
-    public function __construct($userAgent, $disableVerifyPeer, $cookieJar = null)
25
-    {
26
-        $this->curlHandle = curl_init();
27
-
28
-        curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
29
-        curl_setopt($this->curlHandle, CURLOPT_USERAGENT, $userAgent);
30
-        curl_setopt($this->curlHandle, CURLOPT_FAILONERROR, true);
31
-
32
-        if ($disableVerifyPeer) {
33
-            curl_setopt($this->curlHandle, CURLOPT_SSL_VERIFYPEER, false);
34
-        }
35
-
36
-        if($cookieJar !== null) {
37
-            curl_setopt($this->curlHandle, CURLOPT_COOKIEFILE, $cookieJar);
38
-            curl_setopt($this->curlHandle, CURLOPT_COOKIEJAR, $cookieJar);
39
-        }
40
-    }
41
-
42
-    public function __destruct()
43
-    {
44
-        curl_close($this->curlHandle);
45
-    }
46
-
47
-    /**
48
-     * Fetches the content of a URL, with an optional parameter set.
49
-     *
50
-     * @param string     $url        The URL to fetch.
51
-     * @param null|array $parameters Key/value pair of GET parameters to add to the request.
52
-     *                               Null lets you handle it yourself.
53
-     *
54
-     * @param array      $headers
55
-     *
56
-     * @return string
57
-     * @throws CurlException
58
-     */
59
-    public function get($url, $parameters = null, $headers = array())
60
-    {
61
-        if ($parameters !== null && is_array($parameters)) {
62
-            $getString = '?' . http_build_query($parameters);
63
-            $url .= $getString;
64
-        }
65
-
66
-        curl_setopt($this->curlHandle, CURLOPT_URL, $url);
67
-
68
-        // Make sure we're doing a GET
69
-        curl_setopt($this->curlHandle, CURLOPT_POST, false);
70
-
71
-        curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers);
72
-
73
-        $result = curl_exec($this->curlHandle);
74
-
75
-        if ($result === false) {
76
-            $error = curl_error($this->curlHandle);
77
-            throw new CurlException('Remote request failed with error ' . $error);
78
-        }
79
-
80
-        return $result;
81
-    }
82
-
83
-    /**
84
-     * Posts data to a URL
85
-     *
86
-     * @param string $url        The URL to fetch.
87
-     * @param array  $parameters Key/value pair of POST parameters to add to the request.
88
-     * @param array  $headers
89
-     *
90
-     * @return string
91
-     * @throws CurlException
92
-     */
93
-    public function post($url, $parameters, $headers = array())
94
-    {
95
-        curl_setopt($this->curlHandle, CURLOPT_URL, $url);
96
-
97
-        // Make sure we're doing a POST
98
-        curl_setopt($this->curlHandle, CURLOPT_POST, true);
99
-        curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, http_build_query($parameters));
100
-
101
-        curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers);
102
-
103
-        $result = curl_exec($this->curlHandle);
104
-
105
-        if ($result === false) {
106
-            $error = curl_error($this->curlHandle);
107
-            throw new CurlException('Remote request failed with error ' . $error);
108
-        }
109
-
110
-        return $result;
111
-    }
112
-
113
-    /**
114
-     * @return string
115
-     */
116
-    public function getError()
117
-    {
118
-        return curl_error($this->curlHandle);
119
-    }
15
+	private $curlHandle;
16
+
17
+	/**
18
+	 * HttpHelper constructor.
19
+	 *
20
+	 * @param string  $userAgent
21
+	 * @param boolean $disableVerifyPeer
22
+	 * @param string  $cookieJar
23
+	 */
24
+	public function __construct($userAgent, $disableVerifyPeer, $cookieJar = null)
25
+	{
26
+		$this->curlHandle = curl_init();
27
+
28
+		curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
29
+		curl_setopt($this->curlHandle, CURLOPT_USERAGENT, $userAgent);
30
+		curl_setopt($this->curlHandle, CURLOPT_FAILONERROR, true);
31
+
32
+		if ($disableVerifyPeer) {
33
+			curl_setopt($this->curlHandle, CURLOPT_SSL_VERIFYPEER, false);
34
+		}
35
+
36
+		if($cookieJar !== null) {
37
+			curl_setopt($this->curlHandle, CURLOPT_COOKIEFILE, $cookieJar);
38
+			curl_setopt($this->curlHandle, CURLOPT_COOKIEJAR, $cookieJar);
39
+		}
40
+	}
41
+
42
+	public function __destruct()
43
+	{
44
+		curl_close($this->curlHandle);
45
+	}
46
+
47
+	/**
48
+	 * Fetches the content of a URL, with an optional parameter set.
49
+	 *
50
+	 * @param string     $url        The URL to fetch.
51
+	 * @param null|array $parameters Key/value pair of GET parameters to add to the request.
52
+	 *                               Null lets you handle it yourself.
53
+	 *
54
+	 * @param array      $headers
55
+	 *
56
+	 * @return string
57
+	 * @throws CurlException
58
+	 */
59
+	public function get($url, $parameters = null, $headers = array())
60
+	{
61
+		if ($parameters !== null && is_array($parameters)) {
62
+			$getString = '?' . http_build_query($parameters);
63
+			$url .= $getString;
64
+		}
65
+
66
+		curl_setopt($this->curlHandle, CURLOPT_URL, $url);
67
+
68
+		// Make sure we're doing a GET
69
+		curl_setopt($this->curlHandle, CURLOPT_POST, false);
70
+
71
+		curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers);
72
+
73
+		$result = curl_exec($this->curlHandle);
74
+
75
+		if ($result === false) {
76
+			$error = curl_error($this->curlHandle);
77
+			throw new CurlException('Remote request failed with error ' . $error);
78
+		}
79
+
80
+		return $result;
81
+	}
82
+
83
+	/**
84
+	 * Posts data to a URL
85
+	 *
86
+	 * @param string $url        The URL to fetch.
87
+	 * @param array  $parameters Key/value pair of POST parameters to add to the request.
88
+	 * @param array  $headers
89
+	 *
90
+	 * @return string
91
+	 * @throws CurlException
92
+	 */
93
+	public function post($url, $parameters, $headers = array())
94
+	{
95
+		curl_setopt($this->curlHandle, CURLOPT_URL, $url);
96
+
97
+		// Make sure we're doing a POST
98
+		curl_setopt($this->curlHandle, CURLOPT_POST, true);
99
+		curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, http_build_query($parameters));
100
+
101
+		curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers);
102
+
103
+		$result = curl_exec($this->curlHandle);
104
+
105
+		if ($result === false) {
106
+			$error = curl_error($this->curlHandle);
107
+			throw new CurlException('Remote request failed with error ' . $error);
108
+		}
109
+
110
+		return $result;
111
+	}
112
+
113
+	/**
114
+	 * @return string
115
+	 */
116
+	public function getError()
117
+	{
118
+		return curl_error($this->curlHandle);
119
+	}
120 120
 }
121 121
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
             curl_setopt($this->curlHandle, CURLOPT_SSL_VERIFYPEER, false);
34 34
         }
35 35
 
36
-        if($cookieJar !== null) {
36
+        if ($cookieJar !== null) {
37 37
             curl_setopt($this->curlHandle, CURLOPT_COOKIEFILE, $cookieJar);
38 38
             curl_setopt($this->curlHandle, CURLOPT_COOKIEJAR, $cookieJar);
39 39
         }
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
     public function get($url, $parameters = null, $headers = array())
60 60
     {
61 61
         if ($parameters !== null && is_array($parameters)) {
62
-            $getString = '?' . http_build_query($parameters);
62
+            $getString = '?'.http_build_query($parameters);
63 63
             $url .= $getString;
64 64
         }
65 65
 
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 
75 75
         if ($result === false) {
76 76
             $error = curl_error($this->curlHandle);
77
-            throw new CurlException('Remote request failed with error ' . $error);
77
+            throw new CurlException('Remote request failed with error '.$error);
78 78
         }
79 79
 
80 80
         return $result;
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 
105 105
         if ($result === false) {
106 106
             $error = curl_error($this->curlHandle);
107
-            throw new CurlException('Remote request failed with error ' . $error);
107
+            throw new CurlException('Remote request failed with error '.$error);
108 108
         }
109 109
 
110 110
         return $result;
Please login to merge, or discard this patch.
includes/Helpers/MediaWikiHelper.php 3 patches
Braces   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -241,7 +241,8 @@
 block discarded – undo
241 241
      * @param string $username
242 242
      * @return bool
243 243
      */
244
-    public function checkAccountExists($username) {
244
+    public function checkAccountExists($username)
245
+    {
245 246
         $parameters = array(
246 247
             'action'  => 'query',
247 248
             'list'    => 'users',
Please login to merge, or discard this patch.
Indentation   +241 added lines, -241 removed lines patch added patch discarded remove patch
@@ -15,245 +15,245 @@
 block discarded – undo
15 15
 
16 16
 class MediaWikiHelper
17 17
 {
18
-    /**
19
-     * @var IMediaWikiClient
20
-     */
21
-    private $mediaWikiClient;
22
-    /**
23
-     * @var SiteConfiguration
24
-     */
25
-    private $siteConfiguration;
26
-
27
-    /**
28
-     * MediaWikiHelper constructor.
29
-     *
30
-     * @param IMediaWikiClient  $mediaWikiClient
31
-     * @param SiteConfiguration $siteConfiguration
32
-     */
33
-    public function __construct(IMediaWikiClient $mediaWikiClient, SiteConfiguration $siteConfiguration)
34
-    {
35
-        $this->mediaWikiClient = $mediaWikiClient;
36
-        $this->siteConfiguration = $siteConfiguration;
37
-    }
38
-
39
-    /**
40
-     * @todo handle override antispoof and titleblacklist issues
41
-     *
42
-     * @param string $username
43
-     * @param string $emailAddress
44
-     * @param string $reason
45
-     *
46
-     * @throws Exception
47
-     * @throws MediaWikiApiException
48
-     */
49
-    public function createAccount($username, $emailAddress, $reason)
50
-    {
51
-        // get token
52
-        $tokenParams = array(
53
-            'action' => 'query',
54
-            'meta'   => 'tokens',
55
-            'type'   => 'createaccount',
56
-        );
57
-
58
-        $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
59
-
60
-        if (isset($response->error)) {
61
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
62
-        }
63
-
64
-        $token = $response->query->tokens->createaccounttoken;
65
-
66
-        $callback = $this->siteConfiguration->getBaseUrl() . '/internal.php/oauth/createCallback';
67
-
68
-        $checkboxFields = array();
69
-        $requiredFields = array();
70
-        $this->getCreationFieldData($requiredFields, $checkboxFields);
71
-
72
-        $apiCallData = array(
73
-            'action'              => 'createaccount',
74
-            'createreturnurl'     => $callback,
75
-            'createtoken'         => $token,
76
-            'createmessageformat' => 'html',
77
-        );
78
-
79
-        $createParams = array_fill_keys($requiredFields, '') + $apiCallData;
80
-
81
-        $createParams['username'] = $username;
82
-        $createParams['mailpassword'] = true;
83
-        $createParams['email'] = $emailAddress;
84
-        $createParams['reason'] = $reason;
85
-
86
-        $createResponse = $this->mediaWikiClient->doApiCall($createParams, 'POST');
87
-
88
-        if (isset($createResponse->error)) {
89
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
90
-        }
91
-
92
-        if (!isset($createResponse->createaccount) || !isset($createResponse->createaccount->status)) {
93
-            throw new MediaWikiApiException('Unknown error creating account');
94
-        }
95
-
96
-        if ($createResponse->createaccount->status === 'FAIL') {
97
-            throw new MediaWikiApiException($createResponse->createaccount->message);
98
-        }
99
-
100
-        if ($createResponse->createaccount->status === 'PASS') {
101
-            // success!
102
-            return;
103
-        }
104
-
105
-        throw new Exception('API result reported status of ' . $createResponse->createaccount->status);
106
-    }
107
-
108
-    /**
109
-     * @param string $username
110
-     * @param string $title
111
-     * @param        $summary
112
-     * @param string $message
113
-     * @param bool   $createOnly
114
-     *
115
-     * @throws MediaWikiApiException
116
-     */
117
-    public function addTalkPageMessage($username, $title, $summary, $message, $createOnly = true)
118
-    {
119
-        // get token
120
-        $tokenParams = array(
121
-            'action' => 'query',
122
-            'meta'   => 'tokens',
123
-            'type'   => 'csrf',
124
-        );
125
-
126
-        $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
127
-
128
-        if (isset($response->error)) {
129
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
130
-        }
131
-
132
-        $token = $response->query->tokens->csrftoken;
133
-
134
-        if ($token === null) {
135
-            throw new MediaWikiApiException('Edit token could not be acquired');
136
-        }
137
-
138
-        $editParameters = array(
139
-            'action'       => 'edit',
140
-            'title'        => 'User talk:' . $username,
141
-            'section'      => 'new',
142
-            'sectiontitle' => $title,
143
-            'summary'      => $summary,
144
-            'text'         => $message,
145
-            'token'        => $token,
146
-        );
147
-
148
-        if ($createOnly) {
149
-            $editParameters['createonly'] = true;
150
-        }
151
-
152
-        $response = $this->mediaWikiClient->doApiCall($editParameters, 'POST');
153
-
154
-        if (!isset($response->edit)) {
155
-            if (isset($response->error)) {
156
-                throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
157
-            }
158
-
159
-            throw new MediaWikiApiException('Unknown error encountered during editing.');
160
-        }
161
-
162
-        $editResponse = $response->edit;
163
-        if ($editResponse->result === "Success") {
164
-            return;
165
-        }
166
-
167
-        throw new MediaWikiApiException('Edit status unsuccessful: ' . $editResponse->result);
168
-    }
169
-
170
-    public function getCreationFieldData(&$requiredFields, &$checkboxFields)
171
-    {
172
-        // get token
173
-        $params = array(
174
-            'action'         => 'query',
175
-            'meta'           => 'authmanagerinfo',
176
-            'amirequestsfor' => 'create',
177
-        );
178
-
179
-        $response = $this->mediaWikiClient->doApiCall($params, 'GET');
180
-
181
-        if (isset($response->error)) {
182
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
183
-        }
184
-
185
-        $requests = $response->query->authmanagerinfo->requests;
186
-
187
-        // We don't want to deal with these providers ever.
188
-        $discardList = array(
189
-            // Requires a username and password
190
-            'MediaWiki\\Auth\\PasswordAuthenticationRequest',
191
-        );
192
-
193
-        // We require these providers to function
194
-        $requireList = array(
195
-            'MediaWiki\\Auth\\TemporaryPasswordAuthenticationRequest',
196
-            'MediaWiki\\Auth\\UsernameAuthenticationRequest',
197
-            'MediaWiki\\Auth\\UserDataAuthenticationRequest',
198
-            'MediaWiki\\Auth\\CreationReasonAuthenticationRequest',
199
-        );
200
-
201
-        $requiredFields = array();
202
-        // Keep checkbox fields separate, since "required" actually means optional as absent == false.
203
-        $checkboxFields = array();
204
-
205
-        foreach ($requests as $req) {
206
-            // Immediately discard anything that is on the discard list.
207
-            if (in_array($req->id, $discardList)) {
208
-                continue;
209
-            }
210
-
211
-            $required = false;
212
-
213
-            if ($req->required === 'primary-required' && !in_array($req->id, $requireList)) {
214
-                // Only want one.
215
-                continue;
216
-            }
217
-
218
-            if (in_array($req->id, $requireList)) {
219
-                unset($requireList[$req->id]);
220
-                $required = true;
221
-            }
222
-
223
-            if ($req->required === 'required') {
224
-                $required = true;
225
-            }
226
-
227
-            if ($required) {
228
-                foreach ($req->fields as $name => $data) {
229
-                    if ($data->type === 'checkbox') {
230
-                        $checkboxFields[] = $name;
231
-                    }
232
-                    else {
233
-                        $requiredFields[] = $name;
234
-                    }
235
-                }
236
-            }
237
-        }
238
-    }
239
-
240
-    /**
241
-     * @param string $username
242
-     * @return bool
243
-     */
244
-    public function checkAccountExists($username) {
245
-        $parameters = array(
246
-            'action'  => 'query',
247
-            'list'    => 'users',
248
-            'format'  => 'php',
249
-            'ususers' => $username,
250
-        );
251
-
252
-        $apiResult = $this->mediaWikiClient->doApiCall($parameters, 'GET');
253
-
254
-        $entry = $apiResult->query->users[0];
255
-        $exists = !isset($entry->missing);
256
-
257
-        return $exists;
258
-    }
18
+	/**
19
+	 * @var IMediaWikiClient
20
+	 */
21
+	private $mediaWikiClient;
22
+	/**
23
+	 * @var SiteConfiguration
24
+	 */
25
+	private $siteConfiguration;
26
+
27
+	/**
28
+	 * MediaWikiHelper constructor.
29
+	 *
30
+	 * @param IMediaWikiClient  $mediaWikiClient
31
+	 * @param SiteConfiguration $siteConfiguration
32
+	 */
33
+	public function __construct(IMediaWikiClient $mediaWikiClient, SiteConfiguration $siteConfiguration)
34
+	{
35
+		$this->mediaWikiClient = $mediaWikiClient;
36
+		$this->siteConfiguration = $siteConfiguration;
37
+	}
38
+
39
+	/**
40
+	 * @todo handle override antispoof and titleblacklist issues
41
+	 *
42
+	 * @param string $username
43
+	 * @param string $emailAddress
44
+	 * @param string $reason
45
+	 *
46
+	 * @throws Exception
47
+	 * @throws MediaWikiApiException
48
+	 */
49
+	public function createAccount($username, $emailAddress, $reason)
50
+	{
51
+		// get token
52
+		$tokenParams = array(
53
+			'action' => 'query',
54
+			'meta'   => 'tokens',
55
+			'type'   => 'createaccount',
56
+		);
57
+
58
+		$response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
59
+
60
+		if (isset($response->error)) {
61
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
62
+		}
63
+
64
+		$token = $response->query->tokens->createaccounttoken;
65
+
66
+		$callback = $this->siteConfiguration->getBaseUrl() . '/internal.php/oauth/createCallback';
67
+
68
+		$checkboxFields = array();
69
+		$requiredFields = array();
70
+		$this->getCreationFieldData($requiredFields, $checkboxFields);
71
+
72
+		$apiCallData = array(
73
+			'action'              => 'createaccount',
74
+			'createreturnurl'     => $callback,
75
+			'createtoken'         => $token,
76
+			'createmessageformat' => 'html',
77
+		);
78
+
79
+		$createParams = array_fill_keys($requiredFields, '') + $apiCallData;
80
+
81
+		$createParams['username'] = $username;
82
+		$createParams['mailpassword'] = true;
83
+		$createParams['email'] = $emailAddress;
84
+		$createParams['reason'] = $reason;
85
+
86
+		$createResponse = $this->mediaWikiClient->doApiCall($createParams, 'POST');
87
+
88
+		if (isset($createResponse->error)) {
89
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
90
+		}
91
+
92
+		if (!isset($createResponse->createaccount) || !isset($createResponse->createaccount->status)) {
93
+			throw new MediaWikiApiException('Unknown error creating account');
94
+		}
95
+
96
+		if ($createResponse->createaccount->status === 'FAIL') {
97
+			throw new MediaWikiApiException($createResponse->createaccount->message);
98
+		}
99
+
100
+		if ($createResponse->createaccount->status === 'PASS') {
101
+			// success!
102
+			return;
103
+		}
104
+
105
+		throw new Exception('API result reported status of ' . $createResponse->createaccount->status);
106
+	}
107
+
108
+	/**
109
+	 * @param string $username
110
+	 * @param string $title
111
+	 * @param        $summary
112
+	 * @param string $message
113
+	 * @param bool   $createOnly
114
+	 *
115
+	 * @throws MediaWikiApiException
116
+	 */
117
+	public function addTalkPageMessage($username, $title, $summary, $message, $createOnly = true)
118
+	{
119
+		// get token
120
+		$tokenParams = array(
121
+			'action' => 'query',
122
+			'meta'   => 'tokens',
123
+			'type'   => 'csrf',
124
+		);
125
+
126
+		$response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
127
+
128
+		if (isset($response->error)) {
129
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
130
+		}
131
+
132
+		$token = $response->query->tokens->csrftoken;
133
+
134
+		if ($token === null) {
135
+			throw new MediaWikiApiException('Edit token could not be acquired');
136
+		}
137
+
138
+		$editParameters = array(
139
+			'action'       => 'edit',
140
+			'title'        => 'User talk:' . $username,
141
+			'section'      => 'new',
142
+			'sectiontitle' => $title,
143
+			'summary'      => $summary,
144
+			'text'         => $message,
145
+			'token'        => $token,
146
+		);
147
+
148
+		if ($createOnly) {
149
+			$editParameters['createonly'] = true;
150
+		}
151
+
152
+		$response = $this->mediaWikiClient->doApiCall($editParameters, 'POST');
153
+
154
+		if (!isset($response->edit)) {
155
+			if (isset($response->error)) {
156
+				throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
157
+			}
158
+
159
+			throw new MediaWikiApiException('Unknown error encountered during editing.');
160
+		}
161
+
162
+		$editResponse = $response->edit;
163
+		if ($editResponse->result === "Success") {
164
+			return;
165
+		}
166
+
167
+		throw new MediaWikiApiException('Edit status unsuccessful: ' . $editResponse->result);
168
+	}
169
+
170
+	public function getCreationFieldData(&$requiredFields, &$checkboxFields)
171
+	{
172
+		// get token
173
+		$params = array(
174
+			'action'         => 'query',
175
+			'meta'           => 'authmanagerinfo',
176
+			'amirequestsfor' => 'create',
177
+		);
178
+
179
+		$response = $this->mediaWikiClient->doApiCall($params, 'GET');
180
+
181
+		if (isset($response->error)) {
182
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
183
+		}
184
+
185
+		$requests = $response->query->authmanagerinfo->requests;
186
+
187
+		// We don't want to deal with these providers ever.
188
+		$discardList = array(
189
+			// Requires a username and password
190
+			'MediaWiki\\Auth\\PasswordAuthenticationRequest',
191
+		);
192
+
193
+		// We require these providers to function
194
+		$requireList = array(
195
+			'MediaWiki\\Auth\\TemporaryPasswordAuthenticationRequest',
196
+			'MediaWiki\\Auth\\UsernameAuthenticationRequest',
197
+			'MediaWiki\\Auth\\UserDataAuthenticationRequest',
198
+			'MediaWiki\\Auth\\CreationReasonAuthenticationRequest',
199
+		);
200
+
201
+		$requiredFields = array();
202
+		// Keep checkbox fields separate, since "required" actually means optional as absent == false.
203
+		$checkboxFields = array();
204
+
205
+		foreach ($requests as $req) {
206
+			// Immediately discard anything that is on the discard list.
207
+			if (in_array($req->id, $discardList)) {
208
+				continue;
209
+			}
210
+
211
+			$required = false;
212
+
213
+			if ($req->required === 'primary-required' && !in_array($req->id, $requireList)) {
214
+				// Only want one.
215
+				continue;
216
+			}
217
+
218
+			if (in_array($req->id, $requireList)) {
219
+				unset($requireList[$req->id]);
220
+				$required = true;
221
+			}
222
+
223
+			if ($req->required === 'required') {
224
+				$required = true;
225
+			}
226
+
227
+			if ($required) {
228
+				foreach ($req->fields as $name => $data) {
229
+					if ($data->type === 'checkbox') {
230
+						$checkboxFields[] = $name;
231
+					}
232
+					else {
233
+						$requiredFields[] = $name;
234
+					}
235
+				}
236
+			}
237
+		}
238
+	}
239
+
240
+	/**
241
+	 * @param string $username
242
+	 * @return bool
243
+	 */
244
+	public function checkAccountExists($username) {
245
+		$parameters = array(
246
+			'action'  => 'query',
247
+			'list'    => 'users',
248
+			'format'  => 'php',
249
+			'ususers' => $username,
250
+		);
251
+
252
+		$apiResult = $this->mediaWikiClient->doApiCall($parameters, 'GET');
253
+
254
+		$entry = $apiResult->query->users[0];
255
+		$exists = !isset($entry->missing);
256
+
257
+		return $exists;
258
+	}
259 259
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -58,12 +58,12 @@  discard block
 block discarded – undo
58 58
         $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
59 59
 
60 60
         if (isset($response->error)) {
61
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
61
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
62 62
         }
63 63
 
64 64
         $token = $response->query->tokens->createaccounttoken;
65 65
 
66
-        $callback = $this->siteConfiguration->getBaseUrl() . '/internal.php/oauth/createCallback';
66
+        $callback = $this->siteConfiguration->getBaseUrl().'/internal.php/oauth/createCallback';
67 67
 
68 68
         $checkboxFields = array();
69 69
         $requiredFields = array();
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
         $createResponse = $this->mediaWikiClient->doApiCall($createParams, 'POST');
87 87
 
88 88
         if (isset($createResponse->error)) {
89
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
89
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
90 90
         }
91 91
 
92 92
         if (!isset($createResponse->createaccount) || !isset($createResponse->createaccount->status)) {
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
             return;
103 103
         }
104 104
 
105
-        throw new Exception('API result reported status of ' . $createResponse->createaccount->status);
105
+        throw new Exception('API result reported status of '.$createResponse->createaccount->status);
106 106
     }
107 107
 
108 108
     /**
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
         $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
127 127
 
128 128
         if (isset($response->error)) {
129
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
129
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
130 130
         }
131 131
 
132 132
         $token = $response->query->tokens->csrftoken;
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 
138 138
         $editParameters = array(
139 139
             'action'       => 'edit',
140
-            'title'        => 'User talk:' . $username,
140
+            'title'        => 'User talk:'.$username,
141 141
             'section'      => 'new',
142 142
             'sectiontitle' => $title,
143 143
             'summary'      => $summary,
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 
154 154
         if (!isset($response->edit)) {
155 155
             if (isset($response->error)) {
156
-                throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
156
+                throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
157 157
             }
158 158
 
159 159
             throw new MediaWikiApiException('Unknown error encountered during editing.');
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
             return;
165 165
         }
166 166
 
167
-        throw new MediaWikiApiException('Edit status unsuccessful: ' . $editResponse->result);
167
+        throw new MediaWikiApiException('Edit status unsuccessful: '.$editResponse->result);
168 168
     }
169 169
 
170 170
     public function getCreationFieldData(&$requiredFields, &$checkboxFields)
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
         $response = $this->mediaWikiClient->doApiCall($params, 'GET');
180 180
 
181 181
         if (isset($response->error)) {
182
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
182
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
183 183
         }
184 184
 
185 185
         $requests = $response->query->authmanagerinfo->requests;
Please login to merge, or discard this patch.
includes/Helpers/SearchHelpers/UserSearchHelper.php 1 patch
Indentation   +88 added lines, -88 removed lines patch added patch discarded remove patch
@@ -15,80 +15,80 @@  discard block
 block discarded – undo
15 15
 
16 16
 class UserSearchHelper extends SearchHelperBase
17 17
 {
18
-    /**
19
-     * UserSearchHelper constructor.
20
-     *
21
-     * @param PdoDatabase $database
22
-     */
23
-    public function __construct(PdoDatabase $database)
24
-    {
25
-        parent::__construct($database, 'user', User::class);
26
-    }
27
-
28
-    /**
29
-     * Initiates a search for requests
30
-     *
31
-     * @param PdoDatabase $database
32
-     *
33
-     * @return UserSearchHelper
34
-     */
35
-    public static function get(PdoDatabase $database)
36
-    {
37
-        $helper = new UserSearchHelper($database);
38
-
39
-        return $helper;
40
-    }
41
-
42
-    /**
43
-     * @param string $status
44
-     *
45
-     * @return $this
46
-     */
47
-    public function byStatus($status)
48
-    {
49
-        $this->whereClause .= ' AND status = ?';
50
-        $this->parameterList[] = $status;
51
-
52
-        return $this;
53
-    }
54
-
55
-    public function statusIn($statuses)
56
-    {
57
-        $this->inClause('status', $statuses);
58
-
59
-        return $this;
60
-    }
61
-
62
-    /**
63
-     * @param string $role
64
-     *
65
-     * @return $this
66
-     */
67
-    public function byRole($role)
68
-    {
69
-        $this->joinClause .= ' INNER JOIN userrole r on origin.id = r.user';
70
-        $this->whereClause .= ' AND r.role = ?';
71
-        $this->parameterList[] = $role;
72
-
73
-        return $this;
74
-    }
75
-
76
-    /**
77
-     * @param DateTime $instant
78
-     *
79
-     * @return $this
80
-     */
81
-    public function lastActiveBefore(DateTime $instant)
82
-    {
83
-        $this->whereClause .= ' AND origin.lastactive < ?';
84
-        $this->parameterList[] = $instant->format("Y-m-d H:i:s");
85
-
86
-        return $this;
87
-    }
88
-
89
-    public function getRoleMap(&$roleMap)
90
-    {
91
-        $query = <<<SQL
18
+	/**
19
+	 * UserSearchHelper constructor.
20
+	 *
21
+	 * @param PdoDatabase $database
22
+	 */
23
+	public function __construct(PdoDatabase $database)
24
+	{
25
+		parent::__construct($database, 'user', User::class);
26
+	}
27
+
28
+	/**
29
+	 * Initiates a search for requests
30
+	 *
31
+	 * @param PdoDatabase $database
32
+	 *
33
+	 * @return UserSearchHelper
34
+	 */
35
+	public static function get(PdoDatabase $database)
36
+	{
37
+		$helper = new UserSearchHelper($database);
38
+
39
+		return $helper;
40
+	}
41
+
42
+	/**
43
+	 * @param string $status
44
+	 *
45
+	 * @return $this
46
+	 */
47
+	public function byStatus($status)
48
+	{
49
+		$this->whereClause .= ' AND status = ?';
50
+		$this->parameterList[] = $status;
51
+
52
+		return $this;
53
+	}
54
+
55
+	public function statusIn($statuses)
56
+	{
57
+		$this->inClause('status', $statuses);
58
+
59
+		return $this;
60
+	}
61
+
62
+	/**
63
+	 * @param string $role
64
+	 *
65
+	 * @return $this
66
+	 */
67
+	public function byRole($role)
68
+	{
69
+		$this->joinClause .= ' INNER JOIN userrole r on origin.id = r.user';
70
+		$this->whereClause .= ' AND r.role = ?';
71
+		$this->parameterList[] = $role;
72
+
73
+		return $this;
74
+	}
75
+
76
+	/**
77
+	 * @param DateTime $instant
78
+	 *
79
+	 * @return $this
80
+	 */
81
+	public function lastActiveBefore(DateTime $instant)
82
+	{
83
+		$this->whereClause .= ' AND origin.lastactive < ?';
84
+		$this->parameterList[] = $instant->format("Y-m-d H:i:s");
85
+
86
+		return $this;
87
+	}
88
+
89
+	public function getRoleMap(&$roleMap)
90
+	{
91
+		$query = <<<SQL
92 92
             SELECT /* UserSearchHelper/roleMap */ 
93 93
                   r.user user
94 94
                 , group_concat(r.role SEPARATOR ', ') roles 
@@ -97,22 +97,22 @@  discard block
 block discarded – undo
97 97
             GROUP BY r.user
98 98
 SQL;
99 99
 
100
-        $statement = $this->database->prepare($query);
101
-        $statement->execute($this->parameterList);
100
+		$statement = $this->database->prepare($query);
101
+		$statement->execute($this->parameterList);
102 102
 
103
-        $roleMap = array();
104
-        foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
105
-            $roleMap[$row['user']] = $row['roles'];
106
-        }
103
+		$roleMap = array();
104
+		foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
105
+			$roleMap[$row['user']] = $row['roles'];
106
+		}
107 107
 
108
-        return $this;
109
-    }
108
+		return $this;
109
+	}
110 110
 
111
-    public function withReservedRequest()
112
-    {
113
-        $this->joinClause = ' INNER JOIN request req ON req.reserved = origin.id';
114
-        $this->groupByClause = ' GROUP BY origin.id, origin.username';
111
+	public function withReservedRequest()
112
+	{
113
+		$this->joinClause = ' INNER JOIN request req ON req.reserved = origin.id';
114
+		$this->groupByClause = ' GROUP BY origin.id, origin.username';
115 115
 
116
-        return $this->fetchMap('username');
117
-    }
116
+		return $this->fetchMap('username');
117
+	}
118 118
 }
Please login to merge, or discard this patch.
includes/Helpers/SearchHelpers/JobQueueSearchHelper.php 2 patches
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -13,67 +13,67 @@
 block discarded – undo
13 13
 
14 14
 class JobQueueSearchHelper extends SearchHelperBase
15 15
 {
16
-    protected function __construct(PdoDatabase $database)
17
-    {
18
-        parent::__construct($database, 'jobqueue', JobQueue::class, null);
19
-    }
20
-
21
-    /**
22
-     * @param PdoDatabase $database
23
-     *
24
-     * @return JobQueueSearchHelper
25
-     */
26
-    public static function get(PdoDatabase $database) {
27
-        $helper = new JobQueueSearchHelper($database);
28
-        return $helper;
29
-    }
30
-
31
-    /**
32
-     * @param string[] $statuses
33
-     *
34
-     * @return $this
35
-     */
36
-    public function statusIn($statuses) {
37
-        $this->inClause('status', $statuses);
38
-
39
-        return $this;
40
-    }
41
-
42
-    /**
43
-     * @return $this
44
-     */
45
-    public function notAcknowledged() {
46
-        $this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47
-
48
-        return $this;
49
-    }
50
-
51
-    public function byTask($task) {
52
-        $this->whereClause .= ' AND task = ?';
53
-        $this->parameterList[] = $task;
54
-
55
-        return $this;
56
-    }
57
-
58
-    public function byUser($userId) {
59
-        $this->whereClause .= ' AND user = ?';
60
-        $this->parameterList[] = $userId;
61
-
62
-        return $this;
63
-    }
64
-
65
-    public function byStatus($status) {
66
-        $this->whereClause .= ' AND status = ?';
67
-        $this->parameterList[] = $status;
68
-
69
-        return $this;
70
-    }
71
-
72
-    public function byRequest($request)
73
-    {
74
-        $this->whereClause .= ' AND request = ?';
75
-        $this->parameterList[] = $request;
76
-
77
-        return $this;
78
-    }
16
+	protected function __construct(PdoDatabase $database)
17
+	{
18
+		parent::__construct($database, 'jobqueue', JobQueue::class, null);
19
+	}
20
+
21
+	/**
22
+	 * @param PdoDatabase $database
23
+	 *
24
+	 * @return JobQueueSearchHelper
25
+	 */
26
+	public static function get(PdoDatabase $database) {
27
+		$helper = new JobQueueSearchHelper($database);
28
+		return $helper;
29
+	}
30
+
31
+	/**
32
+	 * @param string[] $statuses
33
+	 *
34
+	 * @return $this
35
+	 */
36
+	public function statusIn($statuses) {
37
+		$this->inClause('status', $statuses);
38
+
39
+		return $this;
40
+	}
41
+
42
+	/**
43
+	 * @return $this
44
+	 */
45
+	public function notAcknowledged() {
46
+		$this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47
+
48
+		return $this;
49
+	}
50
+
51
+	public function byTask($task) {
52
+		$this->whereClause .= ' AND task = ?';
53
+		$this->parameterList[] = $task;
54
+
55
+		return $this;
56
+	}
57
+
58
+	public function byUser($userId) {
59
+		$this->whereClause .= ' AND user = ?';
60
+		$this->parameterList[] = $userId;
61
+
62
+		return $this;
63
+	}
64
+
65
+	public function byStatus($status) {
66
+		$this->whereClause .= ' AND status = ?';
67
+		$this->parameterList[] = $status;
68
+
69
+		return $this;
70
+	}
71
+
72
+	public function byRequest($request)
73
+	{
74
+		$this->whereClause .= ' AND request = ?';
75
+		$this->parameterList[] = $request;
76
+
77
+		return $this;
78
+	}
79 79
 }
80 80
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +12 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,7 +23,8 @@  discard block
 block discarded – undo
23 23
      *
24 24
      * @return JobQueueSearchHelper
25 25
      */
26
-    public static function get(PdoDatabase $database) {
26
+    public static function get(PdoDatabase $database)
27
+    {
27 28
         $helper = new JobQueueSearchHelper($database);
28 29
         return $helper;
29 30
     }
@@ -33,7 +34,8 @@  discard block
 block discarded – undo
33 34
      *
34 35
      * @return $this
35 36
      */
36
-    public function statusIn($statuses) {
37
+    public function statusIn($statuses)
38
+    {
37 39
         $this->inClause('status', $statuses);
38 40
 
39 41
         return $this;
@@ -42,27 +44,31 @@  discard block
 block discarded – undo
42 44
     /**
43 45
      * @return $this
44 46
      */
45
-    public function notAcknowledged() {
47
+    public function notAcknowledged()
48
+    {
46 49
         $this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47 50
 
48 51
         return $this;
49 52
     }
50 53
 
51
-    public function byTask($task) {
54
+    public function byTask($task)
55
+    {
52 56
         $this->whereClause .= ' AND task = ?';
53 57
         $this->parameterList[] = $task;
54 58
 
55 59
         return $this;
56 60
     }
57 61
 
58
-    public function byUser($userId) {
62
+    public function byUser($userId)
63
+    {
59 64
         $this->whereClause .= ' AND user = ?';
60 65
         $this->parameterList[] = $userId;
61 66
 
62 67
         return $this;
63 68
     }
64 69
 
65
-    public function byStatus($status) {
70
+    public function byStatus($status)
71
+    {
66 72
         $this->whereClause .= ' AND status = ?';
67 73
         $this->parameterList[] = $status;
68 74
 
Please login to merge, or discard this patch.
includes/Helpers/SearchHelpers/SearchHelperBase.php 2 patches
Indentation   +270 added lines, -270 removed lines patch added patch discarded remove patch
@@ -16,274 +16,274 @@
 block discarded – undo
16 16
 
17 17
 abstract class SearchHelperBase
18 18
 {
19
-    /** @var PdoDatabase */
20
-    protected $database;
21
-    /** @var array */
22
-    protected $parameterList = array();
23
-    /** @var null|int */
24
-    private $limit = null;
25
-    /** @var null|int */
26
-    private $offset = null;
27
-    private $orderBy = null;
28
-    /**
29
-     * @var string The where clause.
30
-     *
31
-     * (the 1=1 condition will be optimised out of the query by the query planner, and simplifies our code here). Note
32
-     * that we use positional parameters instead of named parameters because we don't know many times different options
33
-     * will be called (looking at excluding() here, but there's the option for others).
34
-     */
35
-    protected $whereClause = ' WHERE 1 = 1';
36
-    /** @var string */
37
-    protected $table;
38
-    protected $joinClause = '';
39
-    protected $groupByClause = '';
40
-    protected $modifiersClause = '';
41
-    private $targetClass;
42
-
43
-    /**
44
-     * SearchHelperBase constructor.
45
-     *
46
-     * @param PdoDatabase $database
47
-     * @param string      $table
48
-     * @param             $targetClass
49
-     * @param null|string $order Order by clause, excluding ORDER BY.
50
-     */
51
-    protected function __construct(PdoDatabase $database, $table, $targetClass, $order = null)
52
-    {
53
-        $this->database = $database;
54
-        $this->table = $table;
55
-        $this->orderBy = $order;
56
-        $this->targetClass = $targetClass;
57
-    }
58
-
59
-    /**
60
-     * Finalises the database query, and executes it, returning a set of objects.
61
-     *
62
-     * @return DataObject[]
63
-     */
64
-    public function fetch()
65
-    {
66
-        $statement = $this->getData();
67
-
68
-        /** @var DataObject[] $returnedObjects */
69
-        $returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
70
-        foreach ($returnedObjects as $req) {
71
-            $req->setDatabase($this->database);
72
-        }
73
-
74
-        return $returnedObjects;
75
-    }
76
-
77
-    /**
78
-     * @param string $whereClauseSection
79
-     * @param array  $values
80
-     *
81
-     * @return array
82
-     */
83
-    protected function fetchByParameter($whereClauseSection, $values)
84
-    {
85
-        $this->whereClause .= $whereClauseSection;
86
-
87
-        $countQuery = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
88
-        $countQuery .= $this->joinClause . $this->whereClause;
89
-
90
-        $query = $this->buildQuery(array('*'));
91
-        $query .= $this->applyOrder();
92
-
93
-        // shuffle around hackily TODO: fix this abomination - T593
94
-        $localParameterList = $this->parameterList;
95
-        $this->parameterList = array();
96
-
97
-        $query .= $this->applyLimit();
98
-
99
-        $limitParameters = $this->parameterList;
100
-
101
-        $statement = $this->database->prepare($query);
102
-        $countStatement = $this->database->prepare($countQuery);
103
-
104
-        $result = array();
105
-        foreach ($values as $v) {
106
-            // reset parameter list
107
-            $params = $localParameterList;
108
-            $params[] = $v;
109
-
110
-            $countStatement->execute($params);
111
-
112
-            // reapply the limit parameters
113
-            $params = array_merge($params, $limitParameters);
114
-
115
-            $statement->execute($params);
116
-
117
-            /** @var DataObject[] $returnedObjects */
118
-            $returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
119
-            foreach ($returnedObjects as $req) {
120
-                $req->setDatabase($this->database);
121
-            }
122
-
123
-            $result[$v] = array(
124
-                'count' => $countStatement->fetchColumn(0),
125
-                'data'  => $returnedObjects,
126
-            );
127
-        }
128
-
129
-        return $result;
130
-    }
131
-
132
-    /**
133
-     * Finalises the database query, and executes it, returning only the requested column.
134
-     *
135
-     * @param string $column The required column
136
-     *
137
-     * @param bool   $distinct
138
-     *
139
-     * @return array
140
-     * @throws ApplicationLogicException
141
-     */
142
-    public function fetchColumn($column, $distinct = false)
143
-    {
144
-        if ($distinct) {
145
-            if ($this->groupByClause !== '') {
146
-                throw new ApplicationLogicException('Cannot apply distinct to column fetch already using group by');
147
-            }
148
-
149
-            $this->groupByClause = ' GROUP BY origin.' . $column;
150
-        }
151
-
152
-        $statement = $this->getData(array($column));
153
-
154
-        return $statement->fetchAll(PDO::FETCH_COLUMN);
155
-    }
156
-
157
-    public function fetchMap($column)
158
-    {
159
-        $statement = $this->getData(array('id', $column));
160
-
161
-        $data = $statement->fetchAll(PDO::FETCH_ASSOC);
162
-        $map = array();
163
-
164
-        foreach ($data as $row) {
165
-            $map[$row['id']] = $row[$column];
166
-        }
167
-
168
-        return $map;
169
-    }
170
-
171
-    /**
172
-     * @param int $count Returns the record count of the result set
173
-     *
174
-     * @return $this
175
-     */
176
-    public function getRecordCount(&$count)
177
-    {
178
-        $query = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
179
-        $query .= $this->joinClause . $this->whereClause;
180
-
181
-        $statement = $this->database->prepare($query);
182
-        $statement->execute($this->parameterList);
183
-
184
-        $count = $statement->fetchColumn(0);
185
-        $statement->closeCursor();
186
-
187
-        return $this;
188
-    }
189
-
190
-    /**
191
-     * Limits the results
192
-     *
193
-     * @param integer      $limit
194
-     * @param integer|null $offset
195
-     *
196
-     * @return $this
197
-     *
198
-     */
199
-    public function limit($limit, $offset = null)
200
-    {
201
-        $this->limit = $limit;
202
-        $this->offset = $offset;
203
-
204
-        return $this;
205
-    }
206
-
207
-    private function applyLimit()
208
-    {
209
-        $clause = '';
210
-        if ($this->limit !== null) {
211
-            $clause = ' LIMIT ?';
212
-            $this->parameterList[] = $this->limit;
213
-
214
-            if ($this->offset !== null) {
215
-                $clause .= ' OFFSET ?';
216
-                $this->parameterList[] = $this->offset;
217
-            }
218
-        }
219
-
220
-        return $clause;
221
-    }
222
-
223
-    private function applyOrder()
224
-    {
225
-        if ($this->orderBy !== null) {
226
-            return ' ORDER BY ' . $this->orderBy;
227
-        }
228
-
229
-        return '';
230
-    }
231
-
232
-    /**
233
-     * @param array $columns
234
-     *
235
-     * @return PDOStatement
236
-     */
237
-    private function getData($columns = array('*'))
238
-    {
239
-        $query = $this->buildQuery($columns);
240
-        $query .= $this->applyOrder();
241
-        $query .= $this->applyLimit();
242
-
243
-        $statement = $this->database->prepare($query);
244
-        $statement->execute($this->parameterList);
245
-
246
-        return $statement;
247
-    }
248
-
249
-    /**
250
-     * @param array $columns
251
-     *
252
-     * @return string
253
-     */
254
-    protected function buildQuery($columns)
255
-    {
256
-        $colData = array();
257
-        foreach ($columns as $c) {
258
-            $colData[] = 'origin.' . $c;
259
-        }
260
-
261
-        $query = "SELECT {$this->modifiersClause} /* SearchHelper */ " . implode(', ', $colData) . ' FROM ' . $this->table . ' origin ';
262
-        $query .= $this->joinClause . $this->whereClause . $this->groupByClause;
263
-
264
-        return $query;
265
-    }
266
-
267
-    public function inIds($idList)
268
-    {
269
-        $this->inClause('id', $idList);
270
-
271
-        return $this;
272
-    }
273
-
274
-    protected function inClause($column, $values)
275
-    {
276
-        if (count($values) === 0) {
277
-            return;
278
-        }
279
-
280
-        // Urgh. OK. You can't use IN() with parameters directly, so let's munge something together.
281
-        $valueCount = count($values);
282
-
283
-        // Firstly, let's create a string of question marks, which will do as positional parameters.
284
-        $inSection = str_repeat('?,', $valueCount - 1) . '?';
285
-
286
-        $this->whereClause .= " AND {$column} IN ({$inSection})";
287
-        $this->parameterList = array_merge($this->parameterList, $values);
288
-    }
19
+	/** @var PdoDatabase */
20
+	protected $database;
21
+	/** @var array */
22
+	protected $parameterList = array();
23
+	/** @var null|int */
24
+	private $limit = null;
25
+	/** @var null|int */
26
+	private $offset = null;
27
+	private $orderBy = null;
28
+	/**
29
+	 * @var string The where clause.
30
+	 *
31
+	 * (the 1=1 condition will be optimised out of the query by the query planner, and simplifies our code here). Note
32
+	 * that we use positional parameters instead of named parameters because we don't know many times different options
33
+	 * will be called (looking at excluding() here, but there's the option for others).
34
+	 */
35
+	protected $whereClause = ' WHERE 1 = 1';
36
+	/** @var string */
37
+	protected $table;
38
+	protected $joinClause = '';
39
+	protected $groupByClause = '';
40
+	protected $modifiersClause = '';
41
+	private $targetClass;
42
+
43
+	/**
44
+	 * SearchHelperBase constructor.
45
+	 *
46
+	 * @param PdoDatabase $database
47
+	 * @param string      $table
48
+	 * @param             $targetClass
49
+	 * @param null|string $order Order by clause, excluding ORDER BY.
50
+	 */
51
+	protected function __construct(PdoDatabase $database, $table, $targetClass, $order = null)
52
+	{
53
+		$this->database = $database;
54
+		$this->table = $table;
55
+		$this->orderBy = $order;
56
+		$this->targetClass = $targetClass;
57
+	}
58
+
59
+	/**
60
+	 * Finalises the database query, and executes it, returning a set of objects.
61
+	 *
62
+	 * @return DataObject[]
63
+	 */
64
+	public function fetch()
65
+	{
66
+		$statement = $this->getData();
67
+
68
+		/** @var DataObject[] $returnedObjects */
69
+		$returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
70
+		foreach ($returnedObjects as $req) {
71
+			$req->setDatabase($this->database);
72
+		}
73
+
74
+		return $returnedObjects;
75
+	}
76
+
77
+	/**
78
+	 * @param string $whereClauseSection
79
+	 * @param array  $values
80
+	 *
81
+	 * @return array
82
+	 */
83
+	protected function fetchByParameter($whereClauseSection, $values)
84
+	{
85
+		$this->whereClause .= $whereClauseSection;
86
+
87
+		$countQuery = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
88
+		$countQuery .= $this->joinClause . $this->whereClause;
89
+
90
+		$query = $this->buildQuery(array('*'));
91
+		$query .= $this->applyOrder();
92
+
93
+		// shuffle around hackily TODO: fix this abomination - T593
94
+		$localParameterList = $this->parameterList;
95
+		$this->parameterList = array();
96
+
97
+		$query .= $this->applyLimit();
98
+
99
+		$limitParameters = $this->parameterList;
100
+
101
+		$statement = $this->database->prepare($query);
102
+		$countStatement = $this->database->prepare($countQuery);
103
+
104
+		$result = array();
105
+		foreach ($values as $v) {
106
+			// reset parameter list
107
+			$params = $localParameterList;
108
+			$params[] = $v;
109
+
110
+			$countStatement->execute($params);
111
+
112
+			// reapply the limit parameters
113
+			$params = array_merge($params, $limitParameters);
114
+
115
+			$statement->execute($params);
116
+
117
+			/** @var DataObject[] $returnedObjects */
118
+			$returnedObjects = $statement->fetchAll(PDO::FETCH_CLASS, $this->targetClass);
119
+			foreach ($returnedObjects as $req) {
120
+				$req->setDatabase($this->database);
121
+			}
122
+
123
+			$result[$v] = array(
124
+				'count' => $countStatement->fetchColumn(0),
125
+				'data'  => $returnedObjects,
126
+			);
127
+		}
128
+
129
+		return $result;
130
+	}
131
+
132
+	/**
133
+	 * Finalises the database query, and executes it, returning only the requested column.
134
+	 *
135
+	 * @param string $column The required column
136
+	 *
137
+	 * @param bool   $distinct
138
+	 *
139
+	 * @return array
140
+	 * @throws ApplicationLogicException
141
+	 */
142
+	public function fetchColumn($column, $distinct = false)
143
+	{
144
+		if ($distinct) {
145
+			if ($this->groupByClause !== '') {
146
+				throw new ApplicationLogicException('Cannot apply distinct to column fetch already using group by');
147
+			}
148
+
149
+			$this->groupByClause = ' GROUP BY origin.' . $column;
150
+		}
151
+
152
+		$statement = $this->getData(array($column));
153
+
154
+		return $statement->fetchAll(PDO::FETCH_COLUMN);
155
+	}
156
+
157
+	public function fetchMap($column)
158
+	{
159
+		$statement = $this->getData(array('id', $column));
160
+
161
+		$data = $statement->fetchAll(PDO::FETCH_ASSOC);
162
+		$map = array();
163
+
164
+		foreach ($data as $row) {
165
+			$map[$row['id']] = $row[$column];
166
+		}
167
+
168
+		return $map;
169
+	}
170
+
171
+	/**
172
+	 * @param int $count Returns the record count of the result set
173
+	 *
174
+	 * @return $this
175
+	 */
176
+	public function getRecordCount(&$count)
177
+	{
178
+		$query = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
179
+		$query .= $this->joinClause . $this->whereClause;
180
+
181
+		$statement = $this->database->prepare($query);
182
+		$statement->execute($this->parameterList);
183
+
184
+		$count = $statement->fetchColumn(0);
185
+		$statement->closeCursor();
186
+
187
+		return $this;
188
+	}
189
+
190
+	/**
191
+	 * Limits the results
192
+	 *
193
+	 * @param integer      $limit
194
+	 * @param integer|null $offset
195
+	 *
196
+	 * @return $this
197
+	 *
198
+	 */
199
+	public function limit($limit, $offset = null)
200
+	{
201
+		$this->limit = $limit;
202
+		$this->offset = $offset;
203
+
204
+		return $this;
205
+	}
206
+
207
+	private function applyLimit()
208
+	{
209
+		$clause = '';
210
+		if ($this->limit !== null) {
211
+			$clause = ' LIMIT ?';
212
+			$this->parameterList[] = $this->limit;
213
+
214
+			if ($this->offset !== null) {
215
+				$clause .= ' OFFSET ?';
216
+				$this->parameterList[] = $this->offset;
217
+			}
218
+		}
219
+
220
+		return $clause;
221
+	}
222
+
223
+	private function applyOrder()
224
+	{
225
+		if ($this->orderBy !== null) {
226
+			return ' ORDER BY ' . $this->orderBy;
227
+		}
228
+
229
+		return '';
230
+	}
231
+
232
+	/**
233
+	 * @param array $columns
234
+	 *
235
+	 * @return PDOStatement
236
+	 */
237
+	private function getData($columns = array('*'))
238
+	{
239
+		$query = $this->buildQuery($columns);
240
+		$query .= $this->applyOrder();
241
+		$query .= $this->applyLimit();
242
+
243
+		$statement = $this->database->prepare($query);
244
+		$statement->execute($this->parameterList);
245
+
246
+		return $statement;
247
+	}
248
+
249
+	/**
250
+	 * @param array $columns
251
+	 *
252
+	 * @return string
253
+	 */
254
+	protected function buildQuery($columns)
255
+	{
256
+		$colData = array();
257
+		foreach ($columns as $c) {
258
+			$colData[] = 'origin.' . $c;
259
+		}
260
+
261
+		$query = "SELECT {$this->modifiersClause} /* SearchHelper */ " . implode(', ', $colData) . ' FROM ' . $this->table . ' origin ';
262
+		$query .= $this->joinClause . $this->whereClause . $this->groupByClause;
263
+
264
+		return $query;
265
+	}
266
+
267
+	public function inIds($idList)
268
+	{
269
+		$this->inClause('id', $idList);
270
+
271
+		return $this;
272
+	}
273
+
274
+	protected function inClause($column, $values)
275
+	{
276
+		if (count($values) === 0) {
277
+			return;
278
+		}
279
+
280
+		// Urgh. OK. You can't use IN() with parameters directly, so let's munge something together.
281
+		$valueCount = count($values);
282
+
283
+		// Firstly, let's create a string of question marks, which will do as positional parameters.
284
+		$inSection = str_repeat('?,', $valueCount - 1) . '?';
285
+
286
+		$this->whereClause .= " AND {$column} IN ({$inSection})";
287
+		$this->parameterList = array_merge($this->parameterList, $values);
288
+	}
289 289
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -84,8 +84,8 @@  discard block
 block discarded – undo
84 84
     {
85 85
         $this->whereClause .= $whereClauseSection;
86 86
 
87
-        $countQuery = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
88
-        $countQuery .= $this->joinClause . $this->whereClause;
87
+        $countQuery = 'SELECT /* SearchHelper */ COUNT(*) FROM '.$this->table.' origin ';
88
+        $countQuery .= $this->joinClause.$this->whereClause;
89 89
 
90 90
         $query = $this->buildQuery(array('*'));
91 91
         $query .= $this->applyOrder();
@@ -146,7 +146,7 @@  discard block
 block discarded – undo
146 146
                 throw new ApplicationLogicException('Cannot apply distinct to column fetch already using group by');
147 147
             }
148 148
 
149
-            $this->groupByClause = ' GROUP BY origin.' . $column;
149
+            $this->groupByClause = ' GROUP BY origin.'.$column;
150 150
         }
151 151
 
152 152
         $statement = $this->getData(array($column));
@@ -175,8 +175,8 @@  discard block
 block discarded – undo
175 175
      */
176 176
     public function getRecordCount(&$count)
177 177
     {
178
-        $query = 'SELECT /* SearchHelper */ COUNT(*) FROM ' . $this->table . ' origin ';
179
-        $query .= $this->joinClause . $this->whereClause;
178
+        $query = 'SELECT /* SearchHelper */ COUNT(*) FROM '.$this->table.' origin ';
179
+        $query .= $this->joinClause.$this->whereClause;
180 180
 
181 181
         $statement = $this->database->prepare($query);
182 182
         $statement->execute($this->parameterList);
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
     private function applyOrder()
224 224
     {
225 225
         if ($this->orderBy !== null) {
226
-            return ' ORDER BY ' . $this->orderBy;
226
+            return ' ORDER BY '.$this->orderBy;
227 227
         }
228 228
 
229 229
         return '';
@@ -255,11 +255,11 @@  discard block
 block discarded – undo
255 255
     {
256 256
         $colData = array();
257 257
         foreach ($columns as $c) {
258
-            $colData[] = 'origin.' . $c;
258
+            $colData[] = 'origin.'.$c;
259 259
         }
260 260
 
261
-        $query = "SELECT {$this->modifiersClause} /* SearchHelper */ " . implode(', ', $colData) . ' FROM ' . $this->table . ' origin ';
262
-        $query .= $this->joinClause . $this->whereClause . $this->groupByClause;
261
+        $query = "SELECT {$this->modifiersClause} /* SearchHelper */ ".implode(', ', $colData).' FROM '.$this->table.' origin ';
262
+        $query .= $this->joinClause.$this->whereClause.$this->groupByClause;
263 263
 
264 264
         return $query;
265 265
     }
@@ -281,7 +281,7 @@  discard block
 block discarded – undo
281 281
         $valueCount = count($values);
282 282
 
283 283
         // Firstly, let's create a string of question marks, which will do as positional parameters.
284
-        $inSection = str_repeat('?,', $valueCount - 1) . '?';
284
+        $inSection = str_repeat('?,', $valueCount - 1).'?';
285 285
 
286 286
         $this->whereClause .= " AND {$column} IN ({$inSection})";
287 287
         $this->parameterList = array_merge($this->parameterList, $values);
Please login to merge, or discard this patch.
includes/Helpers/SearchHelpers/RequestSearchHelper.php 2 patches
Indentation   +174 added lines, -174 removed lines patch added patch discarded remove patch
@@ -15,178 +15,178 @@
 block discarded – undo
15 15
 
16 16
 class RequestSearchHelper extends SearchHelperBase
17 17
 {
18
-    /**
19
-     * RequestSearchHelper constructor.
20
-     *
21
-     * @param PdoDatabase $database
22
-     */
23
-    protected function __construct(PdoDatabase $database)
24
-    {
25
-        parent::__construct($database, 'request', Request::class);
26
-    }
27
-
28
-    /**
29
-     * Initiates a search for requests
30
-     *
31
-     * @param PdoDatabase $database
32
-     *
33
-     * @return RequestSearchHelper
34
-     */
35
-    public static function get(PdoDatabase $database)
36
-    {
37
-        $helper = new RequestSearchHelper($database);
38
-
39
-        return $helper;
40
-    }
41
-
42
-    /**
43
-     * Filters the results by IP address
44
-     *
45
-     * @param string $ipAddress
46
-     *
47
-     * @return $this
48
-     */
49
-    public function byIp($ipAddress)
50
-    {
51
-        $this->whereClause .= ' AND (ip LIKE ? OR forwardedip LIKE ?)';
52
-        $this->parameterList[] = $ipAddress;
53
-        $this->parameterList[] = '%' . trim($ipAddress, '%') . '%';
54
-
55
-        return $this;
56
-    }
57
-
58
-    /**
59
-     * Filters the results by email address
60
-     *
61
-     * @param string $emailAddress
62
-     *
63
-     * @return $this
64
-     */
65
-    public function byEmailAddress($emailAddress)
66
-    {
67
-        $this->whereClause .= ' AND email LIKE ?';
68
-        $this->parameterList[] = $emailAddress;
69
-
70
-        return $this;
71
-    }
72
-
73
-    /**
74
-     * Filters the results by name
75
-     *
76
-     * @param string $name
77
-     *
78
-     * @return $this
79
-     */
80
-    public function byName($name)
81
-    {
82
-        $this->whereClause .= ' AND name LIKE ?';
83
-        $this->parameterList[] = $name;
84
-
85
-        return $this;
86
-    }
87
-
88
-    /**
89
-     * Filters the requests to those with a defined status
90
-     *
91
-     * @param $status
92
-     *
93
-     * @return $this
94
-     */
95
-    public function byStatus($status)
96
-    {
97
-        $this->whereClause .= ' AND status = ?';
98
-        $this->parameterList[] = $status;
99
-
100
-        return $this;
101
-    }
102
-
103
-    /**
104
-     * Excludes a request from the results
105
-     *
106
-     * @param int $requestId
107
-     *
108
-     * @return $this
109
-     */
110
-    public function excludingRequest($requestId)
111
-    {
112
-        $this->whereClause .= ' AND id <> ?';
113
-        $this->parameterList[] = $requestId;
114
-
115
-        return $this;
116
-    }
117
-
118
-    /**
119
-     * Filters the results to only those with a confirmed email address
120
-     *
121
-     * @return $this
122
-     */
123
-    public function withConfirmedEmail()
124
-    {
125
-        $this->whereClause .= ' AND emailconfirm = ?';
126
-        $this->parameterList[] = 'Confirmed';
127
-
128
-        return $this;
129
-    }
130
-
131
-    /**
132
-     * Filters the results to exclude purged data
133
-     *
134
-     * @param SiteConfiguration $configuration
135
-     *
136
-     * @return $this
137
-     */
138
-    public function excludingPurgedData(SiteConfiguration $configuration)
139
-    {
140
-        $this->whereClause .= ' AND ip <> ? AND email <> ?';
141
-        $this->parameterList[] = $configuration->getDataClearIp();
142
-        $this->parameterList[] = $configuration->getDataClearEmail();
143
-
144
-        return $this;
145
-    }
146
-
147
-    /**
148
-     * Filters the requests to those without a defined status
149
-     *
150
-     * @param $status
151
-     *
152
-     * @return $this
153
-     */
154
-    public function excludingStatus($status)
155
-    {
156
-        $this->whereClause .= ' AND status <> ?';
157
-        $this->parameterList[] = $status;
158
-
159
-        return $this;
160
-    }
161
-
162
-    /**
163
-     * Filters the requests to those which have failed an auto-creation
164
-     *
165
-     * @return $this
166
-     */
167
-    public function isHospitalised()
168
-    {
169
-        $this->whereClause .= ' AND status = ?';
170
-        $this->parameterList[] =  RequestStatus::HOSPITAL;
171
-
172
-        return $this;
173
-    }
174
-
175
-    /**
176
-     * Filters the requests to those which have not failed an auto-creation
177
-     *
178
-     * @return $this
179
-     */
180
-    public function notHospitalised()
181
-    {
182
-        $this->whereClause .= ' AND status <> ?';
183
-        $this->parameterList[] =  RequestStatus::HOSPITAL;
184
-
185
-        return $this;
186
-    }
187
-
188
-    public function fetchByStatus($statuses)
189
-    {
190
-        return $this->fetchByParameter(' AND status = ?', $statuses);
191
-    }
18
+	/**
19
+	 * RequestSearchHelper constructor.
20
+	 *
21
+	 * @param PdoDatabase $database
22
+	 */
23
+	protected function __construct(PdoDatabase $database)
24
+	{
25
+		parent::__construct($database, 'request', Request::class);
26
+	}
27
+
28
+	/**
29
+	 * Initiates a search for requests
30
+	 *
31
+	 * @param PdoDatabase $database
32
+	 *
33
+	 * @return RequestSearchHelper
34
+	 */
35
+	public static function get(PdoDatabase $database)
36
+	{
37
+		$helper = new RequestSearchHelper($database);
38
+
39
+		return $helper;
40
+	}
41
+
42
+	/**
43
+	 * Filters the results by IP address
44
+	 *
45
+	 * @param string $ipAddress
46
+	 *
47
+	 * @return $this
48
+	 */
49
+	public function byIp($ipAddress)
50
+	{
51
+		$this->whereClause .= ' AND (ip LIKE ? OR forwardedip LIKE ?)';
52
+		$this->parameterList[] = $ipAddress;
53
+		$this->parameterList[] = '%' . trim($ipAddress, '%') . '%';
54
+
55
+		return $this;
56
+	}
57
+
58
+	/**
59
+	 * Filters the results by email address
60
+	 *
61
+	 * @param string $emailAddress
62
+	 *
63
+	 * @return $this
64
+	 */
65
+	public function byEmailAddress($emailAddress)
66
+	{
67
+		$this->whereClause .= ' AND email LIKE ?';
68
+		$this->parameterList[] = $emailAddress;
69
+
70
+		return $this;
71
+	}
72
+
73
+	/**
74
+	 * Filters the results by name
75
+	 *
76
+	 * @param string $name
77
+	 *
78
+	 * @return $this
79
+	 */
80
+	public function byName($name)
81
+	{
82
+		$this->whereClause .= ' AND name LIKE ?';
83
+		$this->parameterList[] = $name;
84
+
85
+		return $this;
86
+	}
87
+
88
+	/**
89
+	 * Filters the requests to those with a defined status
90
+	 *
91
+	 * @param $status
92
+	 *
93
+	 * @return $this
94
+	 */
95
+	public function byStatus($status)
96
+	{
97
+		$this->whereClause .= ' AND status = ?';
98
+		$this->parameterList[] = $status;
99
+
100
+		return $this;
101
+	}
102
+
103
+	/**
104
+	 * Excludes a request from the results
105
+	 *
106
+	 * @param int $requestId
107
+	 *
108
+	 * @return $this
109
+	 */
110
+	public function excludingRequest($requestId)
111
+	{
112
+		$this->whereClause .= ' AND id <> ?';
113
+		$this->parameterList[] = $requestId;
114
+
115
+		return $this;
116
+	}
117
+
118
+	/**
119
+	 * Filters the results to only those with a confirmed email address
120
+	 *
121
+	 * @return $this
122
+	 */
123
+	public function withConfirmedEmail()
124
+	{
125
+		$this->whereClause .= ' AND emailconfirm = ?';
126
+		$this->parameterList[] = 'Confirmed';
127
+
128
+		return $this;
129
+	}
130
+
131
+	/**
132
+	 * Filters the results to exclude purged data
133
+	 *
134
+	 * @param SiteConfiguration $configuration
135
+	 *
136
+	 * @return $this
137
+	 */
138
+	public function excludingPurgedData(SiteConfiguration $configuration)
139
+	{
140
+		$this->whereClause .= ' AND ip <> ? AND email <> ?';
141
+		$this->parameterList[] = $configuration->getDataClearIp();
142
+		$this->parameterList[] = $configuration->getDataClearEmail();
143
+
144
+		return $this;
145
+	}
146
+
147
+	/**
148
+	 * Filters the requests to those without a defined status
149
+	 *
150
+	 * @param $status
151
+	 *
152
+	 * @return $this
153
+	 */
154
+	public function excludingStatus($status)
155
+	{
156
+		$this->whereClause .= ' AND status <> ?';
157
+		$this->parameterList[] = $status;
158
+
159
+		return $this;
160
+	}
161
+
162
+	/**
163
+	 * Filters the requests to those which have failed an auto-creation
164
+	 *
165
+	 * @return $this
166
+	 */
167
+	public function isHospitalised()
168
+	{
169
+		$this->whereClause .= ' AND status = ?';
170
+		$this->parameterList[] =  RequestStatus::HOSPITAL;
171
+
172
+		return $this;
173
+	}
174
+
175
+	/**
176
+	 * Filters the requests to those which have not failed an auto-creation
177
+	 *
178
+	 * @return $this
179
+	 */
180
+	public function notHospitalised()
181
+	{
182
+		$this->whereClause .= ' AND status <> ?';
183
+		$this->parameterList[] =  RequestStatus::HOSPITAL;
184
+
185
+		return $this;
186
+	}
187
+
188
+	public function fetchByStatus($statuses)
189
+	{
190
+		return $this->fetchByParameter(' AND status = ?', $statuses);
191
+	}
192 192
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
     {
51 51
         $this->whereClause .= ' AND (ip LIKE ? OR forwardedip LIKE ?)';
52 52
         $this->parameterList[] = $ipAddress;
53
-        $this->parameterList[] = '%' . trim($ipAddress, '%') . '%';
53
+        $this->parameterList[] = '%'.trim($ipAddress, '%').'%';
54 54
 
55 55
         return $this;
56 56
     }
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
     public function isHospitalised()
168 168
     {
169 169
         $this->whereClause .= ' AND status = ?';
170
-        $this->parameterList[] =  RequestStatus::HOSPITAL;
170
+        $this->parameterList[] = RequestStatus::HOSPITAL;
171 171
 
172 172
         return $this;
173 173
     }
@@ -180,7 +180,7 @@  discard block
 block discarded – undo
180 180
     public function notHospitalised()
181 181
     {
182 182
         $this->whereClause .= ' AND status <> ?';
183
-        $this->parameterList[] =  RequestStatus::HOSPITAL;
183
+        $this->parameterList[] = RequestStatus::HOSPITAL;
184 184
 
185 185
         return $this;
186 186
     }
Please login to merge, or discard this patch.
includes/Helpers/LogHelper.php 3 patches
Indentation   +402 added lines, -402 removed lines patch added patch discarded remove patch
@@ -27,413 +27,413 @@
 block discarded – undo
27 27
 
28 28
 class LogHelper
29 29
 {
30
-    /**
31
-     * Summary of getRequestLogsWithComments
32
-     *
33
-     * @param int             $requestId
34
-     * @param PdoDatabase     $db
35
-     * @param SecurityManager $securityManager
36
-     *
37
-     * @return \Waca\DataObject[]
38
-     */
39
-    public static function getRequestLogsWithComments($requestId, PdoDatabase $db, SecurityManager $securityManager)
40
-    {
41
-        $logs = LogSearchHelper::get($db)->byObjectType('Request')->byObjectId($requestId)->fetch();
42
-
43
-        $currentUser = User::getCurrent($db);
44
-        $securityResult = $securityManager->allows('RequestData', 'seeRestrictedComments', $currentUser);
45
-        $showAllComments = $securityResult === SecurityManager::ALLOWED;
46
-
47
-        $comments = Comment::getForRequest($requestId, $db, $showAllComments, $currentUser->getId());
48
-
49
-        $items = array_merge($logs, $comments);
50
-
51
-        /**
52
-         * @param DataObject $item
53
-         *
54
-         * @return int
55
-         */
56
-        $sortKey = function(DataObject $item) {
57
-            if ($item instanceof Log) {
58
-                return $item->getTimestamp()->getTimestamp();
59
-            }
60
-
61
-            if ($item instanceof Comment) {
62
-                return $item->getTime()->getTimestamp();
63
-            }
64
-
65
-            return 0;
66
-        };
67
-
68
-        do {
69
-            $flag = false;
70
-
71
-            $loopLimit = (count($items) - 1);
72
-            for ($i = 0; $i < $loopLimit; $i++) {
73
-                // are these two items out of order?
74
-                if ($sortKey($items[$i]) > $sortKey($items[$i + 1])) {
75
-                    // swap them
76
-                    $swap = $items[$i];
77
-                    $items[$i] = $items[$i + 1];
78
-                    $items[$i + 1] = $swap;
79
-
80
-                    // set a flag to say we've modified the array this time around
81
-                    $flag = true;
82
-                }
83
-            }
84
-        }
85
-        while ($flag);
86
-
87
-        return $items;
88
-    }
89
-
90
-    /**
91
-     * Summary of getLogDescription
92
-     *
93
-     * @param Log $entry
94
-     *
95
-     * @return string
96
-     */
97
-    public static function getLogDescription(Log $entry)
98
-    {
99
-        $text = "Deferred to ";
100
-        if (substr($entry->getAction(), 0, strlen($text)) == $text) {
101
-            // Deferred to a different queue
102
-            // This is exactly what we want to display.
103
-            return $entry->getAction();
104
-        }
105
-
106
-        $text = "Closed custom-n";
107
-        if ($entry->getAction() == $text) {
108
-            // Custom-closed
109
-            return "closed (custom reason - account not created)";
110
-        }
111
-
112
-        $text = "Closed custom-y";
113
-        if ($entry->getAction() == $text) {
114
-            // Custom-closed
115
-            return "closed (custom reason - account created)";
116
-        }
117
-
118
-        $text = "Closed 0";
119
-        if ($entry->getAction() == $text) {
120
-            // Dropped the request - short-circuit the lookup
121
-            return "dropped request";
122
-        }
123
-
124
-        $text = "Closed ";
125
-        if (substr($entry->getAction(), 0, strlen($text)) == $text) {
126
-            // Closed with a reason - do a lookup here.
127
-            $id = substr($entry->getAction(), strlen($text));
128
-            /** @var EmailTemplate $template */
129
-            $template = EmailTemplate::getById((int)$id, $entry->getDatabase());
130
-
131
-            if ($template != false) {
132
-                return "closed (" . $template->getName() . ")";
133
-            }
134
-        }
135
-
136
-        // Fall back to the basic stuff
137
-        $lookup = array(
138
-            'Reserved'            => 'reserved',
139
-            'Email Confirmed'     => 'email-confirmed',
140
-            'Unreserved'          => 'unreserved',
141
-            'Approved'            => 'approved',
142
-            'Suspended'           => 'suspended',
143
-            'RoleChange'          => 'changed roles',
144
-            'Banned'              => 'banned',
145
-            'Edited'              => 'edited interface message',
146
-            'Declined'            => 'declined',
147
-            'EditComment-c'       => 'edited a comment',
148
-            'EditComment-r'       => 'edited a comment',
149
-            'Unbanned'            => 'unbanned',
150
-            'Promoted'            => 'promoted to tool admin',
151
-            'BreakReserve'        => 'forcibly broke the reservation',
152
-            'Prefchange'          => 'changed user preferences',
153
-            'Renamed'             => 'renamed',
154
-            'Demoted'             => 'demoted from tool admin',
155
-            'ReceiveReserved'     => 'received the reservation',
156
-            'SendReserved'        => 'sent the reservation',
157
-            'EditedEmail'         => 'edited email',
158
-            'DeletedTemplate'     => 'deleted template',
159
-            'EditedTemplate'      => 'edited template',
160
-            'CreatedEmail'        => 'created email',
161
-            'CreatedTemplate'     => 'created template',
162
-            'SentMail'            => 'sent an email to the requestor',
163
-            'Registered'          => 'registered a tool account',
164
-            'JobIssue'            => 'ran a background job unsuccessfully',
165
-            'JobCompleted'        => 'completed a background job',
166
-            'JobAcknowledged'     => 'acknowledged a job failure',
167
-            'JobRequeued'         => 'requeued a job for re-execution',
168
-            'EnqueuedJobQueue'    => 'scheduled for creation',
169
-            'Hospitalised'        => 'sent to the hospital',
170
-        );
171
-
172
-        if (array_key_exists($entry->getAction(), $lookup)) {
173
-            return $lookup[$entry->getAction()];
174
-        }
175
-
176
-        // OK, I don't know what this is. Fall back to something sane.
177
-        return "performed an unknown action ({$entry->getAction()})";
178
-    }
179
-
180
-    /**
181
-     * @param PdoDatabase $database
182
-     *
183
-     * @return array
184
-     */
185
-    public static function getLogActions(PdoDatabase $database)
186
-    {
187
-        $lookup = array(
188
-            'Reserved'            => 'reserved',
189
-            'Email Confirmed'     => 'email-confirmed',
190
-            'Unreserved'          => 'unreserved',
191
-            'Approved'            => 'approved',
192
-            'Suspended'           => 'suspended',
193
-            'RoleChange'          => 'changed roles',
194
-            'Banned'              => 'banned',
195
-            'Edited'              => 'edited interface message',
196
-            'Declined'            => 'declined',
197
-            'EditComment-c'       => 'edited a comment (by comment ID)',
198
-            'EditComment-r'       => 'edited a comment (by request)',
199
-            'Unbanned'            => 'unbanned',
200
-            'Promoted'            => 'promoted to tool admin',
201
-            'BreakReserve'        => 'forcibly broke the reservation',
202
-            'Prefchange'          => 'changed user preferences',
203
-            'Renamed'             => 'renamed',
204
-            'Demoted'             => 'demoted from tool admin',
205
-            'ReceiveReserved'     => 'received the reservation',
206
-            'SendReserved'        => 'sent the reservation',
207
-            'EditedEmail'         => 'edited email',
208
-            'DeletedTemplate'     => 'deleted template',
209
-            'EditedTemplate'      => 'edited template',
210
-            'CreatedEmail'        => 'created email',
211
-            'CreatedTemplate'     => 'created template',
212
-            'SentMail'            => 'sent an email to the requestor',
213
-            'Registered'          => 'registered a tool account',
214
-            'Closed 0'            => 'dropped request',
215
-            'JobIssue'            => 'ran a background job unsuccessfully',
216
-            'JobCompleted'        => 'completed a background job',
217
-            'JobAcknowledged'     => 'acknowledged a job failure',
218
-            'JobRequeued'         => 'requeued a job for re-execution',
219
-            'EnqueuedJobQueue'    => 'scheduled for creation',
220
-            'Hospitalised'        => 'sent to the hospital',
221
-        );
222
-
223
-        $statement = $database->query(<<<SQL
30
+	/**
31
+	 * Summary of getRequestLogsWithComments
32
+	 *
33
+	 * @param int             $requestId
34
+	 * @param PdoDatabase     $db
35
+	 * @param SecurityManager $securityManager
36
+	 *
37
+	 * @return \Waca\DataObject[]
38
+	 */
39
+	public static function getRequestLogsWithComments($requestId, PdoDatabase $db, SecurityManager $securityManager)
40
+	{
41
+		$logs = LogSearchHelper::get($db)->byObjectType('Request')->byObjectId($requestId)->fetch();
42
+
43
+		$currentUser = User::getCurrent($db);
44
+		$securityResult = $securityManager->allows('RequestData', 'seeRestrictedComments', $currentUser);
45
+		$showAllComments = $securityResult === SecurityManager::ALLOWED;
46
+
47
+		$comments = Comment::getForRequest($requestId, $db, $showAllComments, $currentUser->getId());
48
+
49
+		$items = array_merge($logs, $comments);
50
+
51
+		/**
52
+		 * @param DataObject $item
53
+		 *
54
+		 * @return int
55
+		 */
56
+		$sortKey = function(DataObject $item) {
57
+			if ($item instanceof Log) {
58
+				return $item->getTimestamp()->getTimestamp();
59
+			}
60
+
61
+			if ($item instanceof Comment) {
62
+				return $item->getTime()->getTimestamp();
63
+			}
64
+
65
+			return 0;
66
+		};
67
+
68
+		do {
69
+			$flag = false;
70
+
71
+			$loopLimit = (count($items) - 1);
72
+			for ($i = 0; $i < $loopLimit; $i++) {
73
+				// are these two items out of order?
74
+				if ($sortKey($items[$i]) > $sortKey($items[$i + 1])) {
75
+					// swap them
76
+					$swap = $items[$i];
77
+					$items[$i] = $items[$i + 1];
78
+					$items[$i + 1] = $swap;
79
+
80
+					// set a flag to say we've modified the array this time around
81
+					$flag = true;
82
+				}
83
+			}
84
+		}
85
+		while ($flag);
86
+
87
+		return $items;
88
+	}
89
+
90
+	/**
91
+	 * Summary of getLogDescription
92
+	 *
93
+	 * @param Log $entry
94
+	 *
95
+	 * @return string
96
+	 */
97
+	public static function getLogDescription(Log $entry)
98
+	{
99
+		$text = "Deferred to ";
100
+		if (substr($entry->getAction(), 0, strlen($text)) == $text) {
101
+			// Deferred to a different queue
102
+			// This is exactly what we want to display.
103
+			return $entry->getAction();
104
+		}
105
+
106
+		$text = "Closed custom-n";
107
+		if ($entry->getAction() == $text) {
108
+			// Custom-closed
109
+			return "closed (custom reason - account not created)";
110
+		}
111
+
112
+		$text = "Closed custom-y";
113
+		if ($entry->getAction() == $text) {
114
+			// Custom-closed
115
+			return "closed (custom reason - account created)";
116
+		}
117
+
118
+		$text = "Closed 0";
119
+		if ($entry->getAction() == $text) {
120
+			// Dropped the request - short-circuit the lookup
121
+			return "dropped request";
122
+		}
123
+
124
+		$text = "Closed ";
125
+		if (substr($entry->getAction(), 0, strlen($text)) == $text) {
126
+			// Closed with a reason - do a lookup here.
127
+			$id = substr($entry->getAction(), strlen($text));
128
+			/** @var EmailTemplate $template */
129
+			$template = EmailTemplate::getById((int)$id, $entry->getDatabase());
130
+
131
+			if ($template != false) {
132
+				return "closed (" . $template->getName() . ")";
133
+			}
134
+		}
135
+
136
+		// Fall back to the basic stuff
137
+		$lookup = array(
138
+			'Reserved'            => 'reserved',
139
+			'Email Confirmed'     => 'email-confirmed',
140
+			'Unreserved'          => 'unreserved',
141
+			'Approved'            => 'approved',
142
+			'Suspended'           => 'suspended',
143
+			'RoleChange'          => 'changed roles',
144
+			'Banned'              => 'banned',
145
+			'Edited'              => 'edited interface message',
146
+			'Declined'            => 'declined',
147
+			'EditComment-c'       => 'edited a comment',
148
+			'EditComment-r'       => 'edited a comment',
149
+			'Unbanned'            => 'unbanned',
150
+			'Promoted'            => 'promoted to tool admin',
151
+			'BreakReserve'        => 'forcibly broke the reservation',
152
+			'Prefchange'          => 'changed user preferences',
153
+			'Renamed'             => 'renamed',
154
+			'Demoted'             => 'demoted from tool admin',
155
+			'ReceiveReserved'     => 'received the reservation',
156
+			'SendReserved'        => 'sent the reservation',
157
+			'EditedEmail'         => 'edited email',
158
+			'DeletedTemplate'     => 'deleted template',
159
+			'EditedTemplate'      => 'edited template',
160
+			'CreatedEmail'        => 'created email',
161
+			'CreatedTemplate'     => 'created template',
162
+			'SentMail'            => 'sent an email to the requestor',
163
+			'Registered'          => 'registered a tool account',
164
+			'JobIssue'            => 'ran a background job unsuccessfully',
165
+			'JobCompleted'        => 'completed a background job',
166
+			'JobAcknowledged'     => 'acknowledged a job failure',
167
+			'JobRequeued'         => 'requeued a job for re-execution',
168
+			'EnqueuedJobQueue'    => 'scheduled for creation',
169
+			'Hospitalised'        => 'sent to the hospital',
170
+		);
171
+
172
+		if (array_key_exists($entry->getAction(), $lookup)) {
173
+			return $lookup[$entry->getAction()];
174
+		}
175
+
176
+		// OK, I don't know what this is. Fall back to something sane.
177
+		return "performed an unknown action ({$entry->getAction()})";
178
+	}
179
+
180
+	/**
181
+	 * @param PdoDatabase $database
182
+	 *
183
+	 * @return array
184
+	 */
185
+	public static function getLogActions(PdoDatabase $database)
186
+	{
187
+		$lookup = array(
188
+			'Reserved'            => 'reserved',
189
+			'Email Confirmed'     => 'email-confirmed',
190
+			'Unreserved'          => 'unreserved',
191
+			'Approved'            => 'approved',
192
+			'Suspended'           => 'suspended',
193
+			'RoleChange'          => 'changed roles',
194
+			'Banned'              => 'banned',
195
+			'Edited'              => 'edited interface message',
196
+			'Declined'            => 'declined',
197
+			'EditComment-c'       => 'edited a comment (by comment ID)',
198
+			'EditComment-r'       => 'edited a comment (by request)',
199
+			'Unbanned'            => 'unbanned',
200
+			'Promoted'            => 'promoted to tool admin',
201
+			'BreakReserve'        => 'forcibly broke the reservation',
202
+			'Prefchange'          => 'changed user preferences',
203
+			'Renamed'             => 'renamed',
204
+			'Demoted'             => 'demoted from tool admin',
205
+			'ReceiveReserved'     => 'received the reservation',
206
+			'SendReserved'        => 'sent the reservation',
207
+			'EditedEmail'         => 'edited email',
208
+			'DeletedTemplate'     => 'deleted template',
209
+			'EditedTemplate'      => 'edited template',
210
+			'CreatedEmail'        => 'created email',
211
+			'CreatedTemplate'     => 'created template',
212
+			'SentMail'            => 'sent an email to the requestor',
213
+			'Registered'          => 'registered a tool account',
214
+			'Closed 0'            => 'dropped request',
215
+			'JobIssue'            => 'ran a background job unsuccessfully',
216
+			'JobCompleted'        => 'completed a background job',
217
+			'JobAcknowledged'     => 'acknowledged a job failure',
218
+			'JobRequeued'         => 'requeued a job for re-execution',
219
+			'EnqueuedJobQueue'    => 'scheduled for creation',
220
+			'Hospitalised'        => 'sent to the hospital',
221
+		);
222
+
223
+		$statement = $database->query(<<<SQL
224 224
 SELECT CONCAT('Closed ', id) AS k, CONCAT('closed (',name,')') AS v
225 225
 FROM emailtemplate;
226 226
 SQL
227
-        );
228
-        foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
229
-            $lookup[$row['k']] = $row['v'];
230
-        }
231
-
232
-        return $lookup;
233
-    }
234
-
235
-    public static function getObjectTypes()
236
-    {
237
-        return array(
238
-            'Ban'             => 'Ban',
239
-            'Comment'         => 'Comment',
240
-            'EmailTemplate'   => 'Email template',
241
-            'JobQueue'        => 'Job queue item',
242
-            'Request'         => 'Request',
243
-            'SiteNotice'      => 'Site notice',
244
-            'User'            => 'User',
245
-            'WelcomeTemplate' => 'Welcome template',
246
-        );
247
-    }
248
-
249
-    /**
250
-     * This returns a HTML
251
-     *
252
-     * @param string            $objectId
253
-     * @param string            $objectType
254
-     * @param PdoDatabase       $database
255
-     * @param SiteConfiguration $configuration
256
-     *
257
-     * @return null|string
258
-     * @category Security-Critical
259
-     */
260
-    private static function getObjectDescription(
261
-        $objectId,
262
-        $objectType,
263
-        PdoDatabase $database,
264
-        SiteConfiguration $configuration
265
-    ) {
266
-        if ($objectType == '') {
267
-            return null;
268
-        }
269
-
270
-        $baseurl = $configuration->getBaseUrl();
271
-
272
-        switch ($objectType) {
273
-            case 'Ban':
274
-                /** @var Ban $ban */
275
-                $ban = Ban::getById($objectId, $database);
276
-
277
-                if ($ban === false) {
278
-                    return 'Ban #' . $objectId . "</a>";
279
-                }
280
-
281
-                return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
282
-            case 'EmailTemplate':
283
-                /** @var EmailTemplate $emailTemplate */
284
-                $emailTemplate = EmailTemplate::getById($objectId, $database);
285
-                $name = htmlentities($emailTemplate->getName(), ENT_COMPAT, 'UTF-8');
286
-
287
-                return <<<HTML
227
+		);
228
+		foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
229
+			$lookup[$row['k']] = $row['v'];
230
+		}
231
+
232
+		return $lookup;
233
+	}
234
+
235
+	public static function getObjectTypes()
236
+	{
237
+		return array(
238
+			'Ban'             => 'Ban',
239
+			'Comment'         => 'Comment',
240
+			'EmailTemplate'   => 'Email template',
241
+			'JobQueue'        => 'Job queue item',
242
+			'Request'         => 'Request',
243
+			'SiteNotice'      => 'Site notice',
244
+			'User'            => 'User',
245
+			'WelcomeTemplate' => 'Welcome template',
246
+		);
247
+	}
248
+
249
+	/**
250
+	 * This returns a HTML
251
+	 *
252
+	 * @param string            $objectId
253
+	 * @param string            $objectType
254
+	 * @param PdoDatabase       $database
255
+	 * @param SiteConfiguration $configuration
256
+	 *
257
+	 * @return null|string
258
+	 * @category Security-Critical
259
+	 */
260
+	private static function getObjectDescription(
261
+		$objectId,
262
+		$objectType,
263
+		PdoDatabase $database,
264
+		SiteConfiguration $configuration
265
+	) {
266
+		if ($objectType == '') {
267
+			return null;
268
+		}
269
+
270
+		$baseurl = $configuration->getBaseUrl();
271
+
272
+		switch ($objectType) {
273
+			case 'Ban':
274
+				/** @var Ban $ban */
275
+				$ban = Ban::getById($objectId, $database);
276
+
277
+				if ($ban === false) {
278
+					return 'Ban #' . $objectId . "</a>";
279
+				}
280
+
281
+				return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
282
+			case 'EmailTemplate':
283
+				/** @var EmailTemplate $emailTemplate */
284
+				$emailTemplate = EmailTemplate::getById($objectId, $database);
285
+				$name = htmlentities($emailTemplate->getName(), ENT_COMPAT, 'UTF-8');
286
+
287
+				return <<<HTML
288 288
 <a href="{$baseurl}/internal.php/emailManagement/view?id={$objectId}">Email Template #{$objectId} ({$name})</a>
289 289
 HTML;
290
-            case 'SiteNotice':
291
-                return "<a href=\"{$baseurl}/internal.php/siteNotice\">the site notice</a>";
292
-            case 'Request':
293
-                /** @var Request $request */
294
-                $request = Request::getById($objectId, $database);
295
-                $name = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
296
-
297
-                return <<<HTML
290
+			case 'SiteNotice':
291
+				return "<a href=\"{$baseurl}/internal.php/siteNotice\">the site notice</a>";
292
+			case 'Request':
293
+				/** @var Request $request */
294
+				$request = Request::getById($objectId, $database);
295
+				$name = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
296
+
297
+				return <<<HTML
298 298
 <a href="{$baseurl}/internal.php/viewRequest?id={$objectId}">Request #{$objectId} ({$name})</a>
299 299
 HTML;
300
-            case 'User':
301
-                /** @var User $user */
302
-                $user = User::getById($objectId, $database);
303
-                $username = htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8');
304
-
305
-                return "<a href=\"{$baseurl}/internal.php/statistics/users/detail?user={$objectId}\">{$username}</a>";
306
-            case 'WelcomeTemplate':
307
-                /** @var WelcomeTemplate $welcomeTemplate */
308
-                $welcomeTemplate = WelcomeTemplate::getById($objectId, $database);
309
-
310
-                // some old templates have been completely deleted and lost to the depths of time.
311
-                if ($welcomeTemplate === false) {
312
-                    return "Welcome template #{$objectId}";
313
-                }
314
-                else {
315
-                    $userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
316
-
317
-                    return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
318
-                }
319
-            case 'JobQueue':
320
-                /** @var JobQueue $job */
321
-                $job = JobQueue::getById($objectId, $database);
322
-
323
-                $taskDescriptions = JobQueue::getTaskDescriptions();
324
-
325
-                $task = $job->getTask();
326
-                if(isset($taskDescriptions[$task])){
327
-                    $description = $taskDescriptions[$task];
328
-                } else {
329
-                    $description = 'Unknown task';
330
-                }
331
-
332
-                return "<a href=\"{$baseurl}/internal.php/jobQueue/view?id={$objectId}\">Job #{$job->getId()} ({$description})</a>";
333
-            default:
334
-                return '[' . $objectType . " " . $objectId . ']';
335
-        }
336
-    }
337
-
338
-    /**
339
-     * @param Log[]             $logs
340
-     * @param PdoDatabase       $database
341
-     * @param SiteConfiguration $configuration
342
-     *
343
-     * @return array
344
-     * @throws Exception
345
-     */
346
-    public static function prepareLogsForTemplate($logs, PdoDatabase $database, SiteConfiguration $configuration)
347
-    {
348
-        $userIds = array();
349
-
350
-        /** @var Log $logEntry */
351
-        foreach ($logs as $logEntry) {
352
-            if (!$logEntry instanceof Log) {
353
-                // if this happens, we've done something wrong with passing back the log data.
354
-                throw new Exception('Log entry is not an instance of a Log, this should never happen.');
355
-            }
356
-
357
-            $user = $logEntry->getUser();
358
-            if ($user === -1) {
359
-                continue;
360
-            }
361
-
362
-            if (!array_search($user, $userIds)) {
363
-                $userIds[] = $user;
364
-            }
365
-        }
366
-
367
-        $users = UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username');
368
-        $users[-1] = User::getCommunity()->getUsername();
369
-
370
-        $logData = array();
371
-
372
-        /** @var Log $logEntry */
373
-        foreach ($logs as $logEntry) {
374
-            $objectDescription = self::getObjectDescription($logEntry->getObjectId(), $logEntry->getObjectType(),
375
-                $database, $configuration);
376
-
377
-            switch ($logEntry->getAction()) {
378
-                case 'Renamed':
379
-                    $renameData = unserialize($logEntry->getComment());
380
-                    $oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
381
-                    $newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
382
-                    $comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
383
-                    break;
384
-                case 'RoleChange':
385
-                    $roleChangeData = unserialize($logEntry->getComment());
386
-
387
-                    $removed = array();
388
-                    foreach ($roleChangeData['removed'] as $r) {
389
-                        $removed[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
390
-                    }
391
-
392
-                    $added = array();
393
-                    foreach ($roleChangeData['added'] as $r) {
394
-                        $added[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
395
-                    }
396
-
397
-                    $reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
398
-
399
-                    $roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
400
-                    $comment = $roleDelta . ' with comment: ' . $reason;
401
-                    break;
402
-                case 'JobIssue':
403
-                    $jobIssueData = unserialize($logEntry->getComment());
404
-                    $errorMessage = $jobIssueData['error'];
405
-                    $status = $jobIssueData['status'];
406
-
407
-                    $comment = 'Job ' . htmlentities($status, ENT_COMPAT, 'UTF-8') . ': ';
408
-                    $comment .= htmlentities($errorMessage, ENT_COMPAT, 'UTF-8');
409
-                    break;
410
-                case 'JobIssueRequest':
411
-                case 'JobCompletedRequest':
412
-                    $jobData = unserialize($logEntry->getComment());
413
-
414
-                    /** @var JobQueue $job */
415
-                    $job = JobQueue::getById($jobData['job'], $database);
416
-                    $descs = JobQueue::getTaskDescriptions();
417
-                    $comment = htmlentities($descs[$job->getTask()], ENT_COMPAT, 'UTF-8');
418
-                    break;
419
-
420
-                case 'JobCompleted':
421
-                    break;
422
-                default:
423
-                    $comment = $logEntry->getComment();
424
-                    break;
425
-            }
426
-
427
-            $logData[] = array(
428
-                'timestamp'         => $logEntry->getTimestamp(),
429
-                'userid'            => $logEntry->getUser(),
430
-                'username'          => $users[$logEntry->getUser()],
431
-                'description'       => self::getLogDescription($logEntry),
432
-                'objectdescription' => $objectDescription,
433
-                'comment'           => $comment,
434
-            );
435
-        }
436
-
437
-        return array($users, $logData);
438
-    }
300
+			case 'User':
301
+				/** @var User $user */
302
+				$user = User::getById($objectId, $database);
303
+				$username = htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8');
304
+
305
+				return "<a href=\"{$baseurl}/internal.php/statistics/users/detail?user={$objectId}\">{$username}</a>";
306
+			case 'WelcomeTemplate':
307
+				/** @var WelcomeTemplate $welcomeTemplate */
308
+				$welcomeTemplate = WelcomeTemplate::getById($objectId, $database);
309
+
310
+				// some old templates have been completely deleted and lost to the depths of time.
311
+				if ($welcomeTemplate === false) {
312
+					return "Welcome template #{$objectId}";
313
+				}
314
+				else {
315
+					$userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
316
+
317
+					return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
318
+				}
319
+			case 'JobQueue':
320
+				/** @var JobQueue $job */
321
+				$job = JobQueue::getById($objectId, $database);
322
+
323
+				$taskDescriptions = JobQueue::getTaskDescriptions();
324
+
325
+				$task = $job->getTask();
326
+				if(isset($taskDescriptions[$task])){
327
+					$description = $taskDescriptions[$task];
328
+				} else {
329
+					$description = 'Unknown task';
330
+				}
331
+
332
+				return "<a href=\"{$baseurl}/internal.php/jobQueue/view?id={$objectId}\">Job #{$job->getId()} ({$description})</a>";
333
+			default:
334
+				return '[' . $objectType . " " . $objectId . ']';
335
+		}
336
+	}
337
+
338
+	/**
339
+	 * @param Log[]             $logs
340
+	 * @param PdoDatabase       $database
341
+	 * @param SiteConfiguration $configuration
342
+	 *
343
+	 * @return array
344
+	 * @throws Exception
345
+	 */
346
+	public static function prepareLogsForTemplate($logs, PdoDatabase $database, SiteConfiguration $configuration)
347
+	{
348
+		$userIds = array();
349
+
350
+		/** @var Log $logEntry */
351
+		foreach ($logs as $logEntry) {
352
+			if (!$logEntry instanceof Log) {
353
+				// if this happens, we've done something wrong with passing back the log data.
354
+				throw new Exception('Log entry is not an instance of a Log, this should never happen.');
355
+			}
356
+
357
+			$user = $logEntry->getUser();
358
+			if ($user === -1) {
359
+				continue;
360
+			}
361
+
362
+			if (!array_search($user, $userIds)) {
363
+				$userIds[] = $user;
364
+			}
365
+		}
366
+
367
+		$users = UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username');
368
+		$users[-1] = User::getCommunity()->getUsername();
369
+
370
+		$logData = array();
371
+
372
+		/** @var Log $logEntry */
373
+		foreach ($logs as $logEntry) {
374
+			$objectDescription = self::getObjectDescription($logEntry->getObjectId(), $logEntry->getObjectType(),
375
+				$database, $configuration);
376
+
377
+			switch ($logEntry->getAction()) {
378
+				case 'Renamed':
379
+					$renameData = unserialize($logEntry->getComment());
380
+					$oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
381
+					$newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
382
+					$comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
383
+					break;
384
+				case 'RoleChange':
385
+					$roleChangeData = unserialize($logEntry->getComment());
386
+
387
+					$removed = array();
388
+					foreach ($roleChangeData['removed'] as $r) {
389
+						$removed[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
390
+					}
391
+
392
+					$added = array();
393
+					foreach ($roleChangeData['added'] as $r) {
394
+						$added[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
395
+					}
396
+
397
+					$reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
398
+
399
+					$roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
400
+					$comment = $roleDelta . ' with comment: ' . $reason;
401
+					break;
402
+				case 'JobIssue':
403
+					$jobIssueData = unserialize($logEntry->getComment());
404
+					$errorMessage = $jobIssueData['error'];
405
+					$status = $jobIssueData['status'];
406
+
407
+					$comment = 'Job ' . htmlentities($status, ENT_COMPAT, 'UTF-8') . ': ';
408
+					$comment .= htmlentities($errorMessage, ENT_COMPAT, 'UTF-8');
409
+					break;
410
+				case 'JobIssueRequest':
411
+				case 'JobCompletedRequest':
412
+					$jobData = unserialize($logEntry->getComment());
413
+
414
+					/** @var JobQueue $job */
415
+					$job = JobQueue::getById($jobData['job'], $database);
416
+					$descs = JobQueue::getTaskDescriptions();
417
+					$comment = htmlentities($descs[$job->getTask()], ENT_COMPAT, 'UTF-8');
418
+					break;
419
+
420
+				case 'JobCompleted':
421
+					break;
422
+				default:
423
+					$comment = $logEntry->getComment();
424
+					break;
425
+			}
426
+
427
+			$logData[] = array(
428
+				'timestamp'         => $logEntry->getTimestamp(),
429
+				'userid'            => $logEntry->getUser(),
430
+				'username'          => $users[$logEntry->getUser()],
431
+				'description'       => self::getLogDescription($logEntry),
432
+				'objectdescription' => $objectDescription,
433
+				'comment'           => $comment,
434
+			);
435
+		}
436
+
437
+		return array($users, $logData);
438
+	}
439 439
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
             $template = EmailTemplate::getById((int)$id, $entry->getDatabase());
130 130
 
131 131
             if ($template != false) {
132
-                return "closed (" . $template->getName() . ")";
132
+                return "closed (".$template->getName().")";
133 133
             }
134 134
         }
135 135
 
@@ -275,10 +275,10 @@  discard block
 block discarded – undo
275 275
                 $ban = Ban::getById($objectId, $database);
276 276
 
277 277
                 if ($ban === false) {
278
-                    return 'Ban #' . $objectId . "</a>";
278
+                    return 'Ban #'.$objectId."</a>";
279 279
                 }
280 280
 
281
-                return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
281
+                return 'Ban #'.$objectId." (".htmlentities($ban->getTarget()).")</a>";
282 282
             case 'EmailTemplate':
283 283
                 /** @var EmailTemplate $emailTemplate */
284 284
                 $emailTemplate = EmailTemplate::getById($objectId, $database);
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
                 $taskDescriptions = JobQueue::getTaskDescriptions();
324 324
 
325 325
                 $task = $job->getTask();
326
-                if(isset($taskDescriptions[$task])){
326
+                if (isset($taskDescriptions[$task])) {
327 327
                     $description = $taskDescriptions[$task];
328 328
                 } else {
329 329
                     $description = 'Unknown task';
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 
332 332
                 return "<a href=\"{$baseurl}/internal.php/jobQueue/view?id={$objectId}\">Job #{$job->getId()} ({$description})</a>";
333 333
             default:
334
-                return '[' . $objectType . " " . $objectId . ']';
334
+                return '['.$objectType." ".$objectId.']';
335 335
         }
336 336
     }
337 337
 
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
                     $renameData = unserialize($logEntry->getComment());
380 380
                     $oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
381 381
                     $newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
382
-                    $comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
382
+                    $comment = 'Renamed \''.$oldName.'\' to \''.$newName.'\'.';
383 383
                     break;
384 384
                 case 'RoleChange':
385 385
                     $roleChangeData = unserialize($logEntry->getComment());
@@ -396,15 +396,15 @@  discard block
 block discarded – undo
396 396
 
397 397
                     $reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
398 398
 
399
-                    $roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
400
-                    $comment = $roleDelta . ' with comment: ' . $reason;
399
+                    $roleDelta = 'Removed ['.implode(', ', $removed).'], Added ['.implode(', ', $added).']';
400
+                    $comment = $roleDelta.' with comment: '.$reason;
401 401
                     break;
402 402
                 case 'JobIssue':
403 403
                     $jobIssueData = unserialize($logEntry->getComment());
404 404
                     $errorMessage = $jobIssueData['error'];
405 405
                     $status = $jobIssueData['status'];
406 406
 
407
-                    $comment = 'Job ' . htmlentities($status, ENT_COMPAT, 'UTF-8') . ': ';
407
+                    $comment = 'Job '.htmlentities($status, ENT_COMPAT, 'UTF-8').': ';
408 408
                     $comment .= htmlentities($errorMessage, ENT_COMPAT, 'UTF-8');
409 409
                     break;
410 410
                 case 'JobIssueRequest':
Please login to merge, or discard this patch.
Braces   +3 added lines, -2 removed lines patch added patch discarded remove patch
@@ -323,9 +323,10 @@
 block discarded – undo
323 323
                 $taskDescriptions = JobQueue::getTaskDescriptions();
324 324
 
325 325
                 $task = $job->getTask();
326
-                if(isset($taskDescriptions[$task])){
326
+                if(isset($taskDescriptions[$task])) {
327 327
                     $description = $taskDescriptions[$task];
328
-                } else {
328
+                }
329
+                else {
329 330
                     $description = 'Unknown task';
330 331
                 }
331 332
 
Please login to merge, or discard this patch.
includes/Helpers/Logger.php 1 patch
Indentation   +353 added lines, -353 removed lines patch added patch discarded remove patch
@@ -31,357 +31,357 @@
 block discarded – undo
31 31
  */
32 32
 class Logger
33 33
 {
34
-    /**
35
-     * @param PdoDatabase $database
36
-     * @param Request     $object
37
-     */
38
-    public static function emailConfirmed(PdoDatabase $database, Request $object)
39
-    {
40
-        self::createLogEntry($database, $object, "Email Confirmed", null, User::getCommunity());
41
-    }
42
-
43
-    /**
44
-     * @param PdoDatabase $database
45
-     * @param DataObject  $object
46
-     * @param string      $logAction
47
-     * @param null|string $comment
48
-     * @param User        $user
49
-     *
50
-     * @throws Exception
51
-     */
52
-    private static function createLogEntry(
53
-        PdoDatabase $database,
54
-        DataObject $object,
55
-        $logAction,
56
-        $comment = null,
57
-        $user = null
58
-    ) {
59
-        if ($user == null) {
60
-            $user = User::getCurrent($database);
61
-        }
62
-
63
-        $objectType = get_class($object);
64
-        if (strpos($objectType, 'Waca\\DataObjects\\') !== false) {
65
-            $objectType = str_replace('Waca\\DataObjects\\', '', $objectType);
66
-        }
67
-
68
-        $log = new Log();
69
-        $log->setDatabase($database);
70
-        $log->setAction($logAction);
71
-        $log->setObjectId($object->getId());
72
-        $log->setObjectType($objectType);
73
-        $log->setUser($user);
74
-        $log->setComment($comment);
75
-        $log->save();
76
-    }
77
-
78
-    #region Users
79
-
80
-    /**
81
-     * @param PdoDatabase $database
82
-     * @param User        $user
83
-     */
84
-    public static function newUser(PdoDatabase $database, User $user)
85
-    {
86
-        self::createLogEntry($database, $user, 'Registered', null, User::getCommunity());
87
-    }
88
-
89
-    /**
90
-     * @param PdoDatabase $database
91
-     * @param User        $object
92
-     */
93
-    public static function approvedUser(PdoDatabase $database, User $object)
94
-    {
95
-        self::createLogEntry($database, $object, "Approved");
96
-    }
97
-
98
-    /**
99
-     * @param PdoDatabase $database
100
-     * @param User        $object
101
-     * @param string      $comment
102
-     */
103
-    public static function declinedUser(PdoDatabase $database, User $object, $comment)
104
-    {
105
-        self::createLogEntry($database, $object, "Declined", $comment);
106
-    }
107
-
108
-    /**
109
-     * @param PdoDatabase $database
110
-     * @param User        $object
111
-     * @param string      $comment
112
-     */
113
-    public static function suspendedUser(PdoDatabase $database, User $object, $comment)
114
-    {
115
-        self::createLogEntry($database, $object, "Suspended", $comment);
116
-    }
117
-
118
-    /**
119
-     * @param PdoDatabase $database
120
-     * @param User        $object
121
-     * @param string      $comment
122
-     */
123
-    public static function demotedUser(PdoDatabase $database, User $object, $comment)
124
-    {
125
-        self::createLogEntry($database, $object, "Demoted", $comment);
126
-    }
127
-
128
-    /**
129
-     * @param PdoDatabase $database
130
-     * @param User        $object
131
-     */
132
-    public static function promotedUser(PdoDatabase $database, User $object)
133
-    {
134
-        self::createLogEntry($database, $object, "Promoted");
135
-    }
136
-
137
-    /**
138
-     * @param PdoDatabase $database
139
-     * @param User        $object
140
-     * @param string      $comment
141
-     */
142
-    public static function renamedUser(PdoDatabase $database, User $object, $comment)
143
-    {
144
-        self::createLogEntry($database, $object, "Renamed", $comment);
145
-    }
146
-
147
-    /**
148
-     * @param PdoDatabase $database
149
-     * @param User        $object
150
-     */
151
-    public static function userPreferencesChange(PdoDatabase $database, User $object)
152
-    {
153
-        self::createLogEntry($database, $object, "Prefchange");
154
-    }
155
-
156
-    /**
157
-     * @param PdoDatabase $database
158
-     * @param User        $object
159
-     * @param string      $reason
160
-     * @param array       $added
161
-     * @param array       $removed
162
-     */
163
-    public static function userRolesEdited(PdoDatabase $database, User $object, $reason, $added, $removed)
164
-    {
165
-        $logData = serialize(array(
166
-            'added'   => $added,
167
-            'removed' => $removed,
168
-            'reason'  => $reason,
169
-        ));
170
-
171
-        self::createLogEntry($database, $object, "RoleChange", $logData);
172
-    }
173
-
174
-    #endregion
175
-
176
-    /**
177
-     * @param PdoDatabase $database
178
-     * @param SiteNotice  $object
179
-     */
180
-    public static function siteNoticeEdited(PdoDatabase $database, SiteNotice $object)
181
-    {
182
-        self::createLogEntry($database, $object, "Edited");
183
-    }
184
-
185
-    #region Welcome Templates
186
-
187
-    /**
188
-     * @param PdoDatabase     $database
189
-     * @param WelcomeTemplate $object
190
-     */
191
-    public static function welcomeTemplateCreated(PdoDatabase $database, WelcomeTemplate $object)
192
-    {
193
-        self::createLogEntry($database, $object, "CreatedTemplate");
194
-    }
195
-
196
-    /**
197
-     * @param PdoDatabase     $database
198
-     * @param WelcomeTemplate $object
199
-     */
200
-    public static function welcomeTemplateEdited(PdoDatabase $database, WelcomeTemplate $object)
201
-    {
202
-        self::createLogEntry($database, $object, "EditedTemplate");
203
-    }
204
-
205
-    /**
206
-     * @param PdoDatabase     $database
207
-     * @param WelcomeTemplate $object
208
-     */
209
-    public static function welcomeTemplateDeleted(PdoDatabase $database, WelcomeTemplate $object)
210
-    {
211
-        self::createLogEntry($database, $object, "DeletedTemplate");
212
-    }
213
-
214
-    #endregion
215
-
216
-    #region Bans
217
-
218
-    /**
219
-     * @param PdoDatabase $database
220
-     * @param Ban         $object
221
-     * @param string      $reason
222
-     */
223
-    public static function banned(PdoDatabase $database, Ban $object, $reason)
224
-    {
225
-        self::createLogEntry($database, $object, "Banned", $reason);
226
-    }
227
-
228
-    /**
229
-     * @param PdoDatabase $database
230
-     * @param Ban         $object
231
-     * @param string      $reason
232
-     */
233
-    public static function unbanned(PdoDatabase $database, Ban $object, $reason)
234
-    {
235
-        self::createLogEntry($database, $object, "Unbanned", $reason);
236
-    }
237
-
238
-    #endregion
239
-
240
-    #region Requests
241
-
242
-    /**
243
-     * @param PdoDatabase $database
244
-     * @param Request     $object
245
-     * @param string      $target
246
-     */
247
-    public static function deferRequest(PdoDatabase $database, Request $object, $target)
248
-    {
249
-        self::createLogEntry($database, $object, "Deferred to $target");
250
-    }
251
-
252
-    /**
253
-     * @param PdoDatabase $database
254
-     * @param Request     $object
255
-     * @param integer     $target
256
-     * @param string      $comment
257
-     * @param User|null   $logUser
258
-     */
259
-    public static function closeRequest(PdoDatabase $database, Request $object, $target, $comment, User $logUser = null)
260
-    {
261
-        self::createLogEntry($database, $object, "Closed $target", $comment, $logUser);
262
-    }
263
-
264
-    /**
265
-     * @param PdoDatabase $database
266
-     * @param Request     $object
267
-     */
268
-    public static function reserve(PdoDatabase $database, Request $object)
269
-    {
270
-        self::createLogEntry($database, $object, "Reserved");
271
-    }
272
-
273
-    /**
274
-     * @param PdoDatabase $database
275
-     * @param Request     $object
276
-     */
277
-    public static function breakReserve(PdoDatabase $database, Request $object)
278
-    {
279
-        self::createLogEntry($database, $object, "BreakReserve");
280
-    }
281
-
282
-    /**
283
-     * @param PdoDatabase $database
284
-     * @param Request     $object
285
-     */
286
-    public static function unreserve(PdoDatabase $database, Request $object)
287
-    {
288
-        self::createLogEntry($database, $object, "Unreserved");
289
-    }
290
-
291
-    /**
292
-     * @param PdoDatabase $database
293
-     * @param Comment     $object
294
-     * @param Request     $request
295
-     */
296
-    public static function editComment(PdoDatabase $database, Comment $object, Request $request)
297
-    {
298
-        self::createLogEntry($database, $request, "EditComment-r");
299
-        self::createLogEntry($database, $object, "EditComment-c");
300
-    }
301
-
302
-    /**
303
-     * @param PdoDatabase $database
304
-     * @param Request     $object
305
-     * @param User        $target
306
-     */
307
-    public static function sendReservation(PdoDatabase $database, Request $object, User $target)
308
-    {
309
-        self::createLogEntry($database, $object, "SendReserved");
310
-        self::createLogEntry($database, $object, "ReceiveReserved", null, $target);
311
-    }
312
-
313
-    /**
314
-     * @param PdoDatabase $database
315
-     * @param Request     $object
316
-     * @param string      $comment
317
-     */
318
-    public static function sentMail(PdoDatabase $database, Request $object, $comment)
319
-    {
320
-        self::createLogEntry($database, $object, "SentMail", $comment);
321
-    }
322
-
323
-    /**
324
-     * @param PdoDatabase $database
325
-     * @param Request     $object
326
-     */
327
-    public static function enqueuedJobQueue(PdoDatabase $database, Request $object)
328
-    {
329
-        self::createLogEntry($database, $object, 'EnqueuedJobQueue');
330
-    }
331
-
332
-    public static function hospitalised(PdoDatabase $database, Request $object)
333
-    {
334
-        self::createLogEntry($database, $object, 'Hospitalised');
335
-    }
336
-    #endregion
337
-
338
-    #region Email templates
339
-
340
-    /**
341
-     * @param PdoDatabase   $database
342
-     * @param EmailTemplate $object
343
-     */
344
-    public static function createEmail(PdoDatabase $database, EmailTemplate $object)
345
-    {
346
-        self::createLogEntry($database, $object, "CreatedEmail");
347
-    }
348
-
349
-    /**
350
-     * @param PdoDatabase   $database
351
-     * @param EmailTemplate $object
352
-     */
353
-    public static function editedEmail(PdoDatabase $database, EmailTemplate $object)
354
-    {
355
-        self::createLogEntry($database, $object, "EditedEmail");
356
-    }
357
-
358
-    #endregion
359
-
360
-    #region Display
361
-
362
-    #endregion
363
-
364
-    #region Automation
365
-
366
-    public static function backgroundJobComplete(PdoDatabase $database, JobQueue $job)
367
-    {
368
-        self::createLogEntry($database, $job, 'JobCompleted', null, User::getCommunity());
369
-    }
370
-
371
-    public static function backgroundJobIssue(PdoDatabase $database, JobQueue $job)
372
-    {
373
-        $data = array('status' => $job->getStatus(), 'error' => $job->getError());
374
-        self::createLogEntry($database, $job, 'JobIssue', serialize($data), User::getCommunity());
375
-    }
376
-
377
-    public static function backgroundJobRequeued(PdoDatabase $database, JobQueue $job)
378
-    {
379
-        self::createLogEntry($database, $job, 'JobRequeued');
380
-    }
381
-
382
-    public static function backgroundJobAcknowledged(PdoDatabase $database, JobQueue $job)
383
-    {
384
-        self::createLogEntry($database, $job, 'JobAcknowledged');
385
-    }
386
-    #endregion
34
+	/**
35
+	 * @param PdoDatabase $database
36
+	 * @param Request     $object
37
+	 */
38
+	public static function emailConfirmed(PdoDatabase $database, Request $object)
39
+	{
40
+		self::createLogEntry($database, $object, "Email Confirmed", null, User::getCommunity());
41
+	}
42
+
43
+	/**
44
+	 * @param PdoDatabase $database
45
+	 * @param DataObject  $object
46
+	 * @param string      $logAction
47
+	 * @param null|string $comment
48
+	 * @param User        $user
49
+	 *
50
+	 * @throws Exception
51
+	 */
52
+	private static function createLogEntry(
53
+		PdoDatabase $database,
54
+		DataObject $object,
55
+		$logAction,
56
+		$comment = null,
57
+		$user = null
58
+	) {
59
+		if ($user == null) {
60
+			$user = User::getCurrent($database);
61
+		}
62
+
63
+		$objectType = get_class($object);
64
+		if (strpos($objectType, 'Waca\\DataObjects\\') !== false) {
65
+			$objectType = str_replace('Waca\\DataObjects\\', '', $objectType);
66
+		}
67
+
68
+		$log = new Log();
69
+		$log->setDatabase($database);
70
+		$log->setAction($logAction);
71
+		$log->setObjectId($object->getId());
72
+		$log->setObjectType($objectType);
73
+		$log->setUser($user);
74
+		$log->setComment($comment);
75
+		$log->save();
76
+	}
77
+
78
+	#region Users
79
+
80
+	/**
81
+	 * @param PdoDatabase $database
82
+	 * @param User        $user
83
+	 */
84
+	public static function newUser(PdoDatabase $database, User $user)
85
+	{
86
+		self::createLogEntry($database, $user, 'Registered', null, User::getCommunity());
87
+	}
88
+
89
+	/**
90
+	 * @param PdoDatabase $database
91
+	 * @param User        $object
92
+	 */
93
+	public static function approvedUser(PdoDatabase $database, User $object)
94
+	{
95
+		self::createLogEntry($database, $object, "Approved");
96
+	}
97
+
98
+	/**
99
+	 * @param PdoDatabase $database
100
+	 * @param User        $object
101
+	 * @param string      $comment
102
+	 */
103
+	public static function declinedUser(PdoDatabase $database, User $object, $comment)
104
+	{
105
+		self::createLogEntry($database, $object, "Declined", $comment);
106
+	}
107
+
108
+	/**
109
+	 * @param PdoDatabase $database
110
+	 * @param User        $object
111
+	 * @param string      $comment
112
+	 */
113
+	public static function suspendedUser(PdoDatabase $database, User $object, $comment)
114
+	{
115
+		self::createLogEntry($database, $object, "Suspended", $comment);
116
+	}
117
+
118
+	/**
119
+	 * @param PdoDatabase $database
120
+	 * @param User        $object
121
+	 * @param string      $comment
122
+	 */
123
+	public static function demotedUser(PdoDatabase $database, User $object, $comment)
124
+	{
125
+		self::createLogEntry($database, $object, "Demoted", $comment);
126
+	}
127
+
128
+	/**
129
+	 * @param PdoDatabase $database
130
+	 * @param User        $object
131
+	 */
132
+	public static function promotedUser(PdoDatabase $database, User $object)
133
+	{
134
+		self::createLogEntry($database, $object, "Promoted");
135
+	}
136
+
137
+	/**
138
+	 * @param PdoDatabase $database
139
+	 * @param User        $object
140
+	 * @param string      $comment
141
+	 */
142
+	public static function renamedUser(PdoDatabase $database, User $object, $comment)
143
+	{
144
+		self::createLogEntry($database, $object, "Renamed", $comment);
145
+	}
146
+
147
+	/**
148
+	 * @param PdoDatabase $database
149
+	 * @param User        $object
150
+	 */
151
+	public static function userPreferencesChange(PdoDatabase $database, User $object)
152
+	{
153
+		self::createLogEntry($database, $object, "Prefchange");
154
+	}
155
+
156
+	/**
157
+	 * @param PdoDatabase $database
158
+	 * @param User        $object
159
+	 * @param string      $reason
160
+	 * @param array       $added
161
+	 * @param array       $removed
162
+	 */
163
+	public static function userRolesEdited(PdoDatabase $database, User $object, $reason, $added, $removed)
164
+	{
165
+		$logData = serialize(array(
166
+			'added'   => $added,
167
+			'removed' => $removed,
168
+			'reason'  => $reason,
169
+		));
170
+
171
+		self::createLogEntry($database, $object, "RoleChange", $logData);
172
+	}
173
+
174
+	#endregion
175
+
176
+	/**
177
+	 * @param PdoDatabase $database
178
+	 * @param SiteNotice  $object
179
+	 */
180
+	public static function siteNoticeEdited(PdoDatabase $database, SiteNotice $object)
181
+	{
182
+		self::createLogEntry($database, $object, "Edited");
183
+	}
184
+
185
+	#region Welcome Templates
186
+
187
+	/**
188
+	 * @param PdoDatabase     $database
189
+	 * @param WelcomeTemplate $object
190
+	 */
191
+	public static function welcomeTemplateCreated(PdoDatabase $database, WelcomeTemplate $object)
192
+	{
193
+		self::createLogEntry($database, $object, "CreatedTemplate");
194
+	}
195
+
196
+	/**
197
+	 * @param PdoDatabase     $database
198
+	 * @param WelcomeTemplate $object
199
+	 */
200
+	public static function welcomeTemplateEdited(PdoDatabase $database, WelcomeTemplate $object)
201
+	{
202
+		self::createLogEntry($database, $object, "EditedTemplate");
203
+	}
204
+
205
+	/**
206
+	 * @param PdoDatabase     $database
207
+	 * @param WelcomeTemplate $object
208
+	 */
209
+	public static function welcomeTemplateDeleted(PdoDatabase $database, WelcomeTemplate $object)
210
+	{
211
+		self::createLogEntry($database, $object, "DeletedTemplate");
212
+	}
213
+
214
+	#endregion
215
+
216
+	#region Bans
217
+
218
+	/**
219
+	 * @param PdoDatabase $database
220
+	 * @param Ban         $object
221
+	 * @param string      $reason
222
+	 */
223
+	public static function banned(PdoDatabase $database, Ban $object, $reason)
224
+	{
225
+		self::createLogEntry($database, $object, "Banned", $reason);
226
+	}
227
+
228
+	/**
229
+	 * @param PdoDatabase $database
230
+	 * @param Ban         $object
231
+	 * @param string      $reason
232
+	 */
233
+	public static function unbanned(PdoDatabase $database, Ban $object, $reason)
234
+	{
235
+		self::createLogEntry($database, $object, "Unbanned", $reason);
236
+	}
237
+
238
+	#endregion
239
+
240
+	#region Requests
241
+
242
+	/**
243
+	 * @param PdoDatabase $database
244
+	 * @param Request     $object
245
+	 * @param string      $target
246
+	 */
247
+	public static function deferRequest(PdoDatabase $database, Request $object, $target)
248
+	{
249
+		self::createLogEntry($database, $object, "Deferred to $target");
250
+	}
251
+
252
+	/**
253
+	 * @param PdoDatabase $database
254
+	 * @param Request     $object
255
+	 * @param integer     $target
256
+	 * @param string      $comment
257
+	 * @param User|null   $logUser
258
+	 */
259
+	public static function closeRequest(PdoDatabase $database, Request $object, $target, $comment, User $logUser = null)
260
+	{
261
+		self::createLogEntry($database, $object, "Closed $target", $comment, $logUser);
262
+	}
263
+
264
+	/**
265
+	 * @param PdoDatabase $database
266
+	 * @param Request     $object
267
+	 */
268
+	public static function reserve(PdoDatabase $database, Request $object)
269
+	{
270
+		self::createLogEntry($database, $object, "Reserved");
271
+	}
272
+
273
+	/**
274
+	 * @param PdoDatabase $database
275
+	 * @param Request     $object
276
+	 */
277
+	public static function breakReserve(PdoDatabase $database, Request $object)
278
+	{
279
+		self::createLogEntry($database, $object, "BreakReserve");
280
+	}
281
+
282
+	/**
283
+	 * @param PdoDatabase $database
284
+	 * @param Request     $object
285
+	 */
286
+	public static function unreserve(PdoDatabase $database, Request $object)
287
+	{
288
+		self::createLogEntry($database, $object, "Unreserved");
289
+	}
290
+
291
+	/**
292
+	 * @param PdoDatabase $database
293
+	 * @param Comment     $object
294
+	 * @param Request     $request
295
+	 */
296
+	public static function editComment(PdoDatabase $database, Comment $object, Request $request)
297
+	{
298
+		self::createLogEntry($database, $request, "EditComment-r");
299
+		self::createLogEntry($database, $object, "EditComment-c");
300
+	}
301
+
302
+	/**
303
+	 * @param PdoDatabase $database
304
+	 * @param Request     $object
305
+	 * @param User        $target
306
+	 */
307
+	public static function sendReservation(PdoDatabase $database, Request $object, User $target)
308
+	{
309
+		self::createLogEntry($database, $object, "SendReserved");
310
+		self::createLogEntry($database, $object, "ReceiveReserved", null, $target);
311
+	}
312
+
313
+	/**
314
+	 * @param PdoDatabase $database
315
+	 * @param Request     $object
316
+	 * @param string      $comment
317
+	 */
318
+	public static function sentMail(PdoDatabase $database, Request $object, $comment)
319
+	{
320
+		self::createLogEntry($database, $object, "SentMail", $comment);
321
+	}
322
+
323
+	/**
324
+	 * @param PdoDatabase $database
325
+	 * @param Request     $object
326
+	 */
327
+	public static function enqueuedJobQueue(PdoDatabase $database, Request $object)
328
+	{
329
+		self::createLogEntry($database, $object, 'EnqueuedJobQueue');
330
+	}
331
+
332
+	public static function hospitalised(PdoDatabase $database, Request $object)
333
+	{
334
+		self::createLogEntry($database, $object, 'Hospitalised');
335
+	}
336
+	#endregion
337
+
338
+	#region Email templates
339
+
340
+	/**
341
+	 * @param PdoDatabase   $database
342
+	 * @param EmailTemplate $object
343
+	 */
344
+	public static function createEmail(PdoDatabase $database, EmailTemplate $object)
345
+	{
346
+		self::createLogEntry($database, $object, "CreatedEmail");
347
+	}
348
+
349
+	/**
350
+	 * @param PdoDatabase   $database
351
+	 * @param EmailTemplate $object
352
+	 */
353
+	public static function editedEmail(PdoDatabase $database, EmailTemplate $object)
354
+	{
355
+		self::createLogEntry($database, $object, "EditedEmail");
356
+	}
357
+
358
+	#endregion
359
+
360
+	#region Display
361
+
362
+	#endregion
363
+
364
+	#region Automation
365
+
366
+	public static function backgroundJobComplete(PdoDatabase $database, JobQueue $job)
367
+	{
368
+		self::createLogEntry($database, $job, 'JobCompleted', null, User::getCommunity());
369
+	}
370
+
371
+	public static function backgroundJobIssue(PdoDatabase $database, JobQueue $job)
372
+	{
373
+		$data = array('status' => $job->getStatus(), 'error' => $job->getError());
374
+		self::createLogEntry($database, $job, 'JobIssue', serialize($data), User::getCommunity());
375
+	}
376
+
377
+	public static function backgroundJobRequeued(PdoDatabase $database, JobQueue $job)
378
+	{
379
+		self::createLogEntry($database, $job, 'JobRequeued');
380
+	}
381
+
382
+	public static function backgroundJobAcknowledged(PdoDatabase $database, JobQueue $job)
383
+	{
384
+		self::createLogEntry($database, $job, 'JobAcknowledged');
385
+	}
386
+	#endregion
387 387
 }
Please login to merge, or discard this patch.