Failed Conditions
Pull Request — newinternal-bugfixing (#286)
by Simon
06:57 queued 03:32
created
includes/Fragments/TemplateOutput.php 1 patch
Indentation   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -15,88 +15,88 @@
 block discarded – undo
15 15
 
16 16
 trait TemplateOutput
17 17
 {
18
-    /** @var Smarty */
19
-    private $smarty;
20
-    /** @var string Extra JavaScript to include at the end of the page's execution */
21
-    private $tailScript;
18
+	/** @var Smarty */
19
+	private $smarty;
20
+	/** @var string Extra JavaScript to include at the end of the page's execution */
21
+	private $tailScript;
22 22
 
23
-    /**
24
-     * @return SiteConfiguration
25
-     */
26
-    protected abstract function getSiteConfiguration();
23
+	/**
24
+	 * @return SiteConfiguration
25
+	 */
26
+	protected abstract function getSiteConfiguration();
27 27
 
28
-    /**
29
-     * Include extra JavaScript at the end of the page's execution
30
-     *
31
-     * @param $script string JavaScript to include at the end of the page
32
-     */
33
-    final protected function setTailScript($script)
34
-    {
35
-        $this->tailScript = $script;
36
-    }
28
+	/**
29
+	 * Include extra JavaScript at the end of the page's execution
30
+	 *
31
+	 * @param $script string JavaScript to include at the end of the page
32
+	 */
33
+	final protected function setTailScript($script)
34
+	{
35
+		$this->tailScript = $script;
36
+	}
37 37
 
38
-    /**
39
-     * Assigns a Smarty variable
40
-     *
41
-     * @param  array|string $name  the template variable name(s)
42
-     * @param  mixed        $value the value to assign
43
-     */
44
-    final protected function assign($name, $value)
45
-    {
46
-        $this->smarty->assign($name, $value);
47
-    }
38
+	/**
39
+	 * Assigns a Smarty variable
40
+	 *
41
+	 * @param  array|string $name  the template variable name(s)
42
+	 * @param  mixed        $value the value to assign
43
+	 */
44
+	final protected function assign($name, $value)
45
+	{
46
+		$this->smarty->assign($name, $value);
47
+	}
48 48
 
49
-    /**
50
-     * Sets up the variables used by the main Smarty base template.
51
-     *
52
-     * This list is getting kinda long.
53
-     */
54
-    final protected function setUpSmarty()
55
-    {
56
-        $this->smarty = new Smarty();
57
-        $this->smarty->addPluginsDir($this->getSiteConfiguration()->getFilePath() . '/smarty-plugins');
49
+	/**
50
+	 * Sets up the variables used by the main Smarty base template.
51
+	 *
52
+	 * This list is getting kinda long.
53
+	 */
54
+	final protected function setUpSmarty()
55
+	{
56
+		$this->smarty = new Smarty();
57
+		$this->smarty->addPluginsDir($this->getSiteConfiguration()->getFilePath() . '/smarty-plugins');
58 58
 
59
-        $this->assign('currentUser', User::getCommunity());
60
-        $this->assign('loggedIn', false);
61
-        $this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
62
-        $this->assign('mediawikiScriptPath', $this->getSiteConfiguration()->getMediawikiScriptPath());
59
+		$this->assign('currentUser', User::getCommunity());
60
+		$this->assign('loggedIn', false);
61
+		$this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
62
+		$this->assign('mediawikiScriptPath', $this->getSiteConfiguration()->getMediawikiScriptPath());
63 63
 
64
-        $this->assign('siteNoticeText', '');
65
-        $this->assign('toolversion', Environment::getToolVersion());
64
+		$this->assign('siteNoticeText', '');
65
+		$this->assign('toolversion', Environment::getToolVersion());
66 66
 
67
-        // default these
68
-        $this->assign('onlineusers', array());
69
-        $this->assign('typeAheadBlock', '');
70
-        $this->assign('extraJs', array());
71
-        $this->assign('extraCss', array());
67
+		// default these
68
+		$this->assign('onlineusers', array());
69
+		$this->assign('typeAheadBlock', '');
70
+		$this->assign('extraJs', array());
71
+		$this->assign('extraCss', array());
72 72
 
73
-        // nav menu access control
74
-        $this->assign('nav__canRequests', false);
75
-        $this->assign('nav__canLogs', false);
76
-        $this->assign('nav__canUsers', false);
77
-        $this->assign('nav__canSearch', false);
78
-        $this->assign('nav__canStats', false);
79
-        $this->assign('nav__canBan', false);
80
-        $this->assign('nav__canEmailMgmt', false);
81
-        $this->assign('nav__canWelcomeMgmt', false);
82
-        $this->assign('nav__canSiteNoticeMgmt', false);
83
-        $this->assign('nav__canUserMgmt', false);
84
-        $this->assign('nav__canViewRequest', false);
73
+		// nav menu access control
74
+		$this->assign('nav__canRequests', false);
75
+		$this->assign('nav__canLogs', false);
76
+		$this->assign('nav__canUsers', false);
77
+		$this->assign('nav__canSearch', false);
78
+		$this->assign('nav__canStats', false);
79
+		$this->assign('nav__canBan', false);
80
+		$this->assign('nav__canEmailMgmt', false);
81
+		$this->assign('nav__canWelcomeMgmt', false);
82
+		$this->assign('nav__canSiteNoticeMgmt', false);
83
+		$this->assign('nav__canUserMgmt', false);
84
+		$this->assign('nav__canViewRequest', false);
85 85
 
86
-        $this->assign('page', $this);
87
-    }
86
+		$this->assign('page', $this);
87
+	}
88 88
 
89
-    /**
90
-     * Fetches a rendered Smarty template
91
-     *
92
-     * @param $template string Template file path, relative to /templates/
93
-     *
94
-     * @return string Templated HTML
95
-     */
96
-    final protected function fetchTemplate($template)
97
-    {
98
-        $this->assign("tailScript", $this->tailScript);
89
+	/**
90
+	 * Fetches a rendered Smarty template
91
+	 *
92
+	 * @param $template string Template file path, relative to /templates/
93
+	 *
94
+	 * @return string Templated HTML
95
+	 */
96
+	final protected function fetchTemplate($template)
97
+	{
98
+		$this->assign("tailScript", $this->tailScript);
99 99
 
100
-        return $this->smarty->fetch($template);
101
-    }
100
+		return $this->smarty->fetch($template);
101
+	}
102 102
 }
Please login to merge, or discard this patch.
includes/Fragments/RequestData.php 1 patch
Indentation   +318 added lines, -318 removed lines patch added patch discarded remove patch
@@ -23,322 +23,322 @@
 block discarded – undo
23 23
 
24 24
 trait RequestData
25 25
 {
26
-    /**
27
-     * @var array Array of IP address classed as 'private' by RFC1918.
28
-     */
29
-    protected static $rfc1918ips = array(
30
-        "10.0.0.0"    => "10.255.255.255",
31
-        "172.16.0.0"  => "172.31.255.255",
32
-        "192.168.0.0" => "192.168.255.255",
33
-        "169.254.0.0" => "169.254.255.255",
34
-        "127.0.0.0"   => "127.255.255.255",
35
-    );
36
-
37
-    /**
38
-     * Gets a request object
39
-     *
40
-     * @param PdoDatabase $database  The database connection
41
-     * @param int         $requestId The ID of the request to retrieve
42
-     *
43
-     * @return Request
44
-     * @throws ApplicationLogicException
45
-     */
46
-    protected function getRequest(PdoDatabase $database, $requestId)
47
-    {
48
-        if ($requestId === null) {
49
-            throw new ApplicationLogicException("No request specified");
50
-        }
51
-
52
-        $request = Request::getById($requestId, $database);
53
-        if ($request === false || !is_a($request, Request::class)) {
54
-            throw new ApplicationLogicException('Could not load the requested request!');
55
-        }
56
-
57
-        return $request;
58
-    }
59
-
60
-    /**
61
-     * Returns a value stating whether the user is allowed to see private data or not
62
-     *
63
-     * @param Request $request
64
-     * @param User    $currentUser
65
-     *
66
-     * @return bool
67
-     * @category Security-Critical
68
-     */
69
-    protected function isAllowedPrivateData(Request $request, User $currentUser)
70
-    {
71
-        // Test the main security barrier for private data access using SecurityManager
72
-        if ($this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')) {
73
-            // Tool admins/check-users can always see private data
74
-            return true;
75
-        }
76
-
77
-        // reserving user is allowed to see the data
78
-        if ($currentUser->getId() === $request->getReserved()
79
-            && $request->getReserved() !== null
80
-            && $this->barrierTest('seePrivateDataWhenReserved', $currentUser, 'RequestData')
81
-        ) {
82
-            return true;
83
-        }
84
-
85
-        // user has the reveal hash
86
-        if (WebRequest::getString('hash') === $request->getRevealHash()
87
-            && $this->barrierTest('seePrivateDataWithHash', $currentUser, 'RequestData')
88
-        ) {
89
-            return true;
90
-        }
91
-
92
-        // nope. Not allowed.
93
-        return false;
94
-    }
95
-
96
-    /**
97
-     * Tests the security barrier for a specified action.
98
-     *
99
-     * Don't use within templates
100
-     *
101
-     * @param string      $action
102
-     *
103
-     * @param User        $user
104
-     * @param null|string $pageName
105
-     *
106
-     * @return bool
107
-     * @category Security-Critical
108
-     */
109
-    abstract protected function barrierTest($action, User $user, $pageName = null);
110
-
111
-    /**
112
-     * Gets the name of the route that has been passed from the request router.
113
-     * @return string
114
-     */
115
-    abstract protected function getRouteName();
116
-
117
-    /** @return SecurityManager */
118
-    abstract protected function getSecurityManager();
119
-
120
-    /**
121
-     * Sets the name of the template this page should display.
122
-     *
123
-     * @param string $name
124
-     */
125
-    abstract protected function setTemplate($name);
126
-
127
-    /** @return IXffTrustProvider */
128
-    abstract protected function getXffTrustProvider();
129
-
130
-    /** @return ILocationProvider */
131
-    abstract protected function getLocationProvider();
132
-
133
-    /** @return IRDnsProvider */
134
-    abstract protected function getRdnsProvider();
135
-
136
-    /**
137
-     * Assigns a Smarty variable
138
-     *
139
-     * @param  array|string $name  the template variable name(s)
140
-     * @param  mixed        $value the value to assign
141
-     */
142
-    abstract protected function assign($name, $value);
143
-
144
-    /**
145
-     * @param int         $requestReservationId
146
-     * @param PdoDatabase $database
147
-     * @param User        $currentUser
148
-     */
149
-    protected function setupReservationDetails($requestReservationId, PdoDatabase $database, User $currentUser)
150
-    {
151
-        $requestIsReserved = $requestReservationId !== null;
152
-        $this->assign('requestIsReserved', $requestIsReserved);
153
-        $this->assign('requestIsReservedByMe', false);
154
-
155
-        if ($requestIsReserved) {
156
-            $this->assign('requestReservedByName', User::getById($requestReservationId, $database)->getUsername());
157
-            $this->assign('requestReservedById', $requestReservationId);
158
-
159
-            if ($requestReservationId === $currentUser->getId()) {
160
-                $this->assign('requestIsReservedByMe', true);
161
-            }
162
-        }
163
-
164
-        $this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
165
-    }
166
-
167
-    /**
168
-     * Adds private request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
169
-     *
170
-     * @param Request           $request
171
-     * @param User              $currentUser
172
-     * @param SiteConfiguration $configuration
173
-     *
174
-     * @param PdoDatabase       $database
175
-     */
176
-    protected function setupPrivateData(
177
-        $request,
178
-        User $currentUser,
179
-        SiteConfiguration $configuration,
180
-        PdoDatabase $database
181
-    ) {
182
-        $xffProvider = $this->getXffTrustProvider();
183
-
184
-        $relatedEmailRequests = RequestSearchHelper::get($database)
185
-            ->byEmailAddress($request->getEmail())
186
-            ->withConfirmedEmail()
187
-            ->excludingPurgedData($configuration)
188
-            ->excludingRequest($request->getId())
189
-            ->fetch();
190
-
191
-        $this->assign('requestEmail', $request->getEmail());
192
-        $emailDomain = explode("@", $request->getEmail())[1];
193
-        $this->assign("emailurl", $emailDomain);
194
-        $this->assign('requestRelatedEmailRequestsCount', count($relatedEmailRequests));
195
-        $this->assign('requestRelatedEmailRequests', $relatedEmailRequests);
196
-
197
-        $trustedIp = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
198
-        $this->assign('requestTrustedIp', $trustedIp);
199
-        $this->assign('requestRealIp', $request->getIp());
200
-        $this->assign('requestForwardedIp', $request->getForwardedIp());
201
-
202
-        $trustedIpLocation = $this->getLocationProvider()->getIpLocation($trustedIp);
203
-        $this->assign('requestTrustedIpLocation', $trustedIpLocation);
204
-
205
-        $this->assign('requestHasForwardedIp', $request->getForwardedIp() !== null);
206
-
207
-        $relatedIpRequests = RequestSearchHelper::get($database)
208
-            ->byIp($trustedIp)
209
-            ->withConfirmedEmail()
210
-            ->excludingPurgedData($configuration)
211
-            ->excludingRequest($request->getId())
212
-            ->fetch();
213
-
214
-        $this->assign('requestRelatedIpRequestsCount', count($relatedIpRequests));
215
-        $this->assign('requestRelatedIpRequests', $relatedIpRequests);
216
-
217
-        $this->assign('showRevealLink', false);
218
-        if ($request->getReserved() === $currentUser->getId() ||
219
-            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
220
-        ) {
221
-            $this->assign('showRevealLink', true);
222
-            $this->assign('revealHash', $request->getRevealHash());
223
-        }
224
-
225
-        $this->setupForwardedIpData($request);
226
-    }
227
-
228
-    /**
229
-     * Adds checkuser request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
230
-     *
231
-     * @param Request $request
232
-     */
233
-    protected function setupCheckUserData(Request $request)
234
-    {
235
-        $this->assign('requestUserAgent', $request->getUserAgent());
236
-    }
237
-
238
-    /**
239
-     * Sets up the basic data for this request, and adds it to Smarty
240
-     *
241
-     * @param Request           $request
242
-     * @param SiteConfiguration $config
243
-     */
244
-    protected function setupBasicData(Request $request, SiteConfiguration $config)
245
-    {
246
-        $this->assign('requestId', $request->getId());
247
-        $this->assign('updateVersion', $request->getUpdateVersion());
248
-        $this->assign('requestName', $request->getName());
249
-        $this->assign('requestDate', $request->getDate());
250
-        $this->assign('requestStatus', $request->getStatus());
251
-
252
-        $this->assign('requestIsClosed', !array_key_exists($request->getStatus(), $config->getRequestStates()));
253
-    }
254
-
255
-    /**
256
-     * Sets up the forwarded IP data for this request and adds it to Smarty
257
-     *
258
-     * @param Request $request
259
-     */
260
-    protected function setupForwardedIpData(Request $request)
261
-    {
262
-        if ($request->getForwardedIp() !== null) {
263
-            $requestProxyData = array(); // Initialize array to store data to be output in Smarty template.
264
-            $proxyIndex = 0;
265
-
266
-            // Assuming [client] <=> [proxy1] <=> [proxy2] <=> [proxy3] <=> [us], we will see an XFF header of [client],
267
-            // [proxy1], [proxy2], and our actual IP will be [proxy3]
268
-            $proxies = explode(",", $request->getForwardedIp());
269
-            $proxies[] = $request->getIp();
270
-
271
-            // Origin is the supposed "client" IP.
272
-            $origin = $proxies[0];
273
-            $this->assign("forwardedOrigin", $origin);
274
-
275
-            // We step through the servers in reverse order, from closest to furthest
276
-            $proxies = array_reverse($proxies);
277
-
278
-            // By default, we have trust, because the first in the chain is now REMOTE_ADDR, which is hardest to spoof.
279
-            $trust = true;
280
-
281
-            /**
282
-             * @var int    $index     The zero-based index of the proxy.
283
-             * @var string $proxyData The proxy IP address (although possibly not!)
284
-             */
285
-            foreach ($proxies as $index => $proxyData) {
286
-                $proxyAddress = trim($proxyData);
287
-                $requestProxyData[$proxyIndex]['ip'] = $proxyAddress;
288
-
289
-                // get data on this IP.
290
-                $thisProxyIsTrusted = $this->getXffTrustProvider()->isTrusted($proxyAddress);
291
-
292
-                $proxyIsInPrivateRange = $this->getXffTrustProvider()
293
-                    ->ipInRange(self::$rfc1918ips, $proxyAddress);
294
-
295
-                if (!$proxyIsInPrivateRange) {
296
-                    $proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
297
-                    $proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
298
-                }
299
-                else {
300
-                    // this is going to fail, so why bother trying?
301
-                    $proxyReverseDns = false;
302
-                    $proxyLocation = false;
303
-                }
304
-
305
-                // current trust chain status BEFORE this link
306
-                $preLinkTrust = $trust;
307
-
308
-                // is *this* link trusted? Note, this will be true even if there is an untrusted link before this!
309
-                $requestProxyData[$proxyIndex]['trustedlink'] = $thisProxyIsTrusted;
310
-
311
-                // set the trust status of the chain to this point
312
-                $trust = $trust & $thisProxyIsTrusted;
313
-
314
-                // If this is the origin address, and the chain was trusted before this point, then we can trust
315
-                // the origin.
316
-                if ($preLinkTrust && $proxyAddress == $origin) {
317
-                    // if this is the origin, then we are at the last point in the chain.
318
-                    // @todo: this is probably the cause of some bugs when an IP appears twice - we're missing a check
319
-                    // to see if this is *really* the last in the chain, rather than just the same IP as it.
320
-                    $trust = true;
321
-                }
322
-
323
-                $requestProxyData[$proxyIndex]['trust'] = $trust;
324
-
325
-                $requestProxyData[$proxyIndex]['rdnsfailed'] = $proxyReverseDns === false;
326
-                $requestProxyData[$proxyIndex]['rdns'] = $proxyReverseDns;
327
-                $requestProxyData[$proxyIndex]['routable'] = !$proxyIsInPrivateRange;
328
-
329
-                $requestProxyData[$proxyIndex]['location'] = $proxyLocation;
330
-
331
-                if ($proxyReverseDns === $proxyAddress && $proxyIsInPrivateRange === false) {
332
-                    $requestProxyData[$proxyIndex]['rdns'] = null;
333
-                }
334
-
335
-                $showLinks = (!$trust || $proxyAddress == $origin) && !$proxyIsInPrivateRange;
336
-                $requestProxyData[$proxyIndex]['showlinks'] = $showLinks;
337
-
338
-                $proxyIndex++;
339
-            }
340
-
341
-            $this->assign("requestProxyData", $requestProxyData);
342
-        }
343
-    }
26
+	/**
27
+	 * @var array Array of IP address classed as 'private' by RFC1918.
28
+	 */
29
+	protected static $rfc1918ips = array(
30
+		"10.0.0.0"    => "10.255.255.255",
31
+		"172.16.0.0"  => "172.31.255.255",
32
+		"192.168.0.0" => "192.168.255.255",
33
+		"169.254.0.0" => "169.254.255.255",
34
+		"127.0.0.0"   => "127.255.255.255",
35
+	);
36
+
37
+	/**
38
+	 * Gets a request object
39
+	 *
40
+	 * @param PdoDatabase $database  The database connection
41
+	 * @param int         $requestId The ID of the request to retrieve
42
+	 *
43
+	 * @return Request
44
+	 * @throws ApplicationLogicException
45
+	 */
46
+	protected function getRequest(PdoDatabase $database, $requestId)
47
+	{
48
+		if ($requestId === null) {
49
+			throw new ApplicationLogicException("No request specified");
50
+		}
51
+
52
+		$request = Request::getById($requestId, $database);
53
+		if ($request === false || !is_a($request, Request::class)) {
54
+			throw new ApplicationLogicException('Could not load the requested request!');
55
+		}
56
+
57
+		return $request;
58
+	}
59
+
60
+	/**
61
+	 * Returns a value stating whether the user is allowed to see private data or not
62
+	 *
63
+	 * @param Request $request
64
+	 * @param User    $currentUser
65
+	 *
66
+	 * @return bool
67
+	 * @category Security-Critical
68
+	 */
69
+	protected function isAllowedPrivateData(Request $request, User $currentUser)
70
+	{
71
+		// Test the main security barrier for private data access using SecurityManager
72
+		if ($this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')) {
73
+			// Tool admins/check-users can always see private data
74
+			return true;
75
+		}
76
+
77
+		// reserving user is allowed to see the data
78
+		if ($currentUser->getId() === $request->getReserved()
79
+			&& $request->getReserved() !== null
80
+			&& $this->barrierTest('seePrivateDataWhenReserved', $currentUser, 'RequestData')
81
+		) {
82
+			return true;
83
+		}
84
+
85
+		// user has the reveal hash
86
+		if (WebRequest::getString('hash') === $request->getRevealHash()
87
+			&& $this->barrierTest('seePrivateDataWithHash', $currentUser, 'RequestData')
88
+		) {
89
+			return true;
90
+		}
91
+
92
+		// nope. Not allowed.
93
+		return false;
94
+	}
95
+
96
+	/**
97
+	 * Tests the security barrier for a specified action.
98
+	 *
99
+	 * Don't use within templates
100
+	 *
101
+	 * @param string      $action
102
+	 *
103
+	 * @param User        $user
104
+	 * @param null|string $pageName
105
+	 *
106
+	 * @return bool
107
+	 * @category Security-Critical
108
+	 */
109
+	abstract protected function barrierTest($action, User $user, $pageName = null);
110
+
111
+	/**
112
+	 * Gets the name of the route that has been passed from the request router.
113
+	 * @return string
114
+	 */
115
+	abstract protected function getRouteName();
116
+
117
+	/** @return SecurityManager */
118
+	abstract protected function getSecurityManager();
119
+
120
+	/**
121
+	 * Sets the name of the template this page should display.
122
+	 *
123
+	 * @param string $name
124
+	 */
125
+	abstract protected function setTemplate($name);
126
+
127
+	/** @return IXffTrustProvider */
128
+	abstract protected function getXffTrustProvider();
129
+
130
+	/** @return ILocationProvider */
131
+	abstract protected function getLocationProvider();
132
+
133
+	/** @return IRDnsProvider */
134
+	abstract protected function getRdnsProvider();
135
+
136
+	/**
137
+	 * Assigns a Smarty variable
138
+	 *
139
+	 * @param  array|string $name  the template variable name(s)
140
+	 * @param  mixed        $value the value to assign
141
+	 */
142
+	abstract protected function assign($name, $value);
143
+
144
+	/**
145
+	 * @param int         $requestReservationId
146
+	 * @param PdoDatabase $database
147
+	 * @param User        $currentUser
148
+	 */
149
+	protected function setupReservationDetails($requestReservationId, PdoDatabase $database, User $currentUser)
150
+	{
151
+		$requestIsReserved = $requestReservationId !== null;
152
+		$this->assign('requestIsReserved', $requestIsReserved);
153
+		$this->assign('requestIsReservedByMe', false);
154
+
155
+		if ($requestIsReserved) {
156
+			$this->assign('requestReservedByName', User::getById($requestReservationId, $database)->getUsername());
157
+			$this->assign('requestReservedById', $requestReservationId);
158
+
159
+			if ($requestReservationId === $currentUser->getId()) {
160
+				$this->assign('requestIsReservedByMe', true);
161
+			}
162
+		}
163
+
164
+		$this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
165
+	}
166
+
167
+	/**
168
+	 * Adds private request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
169
+	 *
170
+	 * @param Request           $request
171
+	 * @param User              $currentUser
172
+	 * @param SiteConfiguration $configuration
173
+	 *
174
+	 * @param PdoDatabase       $database
175
+	 */
176
+	protected function setupPrivateData(
177
+		$request,
178
+		User $currentUser,
179
+		SiteConfiguration $configuration,
180
+		PdoDatabase $database
181
+	) {
182
+		$xffProvider = $this->getXffTrustProvider();
183
+
184
+		$relatedEmailRequests = RequestSearchHelper::get($database)
185
+			->byEmailAddress($request->getEmail())
186
+			->withConfirmedEmail()
187
+			->excludingPurgedData($configuration)
188
+			->excludingRequest($request->getId())
189
+			->fetch();
190
+
191
+		$this->assign('requestEmail', $request->getEmail());
192
+		$emailDomain = explode("@", $request->getEmail())[1];
193
+		$this->assign("emailurl", $emailDomain);
194
+		$this->assign('requestRelatedEmailRequestsCount', count($relatedEmailRequests));
195
+		$this->assign('requestRelatedEmailRequests', $relatedEmailRequests);
196
+
197
+		$trustedIp = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
198
+		$this->assign('requestTrustedIp', $trustedIp);
199
+		$this->assign('requestRealIp', $request->getIp());
200
+		$this->assign('requestForwardedIp', $request->getForwardedIp());
201
+
202
+		$trustedIpLocation = $this->getLocationProvider()->getIpLocation($trustedIp);
203
+		$this->assign('requestTrustedIpLocation', $trustedIpLocation);
204
+
205
+		$this->assign('requestHasForwardedIp', $request->getForwardedIp() !== null);
206
+
207
+		$relatedIpRequests = RequestSearchHelper::get($database)
208
+			->byIp($trustedIp)
209
+			->withConfirmedEmail()
210
+			->excludingPurgedData($configuration)
211
+			->excludingRequest($request->getId())
212
+			->fetch();
213
+
214
+		$this->assign('requestRelatedIpRequestsCount', count($relatedIpRequests));
215
+		$this->assign('requestRelatedIpRequests', $relatedIpRequests);
216
+
217
+		$this->assign('showRevealLink', false);
218
+		if ($request->getReserved() === $currentUser->getId() ||
219
+			$this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
220
+		) {
221
+			$this->assign('showRevealLink', true);
222
+			$this->assign('revealHash', $request->getRevealHash());
223
+		}
224
+
225
+		$this->setupForwardedIpData($request);
226
+	}
227
+
228
+	/**
229
+	 * Adds checkuser request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
230
+	 *
231
+	 * @param Request $request
232
+	 */
233
+	protected function setupCheckUserData(Request $request)
234
+	{
235
+		$this->assign('requestUserAgent', $request->getUserAgent());
236
+	}
237
+
238
+	/**
239
+	 * Sets up the basic data for this request, and adds it to Smarty
240
+	 *
241
+	 * @param Request           $request
242
+	 * @param SiteConfiguration $config
243
+	 */
244
+	protected function setupBasicData(Request $request, SiteConfiguration $config)
245
+	{
246
+		$this->assign('requestId', $request->getId());
247
+		$this->assign('updateVersion', $request->getUpdateVersion());
248
+		$this->assign('requestName', $request->getName());
249
+		$this->assign('requestDate', $request->getDate());
250
+		$this->assign('requestStatus', $request->getStatus());
251
+
252
+		$this->assign('requestIsClosed', !array_key_exists($request->getStatus(), $config->getRequestStates()));
253
+	}
254
+
255
+	/**
256
+	 * Sets up the forwarded IP data for this request and adds it to Smarty
257
+	 *
258
+	 * @param Request $request
259
+	 */
260
+	protected function setupForwardedIpData(Request $request)
261
+	{
262
+		if ($request->getForwardedIp() !== null) {
263
+			$requestProxyData = array(); // Initialize array to store data to be output in Smarty template.
264
+			$proxyIndex = 0;
265
+
266
+			// Assuming [client] <=> [proxy1] <=> [proxy2] <=> [proxy3] <=> [us], we will see an XFF header of [client],
267
+			// [proxy1], [proxy2], and our actual IP will be [proxy3]
268
+			$proxies = explode(",", $request->getForwardedIp());
269
+			$proxies[] = $request->getIp();
270
+
271
+			// Origin is the supposed "client" IP.
272
+			$origin = $proxies[0];
273
+			$this->assign("forwardedOrigin", $origin);
274
+
275
+			// We step through the servers in reverse order, from closest to furthest
276
+			$proxies = array_reverse($proxies);
277
+
278
+			// By default, we have trust, because the first in the chain is now REMOTE_ADDR, which is hardest to spoof.
279
+			$trust = true;
280
+
281
+			/**
282
+			 * @var int    $index     The zero-based index of the proxy.
283
+			 * @var string $proxyData The proxy IP address (although possibly not!)
284
+			 */
285
+			foreach ($proxies as $index => $proxyData) {
286
+				$proxyAddress = trim($proxyData);
287
+				$requestProxyData[$proxyIndex]['ip'] = $proxyAddress;
288
+
289
+				// get data on this IP.
290
+				$thisProxyIsTrusted = $this->getXffTrustProvider()->isTrusted($proxyAddress);
291
+
292
+				$proxyIsInPrivateRange = $this->getXffTrustProvider()
293
+					->ipInRange(self::$rfc1918ips, $proxyAddress);
294
+
295
+				if (!$proxyIsInPrivateRange) {
296
+					$proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
297
+					$proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
298
+				}
299
+				else {
300
+					// this is going to fail, so why bother trying?
301
+					$proxyReverseDns = false;
302
+					$proxyLocation = false;
303
+				}
304
+
305
+				// current trust chain status BEFORE this link
306
+				$preLinkTrust = $trust;
307
+
308
+				// is *this* link trusted? Note, this will be true even if there is an untrusted link before this!
309
+				$requestProxyData[$proxyIndex]['trustedlink'] = $thisProxyIsTrusted;
310
+
311
+				// set the trust status of the chain to this point
312
+				$trust = $trust & $thisProxyIsTrusted;
313
+
314
+				// If this is the origin address, and the chain was trusted before this point, then we can trust
315
+				// the origin.
316
+				if ($preLinkTrust && $proxyAddress == $origin) {
317
+					// if this is the origin, then we are at the last point in the chain.
318
+					// @todo: this is probably the cause of some bugs when an IP appears twice - we're missing a check
319
+					// to see if this is *really* the last in the chain, rather than just the same IP as it.
320
+					$trust = true;
321
+				}
322
+
323
+				$requestProxyData[$proxyIndex]['trust'] = $trust;
324
+
325
+				$requestProxyData[$proxyIndex]['rdnsfailed'] = $proxyReverseDns === false;
326
+				$requestProxyData[$proxyIndex]['rdns'] = $proxyReverseDns;
327
+				$requestProxyData[$proxyIndex]['routable'] = !$proxyIsInPrivateRange;
328
+
329
+				$requestProxyData[$proxyIndex]['location'] = $proxyLocation;
330
+
331
+				if ($proxyReverseDns === $proxyAddress && $proxyIsInPrivateRange === false) {
332
+					$requestProxyData[$proxyIndex]['rdns'] = null;
333
+				}
334
+
335
+				$showLinks = (!$trust || $proxyAddress == $origin) && !$proxyIsInPrivateRange;
336
+				$requestProxyData[$proxyIndex]['showlinks'] = $showLinks;
337
+
338
+				$proxyIndex++;
339
+			}
340
+
341
+			$this->assign("requestProxyData", $requestProxyData);
342
+		}
343
+	}
344 344
 }
Please login to merge, or discard this patch.
includes/DataObjects/CommunityUser.php 1 patch
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -16,212 +16,212 @@
 block discarded – undo
16 16
  */
17 17
 class CommunityUser extends User
18 18
 {
19
-    public function getId()
20
-    {
21
-        return -1;
22
-    }
23
-
24
-    public function save()
25
-    {
26
-        // Do nothing
27
-    }
28
-
29
-    public function authenticate($password)
30
-    {
31
-        // Impossible to log in as this user
32
-        return false;
33
-    }
34
-
35
-    #region properties
36
-
37
-    /**
38
-     * @return string
39
-     */
40
-    public function getUsername()
41
-    {
42
-        global $communityUsername;
43
-
44
-        return $communityUsername;
45
-    }
46
-
47
-    public function setUsername($username)
48
-    {
49
-    }
50
-
51
-    /**
52
-     * @return string
53
-     */
54
-    public function getEmail()
55
-    {
56
-        global $cDataClearEmail;
57
-
58
-        return $cDataClearEmail;
59
-    }
60
-
61
-    public function setEmail($email)
62
-    {
63
-    }
64
-
65
-    public function setPassword($password)
66
-    {
67
-    }
68
-
69
-    public function getStatus()
70
-    {
71
-        return "Community";
72
-    }
73
-
74
-    public function getOnWikiName()
75
-    {
76
-        return "127.0.0.1";
77
-    }
78
-
79
-    public function getStoredOnWikiName()
80
-    {
81
-        return $this->getOnWikiName();
82
-    }
83
-
84
-    public function setOnWikiName($onWikiName)
85
-    {
86
-    }
87
-
88
-    public function getWelcomeSig()
89
-    {
90
-        return null;
91
-    }
92
-
93
-    public function setWelcomeSig($welcomeSig)
94
-    {
95
-    }
96
-
97
-    public function getLastActive()
98
-    {
99
-        $now = new DateTime();
100
-
101
-        return $now->format("Y-m-d H:i:s");
102
-    }
103
-
104
-    public function getForceLogout()
105
-    {
106
-        return true;
107
-    }
108
-
109
-    public function setForceLogout($forceLogout)
110
-    {
111
-    }
112
-
113
-    /**
114
-     * @param string $status
115
-     */
116
-    public function setStatus($status)
117
-    {
118
-    }
119
-
120
-    public function getWelcomeTemplate()
121
-    {
122
-        return 0;
123
-    }
124
-
125
-    public function setWelcomeTemplate($welcomeTemplate)
126
-    {
127
-    }
128
-
129
-    public function getAbortPref()
130
-    {
131
-        return 0;
132
-    }
133
-
134
-    public function setAbortPref($abortPreference)
135
-    {
136
-    }
137
-
138
-    public function getConfirmationDiff()
139
-    {
140
-        return null;
141
-    }
142
-
143
-    public function setConfirmationDiff($confirmationDiff)
144
-    {
145
-    }
146
-
147
-    public function getEmailSig()
148
-    {
149
-        return null;
150
-    }
151
-
152
-    public function setEmailSig($emailSignature)
153
-    {
154
-    }
155
-
156
-    #endregion
157
-
158
-    #region user access checks
159
-
160
-    public function isIdentified(IdentificationVerifier $iv)
161
-    {
162
-        return false;
163
-    }
164
-
165
-    public function isSuspended()
166
-    {
167
-        return false;
168
-    }
169
-
170
-    public function isNewUser()
171
-    {
172
-        return false;
173
-    }
174
-
175
-    public function isDeclined()
176
-    {
177
-        return false;
178
-    }
179
-
180
-    public function isCommunityUser()
181
-    {
182
-        return true;
183
-    }
184
-
185
-    #endregion 
186
-
187
-    #region OAuth
188
-
189
-    public function getOAuthIdentity($useCached = false)
190
-    {
191
-        return null;
192
-    }
193
-
194
-    public function isOAuthLinked()
195
-    {
196
-        return false;
197
-    }
198
-
199
-    public function oauthCanUse()
200
-    {
201
-        return false;
202
-    }
203
-
204
-    public function oauthCanEdit()
205
-    {
206
-        return false;
207
-    }
208
-
209
-    public function oauthCanCreateAccount()
210
-    {
211
-        return false;
212
-    }
213
-
214
-    protected function oauthCanCheckUser()
215
-    {
216
-        return false;
217
-    }
218
-
219
-    #endregion
220
-
221
-    public function getApprovalDate()
222
-    {
223
-        $data = DateTime::createFromFormat("Y-m-d H:i:s", "1970-01-01 00:00:00");
19
+	public function getId()
20
+	{
21
+		return -1;
22
+	}
23
+
24
+	public function save()
25
+	{
26
+		// Do nothing
27
+	}
28
+
29
+	public function authenticate($password)
30
+	{
31
+		// Impossible to log in as this user
32
+		return false;
33
+	}
34
+
35
+	#region properties
36
+
37
+	/**
38
+	 * @return string
39
+	 */
40
+	public function getUsername()
41
+	{
42
+		global $communityUsername;
43
+
44
+		return $communityUsername;
45
+	}
46
+
47
+	public function setUsername($username)
48
+	{
49
+	}
50
+
51
+	/**
52
+	 * @return string
53
+	 */
54
+	public function getEmail()
55
+	{
56
+		global $cDataClearEmail;
57
+
58
+		return $cDataClearEmail;
59
+	}
60
+
61
+	public function setEmail($email)
62
+	{
63
+	}
64
+
65
+	public function setPassword($password)
66
+	{
67
+	}
68
+
69
+	public function getStatus()
70
+	{
71
+		return "Community";
72
+	}
73
+
74
+	public function getOnWikiName()
75
+	{
76
+		return "127.0.0.1";
77
+	}
78
+
79
+	public function getStoredOnWikiName()
80
+	{
81
+		return $this->getOnWikiName();
82
+	}
83
+
84
+	public function setOnWikiName($onWikiName)
85
+	{
86
+	}
87
+
88
+	public function getWelcomeSig()
89
+	{
90
+		return null;
91
+	}
92
+
93
+	public function setWelcomeSig($welcomeSig)
94
+	{
95
+	}
96
+
97
+	public function getLastActive()
98
+	{
99
+		$now = new DateTime();
100
+
101
+		return $now->format("Y-m-d H:i:s");
102
+	}
103
+
104
+	public function getForceLogout()
105
+	{
106
+		return true;
107
+	}
108
+
109
+	public function setForceLogout($forceLogout)
110
+	{
111
+	}
112
+
113
+	/**
114
+	 * @param string $status
115
+	 */
116
+	public function setStatus($status)
117
+	{
118
+	}
119
+
120
+	public function getWelcomeTemplate()
121
+	{
122
+		return 0;
123
+	}
124
+
125
+	public function setWelcomeTemplate($welcomeTemplate)
126
+	{
127
+	}
128
+
129
+	public function getAbortPref()
130
+	{
131
+		return 0;
132
+	}
133
+
134
+	public function setAbortPref($abortPreference)
135
+	{
136
+	}
137
+
138
+	public function getConfirmationDiff()
139
+	{
140
+		return null;
141
+	}
142
+
143
+	public function setConfirmationDiff($confirmationDiff)
144
+	{
145
+	}
146
+
147
+	public function getEmailSig()
148
+	{
149
+		return null;
150
+	}
151
+
152
+	public function setEmailSig($emailSignature)
153
+	{
154
+	}
155
+
156
+	#endregion
157
+
158
+	#region user access checks
159
+
160
+	public function isIdentified(IdentificationVerifier $iv)
161
+	{
162
+		return false;
163
+	}
164
+
165
+	public function isSuspended()
166
+	{
167
+		return false;
168
+	}
169
+
170
+	public function isNewUser()
171
+	{
172
+		return false;
173
+	}
174
+
175
+	public function isDeclined()
176
+	{
177
+		return false;
178
+	}
179
+
180
+	public function isCommunityUser()
181
+	{
182
+		return true;
183
+	}
184
+
185
+	#endregion 
186
+
187
+	#region OAuth
188
+
189
+	public function getOAuthIdentity($useCached = false)
190
+	{
191
+		return null;
192
+	}
193
+
194
+	public function isOAuthLinked()
195
+	{
196
+		return false;
197
+	}
198
+
199
+	public function oauthCanUse()
200
+	{
201
+		return false;
202
+	}
203
+
204
+	public function oauthCanEdit()
205
+	{
206
+		return false;
207
+	}
208
+
209
+	public function oauthCanCreateAccount()
210
+	{
211
+		return false;
212
+	}
213
+
214
+	protected function oauthCanCheckUser()
215
+	{
216
+		return false;
217
+	}
218
+
219
+	#endregion
220
+
221
+	public function getApprovalDate()
222
+	{
223
+		$data = DateTime::createFromFormat("Y-m-d H:i:s", "1970-01-01 00:00:00");
224 224
 
225
-        return $data;
226
-    }
225
+		return $data;
226
+	}
227 227
 }
Please login to merge, or discard this patch.
includes/DataObjects/UserRole.php 1 patch
Indentation   +79 added lines, -79 removed lines patch added patch discarded remove patch
@@ -15,95 +15,95 @@
 block discarded – undo
15 15
 
16 16
 class UserRole extends DataObject
17 17
 {
18
-    /** @var int */
19
-    private $user;
20
-    /** @var string */
21
-    private $role;
18
+	/** @var int */
19
+	private $user;
20
+	/** @var string */
21
+	private $role;
22 22
 
23
-    /**
24
-     * @param int         $userId
25
-     * @param PdoDatabase $database
26
-     *
27
-     * @return UserRole[]
28
-     */
29
-    public static function getForUser($userId, PdoDatabase $database)
30
-    {
31
-        $sql = 'SELECT * FROM userrole WHERE user = :user';
32
-        $statement = $database->prepare($sql);
33
-        $statement->bindValue(':user', $userId);
23
+	/**
24
+	 * @param int         $userId
25
+	 * @param PdoDatabase $database
26
+	 *
27
+	 * @return UserRole[]
28
+	 */
29
+	public static function getForUser($userId, PdoDatabase $database)
30
+	{
31
+		$sql = 'SELECT * FROM userrole WHERE user = :user';
32
+		$statement = $database->prepare($sql);
33
+		$statement->bindValue(':user', $userId);
34 34
 
35
-        $statement->execute();
35
+		$statement->execute();
36 36
 
37
-        $result = array();
37
+		$result = array();
38 38
 
39
-        /** @var Ban $v */
40
-        foreach ($statement->fetchAll(PDO::FETCH_CLASS, get_called_class()) as $v) {
41
-            $v->setDatabase($database);
42
-            $result[] = $v;
43
-        }
39
+		/** @var Ban $v */
40
+		foreach ($statement->fetchAll(PDO::FETCH_CLASS, get_called_class()) as $v) {
41
+			$v->setDatabase($database);
42
+			$result[] = $v;
43
+		}
44 44
 
45
-        return $result;
46
-    }
45
+		return $result;
46
+	}
47 47
 
48
-    /**
49
-     * Saves a data object to the database, either updating or inserting a record.
50
-     *
51
-     * @throws Exception
52
-     */
53
-    public function save()
54
-    {
55
-        if ($this->isNew()) {
56
-            // insert
57
-            $statement = $this->dbObject->prepare('INSERT INTO `userrole` (user, role) VALUES (:user, :role);'
58
-            );
59
-            $statement->bindValue(":user", $this->user);
60
-            $statement->bindValue(":role", $this->role);
48
+	/**
49
+	 * Saves a data object to the database, either updating or inserting a record.
50
+	 *
51
+	 * @throws Exception
52
+	 */
53
+	public function save()
54
+	{
55
+		if ($this->isNew()) {
56
+			// insert
57
+			$statement = $this->dbObject->prepare('INSERT INTO `userrole` (user, role) VALUES (:user, :role);'
58
+			);
59
+			$statement->bindValue(":user", $this->user);
60
+			$statement->bindValue(":role", $this->role);
61 61
 
62
-            if ($statement->execute()) {
63
-                $this->id = (int)$this->dbObject->lastInsertId();
64
-            }
65
-            else {
66
-                throw new Exception($statement->errorInfo());
67
-            }
68
-        }
69
-        else {
70
-            // update
71
-            throw new Exception('Updating roles is not available');
72
-        }
73
-    }
62
+			if ($statement->execute()) {
63
+				$this->id = (int)$this->dbObject->lastInsertId();
64
+			}
65
+			else {
66
+				throw new Exception($statement->errorInfo());
67
+			}
68
+		}
69
+		else {
70
+			// update
71
+			throw new Exception('Updating roles is not available');
72
+		}
73
+	}
74 74
 
75
-    #region Properties
75
+	#region Properties
76 76
 
77
-    /**
78
-     * @return int
79
-     */
80
-    public function getUser()
81
-    {
82
-        return $this->user;
83
-    }
77
+	/**
78
+	 * @return int
79
+	 */
80
+	public function getUser()
81
+	{
82
+		return $this->user;
83
+	}
84 84
 
85
-    /**
86
-     * @param int $user
87
-     */
88
-    public function setUser($user)
89
-    {
90
-        $this->user = $user;
91
-    }
85
+	/**
86
+	 * @param int $user
87
+	 */
88
+	public function setUser($user)
89
+	{
90
+		$this->user = $user;
91
+	}
92 92
 
93
-    /**
94
-     * @return string
95
-     */
96
-    public function getRole()
97
-    {
98
-        return $this->role;
99
-    }
93
+	/**
94
+	 * @return string
95
+	 */
96
+	public function getRole()
97
+	{
98
+		return $this->role;
99
+	}
100 100
 
101
-    /**
102
-     * @param string $role
103
-     */
104
-    public function setRole($role)
105
-    {
106
-        $this->role = $role;
107
-    }
108
-    #endregion
101
+	/**
102
+	 * @param string $role
103
+	 */
104
+	public function setRole($role)
105
+	{
106
+		$this->role = $role;
107
+	}
108
+	#endregion
109 109
 }
Please login to merge, or discard this patch.
includes/DataObjects/User.php 2 patches
Indentation   +947 added lines, -947 removed lines patch added patch discarded remove patch
@@ -27,229 +27,229 @@  discard block
 block discarded – undo
27 27
  */
28 28
 class User extends DataObject
29 29
 {
30
-    const STATUS_ACTIVE = 'Active';
31
-    const STATUS_SUSPENDED = 'Suspended';
32
-    const STATUS_DECLINED = 'Declined';
33
-    const STATUS_NEW = 'New';
34
-    private $username;
35
-    private $email;
36
-    private $password;
37
-    private $status = self::STATUS_NEW;
38
-    private $onwikiname = "##OAUTH##";
39
-    private $welcome_sig = "";
40
-    private $lastactive = "0000-00-00 00:00:00";
41
-    private $forcelogout = 0;
42
-    private $forceidentified = null;
43
-    private $welcome_template = 0;
44
-    private $abortpref = 0;
45
-    private $confirmationdiff = 0;
46
-    private $emailsig = "";
47
-    /** @var null|string */
48
-    private $oauthrequesttoken = null;
49
-    /** @var null|string */
50
-    private $oauthrequestsecret = null;
51
-    /** @var null|string */
52
-    private $oauthaccesstoken = null;
53
-    /** @var null|string */
54
-    private $oauthaccesssecret = null;
55
-    private $oauthidentitycache = null;
56
-    /** @var User Cache variable of the current user - it's never going to change in the middle of a request. */
57
-    private static $currentUser;
58
-    /** @var null|JWT The identity cache */
59
-    private $identityCache = null;
60
-    #region Object load methods
61
-
62
-    /**
63
-     * Gets the currently logged in user
64
-     *
65
-     * @param PdoDatabase $database
66
-     *
67
-     * @return User|CommunityUser
68
-     */
69
-    public static function getCurrent(PdoDatabase $database)
70
-    {
71
-        if (self::$currentUser === null) {
72
-            $sessionId = WebRequest::getSessionUserId();
73
-
74
-            if ($sessionId !== null) {
75
-                /** @var User $user */
76
-                $user = self::getById($sessionId, $database);
77
-
78
-                if ($user === false) {
79
-                    self::$currentUser = new CommunityUser();
80
-                }
81
-                else {
82
-                    self::$currentUser = $user;
83
-                }
84
-            }
85
-            else {
86
-                $anonymousCoward = new CommunityUser();
87
-
88
-                self::$currentUser = $anonymousCoward;
89
-            }
90
-        }
91
-
92
-        return self::$currentUser;
93
-    }
94
-
95
-    /**
96
-     * Gets a user by their user ID
97
-     *
98
-     * Pass -1 to get the community user.
99
-     *
100
-     * @param int|null    $id
101
-     * @param PdoDatabase $database
102
-     *
103
-     * @return User|false
104
-     */
105
-    public static function getById($id, PdoDatabase $database)
106
-    {
107
-        if ($id === null || $id == -1) {
108
-            return new CommunityUser();
109
-        }
110
-
111
-        /** @var User|false $user */
112
-        $user = parent::getById($id, $database);
113
-
114
-        return $user;
115
-    }
116
-
117
-    /**
118
-     * @return CommunityUser
119
-     */
120
-    public static function getCommunity()
121
-    {
122
-        return new CommunityUser();
123
-    }
124
-
125
-    /**
126
-     * Gets a user by their username
127
-     *
128
-     * @param  string      $username
129
-     * @param  PdoDatabase $database
130
-     *
131
-     * @return CommunityUser|User|false
132
-     */
133
-    public static function getByUsername($username, PdoDatabase $database)
134
-    {
135
-        global $communityUsername;
136
-        if ($username == $communityUsername) {
137
-            return new CommunityUser();
138
-        }
139
-
140
-        $statement = $database->prepare("SELECT * FROM user WHERE username = :id LIMIT 1;");
141
-        $statement->bindValue(":id", $username);
142
-
143
-        $statement->execute();
144
-
145
-        $resultObject = $statement->fetchObject(get_called_class());
146
-
147
-        if ($resultObject != false) {
148
-            $resultObject->setDatabase($database);
149
-        }
150
-
151
-        return $resultObject;
152
-    }
153
-
154
-    /**
155
-     * Gets a user by their on-wiki username.
156
-     *
157
-     * Don't use without asking me first. It's really inefficient in it's current implementation.
158
-     * We need to restructure the user table again to make this more efficient.
159
-     * We don't actually store the on-wiki name in the table any more, instead we
160
-     * are storing JSON in a column (!!). Yep, my fault. Code review is an awesome thing.
161
-     *            -- stw 2015-10-20
162
-     *
163
-     * @param string      $username
164
-     * @param PdoDatabase $database
165
-     *
166
-     * @return User|false
167
-     */
168
-    public static function getByOnWikiUsername($username, PdoDatabase $database)
169
-    {
170
-        // Firstly, try to search by the efficient database lookup.
171
-        $statement = $database->prepare("SELECT * FROM user WHERE onwikiname = :id LIMIT 1;");
172
-        $statement->bindValue(":id", $username);
173
-        $statement->execute();
174
-
175
-        $resultObject = $statement->fetchObject(get_called_class());
176
-
177
-        if ($resultObject != false) {
178
-            $resultObject->setDatabase($database);
179
-
180
-            return $resultObject;
181
-        }
182
-
183
-        // For active users, the above has failed. Let's do it the hard way.
184
-        $sqlStatement = "SELECT * FROM user WHERE onwikiname = '##OAUTH##' AND oauthaccesstoken IS NOT NULL;";
185
-        $statement = $database->prepare($sqlStatement);
186
-        $statement->execute();
187
-        $resultSet = $statement->fetchAll(PDO::FETCH_CLASS, get_called_class());
188
-
189
-        /** @var User $user */
190
-        foreach ($resultSet as $user) {
191
-            // We have to set this before doing OAuth queries. :(
192
-            $user->setDatabase($database);
193
-
194
-            // Using cached data here!
195
-            if ($user->getOAuthOnWikiName(true) == $username) {
196
-                // Success.
197
-                return $user;
198
-            }
199
-        }
200
-
201
-        // Cached data failed. Let's do it the *REALLY* hard way.
202
-        foreach ($resultSet as $user) {
203
-            // We have to set this before doing OAuth queries. :(
204
-            $user->setDatabase($database);
205
-
206
-            // Don't use the cached data, but instead query the API.
207
-            if ($user->getOAuthOnWikiName(false) == $username) {
208
-                // Success.
209
-                return $user;
210
-            }
211
-        }
212
-
213
-        // Nope. Sorry.
214
-        return false;
215
-    }
216
-
217
-    /**
218
-     * Gets a user by their OAuth request token
219
-     *
220
-     * @param string      $requestToken
221
-     * @param PdoDatabase $database
222
-     *
223
-     * @return User|false
224
-     */
225
-    public static function getByRequestToken($requestToken, PdoDatabase $database)
226
-    {
227
-        $statement = $database->prepare("SELECT * FROM user WHERE oauthrequesttoken = :id LIMIT 1;");
228
-        $statement->bindValue(":id", $requestToken);
229
-
230
-        $statement->execute();
231
-
232
-        $resultObject = $statement->fetchObject(get_called_class());
233
-
234
-        if ($resultObject != false) {
235
-            $resultObject->setDatabase($database);
236
-        }
237
-
238
-        return $resultObject;
239
-    }
240
-
241
-    #endregion
242
-
243
-    /**
244
-     * Saves the current object
245
-     *
246
-     * @throws Exception
247
-     */
248
-    public function save()
249
-    {
250
-        if ($this->isNew()) {
251
-            // insert
252
-            $statement = $this->dbObject->prepare(<<<SQL
30
+	const STATUS_ACTIVE = 'Active';
31
+	const STATUS_SUSPENDED = 'Suspended';
32
+	const STATUS_DECLINED = 'Declined';
33
+	const STATUS_NEW = 'New';
34
+	private $username;
35
+	private $email;
36
+	private $password;
37
+	private $status = self::STATUS_NEW;
38
+	private $onwikiname = "##OAUTH##";
39
+	private $welcome_sig = "";
40
+	private $lastactive = "0000-00-00 00:00:00";
41
+	private $forcelogout = 0;
42
+	private $forceidentified = null;
43
+	private $welcome_template = 0;
44
+	private $abortpref = 0;
45
+	private $confirmationdiff = 0;
46
+	private $emailsig = "";
47
+	/** @var null|string */
48
+	private $oauthrequesttoken = null;
49
+	/** @var null|string */
50
+	private $oauthrequestsecret = null;
51
+	/** @var null|string */
52
+	private $oauthaccesstoken = null;
53
+	/** @var null|string */
54
+	private $oauthaccesssecret = null;
55
+	private $oauthidentitycache = null;
56
+	/** @var User Cache variable of the current user - it's never going to change in the middle of a request. */
57
+	private static $currentUser;
58
+	/** @var null|JWT The identity cache */
59
+	private $identityCache = null;
60
+	#region Object load methods
61
+
62
+	/**
63
+	 * Gets the currently logged in user
64
+	 *
65
+	 * @param PdoDatabase $database
66
+	 *
67
+	 * @return User|CommunityUser
68
+	 */
69
+	public static function getCurrent(PdoDatabase $database)
70
+	{
71
+		if (self::$currentUser === null) {
72
+			$sessionId = WebRequest::getSessionUserId();
73
+
74
+			if ($sessionId !== null) {
75
+				/** @var User $user */
76
+				$user = self::getById($sessionId, $database);
77
+
78
+				if ($user === false) {
79
+					self::$currentUser = new CommunityUser();
80
+				}
81
+				else {
82
+					self::$currentUser = $user;
83
+				}
84
+			}
85
+			else {
86
+				$anonymousCoward = new CommunityUser();
87
+
88
+				self::$currentUser = $anonymousCoward;
89
+			}
90
+		}
91
+
92
+		return self::$currentUser;
93
+	}
94
+
95
+	/**
96
+	 * Gets a user by their user ID
97
+	 *
98
+	 * Pass -1 to get the community user.
99
+	 *
100
+	 * @param int|null    $id
101
+	 * @param PdoDatabase $database
102
+	 *
103
+	 * @return User|false
104
+	 */
105
+	public static function getById($id, PdoDatabase $database)
106
+	{
107
+		if ($id === null || $id == -1) {
108
+			return new CommunityUser();
109
+		}
110
+
111
+		/** @var User|false $user */
112
+		$user = parent::getById($id, $database);
113
+
114
+		return $user;
115
+	}
116
+
117
+	/**
118
+	 * @return CommunityUser
119
+	 */
120
+	public static function getCommunity()
121
+	{
122
+		return new CommunityUser();
123
+	}
124
+
125
+	/**
126
+	 * Gets a user by their username
127
+	 *
128
+	 * @param  string      $username
129
+	 * @param  PdoDatabase $database
130
+	 *
131
+	 * @return CommunityUser|User|false
132
+	 */
133
+	public static function getByUsername($username, PdoDatabase $database)
134
+	{
135
+		global $communityUsername;
136
+		if ($username == $communityUsername) {
137
+			return new CommunityUser();
138
+		}
139
+
140
+		$statement = $database->prepare("SELECT * FROM user WHERE username = :id LIMIT 1;");
141
+		$statement->bindValue(":id", $username);
142
+
143
+		$statement->execute();
144
+
145
+		$resultObject = $statement->fetchObject(get_called_class());
146
+
147
+		if ($resultObject != false) {
148
+			$resultObject->setDatabase($database);
149
+		}
150
+
151
+		return $resultObject;
152
+	}
153
+
154
+	/**
155
+	 * Gets a user by their on-wiki username.
156
+	 *
157
+	 * Don't use without asking me first. It's really inefficient in it's current implementation.
158
+	 * We need to restructure the user table again to make this more efficient.
159
+	 * We don't actually store the on-wiki name in the table any more, instead we
160
+	 * are storing JSON in a column (!!). Yep, my fault. Code review is an awesome thing.
161
+	 *            -- stw 2015-10-20
162
+	 *
163
+	 * @param string      $username
164
+	 * @param PdoDatabase $database
165
+	 *
166
+	 * @return User|false
167
+	 */
168
+	public static function getByOnWikiUsername($username, PdoDatabase $database)
169
+	{
170
+		// Firstly, try to search by the efficient database lookup.
171
+		$statement = $database->prepare("SELECT * FROM user WHERE onwikiname = :id LIMIT 1;");
172
+		$statement->bindValue(":id", $username);
173
+		$statement->execute();
174
+
175
+		$resultObject = $statement->fetchObject(get_called_class());
176
+
177
+		if ($resultObject != false) {
178
+			$resultObject->setDatabase($database);
179
+
180
+			return $resultObject;
181
+		}
182
+
183
+		// For active users, the above has failed. Let's do it the hard way.
184
+		$sqlStatement = "SELECT * FROM user WHERE onwikiname = '##OAUTH##' AND oauthaccesstoken IS NOT NULL;";
185
+		$statement = $database->prepare($sqlStatement);
186
+		$statement->execute();
187
+		$resultSet = $statement->fetchAll(PDO::FETCH_CLASS, get_called_class());
188
+
189
+		/** @var User $user */
190
+		foreach ($resultSet as $user) {
191
+			// We have to set this before doing OAuth queries. :(
192
+			$user->setDatabase($database);
193
+
194
+			// Using cached data here!
195
+			if ($user->getOAuthOnWikiName(true) == $username) {
196
+				// Success.
197
+				return $user;
198
+			}
199
+		}
200
+
201
+		// Cached data failed. Let's do it the *REALLY* hard way.
202
+		foreach ($resultSet as $user) {
203
+			// We have to set this before doing OAuth queries. :(
204
+			$user->setDatabase($database);
205
+
206
+			// Don't use the cached data, but instead query the API.
207
+			if ($user->getOAuthOnWikiName(false) == $username) {
208
+				// Success.
209
+				return $user;
210
+			}
211
+		}
212
+
213
+		// Nope. Sorry.
214
+		return false;
215
+	}
216
+
217
+	/**
218
+	 * Gets a user by their OAuth request token
219
+	 *
220
+	 * @param string      $requestToken
221
+	 * @param PdoDatabase $database
222
+	 *
223
+	 * @return User|false
224
+	 */
225
+	public static function getByRequestToken($requestToken, PdoDatabase $database)
226
+	{
227
+		$statement = $database->prepare("SELECT * FROM user WHERE oauthrequesttoken = :id LIMIT 1;");
228
+		$statement->bindValue(":id", $requestToken);
229
+
230
+		$statement->execute();
231
+
232
+		$resultObject = $statement->fetchObject(get_called_class());
233
+
234
+		if ($resultObject != false) {
235
+			$resultObject->setDatabase($database);
236
+		}
237
+
238
+		return $resultObject;
239
+	}
240
+
241
+	#endregion
242
+
243
+	/**
244
+	 * Saves the current object
245
+	 *
246
+	 * @throws Exception
247
+	 */
248
+	public function save()
249
+	{
250
+		if ($this->isNew()) {
251
+			// insert
252
+			$statement = $this->dbObject->prepare(<<<SQL
253 253
 				INSERT INTO `user` ( 
254 254
 					username, email, password, status, onwikiname, welcome_sig, 
255 255
 					lastactive, forcelogout, forceidentified,
@@ -263,35 +263,35 @@  discard block
 block discarded – undo
263 263
 					:ort, :ors, :oat, :oas
264 264
 				);
265 265
 SQL
266
-            );
267
-            $statement->bindValue(":username", $this->username);
268
-            $statement->bindValue(":email", $this->email);
269
-            $statement->bindValue(":password", $this->password);
270
-            $statement->bindValue(":status", $this->status);
271
-            $statement->bindValue(":onwikiname", $this->onwikiname);
272
-            $statement->bindValue(":welcome_sig", $this->welcome_sig);
273
-            $statement->bindValue(":lastactive", $this->lastactive);
274
-            $statement->bindValue(":forcelogout", $this->forcelogout);
275
-            $statement->bindValue(":forceidentified", $this->forceidentified);
276
-            $statement->bindValue(":welcome_template", $this->welcome_template);
277
-            $statement->bindValue(":abortpref", $this->abortpref);
278
-            $statement->bindValue(":confirmationdiff", $this->confirmationdiff);
279
-            $statement->bindValue(":emailsig", $this->emailsig);
280
-            $statement->bindValue(":ort", $this->oauthrequesttoken);
281
-            $statement->bindValue(":ors", $this->oauthrequestsecret);
282
-            $statement->bindValue(":oat", $this->oauthaccesstoken);
283
-            $statement->bindValue(":oas", $this->oauthaccesssecret);
284
-
285
-            if ($statement->execute()) {
286
-                $this->id = (int)$this->dbObject->lastInsertId();
287
-            }
288
-            else {
289
-                throw new Exception($statement->errorInfo());
290
-            }
291
-        }
292
-        else {
293
-            // update
294
-            $statement = $this->dbObject->prepare(<<<SQL
266
+			);
267
+			$statement->bindValue(":username", $this->username);
268
+			$statement->bindValue(":email", $this->email);
269
+			$statement->bindValue(":password", $this->password);
270
+			$statement->bindValue(":status", $this->status);
271
+			$statement->bindValue(":onwikiname", $this->onwikiname);
272
+			$statement->bindValue(":welcome_sig", $this->welcome_sig);
273
+			$statement->bindValue(":lastactive", $this->lastactive);
274
+			$statement->bindValue(":forcelogout", $this->forcelogout);
275
+			$statement->bindValue(":forceidentified", $this->forceidentified);
276
+			$statement->bindValue(":welcome_template", $this->welcome_template);
277
+			$statement->bindValue(":abortpref", $this->abortpref);
278
+			$statement->bindValue(":confirmationdiff", $this->confirmationdiff);
279
+			$statement->bindValue(":emailsig", $this->emailsig);
280
+			$statement->bindValue(":ort", $this->oauthrequesttoken);
281
+			$statement->bindValue(":ors", $this->oauthrequestsecret);
282
+			$statement->bindValue(":oat", $this->oauthaccesstoken);
283
+			$statement->bindValue(":oas", $this->oauthaccesssecret);
284
+
285
+			if ($statement->execute()) {
286
+				$this->id = (int)$this->dbObject->lastInsertId();
287
+			}
288
+			else {
289
+				throw new Exception($statement->errorInfo());
290
+			}
291
+		}
292
+		else {
293
+			// update
294
+			$statement = $this->dbObject->prepare(<<<SQL
295 295
 				UPDATE `user` SET 
296 296
 					username = :username, email = :email, 
297 297
 					password = :password, status = :status,
@@ -306,695 +306,695 @@  discard block
 block discarded – undo
306 306
 				WHERE id = :id AND updateversion = :updateversion
307 307
 				LIMIT 1;
308 308
 SQL
309
-            );
310
-            $statement->bindValue(":forceidentified", $this->forceidentified);
311
-
312
-            $statement->bindValue(':id', $this->id);
313
-            $statement->bindValue(':updateversion', $this->updateversion);
314
-
315
-            $statement->bindValue(':username', $this->username);
316
-            $statement->bindValue(':email', $this->email);
317
-            $statement->bindValue(':password', $this->password);
318
-            $statement->bindValue(':status', $this->status);
319
-            $statement->bindValue(':onwikiname', $this->onwikiname);
320
-            $statement->bindValue(':welcome_sig', $this->welcome_sig);
321
-            $statement->bindValue(':lastactive', $this->lastactive);
322
-            $statement->bindValue(':forcelogout', $this->forcelogout);
323
-            $statement->bindValue(':forceidentified', $this->forceidentified);
324
-            $statement->bindValue(':welcome_template', $this->welcome_template);
325
-            $statement->bindValue(':abortpref', $this->abortpref);
326
-            $statement->bindValue(':confirmationdiff', $this->confirmationdiff);
327
-            $statement->bindValue(':emailsig', $this->emailsig);
328
-            $statement->bindValue(':ort', $this->oauthrequesttoken);
329
-            $statement->bindValue(':ors', $this->oauthrequestsecret);
330
-            $statement->bindValue(':oat', $this->oauthaccesstoken);
331
-            $statement->bindValue(':oas', $this->oauthaccesssecret);
332
-
333
-            if (!$statement->execute()) {
334
-                throw new Exception($statement->errorInfo());
335
-            }
336
-
337
-            if ($statement->rowCount() !== 1) {
338
-                throw new OptimisticLockFailedException();
339
-            }
340
-
341
-            $this->updateversion++;
342
-        }
343
-    }
344
-
345
-    /**
346
-     * Authenticates the user with the supplied password
347
-     *
348
-     * @param string $password
349
-     *
350
-     * @return bool
351
-     * @throws Exception
352
-     * @category Security-Critical
353
-     */
354
-    public function authenticate($password)
355
-    {
356
-        $result = AuthUtility::testCredentials($password, $this->password);
357
-
358
-        if ($result === true) {
359
-            // password version is out of date, update it.
360
-            if (!AuthUtility::isCredentialVersionLatest($this->password)) {
361
-                $this->password = AuthUtility::encryptPassword($password);
362
-                $this->save();
363
-            }
364
-        }
365
-
366
-        return $result;
367
-    }
368
-
369
-    #region properties
370
-
371
-    /**
372
-     * Gets the tool username
373
-     * @return string
374
-     */
375
-    public function getUsername()
376
-    {
377
-        return $this->username;
378
-    }
379
-
380
-    /**
381
-     * Sets the tool username
382
-     *
383
-     * @param string $username
384
-     */
385
-    public function setUsername($username)
386
-    {
387
-        $this->username = $username;
388
-
389
-        // If this isn't a brand new user, then it's a rename, force the logout
390
-        if (!$this->isNew()) {
391
-            $this->forcelogout = 1;
392
-        }
393
-    }
394
-
395
-    /**
396
-     * Gets the user's email address
397
-     * @return string
398
-     */
399
-    public function getEmail()
400
-    {
401
-        return $this->email;
402
-    }
403
-
404
-    /**
405
-     * Sets the user's email address
406
-     *
407
-     * @param string $email
408
-     */
409
-    public function setEmail($email)
410
-    {
411
-        $this->email = $email;
412
-    }
413
-
414
-    /**
415
-     * Sets the user's password
416
-     *
417
-     * @param string $password the plaintext password
418
-     *
419
-     * @category Security-Critical
420
-     */
421
-    public function setPassword($password)
422
-    {
423
-        $this->password = AuthUtility::encryptPassword($password);
424
-    }
425
-
426
-    /**
427
-     * Gets the status (User, Admin, Suspended, etc - excludes checkuser) of the user.
428
-     * @return string
429
-     */
430
-    public function getStatus()
431
-    {
432
-        return $this->status;
433
-    }
434
-
435
-    /**
436
-     * @param string $status
437
-     */
438
-    public function setStatus($status)
439
-    {
440
-        $this->status = $status;
441
-    }
442
-
443
-    /**
444
-     * Gets the user's on-wiki name
445
-     * @return string
446
-     */
447
-    public function getOnWikiName()
448
-    {
449
-        if ($this->oauthaccesstoken !== null) {
450
-            try {
451
-                return $this->getOAuthOnWikiName();
452
-            }
453
-            catch (Exception $ex) {
454
-                // urm.. log this?
455
-                return $this->onwikiname;
456
-            }
457
-        }
458
-
459
-        return $this->onwikiname;
460
-    }
461
-
462
-    /**
463
-     * This is probably NOT the function you want!
464
-     *
465
-     * Take a look at getOnWikiName() instead.
466
-     * @return string
467
-     */
468
-    public function getStoredOnWikiName()
469
-    {
470
-        return $this->onwikiname;
471
-    }
472
-
473
-    /**
474
-     * Sets the user's on-wiki name
475
-     *
476
-     * This can have interesting side-effects with OAuth.
477
-     *
478
-     * @param string $onWikiName
479
-     */
480
-    public function setOnWikiName($onWikiName)
481
-    {
482
-        $this->onwikiname = $onWikiName;
483
-    }
484
-
485
-    /**
486
-     * Gets the welcome signature
487
-     * @return string
488
-     */
489
-    public function getWelcomeSig()
490
-    {
491
-        return $this->welcome_sig;
492
-    }
493
-
494
-    /**
495
-     * Sets the welcome signature
496
-     *
497
-     * @param string $welcomeSig
498
-     */
499
-    public function setWelcomeSig($welcomeSig)
500
-    {
501
-        $this->welcome_sig = $welcomeSig;
502
-    }
503
-
504
-    /**
505
-     * Gets the last activity date for the user
506
-     *
507
-     * @return string
508
-     * @todo This should probably return an instance of DateTime
509
-     */
510
-    public function getLastActive()
511
-    {
512
-        return $this->lastactive;
513
-    }
514
-
515
-    /**
516
-     * Gets the user's forced logout status
517
-     *
518
-     * @return bool
519
-     */
520
-    public function getForceLogout()
521
-    {
522
-        return $this->forcelogout == 1;
523
-    }
524
-
525
-    /**
526
-     * Sets the user's forced logout status
527
-     *
528
-     * @param bool $forceLogout
529
-     */
530
-    public function setForceLogout($forceLogout)
531
-    {
532
-        $this->forcelogout = $forceLogout ? 1 : 0;
533
-    }
534
-
535
-    /**
536
-     * Returns the ID of the welcome template used.
537
-     * @return int
538
-     */
539
-    public function getWelcomeTemplate()
540
-    {
541
-        return $this->welcome_template;
542
-    }
543
-
544
-    /**
545
-     * Sets the ID of the welcome template used.
546
-     *
547
-     * @param int $welcomeTemplate
548
-     */
549
-    public function setWelcomeTemplate($welcomeTemplate)
550
-    {
551
-        $this->welcome_template = $welcomeTemplate;
552
-    }
553
-
554
-    /**
555
-     * Gets the user's abort preference
556
-     * @todo this is badly named too! Also a bool that's actually an int.
557
-     * @return int
558
-     */
559
-    public function getAbortPref()
560
-    {
561
-        return $this->abortpref;
562
-    }
563
-
564
-    /**
565
-     * Sets the user's abort preference
566
-     * @todo rename, retype, and re-comment.
567
-     *
568
-     * @param int $abortPreference
569
-     */
570
-    public function setAbortPref($abortPreference)
571
-    {
572
-        $this->abortpref = $abortPreference;
573
-    }
574
-
575
-    /**
576
-     * Gets the user's confirmation diff. Unused if OAuth is in use.
577
-     * @return int the diff ID
578
-     */
579
-    public function getConfirmationDiff()
580
-    {
581
-        return $this->confirmationdiff;
582
-    }
583
-
584
-    /**
585
-     * Sets the user's confirmation diff.
586
-     *
587
-     * @param int $confirmationDiff
588
-     */
589
-    public function setConfirmationDiff($confirmationDiff)
590
-    {
591
-        $this->confirmationdiff = $confirmationDiff;
592
-    }
593
-
594
-    /**
595
-     * Gets the users' email signature used on outbound mail.
596
-     * @todo rename me!
597
-     * @return string
598
-     */
599
-    public function getEmailSig()
600
-    {
601
-        return $this->emailsig;
602
-    }
603
-
604
-    /**
605
-     * Sets the user's email signature for outbound mail.
606
-     *
607
-     * @param string $emailSignature
608
-     */
609
-    public function setEmailSig($emailSignature)
610
-    {
611
-        $this->emailsig = $emailSignature;
612
-    }
613
-
614
-    /**
615
-     * Gets the user's OAuth request token.
616
-     *
617
-     * @todo move me to a collaborator.
618
-     * @return null|string
619
-     */
620
-    public function getOAuthRequestToken()
621
-    {
622
-        return $this->oauthrequesttoken;
623
-    }
624
-
625
-    /**
626
-     * Sets the user's OAuth request token
627
-     * @todo move me to a collaborator
628
-     *
629
-     * @param string $oAuthRequestToken
630
-     */
631
-    public function setOAuthRequestToken($oAuthRequestToken)
632
-    {
633
-        $this->oauthrequesttoken = $oAuthRequestToken;
634
-    }
635
-
636
-    /**
637
-     * Gets the users OAuth request secret
638
-     * @category Security-Critical
639
-     * @todo     move me to a collaborator
640
-     * @return null|string
641
-     */
642
-    public function getOAuthRequestSecret()
643
-    {
644
-        return $this->oauthrequestsecret;
645
-    }
646
-
647
-    /**
648
-     * Sets the user's OAuth request secret
649
-     * @todo move me to a collaborator
650
-     *
651
-     * @param string $oAuthRequestSecret
652
-     */
653
-    public function setOAuthRequestSecret($oAuthRequestSecret)
654
-    {
655
-        $this->oauthrequestsecret = $oAuthRequestSecret;
656
-    }
657
-
658
-    /**
659
-     * Gets the user's access token
660
-     * @category Security-Critical
661
-     * @todo     move me to a collaborator
662
-     * @return null|string
663
-     */
664
-    public function getOAuthAccessToken()
665
-    {
666
-        return $this->oauthaccesstoken;
667
-    }
668
-
669
-    /**
670
-     * Sets the user's access token
671
-     * @todo move me to a collaborator
672
-     *
673
-     * @param string $oAuthAccessToken
674
-     */
675
-    public function setOAuthAccessToken($oAuthAccessToken)
676
-    {
677
-        $this->oauthaccesstoken = $oAuthAccessToken;
678
-    }
679
-
680
-    /**
681
-     * Gets the user's OAuth access secret
682
-     * @category Security-Critical
683
-     * @todo     move me to a collaborator
684
-     * @return null|string
685
-     */
686
-    public function getOAuthAccessSecret()
687
-    {
688
-        return $this->oauthaccesssecret;
689
-    }
690
-
691
-    /**
692
-     * Sets the user's OAuth access secret
693
-     * @todo move me to a collaborator
694
-     *
695
-     * @param string $oAuthAccessSecret
696
-     */
697
-    public function setOAuthAccessSecret($oAuthAccessSecret)
698
-    {
699
-        $this->oauthaccesssecret = $oAuthAccessSecret;
700
-    }
701
-
702
-    #endregion
703
-
704
-    #region user access checks
705
-
706
-    public function isActive()
707
-    {
708
-        return $this->status == self::STATUS_ACTIVE;
709
-    }
710
-
711
-    /**
712
-     * Tests if the user is identified
713
-     *
714
-     * @param IdentificationVerifier $iv
715
-     *
716
-     * @return bool
717
-     * @todo     Figure out what on earth is going on with PDO's typecasting here.  Apparently, it returns string("0") for
718
-     *       the force-unidentified case, and int(1) for the identified case?!  This is quite ugly, but probably needed
719
-     *       to play it safe for now.
720
-     * @category Security-Critical
721
-     */
722
-    public function isIdentified(IdentificationVerifier $iv)
723
-    {
724
-        if ($this->forceidentified === 0 || $this->forceidentified === "0") {
725
-            // User forced to unidentified in the database.
726
-            return false;
727
-        }
728
-        elseif ($this->forceidentified === 1 || $this->forceidentified === "1") {
729
-            // User forced to identified in the database.
730
-            return true;
731
-        }
732
-        else {
733
-            // User not forced to any particular identified status; consult IdentificationVerifier
734
-            return $iv->isUserIdentified($this->getOnWikiName());
735
-        }
736
-    }
737
-
738
-    /**
739
-     * Tests if the user is suspended
740
-     * @return bool
741
-     * @category Security-Critical
742
-     */
743
-    public function isSuspended()
744
-    {
745
-        return $this->status == self::STATUS_SUSPENDED;
746
-    }
747
-
748
-    /**
749
-     * Tests if the user is new
750
-     * @return bool
751
-     * @category Security-Critical
752
-     */
753
-    public function isNewUser()
754
-    {
755
-        return $this->status == self::STATUS_NEW;
756
-    }
757
-
758
-    /**
759
-     * Tests if the user has been declined access to the tool
760
-     * @return bool
761
-     * @category Security-Critical
762
-     */
763
-    public function isDeclined()
764
-    {
765
-        return $this->status == self::STATUS_DECLINED;
766
-    }
767
-
768
-    /**
769
-     * Tests if the user is the community user
770
-     *
771
-     * @todo     decide if this means logged out. I think it usually does.
772
-     * @return bool
773
-     * @category Security-Critical
774
-     */
775
-    public function isCommunityUser()
776
-    {
777
-        return false;
778
-    }
779
-
780
-    #endregion 
781
-
782
-    #region OAuth
783
-
784
-    /**
785
-     * @todo     move me to a collaborator
786
-     *
787
-     * @param bool $useCached
788
-     *
789
-     * @return mixed|null
790
-     * @category Security-Critical
791
-     */
792
-    public function getOAuthIdentity($useCached = false)
793
-    {
794
-        if ($this->oauthaccesstoken === null) {
795
-            $this->clearOAuthData();
796
-        }
797
-
798
-        global $oauthConsumerToken, $oauthMediaWikiCanonicalServer;
799
-
800
-        if ($this->oauthidentitycache == null) {
801
-            $this->identityCache = null;
802
-        }
803
-        else {
804
-            $this->identityCache = unserialize($this->oauthidentitycache);
805
-        }
806
-
807
-        // check the cache
808
-        if (
809
-            $this->identityCache != null &&
810
-            $this->identityCache->aud == $oauthConsumerToken &&
811
-            $this->identityCache->iss == $oauthMediaWikiCanonicalServer
812
-        ) {
813
-            if (
814
-                $useCached || (
815
-                    DateTime::createFromFormat("U", $this->identityCache->iat) < new DateTime() &&
816
-                    DateTime::createFromFormat("U", $this->identityCache->exp) > new DateTime()
817
-                )
818
-            ) {
819
-                // Use cached value - it's either valid or we don't care.
820
-                return $this->identityCache;
821
-            }
822
-            else {
823
-                // Cache expired and not forcing use of cached value
824
-                $this->getIdentityCache();
825
-
826
-                return $this->identityCache;
827
-            }
828
-        }
829
-        else {
830
-            // Cache isn't ours or doesn't exist
831
-            $this->getIdentityCache();
832
-
833
-            return $this->identityCache;
834
-        }
835
-    }
836
-
837
-    /**
838
-     * @todo     move me to a collaborator
839
-     *
840
-     * @param mixed $useCached Set to false for everything where up-to-date data is important.
841
-     *
842
-     * @return mixed
843
-     * @category Security-Critical
844
-     */
845
-    private function getOAuthOnWikiName($useCached = false)
846
-    {
847
-        $identity = $this->getOAuthIdentity($useCached);
848
-        if ($identity !== null) {
849
-            return $identity->username;
850
-        }
851
-
852
-        return false;
853
-    }
854
-
855
-    /**
856
-     * @return bool
857
-     * @todo move me to a collaborator
858
-     */
859
-    public function isOAuthLinked()
860
-    {
861
-        if ($this->onwikiname === "##OAUTH##") {
862
-            return true; // special value. If an account must be oauth linked, this is true.
863
-        }
864
-
865
-        return $this->oauthaccesstoken !== null;
866
-    }
867
-
868
-    /**
869
-     * @return null
870
-     * @todo move me to a collaborator
871
-     */
872
-    public function clearOAuthData()
873
-    {
874
-        $this->identityCache = null;
875
-        $this->oauthidentitycache = null;
876
-        $clearCacheQuery = "UPDATE user SET oauthidentitycache = NULL WHERE id = :id;";
877
-        $this->dbObject->prepare($clearCacheQuery)->execute(array(":id" => $this->id));
878
-
879
-        return null;
880
-    }
881
-
882
-    /**
883
-     * @throws Exception
884
-     * @todo     move me to a collaborator
885
-     * @category Security-Critical
886
-     */
887
-    private function getIdentityCache()
888
-    {
889
-        /** @var IOAuthHelper $oauthHelper */
890
-        global $oauthHelper;
891
-
892
-        try {
893
-            $this->identityCache = $oauthHelper->getIdentityTicket($this->oauthaccesstoken, $this->oauthaccesssecret);
894
-
895
-            $this->oauthidentitycache = serialize($this->identityCache);
896
-            $this->dbObject->prepare("UPDATE user SET oauthidentitycache = :identity WHERE id = :id;")
897
-                ->execute(array(":id" => $this->id, ":identity" => $this->oauthidentitycache));
898
-        }
899
-        catch (UnexpectedValueException $ex) {
900
-            $this->identityCache = null;
901
-            $this->oauthidentitycache = null;
902
-            $this->dbObject->prepare("UPDATE user SET oauthidentitycache = NULL WHERE id = :id;")
903
-                ->execute(array(":id" => $this->id));
904
-
905
-            SessionAlert::warning("OAuth error getting identity from MediaWiki: " . $ex->getMessage());
906
-        }
907
-    }
908
-
909
-    /**
910
-     * @return bool
911
-     * @todo move me to a collaborator
912
-     */
913
-    public function oauthCanUse()
914
-    {
915
-        try {
916
-            return in_array('useoauth', $this->getOAuthIdentity()->grants);
917
-        }
918
-        catch (Exception $ex) {
919
-            return false;
920
-        }
921
-    }
922
-
923
-    /**
924
-     * @return bool
925
-     * @todo move me to a collaborator
926
-     */
927
-    public function oauthCanEdit()
928
-    {
929
-        try {
930
-            return in_array('useoauth', $this->getOAuthIdentity()->grants)
931
-            && in_array('createeditmovepage', $this->getOAuthIdentity()->grants)
932
-            && in_array('createtalk', $this->getOAuthIdentity()->rights)
933
-            && in_array('edit', $this->getOAuthIdentity()->rights)
934
-            && in_array('writeapi', $this->getOAuthIdentity()->rights);
935
-        }
936
-        catch (Exception $ex) {
937
-            return false;
938
-        }
939
-    }
940
-
941
-    /**
942
-     * @return bool
943
-     * @todo move me to a collaborator
944
-     */
945
-    public function oauthCanCreateAccount()
946
-    {
947
-        try {
948
-            return in_array('useoauth', $this->getOAuthIdentity()->grants)
949
-            && in_array('createaccount', $this->getOAuthIdentity()->grants)
950
-            && in_array('createaccount', $this->getOAuthIdentity()->rights)
951
-            && in_array('writeapi', $this->getOAuthIdentity()->rights);
952
-        }
953
-        catch (Exception $ex) {
954
-            return false;
955
-        }
956
-    }
957
-
958
-    /**
959
-     * @return bool
960
-     * @todo     move me to a collaborator
961
-     * @category Security-Critical
962
-     */
963
-    protected function oauthCanCheckUser()
964
-    {
965
-        if (!$this->isOAuthLinked()) {
966
-            return false;
967
-        }
968
-
969
-        try {
970
-            $identity = $this->getOAuthIdentity();
971
-
972
-            return in_array('checkuser', $identity->rights);
973
-        }
974
-        catch (Exception $ex) {
975
-            return false;
976
-        }
977
-    }
978
-
979
-    #endregion
980
-
981
-    /**
982
-     * Gets a hash of data for the user to reset their password with.
983
-     * @category Security-Critical
984
-     * @return string
985
-     */
986
-    public function getForgottenPasswordHash()
987
-    {
988
-        return md5($this->username . $this->email . $this->welcome_template . $this->id . $this->password);
989
-    }
990
-
991
-    /**
992
-     * Gets the approval date of the user
993
-     * @return DateTime|false
994
-     */
995
-    public function getApprovalDate()
996
-    {
997
-        $query = $this->dbObject->prepare(<<<SQL
309
+			);
310
+			$statement->bindValue(":forceidentified", $this->forceidentified);
311
+
312
+			$statement->bindValue(':id', $this->id);
313
+			$statement->bindValue(':updateversion', $this->updateversion);
314
+
315
+			$statement->bindValue(':username', $this->username);
316
+			$statement->bindValue(':email', $this->email);
317
+			$statement->bindValue(':password', $this->password);
318
+			$statement->bindValue(':status', $this->status);
319
+			$statement->bindValue(':onwikiname', $this->onwikiname);
320
+			$statement->bindValue(':welcome_sig', $this->welcome_sig);
321
+			$statement->bindValue(':lastactive', $this->lastactive);
322
+			$statement->bindValue(':forcelogout', $this->forcelogout);
323
+			$statement->bindValue(':forceidentified', $this->forceidentified);
324
+			$statement->bindValue(':welcome_template', $this->welcome_template);
325
+			$statement->bindValue(':abortpref', $this->abortpref);
326
+			$statement->bindValue(':confirmationdiff', $this->confirmationdiff);
327
+			$statement->bindValue(':emailsig', $this->emailsig);
328
+			$statement->bindValue(':ort', $this->oauthrequesttoken);
329
+			$statement->bindValue(':ors', $this->oauthrequestsecret);
330
+			$statement->bindValue(':oat', $this->oauthaccesstoken);
331
+			$statement->bindValue(':oas', $this->oauthaccesssecret);
332
+
333
+			if (!$statement->execute()) {
334
+				throw new Exception($statement->errorInfo());
335
+			}
336
+
337
+			if ($statement->rowCount() !== 1) {
338
+				throw new OptimisticLockFailedException();
339
+			}
340
+
341
+			$this->updateversion++;
342
+		}
343
+	}
344
+
345
+	/**
346
+	 * Authenticates the user with the supplied password
347
+	 *
348
+	 * @param string $password
349
+	 *
350
+	 * @return bool
351
+	 * @throws Exception
352
+	 * @category Security-Critical
353
+	 */
354
+	public function authenticate($password)
355
+	{
356
+		$result = AuthUtility::testCredentials($password, $this->password);
357
+
358
+		if ($result === true) {
359
+			// password version is out of date, update it.
360
+			if (!AuthUtility::isCredentialVersionLatest($this->password)) {
361
+				$this->password = AuthUtility::encryptPassword($password);
362
+				$this->save();
363
+			}
364
+		}
365
+
366
+		return $result;
367
+	}
368
+
369
+	#region properties
370
+
371
+	/**
372
+	 * Gets the tool username
373
+	 * @return string
374
+	 */
375
+	public function getUsername()
376
+	{
377
+		return $this->username;
378
+	}
379
+
380
+	/**
381
+	 * Sets the tool username
382
+	 *
383
+	 * @param string $username
384
+	 */
385
+	public function setUsername($username)
386
+	{
387
+		$this->username = $username;
388
+
389
+		// If this isn't a brand new user, then it's a rename, force the logout
390
+		if (!$this->isNew()) {
391
+			$this->forcelogout = 1;
392
+		}
393
+	}
394
+
395
+	/**
396
+	 * Gets the user's email address
397
+	 * @return string
398
+	 */
399
+	public function getEmail()
400
+	{
401
+		return $this->email;
402
+	}
403
+
404
+	/**
405
+	 * Sets the user's email address
406
+	 *
407
+	 * @param string $email
408
+	 */
409
+	public function setEmail($email)
410
+	{
411
+		$this->email = $email;
412
+	}
413
+
414
+	/**
415
+	 * Sets the user's password
416
+	 *
417
+	 * @param string $password the plaintext password
418
+	 *
419
+	 * @category Security-Critical
420
+	 */
421
+	public function setPassword($password)
422
+	{
423
+		$this->password = AuthUtility::encryptPassword($password);
424
+	}
425
+
426
+	/**
427
+	 * Gets the status (User, Admin, Suspended, etc - excludes checkuser) of the user.
428
+	 * @return string
429
+	 */
430
+	public function getStatus()
431
+	{
432
+		return $this->status;
433
+	}
434
+
435
+	/**
436
+	 * @param string $status
437
+	 */
438
+	public function setStatus($status)
439
+	{
440
+		$this->status = $status;
441
+	}
442
+
443
+	/**
444
+	 * Gets the user's on-wiki name
445
+	 * @return string
446
+	 */
447
+	public function getOnWikiName()
448
+	{
449
+		if ($this->oauthaccesstoken !== null) {
450
+			try {
451
+				return $this->getOAuthOnWikiName();
452
+			}
453
+			catch (Exception $ex) {
454
+				// urm.. log this?
455
+				return $this->onwikiname;
456
+			}
457
+		}
458
+
459
+		return $this->onwikiname;
460
+	}
461
+
462
+	/**
463
+	 * This is probably NOT the function you want!
464
+	 *
465
+	 * Take a look at getOnWikiName() instead.
466
+	 * @return string
467
+	 */
468
+	public function getStoredOnWikiName()
469
+	{
470
+		return $this->onwikiname;
471
+	}
472
+
473
+	/**
474
+	 * Sets the user's on-wiki name
475
+	 *
476
+	 * This can have interesting side-effects with OAuth.
477
+	 *
478
+	 * @param string $onWikiName
479
+	 */
480
+	public function setOnWikiName($onWikiName)
481
+	{
482
+		$this->onwikiname = $onWikiName;
483
+	}
484
+
485
+	/**
486
+	 * Gets the welcome signature
487
+	 * @return string
488
+	 */
489
+	public function getWelcomeSig()
490
+	{
491
+		return $this->welcome_sig;
492
+	}
493
+
494
+	/**
495
+	 * Sets the welcome signature
496
+	 *
497
+	 * @param string $welcomeSig
498
+	 */
499
+	public function setWelcomeSig($welcomeSig)
500
+	{
501
+		$this->welcome_sig = $welcomeSig;
502
+	}
503
+
504
+	/**
505
+	 * Gets the last activity date for the user
506
+	 *
507
+	 * @return string
508
+	 * @todo This should probably return an instance of DateTime
509
+	 */
510
+	public function getLastActive()
511
+	{
512
+		return $this->lastactive;
513
+	}
514
+
515
+	/**
516
+	 * Gets the user's forced logout status
517
+	 *
518
+	 * @return bool
519
+	 */
520
+	public function getForceLogout()
521
+	{
522
+		return $this->forcelogout == 1;
523
+	}
524
+
525
+	/**
526
+	 * Sets the user's forced logout status
527
+	 *
528
+	 * @param bool $forceLogout
529
+	 */
530
+	public function setForceLogout($forceLogout)
531
+	{
532
+		$this->forcelogout = $forceLogout ? 1 : 0;
533
+	}
534
+
535
+	/**
536
+	 * Returns the ID of the welcome template used.
537
+	 * @return int
538
+	 */
539
+	public function getWelcomeTemplate()
540
+	{
541
+		return $this->welcome_template;
542
+	}
543
+
544
+	/**
545
+	 * Sets the ID of the welcome template used.
546
+	 *
547
+	 * @param int $welcomeTemplate
548
+	 */
549
+	public function setWelcomeTemplate($welcomeTemplate)
550
+	{
551
+		$this->welcome_template = $welcomeTemplate;
552
+	}
553
+
554
+	/**
555
+	 * Gets the user's abort preference
556
+	 * @todo this is badly named too! Also a bool that's actually an int.
557
+	 * @return int
558
+	 */
559
+	public function getAbortPref()
560
+	{
561
+		return $this->abortpref;
562
+	}
563
+
564
+	/**
565
+	 * Sets the user's abort preference
566
+	 * @todo rename, retype, and re-comment.
567
+	 *
568
+	 * @param int $abortPreference
569
+	 */
570
+	public function setAbortPref($abortPreference)
571
+	{
572
+		$this->abortpref = $abortPreference;
573
+	}
574
+
575
+	/**
576
+	 * Gets the user's confirmation diff. Unused if OAuth is in use.
577
+	 * @return int the diff ID
578
+	 */
579
+	public function getConfirmationDiff()
580
+	{
581
+		return $this->confirmationdiff;
582
+	}
583
+
584
+	/**
585
+	 * Sets the user's confirmation diff.
586
+	 *
587
+	 * @param int $confirmationDiff
588
+	 */
589
+	public function setConfirmationDiff($confirmationDiff)
590
+	{
591
+		$this->confirmationdiff = $confirmationDiff;
592
+	}
593
+
594
+	/**
595
+	 * Gets the users' email signature used on outbound mail.
596
+	 * @todo rename me!
597
+	 * @return string
598
+	 */
599
+	public function getEmailSig()
600
+	{
601
+		return $this->emailsig;
602
+	}
603
+
604
+	/**
605
+	 * Sets the user's email signature for outbound mail.
606
+	 *
607
+	 * @param string $emailSignature
608
+	 */
609
+	public function setEmailSig($emailSignature)
610
+	{
611
+		$this->emailsig = $emailSignature;
612
+	}
613
+
614
+	/**
615
+	 * Gets the user's OAuth request token.
616
+	 *
617
+	 * @todo move me to a collaborator.
618
+	 * @return null|string
619
+	 */
620
+	public function getOAuthRequestToken()
621
+	{
622
+		return $this->oauthrequesttoken;
623
+	}
624
+
625
+	/**
626
+	 * Sets the user's OAuth request token
627
+	 * @todo move me to a collaborator
628
+	 *
629
+	 * @param string $oAuthRequestToken
630
+	 */
631
+	public function setOAuthRequestToken($oAuthRequestToken)
632
+	{
633
+		$this->oauthrequesttoken = $oAuthRequestToken;
634
+	}
635
+
636
+	/**
637
+	 * Gets the users OAuth request secret
638
+	 * @category Security-Critical
639
+	 * @todo     move me to a collaborator
640
+	 * @return null|string
641
+	 */
642
+	public function getOAuthRequestSecret()
643
+	{
644
+		return $this->oauthrequestsecret;
645
+	}
646
+
647
+	/**
648
+	 * Sets the user's OAuth request secret
649
+	 * @todo move me to a collaborator
650
+	 *
651
+	 * @param string $oAuthRequestSecret
652
+	 */
653
+	public function setOAuthRequestSecret($oAuthRequestSecret)
654
+	{
655
+		$this->oauthrequestsecret = $oAuthRequestSecret;
656
+	}
657
+
658
+	/**
659
+	 * Gets the user's access token
660
+	 * @category Security-Critical
661
+	 * @todo     move me to a collaborator
662
+	 * @return null|string
663
+	 */
664
+	public function getOAuthAccessToken()
665
+	{
666
+		return $this->oauthaccesstoken;
667
+	}
668
+
669
+	/**
670
+	 * Sets the user's access token
671
+	 * @todo move me to a collaborator
672
+	 *
673
+	 * @param string $oAuthAccessToken
674
+	 */
675
+	public function setOAuthAccessToken($oAuthAccessToken)
676
+	{
677
+		$this->oauthaccesstoken = $oAuthAccessToken;
678
+	}
679
+
680
+	/**
681
+	 * Gets the user's OAuth access secret
682
+	 * @category Security-Critical
683
+	 * @todo     move me to a collaborator
684
+	 * @return null|string
685
+	 */
686
+	public function getOAuthAccessSecret()
687
+	{
688
+		return $this->oauthaccesssecret;
689
+	}
690
+
691
+	/**
692
+	 * Sets the user's OAuth access secret
693
+	 * @todo move me to a collaborator
694
+	 *
695
+	 * @param string $oAuthAccessSecret
696
+	 */
697
+	public function setOAuthAccessSecret($oAuthAccessSecret)
698
+	{
699
+		$this->oauthaccesssecret = $oAuthAccessSecret;
700
+	}
701
+
702
+	#endregion
703
+
704
+	#region user access checks
705
+
706
+	public function isActive()
707
+	{
708
+		return $this->status == self::STATUS_ACTIVE;
709
+	}
710
+
711
+	/**
712
+	 * Tests if the user is identified
713
+	 *
714
+	 * @param IdentificationVerifier $iv
715
+	 *
716
+	 * @return bool
717
+	 * @todo     Figure out what on earth is going on with PDO's typecasting here.  Apparently, it returns string("0") for
718
+	 *       the force-unidentified case, and int(1) for the identified case?!  This is quite ugly, but probably needed
719
+	 *       to play it safe for now.
720
+	 * @category Security-Critical
721
+	 */
722
+	public function isIdentified(IdentificationVerifier $iv)
723
+	{
724
+		if ($this->forceidentified === 0 || $this->forceidentified === "0") {
725
+			// User forced to unidentified in the database.
726
+			return false;
727
+		}
728
+		elseif ($this->forceidentified === 1 || $this->forceidentified === "1") {
729
+			// User forced to identified in the database.
730
+			return true;
731
+		}
732
+		else {
733
+			// User not forced to any particular identified status; consult IdentificationVerifier
734
+			return $iv->isUserIdentified($this->getOnWikiName());
735
+		}
736
+	}
737
+
738
+	/**
739
+	 * Tests if the user is suspended
740
+	 * @return bool
741
+	 * @category Security-Critical
742
+	 */
743
+	public function isSuspended()
744
+	{
745
+		return $this->status == self::STATUS_SUSPENDED;
746
+	}
747
+
748
+	/**
749
+	 * Tests if the user is new
750
+	 * @return bool
751
+	 * @category Security-Critical
752
+	 */
753
+	public function isNewUser()
754
+	{
755
+		return $this->status == self::STATUS_NEW;
756
+	}
757
+
758
+	/**
759
+	 * Tests if the user has been declined access to the tool
760
+	 * @return bool
761
+	 * @category Security-Critical
762
+	 */
763
+	public function isDeclined()
764
+	{
765
+		return $this->status == self::STATUS_DECLINED;
766
+	}
767
+
768
+	/**
769
+	 * Tests if the user is the community user
770
+	 *
771
+	 * @todo     decide if this means logged out. I think it usually does.
772
+	 * @return bool
773
+	 * @category Security-Critical
774
+	 */
775
+	public function isCommunityUser()
776
+	{
777
+		return false;
778
+	}
779
+
780
+	#endregion 
781
+
782
+	#region OAuth
783
+
784
+	/**
785
+	 * @todo     move me to a collaborator
786
+	 *
787
+	 * @param bool $useCached
788
+	 *
789
+	 * @return mixed|null
790
+	 * @category Security-Critical
791
+	 */
792
+	public function getOAuthIdentity($useCached = false)
793
+	{
794
+		if ($this->oauthaccesstoken === null) {
795
+			$this->clearOAuthData();
796
+		}
797
+
798
+		global $oauthConsumerToken, $oauthMediaWikiCanonicalServer;
799
+
800
+		if ($this->oauthidentitycache == null) {
801
+			$this->identityCache = null;
802
+		}
803
+		else {
804
+			$this->identityCache = unserialize($this->oauthidentitycache);
805
+		}
806
+
807
+		// check the cache
808
+		if (
809
+			$this->identityCache != null &&
810
+			$this->identityCache->aud == $oauthConsumerToken &&
811
+			$this->identityCache->iss == $oauthMediaWikiCanonicalServer
812
+		) {
813
+			if (
814
+				$useCached || (
815
+					DateTime::createFromFormat("U", $this->identityCache->iat) < new DateTime() &&
816
+					DateTime::createFromFormat("U", $this->identityCache->exp) > new DateTime()
817
+				)
818
+			) {
819
+				// Use cached value - it's either valid or we don't care.
820
+				return $this->identityCache;
821
+			}
822
+			else {
823
+				// Cache expired and not forcing use of cached value
824
+				$this->getIdentityCache();
825
+
826
+				return $this->identityCache;
827
+			}
828
+		}
829
+		else {
830
+			// Cache isn't ours or doesn't exist
831
+			$this->getIdentityCache();
832
+
833
+			return $this->identityCache;
834
+		}
835
+	}
836
+
837
+	/**
838
+	 * @todo     move me to a collaborator
839
+	 *
840
+	 * @param mixed $useCached Set to false for everything where up-to-date data is important.
841
+	 *
842
+	 * @return mixed
843
+	 * @category Security-Critical
844
+	 */
845
+	private function getOAuthOnWikiName($useCached = false)
846
+	{
847
+		$identity = $this->getOAuthIdentity($useCached);
848
+		if ($identity !== null) {
849
+			return $identity->username;
850
+		}
851
+
852
+		return false;
853
+	}
854
+
855
+	/**
856
+	 * @return bool
857
+	 * @todo move me to a collaborator
858
+	 */
859
+	public function isOAuthLinked()
860
+	{
861
+		if ($this->onwikiname === "##OAUTH##") {
862
+			return true; // special value. If an account must be oauth linked, this is true.
863
+		}
864
+
865
+		return $this->oauthaccesstoken !== null;
866
+	}
867
+
868
+	/**
869
+	 * @return null
870
+	 * @todo move me to a collaborator
871
+	 */
872
+	public function clearOAuthData()
873
+	{
874
+		$this->identityCache = null;
875
+		$this->oauthidentitycache = null;
876
+		$clearCacheQuery = "UPDATE user SET oauthidentitycache = NULL WHERE id = :id;";
877
+		$this->dbObject->prepare($clearCacheQuery)->execute(array(":id" => $this->id));
878
+
879
+		return null;
880
+	}
881
+
882
+	/**
883
+	 * @throws Exception
884
+	 * @todo     move me to a collaborator
885
+	 * @category Security-Critical
886
+	 */
887
+	private function getIdentityCache()
888
+	{
889
+		/** @var IOAuthHelper $oauthHelper */
890
+		global $oauthHelper;
891
+
892
+		try {
893
+			$this->identityCache = $oauthHelper->getIdentityTicket($this->oauthaccesstoken, $this->oauthaccesssecret);
894
+
895
+			$this->oauthidentitycache = serialize($this->identityCache);
896
+			$this->dbObject->prepare("UPDATE user SET oauthidentitycache = :identity WHERE id = :id;")
897
+				->execute(array(":id" => $this->id, ":identity" => $this->oauthidentitycache));
898
+		}
899
+		catch (UnexpectedValueException $ex) {
900
+			$this->identityCache = null;
901
+			$this->oauthidentitycache = null;
902
+			$this->dbObject->prepare("UPDATE user SET oauthidentitycache = NULL WHERE id = :id;")
903
+				->execute(array(":id" => $this->id));
904
+
905
+			SessionAlert::warning("OAuth error getting identity from MediaWiki: " . $ex->getMessage());
906
+		}
907
+	}
908
+
909
+	/**
910
+	 * @return bool
911
+	 * @todo move me to a collaborator
912
+	 */
913
+	public function oauthCanUse()
914
+	{
915
+		try {
916
+			return in_array('useoauth', $this->getOAuthIdentity()->grants);
917
+		}
918
+		catch (Exception $ex) {
919
+			return false;
920
+		}
921
+	}
922
+
923
+	/**
924
+	 * @return bool
925
+	 * @todo move me to a collaborator
926
+	 */
927
+	public function oauthCanEdit()
928
+	{
929
+		try {
930
+			return in_array('useoauth', $this->getOAuthIdentity()->grants)
931
+			&& in_array('createeditmovepage', $this->getOAuthIdentity()->grants)
932
+			&& in_array('createtalk', $this->getOAuthIdentity()->rights)
933
+			&& in_array('edit', $this->getOAuthIdentity()->rights)
934
+			&& in_array('writeapi', $this->getOAuthIdentity()->rights);
935
+		}
936
+		catch (Exception $ex) {
937
+			return false;
938
+		}
939
+	}
940
+
941
+	/**
942
+	 * @return bool
943
+	 * @todo move me to a collaborator
944
+	 */
945
+	public function oauthCanCreateAccount()
946
+	{
947
+		try {
948
+			return in_array('useoauth', $this->getOAuthIdentity()->grants)
949
+			&& in_array('createaccount', $this->getOAuthIdentity()->grants)
950
+			&& in_array('createaccount', $this->getOAuthIdentity()->rights)
951
+			&& in_array('writeapi', $this->getOAuthIdentity()->rights);
952
+		}
953
+		catch (Exception $ex) {
954
+			return false;
955
+		}
956
+	}
957
+
958
+	/**
959
+	 * @return bool
960
+	 * @todo     move me to a collaborator
961
+	 * @category Security-Critical
962
+	 */
963
+	protected function oauthCanCheckUser()
964
+	{
965
+		if (!$this->isOAuthLinked()) {
966
+			return false;
967
+		}
968
+
969
+		try {
970
+			$identity = $this->getOAuthIdentity();
971
+
972
+			return in_array('checkuser', $identity->rights);
973
+		}
974
+		catch (Exception $ex) {
975
+			return false;
976
+		}
977
+	}
978
+
979
+	#endregion
980
+
981
+	/**
982
+	 * Gets a hash of data for the user to reset their password with.
983
+	 * @category Security-Critical
984
+	 * @return string
985
+	 */
986
+	public function getForgottenPasswordHash()
987
+	{
988
+		return md5($this->username . $this->email . $this->welcome_template . $this->id . $this->password);
989
+	}
990
+
991
+	/**
992
+	 * Gets the approval date of the user
993
+	 * @return DateTime|false
994
+	 */
995
+	public function getApprovalDate()
996
+	{
997
+		$query = $this->dbObject->prepare(<<<SQL
998 998
 			SELECT timestamp 
999 999
 			FROM log 
1000 1000
 			WHERE objectid = :userid
@@ -1003,12 +1003,12 @@  discard block
 block discarded – undo
1003 1003
 			ORDER BY id DESC 
1004 1004
 			LIMIT 1;
1005 1005
 SQL
1006
-        );
1007
-        $query->execute(array(":userid" => $this->id));
1006
+		);
1007
+		$query->execute(array(":userid" => $this->id));
1008 1008
 
1009
-        $data = DateTime::createFromFormat("Y-m-d H:i:s", $query->fetchColumn());
1010
-        $query->closeCursor();
1009
+		$data = DateTime::createFromFormat("Y-m-d H:i:s", $query->fetchColumn());
1010
+		$query->closeCursor();
1011 1011
 
1012
-        return $data;
1013
-    }
1012
+		return $data;
1013
+	}
1014 1014
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -902,7 +902,7 @@  discard block
 block discarded – undo
902 902
             $this->dbObject->prepare("UPDATE user SET oauthidentitycache = NULL WHERE id = :id;")
903 903
                 ->execute(array(":id" => $this->id));
904 904
 
905
-            SessionAlert::warning("OAuth error getting identity from MediaWiki: " . $ex->getMessage());
905
+            SessionAlert::warning("OAuth error getting identity from MediaWiki: ".$ex->getMessage());
906 906
         }
907 907
     }
