Failed Conditions
Pull Request — newinternal (#527)
by Simon
17:20 queued 07:22
created
includes/Fragments/RequestData.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -129,7 +129,7 @@
 block discarded – undo
129 129
     /**
130 130
      * Assigns a Smarty variable
131 131
      *
132
-     * @param  array|string $name  the template variable name(s)
132
+     * @param  string $name  the template variable name(s)
133 133
      * @param  mixed        $value the value to assign
134 134
      */
135 135
     abstract protected function assign($name, $value);
Please login to merge, or discard this patch.
Indentation   +320 added lines, -320 removed lines patch added patch discarded remove patch
@@ -24,324 +24,324 @@
 block discarded – undo
24 24
 
25 25
 trait RequestData
26 26
 {
27
-    /**
28
-     * @var array Array of IP address classed as 'private' by RFC1918.
29
-     */
30
-    protected static $rfc1918ips = array(
31
-        "10.0.0.0"    => "10.255.255.255",
32
-        "172.16.0.0"  => "172.31.255.255",
33
-        "192.168.0.0" => "192.168.255.255",
34
-        "169.254.0.0" => "169.254.255.255",
35
-        "127.0.0.0"   => "127.255.255.255",
36
-    );
37
-
38
-    /**
39
-     * Gets a request object
40
-     *
41
-     * @param PdoDatabase $database  The database connection
42
-     * @param int         $requestId The ID of the request to retrieve
43
-     *
44
-     * @return Request
45
-     * @throws ApplicationLogicException
46
-     */
47
-    protected function getRequest(PdoDatabase $database, $requestId)
48
-    {
49
-        if ($requestId === null) {
50
-            throw new ApplicationLogicException("No request specified");
51
-        }
52
-
53
-        $request = Request::getById($requestId, $database);
54
-        if ($request === false || !is_a($request, Request::class)) {
55
-            throw new ApplicationLogicException('Could not load the requested request!');
56
-        }
57
-
58
-        return $request;
59
-    }
60
-
61
-    /**
62
-     * Returns a value stating whether the user is allowed to see private data or not
63
-     *
64
-     * @param Request $request
65
-     * @param User    $currentUser
66
-     *
67
-     * @return bool
68
-     * @category Security-Critical
69
-     */
70
-    protected function isAllowedPrivateData(Request $request, User $currentUser)
71
-    {
72
-        // Test the main security barrier for private data access using SecurityManager
73
-        if ($this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')) {
74
-            // Tool admins/check-users can always see private data
75
-            return true;
76
-        }
77
-
78
-        // reserving user is allowed to see the data
79
-        if ($currentUser->getId() === $request->getReserved()
80
-            && $request->getReserved() !== null
81
-            && $this->barrierTest('seePrivateDataWhenReserved', $currentUser, 'RequestData')
82
-        ) {
83
-            return true;
84
-        }
85
-
86
-        // user has the reveal hash
87
-        if (WebRequest::getString('hash') === $request->getRevealHash()
88
-            && $this->barrierTest('seePrivateDataWithHash', $currentUser, 'RequestData')
89
-        ) {
90
-            return true;
91
-        }
92
-
93
-        // nope. Not allowed.
94
-        return false;
95
-    }
96
-
97
-    /**
98
-     * Tests the security barrier for a specified action.
99
-     *
100
-     * Don't use within templates
101
-     *
102
-     * @param string      $action
103
-     *
104
-     * @param User        $user
105
-     * @param null|string $pageName
106
-     *
107
-     * @return bool
108
-     * @category Security-Critical
109
-     */
110
-    abstract protected function barrierTest($action, User $user, $pageName = null);
111
-
112
-    /**
113
-     * Gets the name of the route that has been passed from the request router.
114
-     * @return string
115
-     */
116
-    abstract protected function getRouteName();
117
-
118
-    /** @return SecurityManager */
119
-    abstract protected function getSecurityManager();
120
-
121
-    /**
122
-     * Sets the name of the template this page should display.
123
-     *
124
-     * @param string $name
125
-     */
126
-    abstract protected function setTemplate($name);
127
-
128
-    /** @return IXffTrustProvider */
129
-    abstract protected function getXffTrustProvider();
130
-
131
-    /** @return ILocationProvider */
132
-    abstract protected function getLocationProvider();
133
-
134
-    /** @return IRDnsProvider */
135
-    abstract protected function getRdnsProvider();
136
-
137
-    /**
138
-     * Assigns a Smarty variable
139
-     *
140
-     * @param  array|string $name  the template variable name(s)
141
-     * @param  mixed        $value the value to assign
142
-     */
143
-    abstract protected function assign($name, $value);
144
-
145
-    /**
146
-     * @param int         $requestReservationId
147
-     * @param PdoDatabase $database
148
-     * @param User        $currentUser
149
-     */
150
-    protected function setupReservationDetails($requestReservationId, PdoDatabase $database, User $currentUser)
151
-    {
152
-        $requestIsReserved = $requestReservationId !== null;
153
-        $this->assign('requestIsReserved', $requestIsReserved);
154
-        $this->assign('requestIsReservedByMe', false);
155
-
156
-        if ($requestIsReserved) {
157
-            $this->assign('requestReservedByName', User::getById($requestReservationId, $database)->getUsername());
158
-            $this->assign('requestReservedById', $requestReservationId);
159
-
160
-            if ($requestReservationId === $currentUser->getId()) {
161
-                $this->assign('requestIsReservedByMe', true);
162
-            }
163
-        }
164
-
165
-        $this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
166
-    }
167
-
168
-    /**
169
-     * Adds private request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
170
-     *
171
-     * @param Request           $request
172
-     * @param User              $currentUser
173
-     * @param SiteConfiguration $configuration
174
-     *
175
-     * @param PdoDatabase       $database
176
-     */
177
-    protected function setupPrivateData(
178
-        $request,
179
-        User $currentUser,
180
-        SiteConfiguration $configuration,
181
-        PdoDatabase $database
182
-    ) {
183
-        $xffProvider = $this->getXffTrustProvider();
184
-
185
-        $relatedEmailRequests = RequestSearchHelper::get($database)
186
-            ->byEmailAddress($request->getEmail())
187
-            ->withConfirmedEmail()
188
-            ->excludingPurgedData($configuration)
189
-            ->excludingRequest($request->getId())
190
-            ->fetch();
191
-
192
-        $this->assign('requestEmail', $request->getEmail());
193
-        $emailDomain = explode("@", $request->getEmail())[1];
194
-        $this->assign("emailurl", $emailDomain);
195
-        $this->assign('requestRelatedEmailRequestsCount', count($relatedEmailRequests));
196
-        $this->assign('requestRelatedEmailRequests', $relatedEmailRequests);
197
-
198
-        $trustedIp = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
199
-        $this->assign('requestTrustedIp', $trustedIp);
200
-        $this->assign('requestRealIp', $request->getIp());
201
-        $this->assign('requestForwardedIp', $request->getForwardedIp());
202
-
203
-        $trustedIpLocation = $this->getLocationProvider()->getIpLocation($trustedIp);
204
-        $this->assign('requestTrustedIpLocation', $trustedIpLocation);
205
-
206
-        $this->assign('requestHasForwardedIp', $request->getForwardedIp() !== null);
207
-
208
-        $relatedIpRequests = RequestSearchHelper::get($database)
209
-            ->byIp($trustedIp)
210
-            ->withConfirmedEmail()
211
-            ->excludingPurgedData($configuration)
212
-            ->excludingRequest($request->getId())
213
-            ->fetch();
214
-
215
-        $this->assign('requestRelatedIpRequestsCount', count($relatedIpRequests));
216
-        $this->assign('requestRelatedIpRequests', $relatedIpRequests);
217
-
218
-        $this->assign('showRevealLink', false);
219
-        if ($request->getReserved() === $currentUser->getId() ||
220
-            $this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
221
-        ) {
222
-            $this->assign('showRevealLink', true);
223
-            $this->assign('revealHash', $request->getRevealHash());
224
-        }
225
-
226
-        $this->setupForwardedIpData($request);
227
-    }
228
-
229
-    /**
230
-     * Adds checkuser request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
231
-     *
232
-     * @param Request $request
233
-     */
234
-    protected function setupCheckUserData(Request $request)
235
-    {
236
-        $this->assign('requestUserAgent', $request->getUserAgent());
237
-    }
238
-
239
-    /**
240
-     * Sets up the basic data for this request, and adds it to Smarty
241
-     *
242
-     * @param Request           $request
243
-     * @param SiteConfiguration $config
244
-     */
245
-    protected function setupBasicData(Request $request, SiteConfiguration $config)
246
-    {
247
-        $this->assign('requestId', $request->getId());
248
-        $this->assign('updateVersion', $request->getUpdateVersion());
249
-        $this->assign('requestName', $request->getName());
250
-        $this->assign('requestDate', $request->getDate());
251
-        $this->assign('requestStatus', $request->getStatus());
252
-
253
-        $isClosed = !array_key_exists($request->getStatus(), $config->getRequestStates())
254
-            && $request->getStatus() !== RequestStatus::HOSPITAL;
255
-        $this->assign('requestIsClosed', $isClosed);
256
-    }
257
-
258
-    /**
259
-     * Sets up the forwarded IP data for this request and adds it to Smarty
260
-     *
261
-     * @param Request $request
262
-     */
263
-    protected function setupForwardedIpData(Request $request)
264
-    {
265
-        if ($request->getForwardedIp() !== null) {
266
-            $requestProxyData = array(); // Initialize array to store data to be output in Smarty template.
267
-            $proxyIndex = 0;
268
-
269
-            // Assuming [client] <=> [proxy1] <=> [proxy2] <=> [proxy3] <=> [us], we will see an XFF header of [client],
270
-            // [proxy1], [proxy2], and our actual IP will be [proxy3]
271
-            $proxies = explode(",", $request->getForwardedIp());
272
-            $proxies[] = $request->getIp();
273
-
274
-            // Origin is the supposed "client" IP.
275
-            $origin = $proxies[0];
276
-            $this->assign("forwardedOrigin", $origin);
277
-
278
-            // We step through the servers in reverse order, from closest to furthest
279
-            $proxies = array_reverse($proxies);
280
-
281
-            // By default, we have trust, because the first in the chain is now REMOTE_ADDR, which is hardest to spoof.
282
-            $trust = true;
283
-
284
-            /**
285
-             * @var int    $index     The zero-based index of the proxy.
286
-             * @var string $proxyData The proxy IP address (although possibly not!)
287
-             */
288
-            foreach ($proxies as $index => $proxyData) {
289
-                $proxyAddress = trim($proxyData);
290
-                $requestProxyData[$proxyIndex]['ip'] = $proxyAddress;
291
-
292
-                // get data on this IP.
293
-                $thisProxyIsTrusted = $this->getXffTrustProvider()->isTrusted($proxyAddress);
294
-
295
-                $proxyIsInPrivateRange = $this->getXffTrustProvider()
296
-                    ->ipInRange(self::$rfc1918ips, $proxyAddress);
297
-
298
-                if (!$proxyIsInPrivateRange) {
299
-                    $proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
300
-                    $proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
301
-                }
302
-                else {
303
-                    // this is going to fail, so why bother trying?
304
-                    $proxyReverseDns = false;
305
-                    $proxyLocation = false;
306
-                }
307
-
308
-                // current trust chain status BEFORE this link
309
-                $preLinkTrust = $trust;
310
-
311
-                // is *this* link trusted? Note, this will be true even if there is an untrusted link before this!
312
-                $requestProxyData[$proxyIndex]['trustedlink'] = $thisProxyIsTrusted;
313
-
314
-                // set the trust status of the chain to this point
315
-                $trust = $trust & $thisProxyIsTrusted;
316
-
317
-                // If this is the origin address, and the chain was trusted before this point, then we can trust
318
-                // the origin.
319
-                if ($preLinkTrust && $proxyAddress == $origin) {
320
-                    // if this is the origin, then we are at the last point in the chain.
321
-                    // @todo: this is probably the cause of some bugs when an IP appears twice - we're missing a check
322
-                    // to see if this is *really* the last in the chain, rather than just the same IP as it.
323
-                    $trust = true;
324
-                }
325
-
326
-                $requestProxyData[$proxyIndex]['trust'] = $trust;
327
-
328
-                $requestProxyData[$proxyIndex]['rdnsfailed'] = $proxyReverseDns === false;
329
-                $requestProxyData[$proxyIndex]['rdns'] = $proxyReverseDns;
330
-                $requestProxyData[$proxyIndex]['routable'] = !$proxyIsInPrivateRange;
331
-
332
-                $requestProxyData[$proxyIndex]['location'] = $proxyLocation;
333
-
334
-                if ($proxyReverseDns === $proxyAddress && $proxyIsInPrivateRange === false) {
335
-                    $requestProxyData[$proxyIndex]['rdns'] = null;
336
-                }
337
-
338
-                $showLinks = (!$trust || $proxyAddress == $origin) && !$proxyIsInPrivateRange;
339
-                $requestProxyData[$proxyIndex]['showlinks'] = $showLinks;
340
-
341
-                $proxyIndex++;
342
-            }
343
-
344
-            $this->assign("requestProxyData", $requestProxyData);
345
-        }
346
-    }
27
+	/**
28
+	 * @var array Array of IP address classed as 'private' by RFC1918.
29
+	 */
30
+	protected static $rfc1918ips = array(
31
+		"10.0.0.0"    => "10.255.255.255",
32
+		"172.16.0.0"  => "172.31.255.255",
33
+		"192.168.0.0" => "192.168.255.255",
34
+		"169.254.0.0" => "169.254.255.255",
35
+		"127.0.0.0"   => "127.255.255.255",
36
+	);
37
+
38
+	/**
39
+	 * Gets a request object
40
+	 *
41
+	 * @param PdoDatabase $database  The database connection
42
+	 * @param int         $requestId The ID of the request to retrieve
43
+	 *
44
+	 * @return Request
45
+	 * @throws ApplicationLogicException
46
+	 */
47
+	protected function getRequest(PdoDatabase $database, $requestId)
48
+	{
49
+		if ($requestId === null) {
50
+			throw new ApplicationLogicException("No request specified");
51
+		}
52
+
53
+		$request = Request::getById($requestId, $database);
54
+		if ($request === false || !is_a($request, Request::class)) {
55
+			throw new ApplicationLogicException('Could not load the requested request!');
56
+		}
57
+
58
+		return $request;
59
+	}
60
+
61
+	/**
62
+	 * Returns a value stating whether the user is allowed to see private data or not
63
+	 *
64
+	 * @param Request $request
65
+	 * @param User    $currentUser
66
+	 *
67
+	 * @return bool
68
+	 * @category Security-Critical
69
+	 */
70
+	protected function isAllowedPrivateData(Request $request, User $currentUser)
71
+	{
72
+		// Test the main security barrier for private data access using SecurityManager
73
+		if ($this->barrierTest('alwaysSeePrivateData', $currentUser, 'RequestData')) {
74
+			// Tool admins/check-users can always see private data
75
+			return true;
76
+		}
77
+
78
+		// reserving user is allowed to see the data
79
+		if ($currentUser->getId() === $request->getReserved()
80
+			&& $request->getReserved() !== null
81
+			&& $this->barrierTest('seePrivateDataWhenReserved', $currentUser, 'RequestData')
82
+		) {
83
+			return true;
84
+		}
85
+
86
+		// user has the reveal hash
87
+		if (WebRequest::getString('hash') === $request->getRevealHash()
88
+			&& $this->barrierTest('seePrivateDataWithHash', $currentUser, 'RequestData')
89
+		) {
90
+			return true;
91
+		}
92
+
93
+		// nope. Not allowed.
94
+		return false;
95
+	}
96
+
97
+	/**
98
+	 * Tests the security barrier for a specified action.
99
+	 *
100
+	 * Don't use within templates
101
+	 *
102
+	 * @param string      $action
103
+	 *
104
+	 * @param User        $user
105
+	 * @param null|string $pageName
106
+	 *
107
+	 * @return bool
108
+	 * @category Security-Critical
109
+	 */
110
+	abstract protected function barrierTest($action, User $user, $pageName = null);
111
+
112
+	/**
113
+	 * Gets the name of the route that has been passed from the request router.
114
+	 * @return string
115
+	 */
116
+	abstract protected function getRouteName();
117
+
118
+	/** @return SecurityManager */
119
+	abstract protected function getSecurityManager();
120
+
121
+	/**
122
+	 * Sets the name of the template this page should display.
123
+	 *
124
+	 * @param string $name
125
+	 */
126
+	abstract protected function setTemplate($name);
127
+
128
+	/** @return IXffTrustProvider */
129
+	abstract protected function getXffTrustProvider();
130
+
131
+	/** @return ILocationProvider */
132
+	abstract protected function getLocationProvider();
133
+
134
+	/** @return IRDnsProvider */
135
+	abstract protected function getRdnsProvider();
136
+
137
+	/**
138
+	 * Assigns a Smarty variable
139
+	 *
140
+	 * @param  array|string $name  the template variable name(s)
141
+	 * @param  mixed        $value the value to assign
142
+	 */
143
+	abstract protected function assign($name, $value);
144
+
145
+	/**
146
+	 * @param int         $requestReservationId
147
+	 * @param PdoDatabase $database
148
+	 * @param User        $currentUser
149
+	 */
150
+	protected function setupReservationDetails($requestReservationId, PdoDatabase $database, User $currentUser)
151
+	{
152
+		$requestIsReserved = $requestReservationId !== null;
153
+		$this->assign('requestIsReserved', $requestIsReserved);
154
+		$this->assign('requestIsReservedByMe', false);
155
+
156
+		if ($requestIsReserved) {
157
+			$this->assign('requestReservedByName', User::getById($requestReservationId, $database)->getUsername());
158
+			$this->assign('requestReservedById', $requestReservationId);
159
+
160
+			if ($requestReservationId === $currentUser->getId()) {
161
+				$this->assign('requestIsReservedByMe', true);
162
+			}
163
+		}
164
+
165
+		$this->assign('canBreakReservation', $this->barrierTest('force', $currentUser, PageBreakReservation::class));
166
+	}
167
+
168
+	/**
169
+	 * Adds private request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
170
+	 *
171
+	 * @param Request           $request
172
+	 * @param User              $currentUser
173
+	 * @param SiteConfiguration $configuration
174
+	 *
175
+	 * @param PdoDatabase       $database
176
+	 */
177
+	protected function setupPrivateData(
178
+		$request,
179
+		User $currentUser,
180
+		SiteConfiguration $configuration,
181
+		PdoDatabase $database
182
+	) {
183
+		$xffProvider = $this->getXffTrustProvider();
184
+
185
+		$relatedEmailRequests = RequestSearchHelper::get($database)
186
+			->byEmailAddress($request->getEmail())
187
+			->withConfirmedEmail()
188
+			->excludingPurgedData($configuration)
189
+			->excludingRequest($request->getId())
190
+			->fetch();
191
+
192
+		$this->assign('requestEmail', $request->getEmail());
193
+		$emailDomain = explode("@", $request->getEmail())[1];
194
+		$this->assign("emailurl", $emailDomain);
195
+		$this->assign('requestRelatedEmailRequestsCount', count($relatedEmailRequests));
196
+		$this->assign('requestRelatedEmailRequests', $relatedEmailRequests);
197
+
198
+		$trustedIp = $xffProvider->getTrustedClientIp($request->getIp(), $request->getForwardedIp());
199
+		$this->assign('requestTrustedIp', $trustedIp);
200
+		$this->assign('requestRealIp', $request->getIp());
201
+		$this->assign('requestForwardedIp', $request->getForwardedIp());
202
+
203
+		$trustedIpLocation = $this->getLocationProvider()->getIpLocation($trustedIp);
204
+		$this->assign('requestTrustedIpLocation', $trustedIpLocation);
205
+
206
+		$this->assign('requestHasForwardedIp', $request->getForwardedIp() !== null);
207
+
208
+		$relatedIpRequests = RequestSearchHelper::get($database)
209
+			->byIp($trustedIp)
210
+			->withConfirmedEmail()
211
+			->excludingPurgedData($configuration)
212
+			->excludingRequest($request->getId())
213
+			->fetch();
214
+
215
+		$this->assign('requestRelatedIpRequestsCount', count($relatedIpRequests));
216
+		$this->assign('requestRelatedIpRequests', $relatedIpRequests);
217
+
218
+		$this->assign('showRevealLink', false);
219
+		if ($request->getReserved() === $currentUser->getId() ||
220
+			$this->barrierTest('alwaysSeeHash', $currentUser, 'RequestData')
221
+		) {
222
+			$this->assign('showRevealLink', true);
223
+			$this->assign('revealHash', $request->getRevealHash());
224
+		}
225
+
226
+		$this->setupForwardedIpData($request);
227
+	}
228
+
229
+	/**
230
+	 * Adds checkuser request data to Smarty. DO NOT USE WITHOUT FIRST CHECKING THAT THE USER IS AUTHORISED!
231
+	 *
232
+	 * @param Request $request
233
+	 */
234
+	protected function setupCheckUserData(Request $request)
235
+	{
236
+		$this->assign('requestUserAgent', $request->getUserAgent());
237
+	}
238
+
239
+	/**
240
+	 * Sets up the basic data for this request, and adds it to Smarty
241
+	 *
242
+	 * @param Request           $request
243
+	 * @param SiteConfiguration $config
244
+	 */
245
+	protected function setupBasicData(Request $request, SiteConfiguration $config)
246
+	{
247
+		$this->assign('requestId', $request->getId());
248
+		$this->assign('updateVersion', $request->getUpdateVersion());
249
+		$this->assign('requestName', $request->getName());
250
+		$this->assign('requestDate', $request->getDate());
251
+		$this->assign('requestStatus', $request->getStatus());
252
+
253
+		$isClosed = !array_key_exists($request->getStatus(), $config->getRequestStates())
254
+			&& $request->getStatus() !== RequestStatus::HOSPITAL;
255
+		$this->assign('requestIsClosed', $isClosed);
256
+	}
257
+
258
+	/**
259
+	 * Sets up the forwarded IP data for this request and adds it to Smarty
260
+	 *
261
+	 * @param Request $request
262
+	 */
263
+	protected function setupForwardedIpData(Request $request)
264
+	{
265
+		if ($request->getForwardedIp() !== null) {
266
+			$requestProxyData = array(); // Initialize array to store data to be output in Smarty template.
267
+			$proxyIndex = 0;
268
+
269
+			// Assuming [client] <=> [proxy1] <=> [proxy2] <=> [proxy3] <=> [us], we will see an XFF header of [client],
270
+			// [proxy1], [proxy2], and our actual IP will be [proxy3]
271
+			$proxies = explode(",", $request->getForwardedIp());
272
+			$proxies[] = $request->getIp();
273
+
274
+			// Origin is the supposed "client" IP.
275
+			$origin = $proxies[0];
276
+			$this->assign("forwardedOrigin", $origin);
277
+
278
+			// We step through the servers in reverse order, from closest to furthest
279
+			$proxies = array_reverse($proxies);
280
+
281
+			// By default, we have trust, because the first in the chain is now REMOTE_ADDR, which is hardest to spoof.
282
+			$trust = true;
283
+
284
+			/**
285
+			 * @var int    $index     The zero-based index of the proxy.
286
+			 * @var string $proxyData The proxy IP address (although possibly not!)
287
+			 */
288
+			foreach ($proxies as $index => $proxyData) {
289
+				$proxyAddress = trim($proxyData);
290
+				$requestProxyData[$proxyIndex]['ip'] = $proxyAddress;
291
+
292
+				// get data on this IP.
293
+				$thisProxyIsTrusted = $this->getXffTrustProvider()->isTrusted($proxyAddress);
294
+
295
+				$proxyIsInPrivateRange = $this->getXffTrustProvider()
296
+					->ipInRange(self::$rfc1918ips, $proxyAddress);
297
+
298
+				if (!$proxyIsInPrivateRange) {
299
+					$proxyReverseDns = $this->getRdnsProvider()->getReverseDNS($proxyAddress);
300
+					$proxyLocation = $this->getLocationProvider()->getIpLocation($proxyAddress);
301
+				}
302
+				else {
303
+					// this is going to fail, so why bother trying?
304
+					$proxyReverseDns = false;
305
+					$proxyLocation = false;
306
+				}
307
+
308
+				// current trust chain status BEFORE this link
309
+				$preLinkTrust = $trust;
310
+
311
+				// is *this* link trusted? Note, this will be true even if there is an untrusted link before this!
312
+				$requestProxyData[$proxyIndex]['trustedlink'] = $thisProxyIsTrusted;
313
+
314
+				// set the trust status of the chain to this point
315
+				$trust = $trust & $thisProxyIsTrusted;
316
+
317
+				// If this is the origin address, and the chain was trusted before this point, then we can trust
318
+				// the origin.
319
+				if ($preLinkTrust && $proxyAddress == $origin) {
320
+					// if this is the origin, then we are at the last point in the chain.
321
+					// @todo: this is probably the cause of some bugs when an IP appears twice - we're missing a check
322
+					// to see if this is *really* the last in the chain, rather than just the same IP as it.
323
+					$trust = true;
324
+				}
325
+
326
+				$requestProxyData[$proxyIndex]['trust'] = $trust;
327
+
328
+				$requestProxyData[$proxyIndex]['rdnsfailed'] = $proxyReverseDns === false;
329
+				$requestProxyData[$proxyIndex]['rdns'] = $proxyReverseDns;
330
+				$requestProxyData[$proxyIndex]['routable'] = !$proxyIsInPrivateRange;
331
+
332
+				$requestProxyData[$proxyIndex]['location'] = $proxyLocation;
333
+
334
+				if ($proxyReverseDns === $proxyAddress && $proxyIsInPrivateRange === false) {
335
+					$requestProxyData[$proxyIndex]['rdns'] = null;
336
+				}
337
+
338
+				$showLinks = (!$trust || $proxyAddress == $origin) && !$proxyIsInPrivateRange;
339
+				$requestProxyData[$proxyIndex]['showlinks'] = $showLinks;
340
+
341
+				$proxyIndex++;
342
+			}
343
+
344
+			$this->assign("requestProxyData", $requestProxyData);
345
+		}
346
+	}
347 347
 }
Please login to merge, or discard this patch.
includes/Router/PublicRequestRouter.php 2 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@
 block discarded – undo
47 47
     /**
48 48
      * Gets the default route if no explicit route is requested.
49 49
      *
50
-     * @return callable
50
+     * @return string[]
51 51
      */
52 52
     protected function getDefaultRoute()
53 53
     {
Please login to merge, or discard this patch.
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -15,42 +15,42 @@
 block discarded – undo
15 15
 
16 16
 class PublicRequestRouter extends RequestRouter
17 17
 {
18
-    /**
19
-     * Gets the route map to be used by this request router.
20
-     *
21
-     * @return array
22
-     */
23
-    protected function getRouteMap()
24
-    {
25
-        return array(
26
-            // Page showing a message stating the request has been submitted to our internal queues
27
-            'requestSubmitted'          =>
28
-                array(
29
-                    'class'   => PageRequestSubmitted::class,
30
-                    'actions' => array(),
31
-                ),
32
-            // Page showing a message stating that email confirmation is required to continue
33
-            'emailConfirmationRequired' =>
34
-                array(
35
-                    'class'   => PageEmailConfirmationRequired::class,
36
-                    'actions' => array(),
37
-                ),
38
-            // Action page which handles email confirmation
39
-            'confirmEmail'              =>
40
-                array(
41
-                    'class'   => PageConfirmEmail::class,
42
-                    'actions' => array(),
43
-                ),
44
-        );
45
-    }
18
+	/**
19
+	 * Gets the route map to be used by this request router.
20
+	 *
21
+	 * @return array
22
+	 */
23
+	protected function getRouteMap()
24
+	{
25
+		return array(
26
+			// Page showing a message stating the request has been submitted to our internal queues
27
+			'requestSubmitted'          =>
28
+				array(
29
+					'class'   => PageRequestSubmitted::class,
30
+					'actions' => array(),
31
+				),
32
+			// Page showing a message stating that email confirmation is required to continue
33
+			'emailConfirmationRequired' =>
34
+				array(
35
+					'class'   => PageEmailConfirmationRequired::class,
36
+					'actions' => array(),
37
+				),
38
+			// Action page which handles email confirmation
39
+			'confirmEmail'              =>
40
+				array(
41
+					'class'   => PageConfirmEmail::class,
42
+					'actions' => array(),
43
+				),
44
+		);
45
+	}
46 46
 
47
-    /**
48
-     * Gets the default route if no explicit route is requested.
49
-     *
50
-     * @return callable
51
-     */
52
-    protected function getDefaultRoute()
53
-    {
54
-        return array(PageRequestAccount::class, 'main');
55
-    }
47
+	/**
48
+	 * Gets the default route if no explicit route is requested.
49
+	 *
50
+	 * @return callable
51
+	 */
52
+	protected function getDefaultRoute()
53
+	{
54
+		return array(PageRequestAccount::class, 'main');
55
+	}
56 56
 }
57 57
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Router/RequestRouter.php 4 patches
Doc Comments   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -435,7 +435,7 @@
 block discarded – undo
435 435
     }
436 436
 
437 437
     /**
438
-     * @return callable
438
+     * @return string[]
439 439
      */
440 440
     protected function getDefaultRoute()
441 441
     {
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -358,7 +358,7 @@
 block discarded – undo
358 358
         $routeMap = $this->routePathSegments($classSegment, $requestedAction);
359 359
 
360 360
         if ($routeMap[0] === Page404::class) {
361
-            $routeMap = $this->routeSinglePathSegment($classSegment . '/' . $requestedAction);
361
+            $routeMap = $this->routeSinglePathSegment($classSegment.'/'.$requestedAction);
362 362
         }
363 363
 
364 364
         return $routeMap;
Please login to merge, or discard this patch.
Unused Use Statements   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -15,27 +15,20 @@  discard block
 block discarded – undo
15 15
 use Waca\Pages\PageEmailManagement;
16 16
 use Waca\Pages\PageExpandedRequestList;
17 17
 use Waca\Pages\PageJobQueue;
18
-use Waca\Pages\RequestAction\PageCreateRequest;
19
-use Waca\Pages\UserAuth\PageChangePassword;
20
-use Waca\Pages\UserAuth\PageForgotPassword;
21 18
 use Waca\Pages\PageLog;
22
-use Waca\Pages\UserAuth\PageLogin;
23
-use Waca\Pages\UserAuth\PageLogout;
24 19
 use Waca\Pages\PageMain;
25
-use Waca\Pages\UserAuth\PageOAuth;
26
-use Waca\Pages\UserAuth\PageOAuthCallback;
27
-use Waca\Pages\UserAuth\PagePreferences;
28
-use Waca\Pages\Registration\PageRegisterStandard;
29
-use Waca\Pages\Registration\PageRegisterOption;
30 20
 use Waca\Pages\PageSearch;
31 21
 use Waca\Pages\PageSiteNotice;
32 22
 use Waca\Pages\PageTeam;
33 23
 use Waca\Pages\PageUserManagement;
34 24
 use Waca\Pages\PageViewRequest;
35 25
 use Waca\Pages\PageWelcomeTemplateManagement;
26
+use Waca\Pages\Registration\PageRegisterOption;
27
+use Waca\Pages\Registration\PageRegisterStandard;
36 28
 use Waca\Pages\RequestAction\PageBreakReservation;
37 29
 use Waca\Pages\RequestAction\PageCloseRequest;
38 30
 use Waca\Pages\RequestAction\PageComment;
31
+use Waca\Pages\RequestAction\PageCreateRequest;
39 32
 use Waca\Pages\RequestAction\PageCustomClose;
40 33
 use Waca\Pages\RequestAction\PageDeferRequest;
41 34
 use Waca\Pages\RequestAction\PageDropRequest;
@@ -49,6 +42,13 @@  discard block
 block discarded – undo
49 42
 use Waca\Pages\Statistics\StatsTemplateStats;
50 43
 use Waca\Pages\Statistics\StatsTopCreators;
51 44
 use Waca\Pages\Statistics\StatsUsers;
45
+use Waca\Pages\UserAuth\PageChangePassword;
46
+use Waca\Pages\UserAuth\PageForgotPassword;
47
+use Waca\Pages\UserAuth\PageLogin;
48
+use Waca\Pages\UserAuth\PageLogout;
49
+use Waca\Pages\UserAuth\PageOAuth;
50
+use Waca\Pages\UserAuth\PageOAuthCallback;
51
+use Waca\Pages\UserAuth\PagePreferences;
52 52
 use Waca\Tasks\IRoutedTask;
53 53
 use Waca\WebRequest;
54 54
 
Please login to merge, or discard this patch.
Indentation   +411 added lines, -411 removed lines patch added patch discarded remove patch
@@ -59,415 +59,415 @@
 block discarded – undo
59 59
  */
60 60
 class RequestRouter implements IRequestRouter
61 61
 {
62
-    /**
63
-     * This is the core routing table for the application. The basic idea is:
64
-     *
65
-     *      array(
66
-     *          "foo" =>
67
-     *              array(
68
-     *                  "class"   => PageFoo::class,
69
-     *                  "actions" => array("bar", "other")
70
-     *              ),
71
-     * );
72
-     *
73
-     * Things to note:
74
-     *     - If no page is requested, we go to PageMain. PageMain can't have actions defined.
75
-     *
76
-     *     - If a page is defined and requested, but no action is requested, go to that page's main() method
77
-     *     - If a page is defined and requested, and an action is defined and requested, go to that action's method.
78
-     *     - If a page is defined and requested, and an action NOT defined and requested, go to Page404 and it's main()
79
-     *       method.
80
-     *     - If a page is NOT defined and requested, go to Page404 and it's main() method.
81
-     *
82
-     *     - Query parameters are ignored.
83
-     *
84
-     * The key point here is request routing with validation that this is allowed, before we start hitting the
85
-     * filesystem through the AutoLoader, and opening random files. Also, so that we validate the action requested
86
-     * before we start calling random methods through the web UI.
87
-     *
88
-     * Examples:
89
-     * /internal.php                => returns instance of PageMain, routed to main()
90
-     * /internal.php?query          => returns instance of PageMain, routed to main()
91
-     * /internal.php/foo            => returns instance of PageFoo, routed to main()
92
-     * /internal.php/foo?query      => returns instance of PageFoo, routed to main()
93
-     * /internal.php/foo/bar        => returns instance of PageFoo, routed to bar()
94
-     * /internal.php/foo/bar?query  => returns instance of PageFoo, routed to bar()
95
-     * /internal.php/foo/baz        => returns instance of Page404, routed to main()
96
-     * /internal.php/foo/baz?query  => returns instance of Page404, routed to main()
97
-     * /internal.php/bar            => returns instance of Page404, routed to main()
98
-     * /internal.php/bar?query      => returns instance of Page404, routed to main()
99
-     * /internal.php/bar/baz        => returns instance of Page404, routed to main()
100
-     * /internal.php/bar/baz?query  => returns instance of Page404, routed to main()
101
-     *
102
-     * Take care when changing this - a lot of places rely on the array key for redirects and other links. If you need
103
-     * to change the key, then you'll likely have to update a lot of files.
104
-     *
105
-     * @var array
106
-     */
107
-    private $routeMap = array(
108
-
109
-        //////////////////////////////////////////////////////////////////////////////////////////////////
110
-        // Login and registration
111
-        'logout'                      =>
112
-            array(
113
-                'class'   => PageLogout::class,
114
-                'actions' => array(),
115
-            ),
116
-        'login'                       =>
117
-            array(
118
-                'class'   => PageLogin::class,
119
-                'actions' => array(),
120
-            ),
121
-        'forgotPassword'              =>
122
-            array(
123
-                'class'   => PageForgotPassword::class,
124
-                'actions' => array('reset'),
125
-            ),
126
-        'register'                    =>
127
-            array(
128
-                'class'   => PageRegisterOption::class,
129
-                'actions' => array(),
130
-            ),
131
-        'register/standard'           =>
132
-            array(
133
-                'class'   => PageRegisterStandard::class,
134
-                'actions' => array('done'),
135
-            ),
136
-
137
-        //////////////////////////////////////////////////////////////////////////////////////////////////
138
-        // Discovery
139
-        'search'                      =>
140
-            array(
141
-                'class'   => PageSearch::class,
142
-                'actions' => array(),
143
-            ),
144
-        'logs'                        =>
145
-            array(
146
-                'class'   => PageLog::class,
147
-                'actions' => array(),
148
-            ),
149
-
150
-        //////////////////////////////////////////////////////////////////////////////////////////////////
151
-        // Administration
152
-        'bans'                        =>
153
-            array(
154
-                'class'   => PageBan::class,
155
-                'actions' => array('set', 'remove'),
156
-            ),
157
-        'userManagement'              =>
158
-            array(
159
-                'class'   => PageUserManagement::class,
160
-                'actions' => array(
161
-                    'approve',
162
-                    'decline',
163
-                    'rename',
164
-                    'editUser',
165
-                    'suspend',
166
-                    'editRoles',
167
-                ),
168
-            ),
169
-        'siteNotice'                  =>
170
-            array(
171
-                'class'   => PageSiteNotice::class,
172
-                'actions' => array(),
173
-            ),
174
-        'emailManagement'             =>
175
-            array(
176
-                'class'   => PageEmailManagement::class,
177
-                'actions' => array('create', 'edit', 'view'),
178
-            ),
179
-        'jobQueue'                    =>
180
-            array(
181
-                'class'   => PageJobQueue::class,
182
-                'actions' => array('acknowledge', 'requeue', 'view', 'all'),
183
-            ),
184
-
185
-        //////////////////////////////////////////////////////////////////////////////////////////////////
186
-        // Personal preferences
187
-        'preferences'                 =>
188
-            array(
189
-                'class'   => PagePreferences::class,
190
-                'actions' => array(),
191
-            ),
192
-        'changePassword'              =>
193
-            array(
194
-                'class'   => PageChangePassword::class,
195
-                'actions' => array(),
196
-            ),
197
-        'oauth'                       =>
198
-            array(
199
-                'class'   => PageOAuth::class,
200
-                'actions' => array('detach', 'attach'),
201
-            ),
202
-        'oauth/callback'              =>
203
-            array(
204
-                'class' => PageOAuthCallback::class,
205
-                'actions' => array('authorise', 'create'),
206
-            ),
207
-
208
-        //////////////////////////////////////////////////////////////////////////////////////////////////
209
-        // Welcomer configuration
210
-        'welcomeTemplates'            =>
211
-            array(
212
-                'class'   => PageWelcomeTemplateManagement::class,
213
-                'actions' => array('select', 'edit', 'delete', 'add', 'view'),
214
-            ),
215
-
216
-        //////////////////////////////////////////////////////////////////////////////////////////////////
217
-        // Statistics
218
-        'statistics'                  =>
219
-            array(
220
-                'class'   => StatsMain::class,
221
-                'actions' => array(),
222
-            ),
223
-        'statistics/fastCloses'       =>
224
-            array(
225
-                'class'   => StatsFastCloses::class,
226
-                'actions' => array(),
227
-            ),
228
-        'statistics/inactiveUsers'    =>
229
-            array(
230
-                'class'   => StatsInactiveUsers::class,
231
-                'actions' => array(),
232
-            ),
233
-        'statistics/monthlyStats'     =>
234
-            array(
235
-                'class'   => StatsMonthlyStats::class,
236
-                'actions' => array(),
237
-            ),
238
-        'statistics/reservedRequests' =>
239
-            array(
240
-                'class'   => StatsReservedRequests::class,
241
-                'actions' => array(),
242
-            ),
243
-        'statistics/templateStats'    =>
244
-            array(
245
-                'class'   => StatsTemplateStats::class,
246
-                'actions' => array(),
247
-            ),
248
-        'statistics/topCreators'      =>
249
-            array(
250
-                'class'   => StatsTopCreators::class,
251
-                'actions' => array(),
252
-            ),
253
-        'statistics/users'            =>
254
-            array(
255
-                'class'   => StatsUsers::class,
256
-                'actions' => array('detail'),
257
-            ),
258
-
259
-        //////////////////////////////////////////////////////////////////////////////////////////////////
260
-        // Zoom page
261
-        'viewRequest'                 =>
262
-            array(
263
-                'class'   => PageViewRequest::class,
264
-                'actions' => array(),
265
-            ),
266
-        'viewRequest/reserve'         =>
267
-            array(
268
-                'class'   => PageReservation::class,
269
-                'actions' => array(),
270
-            ),
271
-        'viewRequest/breakReserve'    =>
272
-            array(
273
-                'class'   => PageBreakReservation::class,
274
-                'actions' => array(),
275
-            ),
276
-        'viewRequest/defer'           =>
277
-            array(
278
-                'class'   => PageDeferRequest::class,
279
-                'actions' => array(),
280
-            ),
281
-        'viewRequest/comment'         =>
282
-            array(
283
-                'class'   => PageComment::class,
284
-                'actions' => array(),
285
-            ),
286
-        'viewRequest/sendToUser'      =>
287
-            array(
288
-                'class'   => PageSendToUser::class,
289
-                'actions' => array(),
290
-            ),
291
-        'viewRequest/close'           =>
292
-            array(
293
-                'class'   => PageCloseRequest::class,
294
-                'actions' => array(),
295
-            ),
296
-        'viewRequest/create'           =>
297
-            array(
298
-                'class'   => PageCreateRequest::class,
299
-                'actions' => array(),
300
-            ),
301
-        'viewRequest/drop'            =>
302
-            array(
303
-                'class'   => PageDropRequest::class,
304
-                'actions' => array(),
305
-            ),
306
-        'viewRequest/custom'          =>
307
-            array(
308
-                'class'   => PageCustomClose::class,
309
-                'actions' => array(),
310
-            ),
311
-        'editComment'                 =>
312
-            array(
313
-                'class'   => PageEditComment::class,
314
-                'actions' => array(),
315
-            ),
316
-
317
-        //////////////////////////////////////////////////////////////////////////////////////////////////
318
-        // Misc stuff
319
-        'team'                        =>
320
-            array(
321
-                'class'   => PageTeam::class,
322
-                'actions' => array(),
323
-            ),
324
-        'requestList'                 =>
325
-            array(
326
-                'class'   => PageExpandedRequestList::class,
327
-                'actions' => array(),
328
-            ),
329
-    );
330
-
331
-    /**
332
-     * @return IRoutedTask
333
-     * @throws Exception
334
-     */
335
-    final public function route()
336
-    {
337
-        $pathInfo = WebRequest::pathInfo();
338
-
339
-        list($pageClass, $action) = $this->getRouteFromPath($pathInfo);
340
-
341
-        /** @var IRoutedTask $page */
342
-        $page = new $pageClass();
343
-
344
-        // Dynamic creation, so we've got to be careful here. We can't use built-in language type protection, so
345
-        // let's use our own.
346
-        if (!($page instanceof IRoutedTask)) {
347
-            throw new Exception('Expected a page, but this is not a page.');
348
-        }
349
-
350
-        // OK, I'm happy at this point that we know we're running a page, and we know it's probably what we want if it
351
-        // inherits PageBase and has been created from the routing map.
352
-        $page->setRoute($action);
353
-
354
-        return $page;
355
-    }
356
-
357
-    /**
358
-     * @param $pathInfo
359
-     *
360
-     * @return array
361
-     */
362
-    protected function getRouteFromPath($pathInfo)
363
-    {
364
-        if (count($pathInfo) === 0) {
365
-            // No pathInfo, so no page to load. Load the main page.
366
-            return $this->getDefaultRoute();
367
-        }
368
-        elseif (count($pathInfo) === 1) {
369
-            // Exactly one path info segment, it's got to be a page.
370
-            $classSegment = $pathInfo[0];
371
-
372
-            return $this->routeSinglePathSegment($classSegment);
373
-        }
374
-
375
-        // OK, we have two or more segments now.
376
-        if (count($pathInfo) > 2) {
377
-            // Let's handle more than two, and collapse it down into two.
378
-            $requestedAction = array_pop($pathInfo);
379
-            $classSegment = implode('/', $pathInfo);
380
-        }
381
-        else {
382
-            // Two path info segments.
383
-            $classSegment = $pathInfo[0];
384
-            $requestedAction = $pathInfo[1];
385
-        }
386
-
387
-        $routeMap = $this->routePathSegments($classSegment, $requestedAction);
388
-
389
-        if ($routeMap[0] === Page404::class) {
390
-            $routeMap = $this->routeSinglePathSegment($classSegment . '/' . $requestedAction);
391
-        }
392
-
393
-        return $routeMap;
394
-    }
395
-
396
-    /**
397
-     * @param $classSegment
398
-     *
399
-     * @return array
400
-     */
401
-    final protected function routeSinglePathSegment($classSegment)
402
-    {
403
-        $routeMap = $this->getRouteMap();
404
-        if (array_key_exists($classSegment, $routeMap)) {
405
-            // Route exists, but we don't have an action in path info, so default to main.
406
-            $pageClass = $routeMap[$classSegment]['class'];
407
-            $action = 'main';
408
-
409
-            return array($pageClass, $action);
410
-        }
411
-        else {
412
-            // Doesn't exist in map. Fall back to 404
413
-            $pageClass = Page404::class;
414
-            $action = "main";
415
-
416
-            return array($pageClass, $action);
417
-        }
418
-    }
419
-
420
-    /**
421
-     * @param $classSegment
422
-     * @param $requestedAction
423
-     *
424
-     * @return array
425
-     */
426
-    final protected function routePathSegments($classSegment, $requestedAction)
427
-    {
428
-        $routeMap = $this->getRouteMap();
429
-        if (array_key_exists($classSegment, $routeMap)) {
430
-            // Route exists, but we don't have an action in path info, so default to main.
431
-
432
-            if (isset($routeMap[$classSegment]['actions'])
433
-                && array_search($requestedAction, $routeMap[$classSegment]['actions']) !== false
434
-            ) {
435
-                // Action exists in allowed action list. Allow both the page and the action
436
-                $pageClass = $routeMap[$classSegment]['class'];
437
-                $action = $requestedAction;
438
-
439
-                return array($pageClass, $action);
440
-            }
441
-            else {
442
-                // Valid page, invalid action. 404 our way out.
443
-                $pageClass = Page404::class;
444
-                $action = 'main';
445
-
446
-                return array($pageClass, $action);
447
-            }
448
-        }
449
-        else {
450
-            // Class doesn't exist in map. Fall back to 404
451
-            $pageClass = Page404::class;
452
-            $action = 'main';
453
-
454
-            return array($pageClass, $action);
455
-        }
456
-    }
457
-
458
-    /**
459
-     * @return array
460
-     */
461
-    protected function getRouteMap()
462
-    {
463
-        return $this->routeMap;
464
-    }
465
-
466
-    /**
467
-     * @return callable
468
-     */
469
-    protected function getDefaultRoute()
470
-    {
471
-        return array(PageMain::class, "main");
472
-    }
62
+	/**
63
+	 * This is the core routing table for the application. The basic idea is:
64
+	 *
65
+	 *      array(
66
+	 *          "foo" =>
67
+	 *              array(
68
+	 *                  "class"   => PageFoo::class,
69
+	 *                  "actions" => array("bar", "other")
70
+	 *              ),
71
+	 * );
72
+	 *
73
+	 * Things to note:
74
+	 *     - If no page is requested, we go to PageMain. PageMain can't have actions defined.
75
+	 *
76
+	 *     - If a page is defined and requested, but no action is requested, go to that page's main() method
77
+	 *     - If a page is defined and requested, and an action is defined and requested, go to that action's method.
78
+	 *     - If a page is defined and requested, and an action NOT defined and requested, go to Page404 and it's main()
79
+	 *       method.
80
+	 *     - If a page is NOT defined and requested, go to Page404 and it's main() method.
81
+	 *
82
+	 *     - Query parameters are ignored.
83
+	 *
84
+	 * The key point here is request routing with validation that this is allowed, before we start hitting the
85
+	 * filesystem through the AutoLoader, and opening random files. Also, so that we validate the action requested
86
+	 * before we start calling random methods through the web UI.
87
+	 *
88
+	 * Examples:
89
+	 * /internal.php                => returns instance of PageMain, routed to main()
90
+	 * /internal.php?query          => returns instance of PageMain, routed to main()
91
+	 * /internal.php/foo            => returns instance of PageFoo, routed to main()
92
+	 * /internal.php/foo?query      => returns instance of PageFoo, routed to main()
93
+	 * /internal.php/foo/bar        => returns instance of PageFoo, routed to bar()
94
+	 * /internal.php/foo/bar?query  => returns instance of PageFoo, routed to bar()
95
+	 * /internal.php/foo/baz        => returns instance of Page404, routed to main()
96
+	 * /internal.php/foo/baz?query  => returns instance of Page404, routed to main()
97
+	 * /internal.php/bar            => returns instance of Page404, routed to main()
98
+	 * /internal.php/bar?query      => returns instance of Page404, routed to main()
99
+	 * /internal.php/bar/baz        => returns instance of Page404, routed to main()
100
+	 * /internal.php/bar/baz?query  => returns instance of Page404, routed to main()
101
+	 *
102
+	 * Take care when changing this - a lot of places rely on the array key for redirects and other links. If you need
103
+	 * to change the key, then you'll likely have to update a lot of files.
104
+	 *
105
+	 * @var array
106
+	 */
107
+	private $routeMap = array(
108
+
109
+		//////////////////////////////////////////////////////////////////////////////////////////////////
110
+		// Login and registration
111
+		'logout'                      =>
112
+			array(
113
+				'class'   => PageLogout::class,
114
+				'actions' => array(),
115
+			),
116
+		'login'                       =>
117
+			array(
118
+				'class'   => PageLogin::class,
119
+				'actions' => array(),
120
+			),
121
+		'forgotPassword'              =>
122
+			array(
123
+				'class'   => PageForgotPassword::class,
124
+				'actions' => array('reset'),
125
+			),
126
+		'register'                    =>
127
+			array(
128
+				'class'   => PageRegisterOption::class,
129
+				'actions' => array(),
130
+			),
131
+		'register/standard'           =>
132
+			array(
133
+				'class'   => PageRegisterStandard::class,
134
+				'actions' => array('done'),
135
+			),
136
+
137
+		//////////////////////////////////////////////////////////////////////////////////////////////////
138
+		// Discovery
139
+		'search'                      =>
140
+			array(
141
+				'class'   => PageSearch::class,
142
+				'actions' => array(),
143
+			),
144
+		'logs'                        =>
145
+			array(
146
+				'class'   => PageLog::class,
147
+				'actions' => array(),
148
+			),
149
+
150
+		//////////////////////////////////////////////////////////////////////////////////////////////////
151
+		// Administration
152
+		'bans'                        =>
153
+			array(
154
+				'class'   => PageBan::class,
155
+				'actions' => array('set', 'remove'),
156
+			),
157
+		'userManagement'              =>
158
+			array(
159
+				'class'   => PageUserManagement::class,
160
+				'actions' => array(
161
+					'approve',
162
+					'decline',
163
+					'rename',
164
+					'editUser',
165
+					'suspend',
166
+					'editRoles',
167
+				),
168
+			),
169
+		'siteNotice'                  =>
170
+			array(
171
+				'class'   => PageSiteNotice::class,
172
+				'actions' => array(),
173
+			),
174
+		'emailManagement'             =>
175
+			array(
176
+				'class'   => PageEmailManagement::class,
177
+				'actions' => array('create', 'edit', 'view'),
178
+			),
179
+		'jobQueue'                    =>
180
+			array(
181
+				'class'   => PageJobQueue::class,
182
+				'actions' => array('acknowledge', 'requeue', 'view', 'all'),
183
+			),
184
+
185
+		//////////////////////////////////////////////////////////////////////////////////////////////////
186
+		// Personal preferences
187
+		'preferences'                 =>
188
+			array(
189
+				'class'   => PagePreferences::class,
190
+				'actions' => array(),
191
+			),
192
+		'changePassword'              =>
193
+			array(
194
+				'class'   => PageChangePassword::class,
195
+				'actions' => array(),
196
+			),
197
+		'oauth'                       =>
198
+			array(
199
+				'class'   => PageOAuth::class,
200
+				'actions' => array('detach', 'attach'),
201
+			),
202
+		'oauth/callback'              =>
203
+			array(
204
+				'class' => PageOAuthCallback::class,
205
+				'actions' => array('authorise', 'create'),
206
+			),
207
+
208
+		//////////////////////////////////////////////////////////////////////////////////////////////////
209
+		// Welcomer configuration
210
+		'welcomeTemplates'            =>
211
+			array(
212
+				'class'   => PageWelcomeTemplateManagement::class,
213
+				'actions' => array('select', 'edit', 'delete', 'add', 'view'),
214
+			),
215
+
216
+		//////////////////////////////////////////////////////////////////////////////////////////////////
217
+		// Statistics
218
+		'statistics'                  =>
219
+			array(
220
+				'class'   => StatsMain::class,
221
+				'actions' => array(),
222
+			),
223
+		'statistics/fastCloses'       =>
224
+			array(
225
+				'class'   => StatsFastCloses::class,
226
+				'actions' => array(),
227
+			),
228
+		'statistics/inactiveUsers'    =>
229
+			array(
230
+				'class'   => StatsInactiveUsers::class,
231
+				'actions' => array(),
232
+			),
233
+		'statistics/monthlyStats'     =>
234
+			array(
235
+				'class'   => StatsMonthlyStats::class,
236
+				'actions' => array(),
237
+			),
238
+		'statistics/reservedRequests' =>
239
+			array(
240
+				'class'   => StatsReservedRequests::class,
241
+				'actions' => array(),
242
+			),
243
+		'statistics/templateStats'    =>
244
+			array(
245
+				'class'   => StatsTemplateStats::class,
246
+				'actions' => array(),
247
+			),
248
+		'statistics/topCreators'      =>
249
+			array(
250
+				'class'   => StatsTopCreators::class,
251
+				'actions' => array(),
252
+			),
253
+		'statistics/users'            =>
254
+			array(
255
+				'class'   => StatsUsers::class,
256
+				'actions' => array('detail'),
257
+			),
258
+
259
+		//////////////////////////////////////////////////////////////////////////////////////////////////
260
+		// Zoom page
261
+		'viewRequest'                 =>
262
+			array(
263
+				'class'   => PageViewRequest::class,
264
+				'actions' => array(),
265
+			),
266
+		'viewRequest/reserve'         =>
267
+			array(
268
+				'class'   => PageReservation::class,
269
+				'actions' => array(),
270
+			),
271
+		'viewRequest/breakReserve'    =>
272
+			array(
273
+				'class'   => PageBreakReservation::class,
274
+				'actions' => array(),
275
+			),
276
+		'viewRequest/defer'           =>
277
+			array(
278
+				'class'   => PageDeferRequest::class,
279
+				'actions' => array(),
280
+			),
281
+		'viewRequest/comment'         =>
282
+			array(
283
+				'class'   => PageComment::class,
284
+				'actions' => array(),
285
+			),
286
+		'viewRequest/sendToUser'      =>
287
+			array(
288
+				'class'   => PageSendToUser::class,
289
+				'actions' => array(),
290
+			),
291
+		'viewRequest/close'           =>
292
+			array(
293
+				'class'   => PageCloseRequest::class,
294
+				'actions' => array(),
295
+			),
296
+		'viewRequest/create'           =>
297
+			array(
298
+				'class'   => PageCreateRequest::class,
299
+				'actions' => array(),
300
+			),
301
+		'viewRequest/drop'            =>
302
+			array(
303
+				'class'   => PageDropRequest::class,
304
+				'actions' => array(),
305
+			),
306
+		'viewRequest/custom'          =>
307
+			array(
308
+				'class'   => PageCustomClose::class,
309
+				'actions' => array(),
310
+			),
311
+		'editComment'                 =>
312
+			array(
313
+				'class'   => PageEditComment::class,
314
+				'actions' => array(),
315
+			),
316
+
317
+		//////////////////////////////////////////////////////////////////////////////////////////////////
318
+		// Misc stuff
319
+		'team'                        =>
320
+			array(
321
+				'class'   => PageTeam::class,
322
+				'actions' => array(),
323
+			),
324
+		'requestList'                 =>
325
+			array(
326
+				'class'   => PageExpandedRequestList::class,
327
+				'actions' => array(),
328
+			),
329
+	);
330
+
331
+	/**
332
+	 * @return IRoutedTask
333
+	 * @throws Exception
334
+	 */
335
+	final public function route()
336
+	{
337
+		$pathInfo = WebRequest::pathInfo();
338
+
339
+		list($pageClass, $action) = $this->getRouteFromPath($pathInfo);
340
+
341
+		/** @var IRoutedTask $page */
342
+		$page = new $pageClass();
343
+
344
+		// Dynamic creation, so we've got to be careful here. We can't use built-in language type protection, so
345
+		// let's use our own.
346
+		if (!($page instanceof IRoutedTask)) {
347
+			throw new Exception('Expected a page, but this is not a page.');
348
+		}
349
+
350
+		// OK, I'm happy at this point that we know we're running a page, and we know it's probably what we want if it
351
+		// inherits PageBase and has been created from the routing map.
352
+		$page->setRoute($action);
353
+
354
+		return $page;
355
+	}
356
+
357
+	/**
358
+	 * @param $pathInfo
359
+	 *
360
+	 * @return array
361
+	 */
362
+	protected function getRouteFromPath($pathInfo)
363
+	{
364
+		if (count($pathInfo) === 0) {
365
+			// No pathInfo, so no page to load. Load the main page.
366
+			return $this->getDefaultRoute();
367
+		}
368
+		elseif (count($pathInfo) === 1) {
369
+			// Exactly one path info segment, it's got to be a page.
370
+			$classSegment = $pathInfo[0];
371
+
372
+			return $this->routeSinglePathSegment($classSegment);
373
+		}
374
+
375
+		// OK, we have two or more segments now.
376
+		if (count($pathInfo) > 2) {
377
+			// Let's handle more than two, and collapse it down into two.
378
+			$requestedAction = array_pop($pathInfo);
379
+			$classSegment = implode('/', $pathInfo);
380
+		}
381
+		else {
382
+			// Two path info segments.
383
+			$classSegment = $pathInfo[0];
384
+			$requestedAction = $pathInfo[1];
385
+		}
386
+
387
+		$routeMap = $this->routePathSegments($classSegment, $requestedAction);
388
+
389
+		if ($routeMap[0] === Page404::class) {
390
+			$routeMap = $this->routeSinglePathSegment($classSegment . '/' . $requestedAction);
391
+		}
392
+
393
+		return $routeMap;
394
+	}
395
+
396
+	/**
397
+	 * @param $classSegment
398
+	 *
399
+	 * @return array
400
+	 */
401
+	final protected function routeSinglePathSegment($classSegment)
402
+	{
403
+		$routeMap = $this->getRouteMap();
404
+		if (array_key_exists($classSegment, $routeMap)) {
405
+			// Route exists, but we don't have an action in path info, so default to main.
406
+			$pageClass = $routeMap[$classSegment]['class'];
407
+			$action = 'main';
408
+
409
+			return array($pageClass, $action);
410
+		}
411
+		else {
412
+			// Doesn't exist in map. Fall back to 404
413
+			$pageClass = Page404::class;
414
+			$action = "main";
415
+
416
+			return array($pageClass, $action);
417
+		}
418
+	}
419
+
420
+	/**
421
+	 * @param $classSegment
422
+	 * @param $requestedAction
423
+	 *
424
+	 * @return array
425
+	 */
426
+	final protected function routePathSegments($classSegment, $requestedAction)
427
+	{
428
+		$routeMap = $this->getRouteMap();
429
+		if (array_key_exists($classSegment, $routeMap)) {
430
+			// Route exists, but we don't have an action in path info, so default to main.
431
+
432
+			if (isset($routeMap[$classSegment]['actions'])
433
+				&& array_search($requestedAction, $routeMap[$classSegment]['actions']) !== false
434
+			) {
435
+				// Action exists in allowed action list. Allow both the page and the action
436
+				$pageClass = $routeMap[$classSegment]['class'];
437
+				$action = $requestedAction;
438
+
439
+				return array($pageClass, $action);
440
+			}
441
+			else {
442
+				// Valid page, invalid action. 404 our way out.
443
+				$pageClass = Page404::class;
444
+				$action = 'main';
445
+
446
+				return array($pageClass, $action);
447
+			}
448
+		}
449
+		else {
450
+			// Class doesn't exist in map. Fall back to 404
451
+			$pageClass = Page404::class;
452
+			$action = 'main';
453
+
454
+			return array($pageClass, $action);
455
+		}
456
+	}
457
+
458
+	/**
459
+	 * @return array
460
+	 */
461
+	protected function getRouteMap()
462
+	{
463
+		return $this->routeMap;
464
+	}
465
+
466
+	/**
467
+	 * @return callable
468
+	 */
469
+	protected function getDefaultRoute()
470
+	{
471
+		return array(PageMain::class, "main");
472
+	}
473 473
 }
Please login to merge, or discard this patch.
includes/WebRequest.php 1 patch
Indentation   +517 added lines, -517 removed lines patch added patch discarded remove patch
@@ -22,521 +22,521 @@
 block discarded – undo
22 22
  */
23 23
 class WebRequest
24 24
 {
25
-    /**
26
-     * @var \Waca\Providers\GlobalState\IGlobalStateProvider Provides access to the global state.
27
-     */
28
-    private static $globalStateProvider;
29
-
30
-    /**
31
-     * Returns a boolean value if the request was submitted with the HTTP POST method.
32
-     * @return bool
33
-     */
34
-    public static function wasPosted()
35
-    {
36
-        return self::method() === 'POST';
37
-    }
38
-
39
-    /**
40
-     * Gets the HTTP Method used
41
-     * @return string|null
42
-     */
43
-    public static function method()
44
-    {
45
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
46
-
47
-        if (isset($server['REQUEST_METHOD'])) {
48
-            return $server['REQUEST_METHOD'];
49
-        }
50
-
51
-        return null;
52
-    }
53
-
54
-    /**
55
-     * Gets a boolean value stating whether the request was served over HTTPS or not.
56
-     * @return bool
57
-     */
58
-    public static function isHttps()
59
-    {
60
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
61
-
62
-        if (isset($server['HTTP_X_FORWARDED_PROTO'])) {
63
-            if ($server['HTTP_X_FORWARDED_PROTO'] === 'https') {
64
-                // Client <=> Proxy is encrypted
65
-                return true;
66
-            }
67
-            else {
68
-                // Proxy <=> Server link unknown, Client <=> Proxy is not encrypted.
69
-                return false;
70
-            }
71
-        }
72
-
73
-        if (isset($server['HTTPS'])) {
74
-            if ($server['HTTPS'] === 'off') {
75
-                // ISAPI on IIS breaks the spec. :(
76
-                return false;
77
-            }
78
-
79
-            if ($server['HTTPS'] !== '') {
80
-                // Set to a non-empty value
81
-                return true;
82
-            }
83
-        }
84
-
85
-        return false;
86
-    }
87
-
88
-    /**
89
-     * Gets the path info
90
-     *
91
-     * @return array Array of path info segments
92
-     */
93
-    public static function pathInfo()
94
-    {
95
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
96
-        if (!isset($server['PATH_INFO'])) {
97
-            return array();
98
-        }
99
-
100
-        $exploded = explode('/', $server['PATH_INFO']);
101
-
102
-        // filter out empty values, and reindex from zero. Notably, the first element is always zero, since it starts
103
-        // with a /
104
-        return array_values(array_filter($exploded));
105
-    }
106
-
107
-    /**
108
-     * Gets the remote address of the web request
109
-     * @return null|string
110
-     */
111
-    public static function remoteAddress()
112
-    {
113
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
114
-
115
-        if (isset($server['REMOTE_ADDR'])) {
116
-            return $server['REMOTE_ADDR'];
117
-        }
118
-
119
-        return null;
120
-    }
121
-
122
-    /**
123
-     * Gets the XFF header contents for the web request
124
-     * @return null|string
125
-     */
126
-    public static function forwardedAddress()
127
-    {
128
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
129
-
130
-        if (isset($server['HTTP_X_FORWARDED_FOR'])) {
131
-            return $server['HTTP_X_FORWARDED_FOR'];
132
-        }
133
-
134
-        return null;
135
-    }
136
-
137
-    /**
138
-     * Sets the global state provider.
139
-     *
140
-     * Almost guaranteed this is not the method you want in production code.
141
-     *
142
-     * @param \Waca\Providers\GlobalState\IGlobalStateProvider $globalState
143
-     */
144
-    public static function setGlobalStateProvider($globalState)
145
-    {
146
-        self::$globalStateProvider = $globalState;
147
-    }
148
-
149
-    #region POST variables
150
-
151
-    /**
152
-     * @param string $key
153
-     *
154
-     * @return null|string
155
-     */
156
-    public static function postString($key)
157
-    {
158
-        $post = &self::$globalStateProvider->getPostSuperGlobal();
159
-        if (!array_key_exists($key, $post)) {
160
-            return null;
161
-        }
162
-
163
-        if ($post[$key] === "") {
164
-            return null;
165
-        }
166
-
167
-        return (string)$post[$key];
168
-    }
169
-
170
-    /**
171
-     * @param string $key
172
-     *
173
-     * @return null|string
174
-     */
175
-    public static function postEmail($key)
176
-    {
177
-        $post = &self::$globalStateProvider->getPostSuperGlobal();
178
-        if (!array_key_exists($key, $post)) {
179
-            return null;
180
-        }
181
-
182
-        $filteredValue = filter_var($post[$key], FILTER_SANITIZE_EMAIL);
183
-
184
-        if ($filteredValue === false) {
185
-            return null;
186
-        }
187
-
188
-        return (string)$filteredValue;
189
-    }
190
-
191
-    /**
192
-     * @param string $key
193
-     *
194
-     * @return int|null
195
-     */
196
-    public static function postInt($key)
197
-    {
198
-        $post = &self::$globalStateProvider->getPostSuperGlobal();
199
-        if (!array_key_exists($key, $post)) {
200
-            return null;
201
-        }
202
-
203
-        $filteredValue = filter_var($post[$key], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
204
-
205
-        if ($filteredValue === null) {
206
-            return null;
207
-        }
208
-
209
-        return (int)$filteredValue;
210
-    }
211
-
212
-    /**
213
-     * @param string $key
214
-     *
215
-     * @return bool
216
-     */
217
-    public static function postBoolean($key)
218
-    {
219
-        $get = &self::$globalStateProvider->getPostSuperGlobal();
220
-        if (!array_key_exists($key, $get)) {
221
-            return false;
222
-        }
223
-
224
-        // presence of parameter only
225
-        if ($get[$key] === "") {
226
-            return true;
227
-        }
228
-
229
-        if (in_array($get[$key], array(false, 'no', 'off', 0, 'false'), true)) {
230
-            return false;
231
-        }
232
-
233
-        return true;
234
-    }
235
-
236
-    #endregion
237
-
238
-    #region GET variables
239
-
240
-    /**
241
-     * @param string $key
242
-     *
243
-     * @return bool
244
-     */
245
-    public static function getBoolean($key)
246
-    {
247
-        $get = &self::$globalStateProvider->getGetSuperGlobal();
248
-        if (!array_key_exists($key, $get)) {
249
-            return false;
250
-        }
251
-
252
-        // presence of parameter only
253
-        if ($get[$key] === "") {
254
-            return true;
255
-        }
256
-
257
-        if (in_array($get[$key], array(false, 'no', 'off', 0, 'false'), true)) {
258
-            return false;
259
-        }
260
-
261
-        return true;
262
-    }
263
-
264
-    /**
265
-     * @param string $key
266
-     *
267
-     * @return int|null
268
-     */
269
-    public static function getInt($key)
270
-    {
271
-        $get = &self::$globalStateProvider->getGetSuperGlobal();
272
-        if (!array_key_exists($key, $get)) {
273
-            return null;
274
-        }
275
-
276
-        $filteredValue = filter_var($get[$key], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
277
-
278
-        if ($filteredValue === null) {
279
-            return null;
280
-        }
281
-
282
-        return (int)$filteredValue;
283
-    }
284
-
285
-    /**
286
-     * @param string $key
287
-     *
288
-     * @return null|string
289
-     */
290
-    public static function getString($key)
291
-    {
292
-        $get = &self::$globalStateProvider->getGetSuperGlobal();
293
-        if (!array_key_exists($key, $get)) {
294
-            return null;
295
-        }
296
-
297
-        if ($get[$key] === "") {
298
-            return null;
299
-        }
300
-
301
-        return (string)$get[$key];
302
-    }
303
-
304
-    #endregion
305
-
306
-    /**
307
-     * Sets the logged-in user to the specified user.
308
-     *
309
-     * @param User $user
310
-     */
311
-    public static function setLoggedInUser(User $user)
312
-    {
313
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
314
-
315
-        $session['userID'] = $user->getId();
316
-        unset($session['partialLogin']);
317
-    }
318
-
319
-    /**
320
-     * Sets the post-login redirect
321
-     */
322
-    public static function setPostLoginRedirect()
323
-    {
324
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
325
-        $session['returnTo'] = self::requestUri();
326
-    }
327
-
328
-    /**
329
-     * @return string|null
330
-     */
331
-    public static function requestUri()
332
-    {
333
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
334
-
335
-        if (isset($server['REQUEST_URI'])) {
336
-            return $server['REQUEST_URI'];
337
-        }
338
-
339
-        return null;
340
-    }
341
-
342
-    /**
343
-     * Clears the post-login redirect
344
-     * @return string
345
-     */
346
-    public static function clearPostLoginRedirect()
347
-    {
348
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
349
-        if (array_key_exists('returnTo', $session)) {
350
-            $path = $session['returnTo'];
351
-            unset($session['returnTo']);
352
-
353
-            return $path;
354
-        }
355
-
356
-        return null;
357
-    }
358
-
359
-    /**
360
-     * @return string|null
361
-     */
362
-    public static function serverName()
363
-    {
364
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
365
-
366
-        if (isset($server['SERVER_NAME'])) {
367
-            return $server['SERVER_NAME'];
368
-        }
369
-
370
-        return null;
371
-    }
372
-
373
-    /**
374
-     * You probably only want to deal with this through SessionAlert.
375
-     * @return void
376
-     */
377
-    public static function clearSessionAlertData()
378
-    {
379
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
380
-        if (array_key_exists('alerts', $session)) {
381
-            unset($session['alerts']);
382
-        }
383
-    }
384
-
385
-    /**
386
-     * You probably only want to deal with this through SessionAlert.
387
-     *
388
-     * @return string[]
389
-     */
390
-    public static function getSessionAlertData()
391
-    {
392
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
393
-        if (array_key_exists('alerts', $session)) {
394
-            return $session['alerts'];
395
-        }
396
-
397
-        return array();
398
-    }
399
-
400
-    /**
401
-     * You probably only want to deal with this through SessionAlert.
402
-     *
403
-     * @param string[] $data
404
-     */
405
-    public static function setSessionAlertData($data)
406
-    {
407
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
408
-        $session['alerts'] = $data;
409
-    }
410
-
411
-    /**
412
-     * You probably only want to deal with this through TokenManager.
413
-     *
414
-     * @return string[]
415
-     */
416
-    public static function getSessionTokenData()
417
-    {
418
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
419
-        if (array_key_exists('tokens', $session)) {
420
-            return $session['tokens'];
421
-        }
422
-
423
-        return array();
424
-    }
425
-
426
-    /**
427
-     * You probably only want to deal with this through TokenManager.
428
-     *
429
-     * @param string[] $data
430
-     */
431
-    public static function setSessionTokenData($data)
432
-    {
433
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
434
-        $session['tokens'] = $data;
435
-    }
436
-
437
-    /**
438
-     * @param string $key
439
-     *
440
-     * @return mixed
441
-     */
442
-    public static function getSessionContext($key)
443
-    {
444
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
445
-
446
-        if (!isset($session['context'])) {
447
-            $session['context'] = array();
448
-        }
449
-
450
-        if (!isset($session['context'][$key])) {
451
-            return null;
452
-        }
453
-
454
-        return $session['context'][$key];
455
-    }
456
-
457
-    /**
458
-     * @param string $key
459
-     * @param mixed  $data
460
-     */
461
-    public static function setSessionContext($key, $data)
462
-    {
463
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
464
-
465
-        if (!isset($session['context'])) {
466
-            $session['context'] = array();
467
-        }
468
-
469
-        $session['context'][$key] = $data;
470
-    }
471
-
472
-    /**
473
-     * @return int|null
474
-     */
475
-    public static function getSessionUserId()
476
-    {
477
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
478
-
479
-        return isset($session['userID']) ? (int)$session['userID'] : null;
480
-    }
481
-
482
-    /**
483
-     * @param User $user
484
-     */
485
-    public static function setPartialLogin(User $user)
486
-    {
487
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
488
-        $session['partialLogin'] = $user->getId();
489
-    }
490
-
491
-    /**
492
-     * @return int|null
493
-     */
494
-    public static function getPartialLogin()
495
-    {
496
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
497
-
498
-        return isset($session['partialLogin']) ? (int)$session['partialLogin'] : null;
499
-    }
500
-
501
-    /**
502
-     * @return null|string
503
-     */
504
-    public static function userAgent()
505
-    {
506
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
507
-
508
-        if (isset($server['HTTP_USER_AGENT'])) {
509
-            return $server['HTTP_USER_AGENT'];
510
-        }
511
-
512
-        return null;
513
-    }
514
-
515
-    /**
516
-     * @return null|string
517
-     */
518
-    public static function scriptName()
519
-    {
520
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
521
-
522
-        if (isset($server['SCRIPT_NAME'])) {
523
-            return $server['SCRIPT_NAME'];
524
-        }
525
-
526
-        return null;
527
-    }
528
-
529
-    /**
530
-     * @return null|string
531
-     */
532
-    public static function origin()
533
-    {
534
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
535
-
536
-        if (isset($server['HTTP_ORIGIN'])) {
537
-            return $server['HTTP_ORIGIN'];
538
-        }
539
-
540
-        return null;
541
-    }
25
+	/**
26
+	 * @var \Waca\Providers\GlobalState\IGlobalStateProvider Provides access to the global state.
27
+	 */
28
+	private static $globalStateProvider;
29
+
30
+	/**
31
+	 * Returns a boolean value if the request was submitted with the HTTP POST method.
32
+	 * @return bool
33
+	 */
34
+	public static function wasPosted()
35
+	{
36
+		return self::method() === 'POST';
37
+	}
38
+
39
+	/**
40
+	 * Gets the HTTP Method used
41
+	 * @return string|null
42
+	 */
43
+	public static function method()
44
+	{
45
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
46
+
47
+		if (isset($server['REQUEST_METHOD'])) {
48
+			return $server['REQUEST_METHOD'];
49
+		}
50
+
51
+		return null;
52
+	}
53
+
54
+	/**
55
+	 * Gets a boolean value stating whether the request was served over HTTPS or not.
56
+	 * @return bool
57
+	 */
58
+	public static function isHttps()
59
+	{
60
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
61
+
62
+		if (isset($server['HTTP_X_FORWARDED_PROTO'])) {
63
+			if ($server['HTTP_X_FORWARDED_PROTO'] === 'https') {
64
+				// Client <=> Proxy is encrypted
65
+				return true;
66
+			}
67
+			else {
68
+				// Proxy <=> Server link unknown, Client <=> Proxy is not encrypted.
69
+				return false;
70
+			}
71
+		}
72
+
73
+		if (isset($server['HTTPS'])) {
74
+			if ($server['HTTPS'] === 'off') {
75
+				// ISAPI on IIS breaks the spec. :(
76
+				return false;
77
+			}
78
+
79
+			if ($server['HTTPS'] !== '') {
80
+				// Set to a non-empty value
81
+				return true;
82
+			}
83
+		}
84
+
85
+		return false;
86
+	}
87
+
88
+	/**
89
+	 * Gets the path info
90
+	 *
91
+	 * @return array Array of path info segments
92
+	 */
93
+	public static function pathInfo()
94
+	{
95
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
96
+		if (!isset($server['PATH_INFO'])) {
97
+			return array();
98
+		}
99
+
100
+		$exploded = explode('/', $server['PATH_INFO']);
101
+
102
+		// filter out empty values, and reindex from zero. Notably, the first element is always zero, since it starts
103
+		// with a /
104
+		return array_values(array_filter($exploded));
105
+	}
106
+
107
+	/**
108
+	 * Gets the remote address of the web request
109
+	 * @return null|string
110
+	 */
111
+	public static function remoteAddress()
112
+	{
113
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
114
+
115
+		if (isset($server['REMOTE_ADDR'])) {
116
+			return $server['REMOTE_ADDR'];
117
+		}
118
+
119
+		return null;
120
+	}
121
+
122
+	/**
123
+	 * Gets the XFF header contents for the web request
124
+	 * @return null|string
125
+	 */
126
+	public static function forwardedAddress()
127
+	{
128
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
129
+
130
+		if (isset($server['HTTP_X_FORWARDED_FOR'])) {
131
+			return $server['HTTP_X_FORWARDED_FOR'];
132
+		}
133
+
134
+		return null;
135
+	}
136
+
137
+	/**
138
+	 * Sets the global state provider.
139
+	 *
140
+	 * Almost guaranteed this is not the method you want in production code.
141
+	 *
142
+	 * @param \Waca\Providers\GlobalState\IGlobalStateProvider $globalState
143
+	 */
144
+	public static function setGlobalStateProvider($globalState)
145
+	{
146
+		self::$globalStateProvider = $globalState;
147
+	}
148
+
149
+	#region POST variables
150
+
151
+	/**
152
+	 * @param string $key
153
+	 *
154
+	 * @return null|string
155
+	 */
156
+	public static function postString($key)
157
+	{
158
+		$post = &self::$globalStateProvider->getPostSuperGlobal();
159
+		if (!array_key_exists($key, $post)) {
160
+			return null;
161
+		}
162
+
163
+		if ($post[$key] === "") {
164
+			return null;
165
+		}
166
+
167
+		return (string)$post[$key];
168
+	}
169
+
170
+	/**
171
+	 * @param string $key
172
+	 *
173
+	 * @return null|string
174
+	 */
175
+	public static function postEmail($key)
176
+	{
177
+		$post = &self::$globalStateProvider->getPostSuperGlobal();
178
+		if (!array_key_exists($key, $post)) {
179
+			return null;
180
+		}
181
+
182
+		$filteredValue = filter_var($post[$key], FILTER_SANITIZE_EMAIL);
183
+
184
+		if ($filteredValue === false) {
185
+			return null;
186
+		}
187
+
188
+		return (string)$filteredValue;
189
+	}
190
+
191
+	/**
192
+	 * @param string $key
193
+	 *
194
+	 * @return int|null
195
+	 */
196
+	public static function postInt($key)
197
+	{
198
+		$post = &self::$globalStateProvider->getPostSuperGlobal();
199
+		if (!array_key_exists($key, $post)) {
200
+			return null;
201
+		}
202
+
203
+		$filteredValue = filter_var($post[$key], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
204
+
205
+		if ($filteredValue === null) {
206
+			return null;
207
+		}
208
+
209
+		return (int)$filteredValue;
210
+	}
211
+
212
+	/**
213
+	 * @param string $key
214
+	 *
215
+	 * @return bool
216
+	 */
217
+	public static function postBoolean($key)
218
+	{
219
+		$get = &self::$globalStateProvider->getPostSuperGlobal();
220
+		if (!array_key_exists($key, $get)) {
221
+			return false;
222
+		}
223
+
224
+		// presence of parameter only
225
+		if ($get[$key] === "") {
226
+			return true;
227
+		}
228
+
229
+		if (in_array($get[$key], array(false, 'no', 'off', 0, 'false'), true)) {
230
+			return false;
231
+		}
232
+
233
+		return true;
234
+	}
235
+
236
+	#endregion
237
+
238
+	#region GET variables
239
+
240
+	/**
241
+	 * @param string $key
242
+	 *
243
+	 * @return bool
244
+	 */
245
+	public static function getBoolean($key)
246
+	{
247
+		$get = &self::$globalStateProvider->getGetSuperGlobal();
248
+		if (!array_key_exists($key, $get)) {
249
+			return false;
250
+		}
251
+
252
+		// presence of parameter only
253
+		if ($get[$key] === "") {
254
+			return true;
255
+		}
256
+
257
+		if (in_array($get[$key], array(false, 'no', 'off', 0, 'false'), true)) {
258
+			return false;
259
+		}
260
+
261
+		return true;
262
+	}
263
+
264
+	/**
265
+	 * @param string $key
266
+	 *
267
+	 * @return int|null
268
+	 */
269
+	public static function getInt($key)
270
+	{
271
+		$get = &self::$globalStateProvider->getGetSuperGlobal();
272
+		if (!array_key_exists($key, $get)) {
273
+			return null;
274
+		}
275
+
276
+		$filteredValue = filter_var($get[$key], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
277
+
278
+		if ($filteredValue === null) {
279
+			return null;
280
+		}
281
+
282
+		return (int)$filteredValue;
283
+	}
284
+
285
+	/**
286
+	 * @param string $key
287
+	 *
288
+	 * @return null|string
289
+	 */
290
+	public static function getString($key)
291
+	{
292
+		$get = &self::$globalStateProvider->getGetSuperGlobal();
293
+		if (!array_key_exists($key, $get)) {
294
+			return null;
295
+		}
296
+
297
+		if ($get[$key] === "") {
298
+			return null;
299
+		}
300
+
301
+		return (string)$get[$key];
302
+	}
303
+
304
+	#endregion
305
+
306
+	/**
307
+	 * Sets the logged-in user to the specified user.
308
+	 *
309
+	 * @param User $user
310
+	 */
311
+	public static function setLoggedInUser(User $user)
312
+	{
313
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
314
+
315
+		$session['userID'] = $user->getId();
316
+		unset($session['partialLogin']);
317
+	}
318
+
319
+	/**
320
+	 * Sets the post-login redirect
321
+	 */
322
+	public static function setPostLoginRedirect()
323
+	{
324
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
325
+		$session['returnTo'] = self::requestUri();
326
+	}
327
+
328
+	/**
329
+	 * @return string|null
330
+	 */
331
+	public static function requestUri()
332
+	{
333
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
334
+
335
+		if (isset($server['REQUEST_URI'])) {
336
+			return $server['REQUEST_URI'];
337
+		}
338
+
339
+		return null;
340
+	}
341
+
342
+	/**
343
+	 * Clears the post-login redirect
344
+	 * @return string
345
+	 */
346
+	public static function clearPostLoginRedirect()
347
+	{
348
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
349
+		if (array_key_exists('returnTo', $session)) {
350
+			$path = $session['returnTo'];
351
+			unset($session['returnTo']);
352
+
353
+			return $path;
354
+		}
355
+
356
+		return null;
357
+	}
358
+
359
+	/**
360
+	 * @return string|null
361
+	 */
362
+	public static function serverName()
363
+	{
364
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
365
+
366
+		if (isset($server['SERVER_NAME'])) {
367
+			return $server['SERVER_NAME'];
368
+		}
369
+
370
+		return null;
371
+	}
372
+
373
+	/**
374
+	 * You probably only want to deal with this through SessionAlert.
375
+	 * @return void
376
+	 */
377
+	public static function clearSessionAlertData()
378
+	{
379
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
380
+		if (array_key_exists('alerts', $session)) {
381
+			unset($session['alerts']);
382
+		}
383
+	}
384
+
385
+	/**
386
+	 * You probably only want to deal with this through SessionAlert.
387
+	 *
388
+	 * @return string[]
389
+	 */
390
+	public static function getSessionAlertData()
391
+	{
392
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
393
+		if (array_key_exists('alerts', $session)) {
394
+			return $session['alerts'];
395
+		}
396
+
397
+		return array();
398
+	}
399
+
400
+	/**
401
+	 * You probably only want to deal with this through SessionAlert.
402
+	 *
403
+	 * @param string[] $data
404
+	 */
405
+	public static function setSessionAlertData($data)
406
+	{
407
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
408
+		$session['alerts'] = $data;
409
+	}
410
+
411
+	/**
412
+	 * You probably only want to deal with this through TokenManager.
413
+	 *
414
+	 * @return string[]
415
+	 */
416
+	public static function getSessionTokenData()
417
+	{
418
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
419
+		if (array_key_exists('tokens', $session)) {
420
+			return $session['tokens'];
421
+		}
422
+
423
+		return array();
424
+	}
425
+
426
+	/**
427
+	 * You probably only want to deal with this through TokenManager.
428
+	 *
429
+	 * @param string[] $data
430
+	 */
431
+	public static function setSessionTokenData($data)
432
+	{
433
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
434
+		$session['tokens'] = $data;
435
+	}
436
+
437
+	/**
438
+	 * @param string $key
439
+	 *
440
+	 * @return mixed
441
+	 */
442
+	public static function getSessionContext($key)
443
+	{
444
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
445
+
446
+		if (!isset($session['context'])) {
447
+			$session['context'] = array();
448
+		}
449
+
450
+		if (!isset($session['context'][$key])) {
451
+			return null;
452
+		}
453
+
454
+		return $session['context'][$key];
455
+	}
456
+
457
+	/**
458
+	 * @param string $key
459
+	 * @param mixed  $data
460
+	 */
461
+	public static function setSessionContext($key, $data)
462
+	{
463
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
464
+
465
+		if (!isset($session['context'])) {
466
+			$session['context'] = array();
467
+		}
468
+
469
+		$session['context'][$key] = $data;
470
+	}
471
+
472
+	/**
473
+	 * @return int|null
474
+	 */
475
+	public static function getSessionUserId()
476
+	{
477
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
478
+
479
+		return isset($session['userID']) ? (int)$session['userID'] : null;
480
+	}
481
+
482
+	/**
483
+	 * @param User $user
484
+	 */
485
+	public static function setPartialLogin(User $user)
486
+	{
487
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
488
+		$session['partialLogin'] = $user->getId();
489
+	}
490
+
491
+	/**
492
+	 * @return int|null
493
+	 */
494
+	public static function getPartialLogin()
495
+	{
496
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
497
+
498
+		return isset($session['partialLogin']) ? (int)$session['partialLogin'] : null;
499
+	}
500
+
501
+	/**
502
+	 * @return null|string
503
+	 */
504
+	public static function userAgent()
505
+	{
506
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
507
+
508
+		if (isset($server['HTTP_USER_AGENT'])) {
509
+			return $server['HTTP_USER_AGENT'];
510
+		}
511
+
512
+		return null;
513
+	}
514
+
515
+	/**
516
+	 * @return null|string
517
+	 */
518
+	public static function scriptName()
519
+	{
520
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
521
+
522
+		if (isset($server['SCRIPT_NAME'])) {
523
+			return $server['SCRIPT_NAME'];
524
+		}
525
+
526
+		return null;
527
+	}
528
+
529
+	/**
530
+	 * @return null|string
531
+	 */
532
+	public static function origin()
533
+	{
534
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
535
+
536
+		if (isset($server['HTTP_ORIGIN'])) {
537
+			return $server['HTTP_ORIGIN'];
538
+		}
539
+
540
+		return null;
541
+	}
542 542
 }
543 543
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Tasks/IRoutedTask.php 1 patch
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -12,21 +12,21 @@
 block discarded – undo
12 12
 
13 13
 interface IRoutedTask extends ITask
14 14
 {
15
-    /**
16
-     * Sets the route the request will take. Only should be called from the request router.
17
-     *
18
-     * @param $routeName string
19
-     *
20
-     * @return void
21
-     *
22
-     * @throws Exception
23
-     * @category Security-Critical
24
-     */
25
-    public function setRoute($routeName);
15
+	/**
16
+	 * Sets the route the request will take. Only should be called from the request router.
17
+	 *
18
+	 * @param $routeName string
19
+	 *
20
+	 * @return void
21
+	 *
22
+	 * @throws Exception
23
+	 * @category Security-Critical
24
+	 */
25
+	public function setRoute($routeName);
26 26
 
27
-    /**
28
-     * Gets the name of the route that has been passed from the request router.
29
-     * @return string
30
-     */
31
-    public function getRouteName();
27
+	/**
28
+	 * Gets the name of the route that has been passed from the request router.
29
+	 * @return string
30
+	 */
31
+	public function getRouteName();
32 32
 }
33 33
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Tasks/ApiPageBase.php 2 patches
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -16,97 +16,97 @@
 block discarded – undo
16 16
 
17 17
 abstract class ApiPageBase extends TaskBase implements IRoutedTask, IApiAction
18 18
 {
19
-    /**
20
-     * API result document
21
-     * @var DOMDocument
22
-     */
23
-    protected $document;
24
-
25
-    public function __construct()
26
-    {
27
-        $this->document = new DOMDocument('1.0');
28
-    }
29
-
30
-    final public function execute()
31
-    {
32
-        $this->main();
33
-    }
34
-
35
-    /**
36
-     * @param string $routeName
37
-     */
38
-    public function setRoute($routeName)
39
-    {
40
-        // no-op
41
-    }
42
-
43
-    /**
44
-     * @return string
45
-     */
46
-    public function getRouteName()
47
-    {
48
-        return 'main';
49
-    }
50
-
51
-    /**
52
-     * Main function for this page, when no specific actions are called.
53
-     *
54
-     * @throws ApiException
55
-     * @return void
56
-     */
57
-    final protected function main()
58
-    {
59
-        if (headers_sent()) {
60
-            throw new ApiException('Headers have already been sent - this indicates a bug in the application!');
61
-        }
62
-
63
-        header("Content-Type: text/xml");
64
-
65
-        // javascript access control
66
-        $httpOrigin = WebRequest::origin();
67
-
68
-        if ($httpOrigin !== null) {
69
-            $CORSallowed = $this->getSiteConfiguration()->getCrossOriginResourceSharingHosts();
70
-
71
-            if (in_array($httpOrigin, $CORSallowed)) {
72
-                header("Access-Control-Allow-Origin: " . $httpOrigin);
73
-            }
74
-        }
75
-
76
-        $responseData = $this->runApiPage();
77
-
78
-        ob_end_clean();
79
-        print($responseData);
80
-        ob_start();
81
-    }
82
-
83
-    /**
84
-     * Method that runs API action
85
-     *
86
-     * @param DOMElement $apiDocument
87
-     *
88
-     * @return DOMElement
89
-     */
90
-    abstract public function executeApiAction(DOMElement $apiDocument);
91
-
92
-    /**
93
-     * @return string
94
-     */
95
-    final public function runApiPage()
96
-    {
97
-        $apiDocument = $this->document->createElement("api");
98
-
99
-        try {
100
-            $apiDocument = $this->executeApiAction($apiDocument);
101
-        }
102
-        catch (ApiException $ex) {
103
-            $exception = $this->document->createElement("error");
104
-            $exception->setAttribute("message", $ex->getMessage());
105
-            $apiDocument->appendChild($exception);
106
-        }
107
-
108
-        $this->document->appendChild($apiDocument);
109
-
110
-        return $this->document->saveXML();
111
-    }
19
+	/**
20
+	 * API result document
21
+	 * @var DOMDocument
22
+	 */
23
+	protected $document;
24
+
25
+	public function __construct()
26
+	{
27
+		$this->document = new DOMDocument('1.0');
28
+	}
29
+
30
+	final public function execute()
31
+	{
32
+		$this->main();
33
+	}
34
+
35
+	/**
36
+	 * @param string $routeName
37
+	 */
38
+	public function setRoute($routeName)
39
+	{
40
+		// no-op
41
+	}
42
+
43
+	/**
44
+	 * @return string
45
+	 */
46
+	public function getRouteName()
47
+	{
48
+		return 'main';
49
+	}
50
+
51
+	/**
52
+	 * Main function for this page, when no specific actions are called.
53
+	 *
54
+	 * @throws ApiException
55
+	 * @return void
56
+	 */
57
+	final protected function main()
58
+	{
59
+		if (headers_sent()) {
60
+			throw new ApiException('Headers have already been sent - this indicates a bug in the application!');
61
+		}
62
+
63
+		header("Content-Type: text/xml");
64
+
65
+		// javascript access control
66
+		$httpOrigin = WebRequest::origin();
67
+
68
+		if ($httpOrigin !== null) {
69
+			$CORSallowed = $this->getSiteConfiguration()->getCrossOriginResourceSharingHosts();
70
+
71
+			if (in_array($httpOrigin, $CORSallowed)) {
72
+				header("Access-Control-Allow-Origin: " . $httpOrigin);
73
+			}
74
+		}
75
+
76
+		$responseData = $this->runApiPage();
77
+
78
+		ob_end_clean();
79
+		print($responseData);
80
+		ob_start();
81
+	}
82
+
83
+	/**
84
+	 * Method that runs API action
85
+	 *
86
+	 * @param DOMElement $apiDocument
87
+	 *
88
+	 * @return DOMElement
89
+	 */
90
+	abstract public function executeApiAction(DOMElement $apiDocument);
91
+
92
+	/**
93
+	 * @return string
94
+	 */
95
+	final public function runApiPage()
96
+	{
97
+		$apiDocument = $this->document->createElement("api");
98
+
99
+		try {
100
+			$apiDocument = $this->executeApiAction($apiDocument);
101
+		}
102
+		catch (ApiException $ex) {
103
+			$exception = $this->document->createElement("error");
104
+			$exception->setAttribute("message", $ex->getMessage());
105
+			$apiDocument->appendChild($exception);
106
+		}
107
+
108
+		$this->document->appendChild($apiDocument);
109
+
110
+		return $this->document->saveXML();
111
+	}
112 112
 }
113 113
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -69,7 +69,7 @@
 block discarded – undo
69 69
             $CORSallowed = $this->getSiteConfiguration()->getCrossOriginResourceSharingHosts();
70 70
 
71 71
             if (in_array($httpOrigin, $CORSallowed)) {
72
-                header("Access-Control-Allow-Origin: " . $httpOrigin);
72
+                header("Access-Control-Allow-Origin: ".$httpOrigin);
73 73
             }
74 74
         }
75 75
 
Please login to merge, or discard this patch.
includes/Tasks/PublicInterfacePageBase.php 1 patch
Indentation   +15 added lines, -15 removed lines patch added patch discarded remove patch
@@ -10,21 +10,21 @@
 block discarded – undo
10 10
 
11 11
 abstract class PublicInterfacePageBase extends PageBase
12 12
 {
13
-    /**
14
-     * PublicInterfaceInternalPageBase constructor.
15
-     */
16
-    public function __construct()
17
-    {
18
-        $this->template = 'publicbase.tpl';
19
-    }
13
+	/**
14
+	 * PublicInterfaceInternalPageBase constructor.
15
+	 */
16
+	public function __construct()
17
+	{
18
+		$this->template = 'publicbase.tpl';
19
+	}
20 20
 
21
-    final public function execute()
22
-    {
23
-        parent::execute();
24
-    }
21
+	final public function execute()
22
+	{
23
+		parent::execute();
24
+	}
25 25
 
26
-    final public function finalisePage()
27
-    {
28
-        parent::finalisePage();
29
-    }
26
+	final public function finalisePage()
27
+	{
28
+		parent::finalisePage();
29
+	}
30 30
 }
31 31
\ No newline at end of file
Please login to merge, or discard this patch.
includes/DataObject.php 1 patch
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -23,124 +23,124 @@
 block discarded – undo
23 23
  */
24 24
 abstract class DataObject
25 25
 {
26
-    /** @var int ID of the object */
27
-    protected $id = null;
28
-    /** @var int update version for optimistic locking */
29
-    protected $updateversion = 0;
30
-    /**
31
-     * @var PdoDatabase
32
-     */
33
-    protected $dbObject;
34
-
35
-    /**
36
-     * Retrieves a data object by it's row ID.
37
-     *
38
-     * @param int         $id
39
-     * @param PdoDatabase $database
40
-     *
41
-     * @return DataObject|false
42
-     */
43
-    public static function getById($id, PdoDatabase $database)
44
-    {
45
-        $array = explode('\\', get_called_class());
46
-        $realClassName = strtolower(end($array));
47
-
48
-        $statement = $database->prepare("SELECT * FROM {$realClassName} WHERE id = :id LIMIT 1;");
49
-        $statement->bindValue(":id", $id);
50
-
51
-        $statement->execute();
52
-
53
-        $resultObject = $statement->fetchObject(get_called_class());
54
-
55
-        if ($resultObject != false) {
56
-            $resultObject->setDatabase($database);
57
-        }
58
-
59
-        return $resultObject;
60
-    }
61
-
62
-    public function setDatabase(PdoDatabase $db)
63
-    {
64
-        $this->dbObject = $db;
65
-    }
66
-
67
-    /**
68
-     * Gets the database associated with this data object.
69
-     * @return PdoDatabase
70
-     */
71
-    public function getDatabase()
72
-    {
73
-        return $this->dbObject;
74
-    }
75
-
76
-    /**
77
-     * Saves a data object to the database, either updating or inserting a record.
78
-     *
79
-     * @return void
80
-     */
81
-    abstract public function save();
82
-
83
-    /**
84
-     * Retrieves the ID attribute
85
-     */
86
-    public function getId()
87
-    {
88
-        return (int)$this->id;
89
-    }
90
-
91
-    /**
92
-     * Deletes the object from the database
93
-     */
94
-    public function delete()
95
-    {
96
-        if ($this->id === null) {
97
-            // wtf?
98
-            return;
99
-        }
100
-
101
-        $array = explode('\\', get_called_class());
102
-        $realClassName = strtolower(end($array));
103
-
104
-        $deleteQuery = "DELETE FROM {$realClassName} WHERE id = :id AND updateversion = :updateversion LIMIT 1;";
105
-        $statement = $this->dbObject->prepare($deleteQuery);
106
-
107
-        $statement->bindValue(":id", $this->id);
108
-        $statement->bindValue(":updateversion", $this->updateversion);
109
-        $statement->execute();
110
-
111
-        if ($statement->rowCount() !== 1) {
112
-            throw new OptimisticLockFailedException();
113
-        }
114
-
115
-        $this->id = null;
116
-    }
117
-
118
-    /**
119
-     * @return int
120
-     */
121
-    public function getUpdateVersion()
122
-    {
123
-        return $this->updateversion;
124
-    }
125
-
126
-    /**
127
-     * Sets the update version.
128
-     *
129
-     * You should never call this to change the value of the update version. You should only call it when passing user
130
-     * input through.
131
-     *
132
-     * @param int $updateVersion
133
-     */
134
-    public function setUpdateVersion($updateVersion)
135
-    {
136
-        $this->updateversion = $updateVersion;
137
-    }
138
-
139
-    /**
140
-     * @return bool
141
-     */
142
-    public function isNew()
143
-    {
144
-        return $this->id === null;
145
-    }
26
+	/** @var int ID of the object */
27
+	protected $id = null;
28
+	/** @var int update version for optimistic locking */
29
+	protected $updateversion = 0;
30
+	/**
31
+	 * @var PdoDatabase
32
+	 */
33
+	protected $dbObject;
34
+
35
+	/**
36
+	 * Retrieves a data object by it's row ID.
37
+	 *
38
+	 * @param int         $id
39
+	 * @param PdoDatabase $database
40
+	 *
41
+	 * @return DataObject|false
42
+	 */
43
+	public static function getById($id, PdoDatabase $database)
44
+	{
45
+		$array = explode('\\', get_called_class());
46
+		$realClassName = strtolower(end($array));
47
+
48
+		$statement = $database->prepare("SELECT * FROM {$realClassName} WHERE id = :id LIMIT 1;");
49
+		$statement->bindValue(":id", $id);
50
+
51
+		$statement->execute();
52
+
53
+		$resultObject = $statement->fetchObject(get_called_class());
54
+
55
+		if ($resultObject != false) {
56
+			$resultObject->setDatabase($database);
57
+		}
58
+
59
+		return $resultObject;
60
+	}
61
+
62
+	public function setDatabase(PdoDatabase $db)
63
+	{
64
+		$this->dbObject = $db;
65
+	}
66
+
67
+	/**
68
+	 * Gets the database associated with this data object.
69
+	 * @return PdoDatabase
70
+	 */
71
+	public function getDatabase()
72
+	{
73
+		return $this->dbObject;
74
+	}
75
+
76
+	/**
77
+	 * Saves a data object to the database, either updating or inserting a record.
78
+	 *
79
+	 * @return void
80
+	 */
81
+	abstract public function save();
82
+
83
+	/**
84
+	 * Retrieves the ID attribute
85
+	 */
86
+	public function getId()
87
+	{
88
+		return (int)$this->id;
89
+	}
90
+
91
+	/**
92
+	 * Deletes the object from the database
93
+	 */
94
+	public function delete()
95
+	{
96
+		if ($this->id === null) {
97
+			// wtf?
98
+			return;
99
+		}
100
+
101
+		$array = explode('\\', get_called_class());
102
+		$realClassName = strtolower(end($array));
103
+
104
+		$deleteQuery = "DELETE FROM {$realClassName} WHERE id = :id AND updateversion = :updateversion LIMIT 1;";
105
+		$statement = $this->dbObject->prepare($deleteQuery);
106
+
107
+		$statement->bindValue(":id", $this->id);
108
+		$statement->bindValue(":updateversion", $this->updateversion);
109
+		$statement->execute();
110
+
111
+		if ($statement->rowCount() !== 1) {
112
+			throw new OptimisticLockFailedException();
113
+		}
114
+
115
+		$this->id = null;
116
+	}
117
+
118
+	/**
119
+	 * @return int
120
+	 */
121
+	public function getUpdateVersion()
122
+	{
123
+		return $this->updateversion;
124
+	}
125
+
126
+	/**
127
+	 * Sets the update version.
128
+	 *
129
+	 * You should never call this to change the value of the update version. You should only call it when passing user
130
+	 * input through.
131
+	 *
132
+	 * @param int $updateVersion
133
+	 */
134
+	public function setUpdateVersion($updateVersion)
135
+	{
136
+		$this->updateversion = $updateVersion;
137
+	}
138
+
139
+	/**
140
+	 * @return bool
141
+	 */
142
+	public function isNew()
143
+	{
144
+		return $this->id === null;
145
+	}
146 146
 }
Please login to merge, or discard this patch.
includes/Offline.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -15,55 +15,55 @@
 block discarded – undo
15 15
  */
16 16
 class Offline
17 17
 {
18
-    /**
19
-     * Determines if the tool is offline
20
-     * @return bool
21
-     */
22
-    public static function isOffline()
23
-    {
24
-        global $dontUseDb;
18
+	/**
19
+	 * Determines if the tool is offline
20
+	 * @return bool
21
+	 */
22
+	public static function isOffline()
23
+	{
24
+		global $dontUseDb;
25 25
 
26
-        return (bool)$dontUseDb;
27
-    }
26
+		return (bool)$dontUseDb;
27
+	}
28 28
 
29
-    /**
30
-     * Gets the offline message
31
-     *
32
-     * @param bool $external
33
-     * @param null $message
34
-     *
35
-     * @return string
36
-     */
37
-    public static function getOfflineMessage($external, $message = null)
38
-    {
39
-        global $dontUseDbCulprit, $dontUseDbReason, $baseurl;
29
+	/**
30
+	 * Gets the offline message
31
+	 *
32
+	 * @param bool $external
33
+	 * @param null $message
34
+	 *
35
+	 * @return string
36
+	 */
37
+	public static function getOfflineMessage($external, $message = null)
38
+	{
39
+		global $dontUseDbCulprit, $dontUseDbReason, $baseurl;
40 40
 
41
-        $smarty = new Smarty();
42
-        $smarty->assign("baseurl", $baseurl);
43
-        $smarty->assign("toolversion", Environment::getToolVersion());
41
+		$smarty = new Smarty();
42
+		$smarty->assign("baseurl", $baseurl);
43
+		$smarty->assign("toolversion", Environment::getToolVersion());
44 44
 
45
-        if (!headers_sent()) {
46
-            header("HTTP/1.1 503 Service Unavailable");
47
-        }
45
+		if (!headers_sent()) {
46
+			header("HTTP/1.1 503 Service Unavailable");
47
+		}
48 48
 
49
-        if ($external) {
50
-            return $smarty->fetch("offline/external.tpl");
51
-        }
52
-        else {
53
-            $hideCulprit = true;
49
+		if ($external) {
50
+			return $smarty->fetch("offline/external.tpl");
51
+		}
52
+		else {
53
+			$hideCulprit = true;
54 54
 
55
-            // Use the provided message if possible
56
-            if ($message === null) {
57
-                $hideCulprit = false;
58
-                $message = $dontUseDbReason;
59
-            }
55
+			// Use the provided message if possible
56
+			if ($message === null) {
57
+				$hideCulprit = false;
58
+				$message = $dontUseDbReason;
59
+			}
60 60
 
61
-            $smarty->assign("hideCulprit", $hideCulprit);
62
-            $smarty->assign("dontUseDbCulprit", $dontUseDbCulprit);
63
-            $smarty->assign("dontUseDbReason", $message);
64
-            $smarty->assign("alerts", array());
61
+			$smarty->assign("hideCulprit", $hideCulprit);
62
+			$smarty->assign("dontUseDbCulprit", $dontUseDbCulprit);
63
+			$smarty->assign("dontUseDbReason", $message);
64
+			$smarty->assign("alerts", array());
65 65
 
66
-            return $smarty->fetch("offline/internal.tpl");
67
-        }
68
-    }
66
+			return $smarty->fetch("offline/internal.tpl");
67
+		}
68
+	}
69 69
 }
Please login to merge, or discard this patch.