Failed Conditions
Push — newinternal ( 216d62...410e59 )
by Simon
05:28 queued 13s
created
includes/ConsoleTasks/ClearOldDataTask.php 1 patch
Indentation   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -13,25 +13,25 @@
 block discarded – undo
13 13
 
14 14
 class ClearOldDataTask extends ConsoleTaskBase
15 15
 {
16
-    public function execute()
17
-    {
18
-        $dataClearInterval = $this->getSiteConfiguration()->getDataClearInterval();
16
+	public function execute()
17
+	{
18
+		$dataClearInterval = $this->getSiteConfiguration()->getDataClearInterval();
19 19
 
20
-        $query = $this->getDatabase()->prepare(<<<SQL
20
+		$query = $this->getDatabase()->prepare(<<<SQL
21 21
 UPDATE request
22 22
 SET ip = :ip, forwardedip = null, email = :mail, useragent = ''
23 23
 WHERE date < DATE_SUB(curdate(), INTERVAL {$dataClearInterval})
24 24
 AND status = 'Closed';
25 25
 SQL
26
-        );
26
+		);
27 27
 
28
-        $success = $query->execute(array(
29
-            ":ip"   => $this->getSiteConfiguration()->getDataClearIp(),
30
-            ":mail" => $this->getSiteConfiguration()->getDataClearEmail(),
31
-        ));
28
+		$success = $query->execute(array(
29
+			":ip"   => $this->getSiteConfiguration()->getDataClearIp(),
30
+			":mail" => $this->getSiteConfiguration()->getDataClearEmail(),
31
+		));
32 32
 
33
-        if (!$success) {
34
-            throw new Exception("Error in transaction: Could not clear data.");
35
-        }
36
-    }
33
+		if (!$success) {
34
+			throw new Exception("Error in transaction: Could not clear data.");
35
+		}
36
+	}
37 37
 }
38 38
\ No newline at end of file
Please login to merge, or discard this patch.
includes/API/Actions/StatsAction.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -20,58 +20,58 @@
 block discarded – undo
20 20
  */
21 21
 class StatsAction extends ApiPageBase implements IApiAction
22 22
 {
23
-    /**
24
-     * The target user
25
-     * @var User $user
26
-     */
27
-    private $user;
23
+	/**
24
+	 * The target user
25
+	 * @var User $user
26
+	 */
27
+	private $user;
28 28
 
29
-    /**
30
-     * Summary of execute
31
-     *
32
-     * @param \DOMElement $apiDocument
33
-     *
34
-     * @return \DOMElement
35
-     * @throws ApiException
36
-     * @throws \Exception
37
-     */
38
-    public function executeApiAction(\DOMElement $apiDocument)
39
-    {
40
-        $username = WebRequest::getString('user');
41
-        $wikiusername = WebRequest::getString('wikiuser');
29
+	/**
30
+	 * Summary of execute
31
+	 *
32
+	 * @param \DOMElement $apiDocument
33
+	 *
34
+	 * @return \DOMElement
35
+	 * @throws ApiException
36
+	 * @throws \Exception
37
+	 */
38
+	public function executeApiAction(\DOMElement $apiDocument)
39
+	{
40
+		$username = WebRequest::getString('user');
41
+		$wikiusername = WebRequest::getString('wikiuser');
42 42
 
43
-        if ($username === null && $wikiusername === null) {
44
-            throw new ApiException("Please specify a username using either user or wikiuser parameters.");
45
-        }
43
+		if ($username === null && $wikiusername === null) {
44
+			throw new ApiException("Please specify a username using either user or wikiuser parameters.");
45
+		}
46 46
 
47
-        $userElement = $this->document->createElement("user");
48
-        $apiDocument->appendChild($userElement);
47
+		$userElement = $this->document->createElement("user");
48
+		$apiDocument->appendChild($userElement);
49 49
 
50
-        if ($username !== null) {
51
-            $user = User::getByUsername($username, $this->getDatabase());
52
-        }
53
-        else {
54
-            $user = User::getByOnWikiUsername($wikiusername, $this->getDatabase());
55
-        }
50
+		if ($username !== null) {
51
+			$user = User::getByUsername($username, $this->getDatabase());
52
+		}
53
+		else {
54
+			$user = User::getByOnWikiUsername($wikiusername, $this->getDatabase());
55
+		}
56 56
 
57
-        if ($user === false) {
58
-            $userElement->setAttribute("missing", "true");
57
+		if ($user === false) {
58
+			$userElement->setAttribute("missing", "true");
59 59
 
60
-            return $apiDocument;
61
-        }
60
+			return $apiDocument;
61
+		}
62 62
 
63
-        $this->user = $user;
63
+		$this->user = $user;
64 64
 
65
-        $oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(),
66
-            $this->getSiteConfiguration());
65
+		$oauth = new OAuthUserHelper($user, $this->getDatabase(), $this->getOAuthProtocolHelper(),
66
+			$this->getSiteConfiguration());
67 67
 
68
-        $userElement->setAttribute("username", $this->user->getUsername());
69
-        $userElement->setAttribute("status", $this->user->getStatus());
70
-        $userElement->setAttribute("lastactive", $this->user->getLastActive());
71
-        $userElement->setAttribute("welcome_template", $this->user->getWelcomeTemplate());
72
-        $userElement->setAttribute("onwikiname", $this->user->getOnWikiName());
73
-        $userElement->setAttribute("oauth", $oauth->isFullyLinked() ? "true" : "false");
68
+		$userElement->setAttribute("username", $this->user->getUsername());
69
+		$userElement->setAttribute("status", $this->user->getStatus());
70
+		$userElement->setAttribute("lastactive", $this->user->getLastActive());
71
+		$userElement->setAttribute("welcome_template", $this->user->getWelcomeTemplate());
72
+		$userElement->setAttribute("onwikiname", $this->user->getOnWikiName());
73
+		$userElement->setAttribute("oauth", $oauth->isFullyLinked() ? "true" : "false");
74 74
 
75
-        return $apiDocument;
76
-    }
75
+		return $apiDocument;
76
+	}
77 77
 }
Please login to merge, or discard this patch.
includes/Helpers/BotMediaWikiClient.php 3 patches
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -16,136 +16,136 @@
 block discarded – undo
16 16
 
17 17
 class BotMediaWikiClient implements IMediaWikiClient