908 908
 
@@ -985,7 +985,7 @@  discard block
 block discarded – undo
985 985
      */
986 986
     public function getForgottenPasswordHash()
987 987
     {
988
-        return md5($this->username . $this->email . $this->welcome_template . $this->id . $this->password);
988
+        return md5($this->username.$this->email.$this->welcome_template.$this->id.$this->password);
989 989
     }
990 990
 
991 991
     /**
Please login to merge, or discard this patch.
includes/DataObjects/Comment.php 1 patch
Indentation   +157 added lines, -157 removed lines patch added patch discarded remove patch
@@ -20,172 +20,172 @@
 block discarded – undo
20 20
  */
21 21
 class Comment extends DataObject
22 22
 {
23
-    private $time;
24
-    private $user;
25
-    private $comment;
26
-    private $visibility = "user";
27
-    private $request;
28
-
29
-    /**
30
-     * Retrieves all comments for a request, optionally filtered
31
-     *
32
-     * @param integer     $id      Request ID to search by
33
-     * @param PdoDatabase $database
34
-     * @param bool        $showAll True to show all comments, False to show only unprotected comments, and protected
35
-     *                             comments visible to $userId
36
-     * @param null|int    $userId  User to filter by
37
-     *
38
-     * @return Comment[]
39
-     */
40
-    public static function getForRequest($id, PdoDatabase $database, $showAll = false, $userId = null)
41
-    {
42
-        if ($showAll) {
43
-            $statement = $database->prepare('SELECT * FROM comment WHERE request = :target;');
44
-        }
45
-        else {
46
-            $statement = $database->prepare(<<<SQL
23
+	private $time;
24
+	private $user;
25
+	private $comment;
26
+	private $visibility = "user";
27
+	private $request;
28
+
29
+	/**
30
+	 * Retrieves all comments for a request, optionally filtered
31
+	 *
32
+	 * @param integer     $id      Request ID to search by
33
+	 * @param PdoDatabase $database
34
+	 * @param bool        $showAll True to show all comments, False to show only unprotected comments, and protected
35
+	 *                             comments visible to $userId
36
+	 * @param null|int    $userId  User to filter by
37
+	 *
38
+	 * @return Comment[]
39
+	 */
40
+	public static function getForRequest($id, PdoDatabase $database, $showAll = false, $userId = null)
41
+	{
42
+		if ($showAll) {
43
+			$statement = $database->prepare('SELECT * FROM comment WHERE request = :target;');
44
+		}
45
+		else {
46
+			$statement = $database->prepare(<<<SQL
47 47
 SELECT * FROM comment
48 48
 WHERE request = :target AND (visibility = 'user' OR user = :userid);
49 49
 SQL
50
-            );
51
-            $statement->bindValue(':userid', $userId);
52
-        }
53
-
54
-        $statement->bindValue(':target', $id);
55
-
56
-        $statement->execute();
57
-
58
-        $result = array();
59
-        /** @var Comment $v */
60
-        foreach ($statement->fetchAll(PDO::FETCH_CLASS, get_called_class()) as $v) {
61
-            $v->setDatabase($database);
62
-            $result[] = $v;
63
-        }
64
-
65
-        return $result;
66
-    }
67
-
68
-    /**
69
-     * @throws Exception
70
-     */
71
-    public function save()
72
-    {
73
-        if ($this->isNew()) {
74
-            // insert
75
-            $statement = $this->dbObject->prepare(<<<SQL
50
+			);
51
+			$statement->bindValue(':userid', $userId);
52
+		}
53
+
54
+		$statement->bindValue(':target', $id);
55
+
56
+		$statement->execute();
57
+
58
+		$result = array();
59
+		/** @var Comment $v */
60
+		foreach ($statement->fetchAll(PDO::FETCH_CLASS, get_called_class()) as $v) {
61
+			$v->setDatabase($database);
62
+			$result[] = $v;
63
+		}
64
+
65
+		return $result;
66
+	}
67
+
68
+	/**
69
+	 * @throws Exception
70
+	 */
71
+	public function save()
72
+	{
73
+		if ($this->isNew()) {
74
+			// insert
75
+			$statement = $this->dbObject->prepare(<<<SQL
76 76
 INSERT INTO comment ( time, user, comment, visibility, request )
77 77
 VALUES ( CURRENT_TIMESTAMP(), :user, :comment, :visibility, :request );
78 78
 SQL
79
-            );
80
-            $statement->bindValue(":user", $this->user);
81
-            $statement->bindValue(":comment", $this->comment);
82
-            $statement->bindValue(":visibility", $this->visibility);
83
-            $statement->bindValue(":request", $this->request);
84
-
85
-            if ($statement->execute()) {
86
-                $this->id = (int)$this->dbObject->lastInsertId();
87
-            }
88
-            else {
89
-                throw new Exception($statement->errorInfo());
90
-            }
91
-        }
92
-        else {
93
-            // update
94
-            $statement = $this->dbObject->prepare(<<<SQL
79
+			);
80
+			$statement->bindValue(":user", $this->user);
81
+			$statement->bindValue(":comment", $this->comment);
82
+			$statement->bindValue(":visibility", $this->visibility);
83
+			$statement->bindValue(":request", $this->request);
84
+
85
+			if ($statement->execute()) {
86
+				$this->id = (int)$this->dbObject->lastInsertId();
87
+			}
88
+			else {
89
+				throw new Exception($statement->errorInfo());
90
+			}
91
+		}
92
+		else {
93
+			// update
94
+			$statement = $this->dbObject->prepare(<<<SQL
95 95
 UPDATE comment
96 96
 SET comment = :comment, visibility = :visibility, updateversion = updateversion + 1
97 97
 WHERE id = :id AND updateversion = :updateversion
98 98
 LIMIT 1;
99 99
 SQL
100
-            );
101
-
102
-            $statement->bindValue(':id', $this->id);
103
-            $statement->bindValue(':updateversion', $this->updateversion);
104
-
105
-            $statement->bindValue(':comment', $this->comment);
106
-            $statement->bindValue(':visibility', $this->visibility);
107
-
108
-            if (!$statement->execute()) {
109
-                throw new Exception($statement->errorInfo());
110
-            }
111
-
112
-            if ($statement->rowCount() !== 1) {
113
-                throw new OptimisticLockFailedException();
114
-            }
115
-
116
-            $this->updateversion++;
117
-        }
118
-    }
119
-
120
-    /**
121
-     * @return DateTimeImmutable
122
-     */
123
-    public function getTime()
124
-    {
125
-        return new DateTimeImmutable($this->time);
126
-    }
127
-
128
-    /**
129
-     * @return int
130
-     */
131
-    public function getUser()
132
-    {
133
-        return $this->user;
134
-    }
135
-
136
-    /**
137
-     * @param int $user
138
-     */
139
-    public function setUser($user)
140
-    {
141
-        $this->user = $user;
142
-    }
143
-
144
-    /**
145
-     * @return string
146
-     */
147
-    public function getComment()
148
-    {
149
-        return $this->comment;
150
-    }
151
-
152
-    /**
153
-     * @param string $comment
154
-     */
155
-    public function setComment($comment)
156
-    {
157
-        $this->comment = $comment;
158
-    }
159
-
160
-    /**
161
-     * @return string
162
-     */
163
-    public function getVisibility()
164
-    {
165
-        return $this->visibility;
166
-    }
167
-
168
-    /**
169
-     * @param string $visibility
170
-     */
171
-    public function setVisibility($visibility)
172
-    {
173
-        $this->visibility = $visibility;
174
-    }
175
-
176
-    /**
177
-     * @return int
178
-     */
179
-    public function getRequest()
180
-    {
181
-        return $this->request;
182
-    }
183
-
184
-    /**
185
-     * @param int $request
186
-     */
187
-    public function setRequest($request)
188
-    {
189
-        $this->request = $request;
190
-    }
100
+			);
101
+
102
+			$statement->bindValue(':id', $this->id);
103
+			$statement->bindValue(':updateversion', $this->updateversion);
104
+
105
+			$statement->bindValue(':comment', $this->comment);
106
+			$statement->bindValue(':visibility', $this->visibility);
107
+
108
+			if (!$statement->execute()) {
109
+				throw new Exception($statement->errorInfo());
110
+			}
111
+
112
+			if ($statement->rowCount() !== 1) {
113
+				throw new OptimisticLockFailedException();
114
+			}
115
+
116
+			$this->updateversion++;
117
+		}
118
+	}
119
+
120
+	/**
121
+	 * @return DateTimeImmutable
122
+	 */
123
+	public function getTime()
124
+	{
125
+		return new DateTimeImmutable($this->time);
126
+	}
127
+
128
+	/**
129
+	 * @return int
130
+	 */
131
+	public function getUser()
132
+	{
133
+		return $this->user;
134
+	}
135
+
136
+	/**
137
+	 * @param int $user
138
+	 */
139
+	public function setUser($user)
140
+	{
141
+		$this->user = $user;
142
+	}
143
+
144
+	/**
145
+	 * @return string
146
+	 */
147
+	public function getComment()
148
+	{
149
+		return $this->comment;
150
+	}
151
+
152
+	/**
153
+	 * @param string $comment
154
+	 */
155
+	public function setComment($comment)
156
+	{
157
+		$this->comment = $comment;
158
+	}
159
+
160
+	/**
161
+	 * @return string
162
+	 */
163
+	public function getVisibility()
164
+	{
165
+		return $this->visibility;
166
+	}
167
+
168
+	/**
169
+	 * @param string $visibility
170
+	 */
171
+	public function setVisibility($visibility)
172
+	{
173
+		$this->visibility = $visibility;
174
+	}
175
+
176
+	/**
177
+	 * @return int
178
+	 */
179
+	public function getRequest()
180
+	{
181
+		return $this->request;
182
+	}
183
+
184
+	/**
185
+	 * @param int $request
186
+	 */
187
+	public function setRequest($request)
188
+	{
189
+		$this->request = $request;
190
+	}
191 191
 }
