Failed Conditions
Push — newinternal ( b66232...216d62 )
by Simon
16:33 queued 06:35
created
includes/Security/CredentialProviders/YubikeyOtpCredentialProvider.php 3 patches
Doc Comments   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
     }
105 105
 
106 106
     /**
107
-     * @param $result
107
+     * @param string $result
108 108
      *
109 109
      * @return array
110 110
      */
@@ -123,6 +123,9 @@  discard block
 block discarded – undo
123 123
         return $data;
124 124
     }
125 125
 
126
+    /**
127
+     * @param string $data
128
+     */
126 129
     private function getYubikeyId($data)
127 130
     {
128 131
         return substr($data, 0, -32);
@@ -146,7 +149,7 @@  discard block
 block discarded – undo
146 149
     }
147 150
 
148 151
     /**
149
-     * @param $data
152
+     * @param string $data
150 153
      *
151 154
      * @return bool
152 155
      */
Please login to merge, or discard this patch.
Indentation   +150 added lines, -150 removed lines patch added patch discarded remove patch
@@ -16,154 +16,154 @@
 block discarded – undo
16 16
 
17 17
 class YubikeyOtpCredentialProvider extends CredentialProviderBase
18 18
 {
19
-    /** @var HttpHelper */
20
-    private $httpHelper;
21
-    /**
22
-     * @var SiteConfiguration
23
-     */
24
-    private $configuration;
25
-
26
-    public function __construct(PdoDatabase $database, SiteConfiguration $configuration, HttpHelper $httpHelper)
27
-    {
28
-        parent::__construct($database, $configuration, 'yubikeyotp');
29
-        $this->httpHelper = $httpHelper;
30
-        $this->configuration = $configuration;
31
-    }
32
-
33
-    public function authenticate(User $user, $data)
34
-    {
35
-        if (is_array($data)) {
36
-            return false;
37
-        }
38
-
39
-        $credentialData = $this->getCredentialData($user->getId());
40
-
41
-        if ($credentialData === null) {
42
-            return false;
43
-        }
44
-
45
-        if ($credentialData->getData() !== $this->getYubikeyId($data)) {
46
-            // different device
47
-            return false;
48
-        }
49
-
50
-        return $this->verifyToken($data);
51
-    }
52
-
53
-    public function setCredential(User $user, $factor, $data)
54
-    {
55
-        $keyId = $this->getYubikeyId($data);
56
-        $valid = $this->verifyToken($data);
57
-
58
-        if (!$valid) {
59
-            throw new ApplicationLogicException("Provided token is not valid.");
60
-        }
61
-
62
-        $storedData = $this->getCredentialData($user->getId());
63
-
64
-        if ($storedData === null) {
65
-            $storedData = $this->createNewCredential($user);
66
-        }
67
-
68
-        $storedData->setData($keyId);
69
-        $storedData->setFactor($factor);
70
-        $storedData->setVersion(1);
71
-        $storedData->setPriority(8);
72
-
73
-        $storedData->save();
74
-    }
75
-
76
-    /**
77
-     * Get the Yubikey ID.
78
-     *
79
-     * This looks like it's just dumping the "password" that's stored in the database, but it's actually fine.
80
-     *
81
-     * We only store the "serial number" of the Yubikey - if we get a validated (by webservice) token prefixed with the
82
-     * serial number, that's a successful OTP authentication. Thus, retrieving the stored data is just retrieving the
83
-     * yubikey's serial number (in modhex format), since the actual security credentials are stored on the device.
84
-     *
85
-     * Note that the serial number is actually the credential serial number - it's possible to regenerate the keys on
86
-     * the device, and that will change the serial number too.
87
-     *
88
-     * More information about the structure of OTPs can be found here:
89
-     * https://developers.yubico.com/OTP/OTPs_Explained.html
90
-     *
91
-     * @param int $userId
92
-     *
93
-     * @return null|string
94
-     */
95
-    public function getYubikeyData($userId)
96
-    {
97
-        $credential = $this->getCredentialData($userId);
98
-
99
-        if ($credential === null) {
100
-            return null;
101
-        }
102
-
103
-        return $credential->getData();
104
-    }
105
-
106
-    /**
107
-     * @param $result
108
-     *
109
-     * @return array
110
-     */
111
-    private function parseYubicoApiResult($result)
112
-    {
113
-        $data = array();
114
-        foreach (explode("\r\n", $result) as $line) {
115
-            $pos = strpos($line, '=');
116
-            if ($pos === false) {
117
-                continue;
118
-            }
119
-
120
-            $data[substr($line, 0, $pos)] = substr($line, $pos + 1);
121
-        }
122
-
123
-        return $data;
124
-    }
125
-
126
-    private function getYubikeyId($data)
127
-    {
128
-        return substr($data, 0, -32);
129
-    }
130
-
131
-    private function verifyHmac($apiResponse, $apiKey)
132
-    {
133
-        ksort($apiResponse);
134
-        $signature = $apiResponse['h'];
135
-        unset($apiResponse['h']);
136
-
137
-        $data = array();
138
-        foreach ($apiResponse as $key => $value) {
139
-            $data[] = $key . "=" . $value;
140
-        }
141
-        $dataString = implode('&', $data);
142
-
143
-        $hmac = base64_encode(hash_hmac('sha1', $dataString, base64_decode($apiKey), true));
144
-
145
-        return $hmac === $signature;
146
-    }
147
-
148
-    /**
149
-     * @param $data
150
-     *
151
-     * @return bool
152
-     */
153
-    private function verifyToken($data)
154
-    {
155
-        $result = $this->httpHelper->get('https://api.yubico.com/wsapi/2.0/verify', array(
156
-            'id'    => $this->configuration->getYubicoApiId(),
157
-            'otp'   => $data,
158
-            'nonce' => md5(openssl_random_pseudo_bytes(64)),
159
-        ));
160
-
161
-        $apiResponse = $this->parseYubicoApiResult($result);
162
-
163
-        if (!$this->verifyHmac($apiResponse, $this->configuration->getYubicoApiKey())) {
164
-            return false;
165
-        }
166
-
167
-        return $apiResponse['status'] == 'OK';
168
-    }
19
+	/** @var HttpHelper */
20
+	private $httpHelper;
21
+	/**
22
+	 * @var SiteConfiguration
23
+	 */
24
+	private $configuration;
25
+
26
+	public function __construct(PdoDatabase $database, SiteConfiguration $configuration, HttpHelper $httpHelper)
27
+	{
28
+		parent::__construct($database, $configuration, 'yubikeyotp');
29
+		$this->httpHelper = $httpHelper;
30
+		$this->configuration = $configuration;
31
+	}
32
+
33
+	public function authenticate(User $user, $data)
34
+	{
35
+		if (is_array($data)) {
36
+			return false;
37
+		}
38
+
39
+		$credentialData = $this->getCredentialData($user->getId());
40
+
41
+		if ($credentialData === null) {
42
+			return false;
43
+		}
44
+
45
+		if ($credentialData->getData() !== $this->getYubikeyId($data)) {
46
+			// different device
47
+			return false;
48
+		}
49
+
50
+		return $this->verifyToken($data);
51
+	}
52
+
53
+	public function setCredential(User $user, $factor, $data)
54
+	{
55
+		$keyId = $this->getYubikeyId($data);
56
+		$valid = $this->verifyToken($data);
57
+
58
+		if (!$valid) {
59
+			throw new ApplicationLogicException("Provided token is not valid.");
60
+		}
61
+
62
+		$storedData = $this->getCredentialData($user->getId());
63
+
64
+		if ($storedData === null) {
65
+			$storedData = $this->createNewCredential($user);
66
+		}
67
+
68
+		$storedData->setData($keyId);
69
+		$storedData->setFactor($factor);
70
+		$storedData->setVersion(1);
71
+		$storedData->setPriority(8);
72
+
73
+		$storedData->save();
74
+	}
75
+
76
+	/**
77
+	 * Get the Yubikey ID.
78
+	 *
79
+	 * This looks like it's just dumping the "password" that's stored in the database, but it's actually fine.
80
+	 *
81
+	 * We only store the "serial number" of the Yubikey - if we get a validated (by webservice) token prefixed with the
82
+	 * serial number, that's a successful OTP authentication. Thus, retrieving the stored data is just retrieving the
83
+	 * yubikey's serial number (in modhex format), since the actual security credentials are stored on the device.
84
+	 *
85
+	 * Note that the serial number is actually the credential serial number - it's possible to regenerate the keys on
86
+	 * the device, and that will change the serial number too.
87
+	 *
88
+	 * More information about the structure of OTPs can be found here:
89
+	 * https://developers.yubico.com/OTP/OTPs_Explained.html
90
+	 *
91
+	 * @param int $userId
92
+	 *
93
+	 * @return null|string
94
+	 */
95
+	public function getYubikeyData($userId)
96
+	{
97
+		$credential = $this->getCredentialData($userId);
98
+
99
+		if ($credential === null) {
100
+			return null;
101
+		}
102
+
103
+		return $credential->getData();
104
+	}
105
+
106
+	/**
107
+	 * @param $result
108
+	 *
109
+	 * @return array
110
+	 */
111
+	private function parseYubicoApiResult($result)
112
+	{
113
+		$data = array();
114
+		foreach (explode("\r\n", $result) as $line) {
115
+			$pos = strpos($line, '=');
116
+			if ($pos === false) {
117
+				continue;
118
+			}
119
+
120
+			$data[substr($line, 0, $pos)] = substr($line, $pos + 1);
121
+		}
122
+
123
+		return $data;
124
+	}
125
+
126
+	private function getYubikeyId($data)
127
+	{
128
+		return substr($data, 0, -32);
129
+	}
130
+
131
+	private function verifyHmac($apiResponse, $apiKey)
132
+	{
133
+		ksort($apiResponse);
134
+		$signature = $apiResponse['h'];
135
+		unset($apiResponse['h']);
136
+
137
+		$data = array();
138
+		foreach ($apiResponse as $key => $value) {
139
+			$data[] = $key . "=" . $value;
140
+		}
141
+		$dataString = implode('&', $data);
142
+
143
+		$hmac = base64_encode(hash_hmac('sha1', $dataString, base64_decode($apiKey), true));
144
+
145
+		return $hmac === $signature;
146
+	}
147
+
148
+	/**
149
+	 * @param $data
150
+	 *
151
+	 * @return bool
152
+	 */
153
+	private function verifyToken($data)
154
+	{
155
+		$result = $this->httpHelper->get('https://api.yubico.com/wsapi/2.0/verify', array(
156
+			'id'    => $this->configuration->getYubicoApiId(),
157
+			'otp'   => $data,
158
+			'nonce' => md5(openssl_random_pseudo_bytes(64)),
159
+		));
160
+
161
+		$apiResponse = $this->parseYubicoApiResult($result);
162
+
163
+		if (!$this->verifyHmac($apiResponse, $this->configuration->getYubicoApiKey())) {
164
+			return false;
165
+		}
166
+
167
+		return $apiResponse['status'] == 'OK';
168
+	}
169 169
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -136,7 +136,7 @@
 block discarded – undo
136 136
 
137 137
         $data = array();
138 138
         foreach ($apiResponse as $key => $value) {
139
-            $data[] = $key . "=" . $value;
139
+            $data[] = $key."=".$value;
140 140
         }
141 141
         $dataString = implode('&', $data);
142 142
 
Please login to merge, or discard this patch.
includes/Security/RoleConfiguration.php 2 patches
Unused Use Statements   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -16,11 +16,6 @@  discard block
 block discarded – undo
16 16
 use Waca\Pages\PageJobQueue;
17 17
 use Waca\Pages\PageLog;
18 18
 use Waca\Pages\PageMain;
19
-use Waca\Pages\RequestAction\PageCreateRequest;
20
-use Waca\Pages\UserAuth\PageChangePassword;
21
-use Waca\Pages\UserAuth\MultiFactor\PageMultiFactor;
22
-use Waca\Pages\UserAuth\PageOAuth;
23
-use Waca\Pages\UserAuth\PagePreferences;
24 19
 use Waca\Pages\PageSearch;
25 20
 use Waca\Pages\PageSiteNotice;
26 21
 use Waca\Pages\PageTeam;
@@ -30,6 +25,7 @@  discard block
 block discarded – undo
30 25
 use Waca\Pages\RequestAction\PageBreakReservation;
31 26
 use Waca\Pages\RequestAction\PageCloseRequest;
32 27
 use Waca\Pages\RequestAction\PageComment;
28
+use Waca\Pages\RequestAction\PageCreateRequest;
33 29
 use Waca\Pages\RequestAction\PageCustomClose;
34 30
 use Waca\Pages\RequestAction\PageDeferRequest;
35 31
 use Waca\Pages\RequestAction\PageDropRequest;
@@ -43,6 +39,10 @@  discard block
 block discarded – undo
43 39
 use Waca\Pages\Statistics\StatsTemplateStats;
44 40
 use Waca\Pages\Statistics\StatsTopCreators;
45 41
 use Waca\Pages\Statistics\StatsUsers;
42
+use Waca\Pages\UserAuth\MultiFactor\PageMultiFactor;
43
+use Waca\Pages\UserAuth\PageChangePassword;
44
+use Waca\Pages\UserAuth\PageOAuth;
45
+use Waca\Pages\UserAuth\PagePreferences;
46 46
 
47 47
 class RoleConfiguration
48 48
 {
Please login to merge, or discard this patch.
Indentation   +344 added lines, -344 removed lines patch added patch discarded remove patch
@@ -46,374 +46,374 @@
 block discarded – undo
46 46
 
47 47
 class RoleConfiguration
48 48
 {
49
-    const ACCESS_ALLOW = 1;
50
-    const ACCESS_DENY = -1;
51
-    const ACCESS_DEFAULT = 0;
52
-    const MAIN = 'main';
53
-    const ALL = '*';
54
-    /**
55
-     * A map of roles to rights
56
-     *
57
-     * For example:
58
-     *
59
-     * array(
60
-     *   'myrole' => array(
61
-     *       PageMyPage::class => array(
62
-     *           'edit' => self::ACCESS_ALLOW,
63
-     *           'create' => self::ACCESS_DENY,
64
-     *       )
65
-     *   )
66
-     * )
67
-     *
68
-     * Note that DENY takes precedence over everything else when roles are combined, followed by ALLOW, followed by
69
-     * DEFAULT. Thus, if you have the following ([A]llow, [D]eny, [-] (default)) grants in different roles, this should
70
-     * be the expected result:
71
-     *
72
-     * - (-,-,-) = - (default because nothing to explicitly say allowed or denied equates to a denial)
73
-     * - (A,-,-) = A
74
-     * - (D,-,-) = D
75
-     * - (A,D,-) = D (deny takes precedence over allow)
76
-     * - (A,A,A) = A (repetition has no effect)
77
-     *
78
-     * The public role is special, and is applied to all users automatically. Avoid using deny on this role.
79
-     *
80
-     * @var array
81
-     */
82
-    private $roleConfig = array(
83
-        'public'            => array(
84
-            /*
49
+	const ACCESS_ALLOW = 1;
50
+	const ACCESS_DENY = -1;
51
+	const ACCESS_DEFAULT = 0;
52
+	const MAIN = 'main';
53
+	const ALL = '*';
54
+	/**
55
+	 * A map of roles to rights
56
+	 *
57
+	 * For example:
58
+	 *
59
+	 * array(
60
+	 *   'myrole' => array(
61
+	 *       PageMyPage::class => array(
62
+	 *           'edit' => self::ACCESS_ALLOW,
63
+	 *           'create' => self::ACCESS_DENY,
64
+	 *       )
65
+	 *   )
66
+	 * )
67
+	 *
68
+	 * Note that DENY takes precedence over everything else when roles are combined, followed by ALLOW, followed by
69
+	 * DEFAULT. Thus, if you have the following ([A]llow, [D]eny, [-] (default)) grants in different roles, this should
70
+	 * be the expected result:
71
+	 *
72
+	 * - (-,-,-) = - (default because nothing to explicitly say allowed or denied equates to a denial)
73
+	 * - (A,-,-) = A
74
+	 * - (D,-,-) = D
75
+	 * - (A,D,-) = D (deny takes precedence over allow)
76
+	 * - (A,A,A) = A (repetition has no effect)
77
+	 *
78
+	 * The public role is special, and is applied to all users automatically. Avoid using deny on this role.
79
+	 *
80
+	 * @var array
81
+	 */
82
+	private $roleConfig = array(
83
+		'public'            => array(
84
+			/*
85 85
              * THIS ROLE IS GRANTED TO ALL LOGGED *OUT* USERS IMPLICITLY.
86 86
              *
87 87
              * USERS IN THIS ROLE DO NOT HAVE TO BE IDENTIFIED TO GET THE RIGHTS CONFERRED HERE.
88 88
              * DO NOT ADD ANY SECURITY-SENSITIVE RIGHTS HERE.
89 89
              */
90
-            '_childRoles'   => array(
91
-                'publicStats',
92
-            ),
93
-            PageTeam::class => array(
94
-                self::MAIN => self::ACCESS_ALLOW,
95
-            ),
96
-        ),
97
-        'loggedIn'          => array(
98
-            /*
90
+			'_childRoles'   => array(
91
+				'publicStats',
92
+			),
93
+			PageTeam::class => array(
94
+				self::MAIN => self::ACCESS_ALLOW,
95
+			),
96
+		),
97
+		'loggedIn'          => array(
98
+			/*
99 99
              * THIS ROLE IS GRANTED TO ALL LOGGED IN USERS IMPLICITLY.
100 100
              *
101 101
              * USERS IN THIS ROLE DO NOT HAVE TO BE IDENTIFIED TO GET THE RIGHTS CONFERRED HERE.
102 102
              * DO NOT ADD ANY SECURITY-SENSITIVE RIGHTS HERE.
103 103
              */
104
-            '_childRoles'             => array(
105
-                'public',
106
-            ),
107
-            PagePreferences::class    => array(
108
-                self::MAIN => self::ACCESS_ALLOW,
109
-            ),
110
-            PageChangePassword::class => array(
111
-                self::MAIN => self::ACCESS_ALLOW,
112
-            ),
113
-            PageMultiFactor::class    => array(
114
-                self::MAIN          => self::ACCESS_ALLOW,
115
-                'scratch'           => self::ACCESS_ALLOW,
116
-                'enableYubikeyOtp'  => self::ACCESS_ALLOW,
117
-                'disableYubikeyOtp' => self::ACCESS_ALLOW,
118
-                'enableTotp'        => self::ACCESS_ALLOW,
119
-                'disableTotp'       => self::ACCESS_ALLOW,
120
-                'enableU2F'       => self::ACCESS_ALLOW,
121
-                'disableU2F'       => self::ACCESS_ALLOW,
122
-            ),
123
-            PageOAuth::class          => array(
124
-                'attach' => self::ACCESS_ALLOW,
125
-                'detach' => self::ACCESS_ALLOW,
126
-            ),
127
-        ),
128
-        'user'              => array(
129
-            '_description'                       => 'A standard tool user.',
130
-            '_editableBy'                        => array('admin', 'toolRoot'),
131
-            '_childRoles'                        => array(
132
-                'internalStats',
133
-            ),
134
-            PageMain::class                      => array(
135
-                self::MAIN => self::ACCESS_ALLOW,
136
-            ),
137
-            PageBan::class                       => array(
138
-                self::MAIN => self::ACCESS_ALLOW,
139
-            ),
140
-            PageEditComment::class               => array(
141
-                self::MAIN => self::ACCESS_ALLOW,
142
-            ),
143
-            PageEmailManagement::class           => array(
144
-                self::MAIN => self::ACCESS_ALLOW,
145
-                'view'     => self::ACCESS_ALLOW,
146
-            ),
147
-            PageExpandedRequestList::class       => array(
148
-                self::MAIN => self::ACCESS_ALLOW,
149
-            ),
150
-            PageLog::class                       => array(
151
-                self::MAIN => self::ACCESS_ALLOW,
152
-            ),
153
-            PageSearch::class                    => array(
154
-                self::MAIN => self::ACCESS_ALLOW,
155
-            ),
156
-            PageWelcomeTemplateManagement::class => array(
157
-                self::MAIN => self::ACCESS_ALLOW,
158
-                'select'   => self::ACCESS_ALLOW,
159
-                'view'     => self::ACCESS_ALLOW,
160
-            ),
161
-            PageViewRequest::class               => array(
162
-                self::MAIN       => self::ACCESS_ALLOW,
163
-                'seeAllRequests' => self::ACCESS_ALLOW,
164
-            ),
165
-            'RequestData'                        => array(
166
-                'seePrivateDataWhenReserved' => self::ACCESS_ALLOW,
167
-                'seePrivateDataWithHash'     => self::ACCESS_ALLOW,
168
-            ),
169
-            PageCustomClose::class               => array(
170
-                self::MAIN => self::ACCESS_ALLOW,
171
-            ),
172
-            PageComment::class                   => array(
173
-                self::MAIN => self::ACCESS_ALLOW,
174
-            ),
175
-            PageCloseRequest::class              => array(
176
-                self::MAIN => self::ACCESS_ALLOW,
177
-            ),
178
-            PageCreateRequest::class             => array(
179
-                self::MAIN => self::ACCESS_ALLOW,
180
-            ),
181
-            PageDeferRequest::class              => array(
182
-                self::MAIN => self::ACCESS_ALLOW,
183
-            ),
184
-            PageDropRequest::class               => array(
185
-                self::MAIN => self::ACCESS_ALLOW,
186
-            ),
187
-            PageReservation::class               => array(
188
-                self::MAIN => self::ACCESS_ALLOW,
189
-            ),
190
-            PageSendToUser::class                => array(
191
-                self::MAIN => self::ACCESS_ALLOW,
192
-            ),
193
-            PageBreakReservation::class          => array(
194
-                self::MAIN => self::ACCESS_ALLOW,
195
-            ),
196
-            PageJobQueue::class                  => array(
197
-                self::MAIN => self::ACCESS_ALLOW,
198
-                'view'     => self::ACCESS_ALLOW,
199
-                'all'      => self::ACCESS_ALLOW,
200
-            ),
201
-            'RequestCreation'                    => array(
202
-                User::CREATION_MANUAL => self::ACCESS_ALLOW,
203
-                User::CREATION_OAUTH  => self::ACCESS_ALLOW,
204
-            ),
205
-        ),
206
-        'admin'             => array(
207
-            '_description'                       => 'A tool administrator.',
208
-            '_editableBy'                        => array('admin', 'toolRoot'),
209
-            '_childRoles'                        => array(
210
-                'user',
211
-                'requestAdminTools',
212
-            ),
213
-            PageEmailManagement::class           => array(
214
-                'edit'   => self::ACCESS_ALLOW,
215
-                'create' => self::ACCESS_ALLOW,
216
-            ),
217
-            PageSiteNotice::class                => array(
218
-                self::MAIN => self::ACCESS_ALLOW,
219
-            ),
220
-            PageUserManagement::class            => array(
221
-                self::MAIN  => self::ACCESS_ALLOW,
222
-                'approve'   => self::ACCESS_ALLOW,
223
-                'decline'   => self::ACCESS_ALLOW,
224
-                'rename'    => self::ACCESS_ALLOW,
225
-                'editUser'  => self::ACCESS_ALLOW,
226
-                'suspend'   => self::ACCESS_ALLOW,
227
-                'editRoles' => self::ACCESS_ALLOW,
228
-            ),
229
-            PageWelcomeTemplateManagement::class => array(
230
-                'edit'   => self::ACCESS_ALLOW,
231
-                'delete' => self::ACCESS_ALLOW,
232
-                'add'    => self::ACCESS_ALLOW,
233
-            ),
234
-            PageJobQueue::class                  => array(
235
-                'acknowledge' => self::ACCESS_ALLOW,
236
-                'requeue'     => self::ACCESS_ALLOW,
237
-            ),
238
-        ),
239
-        'checkuser'         => array(
240
-            '_description'            => 'A user with CheckUser access',
241
-            '_editableBy'             => array('checkuser', 'toolRoot'),
242
-            '_childRoles'             => array(
243
-                'user',
244
-                'requestAdminTools',
245
-            ),
246
-            PageUserManagement::class => array(
247
-                self::MAIN  => self::ACCESS_ALLOW,
248
-                'suspend'   => self::ACCESS_ALLOW,
249
-                'editRoles' => self::ACCESS_ALLOW,
250
-            ),
251
-            'RequestData'             => array(
252
-                'seeUserAgentData' => self::ACCESS_ALLOW,
253
-            ),
254
-        ),
255
-        'toolRoot'          => array(
256
-            '_description' => 'A user with shell access to the servers running the tool',
257
-            '_editableBy'  => array('toolRoot'),
258
-            '_childRoles'  => array(
259
-                'admin',
260
-                'checkuser',
261
-            ),
262
-        ),
263
-        'botCreation'       => array(
264
-            '_description'    => 'A user allowed to use the bot to perform account creations',
265
-            '_editableBy'     => array('admin', 'toolRoot'),
266
-            '_childRoles'     => array(),
267
-            'RequestCreation' => array(
268
-                User::CREATION_BOT => self::ACCESS_ALLOW,
269
-            ),
270
-        ),
104
+			'_childRoles'             => array(
105
+				'public',
106
+			),
107
+			PagePreferences::class    => array(
108
+				self::MAIN => self::ACCESS_ALLOW,
109
+			),
110
+			PageChangePassword::class => array(
111
+				self::MAIN => self::ACCESS_ALLOW,
112
+			),
113
+			PageMultiFactor::class    => array(
114
+				self::MAIN          => self::ACCESS_ALLOW,
115
+				'scratch'           => self::ACCESS_ALLOW,
116
+				'enableYubikeyOtp'  => self::ACCESS_ALLOW,
117
+				'disableYubikeyOtp' => self::ACCESS_ALLOW,
118
+				'enableTotp'        => self::ACCESS_ALLOW,
119
+				'disableTotp'       => self::ACCESS_ALLOW,
120
+				'enableU2F'       => self::ACCESS_ALLOW,
121
+				'disableU2F'       => self::ACCESS_ALLOW,
122
+			),
123
+			PageOAuth::class          => array(
124
+				'attach' => self::ACCESS_ALLOW,
125
+				'detach' => self::ACCESS_ALLOW,
126
+			),
127
+		),
128
+		'user'              => array(
129
+			'_description'                       => 'A standard tool user.',
130
+			'_editableBy'                        => array('admin', 'toolRoot'),
131
+			'_childRoles'                        => array(
132
+				'internalStats',
133
+			),
134
+			PageMain::class                      => array(
135
+				self::MAIN => self::ACCESS_ALLOW,
136
+			),
137
+			PageBan::class                       => array(
138
+				self::MAIN => self::ACCESS_ALLOW,
139
+			),
140
+			PageEditComment::class               => array(
141
+				self::MAIN => self::ACCESS_ALLOW,
142
+			),
143
+			PageEmailManagement::class           => array(
144
+				self::MAIN => self::ACCESS_ALLOW,
145
+				'view'     => self::ACCESS_ALLOW,
146
+			),
147
+			PageExpandedRequestList::class       => array(
148
+				self::MAIN => self::ACCESS_ALLOW,
149
+			),
150
+			PageLog::class                       => array(
151
+				self::MAIN => self::ACCESS_ALLOW,
152
+			),
153
+			PageSearch::class                    => array(
154
+				self::MAIN => self::ACCESS_ALLOW,
155
+			),
156
+			PageWelcomeTemplateManagement::class => array(
157
+				self::MAIN => self::ACCESS_ALLOW,
158
+				'select'   => self::ACCESS_ALLOW,
159
+				'view'     => self::ACCESS_ALLOW,
160
+			),
161
+			PageViewRequest::class               => array(
162
+				self::MAIN       => self::ACCESS_ALLOW,
163
+				'seeAllRequests' => self::ACCESS_ALLOW,
164
+			),
165
+			'RequestData'                        => array(
166
+				'seePrivateDataWhenReserved' => self::ACCESS_ALLOW,
167
+				'seePrivateDataWithHash'     => self::ACCESS_ALLOW,
168
+			),
169
+			PageCustomClose::class               => array(
170
+				self::MAIN => self::ACCESS_ALLOW,
171
+			),
172
+			PageComment::class                   => array(
173
+				self::MAIN => self::ACCESS_ALLOW,
174
+			),
175
+			PageCloseRequest::class              => array(
176
+				self::MAIN => self::ACCESS_ALLOW,
177
+			),
178
+			PageCreateRequest::class             => array(
179
+				self::MAIN => self::ACCESS_ALLOW,
180
+			),
181
+			PageDeferRequest::class              => array(
182
+				self::MAIN => self::ACCESS_ALLOW,
183
+			),
184
+			PageDropRequest::class               => array(
185
+				self::MAIN => self::ACCESS_ALLOW,
186
+			),
187
+			PageReservation::class               => array(
188
+				self::MAIN => self::ACCESS_ALLOW,
189
+			),
190
+			PageSendToUser::class                => array(
191
+				self::MAIN => self::ACCESS_ALLOW,
192
+			),
193
+			PageBreakReservation::class          => array(
194
+				self::MAIN => self::ACCESS_ALLOW,
195
+			),
196
+			PageJobQueue::class                  => array(
197
+				self::MAIN => self::ACCESS_ALLOW,
198
+				'view'     => self::ACCESS_ALLOW,
199
+				'all'      => self::ACCESS_ALLOW,
200
+			),
201
+			'RequestCreation'                    => array(
202
+				User::CREATION_MANUAL => self::ACCESS_ALLOW,
203
+				User::CREATION_OAUTH  => self::ACCESS_ALLOW,
204
+			),
205
+		),
206
+		'admin'             => array(
207
+			'_description'                       => 'A tool administrator.',
208
+			'_editableBy'                        => array('admin', 'toolRoot'),
209
+			'_childRoles'                        => array(
210
+				'user',
211
+				'requestAdminTools',
212
+			),
213
+			PageEmailManagement::class           => array(
214
+				'edit'   => self::ACCESS_ALLOW,
215
+				'create' => self::ACCESS_ALLOW,
216
+			),
217
+			PageSiteNotice::class                => array(
218
+				self::MAIN => self::ACCESS_ALLOW,
219
+			),
220
+			PageUserManagement::class            => array(
221
+				self::MAIN  => self::ACCESS_ALLOW,
222
+				'approve'   => self::ACCESS_ALLOW,
223
+				'decline'   => self::ACCESS_ALLOW,
224
+				'rename'    => self::ACCESS_ALLOW,
225
+				'editUser'  => self::ACCESS_ALLOW,
226
+				'suspend'   => self::ACCESS_ALLOW,
227
+				'editRoles' => self::ACCESS_ALLOW,
228
+			),
229
+			PageWelcomeTemplateManagement::class => array(
230
+				'edit'   => self::ACCESS_ALLOW,
231
+				'delete' => self::ACCESS_ALLOW,
232
+				'add'    => self::ACCESS_ALLOW,
233
+			),
234
+			PageJobQueue::class                  => array(
235
+				'acknowledge' => self::ACCESS_ALLOW,
236
+				'requeue'     => self::ACCESS_ALLOW,
237
+			),
238
+		),
239
+		'checkuser'         => array(
240
+			'_description'            => 'A user with CheckUser access',
241
+			'_editableBy'             => array('checkuser', 'toolRoot'),
242
+			'_childRoles'             => array(
243
+				'user',
244
+				'requestAdminTools',
245
+			),
246
+			PageUserManagement::class => array(
247
+				self::MAIN  => self::ACCESS_ALLOW,
248
+				'suspend'   => self::ACCESS_ALLOW,
249
+				'editRoles' => self::ACCESS_ALLOW,
250
+			),
251
+			'RequestData'             => array(
252
+				'seeUserAgentData' => self::ACCESS_ALLOW,
253
+			),
254
+		),
255
+		'toolRoot'          => array(
256
+			'_description' => 'A user with shell access to the servers running the tool',
257
+			'_editableBy'  => array('toolRoot'),
258
+			'_childRoles'  => array(
259
+				'admin',
260
+				'checkuser',
261
+			),
262
+		),
263
+		'botCreation'       => array(
264
+			'_description'    => 'A user allowed to use the bot to perform account creations',
265
+			'_editableBy'     => array('admin', 'toolRoot'),
266
+			'_childRoles'     => array(),
267
+			'RequestCreation' => array(
268
+				User::CREATION_BOT => self::ACCESS_ALLOW,
269
+			),
270
+		),
271 271
 
272
-        // Child roles go below this point
273
-        'publicStats'       => array(
274
-            '_hidden'               => true,
275
-            StatsUsers::class       => array(
276
-                self::MAIN => self::ACCESS_ALLOW,
277
-                'detail'   => self::ACCESS_ALLOW,
278
-            ),
279
-            StatsTopCreators::class => array(
280
-                self::MAIN => self::ACCESS_ALLOW,
281
-            ),
282
-        ),
283
-        'internalStats'     => array(
284
-            '_hidden'                    => true,
285
-            StatsMain::class             => array(
286
-                self::MAIN => self::ACCESS_ALLOW,
287
-            ),
288
-            StatsFastCloses::class       => array(
289
-                self::MAIN => self::ACCESS_ALLOW,
290
-            ),
291
-            StatsInactiveUsers::class    => array(
292
-                self::MAIN => self::ACCESS_ALLOW,
293
-            ),
294
-            StatsMonthlyStats::class     => array(
295
-                self::MAIN => self::ACCESS_ALLOW,
296
-            ),
297
-            StatsReservedRequests::class => array(
298
-                self::MAIN => self::ACCESS_ALLOW,
299
-            ),
300
-            StatsTemplateStats::class    => array(
301
-                self::MAIN => self::ACCESS_ALLOW,
302
-            ),
303
-        ),
304
-        'requestAdminTools' => array(
305
-            '_hidden'                   => true,
306
-            PageBan::class              => array(
307
-                self::MAIN => self::ACCESS_ALLOW,
308
-                'set'      => self::ACCESS_ALLOW,
309
-                'remove'   => self::ACCESS_ALLOW,
310
-            ),
311
-            PageEditComment::class      => array(
312
-                'editOthers' => self::ACCESS_ALLOW,
313
-            ),
314
-            PageBreakReservation::class => array(
315
-                'force' => self::ACCESS_ALLOW,
316
-            ),
317
-            PageCustomClose::class      => array(
318
-                'skipCcMailingList' => self::ACCESS_ALLOW,
319
-            ),
320
-            'RequestData'               => array(
321
-                'reopenOldRequest'      => self::ACCESS_ALLOW,
322
-                'alwaysSeePrivateData'  => self::ACCESS_ALLOW,
323
-                'alwaysSeeHash'         => self::ACCESS_ALLOW,
324
-                'seeRestrictedComments' => self::ACCESS_ALLOW,
325
-            ),
326
-        ),
327
-    );
328
-    /** @var array
329
-     * List of roles which are *exempt* from the identification requirements
330
-     *
331
-     * Think twice about adding roles to this list.
332
-     *
333
-     * @category Security-Critical
334
-     */
335
-    private $identificationExempt = array('public', 'loggedIn');
272
+		// Child roles go below this point
273
+		'publicStats'       => array(
274
+			'_hidden'               => true,
275
+			StatsUsers::class       => array(
276
+				self::MAIN => self::ACCESS_ALLOW,
277
+				'detail'   => self::ACCESS_ALLOW,
278
+			),
279
+			StatsTopCreators::class => array(
280
+				self::MAIN => self::ACCESS_ALLOW,
281
+			),
282
+		),
283
+		'internalStats'     => array(
284
+			'_hidden'                    => true,
285
+			StatsMain::class             => array(
286
+				self::MAIN => self::ACCESS_ALLOW,
287
+			),
288
+			StatsFastCloses::class       => array(
289
+				self::MAIN => self::ACCESS_ALLOW,
290
+			),
291
+			StatsInactiveUsers::class    => array(
292
+				self::MAIN => self::ACCESS_ALLOW,
293
+			),
294
+			StatsMonthlyStats::class     => array(
295
+				self::MAIN => self::ACCESS_ALLOW,
296
+			),
297
+			StatsReservedRequests::class => array(
298
+				self::MAIN => self::ACCESS_ALLOW,
299
+			),
300
+			StatsTemplateStats::class    => array(
301
+				self::MAIN => self::ACCESS_ALLOW,
302
+			),
303
+		),
304
+		'requestAdminTools' => array(
305
+			'_hidden'                   => true,
306
+			PageBan::class              => array(
307
+				self::MAIN => self::ACCESS_ALLOW,
308
+				'set'      => self::ACCESS_ALLOW,
309
+				'remove'   => self::ACCESS_ALLOW,
310
+			),
311
+			PageEditComment::class      => array(
312
+				'editOthers' => self::ACCESS_ALLOW,
313
+			),
314
+			PageBreakReservation::class => array(
315
+				'force' => self::ACCESS_ALLOW,
316
+			),
317
+			PageCustomClose::class      => array(
318
+				'skipCcMailingList' => self::ACCESS_ALLOW,
319
+			),
320
+			'RequestData'               => array(
321
+				'reopenOldRequest'      => self::ACCESS_ALLOW,
322
+				'alwaysSeePrivateData'  => self::ACCESS_ALLOW,
323
+				'alwaysSeeHash'         => self::ACCESS_ALLOW,
324
+				'seeRestrictedComments' => self::ACCESS_ALLOW,
325
+			),
326
+		),
327
+	);
328
+	/** @var array
329
+	 * List of roles which are *exempt* from the identification requirements
330
+	 *
331
+	 * Think twice about adding roles to this list.
332
+	 *
333
+	 * @category Security-Critical
334
+	 */
335
+	private $identificationExempt = array('public', 'loggedIn');
336 336
 
337
-    /**
338
-     * RoleConfiguration constructor.
339
-     *
340
-     * @param array $roleConfig           Set to non-null to override the default configuration.
341
-     * @param array $identificationExempt Set to non-null to override the default configuration.
342
-     */
343
-    public function __construct(array $roleConfig = null, array $identificationExempt = null)
344
-    {
345
-        if ($roleConfig !== null) {
346
-            $this->roleConfig = $roleConfig;
347
-        }
337
+	/**
338
+	 * RoleConfiguration constructor.
339
+	 *
340
+	 * @param array $roleConfig           Set to non-null to override the default configuration.
341
+	 * @param array $identificationExempt Set to non-null to override the default configuration.
342
+	 */
343
+	public function __construct(array $roleConfig = null, array $identificationExempt = null)
344
+	{
345
+		if ($roleConfig !== null) {
346
+			$this->roleConfig = $roleConfig;
347
+		}
348 348
 
349
-        if ($identificationExempt !== null) {
350
-            $this->identificationExempt = $identificationExempt;
351
-        }
352
-    }
349
+		if ($identificationExempt !== null) {
350
+			$this->identificationExempt = $identificationExempt;
351
+		}
352
+	}
353 353
 
354
-    /**
355
-     * @param array $roles The roles to check
356
-     *
357
-     * @return array
358
-     */
359
-    public function getApplicableRoles(array $roles)
360
-    {
361
-        $available = array();
354
+	/**
355
+	 * @param array $roles The roles to check
356
+	 *
357
+	 * @return array
358
+	 */
359
+	public function getApplicableRoles(array $roles)
360
+	{
361
+		$available = array();
362 362
 
363
-        foreach ($roles as $role) {
364
-            if (!isset($this->roleConfig[$role])) {
365
-                // wat
366
-                continue;
367
-            }
363
+		foreach ($roles as $role) {
364
+			if (!isset($this->roleConfig[$role])) {
365
+				// wat
366
+				continue;
367
+			}
368 368
 
369
-            $available[$role] = $this->roleConfig[$role];
369
+			$available[$role] = $this->roleConfig[$role];
370 370
 
371
-            if (isset($available[$role]['_childRoles'])) {
372
-                $childRoles = self::getApplicableRoles($available[$role]['_childRoles']);
373
-                $available = array_merge($available, $childRoles);
371
+			if (isset($available[$role]['_childRoles'])) {
372
+				$childRoles = self::getApplicableRoles($available[$role]['_childRoles']);
373
+				$available = array_merge($available, $childRoles);
374 374
 
375
-                unset($available[$role]['_childRoles']);
376
-            }
375
+				unset($available[$role]['_childRoles']);
376
+			}
377 377
 
378
-            foreach (array('_hidden', '_editableBy', '_description') as $item) {
379
-                if (isset($available[$role][$item])) {
380
-                    unset($available[$role][$item]);
381
-                }
382
-            }
383
-        }
378
+			foreach (array('_hidden', '_editableBy', '_description') as $item) {
379
+				if (isset($available[$role][$item])) {
380
+					unset($available[$role][$item]);
381
+				}
382
+			}
383
+		}
384 384
 
385
-        return $available;
386
-    }
385
+		return $available;
386
+	}
387 387
 
388
-    public function getAvailableRoles()
389
-    {
390
-        $possible = array_diff(array_keys($this->roleConfig), array('public', 'loggedIn'));
388
+	public function getAvailableRoles()
389
+	{
390
+		$possible = array_diff(array_keys($this->roleConfig), array('public', 'loggedIn'));
391 391
 
392
-        $actual = array();
392
+		$actual = array();
393 393
 
394
-        foreach ($possible as $role) {
395
-            if (!isset($this->roleConfig[$role]['_hidden'])) {
396
-                $actual[$role] = array(
397
-                    'description' => $this->roleConfig[$role]['_description'],
398
-                    'editableBy'  => $this->roleConfig[$role]['_editableBy'],
399
-                );
400
-            }
401
-        }
394
+		foreach ($possible as $role) {
395
+			if (!isset($this->roleConfig[$role]['_hidden'])) {
396
+				$actual[$role] = array(
397
+					'description' => $this->roleConfig[$role]['_description'],
398
+					'editableBy'  => $this->roleConfig[$role]['_editableBy'],
399
+				);
400
+			}
401
+		}
402 402
 
403
-        return $actual;
404
-    }
403
+		return $actual;
404
+	}
405 405
 
406
-    /**
407
-     * @param string $role
408
-     *
409
-     * @return bool
410
-     */
411
-    public function roleNeedsIdentification($role)
412
-    {
413
-        if (in_array($role, $this->identificationExempt)) {
414
-            return false;
415
-        }
406
+	/**
407
+	 * @param string $role
408
+	 *
409
+	 * @return bool
410
+	 */
411
+	public function roleNeedsIdentification($role)
412
+	{
413
+		if (in_array($role, $this->identificationExempt)) {
414
+			return false;
415
+		}
416 416
 
417
-        return true;
418
-    }
417
+		return true;
418
+	}
419 419
 }
Please login to merge, or discard this patch.
includes/WebRequest.php 2 patches
Doc Comments   +4 added lines patch added patch discarded remove patch
@@ -513,6 +513,10 @@
 block discarded – undo
513 513
         return isset($session['oauthPartialLogin']) ? (int)$session['oauthPartialLogin'] : null;
514 514
     }
515 515
 
516
+    /**
517
+     * @param integer $userId
518
+     * @param integer $stage
519
+     */
516 520
     public static function setAuthPartialLogin($userId, $stage)
517 521
     {
518 522
         $session = &self::$globalStateProvider->getSessionSuperGlobal();
Please login to merge, or discard this patch.
Indentation   +556 added lines, -556 removed lines patch added patch discarded remove patch
@@ -22,560 +22,560 @@
 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 remote address of the web request
124
-     * @return null|string
125
-     */
126
-    public static function httpHost()
127
-    {
128
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
129
-
130
-        if (isset($server['HTTP_HOST'])) {
131
-            return $server['HTTP_HOST'];
132
-        }
133
-
134
-        return null;
135
-    }
136
-
137
-    /**
138
-     * Gets the XFF header contents for the web request
139
-     * @return null|string
140
-     */
141
-    public static function forwardedAddress()
142
-    {
143
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
144
-
145
-        if (isset($server['HTTP_X_FORWARDED_FOR'])) {
146
-            return $server['HTTP_X_FORWARDED_FOR'];
147
-        }
148
-
149
-        return null;
150
-    }
151
-
152
-    /**
153
-     * Sets the global state provider.
154
-     *
155
-     * Almost guaranteed this is not the method you want in production code.
156
-     *
157
-     * @param \Waca\Providers\GlobalState\IGlobalStateProvider $globalState
158
-     */
159
-    public static function setGlobalStateProvider($globalState)
160
-    {
161
-        self::$globalStateProvider = $globalState;
162
-    }
163
-
164
-    #region POST variables
165
-
166
-    /**
167
-     * @param string $key
168
-     *
169
-     * @return null|string
170
-     */
171
-    public static function postString($key)
172
-    {
173
-        $post = &self::$globalStateProvider->getPostSuperGlobal();
174
-        if (!array_key_exists($key, $post)) {
175
-            return null;
176
-        }
177
-
178
-        if ($post[$key] === "") {
179
-            return null;
180
-        }
181
-
182
-        return (string)$post[$key];
183
-    }
184
-
185
-    /**
186
-     * @param string $key
187
-     *
188
-     * @return null|string
189
-     */
190
-    public static function postEmail($key)
191
-    {
192
-        $post = &self::$globalStateProvider->getPostSuperGlobal();
193
-        if (!array_key_exists($key, $post)) {
194
-            return null;
195
-        }
196
-
197
-        $filteredValue = filter_var($post[$key], FILTER_SANITIZE_EMAIL);
198
-
199
-        if ($filteredValue === false) {
200
-            return null;
201
-        }
202
-
203
-        return (string)$filteredValue;
204
-    }
205
-
206
-    /**
207
-     * @param string $key
208
-     *
209
-     * @return int|null
210
-     */
211
-    public static function postInt($key)
212
-    {
213
-        $post = &self::$globalStateProvider->getPostSuperGlobal();
214
-        if (!array_key_exists($key, $post)) {
215
-            return null;
216
-        }
217
-
218
-        $filteredValue = filter_var($post[$key], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
219
-
220
-        if ($filteredValue === null) {
221
-            return null;
222
-        }
223
-
224
-        return (int)$filteredValue;
225
-    }
226
-
227
-    /**
228
-     * @param string $key
229
-     *
230
-     * @return bool
231
-     */
232
-    public static function postBoolean($key)
233
-    {
234
-        $get = &self::$globalStateProvider->getPostSuperGlobal();
235
-        if (!array_key_exists($key, $get)) {
236
-            return false;
237
-        }
238
-
239
-        // presence of parameter only
240
-        if ($get[$key] === "") {
241
-            return true;
242
-        }
243
-
244
-        if (in_array($get[$key], array(false, 'no', 'off', 0, 'false'), true)) {
245
-            return false;
246
-        }
247
-
248
-        return true;
249
-    }
250
-
251
-    #endregion
252
-
253
-    #region GET variables
254
-
255
-    /**
256
-     * @param string $key
257
-     *
258
-     * @return bool
259
-     */
260
-    public static function getBoolean($key)
261
-    {
262
-        $get = &self::$globalStateProvider->getGetSuperGlobal();
263
-        if (!array_key_exists($key, $get)) {
264
-            return false;
265
-        }
266
-
267
-        // presence of parameter only
268
-        if ($get[$key] === "") {
269
-            return true;
270
-        }
271
-
272
-        if (in_array($get[$key], array(false, 'no', 'off', 0, 'false'), true)) {
273
-            return false;
274
-        }
275
-
276
-        return true;
277
-    }
278
-
279
-    /**
280
-     * @param string $key
281
-     *
282
-     * @return int|null
283
-     */
284
-    public static function getInt($key)
285
-    {
286
-        $get = &self::$globalStateProvider->getGetSuperGlobal();
287
-        if (!array_key_exists($key, $get)) {
288
-            return null;
289
-        }
290
-
291
-        $filteredValue = filter_var($get[$key], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
292
-
293
-        if ($filteredValue === null) {
294
-            return null;
295
-        }
296
-
297
-        return (int)$filteredValue;
298
-    }
299
-
300
-    /**
301
-     * @param string $key
302
-     *
303
-     * @return null|string
304
-     */
305
-    public static function getString($key)
306
-    {
307
-        $get = &self::$globalStateProvider->getGetSuperGlobal();
308
-        if (!array_key_exists($key, $get)) {
309
-            return null;
310
-        }
311
-
312
-        if ($get[$key] === "") {
313
-            return null;
314
-        }
315
-
316
-        return (string)$get[$key];
317
-    }
318
-
319
-    #endregion
320
-
321
-    /**
322
-     * Sets the logged-in user to the specified user.
323
-     *
324
-     * @param User $user
325
-     */
326
-    public static function setLoggedInUser(User $user)
327
-    {
328
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
329
-
330
-        $session['userID'] = $user->getId();
331
-        unset($session['partialLogin']);
332
-    }
333
-
334
-    /**
335
-     * Sets the post-login redirect
336
-     */
337
-    public static function setPostLoginRedirect()
338
-    {
339
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
340
-        $session['returnTo'] = self::requestUri();
341
-    }
342
-
343
-    /**
344
-     * @return string|null
345
-     */
346
-    public static function requestUri()
347
-    {
348
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
349
-
350
-        if (isset($server['REQUEST_URI'])) {
351
-            return $server['REQUEST_URI'];
352
-        }
353
-
354
-        return null;
355
-    }
356
-
357
-    /**
358
-     * Clears the post-login redirect
359
-     * @return string
360
-     */
361
-    public static function clearPostLoginRedirect()
362
-    {
363
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
364
-        if (array_key_exists('returnTo', $session)) {
365
-            $path = $session['returnTo'];
366
-            unset($session['returnTo']);
367
-
368
-            return $path;
369
-        }
370
-
371
-        return null;
372
-    }
373
-
374
-    /**
375
-     * @return string|null
376
-     */
377
-    public static function serverName()
378
-    {
379
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
380
-
381
-        if (isset($server['SERVER_NAME'])) {
382
-            return $server['SERVER_NAME'];
383
-        }
384
-
385
-        return null;
386
-    }
387
-
388
-    /**
389
-     * You probably only want to deal with this through SessionAlert.
390
-     * @return void
391
-     */
392
-    public static function clearSessionAlertData()
393
-    {
394
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
395
-        if (array_key_exists('alerts', $session)) {
396
-            unset($session['alerts']);
397
-        }
398
-    }
399
-
400
-    /**
401
-     * You probably only want to deal with this through SessionAlert.
402
-     *
403
-     * @return string[]
404
-     */
405
-    public static function getSessionAlertData()
406
-    {
407
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
408
-        if (array_key_exists('alerts', $session)) {
409
-            return $session['alerts'];
410
-        }
411
-
412
-        return array();
413
-    }
414
-
415
-    /**
416
-     * You probably only want to deal with this through SessionAlert.
417
-     *
418
-     * @param string[] $data
419
-     */
420
-    public static function setSessionAlertData($data)
421
-    {
422
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
423
-        $session['alerts'] = $data;
424
-    }
425
-
426
-    /**
427
-     * You probably only want to deal with this through TokenManager.
428
-     *
429
-     * @return string[]
430
-     */
431
-    public static function getSessionTokenData()
432
-    {
433
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
434
-        if (array_key_exists('tokens', $session)) {
435
-            return $session['tokens'];
436
-        }
437
-
438
-        return array();
439
-    }
440
-
441
-    /**
442
-     * You probably only want to deal with this through TokenManager.
443
-     *
444
-     * @param string[] $data
445
-     */
446
-    public static function setSessionTokenData($data)
447
-    {
448
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
449
-        $session['tokens'] = $data;
450
-    }
451
-
452
-    /**
453
-     * @param string $key
454
-     *
455
-     * @return mixed
456
-     */
457
-    public static function getSessionContext($key)
458
-    {
459
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
460
-
461
-        if (!isset($session['context'])) {
462
-            $session['context'] = array();
463
-        }
464
-
465
-        if (!isset($session['context'][$key])) {
466
-            return null;
467
-        }
468
-
469
-        return $session['context'][$key];
470
-    }
471
-
472
-    /**
473
-     * @param string $key
474
-     * @param mixed  $data
475
-     */
476
-    public static function setSessionContext($key, $data)
477
-    {
478
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
479
-
480
-        if (!isset($session['context'])) {
481
-            $session['context'] = array();
482
-        }
483
-
484
-        $session['context'][$key] = $data;
485
-    }
486
-
487
-    /**
488
-     * @return int|null
489
-     */
490
-    public static function getSessionUserId()
491
-    {
492
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
493
-
494
-        return isset($session['userID']) ? (int)$session['userID'] : null;
495
-    }
496
-
497
-    /**
498
-     * @param User $user
499
-     */
500
-    public static function setOAuthPartialLogin(User $user)
501
-    {
502
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
503
-        $session['oauthPartialLogin'] = $user->getId();
504
-    }
505
-
506
-    /**
507
-     * @return int|null
508
-     */
509
-    public static function getOAuthPartialLogin()
510
-    {
511
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
512
-
513
-        return isset($session['oauthPartialLogin']) ? (int)$session['oauthPartialLogin'] : null;
514
-    }
515
-
516
-    public static function setAuthPartialLogin($userId, $stage)
517
-    {
518
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
519
-        $session['authPartialLoginId'] = $userId;
520
-        $session['authPartialLoginStage'] = $stage;
521
-    }
522
-
523
-    public static function getAuthPartialLogin()
524
-    {
525
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
526
-
527
-        $userId = isset($session['authPartialLoginId']) ? (int)$session['authPartialLoginId'] : null;
528
-        $stage = isset($session['authPartialLoginStage']) ? (int)$session['authPartialLoginStage'] : null;
529
-
530
-        return array($userId, $stage);
531
-    }
532
-
533
-    public static function clearAuthPartialLogin()
534
-    {
535
-        $session = &self::$globalStateProvider->getSessionSuperGlobal();
536
-        unset($session['authPartialLoginId']);
537
-        unset($session['authPartialLoginStage']);
538
-    }
539
-
540
-    /**
541
-     * @return null|string
542
-     */
543
-    public static function userAgent()
544
-    {
545
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
546
-
547
-        if (isset($server['HTTP_USER_AGENT'])) {
548
-            return $server['HTTP_USER_AGENT'];
549
-        }
550
-
551
-        return null;
552
-    }
553
-
554
-    /**
555
-     * @return null|string
556
-     */
557
-    public static function scriptName()
558
-    {
559
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
560
-
561
-        if (isset($server['SCRIPT_NAME'])) {
562
-            return $server['SCRIPT_NAME'];
563
-        }
564
-
565
-        return null;
566
-    }
567
-
568
-    /**
569
-     * @return null|string
570
-     */
571
-    public static function origin()
572
-    {
573
-        $server = &self::$globalStateProvider->getServerSuperGlobal();
574
-
575
-        if (isset($server['HTTP_ORIGIN'])) {
576
-            return $server['HTTP_ORIGIN'];
577
-        }
578
-
579
-        return null;
580
-    }
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 remote address of the web request
124
+	 * @return null|string
125
+	 */
126
+	public static function httpHost()
127
+	{
128
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
129
+
130
+		if (isset($server['HTTP_HOST'])) {
131
+			return $server['HTTP_HOST'];
132
+		}
133
+
134
+		return null;
135
+	}
136
+
137
+	/**
138
+	 * Gets the XFF header contents for the web request
139
+	 * @return null|string
140
+	 */
141
+	public static function forwardedAddress()
142
+	{
143
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
144
+
145
+		if (isset($server['HTTP_X_FORWARDED_FOR'])) {
146
+			return $server['HTTP_X_FORWARDED_FOR'];
147
+		}
148
+
149
+		return null;
150
+	}
151
+
152
+	/**
153
+	 * Sets the global state provider.
154
+	 *
155
+	 * Almost guaranteed this is not the method you want in production code.
156
+	 *
157
+	 * @param \Waca\Providers\GlobalState\IGlobalStateProvider $globalState
158
+	 */
159
+	public static function setGlobalStateProvider($globalState)
160
+	{
161
+		self::$globalStateProvider = $globalState;
162
+	}
163
+
164
+	#region POST variables
165
+
166
+	/**
167
+	 * @param string $key
168
+	 *
169
+	 * @return null|string
170
+	 */
171
+	public static function postString($key)
172
+	{
173
+		$post = &self::$globalStateProvider->getPostSuperGlobal();
174
+		if (!array_key_exists($key, $post)) {
175
+			return null;
176
+		}
177
+
178
+		if ($post[$key] === "") {
179
+			return null;
180
+		}
181
+
182
+		return (string)$post[$key];
183
+	}
184
+
185
+	/**
186
+	 * @param string $key
187
+	 *
188
+	 * @return null|string
189
+	 */
190
+	public static function postEmail($key)
191
+	{
192
+		$post = &self::$globalStateProvider->getPostSuperGlobal();
193
+		if (!array_key_exists($key, $post)) {
194
+			return null;
195
+		}
196
+
197
+		$filteredValue = filter_var($post[$key], FILTER_SANITIZE_EMAIL);
198
+
199
+		if ($filteredValue === false) {
200
+			return null;
201
+		}
202
+
203
+		return (string)$filteredValue;
204
+	}
205
+
206
+	/**
207
+	 * @param string $key
208
+	 *
209
+	 * @return int|null
210
+	 */
211
+	public static function postInt($key)
212
+	{
213
+		$post = &self::$globalStateProvider->getPostSuperGlobal();
214
+		if (!array_key_exists($key, $post)) {
215
+			return null;
216
+		}
217
+
218
+		$filteredValue = filter_var($post[$key], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
219
+
220
+		if ($filteredValue === null) {
221
+			return null;
222
+		}
223
+
224
+		return (int)$filteredValue;
225
+	}
226
+
227
+	/**
228
+	 * @param string $key
229
+	 *
230
+	 * @return bool
231
+	 */
232
+	public static function postBoolean($key)
233
+	{
234
+		$get = &self::$globalStateProvider->getPostSuperGlobal();
235
+		if (!array_key_exists($key, $get)) {
236
+			return false;
237
+		}
238
+
239
+		// presence of parameter only
240
+		if ($get[$key] === "") {
241
+			return true;
242
+		}
243
+
244
+		if (in_array($get[$key], array(false, 'no', 'off', 0, 'false'), true)) {
245
+			return false;
246
+		}
247
+
248
+		return true;
249
+	}
250
+
251
+	#endregion
252
+
253
+	#region GET variables
254
+
255
+	/**
256
+	 * @param string $key
257
+	 *
258
+	 * @return bool
259
+	 */
260
+	public static function getBoolean($key)
261
+	{
262
+		$get = &self::$globalStateProvider->getGetSuperGlobal();
263
+		if (!array_key_exists($key, $get)) {
264
+			return false;
265
+		}
266
+
267
+		// presence of parameter only
268
+		if ($get[$key] === "") {
269
+			return true;
270
+		}
271
+
272
+		if (in_array($get[$key], array(false, 'no', 'off', 0, 'false'), true)) {
273
+			return false;
274
+		}
275
+
276
+		return true;
277
+	}
278
+
279
+	/**
280
+	 * @param string $key
281
+	 *
282
+	 * @return int|null
283
+	 */
284
+	public static function getInt($key)
285
+	{
286
+		$get = &self::$globalStateProvider->getGetSuperGlobal();
287
+		if (!array_key_exists($key, $get)) {
288
+			return null;
289
+		}
290
+
291
+		$filteredValue = filter_var($get[$key], FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
292
+
293
+		if ($filteredValue === null) {
294
+			return null;
295
+		}
296
+
297
+		return (int)$filteredValue;
298
+	}
299
+
300
+	/**
301
+	 * @param string $key
302
+	 *
303
+	 * @return null|string
304
+	 */
305
+	public static function getString($key)
306
+	{
307
+		$get = &self::$globalStateProvider->getGetSuperGlobal();
308
+		if (!array_key_exists($key, $get)) {
309
+			return null;
310
+		}
311
+
312
+		if ($get[$key] === "") {
313
+			return null;
314
+		}
315
+
316
+		return (string)$get[$key];
317
+	}
318
+
319
+	#endregion
320
+
321
+	/**
322
+	 * Sets the logged-in user to the specified user.
323
+	 *
324
+	 * @param User $user
325
+	 */
326
+	public static function setLoggedInUser(User $user)
327
+	{
328
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
329
+
330
+		$session['userID'] = $user->getId();
331
+		unset($session['partialLogin']);
332
+	}
333
+
334
+	/**
335
+	 * Sets the post-login redirect
336
+	 */
337
+	public static function setPostLoginRedirect()
338
+	{
339
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
340
+		$session['returnTo'] = self::requestUri();
341
+	}
342
+
343
+	/**
344
+	 * @return string|null
345
+	 */
346
+	public static function requestUri()
347
+	{
348
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
349
+
350
+		if (isset($server['REQUEST_URI'])) {
351
+			return $server['REQUEST_URI'];
352
+		}
353
+
354
+		return null;
355
+	}
356
+
357
+	/**
358
+	 * Clears the post-login redirect
359
+	 * @return string
360
+	 */
361
+	public static function clearPostLoginRedirect()
362
+	{
363
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
364
+		if (array_key_exists('returnTo', $session)) {
365
+			$path = $session['returnTo'];
366
+			unset($session['returnTo']);
367
+
368
+			return $path;
369
+		}
370
+
371
+		return null;
372
+	}
373
+
374
+	/**
375
+	 * @return string|null
376
+	 */
377
+	public static function serverName()
378
+	{
379
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
380
+
381
+		if (isset($server['SERVER_NAME'])) {
382
+			return $server['SERVER_NAME'];
383
+		}
384
+
385
+		return null;
386
+	}
387
+
388
+	/**
389
+	 * You probably only want to deal with this through SessionAlert.
390
+	 * @return void
391
+	 */
392
+	public static function clearSessionAlertData()
393
+	{
394
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
395
+		if (array_key_exists('alerts', $session)) {
396
+			unset($session['alerts']);
397
+		}
398
+	}
399
+
400
+	/**
401
+	 * You probably only want to deal with this through SessionAlert.
402
+	 *
403
+	 * @return string[]
404
+	 */
405
+	public static function getSessionAlertData()
406
+	{
407
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
408
+		if (array_key_exists('alerts', $session)) {
409
+			return $session['alerts'];
410
+		}
411
+
412
+		return array();
413
+	}
414
+
415
+	/**
416
+	 * You probably only want to deal with this through SessionAlert.
417
+	 *
418
+	 * @param string[] $data
419
+	 */
420
+	public static function setSessionAlertData($data)
421
+	{
422
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
423
+		$session['alerts'] = $data;
424
+	}
425
+
426
+	/**
427
+	 * You probably only want to deal with this through TokenManager.
428
+	 *
429
+	 * @return string[]
430
+	 */
431
+	public static function getSessionTokenData()
432
+	{
433
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
434
+		if (array_key_exists('tokens', $session)) {
435
+			return $session['tokens'];
436
+		}
437
+
438
+		return array();
439
+	}
440
+
441
+	/**
442
+	 * You probably only want to deal with this through TokenManager.
443
+	 *
444
+	 * @param string[] $data
445
+	 */
446
+	public static function setSessionTokenData($data)
447
+	{
448
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
449
+		$session['tokens'] = $data;
450
+	}
451
+
452
+	/**
453
+	 * @param string $key
454
+	 *
455
+	 * @return mixed
456
+	 */
457
+	public static function getSessionContext($key)
458
+	{
459
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
460
+
461
+		if (!isset($session['context'])) {
462
+			$session['context'] = array();
463
+		}
464
+
465
+		if (!isset($session['context'][$key])) {
466
+			return null;
467
+		}
468
+
469
+		return $session['context'][$key];
470
+	}
471
+
472
+	/**
473
+	 * @param string $key
474
+	 * @param mixed  $data
475
+	 */
476
+	public static function setSessionContext($key, $data)
477
+	{
478
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
479
+
480
+		if (!isset($session['context'])) {
481
+			$session['context'] = array();
482
+		}
483
+
484
+		$session['context'][$key] = $data;
485
+	}
486
+
487
+	/**
488
+	 * @return int|null
489
+	 */
490
+	public static function getSessionUserId()
491
+	{
492
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
493
+
494
+		return isset($session['userID']) ? (int)$session['userID'] : null;
495
+	}
496
+
497
+	/**
498
+	 * @param User $user
499
+	 */
500
+	public static function setOAuthPartialLogin(User $user)
501
+	{
502
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
503
+		$session['oauthPartialLogin'] = $user->getId();
504
+	}
505
+
506
+	/**
507
+	 * @return int|null
508
+	 */
509
+	public static function getOAuthPartialLogin()
510
+	{
511
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
512
+
513
+		return isset($session['oauthPartialLogin']) ? (int)$session['oauthPartialLogin'] : null;
514
+	}
515
+
516
+	public static function setAuthPartialLogin($userId, $stage)
517
+	{
518
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
519
+		$session['authPartialLoginId'] = $userId;
520
+		$session['authPartialLoginStage'] = $stage;
521
+	}
522
+
523
+	public static function getAuthPartialLogin()
524
+	{
525
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
526
+
527
+		$userId = isset($session['authPartialLoginId']) ? (int)$session['authPartialLoginId'] : null;
528
+		$stage = isset($session['authPartialLoginStage']) ? (int)$session['authPartialLoginStage'] : null;
529
+
530
+		return array($userId, $stage);
531
+	}
532
+
533
+	public static function clearAuthPartialLogin()
534
+	{
535
+		$session = &self::$globalStateProvider->getSessionSuperGlobal();
536
+		unset($session['authPartialLoginId']);
537
+		unset($session['authPartialLoginStage']);
538
+	}
539
+
540
+	/**
541
+	 * @return null|string
542
+	 */
543
+	public static function userAgent()
544
+	{
545
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
546
+
547
+		if (isset($server['HTTP_USER_AGENT'])) {
548
+			return $server['HTTP_USER_AGENT'];
549
+		}
550
+
551
+		return null;
552
+	}
553
+
554
+	/**
555
+	 * @return null|string
556
+	 */
557
+	public static function scriptName()
558
+	{
559
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
560
+
561
+		if (isset($server['SCRIPT_NAME'])) {
562
+			return $server['SCRIPT_NAME'];
563
+		}
564
+
565
+		return null;
566
+	}
567
+
568
+	/**
569
+	 * @return null|string
570
+	 */
571
+	public static function origin()
572
+	{
573
+		$server = &self::$globalStateProvider->getServerSuperGlobal();
574
+
575
+		if (isset($server['HTTP_ORIGIN'])) {
576
+			return $server['HTTP_ORIGIN'];
577
+		}
578
+
579
+		return null;
580
+	}
581 581
 }
582 582
\ No newline at end of file
Please login to merge, or discard this patch.
config.inc.php 2 patches
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -200,24 +200,24 @@  discard block
 block discarded – undo
200 200
 
201 201
 // request states
202 202
 $availableRequestStates = array(
203
-    'Open'          => array(
204
-        'defertolog' => 'users', // don't change or you'll break old logs
205
-        'deferto'    => 'users',
206
-        'header'     => 'Open requests',
207
-        'api'        => "open",
208
-    ),
209
-    'Flagged users' => array(
210
-        'defertolog' => 'flagged users', // don't change or you'll break old logs
211
-        'deferto'    => 'flagged users',
212
-        'header'     => 'Flagged user needed',
213
-        'api'        => "admin",
214
-    ),
215
-    'Checkuser'     => array(
216
-        'defertolog' => 'checkusers', // don't change or you'll break old logs
217
-        'deferto'    => 'checkusers',
218
-        'header'     => 'Checkuser needed',
219
-        'api'        => "checkuser",
220
-    ),
203
+	'Open'          => array(
204
+		'defertolog' => 'users', // don't change or you'll break old logs
205
+		'deferto'    => 'users',
206
+		'header'     => 'Open requests',
207
+		'api'        => "open",
208
+	),
209
+	'Flagged users' => array(
210
+		'defertolog' => 'flagged users', // don't change or you'll break old logs
211
+		'deferto'    => 'flagged users',
212
+		'header'     => 'Flagged user needed',
213
+		'api'        => "admin",
214
+	),
215
+	'Checkuser'     => array(
216
+		'defertolog' => 'checkusers', // don't change or you'll break old logs
217
+		'deferto'    => 'checkusers',
218
+		'header'     => 'Checkuser needed',
219
+		'api'        => "checkuser",
220
+	),
221 221
 );
222 222
 
223 223
 $defaultRequestStateKey = 'Open';
@@ -264,21 +264,21 @@  discard block
 block discarded – undo
264 264
 require_once('config.local.inc.php');
265 265
 
266 266
 $cDatabaseConfig = array(
267
-    "acc"           => array(
268
-        "dsrcname" => "mysql:host=" . $toolserver_host . ";dbname=" . $toolserver_database,
269
-        "username" => $toolserver_username,
270
-        "password" => $toolserver_password,
271
-    ),
272
-    "wikipedia"     => array(
273
-        "dsrcname" => "mysql:host=" . $antispoof_host . ";dbname=" . $antispoof_db,
274
-        "username" => $toolserver_username,
275
-        "password" => $toolserver_password,
276
-    ),
277
-    "notifications" => array(
278
-        "dsrcname" => "mysql:host=" . $toolserver_notification_dbhost . ";dbname=" . $toolserver_notification_database,
279
-        "username" => $notifications_username,
280
-        "password" => $notifications_password,
281
-    ),
267
+	"acc"           => array(
268
+		"dsrcname" => "mysql:host=" . $toolserver_host . ";dbname=" . $toolserver_database,
269
+		"username" => $toolserver_username,
270
+		"password" => $toolserver_password,
271
+	),
272
+	"wikipedia"     => array(
273
+		"dsrcname" => "mysql:host=" . $antispoof_host . ";dbname=" . $antispoof_db,
274
+		"username" => $toolserver_username,
275
+		"password" => $toolserver_password,
276
+	),
277
+	"notifications" => array(
278
+		"dsrcname" => "mysql:host=" . $toolserver_notification_dbhost . ";dbname=" . $toolserver_notification_database,
279
+		"username" => $notifications_username,
280
+		"password" => $notifications_password,
281
+	),
282 282
 );
283 283
 
284 284
 // //Keep the included files from being executed.
@@ -290,18 +290,18 @@  discard block
 block discarded – undo
290 290
 ini_set('user_agent', $toolUserAgent);
291 291
 
292 292
 foreach (array(
293
-    "mbstring", // unicode and stuff
294
-    "pdo",
295
-    "pdo_mysql", // new database module
296
-    "session",
297
-    "date",
298
-    "pcre", // core stuff
299
-    "curl", // mediawiki api access etc
300
-    "openssl", // token generation
293
+	"mbstring", // unicode and stuff
294
+	"pdo",
295
+	"pdo_mysql", // new database module
296
+	"session",
297
+	"date",
298
+	"pcre", // core stuff
299
+	"curl", // mediawiki api access etc
300
+	"openssl", // token generation
301 301
 ) as $x) {
302
-    if (!extension_loaded($x)) {
303
-        die("extension $x is required.");
304
-    }
302
+	if (!extension_loaded($x)) {
303
+		die("extension $x is required.");
304
+	}
305 305
 }
306 306
 
307 307
 // Set up the AutoLoader
@@ -328,39 +328,39 @@  discard block
 block discarded – undo
328 328
 $siteConfiguration = new \Waca\SiteConfiguration();
329 329
 
330 330
 $siteConfiguration->setBaseUrl($baseurl)
331
-    ->setFilePath(__DIR__)
332
-    ->setDebuggingTraceEnabled($enableErrorTrace)
333
-    ->setForceIdentification($forceIdentification)
334
-    ->setIdentificationCacheExpiry($identificationCacheExpiry)
335
-    ->setMediawikiScriptPath($mediawikiScriptPath)
336
-    ->setMediawikiWebServiceEndpoint($mediawikiWebServiceEndpoint)
337
-    ->setMetaWikimediaWebServiceEndpoint($metaWikimediaWebServiceEndpoint)
338
-    ->setEnforceOAuth($enforceOAuth)
339
-    ->setEmailConfirmationEnabled($enableEmailConfirm == 1)
340
-    ->setEmailConfirmationExpiryDays($emailConfirmationExpiryDays)
341
-    ->setMiserModeLimit($requestLimitShowOnly)
342
-    ->setRequestStates($availableRequestStates)
343
-    ->setSquidList($squidIpList)
344
-    ->setDefaultCreatedTemplateId($createdid)
345
-    ->setDefaultRequestStateKey($defaultRequestStateKey)
346
-    ->setUseStrictTransportSecurity($strictTransportSecurityExpiry)
347
-    ->setUserAgent($toolUserAgent)
348
-    ->setCurlDisableVerifyPeer($curlDisableSSLVerifyPeer)
349
-    ->setUseOAuthSignup($useOauthSignup)
350
-    ->setOAuthBaseUrl($oauthBaseUrl)
351
-    ->setOAuthConsumerToken($oauthConsumerToken)
352
-    ->setOAuthConsumerSecret($oauthSecretToken)
353
-    ->setOauthMediaWikiCanonicalServer($oauthMediaWikiCanonicalServer)
354
-    ->setDataClearInterval($dataclear_interval)
355
-    ->setXffTrustedHostsFile($xff_trusted_hosts_file)
356
-    ->setIrcNotificationsEnabled($ircBotNotificationsEnabled == 1)
357
-    ->setIrcNotificationType($ircBotNotificationType)
358
-    ->setIrcNotificationsInstance($whichami)
359
-    ->setTitleBlacklistEnabled($enableTitleblacklist == 1)
360
-    ->setTorExitPaths(array_merge(gethostbynamel('en.wikipedia.org'), gethostbynamel('accounts.wmflabs.org')))
361
-    ->setCreationBotUsername($creationBotUsername)
362
-    ->setCreationBotPassword($creationBotPassword)
363
-    ->setCurlCookieJar($curlCookieJar)
364
-    ->setYubicoApiId($yubicoApiId)
365
-    ->setYubicoApiKey($yubicoApiKey)
366
-    ->setTotpEncryptionKey($totpEncryptionKey);
331
+	->setFilePath(__DIR__)
332
+	->setDebuggingTraceEnabled($enableErrorTrace)
333
+	->setForceIdentification($forceIdentification)
334
+	->setIdentificationCacheExpiry($identificationCacheExpiry)
335
+	->setMediawikiScriptPath($mediawikiScriptPath)
336
+	->setMediawikiWebServiceEndpoint($mediawikiWebServiceEndpoint)
337
+	->setMetaWikimediaWebServiceEndpoint($metaWikimediaWebServiceEndpoint)
338
+	->setEnforceOAuth($enforceOAuth)
339
+	->setEmailConfirmationEnabled($enableEmailConfirm == 1)
340
+	->setEmailConfirmationExpiryDays($emailConfirmationExpiryDays)
341
+	->setMiserModeLimit($requestLimitShowOnly)
342
+	->setRequestStates($availableRequestStates)
343
+	->setSquidList($squidIpList)
344
+	->setDefaultCreatedTemplateId($createdid)
345
+	->setDefaultRequestStateKey($defaultRequestStateKey)
346
+	->setUseStrictTransportSecurity($strictTransportSecurityExpiry)
347
+	->setUserAgent($toolUserAgent)
348
+	->setCurlDisableVerifyPeer($curlDisableSSLVerifyPeer)
349
+	->setUseOAuthSignup($useOauthSignup)
350
+	->setOAuthBaseUrl($oauthBaseUrl)
351
+	->setOAuthConsumerToken($oauthConsumerToken)
352
+	->setOAuthConsumerSecret($oauthSecretToken)
353
+	->setOauthMediaWikiCanonicalServer($oauthMediaWikiCanonicalServer)
354
+	->setDataClearInterval($dataclear_interval)
355
+	->setXffTrustedHostsFile($xff_trusted_hosts_file)
356
+	->setIrcNotificationsEnabled($ircBotNotificationsEnabled == 1)
357
+	->setIrcNotificationType($ircBotNotificationType)
358
+	->setIrcNotificationsInstance($whichami)
359
+	->setTitleBlacklistEnabled($enableTitleblacklist == 1)
360
+	->setTorExitPaths(array_merge(gethostbynamel('en.wikipedia.org'), gethostbynamel('accounts.wmflabs.org')))
361
+	->setCreationBotUsername($creationBotUsername)
362
+	->setCreationBotPassword($creationBotPassword)
363
+	->setCurlCookieJar($curlCookieJar)
364
+	->setYubicoApiId($yubicoApiId)
365
+	->setYubicoApiKey($yubicoApiKey)
366
+	->setTotpEncryptionKey($totpEncryptionKey);
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 
131 131
 $BUbasefile = "backup"; // The basefile's name.
132 132
 $BUdir = "/home/project/a/c/c/acc/backups"; // The directory where backups should be stored.
133
-$BUmonthdir = $BUdir . "/monthly"; // The directory where monthly backups should be stored.
133
+$BUmonthdir = $BUdir."/monthly"; // The directory where monthly backups should be stored.
134 134
 $BUdumper = "/opt/ts/mysql/5.1/bin/mysqldump --defaults-file=~/.my.cnf p_acc_live"; // Add parameters here if they are needed.
135 135
 $BUgzip = "/usr/bin/gzip"; // Add the gzip parameters here if needed.
136 136
 $BUtar = "/bin/tar -cvf"; // Add the tar parameters here if needed.
@@ -246,7 +246,7 @@  discard block
 block discarded – undo
246 246
 $curlDisableSSLVerifyPeer = false;
247 247
 
248 248
 // Change this to be outside the web directory.
249
-$curlCookieJar = __DIR__ . '/../cookies.txt';
249
+$curlCookieJar = __DIR__.'/../cookies.txt';
250 250
 
251 251
 $yubicoApiId = 0;
252 252
 $yubicoApiKey = "";
@@ -265,17 +265,17 @@  discard block
 block discarded – undo
265 265
 
266 266
 $cDatabaseConfig = array(
267 267
     "acc"           => array(
268
-        "dsrcname" => "mysql:host=" . $toolserver_host . ";dbname=" . $toolserver_database,
268
+        "dsrcname" => "mysql:host=".$toolserver_host.";dbname=".$toolserver_database,
269 269
         "username" => $toolserver_username,
270 270
         "password" => $toolserver_password,
271 271
     ),
272 272
     "wikipedia"     => array(
273
-        "dsrcname" => "mysql:host=" . $antispoof_host . ";dbname=" . $antispoof_db,
273
+        "dsrcname" => "mysql:host=".$antispoof_host.";dbname=".$antispoof_db,
274 274
         "username" => $toolserver_username,
275 275
         "password" => $toolserver_password,
276 276
     ),
277 277
     "notifications" => array(
278
-        "dsrcname" => "mysql:host=" . $toolserver_notification_dbhost . ";dbname=" . $toolserver_notification_database,
278
+        "dsrcname" => "mysql:host=".$toolserver_notification_dbhost.";dbname=".$toolserver_notification_database,
279 279
         "username" => $notifications_username,
280 280
         "password" => $notifications_password,
281 281
     ),
@@ -305,13 +305,13 @@  discard block
 block discarded – undo
305 305
 }
306 306
 
307 307
 // Set up the AutoLoader
308
-require_once(__DIR__ . "/includes/AutoLoader.php");
308
+require_once(__DIR__."/includes/AutoLoader.php");
309 309
 spl_autoload_register('Waca\\AutoLoader::load');
310
-require_once(__DIR__ . '/vendor/autoload.php');
310
+require_once(__DIR__.'/vendor/autoload.php');
311 311
 
312 312
 // Extra includes which are just plain awkward wherever they are.
313
-require_once(__DIR__ . '/lib/mediawiki-extensions-OAuth/lib/OAuth.php');
314
-require_once(__DIR__ . '/lib/mediawiki-extensions-OAuth/lib/JWT.php');
313
+require_once(__DIR__.'/lib/mediawiki-extensions-OAuth/lib/OAuth.php');
314
+require_once(__DIR__.'/lib/mediawiki-extensions-OAuth/lib/JWT.php');
315 315
 
316 316
 // Crap that's needed for libraries. >:(
317 317
 /**
Please login to merge, or discard this patch.
includes/Pages/UserAuth/MultiFactor/PageMultiFactor.php 3 patches
Braces   +4 added lines, -2 removed lines patch added patch discarded remove patch
@@ -229,7 +229,8 @@  discard block
 block discarded – undo
229 229
         $this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
230 230
     }
231 231
 
232
-    protected function enableU2F() {
232
+    protected function enableU2F()
233
+    {
233 234
         $database = $this->getDatabase();
234 235
         $currentUser = User::getCurrent($database);
235 236
 
@@ -336,7 +337,8 @@  discard block
 block discarded – undo
336 337
         }
337 338
     }
338 339
 
339
-    protected function disableU2F() {
340
+    protected function disableU2F()
341
+    {
340 342
         $database = $this->getDatabase();
341 343
         $currentUser = User::getCurrent($database);
342 344
 
Please login to merge, or discard this patch.
Indentation   +372 added lines, -372 removed lines patch added patch discarded remove patch
@@ -26,239 +26,239 @@  discard block
 block discarded – undo
26 26
 
27 27
 class PageMultiFactor extends InternalPageBase
28 28
 {
29
-    /**
30
-     * Main function for this page, when no specific actions are called.
31
-     * @return void
32
-     */
33
-    protected function main()
34
-    {
35
-        $database = $this->getDatabase();
36
-        $currentUser = User::getCurrent($database);
37
-
38
-        $yubikeyOtpCredentialProvider = new YubikeyOtpCredentialProvider($database, $this->getSiteConfiguration(),
39
-            $this->getHttpHelper());
40
-        $this->assign('yubikeyOtpIdentity', $yubikeyOtpCredentialProvider->getYubikeyData($currentUser->getId()));
41
-        $this->assign('yubikeyOtpEnrolled', $yubikeyOtpCredentialProvider->userIsEnrolled($currentUser->getId()));
42
-
43
-        $totpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
44
-        $this->assign('totpEnrolled', $totpCredentialProvider->userIsEnrolled($currentUser->getId()));
45
-
46
-        $u2fCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
47
-        $this->assign('u2fEnrolled', $u2fCredentialProvider->userIsEnrolled($currentUser->getId()));
48
-
49
-        $scratchCredentialProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
50
-        $this->assign('scratchEnrolled', $scratchCredentialProvider->userIsEnrolled($currentUser->getId()));
51
-        $this->assign('scratchRemaining', $scratchCredentialProvider->getRemaining($currentUser->getId()));
52
-
53
-        $this->setTemplate('mfa/mfa.tpl');
54
-    }
55
-
56
-    protected function enableYubikeyOtp()
57
-    {
58
-        $database = $this->getDatabase();
59
-        $currentUser = User::getCurrent($database);
60
-
61
-        $otpCredentialProvider = new YubikeyOtpCredentialProvider($database,
62
-            $this->getSiteConfiguration(), $this->getHttpHelper());
63
-
64
-        if (WebRequest::wasPosted()) {
65
-            $this->validateCSRFToken();
66
-
67
-            $passwordCredentialProvider = new PasswordCredentialProvider($database,
68
-                $this->getSiteConfiguration());
69
-
70
-            $password = WebRequest::postString('password');
71
-            $otp = WebRequest::postString('otp');
72
-
73
-            $result = $passwordCredentialProvider->authenticate($currentUser, $password);
74
-
75
-            if ($result) {
76
-                try {
77
-                    $otpCredentialProvider->setCredential($currentUser, 2, $otp);
78
-                    SessionAlert::success('Enabled YubiKey OTP.');
79
-
80
-                    $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
81
-                    if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
82
-                        $scratchProvider->setCredential($currentUser, 2, null);
83
-                        $tokens = $scratchProvider->getTokens();
84
-                        $this->assign('tokens', $tokens);
85
-                        $this->setTemplate('mfa/regenScratchTokens.tpl');
86
-                        return;
87
-                    }
88
-                }
89
-                catch (ApplicationLogicException $ex) {
90
-                    SessionAlert::error('Error enabling YubiKey OTP: ' . $ex->getMessage());
91
-                }
92
-
93
-                $this->redirect('multiFactor');
94
-            }
95
-            else {
96
-                SessionAlert::error('Error enabling YubiKey OTP - invalid credentials.');
97
-                $this->redirect('multiFactor');
98
-            }
99
-        }
100
-        else {
101
-            if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
102
-                // user is not enrolled, we shouldn't have got here.
103
-                throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
104
-            }
105
-
106
-            $this->assignCSRFToken();
107
-            $this->setTemplate('mfa/enableYubikey.tpl');
108
-        }
109
-    }
110
-
111
-    protected function disableYubikeyOtp()
112
-    {
113
-        $database = $this->getDatabase();
114
-        $currentUser = User::getCurrent($database);
115
-
116
-        $otpCredentialProvider = new YubikeyOtpCredentialProvider($database,
117
-            $this->getSiteConfiguration(), $this->getHttpHelper());
118
-
119
-        $factorType = 'YubiKey OTP';
120
-
121
-        $this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
122
-    }
123
-
124
-    protected function enableTotp()
125
-    {
126
-        $database = $this->getDatabase();
127
-        $currentUser = User::getCurrent($database);
128
-
129
-        $otpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
130
-
131
-        if (WebRequest::wasPosted()) {
132
-            $this->validateCSRFToken();
133
-
134
-            // used for routing only, not security
135
-            $stage = WebRequest::postString('stage');
136
-
137
-            if ($stage === "auth") {
138
-                $password = WebRequest::postString('password');
139
-
140
-                $passwordCredentialProvider = new PasswordCredentialProvider($database,
141
-                    $this->getSiteConfiguration());
142
-                $result = $passwordCredentialProvider->authenticate($currentUser, $password);
143
-
144
-                if ($result) {
145
-                    $otpCredentialProvider->setCredential($currentUser, 2, null);
146
-
147
-                    $provisioningUrl = $otpCredentialProvider->getProvisioningUrl($currentUser);
148
-
149
-                    $renderer = new Svg();
150
-                    $renderer->setHeight(256);
151
-                    $renderer->setWidth(256);
152
-                    $writer = new Writer($renderer);
153
-                    $svg = $writer->writeString($provisioningUrl);
154
-
155
-                    $this->assign('svg', $svg);
156
-                    $this->assign('secret', $otpCredentialProvider->getSecret($currentUser));
157
-
158
-                    $this->assignCSRFToken();
159
-                    $this->setTemplate('mfa/enableTotpEnroll.tpl');
160
-
161
-                    return;
162
-                }
163
-                else {
164
-                    SessionAlert::error('Error enabling TOTP - invalid credentials.');
165
-                    $this->redirect('multiFactor');
166
-
167
-                    return;
168
-                }
169
-            }
170
-
171
-            if ($stage === "enroll") {
172
-                // we *must* have a defined credential already here,
173
-                if ($otpCredentialProvider->isPartiallyEnrolled($currentUser)) {
174
-                    $otp = WebRequest::postString('otp');
175
-                    $result = $otpCredentialProvider->verifyEnable($currentUser, $otp);
176
-
177
-                    if ($result) {
178
-                        SessionAlert::success('Enabled TOTP.');
179
-
180
-                        $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
181
-                        if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
182
-                            $scratchProvider->setCredential($currentUser, 2, null);
183
-                            $tokens = $scratchProvider->getTokens();
184
-                            $this->assign('tokens', $tokens);
185
-                            $this->setTemplate('mfa/regenScratchTokens.tpl');
186
-                            return;
187
-                        }
188
-                    }
189
-                    else {
190
-                        $otpCredentialProvider->deleteCredential($currentUser);
191
-                        SessionAlert::error('Error enabling TOTP: invalid token provided');
192
-                    }
193
-
194
-
195
-                    $this->redirect('multiFactor');
196
-                    return;
197
-                }
198
-                else {
199
-                    SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
200
-                    $this->redirect('multiFactor');
29
+	/**
30
+	 * Main function for this page, when no specific actions are called.
31
+	 * @return void
32
+	 */
33
+	protected function main()
34
+	{
35
+		$database = $this->getDatabase();
36
+		$currentUser = User::getCurrent($database);
37
+
38
+		$yubikeyOtpCredentialProvider = new YubikeyOtpCredentialProvider($database, $this->getSiteConfiguration(),
39
+			$this->getHttpHelper());
40
+		$this->assign('yubikeyOtpIdentity', $yubikeyOtpCredentialProvider->getYubikeyData($currentUser->getId()));
41
+		$this->assign('yubikeyOtpEnrolled', $yubikeyOtpCredentialProvider->userIsEnrolled($currentUser->getId()));
42
+
43
+		$totpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
44
+		$this->assign('totpEnrolled', $totpCredentialProvider->userIsEnrolled($currentUser->getId()));
45
+
46
+		$u2fCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
47
+		$this->assign('u2fEnrolled', $u2fCredentialProvider->userIsEnrolled($currentUser->getId()));
48
+
49
+		$scratchCredentialProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
50
+		$this->assign('scratchEnrolled', $scratchCredentialProvider->userIsEnrolled($currentUser->getId()));
51
+		$this->assign('scratchRemaining', $scratchCredentialProvider->getRemaining($currentUser->getId()));
52
+
53
+		$this->setTemplate('mfa/mfa.tpl');
54
+	}
55
+
56
+	protected function enableYubikeyOtp()
57
+	{
58
+		$database = $this->getDatabase();
59
+		$currentUser = User::getCurrent($database);
60
+
61
+		$otpCredentialProvider = new YubikeyOtpCredentialProvider($database,
62
+			$this->getSiteConfiguration(), $this->getHttpHelper());
63
+
64
+		if (WebRequest::wasPosted()) {
65
+			$this->validateCSRFToken();
66
+
67
+			$passwordCredentialProvider = new PasswordCredentialProvider($database,
68
+				$this->getSiteConfiguration());
69
+
70
+			$password = WebRequest::postString('password');
71
+			$otp = WebRequest::postString('otp');
72
+
73
+			$result = $passwordCredentialProvider->authenticate($currentUser, $password);
74
+
75
+			if ($result) {
76
+				try {
77
+					$otpCredentialProvider->setCredential($currentUser, 2, $otp);
78
+					SessionAlert::success('Enabled YubiKey OTP.');
79
+
80
+					$scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
81
+					if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
82
+						$scratchProvider->setCredential($currentUser, 2, null);
83
+						$tokens = $scratchProvider->getTokens();
84
+						$this->assign('tokens', $tokens);
85
+						$this->setTemplate('mfa/regenScratchTokens.tpl');
86
+						return;
87
+					}
88
+				}
89
+				catch (ApplicationLogicException $ex) {
90
+					SessionAlert::error('Error enabling YubiKey OTP: ' . $ex->getMessage());
91
+				}
92
+
93
+				$this->redirect('multiFactor');
94
+			}
95
+			else {
96
+				SessionAlert::error('Error enabling YubiKey OTP - invalid credentials.');
97
+				$this->redirect('multiFactor');
98
+			}
99
+		}
100
+		else {
101
+			if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
102
+				// user is not enrolled, we shouldn't have got here.
103
+				throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
104
+			}
105
+
106
+			$this->assignCSRFToken();
107
+			$this->setTemplate('mfa/enableYubikey.tpl');
108
+		}
109
+	}
110
+
111
+	protected function disableYubikeyOtp()
112
+	{
113
+		$database = $this->getDatabase();
114
+		$currentUser = User::getCurrent($database);
201 115
 
202
-                    return;
203
-                }
204
-            }
116
+		$otpCredentialProvider = new YubikeyOtpCredentialProvider($database,
117
+			$this->getSiteConfiguration(), $this->getHttpHelper());
118
+
119
+		$factorType = 'YubiKey OTP';
120
+
121
+		$this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
122
+	}
205 123
 
206
-            // urgh, dunno what happened, but it's not something expected.
207
-            throw new ApplicationLogicException();
208
-        }
209
-        else {
210
-            if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
211
-                // user is not enrolled, we shouldn't have got here.
212
-                throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
213
-            }
124
+	protected function enableTotp()
125
+	{
126
+		$database = $this->getDatabase();
127
+		$currentUser = User::getCurrent($database);
128
+
129
+		$otpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
130
+
131
+		if (WebRequest::wasPosted()) {
132
+			$this->validateCSRFToken();
133
+
134
+			// used for routing only, not security
135
+			$stage = WebRequest::postString('stage');
136
+
137
+			if ($stage === "auth") {
138
+				$password = WebRequest::postString('password');
139
+
140
+				$passwordCredentialProvider = new PasswordCredentialProvider($database,
141
+					$this->getSiteConfiguration());
142
+				$result = $passwordCredentialProvider->authenticate($currentUser, $password);
143
+
144
+				if ($result) {
145
+					$otpCredentialProvider->setCredential($currentUser, 2, null);
146
+
147
+					$provisioningUrl = $otpCredentialProvider->getProvisioningUrl($currentUser);
148
+
149
+					$renderer = new Svg();
150
+					$renderer->setHeight(256);
151
+					$renderer->setWidth(256);
152
+					$writer = new Writer($renderer);
153
+					$svg = $writer->writeString($provisioningUrl);
154
+
155
+					$this->assign('svg', $svg);
156
+					$this->assign('secret', $otpCredentialProvider->getSecret($currentUser));
157
+
158
+					$this->assignCSRFToken();
159
+					$this->setTemplate('mfa/enableTotpEnroll.tpl');
160
+
161
+					return;
162
+				}
163
+				else {
164
+					SessionAlert::error('Error enabling TOTP - invalid credentials.');
165
+					$this->redirect('multiFactor');
166
+
167
+					return;
168
+				}
169
+			}
170
+
171
+			if ($stage === "enroll") {
172
+				// we *must* have a defined credential already here,
173
+				if ($otpCredentialProvider->isPartiallyEnrolled($currentUser)) {
174
+					$otp = WebRequest::postString('otp');
175
+					$result = $otpCredentialProvider->verifyEnable($currentUser, $otp);
176
+
177
+					if ($result) {
178
+						SessionAlert::success('Enabled TOTP.');
179
+
180
+						$scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
181
+						if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
182
+							$scratchProvider->setCredential($currentUser, 2, null);
183
+							$tokens = $scratchProvider->getTokens();
184
+							$this->assign('tokens', $tokens);
185
+							$this->setTemplate('mfa/regenScratchTokens.tpl');
186
+							return;
187
+						}
188
+					}
189
+					else {
190
+						$otpCredentialProvider->deleteCredential($currentUser);
191
+						SessionAlert::error('Error enabling TOTP: invalid token provided');
192
+					}
193
+
194
+
195
+					$this->redirect('multiFactor');
196
+					return;
197
+				}
198
+				else {
199
+					SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
200
+					$this->redirect('multiFactor');
201
+
202
+					return;
203
+				}
204
+			}
205
+
206
+			// urgh, dunno what happened, but it's not something expected.
207
+			throw new ApplicationLogicException();
208
+		}
209
+		else {
210
+			if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
211
+				// user is not enrolled, we shouldn't have got here.
212
+				throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
213
+			}
214
+
215
+			$this->assignCSRFToken();
216
+			$this->setTemplate('mfa/enableTotpAuth.tpl');
217
+		}
218
+	}
219
+
220
+	protected function disableTotp()
221
+	{
222
+		$database = $this->getDatabase();
223
+		$currentUser = User::getCurrent($database);
224
+
225
+		$otpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
226
+
227
+		$factorType = 'TOTP';
228
+
229
+		$this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
230
+	}
214 231
 