18 18
 {
19
-    /**
20
-     * @var HttpHelper
21
-     */
22
-    private $httpHelper;
23
-    /** @var string */
24
-    private $mediawikiWebServiceEndpoint;
25
-    /** @var string */
26
-    private $creationBotUsername;
27
-    /** @var string */
28
-    private $creationBotPassword;
29
-    /** @var bool */
30
-    private $knownLoggedIn = false;
31
-
32
-    /**
33
-     * BotMediaWikiClient constructor.
34
-     *
35
-     * @param SiteConfiguration $siteConfiguration
36
-     */
37
-    public function __construct(SiteConfiguration $siteConfiguration)
38
-    {
39
-        $this->mediawikiWebServiceEndpoint = $siteConfiguration->getMediawikiWebServiceEndpoint();
40
-
41
-        $this->creationBotUsername = $siteConfiguration->getCreationBotUsername();
42
-        $this->creationBotPassword = $siteConfiguration->getCreationBotPassword();
43
-
44
-        $this->httpHelper = new HttpHelper(
45
-            $siteConfiguration->getUserAgent(),
46
-            $siteConfiguration->getCurlDisableVerifyPeer(),
47
-            $siteConfiguration->getCurlCookieJar()
48
-        );
49
-    }
50
-
51
-    function doApiCall($apiParams, $method = 'GET')
52
-    {
53
-        $this->ensureLoggedIn();
54
-        $apiParams['assert'] = 'user';
55
-
56
-        return $this->callApi($apiParams, $method);
57
-    }
58
-
59
-    private function ensureLoggedIn()
60
-    {
61
-        if ($this->knownLoggedIn) {
62
-            return;
63
-        }
64
-
65
-        $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
66
-        if (isset($userinfoResult->query->userinfo->anon)) {
67
-            // not logged in.
68
-            $this->logIn();
69
-
70
-            // retest
71
-            $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
72
-            if (isset($userinfoResult->query->userinfo->anon)) {
73
-                throw new MediaWikiApiException('Unable to log in.');
74
-            }
75
-            else {
76
-                $this->knownLoggedIn = true;
77
-            }
78
-        }
79
-        else {
80
-            $this->knownLoggedIn = true;
81
-        }
82
-    }
83
-
84
-    /**
85
-     * @param $apiParams
86
-     * @param $method
87
-     *
88
-     * @return mixed
89
-     * @throws ApplicationLogicException
90
-     * @throws CurlException
91
-     */
92
-    private function callApi($apiParams, $method)
93
-    {
94
-        $apiParams['format'] = 'json';
95
-
96
-        if ($method == 'GET') {
97
-            $data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
98
-        }
99
-        elseif ($method == 'POST') {
100
-            $data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
101
-        }
102
-        else {
103
-            throw new ApplicationLogicException('Unsupported HTTP Method');
104
-        }
105
-
106
-        if ($data === false) {
107
-            throw new CurlException('Curl error: ' . $this->httpHelper->getError());
108
-        }
109
-
110
-        $result = json_decode($data);
111
-
112
-        return $result;
113
-    }
114
-
115
-    private function logIn()
116
-    {
117
-        // get token
118
-        $tokenParams = array(
119
-            'action' => 'query',
120
-            'meta'   => 'tokens',
121
-            'type'   => 'login',
122
-        );
123
-
124
-        $response = $this->callApi($tokenParams, 'POST');
125
-
126
-        if (isset($response->error)) {
127
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
128
-        }
129
-
130
-        $token = $response->query->tokens->logintoken;
131
-
132
-        if ($token === null) {
133
-            throw new MediaWikiApiException('Edit token could not be acquired');
134
-        }
135
-
136
-        $params = array(
137
-            'action' => 'login',
138
-            'lgname' => $this->creationBotUsername,
139
-            'lgpassword' => $this->creationBotPassword,
140
-            'lgtoken' => $token,
141
-        );
142
-
143
-        $loginResponse = $this->callApi($params, 'POST');
144
-
145
-        if($loginResponse->login->result == 'Success'){
146
-            return;
147
-        }
148
-
149
-        throw new ApplicationLogicException(json_encode($loginResponse));
150
-    }
19
+	/**
20
+	 * @var HttpHelper
21
+	 */
22
+	private $httpHelper;
23
+	/** @var string */
24
+	private $mediawikiWebServiceEndpoint;
25
+	/** @var string */
26
+	private $creationBotUsername;
27
+	/** @var string */
28
+	private $creationBotPassword;
29
+	/** @var bool */
30
+	private $knownLoggedIn = false;
31
+
32
+	/**
33
+	 * BotMediaWikiClient constructor.
34
+	 *
35
+	 * @param SiteConfiguration $siteConfiguration
36
+	 */
37
+	public function __construct(SiteConfiguration $siteConfiguration)
38
+	{
39
+		$this->mediawikiWebServiceEndpoint = $siteConfiguration->getMediawikiWebServiceEndpoint();
40
+
41
+		$this->creationBotUsername = $siteConfiguration->getCreationBotUsername();
42
+		$this->creationBotPassword = $siteConfiguration->getCreationBotPassword();
43
+
44
+		$this->httpHelper = new HttpHelper(
45
+			$siteConfiguration->getUserAgent(),
46
+			$siteConfiguration->getCurlDisableVerifyPeer(),
47
+			$siteConfiguration->getCurlCookieJar()
48
+		);
49
+	}
50
+
51
+	function doApiCall($apiParams, $method = 'GET')
52
+	{
53
+		$this->ensureLoggedIn();
54
+		$apiParams['assert'] = 'user';
55
+
56
+		return $this->callApi($apiParams, $method);
57
+	}
58
+
59
+	private function ensureLoggedIn()
60
+	{
61
+		if ($this->knownLoggedIn) {
62
+			return;
63
+		}
64
+
65
+		$userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
66
+		if (isset($userinfoResult->query->userinfo->anon)) {
67
+			// not logged in.
68
+			$this->logIn();
69
+
70
+			// retest
71
+			$userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
72
+			if (isset($userinfoResult->query->userinfo->anon)) {
73
+				throw new MediaWikiApiException('Unable to log in.');
74
+			}
75
+			else {
76
+				$this->knownLoggedIn = true;
77
+			}
78
+		}
79
+		else {
80
+			$this->knownLoggedIn = true;
81
+		}
82
+	}
83
+
84
+	/**
85
+	 * @param $apiParams
86
+	 * @param $method
87
+	 *
88
+	 * @return mixed
89
+	 * @throws ApplicationLogicException
90
+	 * @throws CurlException
91
+	 */
92
+	private function callApi($apiParams, $method)
93
+	{
94
+		$apiParams['format'] = 'json';
95
+
96
+		if ($method == 'GET') {
97
+			$data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
98
+		}
99
+		elseif ($method == 'POST') {
100
+			$data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
101
+		}
102
+		else {
103
+			throw new ApplicationLogicException('Unsupported HTTP Method');
104
+		}
105
+
106
+		if ($data === false) {
107
+			throw new CurlException('Curl error: ' . $this->httpHelper->getError());
108
+		}
109
+
110
+		$result = json_decode($data);
111
+
112
+		return $result;
113
+	}
114
+
115
+	private function logIn()
116
+	{
117
+		// get token
118
+		$tokenParams = array(
119
+			'action' => 'query',
120
+			'meta'   => 'tokens',
121
+			'type'   => 'login',
122
+		);
123
+
124
+		$response = $this->callApi($tokenParams, 'POST');
125
+
126
+		if (isset($response->error)) {
127
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
128
+		}
129
+
130
+		$token = $response->query->tokens->logintoken;
131
+
132
+		if ($token === null) {
133
+			throw new MediaWikiApiException('Edit token could not be acquired');
134
+		}
135
+
136
+		$params = array(
137
+			'action' => 'login',
138
+			'lgname' => $this->creationBotUsername,
139
+			'lgpassword' => $this->creationBotPassword,
140
+			'lgtoken' => $token,
141
+		);
142
+
143
+		$loginResponse = $this->callApi($params, 'POST');
144
+
145
+		if($loginResponse->login->result == 'Success'){
146
+			return;
147
+		}
148
+
149
+		throw new ApplicationLogicException(json_encode($loginResponse));
150
+	}
151 151
 }
152 152
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
         }
105 105
 
106 106
         if ($data === false) {
107
-            throw new CurlException('Curl error: ' . $this->httpHelper->getError());
107
+            throw new CurlException('Curl error: '.$this->httpHelper->getError());
108 108
         }
109 109
 
110 110
         $result = json_decode($data);
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
         $response = $this->callApi($tokenParams, 'POST');
125 125
 
126 126
         if (isset($response->error)) {
127
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
127
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
128 128
         }
129 129
 
130 130
         $token = $response->query->tokens->logintoken;
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 
143 143
         $loginResponse = $this->callApi($params, 'POST');
144 144
 