Please login to merge, or discard this patch.
includes/API/Actions/CountAction.php 1 patch
Indentation   +121 added lines, -121 removed lines patch added patch discarded remove patch
@@ -20,47 +20,47 @@  discard block
 block discarded – undo
20 20
  */
21 21
 class CountAction extends ApiPageBase implements IApiAction
22 22
 {
23
-    /**
24
-     * The target user
25
-     * @var User $user
26
-     */
27
-    private $user;
23
+	/**
24
+	 * The target user
25
+	 * @var User $user
26
+	 */
27
+	private $user;
28 28
 
29
-    public function executeApiAction(DOMElement $apiDocument)
30
-    {
31
-        $username = WebRequest::getString('user');
32
-        if ($username === null) {
33
-            throw new ApiException("Please specify a username");
34
-        }
29
+	public function executeApiAction(DOMElement $apiDocument)
30
+	{
31
+		$username = WebRequest::getString('user');
32
+		if ($username === null) {
33
+			throw new ApiException("Please specify a username");
34
+		}
35 35
 
36
-        $userElement = $this->document->createElement("user");
37
-        $userElement->setAttribute("name", $username);
38
-        $apiDocument->appendChild($userElement);
36
+		$userElement = $this->document->createElement("user");
37
+		$userElement->setAttribute("name", $username);
38
+		$apiDocument->appendChild($userElement);
39 39
 
40
-        $user = User::getByUsername($username, $this->getDatabase());
40
+		$user = User::getByUsername($username, $this->getDatabase());
41 41
 
42
-        if ($user === false) {
43
-            $userElement->setAttribute("missing", "true");
42
+		if ($user === false) {
43
+			$userElement->setAttribute("missing", "true");
44 44
 
45
-            return $apiDocument;
46
-        }
45
+			return $apiDocument;
46
+		}
47 47
 
48
-        $this->user = $user;
48
+		$this->user = $user;
49 49
 
50
-        $userElement->setAttribute("level", $this->user->getStatus());
51
-        $userElement->setAttribute("created", $this->getAccountsCreated());
50
+		$userElement->setAttribute("level", $this->user->getStatus());
51
+		$userElement->setAttribute("created", $this->getAccountsCreated());
52 52
 
53
-        $userElement->setAttribute("today", $this->getToday());
53
+		$userElement->setAttribute("today", $this->getToday());
54 54
 
55
-        // Let the IRC bot handle the result of this.
56
-        $this->fetchAdminData($userElement);
55
+		// Let the IRC bot handle the result of this.
56
+		$this->fetchAdminData($userElement);
57 57
 
58
-        return $apiDocument;
59
-    }
58
+		return $apiDocument;
59
+	}
60 60
 
61
-    private function getAccountsCreated()
62
-    {
63
-        $query = <<<QUERY
61
+	private function getAccountsCreated()
62
+	{
63
+		$query = <<<QUERY
64 64
         SELECT COUNT(*) AS count
65 65
         FROM log
66 66
             LEFT JOIN emailtemplate ON concat('Closed ', emailtemplate.id) = log.action
@@ -71,17 +71,17 @@  discard block
 block discarded – undo
71 71
             AND user.username = :username;
72 72
 QUERY;
73 73
 
74
-        $statement = $this->getDatabase()->prepare($query);
75
-        $statement->execute(array(":username" => $this->user->getUsername()));
76
-        $result = $statement->fetchColumn();
77
-        $statement->closeCursor();
74
+		$statement = $this->getDatabase()->prepare($query);
75
+		$statement->execute(array(":username" => $this->user->getUsername()));
76
+		$result = $statement->fetchColumn();
77
+		$statement->closeCursor();
78 78
 
79
-        return $result;
80
-    }
79
+		return $result;
80
+	}
81 81
 
82
-    private function getToday()
83
-    {
84
-        $query = <<<QUERY
82
+	private function getToday()
83
+	{
84
+		$query = <<<QUERY
85 85
         SELECT
86 86
             COUNT(*) AS count
87 87
         FROM log
@@ -93,99 +93,99 @@  discard block
 block discarded – undo
93 93
             AND user.username = :username;
94 94
 QUERY;
95 95
 
96
-        $statement = $this->getDatabase()->prepare($query);
97
-        $statement->bindValue(":username", $this->user->getUsername());
98
-        $statement->bindValue(":date", date('Y-m-d') . "%");
99
-        $statement->execute();
100
-        $today = $statement->fetchColumn();
101
-        $statement->closeCursor();
102
-
103
-        return $today;
104
-    }
105
-
106
-    private function fetchAdminData(DOMElement $userElement)
107
-    {
108
-        $query = "SELECT COUNT(*) AS count FROM log WHERE log.user = :userid AND log.action = :action;";
109
-
110
-        $statement = $this->getDatabase()->prepare($query);
111
-        $statement->bindValue(":userid", $this->user->getId());
112
-        $statement->bindValue(":action", "Suspended");
113
-        $statement->execute();
114
-        $sus = $statement->fetchColumn();
115
-        $userElement->setAttribute("suspended", $sus);
116
-        $statement->closeCursor();
117
-
118
-        $statement->bindValue(":action", "Promoted");
119
-        $statement->execute();
120
-        $pro = $statement->fetchColumn();
121
-        $userElement->setAttribute("promoted", $pro);
122
-        $statement->closeCursor();
123
-
124
-        $statement->bindValue(":action", "Approved");
125
-        $statement->execute();
126
-        $app = $statement->fetchColumn();
127
-        $userElement->setAttribute("approved", $app);
128
-        $statement->closeCursor();
129
-
130
-        $statement->bindValue(":action", "Demoted");
131
-        $statement->execute();
132
-        $dem = $statement->fetchColumn();
133
-        $userElement->setAttribute("demoted", $dem);
134
-        $statement->closeCursor();
135
-
136
-        $statement->bindValue(":action", "Declined");
137
-        $statement->execute();
138
-        $dec = $statement->fetchColumn();
139
-        $userElement->setAttribute("declined", $dec);
140
-        $statement->closeCursor();
141
-
142
-        $statement->bindValue(":action", "Renamed");
143
-        $statement->execute();
144
-        $rnc = $statement->fetchColumn();
145
-        $userElement->setAttribute("renamed", $rnc);
146
-        $statement->closeCursor();
147
-
148
-        $statement->bindValue(":action", "Edited");
149
-        $statement->execute();
150
-        $mec = $statement->fetchColumn();
151
-        $userElement->setAttribute("edited", $mec);
152
-        $statement->closeCursor();
153
-
154
-        $statement->bindValue(":action", "Prefchange");
155
-        $statement->execute();
156
-        $pcc = $statement->fetchColumn();
157
-        $userElement->setAttribute("prefchange", $pcc);
158
-        $statement->closeCursor();
159
-
160
-        // Combine all three actions affecting Welcome templates into one count.
161
-        $combinedquery = $this->getDatabase()->prepare(<<<SQL
96
+		$statement = $this->getDatabase()->prepare($query);
97
+		$statement->bindValue(":username", $this->user->getUsername());
98
+		$statement->bindValue(":date", date('Y-m-d') . "%");
99
+		$statement->execute();
100
+		$today = $statement->fetchColumn();
101
+		$statement->closeCursor();
102
+
103
+		return $today;
104
+	}
105
+
106
+	private function fetchAdminData(DOMElement $userElement)
107
+	{
108
+		$query = "SELECT COUNT(*) AS count FROM log WHERE log.user = :userid AND log.action = :action;";
109
+
110
+		$statement = $this->getDatabase()->prepare($query);
111
+		$statement->bindValue(":userid", $this->user->getId());
112
+		$statement->bindValue(":action", "Suspended");
113
+		$statement->execute();
114
+		$sus = $statement->fetchColumn();
115
+		$userElement->setAttribute("suspended", $sus);
116
+		$statement->closeCursor();
117
+
118
+		$statement->bindValue(":action", "Promoted");
119
+		$statement->execute();
120
+		$pro = $statement->fetchColumn();
121
+		$userElement->setAttribute("promoted", $pro);
122
+		$statement->closeCursor();
123
+
124
+		$statement->bindValue(":action", "Approved");
125
+		$statement->execute();
126
+		$app = $statement->fetchColumn();
127
+		$userElement->setAttribute("approved", $app);
128
+		$statement->closeCursor();
129
+
130
+		$statement->bindValue(":action", "Demoted");
131
+		$statement->execute();
132
+		$dem = $statement->fetchColumn();
133
+		$userElement->setAttribute("demoted", $dem);
134
+		$statement->closeCursor();
135
+
136
+		$statement->bindValue(":action", "Declined");
137
+		$statement->execute();
138
+		$dec = $statement->fetchColumn();
139
+		$userElement->setAttribute("declined", $dec);
140
+		$statement->closeCursor();
141
+
142
+		$statement->bindValue(":action", "Renamed");
143
+		$statement->execute();
144
+		$rnc = $statement->fetchColumn();
145
+		$userElement->setAttribute("renamed", $rnc);
146
+		$statement->closeCursor();
147
+
148
+		$statement->bindValue(":action", "Edited");
149
+		$statement->execute();
150
+		$mec = $statement->fetchColumn();
151
+		$userElement->setAttribute("edited", $mec);
152
+		$statement->closeCursor();
153
+
154
+		$statement->bindValue(":action", "Prefchange");
155
+		$statement->execute();
156
+		$pcc = $statement->fetchColumn();
157
+		$userElement->setAttribute("prefchange", $pcc);
158
+		$statement->closeCursor();
159
+
160
+		// Combine all three actions affecting Welcome templates into one count.
161
+		$combinedquery = $this->getDatabase()->prepare(<<<SQL
162 162
             SELECT
163 163
                 COUNT(*) AS count
164 164
             FROM log
165 165
             WHERE log.user = :userid
166 166
                 AND log.action IN ('CreatedTemplate', 'EditedTemplate', 'DeletedTemplate');
167 167
 SQL
168
-        );
168
+		);
169 169
 
170
-        $combinedquery->bindValue(":userid", $this->user->getId());
171
-        $combinedquery->execute();
172
-        $dtc = $combinedquery->fetchColumn();
173
-        $userElement->setAttribute("welctempchange", $dtc);
174
-        $combinedquery->closeCursor();
170
+		$combinedquery->bindValue(":userid", $this->user->getId());
171
+		$combinedquery->execute();
172
+		$dtc = $combinedquery->fetchColumn();
173
+		$userElement->setAttribute("welctempchange", $dtc);
174
+		$combinedquery->closeCursor();
175 175
 
176
-        // Combine both actions affecting Email templates into one count.
177
-        $combinedquery = $this->getDatabase()->prepare(<<<SQL
176
+		// Combine both actions affecting Email templates into one count.
177
+		$combinedquery = $this->getDatabase()->prepare(<<<SQL
178 178
             SELECT COUNT(*) AS count
179 179
             FROM log
180 180
             WHERE log.user = :userid
181 181
                 AND log.action IN ('CreatedEmail', 'EditedEmail');
182 182
 SQL
183
-        );
184
-
185
-        $combinedquery->bindValue(":userid", $this->user->getId());
186
-        $combinedquery->execute();
187
-        $cec = $combinedquery->fetchColumn();
188
-        $userElement->setAttribute("emailtempchange", $cec);
189
-        $combinedquery->closeCursor();
190
-    }
183
+		);
184
+
185
+		$combinedquery->bindValue(":userid", $this->user->getId());
186
+		$combinedquery->execute();
187
+		$cec = $combinedquery->fetchColumn();
188
+		$userElement->setAttribute("emailtempchange", $cec);
189
+		$combinedquery->closeCursor();
190
+	}
191 191
 }