215
-            $this->assignCSRFToken();
216
-            $this->setTemplate('mfa/enableTotpAuth.tpl');
217
-        }
218
-    }
232
+	protected function enableU2F() {
233
+		$database = $this->getDatabase();
234
+		$currentUser = User::getCurrent($database);
219 235
 
220
-    protected function disableTotp()
221
-    {
222
-        $database = $this->getDatabase();
223
-        $currentUser = User::getCurrent($database);
236
+		$otpCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
224 237
 
225
-        $otpCredentialProvider = new TotpCredentialProvider($database, $this->getSiteConfiguration());
238
+		if (WebRequest::wasPosted()) {
239
+			$this->validateCSRFToken();
226 240
 
227
-        $factorType = 'TOTP';
241
+			// used for routing only, not security
242
+			$stage = WebRequest::postString('stage');
228 243
 
229
-        $this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
230
-    }
244
+			if ($stage === "auth") {
245
+				$password = WebRequest::postString('password');
231 246
 
232
-    protected function enableU2F() {
233
-        $database = $this->getDatabase();
234
-        $currentUser = User::getCurrent($database);
247
+				$passwordCredentialProvider = new PasswordCredentialProvider($database,
248
+					$this->getSiteConfiguration());
249
+				$result = $passwordCredentialProvider->authenticate($currentUser, $password);
235 250
 
236
-        $otpCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
237
-
238
-        if (WebRequest::wasPosted()) {
239
-            $this->validateCSRFToken();
240
-
241
-            // used for routing only, not security
242
-            $stage = WebRequest::postString('stage');
251
+				if ($result) {
252
+					$otpCredentialProvider->setCredential($currentUser, 2, null);
253
+					$this->assignCSRFToken();
243 254
 
244
-            if ($stage === "auth") {
245
-                $password = WebRequest::postString('password');
246
-
247
-                $passwordCredentialProvider = new PasswordCredentialProvider($database,
248
-                    $this->getSiteConfiguration());
249
-                $result = $passwordCredentialProvider->authenticate($currentUser, $password);
250
-
251
-                if ($result) {
252
-                    $otpCredentialProvider->setCredential($currentUser, 2, null);
253
-                    $this->assignCSRFToken();
254
-
255
-                    list($data, $reqs) = $otpCredentialProvider->getRegistrationData();
256
-
257
-                    $u2fRequest =json_encode($data);
258
-                    $u2fSigns = json_encode($reqs);
259
-
260
-                    $this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
261
-                    $this->setTailScript(<<<JS
255
+					list($data, $reqs) = $otpCredentialProvider->getRegistrationData();
256
+
257
+					$u2fRequest =json_encode($data);
258
+					$u2fSigns = json_encode($reqs);
259
+
260
+					$this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
261
+					$this->setTailScript(<<<JS
262 262
 var request = ${u2fRequest};
263 263
 var signs = ${u2fSigns};
264 264
 
@@ -277,153 +277,153 @@  discard block
 block discarded – undo
277 277
 	form.submit();
278 278
 });
279 279
 JS
280
-                    );
281
-
282
-                    $this->setTemplate('mfa/enableU2FEnroll.tpl');
283
-
284
-                    return;
285
-                }
286
-                else {
287
-                    SessionAlert::error('Error enabling TOTP - invalid credentials.');
288
-                    $this->redirect('multiFactor');
289
-
290
-                    return;
291
-                }
292
-            }
293
-
294
-            if ($stage === "enroll") {
295
-                // we *must* have a defined credential already here,
296
-                if ($otpCredentialProvider->isPartiallyEnrolled($currentUser)) {
297
-
298
-                    $request = json_decode(WebRequest::postString('u2fRequest'));
299
-                    $u2fData = json_decode(WebRequest::postString('u2fData'));
300
-
301
-                    $otpCredentialProvider->enable($currentUser, $request, $u2fData);
302
-
303
-                    SessionAlert::success('Enabled TOTP.');
304
-
305
-                    $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
306
-                    if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
307
-                        $scratchProvider->setCredential($currentUser, 2, null);
308
-                        $tokens = $scratchProvider->getTokens();
309
-                        $this->assign('tokens', $tokens);
310
-                        $this->setTemplate('mfa/regenScratchTokens.tpl');
311
-                        return;
312
-                    }
313
-
314
-                    $this->redirect('multiFactor');
315
-                    return;
316
-                }
317
-                else {
318
-                    SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
319
-                    $this->redirect('multiFactor');
320
-
321
-                    return;
322
-                }
323
-            }
324
-
325
-            // urgh, dunno what happened, but it's not something expected.
326
-            throw new ApplicationLogicException();
327
-        }
328
-        else {
329
-            if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
330
-                // user is not enrolled, we shouldn't have got here.
331
-                throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
332
-            }
333
-
334
-            $this->assignCSRFToken();
335
-            $this->setTemplate('mfa/enableU2FAuth.tpl');
336
-        }
337
-    }
338
-
339
-    protected function disableU2F() {
340
-        $database = $this->getDatabase();
341
-        $currentUser = User::getCurrent($database);
342
-
343
-        $otpCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
344
-
345
-        $factorType = 'U2F';
346
-
347
-        $this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
348
-    }
349
-
350
-    protected function scratch()
351
-    {
352
-        $database = $this->getDatabase();
353
-        $currentUser = User::getCurrent($database);
354
-
355
-        if (WebRequest::wasPosted()) {
356
-            $this->validateCSRFToken();
357
-
358
-            $passwordCredentialProvider = new PasswordCredentialProvider($database,
359
-                $this->getSiteConfiguration());
360
-
361
-            $otpCredentialProvider = new ScratchTokenCredentialProvider($database,
362
-                $this->getSiteConfiguration());
363
-
364
-            $password = WebRequest::postString('password');
365
-
366
-            $result = $passwordCredentialProvider->authenticate($currentUser, $password);
367
-
368
-            if ($result) {
369
-                $otpCredentialProvider->setCredential($currentUser, 2, null);
370
-                $tokens = $otpCredentialProvider->getTokens();
371
-                $this->assign('tokens', $tokens);
372
-                $this->setTemplate('mfa/regenScratchTokens.tpl');
373
-            }
374
-            else {
375
-                SessionAlert::error('Error refreshing scratch tokens - invalid credentials.');
376
-                $this->redirect('multiFactor');
377
-            }
378
-        }
379
-        else {
380
-            $this->assignCSRFToken();
381
-            $this->setTemplate('mfa/regenScratchAuth.tpl');
382
-        }
383
-    }
384
-
385
-    /**
386
-     * @param PdoDatabase         $database
387
-     * @param User                $currentUser
388
-     * @param ICredentialProvider $otpCredentialProvider
389
-     * @param string              $factorType
390
-     *
391
-     * @throws ApplicationLogicException
392
-     */
393
-    private function deleteCredential(
394
-        PdoDatabase $database,
395
-        User $currentUser,
396
-        ICredentialProvider $otpCredentialProvider,
397
-        $factorType
398
-    ) {
399
-        if (WebRequest::wasPosted()) {
400
-            $passwordCredentialProvider = new PasswordCredentialProvider($database,
401
-                $this->getSiteConfiguration());
402
-
403
-            $this->validateCSRFToken();
404
-
405
-            $password = WebRequest::postString('password');
406
-            $result = $passwordCredentialProvider->authenticate($currentUser, $password);
407
-
408
-            if ($result) {
409
-                $otpCredentialProvider->deleteCredential($currentUser);
410
-                SessionAlert::success('Disabled ' . $factorType . '.');
411
-                $this->redirect('multiFactor');
412
-            }
413
-            else {
414
-                SessionAlert::error('Error disabling ' . $factorType . ' - invalid credentials.');
415
-                $this->redirect('multiFactor');
416
-            }
417
-        }
418
-        else {
419
-            if (!$otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
420
-                // user is not enrolled, we shouldn't have got here.
421
-                throw new ApplicationLogicException('User is not enrolled in the selected MFA mechanism');
422
-            }
423
-
424
-            $this->assignCSRFToken();
425
-            $this->assign('otpType', $factorType);
426
-            $this->setTemplate('mfa/disableOtp.tpl');
427
-        }
428
-    }
280
+					);
281
+
282
+					$this->setTemplate('mfa/enableU2FEnroll.tpl');
283
+
284
+					return;
285
+				}
286
+				else {
287
+					SessionAlert::error('Error enabling TOTP - invalid credentials.');
288
+					$this->redirect('multiFactor');
289
+
290
+					return;
291
+				}
292
+			}
293
+
294
+			if ($stage === "enroll") {
295
+				// we *must* have a defined credential already here,
296
+				if ($otpCredentialProvider->isPartiallyEnrolled($currentUser)) {
297
+
298
+					$request = json_decode(WebRequest::postString('u2fRequest'));
299
+					$u2fData = json_decode(WebRequest::postString('u2fData'));
300
+
301
+					$otpCredentialProvider->enable($currentUser, $request, $u2fData);
302
+
303
+					SessionAlert::success('Enabled TOTP.');
304
+
305
+					$scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
306
+					if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
307
+						$scratchProvider->setCredential($currentUser, 2, null);
308
+						$tokens = $scratchProvider->getTokens();
309
+						$this->assign('tokens', $tokens);
310
+						$this->setTemplate('mfa/regenScratchTokens.tpl');
311
+						return;
312
+					}
313
+
314
+					$this->redirect('multiFactor');
315
+					return;
316
+				}
317
+				else {
318
+					SessionAlert::error('Error enabling TOTP - no enrollment found or enrollment expired.');
319
+					$this->redirect('multiFactor');
320
+
321
+					return;
322
+				}
323
+			}
324
+
325
+			// urgh, dunno what happened, but it's not something expected.
326
+			throw new ApplicationLogicException();
327
+		}
328
+		else {
329
+			if ($otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
330
+				// user is not enrolled, we shouldn't have got here.
331
+				throw new ApplicationLogicException('User is already enrolled in the selected MFA mechanism');
332
+			}
333
+
334
+			$this->assignCSRFToken();
335
+			$this->setTemplate('mfa/enableU2FAuth.tpl');
336
+		}
337
+	}
338
+
339
+	protected function disableU2F() {
340
+		$database = $this->getDatabase();
341
+		$currentUser = User::getCurrent($database);
342
+
343
+		$otpCredentialProvider = new U2FCredentialProvider($database, $this->getSiteConfiguration());
344
+
345
+		$factorType = 'U2F';
346
+
347
+		$this->deleteCredential($database, $currentUser, $otpCredentialProvider, $factorType);
348
+	}
349
+
350
+	protected function scratch()
351
+	{
352
+		$database = $this->getDatabase();
353
+		$currentUser = User::getCurrent($database);
354
+
355
+		if (WebRequest::wasPosted()) {
356
+			$this->validateCSRFToken();
357
+
358
+			$passwordCredentialProvider = new PasswordCredentialProvider($database,
359
+				$this->getSiteConfiguration());
360
+
361
+			$otpCredentialProvider = new ScratchTokenCredentialProvider($database,
362
+				$this->getSiteConfiguration());
363
+
364
+			$password = WebRequest::postString('password');
365
+
366
+			$result = $passwordCredentialProvider->authenticate($currentUser, $password);
367
+
368
+			if ($result) {
369
+				$otpCredentialProvider->setCredential($currentUser, 2, null);
370
+				$tokens = $otpCredentialProvider->getTokens();
371
+				$this->assign('tokens', $tokens);
372
+				$this->setTemplate('mfa/regenScratchTokens.tpl');
373
+			}
374
+			else {
375
+				SessionAlert::error('Error refreshing scratch tokens - invalid credentials.');
376
+				$this->redirect('multiFactor');
377
+			}
378
+		}
379
+		else {
380
+			$this->assignCSRFToken();
381
+			$this->setTemplate('mfa/regenScratchAuth.tpl');
382
+		}
383
+	}
384
+
385
+	/**
386
+	 * @param PdoDatabase         $database
387
+	 * @param User                $currentUser
388
+	 * @param ICredentialProvider $otpCredentialProvider
389
+	 * @param string              $factorType
390
+	 *
391
+	 * @throws ApplicationLogicException
392
+	 */
393
+	private function deleteCredential(
394
+		PdoDatabase $database,
395
+		User $currentUser,
396
+		ICredentialProvider $otpCredentialProvider,
397
+		$factorType
398
+	) {
399
+		if (WebRequest::wasPosted()) {
400
+			$passwordCredentialProvider = new PasswordCredentialProvider($database,
401
+				$this->getSiteConfiguration());
402
+
403
+			$this->validateCSRFToken();
404
+
405
+			$password = WebRequest::postString('password');
406
+			$result = $passwordCredentialProvider->authenticate($currentUser, $password);
407
+
408
+			if ($result) {
409
+				$otpCredentialProvider->deleteCredential($currentUser);
410
+				SessionAlert::success('Disabled ' . $factorType . '.');
411
+				$this->redirect('multiFactor');
412
+			}
413
+			else {
414
+				SessionAlert::error('Error disabling ' . $factorType . ' - invalid credentials.');
415
+				$this->redirect('multiFactor');
416
+			}
417
+		}
418
+		else {
419
+			if (!$otpCredentialProvider->userIsEnrolled($currentUser->getId())) {
420
+				// user is not enrolled, we shouldn't have got here.
421
+				throw new ApplicationLogicException('User is not enrolled in the selected MFA mechanism');
422
+			}
423
+
424
+			$this->assignCSRFToken();
425
+			$this->assign('otpType', $factorType);
426
+			$this->setTemplate('mfa/disableOtp.tpl');
427
+		}
428
+	}
429 429
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -78,7 +78,7 @@  discard block
 block discarded – undo