145
-        if($loginResponse->login->result == 'Success'){
145
+        if ($loginResponse->login->result == 'Success') {
146 146
             return;
147 147
         }
148 148
 
Please login to merge, or discard this patch.
Braces   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -142,7 +142,7 @@
 block discarded – undo
142 142
 
143 143
         $loginResponse = $this->callApi($params, 'POST');
144 144
 
145
-        if($loginResponse->login->result == 'Success'){
145
+        if($loginResponse->login->result == 'Success') {
146 146
             return;
147 147
         }
148 148
 
Please login to merge, or discard this patch.
includes/Helpers/OAuthUserHelper.php 1 patch
Indentation   +403 added lines, -403 removed lines patch added patch discarded remove patch
@@ -22,411 +22,411 @@
 block discarded – undo
22 22
 
23 23
 class OAuthUserHelper implements IMediaWikiClient
24 24
 {
25
-    const TOKEN_REQUEST = 'request';
26
-    const TOKEN_ACCESS = 'access';
27
-    /** @var PDOStatement */
28
-    private static $tokenCountStatement = null;
29
-    /** @var PDOStatement */
30
-    private $getTokenStatement;
31
-    /**
32
-     * @var User
33
-     */
34
-    private $user;
35
-    /**
36
-     * @var PdoDatabase
37
-     */
38
-    private $database;
39
-    /**
40
-     * @var IOAuthProtocolHelper
41
-     */
42
-    private $oauthProtocolHelper;
43
-    /**
44
-     * @var bool|null Is the user linked to OAuth
45
-     */
46
-    private $linked;
47
-    private $partiallyLinked;
48
-    /** @var OAuthToken */
49
-    private $accessToken;
50
-    /** @var bool */
51
-    private $accessTokenLoaded = false;
52
-    /**
53
-     * @var OAuthIdentity
54
-     */
55
-    private $identity = null;
56
-    /**
57
-     * @var bool
58
-     */
59
-    private $identityLoaded = false;
60
-    /**
61
-     * @var SiteConfiguration
62
-     */
63
-    private $siteConfiguration;
64
-
65
-    #region Static methods
66
-    public static function findUserByRequestToken($requestToken, PdoDatabase $database)
67
-    {
68
-        $statement = $database->prepare(<<<'SQL'
25
+	const TOKEN_REQUEST = 'request';
26
+	const TOKEN_ACCESS = 'access';
27
+	/** @var PDOStatement */
28
+	private static $tokenCountStatement = null;
29
+	/** @var PDOStatement */
30
+	private $getTokenStatement;
31
+	/**
32
+	 * @var User
33
+	 */
34
+	private $user;
35
+	/**
36
+	 * @var PdoDatabase
37
+	 */
38
+	private $database;
39
+	/**
40
+	 * @var IOAuthProtocolHelper
41
+	 */
42
+	private $oauthProtocolHelper;
43
+	/**
44
+	 * @var bool|null Is the user linked to OAuth
45
+	 */
46
+	private $linked;
47
+	private $partiallyLinked;
48
+	/** @var OAuthToken */
49
+	private $accessToken;
50
+	/** @var bool */
51
+	private $accessTokenLoaded = false;
52
+	/**
53
+	 * @var OAuthIdentity
54
+	 */
55
+	private $identity = null;
56
+	/**
57
+	 * @var bool
58
+	 */
59
+	private $identityLoaded = false;
60
+	/**
61
+	 * @var SiteConfiguration
62
+	 */
63
+	private $siteConfiguration;
64
+
65
+	#region Static methods
66
+	public static function findUserByRequestToken($requestToken, PdoDatabase $database)
67
+	{
68
+		$statement = $database->prepare(<<<'SQL'
69 69
             SELECT u.* FROM user u 
70 70
             INNER JOIN oauthtoken t ON t.user = u.id 
71 71
             WHERE t.type = :type AND t.token = :token
72 72
 SQL
73
-        );
74
-        $statement->execute(array(':type' => self::TOKEN_REQUEST, ':token' => $requestToken));
75
-
76
-        /** @var User $user */
77
-        $user = $statement->fetchObject(User::class);
78
-        $statement->closeCursor();
79
-
80
-        if ($user === false) {
81
-            throw new ApplicationLogicException('Token not found in store, please try again');
82
-        }
83
-
84
-        $user->setDatabase($database);
85
-
86
-        return $user;
87
-    }
88
-
89
-    public static function userIsFullyLinked(User $user, PdoDatabase $database = null)
90
-    {
91
-        if (self::$tokenCountStatement === null && $database === null) {
92
-            throw new ApplicationLogicException('Static link request without initialised statement');
93
-        }
94
-
95
-        return self::runTokenCount($user->getId(), $database, self::TOKEN_ACCESS);
96
-    }
97
-
98
-    public static function userIsPartiallyLinked(User $user, PdoDatabase $database = null)
99
-    {
100
-        if (self::$tokenCountStatement === null && $database === null) {
101
-            throw new ApplicationLogicException('Static link request without initialised statement');
102
-        }
103
-
104
-        if (self::userIsFullyLinked($user, $database)) {
105
-            return false;
106
-        }
107
-
108
-        return self::runTokenCount($user->getId(), $database, self::TOKEN_REQUEST)
109
-            || $user->getOnWikiName() == null;
110
-    }
111
-
112
-    /**
113
-     * @param PdoDatabase $database
114
-     */
115
-    public static function prepareTokenCountStatement(PdoDatabase $database)
116
-    {
117
-        if (self::$tokenCountStatement === null) {
118
-            self::$tokenCountStatement = $database->prepare('SELECT COUNT(*) FROM oauthtoken WHERE user = :user AND type = :type');
119
-        }
120
-    }
121
-
122
-    private static function runTokenCount($userId, $database, $tokenType)
123
-    {
124
-        if (self::$tokenCountStatement === null) {
125
-            self::prepareTokenCountStatement($database);
126
-        }
127
-
128
-        self::$tokenCountStatement->execute(array(
129
-            ':user' => $userId,
130
-            ':type' => $tokenType,
131
-        ));
132
-
133
-        $tokenCount = self::$tokenCountStatement->fetchColumn();
134
-        $linked = $tokenCount > 0;
135
-        self::$tokenCountStatement->closeCursor();
136
-
137
-        return $linked;
138
-    }
139
-
140
-    #endregion Static methods
141
-
142
-    /**
143
-     * OAuthUserHelper constructor.
144
-     *
145
-     * @param User                 $user
146
-     * @param PdoDatabase          $database
147
-     * @param IOAuthProtocolHelper $oauthProtocolHelper
148
-     * @param SiteConfiguration    $siteConfiguration
149
-     */
150
-    public function __construct(
151
-        User $user,
152
-        PdoDatabase $database,
153
-        IOAuthProtocolHelper $oauthProtocolHelper,
154
-        SiteConfiguration $siteConfiguration
155
-    ) {
156
-        $this->user = $user;
157
-        $this->database = $database;
158
-        $this->oauthProtocolHelper = $oauthProtocolHelper;
159
-
160
-        $this->linked = null;
161
-        $this->partiallyLinked = null;
162
-        $this->siteConfiguration = $siteConfiguration;
163
-
164
-        self::prepareTokenCountStatement($database);
165
-        $this->getTokenStatement = $this->database->prepare('SELECT * FROM oauthtoken WHERE user = :user AND type = :type');
166
-    }
167
-
168
-    /**
169
-     * Determines if the user is fully connected to OAuth.
170
-     *
171
-     * @return bool
172
-     */
173
-    public function isFullyLinked()
174
-    {
175
-        if ($this->linked === null) {
176
-            $this->linked = self::userIsFullyLinked($this->user, $this->database);
177
-        }
178
-
179
-        return $this->linked;
180
-    }
181
-
182
-    /**
183
-     * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
184
-     * procedure before configuring.
185
-     * @return bool
186
-     */
187
-    public function isPartiallyLinked()
188
-    {
189
-        if ($this->partiallyLinked === null) {
190
-            $this->partiallyLinked = self::userIsPartiallyLinked($this->user, $this->database);
191
-        }
192
-
193
-        return $this->partiallyLinked;
194
-    }
195
-
196
-    /**
197
-     * @throws OAuthException
198
-     */
199
-    public function refreshIdentity()
200
-    {
201
-        $this->loadIdentity();
202
-
203
-        if ($this->identity === null) {
204
-            $this->identity = new OAuthIdentity();
205
-            $this->identity->setUserId($this->user->getId());
206
-            $this->identity->setDatabase($this->database);
207
-        }
208
-
209
-        $token = $this->loadAccessToken();
210
-
211
-        $rawTicket = $this->oauthProtocolHelper->getIdentityTicket($token->getToken(), $token->getSecret());
212
-
213
-        $this->identity->populate($rawTicket);
214
-
215
-        if (!$this->identityIsValid()) {
216
-            throw new OAuthException('Identity ticket is not valid!');
217
-        }
218
-
219
-        $this->identity->save();
220
-
221
-        $this->user->setOnWikiName($this->identity->getUsername());
222
-        $this->user->save();
223
-    }
224
-
225
-    public function getRequestToken()
226
-    {
227
-        $token = $this->oauthProtocolHelper->getRequestToken();
228
-
229
-        $this->partiallyLinked = true;
230
-        $this->linked = false;
231
-
232
-        $this->database
233
-            ->prepare('DELETE FROM oauthtoken WHERE user = :user AND type = :type')
234
-            ->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
235
-
236
-        $this->database
237
-            ->prepare('INSERT INTO oauthtoken (user, type, token, secret, expiry) VALUES (:user, :type, :token, :secret, DATE_ADD(NOW(), INTERVAL 1 DAY))')
238
-            ->execute(array(
239
-                ':user'   => $this->user->getId(),
240
-                ':type'   => self::TOKEN_REQUEST,
241
-                ':token'  => $token->key,
242
-                ':secret' => $token->secret,
243
-            ));
244
-
245
-        return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
246
-    }
247
-
248
-    public function completeHandshake($verificationToken)
249
-    {
250
-        $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
251
-
252
-        /** @var OAuthToken $token */
253
-        $token = $this->getTokenStatement->fetchObject(OAuthToken::class);
254
-        $this->getTokenStatement->closeCursor();
255
-
256
-        if ($token === false) {
257
-            throw new ApplicationLogicException('Cannot find request token');
258
-        }
259
-
260
-        $token->setDatabase($this->database);
261
-
262
-        $accessToken = $this->oauthProtocolHelper->callbackCompleted($token->getToken(), $token->getSecret(),
263
-            $verificationToken);
264
-
265
-        $clearStatement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :u AND type = :t');
266
-        $clearStatement->execute(array(':u' => $this->user->getId(), ':t' => self::TOKEN_ACCESS));
267
-
268
-        $token->setToken($accessToken->key);
269
-        $token->setSecret($accessToken->secret);
270
-        $token->setType(self::TOKEN_ACCESS);
271
-        $token->setExpiry(null);
272
-        $token->save();
273
-
274
-        $this->partiallyLinked = false;
275
-        $this->linked = true;
276
-
277
-        $this->refreshIdentity();
278
-    }
279
-
280
-    public function detach()
281
-    {
282
-        $this->loadIdentity();
283
-
284
-        $this->identity->delete();
285
-        $statement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :user');
286
-        $statement->execute(array(':user' => $this->user->getId()));
287
-
288
-        $this->identity = null;
289
-        $this->linked = false;
290
-        $this->partiallyLinked = false;
291
-    }
292
-
293
-    /**
294
-     * @param bool $expiredOk
295
-     *
296
-     * @return OAuthIdentity
297
-     * @throws OAuthException
298
-     */
299
-    public function getIdentity($expiredOk = false)
300
-    {
301
-        $this->loadIdentity();
302
-
303
-        if (!$this->identityIsValid($expiredOk)) {
304
-            throw new OAuthException('Stored identity is not valid.');
305
-        }
306
-
307
-        return $this->identity;
308
-    }
309
-
310
-    public function doApiCall($params, $method)
311
-    {
312
-        // Ensure we're logged in
313
-        $params['assert'] = 'user';
314
-
315
-        $token = $this->loadAccessToken();
316
-        return $this->oauthProtocolHelper->apiCall($params, $token->getToken(), $token->getSecret(), $method);
317
-    }
318
-
319
-    /**
320
-     * @param bool $expiredOk
321
-     *
322
-     * @return bool
323
-     */
324
-    private function identityIsValid($expiredOk = false)
325
-    {
326
-        $this->loadIdentity();
327
-
328
-        if ($this->identity === null) {
329
-            return false;
330
-        }
331
-
332
-        if ($this->identity->getIssuedAtTime() === false
333
-            || $this->identity->getExpirationTime() === false
334
-            || $this->identity->getAudience() === false
335
-            || $this->identity->getIssuer() === false
336
-        ) {
337
-            // this isn't populated properly.
338
-            return false;
339
-        }
340
-
341
-        $issue = DateTimeImmutable::createFromFormat("U", $this->identity->getIssuedAtTime());
342
-        $now = new DateTimeImmutable();
343
-
344
-        if ($issue > $now) {
345
-            // wat.
346
-            return false;
347
-        }
348
-
349
-        if ($this->identityExpired() && !$expiredOk) {
350
-            // soz.
351
-            return false;
352
-        }
353
-
354
-        if ($this->identity->getAudience() !== $this->siteConfiguration->getOAuthConsumerToken()) {
355
-            // token not issued for us
356
-            return false;
357
-        }
358
-
359
-        if ($this->identity->getIssuer() !== $this->siteConfiguration->getOauthMediaWikiCanonicalServer()) {
360
-            // token not issued by the right person
361
-            return false;
362
-        }
363
-
364
-        // can't find a reason to not trust it
365
-        return true;
366
-    }
367
-
368
-    /**
369
-     * @return bool
370
-     */
371
-    public function identityExpired()
372
-    {
373
-        // allowed max age
374
-        $gracePeriod = $this->siteConfiguration->getOauthIdentityGraceTime();
375
-
376
-        $expiry = DateTimeImmutable::createFromFormat("U", $this->identity->getExpirationTime());
377
-        $graceExpiry = $expiry->modify($gracePeriod);
378
-        $now = new DateTimeImmutable();
379
-
380
-        return $graceExpiry < $now;
381
-    }
382
-
383
-    /**
384
-     * Loads the OAuth identity from the database for the current user.
385
-     */
386
-    private function loadIdentity()
387
-    {
388
-        if ($this->identityLoaded) {
389
-            return;
390
-        }
391
-
392
-        $statement = $this->database->prepare('SELECT * FROM oauthidentity WHERE user = :user');
393
-        $statement->execute(array(':user' => $this->user->getId()));
394
-        /** @var OAuthIdentity $obj */
395
-        $obj = $statement->fetchObject(OAuthIdentity::class);
396
-
397
-        if ($obj === false) {
398
-            // failed to load identity.
399
-            $this->identityLoaded = true;
400
-            $this->identity = null;
401
-
402
-            return;
403
-        }
404
-
405
-        $obj->setDatabase($this->database);
406
-        $this->identityLoaded = true;
407
-        $this->identity = $obj;
408
-    }
409
-
410
-    /**
411
-     * @return OAuthToken
412
-     * @throws OAuthException
413
-     */
414
-    private function loadAccessToken()
415
-    {
416
-        if (!$this->accessTokenLoaded) {
417
-            $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_ACCESS));
418
-            /** @var OAuthToken $token */
419
-            $token = $this->getTokenStatement->fetchObject(OAuthToken::class);
420
-            $this->getTokenStatement->closeCursor();
421
-
422
-            if ($token === false) {
423
-                throw new OAuthException('Access token not found!');
424
-            }
425
-
426
-            $this->accessToken = $token;
427
-            $this->accessTokenLoaded = true;
428
-        }
429
-
430
-        return $this->accessToken;
431
-    }
73
+		);
74
+		$statement->execute(array(':type' => self::TOKEN_REQUEST, ':token' => $requestToken));
75
+
76
+		/** @var User $user */
77
+		$user = $statement->fetchObject(User::class);
78
+		$statement->closeCursor();
79
+
80
+		if ($user === false) {
81
+			throw new ApplicationLogicException('Token not found in store, please try again');
82
+		}
83
+
84
+		$user->setDatabase($database);
85
+
86
+		return $user;
87
+	}
88
+
89
+	public static function userIsFullyLinked(User $user, PdoDatabase $database = null)
90
+	{
91
+		if (self::$tokenCountStatement === null && $database === null) {
92
+			throw new ApplicationLogicException('Static link request without initialised statement');
93
+		}
94
+
95
+		return self::runTokenCount($user->getId(), $database, self::TOKEN_ACCESS);
96
+	}
97
+
98
+	public static function userIsPartiallyLinked(User $user, PdoDatabase $database = null)
99
+	{
100
+		if (self::$tokenCountStatement === null && $database === null) {
101
+			throw new ApplicationLogicException('Static link request without initialised statement');
102
+		}
103
+
104
+		if (self::userIsFullyLinked($user, $database)) {
105
+			return false;
106
+		}
107
+
108
+		return self::runTokenCount($user->getId(), $database, self::TOKEN_REQUEST)
109
+			|| $user->getOnWikiName() == null;
110
+	}
111
+
112
+	/**
113
+	 * @param PdoDatabase $database
114
+	 */
115
+	public static function prepareTokenCountStatement(PdoDatabase $database)
116
+	{
117
+		if (self::$tokenCountStatement === null) {
118
+			self::$tokenCountStatement = $database->prepare('SELECT COUNT(*) FROM oauthtoken WHERE user = :user AND type = :type');
119
+		}
120
+	}
121
+
122
+	private static function runTokenCount($userId, $database, $tokenType)
123
+	{
124
+		if (self::$tokenCountStatement === null) {
125
+			self::prepareTokenCountStatement($database);
126
+		}
127
+
128
+		self::$tokenCountStatement->execute(array(
129
+			':user' => $userId,
130
+			':type' => $tokenType,
131
+		));
132
+
133
+		$tokenCount = self::$tokenCountStatement->fetchColumn();
134
+		$linked = $tokenCount > 0;
135
+		self::$tokenCountStatement->closeCursor();
136
+
137
+		return $linked;
138
+	}
139
+
140
+	#endregion Static methods
141
+
142
+	/**
143
+	 * OAuthUserHelper constructor.
144
+	 *
145
+	 * @param User                 $user
146
+	 * @param PdoDatabase          $database
147
+	 * @param IOAuthProtocolHelper $oauthProtocolHelper
148
+	 * @param SiteConfiguration    $siteConfiguration
149
+	 */
150
+	public function __construct(
151
+		User $user,
152
+		PdoDatabase $database,
153
+		IOAuthProtocolHelper $oauthProtocolHelper,
154
+		SiteConfiguration $siteConfiguration
155
+	) {
156
+		$this->user = $user;
157
+		$this->database = $database;
158
+		$this->oauthProtocolHelper = $oauthProtocolHelper;
159
+
160
+		$this->linked = null;
161
+		$this->partiallyLinked = null;
162
+		$this->siteConfiguration = $siteConfiguration;
163
+
164
+		self::prepareTokenCountStatement($database);
165
+		$this->getTokenStatement = $this->database->prepare('SELECT * FROM oauthtoken WHERE user = :user AND type = :type');
166
+	}
167
+
168
+	/**
169
+	 * Determines if the user is fully connected to OAuth.
170
+	 *
171
+	 * @return bool
172
+	 */
173
+	public function isFullyLinked()
174
+	{
175
+		if ($this->linked === null) {
176
+			$this->linked = self::userIsFullyLinked($this->user, $this->database);
177
+		}
178
+
179
+		return $this->linked;
180
+	}
181
+
182
+	/**
183
+	 * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
184
+	 * procedure before configuring.
185
+	 * @return bool
186
+	 */
187
+	public function isPartiallyLinked()
188
+	{
189
+		if ($this->partiallyLinked === null) {
190
+			$this->partiallyLinked = self::userIsPartiallyLinked($this->user, $this->database);
191
+		}
192
+
193
+		return $this->partiallyLinked;
194
+	}
195
+
196
+	/**
197
+	 * @throws OAuthException
198
+	 */
199
+	public function refreshIdentity()
200
+	{
201
+		$this->loadIdentity();
202
+
203
+		if ($this->identity === null) {
204
+			$this->identity = new OAuthIdentity();
205
+			$this->identity->setUserId($this->user->getId());
206
+			$this->identity->setDatabase($this->database);
207
+		}
208
+
209
+		$token = $this->loadAccessToken();
210
+
211
+		$rawTicket = $this->oauthProtocolHelper->getIdentityTicket($token->getToken(), $token->getSecret());
212
+
213
+		$this->identity->populate($rawTicket);
214
+
215
+		if (!$this->identityIsValid()) {
216
+			throw new OAuthException('Identity ticket is not valid!');
217
+		}
218
+
219
+		$this->identity->save();
220
+
221
+		$this->user->setOnWikiName($this->identity->getUsername());
222
+		$this->user->save();
223
+	}
224
+
225
+	public function getRequestToken()
226
+	{
227
+		$token = $this->oauthProtocolHelper->getRequestToken();
228
+
229
+		$this->partiallyLinked = true;
230
+		$this->linked = false;
231
+
232
+		$this->database
233
+			->prepare('DELETE FROM oauthtoken WHERE user = :user AND type = :type')
234
+			->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
235
+
236
+		$this->database
237
+			->prepare('INSERT INTO oauthtoken (user, type, token, secret, expiry) VALUES (:user, :type, :token, :secret, DATE_ADD(NOW(), INTERVAL 1 DAY))')
238
+			->execute(array(
239
+				':user'   => $this->user->getId(),
240
+				':type'   => self::TOKEN_REQUEST,
241
+				':token'  => $token->key,
242
+				':secret' => $token->secret,
243
+			));
244
+
245
+		return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
246
+	}
247
+
248
+	public function completeHandshake($verificationToken)
249
+	{
250
+		$this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
251
+
252
+		/** @var OAuthToken $token */
253
+		$token = $this->getTokenStatement->fetchObject(OAuthToken::class);
254
+		$this->getTokenStatement->closeCursor();
255
+
256
+		if ($token === false) {
257
+			throw new ApplicationLogicException('Cannot find request token');
258
+		}
259
+
260
+		$token->setDatabase($this->database);
261
+
262
+		$accessToken = $this->oauthProtocolHelper->callbackCompleted($token->getToken(), $token->getSecret(),
263
+			$verificationToken);
264
+
265
+		$clearStatement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :u AND type = :t');
266
+		$clearStatement->execute(array(':u' => $this->user->getId(), ':t' => self::TOKEN_ACCESS));
267
+
268
+		$token->setToken($accessToken->key);
269
+		$token->setSecret($accessToken->secret);
270
+		$token->setType(self::TOKEN_ACCESS);
271
+		$token->setExpiry(null);
272
+		$token->save();
273
+
274
+		$this->partiallyLinked = false;
275
+		$this->linked = true;
276
+
277
+		$this->refreshIdentity();
278
+	}
279
+
280
+	public function detach()
281
+	{
282
+		$this->loadIdentity();
283
+
284
+		$this->identity->delete();
285
+		$statement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :user');
286
+		$statement->execute(array(':user' => $this->user->getId()));
287
+
288
+		$this->identity = null;
289
+		$this->linked = false;
290
+		$this->partiallyLinked = false;
291
+	}
292
+
293
+	/**
294
+	 * @param bool $expiredOk
295
+	 *
296
+	 * @return OAuthIdentity
297
+	 * @throws OAuthException
298
+	 */
299
+	public function getIdentity($expiredOk = false)
300
+	{
301
+		$this->loadIdentity();
302
+
303
+		if (!$this->identityIsValid($expiredOk)) {
304
+			throw new OAuthException('Stored identity is not valid.');
305
+		}
306
+
307
+		return $this->identity;
308
+	}
309
+
310
+	public function doApiCall($params, $method)
311
+	{
312
+		// Ensure we're logged in
313
+		$params['assert'] = 'user';
314
+
315
+		$token = $this->loadAccessToken();
316
+		return $this->oauthProtocolHelper->apiCall($params, $token->getToken(), $token->getSecret(), $method);
317
+	}
318
+
319
+	/**
320
+	 * @param bool $expiredOk
321
+	 *
322
+	 * @return bool
323
+	 */
324
+	private function identityIsValid($expiredOk = false)
325
+	{
326
+		$this->loadIdentity();
327
+
328
+		if ($this->identity === null) {
329
+			return false;
330
+		}
331
+
332
+		if ($this->identity->getIssuedAtTime() === false
333
+			|| $this->identity->getExpirationTime() === false
334
+			|| $this->identity->getAudience() === false
335
+			|| $this->identity->getIssuer() === false
336
+		) {
337
+			// this isn't populated properly.
338
+			return false;
339
+		}
340
+
341
+		$issue = DateTimeImmutable::createFromFormat("U", $this->identity->getIssuedAtTime());
342
+		$now = new DateTimeImmutable();
343
+
344
+		if ($issue > $now) {
345
+			// wat.
346
+			return false;
347
+		}
348
+
349
+		if ($this->identityExpired() && !$expiredOk) {
350
+			// soz.
351
+			return false;
352
+		}
353
+
354
+		if ($this->identity->getAudience() !== $this->siteConfiguration->getOAuthConsumerToken()) {
355
+			// token not issued for us
356
+			return false;
357
+		}
358
+
359
+		if ($this->identity->getIssuer() !== $this->siteConfiguration->getOauthMediaWikiCanonicalServer()) {
360
+			// token not issued by the right person
361
+			return false;
362
+		}
363
+
364
+		// can't find a reason to not trust it
365
+		return true;
366
+	}
367
+
368
+	/**
369
+	 * @return bool
370
+	 */
371
+	public function identityExpired()
372
+	{
373
+		// allowed max age
374
+		$gracePeriod = $this->siteConfiguration->getOauthIdentityGraceTime();
375
+
376
+		$expiry = DateTimeImmutable::createFromFormat("U", $this->identity->getExpirationTime());
377
+		$graceExpiry = $expiry->modify($gracePeriod);
378
+		$now = new DateTimeImmutable();
379
+
380
+		return $graceExpiry < $now;
381
+	}
382
+
383
+	/**
384
+	 * Loads the OAuth identity from the database for the current user.
385
+	 */
386
+	private function loadIdentity()
387
+	{
388
+		if ($this->identityLoaded) {
389
+			return;
390
+		}
391
+
392
+		$statement = $this->database->prepare('SELECT * FROM oauthidentity WHERE user = :user');
393
+		$statement->execute(array(':user' => $this->user->getId()));
394
+		/** @var OAuthIdentity $obj */
395
+		$obj = $statement->fetchObject(OAuthIdentity::class);
396
+
397
+		if ($obj === false) {
398
+			// failed to load identity.
399
+			$this->identityLoaded = true;
400
+			$this->identity = null;
401
+
402
+			return;
403
+		}
404
+
405
+		$obj->setDatabase($this->database);
406
+		$this->identityLoaded = true;
407
+		$this->identity = $obj;
408
+	}
409
+
410
+	/**
411
+	 * @return OAuthToken
412
+	 * @throws OAuthException
413
+	 */
414
+	private function loadAccessToken()
415
+	{
416
+		if (!$this->accessTokenLoaded) {
417
+			$this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_ACCESS));
418
+			/** @var OAuthToken $token */
419
+			$token = $this->getTokenStatement->fetchObject(OAuthToken::class);
420
+			$this->getTokenStatement->closeCursor();
421
+
422
+			if ($token === false) {
423
+				throw new OAuthException('Access token not found!');
424
+			}
425
+
426
+			$this->accessToken = $token;
427
+			$this->accessTokenLoaded = true;
428
+		}
429
+
430
+		return $this->accessToken;
431
+	}
432 432
 }