Please login to merge, or discard this patch.
includes/Helpers/Logger.php 1 patch
Indentation   +314 added lines, -314 removed lines patch added patch discarded remove patch
@@ -30,318 +30,318 @@
 block discarded – undo
30 30
  */
31 31
 class Logger
32 32
 {
33
-    /**
34
-     * @param PdoDatabase $database
35
-     * @param Request     $object
36
-     */
37
-    public static function emailConfirmed(PdoDatabase $database, Request $object)
38
-    {
39
-        self::createLogEntry($database, $object, "Email Confirmed", null, User::getCommunity());
40
-    }
41
-
42
-    /**
43
-     * @param PdoDatabase $database
44
-     * @param DataObject  $object
45
-     * @param string      $logAction
46
-     * @param null|string $comment
47
-     * @param User        $user
48
-     *
49
-     * @throws Exception
50
-     */
51
-    private static function createLogEntry(
52
-        PdoDatabase $database,
53
-        DataObject $object,
54
-        $logAction,
55
-        $comment = null,
56
-        $user = null
57
-    ) {
58
-        if ($user == null) {
59
-            $user = User::getCurrent($database);
60
-        }
61
-
62
-        $objectType = get_class($object);
63
-        if (strpos($objectType, 'Waca\\DataObjects\\') !== false) {
64
-            $objectType = str_replace('Waca\\DataObjects\\', '', $objectType);
65
-        }
66
-
67
-        $log = new Log();
68
-        $log->setDatabase($database);
69
-        $log->setAction($logAction);
70
-        $log->setObjectId($object->getId());
71
-        $log->setObjectType($objectType);
72
-        $log->setUser($user);
73
-        $log->setComment($comment);
74
-        $log->save();
75
-    }
76
-
77
-    #region Users
78
-
79
-    /**
80
-     * @param PdoDatabase $database
81
-     * @param User        $user
82
-     */
83
-    public static function newUser(PdoDatabase $database, User $user)
84
-    {
85
-        self::createLogEntry($database, $user, 'Registered', null, User::getCommunity());
86
-    }
87
-
88
-    /**
89
-     * @param PdoDatabase $database
90
-     * @param User        $object
91
-     */
92
-    public static function approvedUser(PdoDatabase $database, User $object)
93
-    {
94
-        self::createLogEntry($database, $object, "Approved");
95
-    }
96
-
97
-    /**
98
-     * @param PdoDatabase $database
99
-     * @param User        $object
100
-     * @param string      $comment
101
-     */
102
-    public static function declinedUser(PdoDatabase $database, User $object, $comment)
103
-    {
104
-        self::createLogEntry($database, $object, "Declined", $comment);
105
-    }
106
-
107
-    /**
108
-     * @param PdoDatabase $database
109
-     * @param User        $object
110
-     * @param string      $comment
111
-     */
112
-    public static function suspendedUser(PdoDatabase $database, User $object, $comment)
113
-    {
114
-        self::createLogEntry($database, $object, "Suspended", $comment);
115
-    }
116
-
117
-    /**
118
-     * @param PdoDatabase $database
119
-     * @param User        $object
120
-     * @param string      $comment
121
-     */
122
-    public static function demotedUser(PdoDatabase $database, User $object, $comment)
123
-    {
124
-        self::createLogEntry($database, $object, "Demoted", $comment);
125
-    }
126
-
127
-    /**
128
-     * @param PdoDatabase $database
129
-     * @param User        $object
130
-     */
131
-    public static function promotedUser(PdoDatabase $database, User $object)
132
-    {
133
-        self::createLogEntry($database, $object, "Promoted");
134
-    }
135
-
136
-    /**
137
-     * @param PdoDatabase $database
138
-     * @param User        $object
139
-     * @param string      $comment
140
-     */
141
-    public static function renamedUser(PdoDatabase $database, User $object, $comment)
142
-    {
143
-        self::createLogEntry($database, $object, "Renamed", $comment);
144
-    }
145
-
146
-    /**
147
-     * @param PdoDatabase $database
148
-     * @param User        $object
149
-     */
150
-    public static function userPreferencesChange(PdoDatabase $database, User $object)
151
-    {
152
-        self::createLogEntry($database, $object, "Prefchange");
153
-    }
154
-
155
-    /**
156
-     * @param PdoDatabase $database
157
-     * @param User        $object
158
-     * @param string      $reason
159
-     * @param array       $added
160
-     * @param array       $removed
161
-     */
162
-    public static function userRolesEdited(PdoDatabase $database, User $object, $reason, $added, $removed)
163
-    {
164
-        $logData = serialize(array(
165
-            'added'   => $added,
166
-            'removed' => $removed,
167
-            'reason'  => $reason,
168
-        ));
169
-
170
-        self::createLogEntry($database, $object, "RoleChange", $logData);
171
-    }
172
-
173
-    #endregion
174
-
175
-    /**
176
-     * @param PdoDatabase $database
177
-     * @param SiteNotice  $object
178
-     */
179
-    public static function siteNoticeEdited(PdoDatabase $database, SiteNotice $object)
180
-    {
181
-        self::createLogEntry($database, $object, "Edited");
182
-    }
183
-
184
-    #region Welcome Templates
185
-
186
-    /**
187
-     * @param PdoDatabase     $database
188
-     * @param WelcomeTemplate $object
189
-     */
190
-    public static function welcomeTemplateCreated(PdoDatabase $database, WelcomeTemplate $object)
191
-    {
192
-        self::createLogEntry($database, $object, "CreatedTemplate");
193
-    }
194
-
195
-    /**
196
-     * @param PdoDatabase     $database
197
-     * @param WelcomeTemplate $object
198
-     */
199
-    public static function welcomeTemplateEdited(PdoDatabase $database, WelcomeTemplate $object)
200
-    {
201
-        self::createLogEntry($database, $object, "EditedTemplate");
202
-    }
203
-
204
-    /**
205
-     * @param PdoDatabase     $database
206
-     * @param WelcomeTemplate $object
207
-     */
208
-    public static function welcomeTemplateDeleted(PdoDatabase $database, WelcomeTemplate $object)
209
-    {
210
-        self::createLogEntry($database, $object, "DeletedTemplate");
211
-    }
212
-
213
-    #endregion
214
-
215
-    #region Bans
216
-
217
-    /**
218
-     * @param PdoDatabase $database
219
-     * @param Ban         $object
220
-     * @param string      $reason
221
-     */
222
-    public static function banned(PdoDatabase $database, Ban $object, $reason)
223
-    {
224
-        self::createLogEntry($database, $object, "Banned", $reason);
225
-    }
226
-
227
-    /**
228
-     * @param PdoDatabase $database
229
-     * @param Ban         $object
230
-     * @param string      $reason
231
-     */
232
-    public static function unbanned(PdoDatabase $database, Ban $object, $reason)
233
-    {
234
-        self::createLogEntry($database, $object, "Unbanned", $reason);
235
-    }
236
-
237
-    #endregion
238
-
239
-    #region Requests
240
-
241
-    /**
242
-     * @param PdoDatabase $database
243
-     * @param Request     $object
244
-     * @param string      $target
245
-     */
246
-    public static function deferRequest(PdoDatabase $database, Request $object, $target)
247
-    {
248
-        self::createLogEntry($database, $object, "Deferred to $target");
249
-    }
250
-
251
-    /**
252
-     * @param PdoDatabase $database
253
-     * @param Request     $object
254
-     * @param integer     $target
255
-     * @param string      $comment
256
-     */
257
-    public static function closeRequest(PdoDatabase $database, Request $object, $target, $comment)
258
-    {
259
-        self::createLogEntry($database, $object, "Closed $target", $comment);
260
-    }
261
-
262
-    /**
263
-     * @param PdoDatabase $database
264
-     * @param Request     $object
265
-     */
266
-    public static function reserve(PdoDatabase $database, Request $object)
267
-    {
268
-        self::createLogEntry($database, $object, "Reserved");
269
-    }
270
-
271
-    /**
272
-     * @param PdoDatabase $database
273
-     * @param Request     $object
274
-     */
275
-    public static function breakReserve(PdoDatabase $database, Request $object)
276
-    {
277
-        self::createLogEntry($database, $object, "BreakReserve");
278
-    }
279
-
280
-    /**
281
-     * @param PdoDatabase $database
282
-     * @param Request     $object
283
-     */
284
-    public static function unreserve(PdoDatabase $database, Request $object)
285
-    {
286
-        self::createLogEntry($database, $object, "Unreserved");
287
-    }
288
-
289
-    /**
290
-     * @param PdoDatabase $database
291
-     * @param Comment     $object
292
-     * @param Request     $request
293
-     */
294
-    public static function editComment(PdoDatabase $database, Comment $object, Request $request)
295
-    {
296
-        self::createLogEntry($database, $request, "EditComment-r");
297
-        self::createLogEntry($database, $object, "EditComment-c");
298
-    }
299
-
300
-    /**
301
-     * @param PdoDatabase $database
302
-     * @param Request     $object
303
-     * @param User        $target
304
-     */
305
-    public static function sendReservation(PdoDatabase $database, Request $object, User $target)
306
-    {
307
-        self::createLogEntry($database, $object, "SendReserved");
308
-        self::createLogEntry($database, $object, "ReceiveReserved", null, $target);
309
-    }
310
-
311
-    /**
312
-     * @param PdoDatabase $database
313
-     * @param Request     $object
314
-     * @param string      $comment
315
-     */
316
-    public static function sentMail(PdoDatabase $database, Request $object, $comment)
317
-    {
318
-        self::createLogEntry($database, $object, "SentMail", $comment);
319
-    }
320
-    #endregion
321
-
322
-    #region Email templates
323
-
324
-    /**
325
-     * @param PdoDatabase   $database
326
-     * @param EmailTemplate $object
327
-     */
328
-    public static function createEmail(PdoDatabase $database, EmailTemplate $object)
329
-    {
330
-        self::createLogEntry($database, $object, "CreatedEmail");
331
-    }
332
-
333
-    /**
334
-     * @param PdoDatabase   $database
335
-     * @param EmailTemplate $object
336
-     */
337
-    public static function editedEmail(PdoDatabase $database, EmailTemplate $object)
338
-    {
339
-        self::createLogEntry($database, $object, "EditedEmail");
340
-    }
341
-
342
-    #endregion
343
-
344
-    #region Display
345
-
346
-    #endregion
33
+	/**
34
+	 * @param PdoDatabase $database
35
+	 * @param Request     $object
36
+	 */
37
+	public static function emailConfirmed(PdoDatabase $database, Request $object)
38
+	{
39
+		self::createLogEntry($database, $object, "Email Confirmed", null, User::getCommunity());
40
+	}
41
+
42
+	/**
43
+	 * @param PdoDatabase $database
44
+	 * @param DataObject  $object
45
+	 * @param string      $logAction
46
+	 * @param null|string $comment
47
+	 * @param User        $user
48
+	 *
49
+	 * @throws Exception
50
+	 */
51
+	private static function createLogEntry(
52
+		PdoDatabase $database,
53
+		DataObject $object,
54
+		$logAction,
55
+		$comment = null,
56
+		$user = null
57
+	) {
58
+		if ($user == null) {
59
+			$user = User::getCurrent($database);
60
+		}
61
+
62
+		$objectType = get_class($object);
63
+		if (strpos($objectType, 'Waca\\DataObjects\\') !== false) {
64
+			$objectType = str_replace('Waca\\DataObjects\\', '', $objectType);
65
+		}
66
+
67
+		$log = new Log();
68
+		$log->setDatabase($database);
69
+		$log->setAction($logAction);
70
+		$log->setObjectId($object->getId());
71
+		$log->setObjectType($objectType);
72
+		$log->setUser($user);
73
+		$log->setComment($comment);
74
+		$log->save();
75
+	}
76
+
77
+	#region Users
78
+
79
+	/**
80
+	 * @param PdoDatabase $database
81
+	 * @param User        $user
82
+	 */
83
+	public static function newUser(PdoDatabase $database, User $user)
84
+	{
85
+		self::createLogEntry($database, $user, 'Registered', null, User::getCommunity());
86
+	}
87
+
88
+	/**
89
+	 * @param PdoDatabase $database
90
+	 * @param User        $object
91
+	 */
92
+	public static function approvedUser(PdoDatabase $database, User $object)
93
+	{
94
+		self::createLogEntry($database, $object, "Approved");
95
+	}
96
+
97
+	/**
98
+	 * @param PdoDatabase $database
99
+	 * @param User        $object
100
+	 * @param string      $comment
101
+	 */
102
+	public static function declinedUser(PdoDatabase $database, User $object, $comment)
103
+	{
104
+		self::createLogEntry($database, $object, "Declined", $comment);
105
+	}
106
+
107
+	/**
108
+	 * @param PdoDatabase $database
109
+	 * @param User        $object
110
+	 * @param string      $comment
111
+	 */
112
+	public static function suspendedUser(PdoDatabase $database, User $object, $comment)
113
+	{
114
+		self::createLogEntry($database, $object, "Suspended", $comment);
115
+	}
116
+
117
+	/**
118
+	 * @param PdoDatabase $database
119
+	 * @param User        $object
120
+	 * @param string      $comment
121
+	 */
122
+	public static function demotedUser(PdoDatabase $database, User $object, $comment)
123
+	{
124
+		self::createLogEntry($database, $object, "Demoted", $comment);
125
+	}
126
+
127
+	/**
128
+	 * @param PdoDatabase $database
129
+	 * @param User        $object
130
+	 */
131
+	public static function promotedUser(PdoDatabase $database, User $object)
132
+	{
133
+		self::createLogEntry($database, $object, "Promoted");
134
+	}
135
+
136
+	/**
137
+	 * @param PdoDatabase $database
138
+	 * @param User        $object
139
+	 * @param string      $comment
140
+	 */
141
+	public static function renamedUser(PdoDatabase $database, User $object, $comment)
142
+	{
143
+		self::createLogEntry($database, $object, "Renamed", $comment);
144
+	}
145
+
146
+	/**
147
+	 * @param PdoDatabase $database
148
+	 * @param User        $object
149
+	 */
150
+	public static function userPreferencesChange(PdoDatabase $database, User $object)
151
+	{
152
+		self::createLogEntry($database, $object, "Prefchange");
153
+	}
154
+
155
+	/**
156
+	 * @param PdoDatabase $database
157
+	 * @param User        $object
158
+	 * @param string      $reason
159
+	 * @param array       $added
160
+	 * @param array       $removed
161
+	 */
162
+	public static function userRolesEdited(PdoDatabase $database, User $object, $reason, $added, $removed)
163
+	{
164
+		$logData = serialize(array(
165
+			'added'   => $added,
166
+			'removed' => $removed,
167
+			'reason'  => $reason,
168
+		));
169
+
170
+		self::createLogEntry($database, $object, "RoleChange", $logData);
171
+	}
172
+
173
+	#endregion
174
+
175
+	/**
176
+	 * @param PdoDatabase $database
177
+	 * @param SiteNotice  $object
178
+	 */
179
+	public static function siteNoticeEdited(PdoDatabase $database, SiteNotice $object)
180
+	{
181
+		self::createLogEntry($database, $object, "Edited");
182
+	}
183
+
184
+	#region Welcome Templates
185
+
186
+	/**
187
+	 * @param PdoDatabase     $database
188
+	 * @param WelcomeTemplate $object
189
+	 */
190
+	public static function welcomeTemplateCreated(PdoDatabase $database, WelcomeTemplate $object)
191
+	{
192
+		self::createLogEntry($database, $object, "CreatedTemplate");
193
+	}
194
+
195
+	/**
196
+	 * @param PdoDatabase     $database
197
+	 * @param WelcomeTemplate $object
198
+	 */
199
+	public static function welcomeTemplateEdited(PdoDatabase $database, WelcomeTemplate $object)
200
+	{
201
+		self::createLogEntry($database, $object, "EditedTemplate");
202
+	}
203
+
204
+	/**
205
+	 * @param PdoDatabase     $database
206
+	 * @param WelcomeTemplate $object
207
+	 */
208
+	public static function welcomeTemplateDeleted(PdoDatabase $database, WelcomeTemplate $object)
209
+	{
210
+		self::createLogEntry($database, $object, "DeletedTemplate");
211
+	}
212
+
213
+	#endregion
214
+
215
+	#region Bans
216
+
217
+	/**
218
+	 * @param PdoDatabase $database
219
+	 * @param Ban         $object
220
+	 * @param string      $reason
221
+	 */
222
+	public static function banned(PdoDatabase $database, Ban $object, $reason)
223
+	{
224
+		self::createLogEntry($database, $object, "Banned", $reason);
225
+	}
226
+
227
+	/**
228
+	 * @param PdoDatabase $database
229
+	 * @param Ban         $object
230
+	 * @param string      $reason
231
+	 */
232
+	public static function unbanned(PdoDatabase $database, Ban $object, $reason)
233
+	{
234
+		self::createLogEntry($database, $object, "Unbanned", $reason);
235
+	}
236
+
237
+	#endregion
238
+
239
+	#region Requests
240
+
241
+	/**
242
+	 * @param PdoDatabase $database
243
+	 * @param Request     $object
244
+	 * @param string      $target
245
+	 */
246
+	public static function deferRequest(PdoDatabase $database, Request $object, $target)
247
+	{
248
+		self::createLogEntry($database, $object, "Deferred to $target");
249
+	}
250
+
251
+	/**
252
+	 * @param PdoDatabase $database
253
+	 * @param Request     $object
254
+	 * @param integer     $target
255
+	 * @param string      $comment
256
+	 */
257
+	public static function closeRequest(PdoDatabase $database, Request $object, $target, $comment)
258
+	{
259
+		self::createLogEntry($database, $object, "Closed $target", $comment);
260
+	}
261
+
262
+	/**
263
+	 * @param PdoDatabase $database
264
+	 * @param Request     $object
265
+	 */
266
+	public static function reserve(PdoDatabase $database, Request $object)
267
+	{
268
+		self::createLogEntry($database, $object, "Reserved");
269
+	}
270
+
271
+	/**
272
+	 * @param PdoDatabase $database
273
+	 * @param Request     $object
274
+	 */
275
+	public static function breakReserve(PdoDatabase $database, Request $object)
276
+	{
277
+		self::createLogEntry($database, $object, "BreakReserve");
278
+	}
279
+
280
+	/**
281
+	 * @param PdoDatabase $database
282
+	 * @param Request     $object
283
+	 */
284
+	public static function unreserve(PdoDatabase $database, Request $object)
285
+	{
286
+		self::createLogEntry($database, $object, "Unreserved");
287
+	}
288
+
289
+	/**
290
+	 * @param PdoDatabase $database
291
+	 * @param Comment     $object
292
+	 * @param Request     $request
293
+	 */
294
+	public static function editComment(PdoDatabase $database, Comment $object, Request $request)
295
+	{
296
+		self::createLogEntry($database, $request, "EditComment-r");
297
+		self::createLogEntry($database, $object, "EditComment-c");
298
+	}
299
+
300
+	/**
301
+	 * @param PdoDatabase $database
302
+	 * @param Request     $object
303
+	 * @param User        $target
304
+	 */
305
+	public static function sendReservation(PdoDatabase $database, Request $object, User $target)
306
+	{
307
+		self::createLogEntry($database, $object, "SendReserved");
308
+		self::createLogEntry($database, $object, "ReceiveReserved", null, $target);
309
+	}
310
+
311
+	/**
312
+	 * @param PdoDatabase $database
313
+	 * @param Request     $object
314
+	 * @param string      $comment
315
+	 */
316
+	public static function sentMail(PdoDatabase $database, Request $object, $comment)
317
+	{
318
+		self::createLogEntry($database, $object, "SentMail", $comment);
319
+	}
320
+	#endregion
321
+
322
+	#region Email templates
323
+
324
+	/**
325
+	 * @param PdoDatabase   $database
326
+	 * @param EmailTemplate $object
327
+	 */
328
+	public static function createEmail(PdoDatabase $database, EmailTemplate $object)
329
+	{
330
+		self::createLogEntry($database, $object, "CreatedEmail");
331
+	}
332
+
333
+	/**
334
+	 * @param PdoDatabase   $database
335
+	 * @param EmailTemplate $object
336
+	 */
337
+	public static function editedEmail(PdoDatabase $database, EmailTemplate $object)
338
+	{
339
+		self::createLogEntry($database, $object, "EditedEmail");
340
+	}
341
+
342
+	#endregion
343
+
344
+	#region Display
345
+
346
+	#endregion
347 347
 }