78 78
                     SessionAlert::success('Enabled YubiKey OTP.');
79 79
 
80 80
                     $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
81
-                    if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
81
+                    if ($scratchProvider->getRemaining($currentUser->getId()) < 3) {
82 82
                         $scratchProvider->setCredential($currentUser, 2, null);
83 83
                         $tokens = $scratchProvider->getTokens();
84 84
                         $this->assign('tokens', $tokens);
@@ -87,7 +87,7 @@  discard block
 block discarded – undo
87 87
                     }
88 88
                 }
89 89
                 catch (ApplicationLogicException $ex) {
90
-                    SessionAlert::error('Error enabling YubiKey OTP: ' . $ex->getMessage());
90
+                    SessionAlert::error('Error enabling YubiKey OTP: '.$ex->getMessage());
91 91
                 }
92 92
 
93 93
                 $this->redirect('multiFactor');
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
                         SessionAlert::success('Enabled TOTP.');
179 179
 
180 180
                         $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
181
-                        if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
181
+                        if ($scratchProvider->getRemaining($currentUser->getId()) < 3) {
182 182
                             $scratchProvider->setCredential($currentUser, 2, null);
183 183
                             $tokens = $scratchProvider->getTokens();
184 184
                             $this->assign('tokens', $tokens);
@@ -254,7 +254,7 @@  discard block
 block discarded – undo
254 254
 
255 255
                     list($data, $reqs) = $otpCredentialProvider->getRegistrationData();
256 256
 
257
-                    $u2fRequest =json_encode($data);
257
+                    $u2fRequest = json_encode($data);
258 258
                     $u2fSigns = json_encode($reqs);
259 259
 
260 260
                     $this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
@@ -303,7 +303,7 @@  discard block
 block discarded – undo
303 303
                     SessionAlert::success('Enabled TOTP.');
304 304
 
305 305
                     $scratchProvider = new ScratchTokenCredentialProvider($database, $this->getSiteConfiguration());
306
-                    if($scratchProvider->getRemaining($currentUser->getId()) < 3) {
306
+                    if ($scratchProvider->getRemaining($currentUser->getId()) < 3) {
307 307
                         $scratchProvider->setCredential($currentUser, 2, null);
308 308
                         $tokens = $scratchProvider->getTokens();
309 309
                         $this->assign('tokens', $tokens);
@@ -407,11 +407,11 @@  discard block
 block discarded – undo
407 407
 
408 408
             if ($result) {
409 409
                 $otpCredentialProvider->deleteCredential($currentUser);
410
-                SessionAlert::success('Disabled ' . $factorType . '.');
410
+                SessionAlert::success('Disabled '.$factorType.'.');
411 411
                 $this->redirect('multiFactor');
412 412
             }
413 413
             else {
414
-                SessionAlert::error('Error disabling ' . $factorType . ' - invalid credentials.');
414
+                SessionAlert::error('Error disabling '.$factorType.' - invalid credentials.');
415 415
                 $this->redirect('multiFactor');
416 416
             }
417 417
         }
Please login to merge, or discard this patch.
includes/Pages/UserAuth/PageOAuthCallback.php 1 patch
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -17,90 +17,90 @@
 block discarded – undo
17 17
 
18 18
 class PageOAuthCallback extends InternalPageBase
19 19
 {
20
-    /**
21
-     * @return bool
22
-     */
23
-    protected function isProtectedPage()
24
-    {
25
-        // This page is critical to ensuring OAuth functionality is operational.
26
-        return false;
27
-    }
20
+	/**
21
+	 * @return bool
22
+	 */
23
+	protected function isProtectedPage()
24
+	{
25
+		// This page is critical to ensuring OAuth functionality is operational.
26
+		return false;
27
+	}
28 28
 
29
-    /**
30
-     * Main function for this page, when no specific actions are called.
31
-     * @return void
32
-     */
33
-    protected function main()
34
-    {
35
-        // This should never get hit except by URL manipulation.
36
-        $this->redirect('');
37
-    }
29
+	/**
30
+	 * Main function for this page, when no specific actions are called.
31
+	 * @return void
32
+	 */
33
+	protected function main()
34
+	{
35
+		// This should never get hit except by URL manipulation.
36
+		$this->redirect('');
37
+	}
38 38
 
39
-    /**
40
-     * Registered endpoint for the account creation callback.
41
-     *
42
-     * If this ever gets hit, something is wrong somewhere.
43
-     */
44
-    protected function create()
45
-    {
46
-        throw new Exception('OAuth account creation endpoint triggered.');
47
-    }
39
+	/**
40
+	 * Registered endpoint for the account creation callback.
41
+	 *
42
+	 * If this ever gets hit, something is wrong somewhere.
43
+	 */
44
+	protected function create()
45
+	{
46
+		throw new Exception('OAuth account creation endpoint triggered.');
47
+	}
48 48
 
49
-    /**
50
-     * Callback entry point
51
-     */
52
-    protected function authorise()
53
-    {
54
-        $oauthToken = WebRequest::getString('oauth_token');
55
-        $oauthVerifier = WebRequest::getString('oauth_verifier');
49
+	/**
50
+	 * Callback entry point
51
+	 */
52
+	protected function authorise()
53
+	{
54
+		$oauthToken = WebRequest::getString('oauth_token');
55
+		$oauthVerifier = WebRequest::getString('oauth_verifier');
56 56
 
57
-        $this->doCallbackValidation($oauthToken, $oauthVerifier);
57
+		$this->doCallbackValidation($oauthToken, $oauthVerifier);
58 58
 
59
-        $database = $this->getDatabase();
59
+		$database = $this->getDatabase();
60 60
 
61
-        $user = OAuthUserHelper::findUserByRequestToken($oauthToken, $database);
62
-        $oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
61
+		$user = OAuthUserHelper::findUserByRequestToken($oauthToken, $database);
62
+		$oauth = new OAuthUserHelper($user, $database, $this->getOAuthProtocolHelper(), $this->getSiteConfiguration());
63 63
 
64
-        try {
65
-            $oauth->completeHandshake($oauthVerifier);
66
-        }
67
-        catch (CurlException $ex) {
68
-            throw new ApplicationLogicException($ex->getMessage(), 0, $ex);
69
-        }
64
+		try {
65
+			$oauth->completeHandshake($oauthVerifier);
66
+		}
67
+		catch (CurlException $ex) {
68
+			throw new ApplicationLogicException($ex->getMessage(), 0, $ex);
69
+		}
70 70
 
71
-        // OK, we're the same session that just did a partial login that was redirected to OAuth. Let's upgrade the
72
-        // login to a full login
73
-        if (WebRequest::getOAuthPartialLogin() === $user->getId()) {
74
-            WebRequest::setLoggedInUser($user);
75
-        }
71
+		// OK, we're the same session that just did a partial login that was redirected to OAuth. Let's upgrade the
72
+		// login to a full login
73
+		if (WebRequest::getOAuthPartialLogin() === $user->getId()) {
74
+			WebRequest::setLoggedInUser($user);
75
+		}
76 76
 
77
-        // My thinking is there are three cases here:
78
-        //   a) new user => redirect to prefs - it's the only thing they can access other than stats
79
-        //   b) existing user hit the connect button in prefs => redirect to prefs since it's where they were
80
-        //   c) existing user logging in => redirect to wherever they came from
81
-        $redirectDestination = WebRequest::clearPostLoginRedirect();
82
-        if ($redirectDestination !== null && !$user->isNewUser()) {
83
-            $this->redirectUrl($redirectDestination);
84
-        }
85
-        else {
86
-            $this->redirect('preferences', null, null, 'internal.php');
87
-        }
88
-    }
77
+		// My thinking is there are three cases here:
78
+		//   a) new user => redirect to prefs - it's the only thing they can access other than stats
79
+		//   b) existing user hit the connect button in prefs => redirect to prefs since it's where they were
80
+		//   c) existing user logging in => redirect to wherever they came from
81
+		$redirectDestination = WebRequest::clearPostLoginRedirect();
82
+		if ($redirectDestination !== null && !$user->isNewUser()) {
83
+			$this->redirectUrl($redirectDestination);
84
+		}
85
+		else {
86
+			$this->redirect('preferences', null, null, 'internal.php');
87
+		}
88
+	}
89 89
 
90
-    /**
91
-     * @param string $oauthToken
92
-     * @param string $oauthVerifier
93
-     *
94
-     * @throws ApplicationLogicException
95
-     */
96
-    private function doCallbackValidation($oauthToken, $oauthVerifier)
97
-    {
98
-        if ($oauthToken === null) {
99
-            throw new ApplicationLogicException('No token provided');
100
-        }
90
+	/**
91
+	 * @param string $oauthToken
92
+	 * @param string $oauthVerifier
93
+	 *
94
+	 * @throws ApplicationLogicException
95
+	 */
96
+	private function doCallbackValidation($oauthToken, $oauthVerifier)
97
+	{
98
+		if ($oauthToken === null) {
99
+			throw new ApplicationLogicException('No token provided');
100
+		}
101 101
 
102
-        if ($oauthVerifier === null) {
103
-            throw new ApplicationLogicException('No oauth verifier provided.');
104
-        }
105
-    }
102
+		if ($oauthVerifier === null) {
103
+			throw new ApplicationLogicException('No oauth verifier provided.');
104
+		}
105
+	}
106 106
 }
107 107
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/UserAuth/Login/PagePasswordLogin.php 2 patches
Indentation   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -13,31 +13,31 @@
 block discarded – undo
13 13
 
14 14
 class PagePasswordLogin extends LoginCredentialPageBase
15 15
 {
16
-    protected function providerSpecificSetup()
17
-    {
18
-        list($partialId, $partialStage) = WebRequest::getAuthPartialLogin();
19
-
20
-        if($partialId !== null && $partialStage > 1) {
21
-            $sql = 'SELECT type FROM credential WHERE user = :user AND factor = :stage AND disabled = 0 ORDER BY priority';
22
-            $statement = $this->getDatabase()->prepare($sql);
23
-            $statement->execute(array(':user' => $partialId, ':stage' => $partialStage));
24
-            $nextStage = $statement->fetchColumn();
25
-            $statement->closeCursor();
26
-
27
-            $this->redirect("login/" . $this->nextPageMap[$nextStage]);
28
-            return;
29
-        }
30
-
31
-        $this->setTemplate('login/password.tpl');
32
-    }
33
-
34
-    protected function getProviderCredentials()
35
-    {
36
-        $password = WebRequest::postString("password");
37
-        if ($password === null || $password === "") {
38
-            throw new ApplicationLogicException("No password specified");
39
-        }
40
-
41
-        return $password;
42
-    }
16
+	protected function providerSpecificSetup()
17
+	{
18
+		list($partialId, $partialStage) = WebRequest::getAuthPartialLogin();
19
+
20
+		if($partialId !== null && $partialStage > 1) {
21
+			$sql = 'SELECT type FROM credential WHERE user = :user AND factor = :stage AND disabled = 0 ORDER BY priority';
22
+			$statement = $this->getDatabase()->prepare($sql);
23
+			$statement->execute(array(':user' => $partialId, ':stage' => $partialStage));
24
+			$nextStage = $statement->fetchColumn();
25
+			$statement->closeCursor();
26
+
27
+			$this->redirect("login/" . $this->nextPageMap[$nextStage]);
28
+			return;
29
+		}
30
+
31
+		$this->setTemplate('login/password.tpl');
32
+	}
33
+
34
+	protected function getProviderCredentials()
35
+	{
36
+		$password = WebRequest::postString("password");
37
+		if ($password === null || $password === "") {
38
+			throw new ApplicationLogicException("No password specified");
39
+		}
40
+
41
+		return $password;
42
+	}
43 43
 }
44 44
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -17,14 +17,14 @@
 block discarded – undo
17 17
     {
18 18
         list($partialId, $partialStage) = WebRequest::getAuthPartialLogin();
19 19
 
20
-        if($partialId !== null && $partialStage > 1) {
20
+        if ($partialId !== null && $partialStage > 1) {
21 21
             $sql = 'SELECT type FROM credential WHERE user = :user AND factor = :stage AND disabled = 0 ORDER BY priority';
22 22
             $statement = $this->getDatabase()->prepare($sql);
23 23
             $statement->execute(array(':user' => $partialId, ':stage' => $partialStage));
24 24
             $nextStage = $statement->fetchColumn();
25 25
             $statement->closeCursor();
26 26
 
27
-            $this->redirect("login/" . $this->nextPageMap[$nextStage]);
27
+            $this->redirect("login/".$this->nextPageMap[$nextStage]);
28 28
             return;
29 29
         }
30 30
 
Please login to merge, or discard this patch.
includes/Pages/UserAuth/Login/PageU2FLogin.php 1 patch
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -14,20 +14,20 @@  discard block
 block discarded – undo
14 14
 
15 15
 class PageU2FLogin extends LoginCredentialPageBase
16 16
 {
17
-    protected function providerSpecificSetup()
18
-    {
19
-        $this->assign('showSignIn', false);
20
-        $this->setTemplate('login/u2f.tpl');
17
+	protected function providerSpecificSetup()
18
+	{
19
+		$this->assign('showSignIn', false);
20
+		$this->setTemplate('login/u2f.tpl');
21 21
 
22
-        if ($this->partialUser === null) {
23
-            throw new ApplicationLogicException("U2F cannot be first-stage authentication");
24
-        }
22
+		if ($this->partialUser === null) {
23
+			throw new ApplicationLogicException("U2F cannot be first-stage authentication");
24
+		}
25 25
 
26
-        $u2f = new U2FCredentialProvider($this->getDatabase(), $this->getSiteConfiguration());
27
-        $authData = json_encode($u2f->getAuthenticationData($this->partialUser));
26
+		$u2f = new U2FCredentialProvider($this->getDatabase(), $this->getSiteConfiguration());
27
+		$authData = json_encode($u2f->getAuthenticationData($this->partialUser));
28 28
 
29
-        $this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
30
-        $this->setTailScript(<<<JS
29
+		$this->addJs('/vendor/yubico/u2flib-server/examples/assets/u2f-api.js');
30
+		$this->setTailScript(<<<JS
31 31
 var request = ${authData};
32 32
 console.log("starting sign");
33 33
 u2f.sign(request, function(data) {
@@ -44,19 +44,19 @@  discard block
 block discarded – undo
44 44
                 form.submit();
45 45
             });
46 46
 JS
47
-        );
47
+		);
48 48
 
49
-    }
49
+	}
50 50
 
51
-    protected function getProviderCredentials()
52
-    {
53
-        $authenticate = WebRequest::postString("authenticate");
54
-        $request = WebRequest::postString("request");
51
+	protected function getProviderCredentials()
52
+	{
53
+		$authenticate = WebRequest::postString("authenticate");
54
+		$request = WebRequest::postString("request");
55 55
 
56
-        if ($authenticate === null || $authenticate === "" || $request === null || $request === "") {
57
-              throw new ApplicationLogicException("No authentication specified");
58
-        }
56
+		if ($authenticate === null || $authenticate === "" || $request === null || $request === "") {
57
+			  throw new ApplicationLogicException("No authentication specified");
58
+		}
59 59
 
60
-        return array(json_decode($authenticate), json_decode($request), 'u2f');
61
-    }
60
+		return array(json_decode($authenticate), json_decode($request), 'u2f');
61
+	}
62 62
 }
63 63
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Pages/UserAuth/Login/PageOtpLogin.php 1 patch
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -13,18 +13,18 @@
 block discarded – undo
13 13
 
14 14
 class PageOtpLogin extends LoginCredentialPageBase
15 15
 {
16
-    protected function providerSpecificSetup()
17
-    {
18
-        $this->setTemplate('login/otp.tpl');
19
-    }
16
+	protected function providerSpecificSetup()
17
+	{
18
+		$this->setTemplate('login/otp.tpl');
19
+	}
20 20
 
21
-    protected function getProviderCredentials()
22
-    {
23
-        $otp = WebRequest::postString("otp");
24
-        if ($otp === null || $otp === "") {
25
-            throw new ApplicationLogicException("No one-time code specified");
26
-        }
21
+	protected function getProviderCredentials()
22
+	{
23
+		$otp = WebRequest::postString("otp");
24
+		if ($otp === null || $otp === "") {
25
+			throw new ApplicationLogicException("No one-time code specified");
26
+		}
27 27
 
28
-        return $otp;
29
-    }
28
+		return $otp;
29
+	}
30 30
 }
31 31
\ No newline at end of file
Please login to merge, or discard this patch.