433 433
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/Interfaces/IMediaWikiClient.php 1 patch
Indentation   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -10,5 +10,5 @@
 block discarded – undo
10 10
 
11 11
 interface IMediaWikiClient
12 12
 {
13
-    function doApiCall($params, $method);
13
+	function doApiCall($params, $method);
14 14
 }
15 15
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/Interfaces/IOAuthProtocolHelper.php 1 patch
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -19,52 +19,52 @@
 block discarded – undo
19 19
 
20 20
 interface IOAuthProtocolHelper
21 21
 {
22
-    /**
23
-     * @return stdClass
24
-     *
25
-     * @throws Exception
26
-     * @throws CurlException
27
-     */
28
-    public function getRequestToken();
22
+	/**
23
+	 * @return stdClass
24
+	 *
25
+	 * @throws Exception
26
+	 * @throws CurlException
27
+	 */
28
+	public function getRequestToken();
29 29
 
30
-    /**
31
-     * @param string $requestToken
32
-     *
33
-     * @return string
34
-     */
35
-    public function getAuthoriseUrl($requestToken);
30
+	/**
31
+	 * @param string $requestToken
32
+	 *
33
+	 * @return string
34
+	 */
35
+	public function getAuthoriseUrl($requestToken);
36 36
 
37
-    /**
38
-     * @param string $oauthRequestToken
39
-     * @param string $oauthRequestSecret
40
-     * @param string $oauthVerifier
41
-     *
42
-     * @return stdClass
43
-     * @throws CurlException
44
-     * @throws Exception
45
-     */
46
-    public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
37
+	/**
38
+	 * @param string $oauthRequestToken
39
+	 * @param string $oauthRequestSecret
40
+	 * @param string $oauthVerifier
41
+	 *
42
+	 * @return stdClass
43
+	 * @throws CurlException
44
+	 * @throws Exception
45
+	 */
46
+	public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier);
47 47
 