Please login to merge, or discard this patch.
includes/Helpers/LogHelper.php 2 patches
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
             $template = EmailTemplate::getById((int)$id, $entry->getDatabase());
129 129
 
130 130
             if ($template != false) {
131
-                return "closed (" . $template->getName() . ")";
131
+                return "closed (".$template->getName().")";
132 132
             }
133 133
         }
134 134
 
@@ -247,7 +247,7 @@  discard block
 block discarded – undo
247 247
                 /** @var Ban $ban */
248 248
                 $ban = Ban::getById($objectId, $database);
249 249
 
250
-                return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
250
+                return 'Ban #'.$objectId." (".htmlentities($ban->getTarget()).")</a>";
251 251
             case 'EmailTemplate':
252 252
                 /** @var EmailTemplate $emailTemplate */
253 253
                 $emailTemplate = EmailTemplate::getById($objectId, $database);
@@ -286,7 +286,7 @@  discard block
 block discarded – undo
286 286
                     return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
287 287
                 }
288 288
             default:
289
-                return '[' . $objectType . " " . $objectId . ']';
289
+                return '['.$objectType." ".$objectId.']';
290 290
         }
291 291
     }
292 292
 
@@ -333,7 +333,7 @@  discard block
 block discarded – undo
333 333
                 $renameData = unserialize($logEntry->getComment());