48
-    /**
49
-     * @param string $oauthAccessToken
50
-     * @param string $oauthAccessSecret
51
-     *
52
-     * @return stdClass
53
-     * @throws CurlException
54
-     * @throws Exception
55
-     */
56
-    public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
48
+	/**
49
+	 * @param string $oauthAccessToken
50
+	 * @param string $oauthAccessSecret
51
+	 *
52
+	 * @return stdClass
53
+	 * @throws CurlException
54
+	 * @throws Exception
55
+	 */
56
+	public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret);
57 57
 
58
-    /**
59
-     * @param array  $apiParams    array of parameters to send to the API
60
-     * @param string $accessToken  user's access token
61
-     * @param string $accessSecret user's secret
62
-     * @param string $method       HTTP method
63
-     *
64
-     * @return stdClass
65
-     * @throws ApplicationLogicException
66
-     * @throws CurlException
67
-     * @throws Exception
68
-     */
69
-    public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
58
+	/**
59
+	 * @param array  $apiParams    array of parameters to send to the API
60
+	 * @param string $accessToken  user's access token
61
+	 * @param string $accessSecret user's secret
62
+	 * @param string $method       HTTP method
63
+	 *
64
+	 * @return stdClass
65
+	 * @throws ApplicationLogicException
66
+	 * @throws CurlException
67
+	 * @throws Exception
68
+	 */
69
+	public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET');
70 70
 }
71 71
\ No newline at end of file
Please login to merge, or discard this patch.
includes/Helpers/HttpHelper.php 2 patches
Indentation   +105 added lines, -105 removed lines patch added patch discarded remove patch
@@ -12,109 +12,109 @@
 block discarded – undo
12 12
 
13 13
 class HttpHelper