334 334
                 $oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
335 335
                 $newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
336
-                $comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
336
+                $comment = 'Renamed \''.$oldName.'\' to \''.$newName.'\'.';
337 337
             }
338 338
             else if ($logEntry->getAction() === 'RoleChange') {
339 339
                 $roleChangeData = unserialize($logEntry->getComment());
@@ -350,8 +350,8 @@  discard block
 block discarded – undo
350 350
 
351 351
                 $reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
352 352
 
353
-                $roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
354
-                $comment = $roleDelta . ' with comment: ' . $reason;
353
+                $roleDelta = 'Removed ['.implode(', ', $removed).'], Added ['.implode(', ', $added).']';
354
+                $comment = $roleDelta.' with comment: '.$reason;
355 355
             }
356 356
             else {
357 357
                 $comment = $logEntry->getComment();
Please login to merge, or discard this patch.
Indentation   +336 added lines, -336 removed lines patch added patch discarded remove patch
@@ -26,347 +26,347 @@
 block discarded – undo
26 26
 
27 27
 class LogHelper
28 28
 {
29
-    /**
30
-     * Summary of getRequestLogsWithComments
31
-     *
32
-     * @param int             $requestId
33
-     * @param PdoDatabase     $db
34
-     * @param SecurityManager $securityManager
35
-     *
36
-     * @return \Waca\DataObject[]
37
-     */
38
-    public static function getRequestLogsWithComments($requestId, PdoDatabase $db, SecurityManager $securityManager)
39
-    {
40
-        $logs = LogSearchHelper::get($db)->byObjectType('Request')->byObjectId($requestId)->fetch();
41
-
42
-        $currentUser = User::getCurrent($db);
43
-        $securityResult = $securityManager->allows('RequestData', 'seeRestrictedComments', $currentUser);
44
-        $showAllComments = $securityResult === SecurityManager::ALLOWED;
45
-
46
-        $comments = Comment::getForRequest($requestId, $db, $showAllComments, $currentUser->getId());
47
-
48
-        $items = array_merge($logs, $comments);
49
-
50
-        /**
51
-         * @param DataObject $item
52
-         *
53
-         * @return int
54
-         */
55
-        $sortKey = function(DataObject $item) {
56
-            if ($item instanceof Log) {
57
-                return $item->getTimestamp()->getTimestamp();
58
-            }
59
-
60
-            if ($item instanceof Comment) {
61
-                return $item->getTime()->getTimestamp();
62
-            }
63
-
64
-            return 0;
65
-        };
66
-
67
-        do {
68
-            $flag = false;
69
-
70
-            $loopLimit = (count($items) - 1);
71
-            for ($i = 0; $i < $loopLimit; $i++) {
72
-                // are these two items out of order?
73
-                if ($sortKey($items[$i]) > $sortKey($items[$i + 1])) {
74
-                    // swap them
75
-                    $swap = $items[$i];
76
-                    $items[$i] = $items[$i + 1];
77
-                    $items[$i + 1] = $swap;
78
-
79
-                    // set a flag to say we've modified the array this time around
80
-                    $flag = true;
81
-                }
82
-            }
83
-        }
84
-        while ($flag);
85
-
86
-        return $items;
87
-    }
88
-
89
-    /**
90
-     * Summary of getLogDescription
91
-     *
92
-     * @param Log $entry
93
-     *
94
-     * @return string
95
-     */
96
-    public static function getLogDescription(Log $entry)
97
-    {
98
-        $text = "Deferred to ";
99
-        if (substr($entry->getAction(), 0, strlen($text)) == $text) {
100
-            // Deferred to a different queue
101
-            // This is exactly what we want to display.
102
-            return $entry->getAction();
103
-        }
104
-
105
-        $text = "Closed custom-n";
106
-        if ($entry->getAction() == $text) {
107
-            // Custom-closed
108
-            return "closed (custom reason - account not created)";
109
-        }
110
-
111
-        $text = "Closed custom-y";
112
-        if ($entry->getAction() == $text) {
113
-            // Custom-closed
114
-            return "closed (custom reason - account created)";
115
-        }
116
-
117
-        $text = "Closed 0";
118
-        if ($entry->getAction() == $text) {
119
-            // Dropped the request - short-circuit the lookup
120
-            return "dropped request";
121
-        }
122
-
123
-        $text = "Closed ";
124
-        if (substr($entry->getAction(), 0, strlen($text)) == $text) {
125
-            // Closed with a reason - do a lookup here.
126
-            $id = substr($entry->getAction(), strlen($text));
127
-            /** @var EmailTemplate $template */
128
-            $template = EmailTemplate::getById((int)$id, $entry->getDatabase());
129
-
130
-            if ($template != false) {
131
-                return "closed (" . $template->getName() . ")";
132
-            }
133
-        }
134
-
135
-        // Fall back to the basic stuff
136
-        $lookup = array(
137
-            'Reserved'        => 'reserved',
138
-            'Email Confirmed' => 'email-confirmed',
139
-            'Unreserved'      => 'unreserved',
140
-            'Approved'        => 'approved',
141
-            'Suspended'       => 'suspended',
142
-            'RoleChange'      => 'changed roles',
143
-            'Banned'          => 'banned',
144
-            'Edited'          => 'edited interface message',
145
-            'Declined'        => 'declined',
146
-            'EditComment-c'   => 'edited a comment',
147
-            'EditComment-r'   => 'edited a comment',
148
-            'Unbanned'        => 'unbanned',
149
-            'Promoted'        => 'promoted to tool admin',
150
-            'BreakReserve'    => 'forcibly broke the reservation',
151
-            'Prefchange'      => 'changed user preferences',
152
-            'Renamed'         => 'renamed',
153
-            'Demoted'         => 'demoted from tool admin',
154
-            'ReceiveReserved' => 'received the reservation',
155
-            'SendReserved'    => 'sent the reservation',
156
-            'EditedEmail'     => 'edited email',
157
-            'DeletedTemplate' => 'deleted template',
158
-            'EditedTemplate'  => 'edited template',
159
-            'CreatedEmail'    => 'created email',
160
-            'CreatedTemplate' => 'created template',
161
-            'SentMail'        => 'sent an email to the requestor',
162
-            'Registered'      => 'registered a tool account',
163
-        );
164
-
165
-        if (array_key_exists($entry->getAction(), $lookup)) {
166
-            return $lookup[$entry->getAction()];
167
-        }
168
-
169
-        // OK, I don't know what this is. Fall back to something sane.
170
-        return "performed an unknown action ({$entry->getAction()})";
171
-    }
172
-
173
-    /**
174
-     * @param PdoDatabase $database
175
-     *
176
-     * @return array
177
-     */
178
-    public static function getLogActions(PdoDatabase $database)
179
-    {
180
-        $lookup = array(
181
-            'Reserved'        => 'reserved',
182
-            'Email Confirmed' => 'email-confirmed',
183
-            'Unreserved'      => 'unreserved',
184
-            'Approved'        => 'approved',
185
-            'Suspended'       => 'suspended',
186
-            'RoleChange'      => 'changed roles',
187
-            'Banned'          => 'banned',
188
-            'Edited'          => 'edited interface message',
189
-            'Declined'        => 'declined',
190
-            'EditComment-c'   => 'edited a comment (by comment ID)',
191
-            'EditComment-r'   => 'edited a comment (by request)',
192
-            'Unbanned'        => 'unbanned',
193
-            'Promoted'        => 'promoted to tool admin',
194
-            'BreakReserve'    => 'forcibly broke the reservation',
195
-            'Prefchange'      => 'changed user preferences',
196
-            'Renamed'         => 'renamed',
197
-            'Demoted'         => 'demoted from tool admin',
198
-            'ReceiveReserved' => 'received the reservation',
199
-            'SendReserved'    => 'sent the reservation',
200
-            'EditedEmail'     => 'edited email',
201
-            'DeletedTemplate' => 'deleted template',
202
-            'EditedTemplate'  => 'edited template',
203
-            'CreatedEmail'    => 'created email',
204
-            'CreatedTemplate' => 'created template',
205
-            'SentMail'        => 'sent an email to the requestor',
206
-            'Registered'      => 'registered a tool account',
207
-            'Closed 0'        => 'dropped request',
208
-        );
209
-
210
-        $statement = $database->query(<<<SQL
29
+	/**
30
+	 * Summary of getRequestLogsWithComments
31
+	 *
32
+	 * @param int             $requestId
33
+	 * @param PdoDatabase     $db
34
+	 * @param SecurityManager $securityManager
35
+	 *
36
+	 * @return \Waca\DataObject[]
37
+	 */
38
+	public static function getRequestLogsWithComments($requestId, PdoDatabase $db, SecurityManager $securityManager)
39
+	{
40
+		$logs = LogSearchHelper::get($db)->byObjectType('Request')->byObjectId($requestId)->fetch();
41
+
42
+		$currentUser = User::getCurrent($db);
43
+		$securityResult = $securityManager->allows('RequestData', 'seeRestrictedComments', $currentUser);
44
+		$showAllComments = $securityResult === SecurityManager::ALLOWED;
45
+
46
+		$comments = Comment::getForRequest($requestId, $db, $showAllComments, $currentUser->getId());
47
+
48
+		$items = array_merge($logs, $comments);
49
+
50
+		/**
51
+		 * @param DataObject $item
52
+		 *
53
+		 * @return int
54
+		 */
55
+		$sortKey = function(DataObject $item) {
56
+			if ($item instanceof Log) {
57
+				return $item->getTimestamp()->getTimestamp();
58
+			}
59
+
60
+			if ($item instanceof Comment) {
61
+				return $item->getTime()->getTimestamp();
62
+			}
63
+
64
+			return 0;
65
+		};
66
+
67
+		do {
68
+			$flag = false;
69
+
70
+			$loopLimit = (count($items) - 1);
71
+			for ($i = 0; $i < $loopLimit; $i++) {
72
+				// are these two items out of order?
73
+				if ($sortKey($items[$i]) > $sortKey($items[$i + 1])) {
74
+					// swap them
75
+					$swap = $items[$i];
76
+					$items[$i] = $items[$i + 1];
77
+					$items[$i + 1] = $swap;
78
+
79
+					// set a flag to say we've modified the array this time around
80
+					$flag = true;
81
+				}
82
+			}
83
+		}
84
+		while ($flag);
85
+
86
+		return $items;
87
+	}
88
+
89
+	/**
90
+	 * Summary of getLogDescription
91
+	 *
92
+	 * @param Log $entry
93
+	 *
94
+	 * @return string
95
+	 */
96
+	public static function getLogDescription(Log $entry)
97
+	{
98
+		$text = "Deferred to ";
99
+		if (substr($entry->getAction(), 0, strlen($text)) == $text) {
100
+			// Deferred to a different queue
101
+			// This is exactly what we want to display.
102
+			return $entry->getAction();
103
+		}
104
+
105
+		$text = "Closed custom-n";
106
+		if ($entry->getAction() == $text) {
107
+			// Custom-closed
108
+			return "closed (custom reason - account not created)";
109
+		}
110
+
111
+		$text = "Closed custom-y";
112
+		if ($entry->getAction() == $text) {
113
+			// Custom-closed
114
+			return "closed (custom reason - account created)";
115
+		}
116
+
117
+		$text = "Closed 0";
118
+		if ($entry->getAction() == $text) {
119
+			// Dropped the request - short-circuit the lookup
120
+			return "dropped request";
121
+		}
122
+
123
+		$text = "Closed ";
124
+		if (substr($entry->getAction(), 0, strlen($text)) == $text) {
125
+			// Closed with a reason - do a lookup here.
126
+			$id = substr($entry->getAction(), strlen($text));
127
+			/** @var EmailTemplate $template */
128
+			$template = EmailTemplate::getById((int)$id, $entry->getDatabase());
129
+
130
+			if ($template != false) {
131
+				return "closed (" . $template->getName() . ")";
132
+			}
133
+		}
134
+
135
+		// Fall back to the basic stuff
136
+		$lookup = array(
137
+			'Reserved'        => 'reserved',
138
+			'Email Confirmed' => 'email-confirmed',
139
+			'Unreserved'      => 'unreserved',
140
+			'Approved'        => 'approved',
141
+			'Suspended'       => 'suspended',
142
+			'RoleChange'      => 'changed roles',
143
+			'Banned'          => 'banned',
144
+			'Edited'          => 'edited interface message',
145
+			'Declined'        => 'declined',
146
+			'EditComment-c'   => 'edited a comment',
147
+			'EditComment-r'   => 'edited a comment',
148
+			'Unbanned'        => 'unbanned',
149
+			'Promoted'        => 'promoted to tool admin',
150
+			'BreakReserve'    => 'forcibly broke the reservation',
151
+			'Prefchange'      => 'changed user preferences',
152
+			'Renamed'         => 'renamed',
153
+			'Demoted'         => 'demoted from tool admin',
154
+			'ReceiveReserved' => 'received the reservation',
155
+			'SendReserved'    => 'sent the reservation',
156
+			'EditedEmail'     => 'edited email',
157
+			'DeletedTemplate' => 'deleted template',
158
+			'EditedTemplate'  => 'edited template',
159
+			'CreatedEmail'    => 'created email',
160
+			'CreatedTemplate' => 'created template',
161
+			'SentMail'        => 'sent an email to the requestor',
162
+			'Registered'      => 'registered a tool account',
163
+		);
164
+
165
+		if (array_key_exists($entry->getAction(), $lookup)) {
166
+			return $lookup[$entry->getAction()];
167
+		}
168
+
169
+		// OK, I don't know what this is. Fall back to something sane.
170
+		return "performed an unknown action ({$entry->getAction()})";
171
+	}
172
+
173
+	/**
174
+	 * @param PdoDatabase $database
175
+	 *
176
+	 * @return array
177
+	 */
178
+	public static function getLogActions(PdoDatabase $database)
179
+	{
180
+		$lookup = array(
181
+			'Reserved'        => 'reserved',
182
+			'Email Confirmed' => 'email-confirmed',
183
+			'Unreserved'      => 'unreserved',
184
+			'Approved'        => 'approved',
185
+			'Suspended'       => 'suspended',
186
+			'RoleChange'      => 'changed roles',
187
+			'Banned'          => 'banned',
188
+			'Edited'          => 'edited interface message',
189
+			'Declined'        => 'declined',
190
+			'EditComment-c'   => 'edited a comment (by comment ID)',
191
+			'EditComment-r'   => 'edited a comment (by request)',
192
+			'Unbanned'        => 'unbanned',
193
+			'Promoted'        => 'promoted to tool admin',
194
+			'BreakReserve'    => 'forcibly broke the reservation',
195
+			'Prefchange'      => 'changed user preferences',
196
+			'Renamed'         => 'renamed',
197
+			'Demoted'         => 'demoted from tool admin',
198
+			'ReceiveReserved' => 'received the reservation',
199
+			'SendReserved'    => 'sent the reservation',
200
+			'EditedEmail'     => 'edited email',
201
+			'DeletedTemplate' => 'deleted template',
202
+			'EditedTemplate'  => 'edited template',
203
+			'CreatedEmail'    => 'created email',
204
+			'CreatedTemplate' => 'created template',
205
+			'SentMail'        => 'sent an email to the requestor',
206
+			'Registered'      => 'registered a tool account',
207
+			'Closed 0'        => 'dropped request',
208
+		);
209
+
210
+		$statement = $database->query(<<<SQL
211 211
 SELECT CONCAT('Closed ', id) AS k, CONCAT('closed (',name,')') AS v
212 212
 FROM emailtemplate;
213 213
 SQL
214
-        );
215
-        foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
216
-            $lookup[$row['k']] = $row['v'];
217
-        }
218
-
219
-        return $lookup;
220
-    }
221
-
222
-    /**
223
-     * This returns a HTML
224
-     *
225
-     * @param string            $objectId
226
-     * @param string            $objectType
227
-     * @param PdoDatabase       $database
228
-     * @param SiteConfiguration $configuration
229
-     *
230
-     * @return null|string
231
-     * @category Security-Critical
232
-     */
233
-    private static function getObjectDescription(
234
-        $objectId,
235
-        $objectType,
236
-        PdoDatabase $database,
237
-        SiteConfiguration $configuration
238
-    ) {
239
-        if ($objectType == '') {
240
-            return null;
241
-        }
242
-
243
-        $baseurl = $configuration->getBaseUrl();
244
-
245
-        switch ($objectType) {
246
-            case 'Ban':
247
-                /** @var Ban $ban */
248
-                $ban = Ban::getById($objectId, $database);
249
-
250
-                return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
251
-            case 'EmailTemplate':
252
-                /** @var EmailTemplate $emailTemplate */
253
-                $emailTemplate = EmailTemplate::getById($objectId, $database);
254
-                $name = htmlentities($emailTemplate->getName(), ENT_COMPAT, 'UTF-8');
255
-
256
-                return <<<HTML
214
+		);
215
+		foreach ($statement->fetchAll(PDO::FETCH_ASSOC) as $row) {
216
+			$lookup[$row['k']] = $row['v'];
217
+		}
218
+
219
+		return $lookup;
220
+	}
221
+
222
+	/**
223
+	 * This returns a HTML
224
+	 *
225
+	 * @param string            $objectId
226
+	 * @param string            $objectType
227
+	 * @param PdoDatabase       $database
228
+	 * @param SiteConfiguration $configuration
229
+	 *
230
+	 * @return null|string
231
+	 * @category Security-Critical
232
+	 */
233
+	private static function getObjectDescription(
234
+		$objectId,
235
+		$objectType,
236
+		PdoDatabase $database,
237
+		SiteConfiguration $configuration
238
+	) {
239
+		if ($objectType == '') {
240
+			return null;
241
+		}
242
+
243
+		$baseurl = $configuration->getBaseUrl();
244
+
245
+		switch ($objectType) {
246
+			case 'Ban':
247
+				/** @var Ban $ban */
248
+				$ban = Ban::getById($objectId, $database);
249
+
250
+				return 'Ban #' . $objectId . " (" . htmlentities($ban->getTarget()) . ")</a>";
251
+			case 'EmailTemplate':
252
+				/** @var EmailTemplate $emailTemplate */
253
+				$emailTemplate = EmailTemplate::getById($objectId, $database);
254
+				$name = htmlentities($emailTemplate->getName(), ENT_COMPAT, 'UTF-8');
255
+
256
+				return <<<HTML
257 257
 <a href="{$baseurl}/internal.php/emailManagement/view?id={$objectId}">Email Template #{$objectId} ({$name})</a>
258 258
 HTML;
259
-            case 'SiteNotice':
260
-                return "<a href=\"{$baseurl}/internal.php/siteNotice\">the site notice</a>";
261
-            case 'Request':
262
-                /** @var Request $request */
263
-                $request = Request::getById($objectId, $database);
264
-                $name = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
265
-
266
-                return <<<HTML
259
+			case 'SiteNotice':
260
+				return "<a href=\"{$baseurl}/internal.php/siteNotice\">the site notice</a>";
261
+			case 'Request':
262
+				/** @var Request $request */
263
+				$request = Request::getById($objectId, $database);
264
+				$name = htmlentities($request->getName(), ENT_COMPAT, 'UTF-8');
265
+
266
+				return <<<HTML
267 267
 <a href="{$baseurl}/internal.php/viewRequest?id={$objectId}">Request #{$objectId} ({$name})</a>
268 268
 HTML;
269
-            case 'User':
270
-                /** @var User $user */
271
-                $user = User::getById($objectId, $database);
272
-                $username = htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8');
273
-
274
-                return "<a href=\"{$baseurl}/internal.php/statistics/users/detail?user={$objectId}\">{$username}</a>";
275
-            case 'WelcomeTemplate':
276
-                /** @var WelcomeTemplate $welcomeTemplate */
277
-                $welcomeTemplate = WelcomeTemplate::getById($objectId, $database);
278
-
279
-                // some old templates have been completely deleted and lost to the depths of time.
280
-                if ($welcomeTemplate === false) {
281
-                    return "Welcome template #{$objectId}";
282
-                }
283
-                else {
284
-                    $userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
285
-
286
-                    return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
287
-                }
288
-            default:
289
-                return '[' . $objectType . " " . $objectId . ']';
290
-        }
291
-    }
292
-
293
-    /**
294
-     * @param    Log[]          $logs
295
-     * @param     PdoDatabase   $database
296
-     * @param SiteConfiguration $configuration
297
-     *
298
-     * @return array
299
-     * @throws Exception
300
-     */
301
-    public static function prepareLogsForTemplate($logs, PdoDatabase $database, SiteConfiguration $configuration)
302
-    {
303
-        $userIds = array();
304
-
305
-        /** @var Log $logEntry */
306
-        foreach ($logs as $logEntry) {
307
-            if (!$logEntry instanceof Log) {
308
-                // if this happens, we've done something wrong with passing back the log data.
309
-                throw new Exception('Log entry is not an instance of a Log, this should never happen.');
310
-            }
311
-
312
-            $user = $logEntry->getUser();
313
-            if ($user === -1) {
314
-                continue;
315
-            }
316
-
317
-            if (!array_search($user, $userIds)) {
318
-                $userIds[] = $user;
319
-            }
320
-        }
321
-
322
-        $users = UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username');
323
-        $users[-1] = User::getCommunity()->getUsername();
324
-
325
-        $logData = array();
326
-
327
-        /** @var Log $logEntry */
328
-        foreach ($logs as $logEntry) {
329
-            $objectDescription = self::getObjectDescription($logEntry->getObjectId(), $logEntry->getObjectType(),
330
-                $database, $configuration);
331
-
332
-            if ($logEntry->getAction() === 'Renamed') {
333
-                $renameData = unserialize($logEntry->getComment());
334
-                $oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
335
-                $newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
336
-                $comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
337
-            }
338
-            else if ($logEntry->getAction() === 'RoleChange') {
339
-                $roleChangeData = unserialize($logEntry->getComment());
340
-
341
-                $removed = array();
342
-                foreach ($roleChangeData['removed'] as $r) {
343
-                    $removed[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
344
-                }
345
-
346
-                $added = array();
347
-                foreach ($roleChangeData['added'] as $r) {
348
-                    $added[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
349
-                }
350
-
351
-                $reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
352
-
353
-                $roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
354
-                $comment = $roleDelta . ' with comment: ' . $reason;
355
-            }
356
-            else {
357
-                $comment = $logEntry->getComment();
358
-            }
359
-
360
-            $logData[] = array(
361
-                'timestamp'         => $logEntry->getTimestamp(),
362
-                'userid'            => $logEntry->getUser(),
363
-                'username'          => $users[$logEntry->getUser()],
364
-                'description'       => self::getLogDescription($logEntry),
365
-                'objectdescription' => $objectDescription,
366
-                'comment'           => $comment,
367
-            );
368
-        }
369
-
370
-        return array($users, $logData);
371
-    }
269
+			case 'User':
270
+				/** @var User $user */
271
+				$user = User::getById($objectId, $database);
272
+				$username = htmlentities($user->getUsername(), ENT_COMPAT, 'UTF-8');
273
+
274
+				return "<a href=\"{$baseurl}/internal.php/statistics/users/detail?user={$objectId}\">{$username}</a>";
275
+			case 'WelcomeTemplate':
276
+				/** @var WelcomeTemplate $welcomeTemplate */
277
+				$welcomeTemplate = WelcomeTemplate::getById($objectId, $database);
278
+
279
+				// some old templates have been completely deleted and lost to the depths of time.
280
+				if ($welcomeTemplate === false) {
281
+					return "Welcome template #{$objectId}";
282
+				}
283
+				else {
284
+					$userCode = htmlentities($welcomeTemplate->getUserCode(), ENT_COMPAT, 'UTF-8');
285
+
286
+					return "<a href=\"{$baseurl}/internal.php/welcomeTemplates/view?template={$objectId}\">{$userCode}</a>";
287
+				}
288
+			default:
289
+				return '[' . $objectType . " " . $objectId . ']';
290
+		}
291
+	}
292
+
293
+	/**
294
+	 * @param    Log[]          $logs
295
+	 * @param     PdoDatabase   $database
296
+	 * @param SiteConfiguration $configuration
297
+	 *
298
+	 * @return array
299
+	 * @throws Exception
300
+	 */
301
+	public static function prepareLogsForTemplate($logs, PdoDatabase $database, SiteConfiguration $configuration)
302
+	{
303
+		$userIds = array();
304
+
305
+		/** @var Log $logEntry */
306
+		foreach ($logs as $logEntry) {
307
+			if (!$logEntry instanceof Log) {
308
+				// if this happens, we've done something wrong with passing back the log data.
309
+				throw new Exception('Log entry is not an instance of a Log, this should never happen.');
310
+			}
311
+
312
+			$user = $logEntry->getUser();
313
+			if ($user === -1) {
314
+				continue;
315
+			}
316
+
317
+			if (!array_search($user, $userIds)) {
318
+				$userIds[] = $user;
319
+			}
320
+		}
321
+
322
+		$users = UserSearchHelper::get($database)->inIds($userIds)->fetchMap('username');
323
+		$users[-1] = User::getCommunity()->getUsername();
324
+
325
+		$logData = array();
326
+
327
+		/** @var Log $logEntry */
328
+		foreach ($logs as $logEntry) {
329
+			$objectDescription = self::getObjectDescription($logEntry->getObjectId(), $logEntry->getObjectType(),
330
+				$database, $configuration);
331
+
332
+			if ($logEntry->getAction() === 'Renamed') {
333
+				$renameData = unserialize($logEntry->getComment());
334
+				$oldName = htmlentities($renameData['old'], ENT_COMPAT, 'UTF-8');
335
+				$newName = htmlentities($renameData['new'], ENT_COMPAT, 'UTF-8');
336
+				$comment = 'Renamed \'' . $oldName . '\' to \'' . $newName . '\'.';
337
+			}
338
+			else if ($logEntry->getAction() === 'RoleChange') {
339
+				$roleChangeData = unserialize($logEntry->getComment());
340
+
341
+				$removed = array();
342
+				foreach ($roleChangeData['removed'] as $r) {
343
+					$removed[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
344
+				}
345
+
346
+				$added = array();
347
+				foreach ($roleChangeData['added'] as $r) {
348
+					$added[] = htmlentities($r, ENT_COMPAT, 'UTF-8');
349
+				}
350
+
351
+				$reason = htmlentities($roleChangeData['reason'], ENT_COMPAT, 'UTF-8');
352
+
353
+				$roleDelta = 'Removed [' . implode(', ', $removed) . '], Added [' . implode(', ', $added) . ']';
354
+				$comment = $roleDelta . ' with comment: ' . $reason;
355
+			}
356
+			else {
357
+				$comment = $logEntry->getComment();
358
+			}
359
+
360
+			$logData[] = array(
361
+				'timestamp'         => $logEntry->getTimestamp(),
362
+				'userid'            => $logEntry->getUser(),
363
+				'username'          => $users[$logEntry->getUser()],
364
+				'description'       => self::getLogDescription($logEntry),
365
+				'objectdescription' => $objectDescription,
366
+				'comment'           => $comment,
367
+			);
368
+		}
369
+
370
+		return array($users, $logData);
371
+	}
372 372
 }
Please login to merge, or discard this patch.