14 14
 {
15
-    private $curlHandle;
16
-
17
-    /**
18
-     * HttpHelper constructor.
19
-     *
20
-     * @param string  $userAgent
21
-     * @param boolean $disableVerifyPeer
22
-     * @param string  $cookieJar
23
-     */
24
-    public function __construct($userAgent, $disableVerifyPeer, $cookieJar = null)
25
-    {
26
-        $this->curlHandle = curl_init();
27
-
28
-        curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
29
-        curl_setopt($this->curlHandle, CURLOPT_USERAGENT, $userAgent);
30
-        curl_setopt($this->curlHandle, CURLOPT_FAILONERROR, true);
31
-
32
-        if ($disableVerifyPeer) {
33
-            curl_setopt($this->curlHandle, CURLOPT_SSL_VERIFYPEER, false);
34
-        }
35
-
36
-        if($cookieJar !== null) {
37
-            curl_setopt($this->curlHandle, CURLOPT_COOKIEFILE, $cookieJar);
38
-            curl_setopt($this->curlHandle, CURLOPT_COOKIEJAR, $cookieJar);
39
-        }
40
-    }
41
-
42
-    public function __destruct()
43
-    {
44
-        curl_close($this->curlHandle);
45
-    }
46
-
47
-    /**
48
-     * Fetches the content of a URL, with an optional parameter set.
49
-     *
50
-     * @param string     $url        The URL to fetch.
51
-     * @param null|array $parameters Key/value pair of GET parameters to add to the request.
52
-     *                               Null lets you handle it yourself.
53
-     *
54
-     * @param array      $headers
55
-     *
56
-     * @return string
57
-     * @throws CurlException
58
-     */
59
-    public function get($url, $parameters = null, $headers = array())
60
-    {
61
-        if ($parameters !== null && is_array($parameters)) {
62
-            $getString = '?' . http_build_query($parameters);
63
-            $url .= $getString;
64
-        }
65
-
66
-        curl_setopt($this->curlHandle, CURLOPT_URL, $url);
67
-
68
-        // Make sure we're doing a GET
69
-        curl_setopt($this->curlHandle, CURLOPT_POST, false);
70
-
71
-        curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers);
72
-
73
-        $result = curl_exec($this->curlHandle);
74
-
75
-        if ($result === false) {
76
-            $error = curl_error($this->curlHandle);
77
-            throw new CurlException('Remote request failed with error ' . $error);
78
-        }
79
-
80
-        return $result;
81
-    }
82
-
83
-    /**
84
-     * Posts data to a URL
85
-     *
86
-     * @param string $url        The URL to fetch.
87
-     * @param array  $parameters Key/value pair of POST parameters to add to the request.
88
-     * @param array  $headers
89
-     *
90
-     * @return string
91
-     * @throws CurlException
92
-     */
93
-    public function post($url, $parameters, $headers = array())
94
-    {
95
-        curl_setopt($this->curlHandle, CURLOPT_URL, $url);
96
-
97
-        // Make sure we're doing a POST
98
-        curl_setopt($this->curlHandle, CURLOPT_POST, true);
99
-        curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, http_build_query($parameters));
100
-
101
-        curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers);
102
-
103
-        $result = curl_exec($this->curlHandle);
104
-
105
-        if ($result === false) {
106
-            $error = curl_error($this->curlHandle);
107
-            throw new CurlException('Remote request failed with error ' . $error);
108
-        }
109
-
110
-        return $result;
111
-    }
112
-
113
-    /**
114
-     * @return string
115
-     */
116
-    public function getError()
117
-    {
118
-        return curl_error($this->curlHandle);
119
-    }
15
+	private $curlHandle;
16
+
17
+	/**
18
+	 * HttpHelper constructor.
19
+	 *
20
+	 * @param string  $userAgent
21
+	 * @param boolean $disableVerifyPeer
22
+	 * @param string  $cookieJar
23
+	 */
24
+	public function __construct($userAgent, $disableVerifyPeer, $cookieJar = null)
25
+	{
26
+		$this->curlHandle = curl_init();
27
+
28
+		curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
29
+		curl_setopt($this->curlHandle, CURLOPT_USERAGENT, $userAgent);
30
+		curl_setopt($this->curlHandle, CURLOPT_FAILONERROR, true);
31
+
32
+		if ($disableVerifyPeer) {
33
+			curl_setopt($this->curlHandle, CURLOPT_SSL_VERIFYPEER, false);
34
+		}
35
+
36
+		if($cookieJar !== null) {
37
+			curl_setopt($this->curlHandle, CURLOPT_COOKIEFILE, $cookieJar);
38
+			curl_setopt($this->curlHandle, CURLOPT_COOKIEJAR, $cookieJar);
39
+		}
40
+	}
41
+
42
+	public function __destruct()
43
+	{
44
+		curl_close($this->curlHandle);
45
+	}
46
+
47
+	/**
48
+	 * Fetches the content of a URL, with an optional parameter set.
49
+	 *
50
+	 * @param string     $url        The URL to fetch.
51
+	 * @param null|array $parameters Key/value pair of GET parameters to add to the request.
52
+	 *                               Null lets you handle it yourself.
53
+	 *
54
+	 * @param array      $headers
55
+	 *
56
+	 * @return string
57
+	 * @throws CurlException
58
+	 */
59
+	public function get($url, $parameters = null, $headers = array())
60
+	{
61
+		if ($parameters !== null && is_array($parameters)) {
62
+			$getString = '?' . http_build_query($parameters);
63
+			$url .= $getString;
64
+		}
65
+
66
+		curl_setopt($this->curlHandle, CURLOPT_URL, $url);
67
+
68
+		// Make sure we're doing a GET
69
+		curl_setopt($this->curlHandle, CURLOPT_POST, false);
70
+
71
+		curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers);
72
+
73
+		$result = curl_exec($this->curlHandle);
74
+
75
+		if ($result === false) {
76
+			$error = curl_error($this->curlHandle);
77
+			throw new CurlException('Remote request failed with error ' . $error);
78
+		}
79
+
80
+		return $result;
81
+	}
82
+
83
+	/**
84
+	 * Posts data to a URL
85
+	 *
86
+	 * @param string $url        The URL to fetch.
87
+	 * @param array  $parameters Key/value pair of POST parameters to add to the request.
88
+	 * @param array  $headers
89
+	 *
90
+	 * @return string
91
+	 * @throws CurlException
92
+	 */
93
+	public function post($url, $parameters, $headers = array())
94
+	{
95
+		curl_setopt($this->curlHandle, CURLOPT_URL, $url);
96
+
97
+		// Make sure we're doing a POST
98
+		curl_setopt($this->curlHandle, CURLOPT_POST, true);
99
+		curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, http_build_query($parameters));
100
+
101
+		curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers);
102
+
103
+		$result = curl_exec($this->curlHandle);
104
+
105
+		if ($result === false) {
106
+			$error = curl_error($this->curlHandle);
107
+			throw new CurlException('Remote request failed with error ' . $error);
108
+		}
109
+
110
+		return $result;
111
+	}
112
+
113
+	/**
114
+	 * @return string
115
+	 */
116
+	public function getError()
117
+	{
118
+		return curl_error($this->curlHandle);
119
+	}
120 120
 }
121 121
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@  discard block
 block discarded – undo
33 33
             curl_setopt($this->curlHandle, CURLOPT_SSL_VERIFYPEER, false);
34 34
         }
35 35
 
36
-        if($cookieJar !== null) {
36
+        if ($cookieJar !== null) {
37 37
             curl_setopt($this->curlHandle, CURLOPT_COOKIEFILE, $cookieJar);
38 38
             curl_setopt($this->curlHandle, CURLOPT_COOKIEJAR, $cookieJar);
39 39
         }
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
     public function get($url, $parameters = null, $headers = array())
60 60
     {
61 61
         if ($parameters !== null && is_array($parameters)) {
62
-            $getString = '?' . http_build_query($parameters);
62
+            $getString = '?'.http_build_query($parameters);
63 63
             $url .= $getString;
64 64
         }
65 65
 
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
 
75 75
         if ($result === false) {
76 76
             $error = curl_error($this->curlHandle);
77
-            throw new CurlException('Remote request failed with error ' . $error);
77
+            throw new CurlException('Remote request failed with error '.$error);
78 78
         }
79 79
 
80 80
         return $result;
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 
105 105
         if ($result === false) {
106 106
             $error = curl_error($this->curlHandle);
107
-            throw new CurlException('Remote request failed with error ' . $error);
107
+            throw new CurlException('Remote request failed with error '.$error);
108 108
         }
109 109
 
110 110
         return $result;
Please login to merge, or discard this patch.
includes/Helpers/MediaWikiHelper.php 3 patches
Braces   +2 added lines, -1 removed lines patch added patch discarded remove patch
@@ -241,7 +241,8 @@
 block discarded – undo
241 241
      * @param string $username
242 242
      * @return bool
243 243
      */
244
-    public function checkAccountExists($username) {
244
+    public function checkAccountExists($username)
245
+    {
245 246
         $parameters = array(
246 247
             'action'  => 'query',
247 248
             'list'    => 'users',
Please login to merge, or discard this patch.
Indentation   +241 added lines, -241 removed lines patch added patch discarded remove patch
@@ -15,245 +15,245 @@
 block discarded – undo
15 15
 
16 16
 class MediaWikiHelper
17 17
 {
18
-    /**
19
-     * @var IMediaWikiClient
20
-     */
21
-    private $mediaWikiClient;
22
-    /**
23
-     * @var SiteConfiguration
24
-     */
25
-    private $siteConfiguration;
26
-
27
-    /**
28
-     * MediaWikiHelper constructor.
29
-     *
30
-     * @param IMediaWikiClient  $mediaWikiClient
31
-     * @param SiteConfiguration $siteConfiguration
32
-     */
33
-    public function __construct(IMediaWikiClient $mediaWikiClient, SiteConfiguration $siteConfiguration)
34
-    {
35
-        $this->mediaWikiClient = $mediaWikiClient;
36
-        $this->siteConfiguration = $siteConfiguration;
37
-    }
38
-
39
-    /**
40
-     * @todo handle override antispoof and titleblacklist issues
41
-     *
42
-     * @param string $username
43
-     * @param string $emailAddress
44
-     * @param string $reason
45
-     *
46
-     * @throws Exception
47
-     * @throws MediaWikiApiException
48
-     */
49
-    public function createAccount($username, $emailAddress, $reason)
50
-    {
51
-        // get token
52
-        $tokenParams = array(
53
-            'action' => 'query',
54
-            'meta'   => 'tokens',
55
-            'type'   => 'createaccount',
56
-        );
57
-
58
-        $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
59
-
60
-        if (isset($response->error)) {
61
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
62
-        }
63
-
64
-        $token = $response->query->tokens->createaccounttoken;
65
-
66
-        $callback = $this->siteConfiguration->getBaseUrl() . '/internal.php/oauth/createCallback';
67
-
68
-        $checkboxFields = array();
69
-        $requiredFields = array();
70
-        $this->getCreationFieldData($requiredFields, $checkboxFields);
71
-
72
-        $apiCallData = array(
73
-            'action'              => 'createaccount',
74
-            'createreturnurl'     => $callback,
75
-            'createtoken'         => $token,
76
-            'createmessageformat' => 'html',
77
-        );
78
-
79
-        $createParams = array_fill_keys($requiredFields, '') + $apiCallData;
80
-
81
-        $createParams['username'] = $username;
82
-        $createParams['mailpassword'] = true;
83
-        $createParams['email'] = $emailAddress;
84
-        $createParams['reason'] = $reason;
85
-
86
-        $createResponse = $this->mediaWikiClient->doApiCall($createParams, 'POST');
87
-
88
-        if (isset($createResponse->error)) {
89
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
90
-        }
91
-
92
-        if (!isset($createResponse->createaccount) || !isset($createResponse->createaccount->status)) {
93
-            throw new MediaWikiApiException('Unknown error creating account');
94
-        }
95
-
96
-        if ($createResponse->createaccount->status === 'FAIL') {
97
-            throw new MediaWikiApiException($createResponse->createaccount->message);
98
-        }
99
-
100
-        if ($createResponse->createaccount->status === 'PASS') {
101
-            // success!
102
-            return;
103
-        }
104
-
105
-        throw new Exception('API result reported status of ' . $createResponse->createaccount->status);
106
-    }
107
-
108
-    /**
109
-     * @param string $username
110
-     * @param string $title
111
-     * @param        $summary
112
-     * @param string $message
113
-     * @param bool   $createOnly
114
-     *
115
-     * @throws MediaWikiApiException
116
-     */
117
-    public function addTalkPageMessage($username, $title, $summary, $message, $createOnly = true)
118
-    {
119
-        // get token
120
-        $tokenParams = array(
121
-            'action' => 'query',
122
-            'meta'   => 'tokens',
123
-            'type'   => 'csrf',
124
-        );
125
-
126
-        $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
127
-
128
-        if (isset($response->error)) {
129
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
130
-        }
131
-
132
-        $token = $response->query->tokens->csrftoken;
133
-
134
-        if ($token === null) {
135
-            throw new MediaWikiApiException('Edit token could not be acquired');
136
-        }
137
-
138
-        $editParameters = array(
139
-            'action'       => 'edit',
140
-            'title'        => 'User talk:' . $username,
141
-            'section'      => 'new',
142
-            'sectiontitle' => $title,
143
-            'summary'      => $summary,
144
-            'text'         => $message,
145
-            'token'        => $token,
146
-        );
147
-
148
-        if ($createOnly) {
149
-            $editParameters['createonly'] = true;
150
-        }
151
-
152
-        $response = $this->mediaWikiClient->doApiCall($editParameters, 'POST');
153
-
154
-        if (!isset($response->edit)) {
155
-            if (isset($response->error)) {
156
-                throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
157
-            }
158
-
159
-            throw new MediaWikiApiException('Unknown error encountered during editing.');
160
-        }
161
-
162
-        $editResponse = $response->edit;
163
-        if ($editResponse->result === "Success") {
164
-            return;
165
-        }
166
-
167
-        throw new MediaWikiApiException('Edit status unsuccessful: ' . $editResponse->result);
168
-    }
169
-
170
-    public function getCreationFieldData(&$requiredFields, &$checkboxFields)
171
-    {
172
-        // get token
173
-        $params = array(
174
-            'action'         => 'query',
175
-            'meta'           => 'authmanagerinfo',
176
-            'amirequestsfor' => 'create',
177
-        );
178
-
179
-        $response = $this->mediaWikiClient->doApiCall($params, 'GET');
180
-
181
-        if (isset($response->error)) {
182
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
183
-        }
184
-
185
-        $requests = $response->query->authmanagerinfo->requests;
186
-
187
-        // We don't want to deal with these providers ever.
188
-        $discardList = array(
189
-            // Requires a username and password
190
-            'MediaWiki\\Auth\\PasswordAuthenticationRequest',
191
-        );
192
-
193
-        // We require these providers to function
194
-        $requireList = array(
195
-            'MediaWiki\\Auth\\TemporaryPasswordAuthenticationRequest',
196
-            'MediaWiki\\Auth\\UsernameAuthenticationRequest',
197
-            'MediaWiki\\Auth\\UserDataAuthenticationRequest',
198
-            'MediaWiki\\Auth\\CreationReasonAuthenticationRequest',
199
-        );
200
-
201
-        $requiredFields = array();
202
-        // Keep checkbox fields separate, since "required" actually means optional as absent == false.
203
-        $checkboxFields = array();
204
-
205
-        foreach ($requests as $req) {
206
-            // Immediately discard anything that is on the discard list.
207
-            if (in_array($req->id, $discardList)) {
208
-                continue;
209
-            }
210
-
211
-            $required = false;
212
-
213
-            if ($req->required === 'primary-required' && !in_array($req->id, $requireList)) {
214
-                // Only want one.
215
-                continue;
216
-            }
217
-
218
-            if (in_array($req->id, $requireList)) {
219
-                unset($requireList[$req->id]);
220
-                $required = true;
221
-            }
222
-
223
-            if ($req->required === 'required') {
224
-                $required = true;
225
-            }
226
-
227
-            if ($required) {
228
-                foreach ($req->fields as $name => $data) {
229
-                    if ($data->type === 'checkbox') {
230
-                        $checkboxFields[] = $name;
231
-                    }
232
-                    else {
233
-                        $requiredFields[] = $name;
234
-                    }
235
-                }
236
-            }
237
-        }
238
-    }
239
-
240
-    /**
241
-     * @param string $username
242
-     * @return bool
243
-     */
244
-    public function checkAccountExists($username) {
245
-        $parameters = array(
246
-            'action'  => 'query',
247
-            'list'    => 'users',
248
-            'format'  => 'php',
249
-            'ususers' => $username,
250
-        );
251
-
252
-        $apiResult = $this->mediaWikiClient->doApiCall($parameters, 'GET');
253
-
254
-        $entry = $apiResult->query->users[0];
255
-        $exists = !isset($entry->missing);
256
-
257
-        return $exists;
258
-    }
18
+	/**
19
+	 * @var IMediaWikiClient
20
+	 */
21
+	private $mediaWikiClient;
22
+	/**
23
+	 * @var SiteConfiguration
24
+	 */
25
+	private $siteConfiguration;
26
+
27
+	/**
28
+	 * MediaWikiHelper constructor.
29
+	 *
30
+	 * @param IMediaWikiClient  $mediaWikiClient
31
+	 * @param SiteConfiguration $siteConfiguration
32
+	 */
33
+	public function __construct(IMediaWikiClient $mediaWikiClient, SiteConfiguration $siteConfiguration)
34
+	{
35
+		$this->mediaWikiClient = $mediaWikiClient;
36
+		$this->siteConfiguration = $siteConfiguration;
37
+	}
38
+
39
+	/**
40
+	 * @todo handle override antispoof and titleblacklist issues
41
+	 *
42
+	 * @param string $username
43
+	 * @param string $emailAddress
44
+	 * @param string $reason
45
+	 *
46
+	 * @throws Exception
47
+	 * @throws MediaWikiApiException
48
+	 */
49
+	public function createAccount($username, $emailAddress, $reason)
50
+	{
51
+		// get token
52
+		$tokenParams = array(
53
+			'action' => 'query',
54
+			'meta'   => 'tokens',
55
+			'type'   => 'createaccount',
56
+		);
57
+
58
+		$response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
59
+
60
+		if (isset($response->error)) {
61
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
62
+		}
63
+
64
+		$token = $response->query->tokens->createaccounttoken;
65
+
66
+		$callback = $this->siteConfiguration->getBaseUrl() . '/internal.php/oauth/createCallback';
67
+
68
+		$checkboxFields = array();
69
+		$requiredFields = array();
70
+		$this->getCreationFieldData($requiredFields, $checkboxFields);
71
+
72
+		$apiCallData = array(
73
+			'action'              => 'createaccount',
74
+			'createreturnurl'     => $callback,
75
+			'createtoken'         => $token,
76
+			'createmessageformat' => 'html',
77
+		);
78
+
79
+		$createParams = array_fill_keys($requiredFields, '') + $apiCallData;
80
+
81
+		$createParams['username'] = $username;
82
+		$createParams['mailpassword'] = true;
83
+		$createParams['email'] = $emailAddress;
84
+		$createParams['reason'] = $reason;
85
+
86
+		$createResponse = $this->mediaWikiClient->doApiCall($createParams, 'POST');
87
+
88
+		if (isset($createResponse->error)) {
89
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
90
+		}
91
+
92
+		if (!isset($createResponse->createaccount) || !isset($createResponse->createaccount->status)) {
93
+			throw new MediaWikiApiException('Unknown error creating account');
94
+		}
95
+
96
+		if ($createResponse->createaccount->status === 'FAIL') {
97
+			throw new MediaWikiApiException($createResponse->createaccount->message);
98
+		}
99
+
100
+		if ($createResponse->createaccount->status === 'PASS') {
101
+			// success!
102
+			return;
103
+		}
104
+
105
+		throw new Exception('API result reported status of ' . $createResponse->createaccount->status);
106
+	}
107
+
108
+	/**
109
+	 * @param string $username
110
+	 * @param string $title
111
+	 * @param        $summary
112
+	 * @param string $message
113
+	 * @param bool   $createOnly
114
+	 *
115
+	 * @throws MediaWikiApiException
116
+	 */
117
+	public function addTalkPageMessage($username, $title, $summary, $message, $createOnly = true)
118
+	{
119
+		// get token
120
+		$tokenParams = array(
121
+			'action' => 'query',
122
+			'meta'   => 'tokens',
123
+			'type'   => 'csrf',
124
+		);
125
+
126
+		$response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
127
+
128
+		if (isset($response->error)) {
129
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
130
+		}
131
+
132
+		$token = $response->query->tokens->csrftoken;
133
+
134
+		if ($token === null) {
135
+			throw new MediaWikiApiException('Edit token could not be acquired');
136
+		}
137
+
138
+		$editParameters = array(
139
+			'action'       => 'edit',
140
+			'title'        => 'User talk:' . $username,
141
+			'section'      => 'new',
142
+			'sectiontitle' => $title,
143
+			'summary'      => $summary,
144
+			'text'         => $message,
145
+			'token'        => $token,
146
+		);
147
+
148
+		if ($createOnly) {
149
+			$editParameters['createonly'] = true;
150
+		}
151
+
152
+		$response = $this->mediaWikiClient->doApiCall($editParameters, 'POST');
153
+
154
+		if (!isset($response->edit)) {
155
+			if (isset($response->error)) {
156
+				throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
157
+			}
158
+
159
+			throw new MediaWikiApiException('Unknown error encountered during editing.');
160
+		}
161
+
162
+		$editResponse = $response->edit;
163
+		if ($editResponse->result === "Success") {
164
+			return;
165
+		}
166
+
167
+		throw new MediaWikiApiException('Edit status unsuccessful: ' . $editResponse->result);
168
+	}
169
+
170
+	public function getCreationFieldData(&$requiredFields, &$checkboxFields)
171
+	{
172
+		// get token
173
+		$params = array(
174
+			'action'         => 'query',
175
+			'meta'           => 'authmanagerinfo',
176
+			'amirequestsfor' => 'create',
177
+		);
178
+
179
+		$response = $this->mediaWikiClient->doApiCall($params, 'GET');
180
+
181
+		if (isset($response->error)) {
182
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
183
+		}
184
+
185
+		$requests = $response->query->authmanagerinfo->requests;
186
+
187
+		// We don't want to deal with these providers ever.
188
+		$discardList = array(
189
+			// Requires a username and password
190
+			'MediaWiki\\Auth\\PasswordAuthenticationRequest',
191
+		);
192
+
193
+		// We require these providers to function
194
+		$requireList = array(
195
+			'MediaWiki\\Auth\\TemporaryPasswordAuthenticationRequest',
196
+			'MediaWiki\\Auth\\UsernameAuthenticationRequest',
197
+			'MediaWiki\\Auth\\UserDataAuthenticationRequest',
198
+			'MediaWiki\\Auth\\CreationReasonAuthenticationRequest',
199
+		);
200
+
201
+		$requiredFields = array();
202
+		// Keep checkbox fields separate, since "required" actually means optional as absent == false.
203
+		$checkboxFields = array();
204
+
205
+		foreach ($requests as $req) {
206
+			// Immediately discard anything that is on the discard list.
207
+			if (in_array($req->id, $discardList)) {
208
+				continue;
209
+			}
210
+
211
+			$required = false;
212
+
213
+			if ($req->required === 'primary-required' && !in_array($req->id, $requireList)) {
214
+				// Only want one.
215
+				continue;
216
+			}
217
+
218
+			if (in_array($req->id, $requireList)) {
219
+				unset($requireList[$req->id]);
220
+				$required = true;
221
+			}
222
+
223
+			if ($req->required === 'required') {
224
+				$required = true;
225
+			}
226
+
227
+			if ($required) {
228
+				foreach ($req->fields as $name => $data) {
229
+					if ($data->type === 'checkbox') {
230
+						$checkboxFields[] = $name;
231
+					}
232
+					else {
233
+						$requiredFields[] = $name;
234
+					}
235
+				}
236
+			}
237
+		}
238
+	}
239
+
240
+	/**
241
+	 * @param string $username
242
+	 * @return bool
243
+	 */
244
+	public function checkAccountExists($username) {
245
+		$parameters = array(
246
+			'action'  => 'query',
247
+			'list'    => 'users',
248
+			'format'  => 'php',
249
+			'ususers' => $username,
250
+		);
251
+
252
+		$apiResult = $this->mediaWikiClient->doApiCall($parameters, 'GET');
253
+
254
+		$entry = $apiResult->query->users[0];
255
+		$exists = !isset($entry->missing);
256
+
257
+		return $exists;
258
+	}
259 259
 }
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -58,12 +58,12 @@  discard block
 block discarded – undo
58 58
         $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
59 59
 
60 60
         if (isset($response->error)) {
61
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
61
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
62 62
         }
63 63
 
64 64
         $token = $response->query->tokens->createaccounttoken;
65 65
 
66
-        $callback = $this->siteConfiguration->getBaseUrl() . '/internal.php/oauth/createCallback';
66
+        $callback = $this->siteConfiguration->getBaseUrl().'/internal.php/oauth/createCallback';
67 67
 
68 68
         $checkboxFields = array();
69 69
         $requiredFields = array();
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
         $createResponse = $this->mediaWikiClient->doApiCall($createParams, 'POST');
87 87
 
88 88
         if (isset($createResponse->error)) {
89
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
89
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
90 90
         }
91 91
 
92 92
         if (!isset($createResponse->createaccount) || !isset($createResponse->createaccount->status)) {
@@ -102,7 +102,7 @@  discard block
 block discarded – undo
102 102
             return;
103 103
         }
104 104
 
105
-        throw new Exception('API result reported status of ' . $createResponse->createaccount->status);
105
+        throw new Exception('API result reported status of '.$createResponse->createaccount->status);
106 106
     }
107 107
 
108 108
     /**
@@ -126,7 +126,7 @@  discard block
 block discarded – undo
126 126
         $response = $this->mediaWikiClient->doApiCall($tokenParams, 'POST');
127 127
 
128 128
         if (isset($response->error)) {
129
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
129
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
130 130
         }
131 131
 
132 132
         $token = $response->query->tokens->csrftoken;
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 
138 138
         $editParameters = array(
139 139
             'action'       => 'edit',
140
-            'title'        => 'User talk:' . $username,
140
+            'title'        => 'User talk:'.$username,
141 141
             'section'      => 'new',
142 142
             'sectiontitle' => $title,
143 143
             'summary'      => $summary,
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 
154 154
         if (!isset($response->edit)) {
155 155
             if (isset($response->error)) {
156
-                throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
156
+                throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
157 157
             }
158 158
 
159 159
             throw new MediaWikiApiException('Unknown error encountered during editing.');
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
             return;
165 165
         }
166 166
 
167
-        throw new MediaWikiApiException('Edit status unsuccessful: ' . $editResponse->result);
167
+        throw new MediaWikiApiException('Edit status unsuccessful: '.$editResponse->result);
168 168
     }
169 169
 
170 170
     public function getCreationFieldData(&$requiredFields, &$checkboxFields)
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
         $response = $this->mediaWikiClient->doApiCall($params, 'GET');
180 180
 
181 181
         if (isset($response->error)) {
182
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
182
+            throw new MediaWikiApiException($response->error->code.': '.$response->error->info);
183 183
         }
184 184
 
185 185
         $requests = $response->query->authmanagerinfo->requests;
Please login to merge, or discard this patch.
includes/Helpers/SearchHelpers/JobQueueSearchHelper.php 2 patches
Indentation   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -13,67 +13,67 @@
 block discarded – undo
13 13
 
14 14
 class JobQueueSearchHelper extends SearchHelperBase
15 15
 {
16
-    protected function __construct(PdoDatabase $database)
17
-    {
18
-        parent::__construct($database, 'jobqueue', JobQueue::class, null);
19
-    }
20
-
21
-    /**
22
-     * @param PdoDatabase $database
23
-     *
24
-     * @return JobQueueSearchHelper
25
-     */
26
-    public static function get(PdoDatabase $database) {
27
-        $helper = new JobQueueSearchHelper($database);
28
-        return $helper;
29
-    }
30
-
31
-    /**
32
-     * @param string[] $statuses
33
-     *
34
-     * @return $this
35
-     */
36
-    public function statusIn($statuses) {
37
-        $this->inClause('status', $statuses);
38
-
39
-        return $this;
40
-    }
41
-
42
-    /**
43
-     * @return $this
44
-     */
45
-    public function notAcknowledged() {
46
-        $this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47
-
48
-        return $this;
49
-    }
50
-
51
-    public function byTask($task) {
52
-        $this->whereClause .= ' AND task = ?';
53
-        $this->parameterList[] = $task;
54
-
55
-        return $this;
56
-    }
57
-
58
-    public function byUser($userId) {
59
-        $this->whereClause .= ' AND user = ?';
60
-        $this->parameterList[] = $userId;
61
-
62
-        return $this;
63
-    }
64
-
65
-    public function byStatus($status) {
66
-        $this->whereClause .= ' AND status = ?';
67
-        $this->parameterList[] = $status;
68
-
69
-        return $this;
70
-    }
71
-
72
-    public function byRequest($request)
73
-    {
74
-        $this->whereClause .= ' AND request = ?';
75
-        $this->parameterList[] = $request;
76
-
77
-        return $this;
78
-    }
16
+	protected function __construct(PdoDatabase $database)
17
+	{
18
+		parent::__construct($database, 'jobqueue', JobQueue::class, null);
19
+	}
20
+
21
+	/**
22
+	 * @param PdoDatabase $database
23
+	 *
24
+	 * @return JobQueueSearchHelper
25
+	 */
26
+	public static function get(PdoDatabase $database) {
27
+		$helper = new JobQueueSearchHelper($database);
28
+		return $helper;
29
+	}
30
+
31
+	/**
32
+	 * @param string[] $statuses
33
+	 *
34
+	 * @return $this
35
+	 */
36
+	public function statusIn($statuses) {
37
+		$this->inClause('status', $statuses);
38
+
39
+		return $this;
40
+	}
41
+
42
+	/**
43
+	 * @return $this
44
+	 */
45
+	public function notAcknowledged() {
46
+		$this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47
+
48
+		return $this;
49
+	}
50
+
51
+	public function byTask($task) {
52
+		$this->whereClause .= ' AND task = ?';
53
+		$this->parameterList[] = $task;
54
+
55
+		return $this;
56
+	}
57
+
58
+	public function byUser($userId) {
59
+		$this->whereClause .= ' AND user = ?';
60
+		$this->parameterList[] = $userId;
61
+
62
+		return $this;
63
+	}
64
+
65
+	public function byStatus($status) {
66
+		$this->whereClause .= ' AND status = ?';
67
+		$this->parameterList[] = $status;
68
+
69
+		return $this;
70
+	}
71
+
72
+	public function byRequest($request)
73
+	{
74
+		$this->whereClause .= ' AND request = ?';
75
+		$this->parameterList[] = $request;
76
+
77
+		return $this;
78
+	}
79 79
 }
80 80
\ No newline at end of file
Please login to merge, or discard this patch.
Braces   +12 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,7 +23,8 @@  discard block
 block discarded – undo
23 23
      *
24 24
      * @return JobQueueSearchHelper
25 25
      */
26
-    public static function get(PdoDatabase $database) {
26
+    public static function get(PdoDatabase $database)
27
+    {
27 28
         $helper = new JobQueueSearchHelper($database);
28 29
         return $helper;
29 30
     }
@@ -33,7 +34,8 @@  discard block
 block discarded – undo
33 34
      *
34 35
      * @return $this
35 36
      */
36
-    public function statusIn($statuses) {
37
+    public function statusIn($statuses)
38
+    {
37 39
         $this->inClause('status', $statuses);
38 40
 
39 41
         return $this;
@@ -42,27 +44,31 @@  discard block
 block discarded – undo
42 44
     /**
43 45
      * @return $this
44 46
      */
45
-    public function notAcknowledged() {
47
+    public function notAcknowledged()
48
+    {
46 49
         $this->whereClause .= ' AND (acknowledged IS NULL OR acknowledged = 0)';
47 50
 
48 51
         return $this;
49 52
     }
50 53
 
51
-    public function byTask($task) {
54
+    public function byTask($task)
55
+    {
52 56
         $this->whereClause .= ' AND task = ?';
53 57
         $this->parameterList[] = $task;
54 58
 
55 59
         return $this;
56 60
     }
57 61
 
58
-    public function byUser($userId) {
62
+    public function byUser($userId)
63
+    {
59 64
         $this->whereClause .= ' AND user = ?';
60 65
         $this->parameterList[] = $userId;
61 66
 
62 67
         return $this;
63 68
     }
64 69
 
65
-    public function byStatus($status) {
70
+    public function byStatus($status)
71
+    {
66 72
         $this->whereClause .= ' AND status = ?';
67 73
         $this->parameterList[] = $status;
68 74
 
Please login to merge, or discard this patch.