Test Failed
Push — dependabot/composer/newinterna... ( fef629 )
by
unknown
16:20 queued 10:15
created
includes/Fragments/TemplateOutput.php 1 patch
Indentation   +80 added lines, -80 removed lines patch added patch discarded remove patch
@@ -15,95 +15,95 @@
 block discarded – undo
15 15
 
16 16
 trait TemplateOutput
17 17
 {
18
-    /** @var Smarty */
19
-    private $smarty;
20
-    /** @var string Extra JavaScript to include at the end of the page's execution */
21
-    private $tailScript;
22
-    /** @var string */
23
-    private $tailScriptNonce;
18
+	/** @var Smarty */
19
+	private $smarty;
20
+	/** @var string Extra JavaScript to include at the end of the page's execution */
21
+	private $tailScript;
22
+	/** @var string */
23
+	private $tailScriptNonce;
24 24
 
25
-    /**
26
-     * @return SiteConfiguration
27
-     */
28
-    protected abstract function getSiteConfiguration();
25
+	/**
26
+	 * @return SiteConfiguration
27
+	 */
28
+	protected abstract function getSiteConfiguration();
29 29
 
30
-    /**
31
-     * Include extra JavaScript at the end of the page's execution
32
-     *
33
-     * @param $nonce string CSP Nonce generated by ContentSecurityPolicyManager::getNonce()
34
-     * @param $script string JavaScript to include at the end of the page
35
-     */
36
-    final protected function setTailScript($nonce, $script)
37
-    {
38
-        $this->tailScriptNonce = $nonce;
39
-        $this->tailScript = $script;
40
-    }
30
+	/**
31
+	 * Include extra JavaScript at the end of the page's execution
32
+	 *
33
+	 * @param $nonce string CSP Nonce generated by ContentSecurityPolicyManager::getNonce()
34
+	 * @param $script string JavaScript to include at the end of the page
35
+	 */
36
+	final protected function setTailScript($nonce, $script)
37
+	{
38
+		$this->tailScriptNonce = $nonce;
39
+		$this->tailScript = $script;
40
+	}
41 41
 
42
-    /**
43
-     * Assigns a Smarty variable
44
-     *
45
-     * @param  array|string $name  the template variable name(s)
46
-     * @param  mixed        $value the value to assign
47
-     */
48
-    final protected function assign($name, $value)
49
-    {
50
-        $this->smarty->assign($name, $value);
51
-    }
42
+	/**
43
+	 * Assigns a Smarty variable
44
+	 *
45
+	 * @param  array|string $name  the template variable name(s)
46
+	 * @param  mixed        $value the value to assign
47
+	 */
48
+	final protected function assign($name, $value)
49
+	{
50
+		$this->smarty->assign($name, $value);
51
+	}
52 52
 
53
-    /**
54
-     * Sets up the variables used by the main Smarty base template.
55
-     *
56
-     * This list is getting kinda long.
57
-     */
58
-    final protected function setUpSmarty()
59
-    {
60
-        $this->smarty = new Smarty();
61
-        $this->smarty->addPluginsDir($this->getSiteConfiguration()->getFilePath() . '/smarty-plugins');
53
+	/**
54
+	 * Sets up the variables used by the main Smarty base template.
55
+	 *
56
+	 * This list is getting kinda long.
57
+	 */
58
+	final protected function setUpSmarty()
59
+	{
60
+		$this->smarty = new Smarty();
61
+		$this->smarty->addPluginsDir($this->getSiteConfiguration()->getFilePath() . '/smarty-plugins');
62 62
 
63
-        $this->assign('currentUser', User::getCommunity());
64
-        $this->assign('loggedIn', false);
65
-        $this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
66
-        $this->assign('mediawikiScriptPath', $this->getSiteConfiguration()->getMediawikiScriptPath());
63
+		$this->assign('currentUser', User::getCommunity());
64
+		$this->assign('loggedIn', false);
65
+		$this->assign('baseurl', $this->getSiteConfiguration()->getBaseUrl());
66
+		$this->assign('mediawikiScriptPath', $this->getSiteConfiguration()->getMediawikiScriptPath());
67 67
 
68
-        $this->assign('siteNoticeText', '');
69
-        $this->assign('siteNoticeVersion', 0);
70
-        $this->assign('siteNoticeState', 'd-none');
71
-        $this->assign('toolversion', Environment::getToolVersion());
68
+		$this->assign('siteNoticeText', '');
69
+		$this->assign('siteNoticeVersion', 0);
70
+		$this->assign('siteNoticeState', 'd-none');
71
+		$this->assign('toolversion', Environment::getToolVersion());
72 72
 
73
-        // default these
74
-        $this->assign('onlineusers', array());
75
-        $this->assign('typeAheadBlock', '');
76
-        $this->assign('extraJs', array());
73
+		// default these
74
+		$this->assign('onlineusers', array());
75
+		$this->assign('typeAheadBlock', '');
76
+		$this->assign('extraJs', array());
77 77
 
78
-        // nav menu access control
79
-        $this->assign('nav__canRequests', false);
80
-        $this->assign('nav__canLogs', false);
81
-        $this->assign('nav__canUsers', false);
82
-        $this->assign('nav__canSearch', false);
83
-        $this->assign('nav__canStats', false);
84
-        $this->assign('nav__canBan', false);
85
-        $this->assign('nav__canEmailMgmt', false);
86
-        $this->assign('nav__canWelcomeMgmt', false);
87
-        $this->assign('nav__canSiteNoticeMgmt', false);
88
-        $this->assign('nav__canUserMgmt', false);
89
-        $this->assign('nav__canViewRequest', false);
90
-        $this->assign('nav__canJobQueue', false);
78
+		// nav menu access control
79
+		$this->assign('nav__canRequests', false);
80
+		$this->assign('nav__canLogs', false);
81
+		$this->assign('nav__canUsers', false);
82
+		$this->assign('nav__canSearch', false);
83
+		$this->assign('nav__canStats', false);
84
+		$this->assign('nav__canBan', false);
85
+		$this->assign('nav__canEmailMgmt', false);
86
+		$this->assign('nav__canWelcomeMgmt', false);
87
+		$this->assign('nav__canSiteNoticeMgmt', false);
88
+		$this->assign('nav__canUserMgmt', false);
89
+		$this->assign('nav__canViewRequest', false);
90
+		$this->assign('nav__canJobQueue', false);
91 91
 
92
-        $this->assign('page', $this);
93
-    }
92
+		$this->assign('page', $this);
93
+	}
94 94
 
95
-    /**
96
-     * Fetches a rendered Smarty template
97
-     *
98
-     * @param $template string Template file path, relative to /templates/
99
-     *
100
-     * @return string Templated HTML
101
-     */
102
-    final protected function fetchTemplate($template)
103
-    {
104
-        $this->assign('tailScript', $this->tailScript);
105
-        $this->assign('tailScriptNonce', $this->tailScriptNonce);
95
+	/**
96
+	 * Fetches a rendered Smarty template
97
+	 *
98
+	 * @param $template string Template file path, relative to /templates/
99
+	 *
100
+	 * @return string Templated HTML
101
+	 */
102
+	final protected function fetchTemplate($template)
103
+	{
104
+		$this->assign('tailScript', $this->tailScript);
105
+		$this->assign('tailScriptNonce', $this->tailScriptNonce);
106 106
 
107
-        return $this->smarty->fetch($template);
108
-    }
107
+		return $this->smarty->fetch($template);
108
+	}
109 109
 }
Please login to merge, or discard this patch.
includes/Helpers/TypeAheadHelper.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -12,21 +12,21 @@  discard block
 block discarded – undo
12 12
 
13 13
 class TypeAheadHelper implements ITypeAheadHelper
14 14
 {
15
-    private $definedClasses = array();
15
+	private $definedClasses = array();
16 16
 
17
-    /**
18
-     * @param string   $class     CSS class to apply this typeahead to.
19
-     * @param callable $generator Generator function taking no arguments to return an array of strings.
20
-     */
21
-    public function defineTypeAheadSource($class, callable $generator)
22
-    {
23
-        $dataList = '';
24
-        foreach ($generator() as $dataItem) {
25
-            $dataList .= '"' . htmlentities($dataItem) . '", ';
26
-        }
27
-        $dataList = "[" . rtrim($dataList, ", ") . "]";
17
+	/**
18
+	 * @param string   $class     CSS class to apply this typeahead to.
19
+	 * @param callable $generator Generator function taking no arguments to return an array of strings.
20
+	 */
21
+	public function defineTypeAheadSource($class, callable $generator)
22
+	{
23
+		$dataList = '';
24
+		foreach ($generator() as $dataItem) {
25
+			$dataList .= '"' . htmlentities($dataItem) . '", ';
26
+		}
27
+		$dataList = "[" . rtrim($dataList, ", ") . "]";
28 28
 
29
-        $script = <<<JS
29
+		$script = <<<JS
30 30
 
31 31
 $('.{$class}').typeahead({
32 32
         hint: true,
@@ -39,32 +39,32 @@  discard block
 block discarded – undo
39 39
 })
40 40
 ;
41 41
 JS;
42
-        $this->definedClasses[$class] = $script;
43
-    }
42
+		$this->definedClasses[$class] = $script;
43
+	}
44 44
 
45
-    /**
46
-     * @return string HTML fragment containing a JS block for typeaheads.
47
-     */
48
-    public function getTypeAheadScriptBlock()
49
-    {
50
-        $jsBlocks = '';
45
+	/**
46
+	 * @return string HTML fragment containing a JS block for typeaheads.
47
+	 */
48
+	public function getTypeAheadScriptBlock()
49
+	{
50
+		$jsBlocks = '';
51 51
 
52
-        if (count($this->definedClasses) === 0) {
53
-            return '';
54
-        }
52
+		if (count($this->definedClasses) === 0) {
53
+			return '';
54
+		}
55 55
 
56
-        foreach ($this->definedClasses as $class => $js) {
57
-            $jsBlocks = $js . "\r\n\r\n";
58
-        }
56
+		foreach ($this->definedClasses as $class => $js) {
57
+			$jsBlocks = $js . "\r\n\r\n";
58
+		}
59 59
 
60
-        $data = <<<HTML
60
+		$data = <<<HTML
61 61
 <script type="text/javascript">
62 62
 	{$jsBlocks}
63 63
 </script>
64 64
 HTML;
65 65
 
66
-        $this->definedClasses = array();
66
+		$this->definedClasses = array();
67 67
 
68
-        return $data;
69
-    }
68
+		return $data;
69
+	}
70 70
 }
Please login to merge, or discard this patch.
includes/Helpers/RequestEmailHelper.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -14,50 +14,50 @@
 block discarded – undo
14 14
 
15 15
 class RequestEmailHelper
16 16
 {
17
-    /**
18
-     * @var IEmailHelper
19
-     */
20
-    private $emailHelper;
21
-
22
-    /**
23
-     * RequestEmailHelper constructor.
24
-     *
25
-     * @param IEmailHelper $emailHelper
26
-     */
27
-    public function __construct(IEmailHelper $emailHelper)
28
-    {
29
-        $this->emailHelper = $emailHelper;
30
-    }
31
-
32
-    /**
33
-     * @param Request $request
34
-     * @param string  $mailText
35
-     * @param User    $currentUser
36
-     * @param boolean $ccMailingList
37
-     */
38
-    public function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
39
-    {
40
-        $headers = array(
41
-            'X-ACC-Request' => $request->getId(),
42
-            'X-ACC-UserID'  => $currentUser->getId(),
43
-        );
44
-
45
-        if ($ccMailingList) {
46
-            $headers['Cc'] = '[email protected]';
47
-        }
48
-
49
-        $helper = $this->emailHelper;
50
-
51
-        $emailSig = $currentUser->getEmailSig();
52
-        if ($emailSig !== '' || $emailSig !== null) {
53
-            $emailSig = "\n\n" . $emailSig;
54
-        }
55
-
56
-        $subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
57
-        $content = $mailText . $emailSig;
58
-
59
-        $helper->sendMail($request->getEmail(), $subject, $content, $headers);
60
-
61
-        $request->setEmailSent(true);
62
-    }
17
+	/**
18
+	 * @var IEmailHelper
19
+	 */
20
+	private $emailHelper;
21
+
22
+	/**
23
+	 * RequestEmailHelper constructor.
24
+	 *
25
+	 * @param IEmailHelper $emailHelper
26
+	 */
27
+	public function __construct(IEmailHelper $emailHelper)
28
+	{
29
+		$this->emailHelper = $emailHelper;
30
+	}
31
+
32
+	/**
33
+	 * @param Request $request
34
+	 * @param string  $mailText
35
+	 * @param User    $currentUser
36
+	 * @param boolean $ccMailingList
37
+	 */
38
+	public function sendMail(Request $request, $mailText, User $currentUser, $ccMailingList)
39
+	{
40
+		$headers = array(
41
+			'X-ACC-Request' => $request->getId(),
42
+			'X-ACC-UserID'  => $currentUser->getId(),
43
+		);
44
+
45
+		if ($ccMailingList) {
46
+			$headers['Cc'] = '[email protected]';
47
+		}
48
+
49
+		$helper = $this->emailHelper;
50
+
51
+		$emailSig = $currentUser->getEmailSig();
52
+		if ($emailSig !== '' || $emailSig !== null) {
53
+			$emailSig = "\n\n" . $emailSig;
54
+		}
55
+
56
+		$subject = "RE: [ACC #{$request->getId()}] English Wikipedia Account Request";
57
+		$content = $mailText . $emailSig;
58
+
59
+		$helper->sendMail($request->getEmail(), $subject, $content, $headers);
60
+
61
+		$request->setEmailSent(true);
62
+	}
63 63
 }
Please login to merge, or discard this patch.
includes/Helpers/OAuthProtocolHelper.php 2 patches
Indentation   +91 added lines, -91 removed lines patch added patch discarded remove patch
@@ -16,95 +16,95 @@
 block discarded – undo
16 16
 
17 17
 class OAuthProtocolHelper implements Interfaces\IOAuthProtocolHelper
18 18
 {
19
-    private $oauthClient;
20
-
21
-    private $mediawikiWebServiceEndpoint;
22
-
23
-    private $authUrl;
24
-
25
-    /**
26
-     * OAuthHelper constructor.
27
-     *
28
-     * @param string     $oauthEndpoint
29
-     * @param string     $consumerKey
30
-     * @param string     $consumerSecret
31
-     * @param string     $mediawikiWebServiceEndpoint
32
-     */
33
-    public function __construct(
34
-        $oauthEndpoint,
35
-        $consumerKey,
36
-        $consumerSecret,
37
-        $mediawikiWebServiceEndpoint
38
-    ) {
39
-        $this->mediawikiWebServiceEndpoint = $mediawikiWebServiceEndpoint;
40
-
41
-        $oauthClientConfig = new ClientConfig($oauthEndpoint);
42
-        $oauthClientConfig->setConsumer(new Consumer($consumerKey, $consumerSecret));
43
-
44
-        $this->oauthClient = new Client($oauthClientConfig);
45
-    }
46
-
47
-    /**
48
-     * @inheritDoc
49
-     */
50
-    public function getRequestToken()
51
-    {
52
-        /** @var Token $requestToken */
53
-        list($authUrl, $requestToken) = $this->oauthClient->initiate();
54
-        $this->authUrl = $authUrl;
55
-        return $requestToken;
56
-    }
57
-
58
-    /**
59
-     * @inheritDoc
60
-     */
61
-    public function getAuthoriseUrl($requestToken)
62
-    {
63
-        return $this->authUrl;
64
-    }
65
-
66
-    /**
67
-     * @inheritDoc
68
-     */
69
-    public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier)
70
-    {
71
-        $requestToken = new Token($oauthRequestToken, $oauthRequestSecret);
72
-
73
-        return $this->oauthClient->complete($requestToken, $oauthVerifier);
74
-    }
75
-
76
-    /**
77
-     * @inheritDoc
78
-     */
79
-    public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret)
80
-    {
81
-        return $this->oauthClient->identify(new Token($oauthAccessToken, $oauthAccessSecret));
82
-    }
83
-
84
-    /**
85
-     * @inheritDoc
86
-     */
87
-    public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET')
88
-    {
89
-        $userToken = new Token($accessToken, $accessSecret);
90
-
91
-        $apiParams['format'] = 'json';
92
-
93
-        if ($apiParams === null || ! is_array($apiParams)) {
94
-            throw new CurlException("Invalid API call");
95
-        }
96
-
97
-        $url = $this->mediawikiWebServiceEndpoint;
98
-        $isPost = ($method === 'POST');
99
-
100
-        if ($method === 'GET') {
101
-            $query = http_build_query($apiParams);
102
-            $url .= '?' . $query;
103
-            $apiParams = null;
104
-        }
105
-
106
-        $data = $this->oauthClient->makeOAuthCall($userToken, $url, $isPost, $apiParams);
107
-
108
-        return json_decode($data);
109
-    }
19
+	private $oauthClient;
20
+
21
+	private $mediawikiWebServiceEndpoint;
22
+
23
+	private $authUrl;
24
+
25
+	/**
26
+	 * OAuthHelper constructor.
27
+	 *
28
+	 * @param string     $oauthEndpoint
29
+	 * @param string     $consumerKey
30
+	 * @param string     $consumerSecret
31
+	 * @param string     $mediawikiWebServiceEndpoint
32
+	 */
33
+	public function __construct(
34
+		$oauthEndpoint,
35
+		$consumerKey,
36
+		$consumerSecret,
37
+		$mediawikiWebServiceEndpoint
38
+	) {
39
+		$this->mediawikiWebServiceEndpoint = $mediawikiWebServiceEndpoint;
40
+
41
+		$oauthClientConfig = new ClientConfig($oauthEndpoint);
42
+		$oauthClientConfig->setConsumer(new Consumer($consumerKey, $consumerSecret));
43
+
44
+		$this->oauthClient = new Client($oauthClientConfig);
45
+	}
46
+
47
+	/**
48
+	 * @inheritDoc
49
+	 */
50
+	public function getRequestToken()
51
+	{
52
+		/** @var Token $requestToken */
53
+		list($authUrl, $requestToken) = $this->oauthClient->initiate();
54
+		$this->authUrl = $authUrl;
55
+		return $requestToken;
56
+	}
57
+
58
+	/**
59
+	 * @inheritDoc
60
+	 */
61
+	public function getAuthoriseUrl($requestToken)
62
+	{
63
+		return $this->authUrl;
64
+	}
65
+
66
+	/**
67
+	 * @inheritDoc
68
+	 */
69
+	public function callbackCompleted($oauthRequestToken, $oauthRequestSecret, $oauthVerifier)
70
+	{
71
+		$requestToken = new Token($oauthRequestToken, $oauthRequestSecret);
72
+
73
+		return $this->oauthClient->complete($requestToken, $oauthVerifier);
74
+	}
75
+
76
+	/**
77
+	 * @inheritDoc
78
+	 */
79
+	public function getIdentityTicket($oauthAccessToken, $oauthAccessSecret)
80
+	{
81
+		return $this->oauthClient->identify(new Token($oauthAccessToken, $oauthAccessSecret));
82
+	}
83
+
84
+	/**
85
+	 * @inheritDoc
86
+	 */
87
+	public function apiCall($apiParams, $accessToken, $accessSecret, $method = 'GET')
88
+	{
89
+		$userToken = new Token($accessToken, $accessSecret);
90
+
91
+		$apiParams['format'] = 'json';
92
+
93
+		if ($apiParams === null || ! is_array($apiParams)) {
94
+			throw new CurlException("Invalid API call");
95
+		}
96
+
97
+		$url = $this->mediawikiWebServiceEndpoint;
98
+		$isPost = ($method === 'POST');
99
+
100
+		if ($method === 'GET') {
101
+			$query = http_build_query($apiParams);
102
+			$url .= '?' . $query;
103
+			$apiParams = null;
104
+		}
105
+
106
+		$data = $this->oauthClient->makeOAuthCall($userToken, $url, $isPost, $apiParams);
107
+
108
+		return json_decode($data);
109
+	}
110 110
 }
111 111
\ No newline at end of file
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -90,7 +90,7 @@
 block discarded – undo
90 90
 
91 91
         $apiParams['format'] = 'json';
92 92
 
93
-        if ($apiParams === null || ! is_array($apiParams)) {
93
+        if ($apiParams === null || !is_array($apiParams)) {
94 94
             throw new CurlException("Invalid API call");
95 95
         }
96 96
 
Please login to merge, or discard this patch.
includes/Helpers/BotMediaWikiClient.php 3 patches
Indentation   +131 added lines, -131 removed lines patch added patch discarded remove patch
@@ -16,135 +16,135 @@
 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,
46
-            $siteConfiguration->getCurlCookieJar()
47
-        );
48
-    }
49
-
50
-    public function doApiCall($apiParams, $method = 'GET')
51
-    {
52
-        $this->ensureLoggedIn();
53
-        $apiParams['assert'] = 'user';
54
-
55
-        return $this->callApi($apiParams, $method);
56
-    }
57
-
58
-    private function ensureLoggedIn()
59
-    {
60
-        if ($this->knownLoggedIn) {
61
-            return;
62
-        }
63
-
64
-        $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
65
-        if (isset($userinfoResult->query->userinfo->anon)) {
66
-            // not logged in.
67
-            $this->logIn();
68
-
69
-            // retest
70
-            $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
71
-            if (isset($userinfoResult->query->userinfo->anon)) {
72
-                throw new MediaWikiApiException('Unable to log in.');
73
-            }
74
-            else {
75
-                $this->knownLoggedIn = true;
76
-            }
77
-        }
78
-        else {
79
-            $this->knownLoggedIn = true;
80
-        }
81
-    }
82
-
83
-    /**
84
-     * @param $apiParams
85
-     * @param $method
86
-     *
87
-     * @return mixed
88
-     * @throws ApplicationLogicException
89
-     * @throws CurlException
90
-     */
91
-    private function callApi($apiParams, $method)
92
-    {
93
-        $apiParams['format'] = 'json';
94
-
95
-        if ($method == 'GET') {
96
-            $data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
97
-        }
98
-        elseif ($method == 'POST') {
99
-            $data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
100
-        }
101
-        else {
102
-            throw new ApplicationLogicException('Unsupported HTTP Method');
103
-        }
104
-
105
-        if ($data === false) {
106
-            throw new CurlException('Curl error: ' . $this->httpHelper->getError());
107
-        }
108
-
109
-        $result = json_decode($data);
110
-
111
-        return $result;
112
-    }
113
-
114
-    private function logIn()
115
-    {
116
-        // get token
117
-        $tokenParams = array(
118
-            'action' => 'query',
119
-            'meta'   => 'tokens',
120
-            'type'   => 'login',
121
-        );
122
-
123
-        $response = $this->callApi($tokenParams, 'POST');
124
-
125
-        if (isset($response->error)) {
126
-            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
127
-        }
128
-
129
-        $token = $response->query->tokens->logintoken;
130
-
131
-        if ($token === null) {
132
-            throw new MediaWikiApiException('Edit token could not be acquired');
133
-        }
134
-
135
-        $params = array(
136
-            'action' => 'login',
137
-            'lgname' => $this->creationBotUsername,
138
-            'lgpassword' => $this->creationBotPassword,
139
-            'lgtoken' => $token,
140
-        );
141
-
142
-        $loginResponse = $this->callApi($params, 'POST');
143
-
144
-        if($loginResponse->login->result == 'Success'){
145
-            return;
146
-        }
147
-
148
-        throw new ApplicationLogicException(json_encode($loginResponse));
149
-    }
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,
46
+			$siteConfiguration->getCurlCookieJar()
47
+		);
48
+	}
49
+
50
+	public function doApiCall($apiParams, $method = 'GET')
51
+	{
52
+		$this->ensureLoggedIn();
53
+		$apiParams['assert'] = 'user';
54
+
55
+		return $this->callApi($apiParams, $method);
56
+	}
57
+
58
+	private function ensureLoggedIn()
59
+	{
60
+		if ($this->knownLoggedIn) {
61
+			return;
62
+		}
63
+
64
+		$userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
65
+		if (isset($userinfoResult->query->userinfo->anon)) {
66
+			// not logged in.
67
+			$this->logIn();
68
+
69
+			// retest
70
+			$userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
71
+			if (isset($userinfoResult->query->userinfo->anon)) {
72
+				throw new MediaWikiApiException('Unable to log in.');
73
+			}
74
+			else {
75
+				$this->knownLoggedIn = true;
76
+			}
77
+		}
78
+		else {
79
+			$this->knownLoggedIn = true;
80
+		}
81
+	}
82
+
83
+	/**
84
+	 * @param $apiParams
85
+	 * @param $method
86
+	 *
87
+	 * @return mixed
88
+	 * @throws ApplicationLogicException
89
+	 * @throws CurlException
90
+	 */
91
+	private function callApi($apiParams, $method)
92
+	{
93
+		$apiParams['format'] = 'json';
94
+
95
+		if ($method == 'GET') {
96
+			$data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
97
+		}
98
+		elseif ($method == 'POST') {
99
+			$data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
100
+		}
101
+		else {
102
+			throw new ApplicationLogicException('Unsupported HTTP Method');
103
+		}
104
+
105
+		if ($data === false) {
106
+			throw new CurlException('Curl error: ' . $this->httpHelper->getError());
107
+		}
108
+
109
+		$result = json_decode($data);
110
+
111
+		return $result;
112
+	}
113
+
114
+	private function logIn()
115
+	{
116
+		// get token
117
+		$tokenParams = array(
118
+			'action' => 'query',
119
+			'meta'   => 'tokens',
120
+			'type'   => 'login',
121
+		);
122
+
123
+		$response = $this->callApi($tokenParams, 'POST');
124
+
125
+		if (isset($response->error)) {
126
+			throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
127
+		}
128
+
129
+		$token = $response->query->tokens->logintoken;
130
+
131
+		if ($token === null) {
132
+			throw new MediaWikiApiException('Edit token could not be acquired');
133
+		}
134
+
135
+		$params = array(
136
+			'action' => 'login',
137
+			'lgname' => $this->creationBotUsername,
138
+			'lgpassword' => $this->creationBotPassword,
139
+			'lgtoken' => $token,
140
+		);
141
+
142
+		$loginResponse = $this->callApi($params, 'POST');
143
+
144
+		if($loginResponse->login->result == 'Success'){
145
+			return;
146
+		}
147
+
148
+		throw new ApplicationLogicException(json_encode($loginResponse));
149
+	}
150 150
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -141,7 +141,7 @@
 block discarded – undo
141 141
 
142 142
         $loginResponse = $this->callApi($params, 'POST');
143 143
 
144
-        if($loginResponse->login->result == 'Success'){
144
+        if ($loginResponse->login->result == 'Success') {
145 145
             return;
146 146
         }
147 147
 
Please login to merge, or discard this patch.
Braces   +5 added lines, -9 removed lines patch added patch discarded remove patch
@@ -70,12 +70,10 @@  discard block
 block discarded – undo
70 70
             $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
71 71
             if (isset($userinfoResult->query->userinfo->anon)) {
72 72
                 throw new MediaWikiApiException('Unable to log in.');
73
-            }
74
-            else {
73
+            } else {
75 74
                 $this->knownLoggedIn = true;
76 75
             }
77
-        }
78
-        else {
76
+        } else {
79 77
             $this->knownLoggedIn = true;
80 78
         }
81 79
     }
@@ -94,11 +92,9 @@  discard block
 block discarded – undo
94 92
 
95 93
         if ($method == 'GET') {
96 94
             $data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
97
-        }
98
-        elseif ($method == 'POST') {
95
+        } elseif ($method == 'POST') {
99 96
             $data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
100
-        }
101
-        else {
97
+        } else {
102 98
             throw new ApplicationLogicException('Unsupported HTTP Method');
103 99
         }
104 100
 
@@ -141,7 +137,7 @@  discard block
 block discarded – undo
141 137
 
142 138
         $loginResponse = $this->callApi($params, 'POST');
143 139
 
144
-        if($loginResponse->login->result == 'Success'){
140
+        if($loginResponse->login->result == 'Success') {
145 141
             return;
146 142
         }
147 143
 
Please login to merge, or discard this patch.
includes/Helpers/MediaWikiHelper.php 2 patches
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.
Braces   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -228,8 +228,7 @@  discard block
 block discarded – undo
228 228
                 foreach ($req->fields as $name => $data) {
229 229
                     if ($data->type === 'checkbox') {
230 230
                         $checkboxFields[] = $name;
231
-                    }
232
-                    else {
231
+                    } else {
233 232
                         $requiredFields[] = $name;
234 233
                     }
235 234
                 }
@@ -241,7 +240,8 @@  discard block
 block discarded – undo
241 240
      * @param string $username
242 241
      * @return bool
243 242
      */
244
-    public function checkAccountExists($username) {
243
+    public function checkAccountExists($username)
244
+    {
245 245
         $parameters = array(
246 246
             'action'  => 'query',
247 247
             'list'    => 'users',
Please login to merge, or discard this patch.
includes/Helpers/OAuthUserHelper.php 2 patches
Indentation   +431 added lines, -431 removed lines patch added patch discarded remove patch
@@ -24,439 +24,439 @@
 block discarded – undo
24 24
 
25 25
 class OAuthUserHelper implements IMediaWikiClient
26 26
 {
27
-    const TOKEN_REQUEST = 'request';
28
-    const TOKEN_ACCESS = 'access';
29
-    /** @var PDOStatement */
30
-    private static $tokenCountStatement = null;
31
-    /** @var PDOStatement */
32
-    private $getTokenStatement;
33
-    /**
34
-     * @var User
35
-     */
36
-    private $user;
37
-    /**
38
-     * @var PdoDatabase
39
-     */
40
-    private $database;
41
-    /**
42
-     * @var IOAuthProtocolHelper
43
-     */
44
-    private $oauthProtocolHelper;
45
-    /**
46
-     * @var bool|null Is the user linked to OAuth
47
-     */
48
-    private $linked;
49
-    private $partiallyLinked;
50
-    /** @var OAuthToken */
51
-    private $accessToken;
52
-    /** @var bool */
53
-    private $accessTokenLoaded = false;
54
-    /**
55
-     * @var OAuthIdentity
56
-     */
57
-    private $identity = null;
58
-    /**
59
-     * @var bool
60
-     */
61
-    private $identityLoaded = false;
62
-    /**
63
-     * @var SiteConfiguration
64
-     */
65
-    private $siteConfiguration;
66
-
67
-    #region Static methods
68
-    public static function findUserByRequestToken($requestToken, PdoDatabase $database)
69
-    {
70
-        $statement = $database->prepare(<<<'SQL'
27
+	const TOKEN_REQUEST = 'request';
28
+	const TOKEN_ACCESS = 'access';
29
+	/** @var PDOStatement */
30
+	private static $tokenCountStatement = null;
31
+	/** @var PDOStatement */
32
+	private $getTokenStatement;
33
+	/**
34
+	 * @var User
35
+	 */
36
+	private $user;
37
+	/**
38
+	 * @var PdoDatabase
39
+	 */
40
+	private $database;
41
+	/**
42
+	 * @var IOAuthProtocolHelper
43
+	 */
44
+	private $oauthProtocolHelper;
45
+	/**
46
+	 * @var bool|null Is the user linked to OAuth
47
+	 */
48
+	private $linked;
49
+	private $partiallyLinked;
50
+	/** @var OAuthToken */
51
+	private $accessToken;
52
+	/** @var bool */
53
+	private $accessTokenLoaded = false;
54
+	/**
55
+	 * @var OAuthIdentity
56
+	 */
57
+	private $identity = null;
58
+	/**
59
+	 * @var bool
60
+	 */
61
+	private $identityLoaded = false;
62
+	/**
63
+	 * @var SiteConfiguration
64
+	 */
65
+	private $siteConfiguration;
66
+
67
+	#region Static methods
68
+	public static function findUserByRequestToken($requestToken, PdoDatabase $database)
69
+	{
70
+		$statement = $database->prepare(<<<'SQL'
71 71
             SELECT u.* FROM user u 
72 72
             INNER JOIN oauthtoken t ON t.user = u.id 
73 73
             WHERE t.type = :type AND t.token = :token
74 74
 SQL
75
-        );
76
-        $statement->execute(array(':type' => self::TOKEN_REQUEST, ':token' => $requestToken));
77
-
78
-        /** @var User $user */
79
-        $user = $statement->fetchObject(User::class);
80
-        $statement->closeCursor();
81
-
82
-        if ($user === false) {
83
-            throw new ApplicationLogicException('Token not found in store, please try again');
84
-        }
85
-
86
-        $user->setDatabase($database);
87
-
88
-        return $user;
89
-    }
90
-
91
-    public static function userIsFullyLinked(User $user, PdoDatabase $database = null)
92
-    {
93
-        if (self::$tokenCountStatement === null && $database === null) {
94
-            throw new ApplicationLogicException('Static link request without initialised statement');
95
-        }
96
-
97
-        return self::runTokenCount($user->getId(), $database, self::TOKEN_ACCESS);
98
-    }
99
-
100
-    public static function userIsPartiallyLinked(User $user, PdoDatabase $database = null)
101
-    {
102
-        if (self::$tokenCountStatement === null && $database === null) {
103
-            throw new ApplicationLogicException('Static link request without initialised statement');
104
-        }
105
-
106
-        if (self::userIsFullyLinked($user, $database)) {
107
-            return false;
108
-        }
109
-
110
-        return self::runTokenCount($user->getId(), $database, self::TOKEN_REQUEST)
111
-            || $user->getOnWikiName() == null;
112
-    }
113
-
114
-    /**
115
-     * @param PdoDatabase $database
116
-     */
117
-    public static function prepareTokenCountStatement(PdoDatabase $database)
118
-    {
119
-        if (self::$tokenCountStatement === null) {
120
-            self::$tokenCountStatement = $database->prepare('SELECT COUNT(*) FROM oauthtoken WHERE user = :user AND type = :type');
121
-        }
122
-    }
123
-
124
-    private static function runTokenCount($userId, $database, $tokenType)
125
-    {
126
-        if (self::$tokenCountStatement === null) {
127
-            self::prepareTokenCountStatement($database);
128
-        }
129
-
130
-        self::$tokenCountStatement->execute(array(
131
-            ':user' => $userId,
132
-            ':type' => $tokenType,
133
-        ));
134
-
135
-        $tokenCount = self::$tokenCountStatement->fetchColumn();
136
-        $linked = $tokenCount > 0;
137
-        self::$tokenCountStatement->closeCursor();
138
-
139
-        return $linked;
140
-    }
141
-
142
-    #endregion Static methods
143
-
144
-    /**
145
-     * OAuthUserHelper constructor.
146
-     *
147
-     * @param User                 $user
148
-     * @param PdoDatabase          $database
149
-     * @param IOAuthProtocolHelper $oauthProtocolHelper
150
-     * @param SiteConfiguration    $siteConfiguration
151
-     */
152
-    public function __construct(
153
-        User $user,
154
-        PdoDatabase $database,
155
-        IOAuthProtocolHelper $oauthProtocolHelper,
156
-        SiteConfiguration $siteConfiguration
157
-    ) {
158
-        $this->user = $user;
159
-        $this->database = $database;
160
-        $this->oauthProtocolHelper = $oauthProtocolHelper;
161
-
162
-        $this->linked = null;
163
-        $this->partiallyLinked = null;
164
-        $this->siteConfiguration = $siteConfiguration;
165
-
166
-        self::prepareTokenCountStatement($database);
167
-        $this->getTokenStatement = $this->database->prepare('SELECT * FROM oauthtoken WHERE user = :user AND type = :type');
168
-    }
169
-
170
-    /**
171
-     * Determines if the user is fully connected to OAuth.
172
-     *
173
-     * @return bool
174
-     */
175
-    public function isFullyLinked()
176
-    {
177
-        if ($this->linked === null) {
178
-            $this->linked = self::userIsFullyLinked($this->user, $this->database);
179
-        }
180
-
181
-        return $this->linked;
182
-    }
183
-
184
-    /**
185
-     * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
186
-     * procedure before configuring.
187
-     * @return bool
188
-     */
189
-    public function isPartiallyLinked()
190
-    {
191
-        if ($this->partiallyLinked === null) {
192
-            $this->partiallyLinked = self::userIsPartiallyLinked($this->user, $this->database);
193
-        }
194
-
195
-        return $this->partiallyLinked;
196
-    }
197
-
198
-    public function canCreateAccount() {
199
-        return $this->isFullyLinked()
200
-            && $this->getIdentity(true)->getGrantBasic()
201
-            && $this->getIdentity(true)->getGrantHighVolume()
202
-            && $this->getIdentity(true)->getGrantCreateAccount();
203
-    }
204
-
205
-    public function canWelcome() {
206
-        return $this->isFullyLinked()
207
-            && $this->getIdentity(true)->getGrantBasic()
208
-            && $this->getIdentity(true)->getGrantHighVolume()
209
-            && $this->getIdentity(true)->getGrantCreateEditMovePage();
210
-    }
211
-
212
-    /**
213
-     * @throws OAuthException
214
-     * @throws CurlException
215
-     * @throws OptimisticLockFailedException
216
-     */
217
-    public function refreshIdentity()
218
-    {
219
-        $this->loadIdentity();
220
-
221
-        if ($this->identity === null) {
222
-            $this->identity = new OAuthIdentity();
223
-            $this->identity->setUserId($this->user->getId());
224
-            $this->identity->setDatabase($this->database);
225
-        }
226
-
227
-        $token = $this->loadAccessToken();
228
-
229
-        $rawTicket = $this->oauthProtocolHelper->getIdentityTicket($token->getToken(), $token->getSecret());
230
-
231
-        $this->identity->populate($rawTicket);
232
-
233
-        if (!$this->identityIsValid()) {
234
-            throw new OAuthException('Identity ticket is not valid!');
235
-        }
236
-
237
-        $this->identity->save();
238
-
239
-        $this->user->setOnWikiName($this->identity->getUsername());
240
-        $this->user->save();
241
-    }
242
-
243
-    /**
244
-     * @return string
245
-     * @throws CurlException
246
-     */
247
-    public function getRequestToken()
248
-    {
249
-        $token = $this->oauthProtocolHelper->getRequestToken();
250
-
251
-        $this->partiallyLinked = true;
252
-        $this->linked = false;
253
-
254
-        $this->database
255
-            ->prepare('DELETE FROM oauthtoken WHERE user = :user AND type = :type')
256
-            ->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
257
-
258
-        $this->database
259
-            ->prepare('INSERT INTO oauthtoken (user, type, token, secret, expiry) VALUES (:user, :type, :token, :secret, DATE_ADD(NOW(), INTERVAL 1 DAY))')
260
-            ->execute(array(
261
-                ':user'   => $this->user->getId(),
262
-                ':type'   => self::TOKEN_REQUEST,
263
-                ':token'  => $token->key,
264
-                ':secret' => $token->secret,
265
-            ));
266
-
267
-        return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
268
-    }
269
-
270
-    /**
271
-     * @param $verificationToken
272
-     *
273
-     * @throws ApplicationLogicException
274
-     * @throws CurlException
275
-     * @throws OAuthException
276
-     * @throws OptimisticLockFailedException
277
-     */
278
-    public function completeHandshake($verificationToken)
279
-    {
280
-        $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
281
-
282
-        /** @var OAuthToken $token */
283
-        $token = $this->getTokenStatement->fetchObject(OAuthToken::class);
284
-        $this->getTokenStatement->closeCursor();
285
-
286
-        if ($token === false) {
287
-            throw new ApplicationLogicException('Cannot find request token');
288
-        }
289
-
290
-        $token->setDatabase($this->database);
291
-
292
-        $accessToken = $this->oauthProtocolHelper->callbackCompleted($token->getToken(), $token->getSecret(),
293
-            $verificationToken);
294
-
295
-        $clearStatement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :u AND type = :t');
296
-        $clearStatement->execute(array(':u' => $this->user->getId(), ':t' => self::TOKEN_ACCESS));
297
-
298
-        $token->setToken($accessToken->key);
299
-        $token->setSecret($accessToken->secret);
300
-        $token->setType(self::TOKEN_ACCESS);
301
-        $token->setExpiry(null);
302
-        $token->save();
303
-
304
-        $this->partiallyLinked = false;
305
-        $this->linked = true;
306
-
307
-        $this->refreshIdentity();
308
-    }
309
-
310
-    public function detach()
311
-    {
312
-        $this->loadIdentity();
313
-
314
-        $this->identity->delete();
315
-        $statement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :user');
316
-        $statement->execute(array(':user' => $this->user->getId()));
317
-
318
-        $this->identity = null;
319
-        $this->linked = false;
320
-        $this->partiallyLinked = false;
321
-    }
322
-
323
-    /**
324
-     * @param bool $expiredOk
325
-     *
326
-     * @return OAuthIdentity
327
-     * @throws OAuthException
328
-     */
329
-    public function getIdentity($expiredOk = false)
330
-    {
331
-        $this->loadIdentity();
332
-
333
-        if (!$this->identityIsValid($expiredOk)) {
334
-            throw new OAuthException('Stored identity is not valid.');
335
-        }
336
-
337
-        return $this->identity;
338
-    }
339
-
340
-    public function doApiCall($params, $method)
341
-    {
342
-        // Ensure we're logged in
343
-        $params['assert'] = 'user';
344
-
345
-        $token = $this->loadAccessToken();
346
-        return $this->oauthProtocolHelper->apiCall($params, $token->getToken(), $token->getSecret(), $method);
347
-    }
348
-
349
-    /**
350
-     * @param bool $expiredOk
351
-     *
352
-     * @return bool
353
-     */
354
-    private function identityIsValid($expiredOk = false)
355
-    {
356
-        $this->loadIdentity();
357
-
358
-        if ($this->identity === null) {
359
-            return false;
360
-        }
361
-
362
-        if ($this->identity->getIssuedAtTime() === false
363
-            || $this->identity->getExpirationTime() === false
364
-            || $this->identity->getAudience() === false
365
-            || $this->identity->getIssuer() === false
366
-        ) {
367
-            // this isn't populated properly.
368
-            return false;
369
-        }
370
-
371
-        $issue = DateTimeImmutable::createFromFormat("U", $this->identity->getIssuedAtTime());
372
-        $now = new DateTimeImmutable();
373
-
374
-        if ($issue > $now) {
375
-            // wat.
376
-            return false;
377
-        }
378
-
379
-        if ($this->identityExpired() && !$expiredOk) {
380
-            // soz.
381
-            return false;
382
-        }
383
-
384
-        if ($this->identity->getAudience() !== $this->siteConfiguration->getOAuthConsumerToken()) {
385
-            // token not issued for us
386
-            return false;
387
-        }
388
-
389
-        if ($this->identity->getIssuer() !== $this->siteConfiguration->getOauthMediaWikiCanonicalServer()) {
390
-            // token not issued by the right person
391
-            return false;
392
-        }
393
-
394
-        // can't find a reason to not trust it
395
-        return true;
396
-    }
397
-
398
-    /**
399
-     * @return bool
400
-     */
401
-    public function identityExpired()
402
-    {
403
-        // allowed max age
404
-        $gracePeriod = $this->siteConfiguration->getOauthIdentityGraceTime();
405
-
406
-        $expiry = DateTimeImmutable::createFromFormat("U", $this->identity->getExpirationTime());
407
-        $graceExpiry = $expiry->modify($gracePeriod);
408
-        $now = new DateTimeImmutable();
409
-
410
-        return $graceExpiry < $now;
411
-    }
412
-
413
-    /**
414
-     * Loads the OAuth identity from the database for the current user.
415
-     */
416
-    private function loadIdentity()
417
-    {
418
-        if ($this->identityLoaded) {
419
-            return;
420
-        }
421
-
422
-        $statement = $this->database->prepare('SELECT * FROM oauthidentity WHERE user = :user');
423
-        $statement->execute(array(':user' => $this->user->getId()));
424
-        /** @var OAuthIdentity $obj */
425
-        $obj = $statement->fetchObject(OAuthIdentity::class);
426
-
427
-        if ($obj === false) {
428
-            // failed to load identity.
429
-            $this->identityLoaded = true;
430
-            $this->identity = null;
431
-
432
-            return;
433
-        }
434
-
435
-        $obj->setDatabase($this->database);
436
-        $this->identityLoaded = true;
437
-        $this->identity = $obj;
438
-    }
439
-
440
-    /**
441
-     * @return OAuthToken
442
-     * @throws OAuthException
443
-     */
444
-    private function loadAccessToken()
445
-    {
446
-        if (!$this->accessTokenLoaded) {
447
-            $this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_ACCESS));
448
-            /** @var OAuthToken $token */
449
-            $token = $this->getTokenStatement->fetchObject(OAuthToken::class);
450
-            $this->getTokenStatement->closeCursor();
451
-
452
-            if ($token === false) {
453
-                throw new OAuthException('Access token not found!');
454
-            }
455
-
456
-            $this->accessToken = $token;
457
-            $this->accessTokenLoaded = true;
458
-        }
459
-
460
-        return $this->accessToken;
461
-    }
75
+		);
76
+		$statement->execute(array(':type' => self::TOKEN_REQUEST, ':token' => $requestToken));
77
+
78
+		/** @var User $user */
79
+		$user = $statement->fetchObject(User::class);
80
+		$statement->closeCursor();
81
+
82
+		if ($user === false) {
83
+			throw new ApplicationLogicException('Token not found in store, please try again');
84
+		}
85
+
86
+		$user->setDatabase($database);
87
+
88
+		return $user;
89
+	}
90
+
91
+	public static function userIsFullyLinked(User $user, PdoDatabase $database = null)
92
+	{
93
+		if (self::$tokenCountStatement === null && $database === null) {
94
+			throw new ApplicationLogicException('Static link request without initialised statement');
95
+		}
96
+
97
+		return self::runTokenCount($user->getId(), $database, self::TOKEN_ACCESS);
98
+	}
99
+
100
+	public static function userIsPartiallyLinked(User $user, PdoDatabase $database = null)
101
+	{
102
+		if (self::$tokenCountStatement === null && $database === null) {
103
+			throw new ApplicationLogicException('Static link request without initialised statement');
104
+		}
105
+
106
+		if (self::userIsFullyLinked($user, $database)) {
107
+			return false;
108
+		}
109
+
110
+		return self::runTokenCount($user->getId(), $database, self::TOKEN_REQUEST)
111
+			|| $user->getOnWikiName() == null;
112
+	}
113
+
114
+	/**
115
+	 * @param PdoDatabase $database
116
+	 */
117
+	public static function prepareTokenCountStatement(PdoDatabase $database)
118
+	{
119
+		if (self::$tokenCountStatement === null) {
120
+			self::$tokenCountStatement = $database->prepare('SELECT COUNT(*) FROM oauthtoken WHERE user = :user AND type = :type');
121
+		}
122
+	}
123
+
124
+	private static function runTokenCount($userId, $database, $tokenType)
125
+	{
126
+		if (self::$tokenCountStatement === null) {
127
+			self::prepareTokenCountStatement($database);
128
+		}
129
+
130
+		self::$tokenCountStatement->execute(array(
131
+			':user' => $userId,
132
+			':type' => $tokenType,
133
+		));
134
+
135
+		$tokenCount = self::$tokenCountStatement->fetchColumn();
136
+		$linked = $tokenCount > 0;
137
+		self::$tokenCountStatement->closeCursor();
138
+
139
+		return $linked;
140
+	}
141
+
142
+	#endregion Static methods
143
+
144
+	/**
145
+	 * OAuthUserHelper constructor.
146
+	 *
147
+	 * @param User                 $user
148
+	 * @param PdoDatabase          $database
149
+	 * @param IOAuthProtocolHelper $oauthProtocolHelper
150
+	 * @param SiteConfiguration    $siteConfiguration
151
+	 */
152
+	public function __construct(
153
+		User $user,
154
+		PdoDatabase $database,
155
+		IOAuthProtocolHelper $oauthProtocolHelper,
156
+		SiteConfiguration $siteConfiguration
157
+	) {
158
+		$this->user = $user;
159
+		$this->database = $database;
160
+		$this->oauthProtocolHelper = $oauthProtocolHelper;
161
+
162
+		$this->linked = null;
163
+		$this->partiallyLinked = null;
164
+		$this->siteConfiguration = $siteConfiguration;
165
+
166
+		self::prepareTokenCountStatement($database);
167
+		$this->getTokenStatement = $this->database->prepare('SELECT * FROM oauthtoken WHERE user = :user AND type = :type');
168
+	}
169
+
170
+	/**
171
+	 * Determines if the user is fully connected to OAuth.
172
+	 *
173
+	 * @return bool
174
+	 */
175
+	public function isFullyLinked()
176
+	{
177
+		if ($this->linked === null) {
178
+			$this->linked = self::userIsFullyLinked($this->user, $this->database);
179
+		}
180
+
181
+		return $this->linked;
182
+	}
183
+
184
+	/**
185
+	 * Attempts to figure out if a user is partially linked to OAuth, and therefore needs to complete the OAuth
186
+	 * procedure before configuring.
187
+	 * @return bool
188
+	 */
189
+	public function isPartiallyLinked()
190
+	{
191
+		if ($this->partiallyLinked === null) {
192
+			$this->partiallyLinked = self::userIsPartiallyLinked($this->user, $this->database);
193
+		}
194
+
195
+		return $this->partiallyLinked;
196
+	}
197
+
198
+	public function canCreateAccount() {
199
+		return $this->isFullyLinked()
200
+			&& $this->getIdentity(true)->getGrantBasic()
201
+			&& $this->getIdentity(true)->getGrantHighVolume()
202
+			&& $this->getIdentity(true)->getGrantCreateAccount();
203
+	}
204
+
205
+	public function canWelcome() {
206
+		return $this->isFullyLinked()
207
+			&& $this->getIdentity(true)->getGrantBasic()
208
+			&& $this->getIdentity(true)->getGrantHighVolume()
209
+			&& $this->getIdentity(true)->getGrantCreateEditMovePage();
210
+	}
211
+
212
+	/**
213
+	 * @throws OAuthException
214
+	 * @throws CurlException
215
+	 * @throws OptimisticLockFailedException
216
+	 */
217
+	public function refreshIdentity()
218
+	{
219
+		$this->loadIdentity();
220
+
221
+		if ($this->identity === null) {
222
+			$this->identity = new OAuthIdentity();
223
+			$this->identity->setUserId($this->user->getId());
224
+			$this->identity->setDatabase($this->database);
225
+		}
226
+
227
+		$token = $this->loadAccessToken();
228
+
229
+		$rawTicket = $this->oauthProtocolHelper->getIdentityTicket($token->getToken(), $token->getSecret());
230
+
231
+		$this->identity->populate($rawTicket);
232
+
233
+		if (!$this->identityIsValid()) {
234
+			throw new OAuthException('Identity ticket is not valid!');
235
+		}
236
+
237
+		$this->identity->save();
238
+
239
+		$this->user->setOnWikiName($this->identity->getUsername());
240
+		$this->user->save();
241
+	}
242
+
243
+	/**
244
+	 * @return string
245
+	 * @throws CurlException
246
+	 */
247
+	public function getRequestToken()
248
+	{
249
+		$token = $this->oauthProtocolHelper->getRequestToken();
250
+
251
+		$this->partiallyLinked = true;
252
+		$this->linked = false;
253
+
254
+		$this->database
255
+			->prepare('DELETE FROM oauthtoken WHERE user = :user AND type = :type')
256
+			->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
257
+
258
+		$this->database
259
+			->prepare('INSERT INTO oauthtoken (user, type, token, secret, expiry) VALUES (:user, :type, :token, :secret, DATE_ADD(NOW(), INTERVAL 1 DAY))')
260
+			->execute(array(
261
+				':user'   => $this->user->getId(),
262
+				':type'   => self::TOKEN_REQUEST,
263
+				':token'  => $token->key,
264
+				':secret' => $token->secret,
265
+			));
266
+
267
+		return $this->oauthProtocolHelper->getAuthoriseUrl($token->key);
268
+	}
269
+
270
+	/**
271
+	 * @param $verificationToken
272
+	 *
273
+	 * @throws ApplicationLogicException
274
+	 * @throws CurlException
275
+	 * @throws OAuthException
276
+	 * @throws OptimisticLockFailedException
277
+	 */
278
+	public function completeHandshake($verificationToken)
279
+	{
280
+		$this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_REQUEST));
281
+
282
+		/** @var OAuthToken $token */
283
+		$token = $this->getTokenStatement->fetchObject(OAuthToken::class);
284
+		$this->getTokenStatement->closeCursor();
285
+
286
+		if ($token === false) {
287
+			throw new ApplicationLogicException('Cannot find request token');
288
+		}
289
+
290
+		$token->setDatabase($this->database);
291
+
292
+		$accessToken = $this->oauthProtocolHelper->callbackCompleted($token->getToken(), $token->getSecret(),
293
+			$verificationToken);
294
+
295
+		$clearStatement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :u AND type = :t');
296
+		$clearStatement->execute(array(':u' => $this->user->getId(), ':t' => self::TOKEN_ACCESS));
297
+
298
+		$token->setToken($accessToken->key);
299
+		$token->setSecret($accessToken->secret);
300
+		$token->setType(self::TOKEN_ACCESS);
301
+		$token->setExpiry(null);
302
+		$token->save();
303
+
304
+		$this->partiallyLinked = false;
305
+		$this->linked = true;
306
+
307
+		$this->refreshIdentity();
308
+	}
309
+
310
+	public function detach()
311
+	{
312
+		$this->loadIdentity();
313
+
314
+		$this->identity->delete();
315
+		$statement = $this->database->prepare('DELETE FROM oauthtoken WHERE user = :user');
316
+		$statement->execute(array(':user' => $this->user->getId()));
317
+
318
+		$this->identity = null;
319
+		$this->linked = false;
320
+		$this->partiallyLinked = false;
321
+	}
322
+
323
+	/**
324
+	 * @param bool $expiredOk
325
+	 *
326
+	 * @return OAuthIdentity
327
+	 * @throws OAuthException
328
+	 */
329
+	public function getIdentity($expiredOk = false)
330
+	{
331
+		$this->loadIdentity();
332
+
333
+		if (!$this->identityIsValid($expiredOk)) {
334
+			throw new OAuthException('Stored identity is not valid.');
335
+		}
336
+
337
+		return $this->identity;
338
+	}
339
+
340
+	public function doApiCall($params, $method)
341
+	{
342
+		// Ensure we're logged in
343
+		$params['assert'] = 'user';
344
+
345
+		$token = $this->loadAccessToken();
346
+		return $this->oauthProtocolHelper->apiCall($params, $token->getToken(), $token->getSecret(), $method);
347
+	}
348
+
349
+	/**
350
+	 * @param bool $expiredOk
351
+	 *
352
+	 * @return bool
353
+	 */
354
+	private function identityIsValid($expiredOk = false)
355
+	{
356
+		$this->loadIdentity();
357
+
358
+		if ($this->identity === null) {
359
+			return false;
360
+		}
361
+
362
+		if ($this->identity->getIssuedAtTime() === false
363
+			|| $this->identity->getExpirationTime() === false
364
+			|| $this->identity->getAudience() === false
365
+			|| $this->identity->getIssuer() === false
366
+		) {
367
+			// this isn't populated properly.
368
+			return false;
369
+		}
370
+
371
+		$issue = DateTimeImmutable::createFromFormat("U", $this->identity->getIssuedAtTime());
372
+		$now = new DateTimeImmutable();
373
+
374
+		if ($issue > $now) {
375
+			// wat.
376
+			return false;
377
+		}
378
+
379
+		if ($this->identityExpired() && !$expiredOk) {
380
+			// soz.
381
+			return false;
382
+		}
383
+
384
+		if ($this->identity->getAudience() !== $this->siteConfiguration->getOAuthConsumerToken()) {
385
+			// token not issued for us
386
+			return false;
387
+		}
388
+
389
+		if ($this->identity->getIssuer() !== $this->siteConfiguration->getOauthMediaWikiCanonicalServer()) {
390
+			// token not issued by the right person
391
+			return false;
392
+		}
393
+
394
+		// can't find a reason to not trust it
395
+		return true;
396
+	}
397
+
398
+	/**
399
+	 * @return bool
400
+	 */
401
+	public function identityExpired()
402
+	{
403
+		// allowed max age
404
+		$gracePeriod = $this->siteConfiguration->getOauthIdentityGraceTime();
405
+
406
+		$expiry = DateTimeImmutable::createFromFormat("U", $this->identity->getExpirationTime());
407
+		$graceExpiry = $expiry->modify($gracePeriod);
408
+		$now = new DateTimeImmutable();
409
+
410
+		return $graceExpiry < $now;
411
+	}
412
+
413
+	/**
414
+	 * Loads the OAuth identity from the database for the current user.
415
+	 */
416
+	private function loadIdentity()
417
+	{
418
+		if ($this->identityLoaded) {
419
+			return;
420
+		}
421
+
422
+		$statement = $this->database->prepare('SELECT * FROM oauthidentity WHERE user = :user');
423
+		$statement->execute(array(':user' => $this->user->getId()));
424
+		/** @var OAuthIdentity $obj */
425
+		$obj = $statement->fetchObject(OAuthIdentity::class);
426
+
427
+		if ($obj === false) {
428
+			// failed to load identity.
429
+			$this->identityLoaded = true;
430
+			$this->identity = null;
431
+
432
+			return;
433
+		}
434
+
435
+		$obj->setDatabase($this->database);
436
+		$this->identityLoaded = true;
437
+		$this->identity = $obj;
438
+	}
439
+
440
+	/**
441
+	 * @return OAuthToken
442
+	 * @throws OAuthException
443
+	 */
444
+	private function loadAccessToken()
445
+	{
446
+		if (!$this->accessTokenLoaded) {
447
+			$this->getTokenStatement->execute(array(':user' => $this->user->getId(), ':type' => self::TOKEN_ACCESS));
448
+			/** @var OAuthToken $token */
449
+			$token = $this->getTokenStatement->fetchObject(OAuthToken::class);
450
+			$this->getTokenStatement->closeCursor();
451
+
452
+			if ($token === false) {
453
+				throw new OAuthException('Access token not found!');
454
+			}
455
+
456
+			$this->accessToken = $token;
457
+			$this->accessTokenLoaded = true;
458
+		}
459
+
460
+		return $this->accessToken;
461
+	}
462 462
 }
Please login to merge, or discard this patch.
Braces   +4 added lines, -2 removed lines patch added patch discarded remove patch
@@ -195,14 +195,16 @@
 block discarded – undo
195 195
         return $this->partiallyLinked;
196 196
     }
197 197
 
198
-    public function canCreateAccount() {
198
+    public function canCreateAccount()
199
+    {
199 200
         return $this->isFullyLinked()
200 201
             && $this->getIdentity(true)->getGrantBasic()
201 202
             && $this->getIdentity(true)->getGrantHighVolume()
202 203
             && $this->getIdentity(true)->getGrantCreateAccount();
203 204
     }
204 205
 
205
-    public function canWelcome() {
206
+    public function canWelcome()
207
+    {
206 208
         return $this->isFullyLinked()
207 209
             && $this->getIdentity(true)->getGrantBasic()
208 210
             && $this->getIdentity(true)->getGrantHighVolume()
Please login to merge, or discard this patch.
includes/Helpers/IrcNotificationHelper.php 2 patches
Indentation   +451 added lines, -451 removed lines patch added patch discarded remove patch
@@ -26,457 +26,457 @@
 block discarded – undo
26 26
  */
27 27
 class IrcNotificationHelper
28 28
 {
29
-    /** @var PdoDatabase $notificationsDatabase */
30
-    private $notificationsDatabase;
31
-    /** @var PdoDatabase $primaryDatabase */
32
-    private $primaryDatabase;
33
-    /** @var bool $notificationsEnabled */
34
-    private $notificationsEnabled;
35
-    /** @var int $notificationType */
36
-    private $notificationType;
37
-    /** @var User $currentUser */
38
-    private $currentUser;
39
-    /** @var string $instanceName */
40
-    private $instanceName;
41
-    /** @var string */
42
-    private $baseUrl;
43
-    /** @var array */
44
-    private $requestStates;
45
-
46
-    /**
47
-     * IrcNotificationHelper constructor.
48
-     *
49
-     * @param SiteConfiguration $siteConfiguration
50
-     * @param PdoDatabase       $primaryDatabase
51
-     * @param PdoDatabase       $notificationsDatabase
52
-     */
53
-    public function __construct(
54
-        SiteConfiguration $siteConfiguration,
55
-        PdoDatabase $primaryDatabase,
56
-        PdoDatabase $notificationsDatabase = null
57
-    ) {
58
-        $this->primaryDatabase = $primaryDatabase;
59
-
60
-        if ($notificationsDatabase !== null) {
61
-            $this->notificationsDatabase = $notificationsDatabase;
62
-            $this->notificationsEnabled = $siteConfiguration->getIrcNotificationsEnabled();
63
-        }
64
-        else {
65
-            $this->notificationsEnabled = false;
66
-        }
67
-
68
-        $this->notificationType = $siteConfiguration->getIrcNotificationType();
69
-        $this->instanceName = $siteConfiguration->getIrcNotificationsInstance();
70
-        $this->baseUrl = $siteConfiguration->getBaseUrl();
71
-        $this->requestStates = $siteConfiguration->getRequestStates();
72
-
73
-        $this->currentUser = User::getCurrent($primaryDatabase);
74
-    }
75
-
76
-    /**
77
-     * Send a notification
78
-     *
79
-     * @param string $message The text to send
80
-     */
81
-    protected function send($message)
82
-    {
83
-        $instanceName = $this->instanceName;
84
-
85
-        if (!$this->notificationsEnabled) {
86
-            return;
87
-        }
88
-
89
-        $blacklist = array("DCC", "CCTP", "PRIVMSG");
90
-        $message = str_replace($blacklist, "(IRC Blacklist)", $message); // Lets stop DCC etc
91
-
92
-        $msg = IrcColourCode::RESET . IrcColourCode::BOLD . "[$instanceName]" . IrcColourCode::RESET . ": $message";
93
-
94
-        try {
95
-            $notification = new Notification();
96
-            $notification->setDatabase($this->notificationsDatabase);
97
-            $notification->setType($this->notificationType);
98
-            $notification->setText($msg);
99
-
100
-            $notification->save();
101
-        }
102
-        catch (Exception $ex) {
103
-            // OK, so we failed to send the notification - that db might be down?
104
-            // This is non-critical, so silently fail.
105
-
106
-            // Disable notifications for remainder of request.
107
-            $this->notificationsEnabled = false;
108
-        }
109
-    }
110
-
111
-    #region user management
112
-
113
-    /**
114
-     * send a new user notification
115
-     *
116
-     * @param User $user
117
-     */
118
-    public function userNew(User $user)
119
-    {
120
-        $this->send("New user: {$user->getUsername()}");
121
-    }
122
-
123
-    /**
124
-     * send an approved notification
125
-     *
126
-     * @param User $user
127
-     */
128
-    public function userApproved(User $user)
129
-    {
130
-        $this->send("{$user->getUsername()} approved by " . $this->currentUser->getUsername());
131
-    }
132
-
133
-    /**
134
-     * send a declined notification
135
-     *
136
-     * @param User   $user
137
-     * @param string $reason the reason the user was declined
138
-     */
139
-    public function userDeclined(User $user, $reason)
140
-    {
141
-        $this->send("{$user->getUsername()} declined by " . $this->currentUser->getUsername() . " ($reason)");
142
-    }
143
-
144
-    /**
145
-     * send a suspended notification
146
-     *
147
-     * @param User   $user
148
-     * @param string $reason The reason the user has been suspended
149
-     */
150
-    public function userSuspended(User $user, $reason)
151
-    {
152
-        $this->send("{$user->getUsername()} suspended by " . $this->currentUser->getUsername() . " ($reason)");
153
-    }
154
-
155
-    /**
156
-     * Send a preference change notification
157
-     *
158
-     * @param User $user
159
-     */
160
-    public function userPrefChange(User $user)
161
-    {
162
-        $this->send("{$user->getUsername()}'s preferences were changed by " . $this->currentUser->getUsername());
163
-    }
164
-
165
-    /**
166
-     * Send a user renamed notification
167
-     *
168
-     * @param User   $user
169
-     * @param string $old
170
-     */
171
-    public function userRenamed(User $user, $old)
172
-    {
173
-        $this->send($this->currentUser->getUsername() . " renamed $old to {$user->getUsername()}");
174
-    }
175
-
176
-    /**
177
-     * @param User   $user
178
-     * @param string $reason
179
-     */
180
-    public function userRolesEdited(User $user, $reason)
181
-    {
182
-        $currentUser = $this->currentUser->getUsername();
183
-        $this->send("Active roles for {$user->getUsername()} changed by " . $currentUser . " ($reason)");
184
-    }
185
-
186
-    #endregion
187
-
188
-    #region Site Notice
189
-
190
-    /**
191
-     * Summary of siteNoticeEdited
192
-     */
193
-    public function siteNoticeEdited()
194
-    {
195
-        $this->send("Site notice edited by " . $this->currentUser->getUsername());
196
-    }
197
-    #endregion
198
-
199
-    #region Welcome Templates
200
-    /**
201
-     * Summary of welcomeTemplateCreated
202
-     *
203
-     * @param WelcomeTemplate $template
204
-     */
205
-    public function welcomeTemplateCreated(WelcomeTemplate $template)
206
-    {
207
-        $this->send("Welcome template {$template->getId()} created by " . $this->currentUser->getUsername());
208
-    }
209
-
210
-    /**
211
-     * Summary of welcomeTemplateDeleted
212
-     *
213
-     * @param int $templateid
214
-     */
215
-    public function welcomeTemplateDeleted($templateid)
216
-    {
217
-        $this->send("Welcome template {$templateid} deleted by " . $this->currentUser->getUsername());
218
-    }
219
-
220
-    /**
221
-     * Summary of welcomeTemplateEdited
222
-     *
223
-     * @param WelcomeTemplate $template
224
-     */
225
-    public function welcomeTemplateEdited(WelcomeTemplate $template)
226
-    {
227
-        $this->send("Welcome template {$template->getId()} edited by " . $this->currentUser->getUsername());
228
-    }
229
-
230
-    #endregion
231
-
232
-    #region bans
233
-    /**
234
-     * Summary of banned
235
-     *
236
-     * @param Ban $ban
237
-     */
238
-    public function banned(Ban $ban)
239
-    {
240
-        if ($ban->getDuration() === null) {
241
-            $duration = "indefinitely";
242
-        }
243
-        else {
244
-            $duration = "until " . date("F j, Y, g:i a", $ban->getDuration());
245
-        }
246
-
247
-        $username = $this->currentUser->getUsername();
248
-
249
-        $this->send("{$ban->getTarget()} banned by {$username} for '{$ban->getReason()}' {$duration}");
250
-    }
251
-
252
-    /**
253
-     * Summary of unbanned
254
-     *
255
-     * @param Ban    $ban
256
-     * @param string $unbanreason
257
-     */
258
-    public function unbanned(Ban $ban, $unbanreason)
259
-    {
260
-        $this->send($ban->getTarget() . " unbanned by " . $this->currentUser
261
-                ->getUsername() . " (" . $unbanreason . ")");
262
-    }
263
-
264
-    #endregion
265
-
266
-    #region request management
267
-
268
-    /**
269
-     * Summary of requestReceived
270
-     *
271
-     * @param Request $request
272
-     */
273
-    public function requestReceived(Request $request)
274
-    {
275
-        $this->send(
276
-            IrcColourCode::DARK_GREY . "[["
277
-            . IrcColourCode::DARK_GREEN . "acc:"
278
-            . IrcColourCode::ORANGE . $request->getId()
279
-            . IrcColourCode::DARK_GREY . "]]"
280
-            . IrcColourCode::RED . " N "
281
-            . IrcColourCode::DARK_BLUE . $this->baseUrl . "/internal.php/viewRequest?id={$request->getId()} "
282
-            . IrcColourCode::DARK_RED . "* "
283
-            . IrcColourCode::DARK_GREEN . $request->getName()
284
-            . IrcColourCode::DARK_RED . " * "
285
-            . IrcColourCode::RESET
286
-        );
287
-    }
288
-
289
-    /**
290
-     * Summary of requestDeferred
291
-     *
292
-     * @param Request $request
293
-     */
294
-    public function requestDeferred(Request $request)
295
-    {
296
-        $availableRequestStates = $this->requestStates;
297
-
298
-        $deferTo = $availableRequestStates[$request->getStatus()]['deferto'];
299
-        $username = $this->currentUser->getUsername();
300
-
301
-        $this->send("Request {$request->getId()} ({$request->getName()}) deferred to {$deferTo} by {$username}");
302
-    }
303
-
304
-    /**
305
-     *
306
-     * Summary of requestDeferredWithMail
307
-     *
308
-     * @param Request $request
309
-     */
310
-    public function requestDeferredWithMail(Request $request)
311
-    {
312
-        $availableRequestStates = $this->requestStates;
313
-
314
-        $deferTo = $availableRequestStates[$request->getStatus()]['deferto'];
315
-        $username = $this->currentUser->getUsername();
316
-        $id = $request->getId();
317
-        $name = $request->getName();
318
-
319
-        $this->send("Request {$id} ({$name}) deferred to {$deferTo} with an email by {$username}");
320
-    }
321
-
322
-    /**
323
-     * Summary of requestClosed
324
-     *
325
-     * @param Request $request
326
-     * @param string  $closetype
327
-     */
328
-    public function requestClosed(Request $request, $closetype)
329
-    {
330
-        $username = $this->currentUser->getUsername();
331
-
332
-        $this->send("Request {$request->getId()} ({$request->getName()}) closed ($closetype) by {$username}");
333
-    }
334
-
335
-    /**
336
-     * Summary of requestClosed
337
-     *
338
-     * @param Request $request
339
-     * @param string  $closetype
340
-     */
341
-    public function requestCloseQueued(Request $request, $closetype)
342
-    {
343
-        $username = $this->currentUser->getUsername();
344
-
345
-        $this->send("Request {$request->getId()} ({$request->getName()}) queued for creation ($closetype) by {$username}");
346
-    }
347
-
348
-    /**
349
-     * Summary of requestClosed
350
-     *
351
-     * @param Request $request
352
-     */
353
-    public function requestCreationFailed(Request $request)
354
-    {
355
-        $this->send("Request {$request->getId()} ({$request->getName()}) failed auto-creation, and was sent to the hospital queue.");
356
-    }
357
-
358
-    /**
359
-     * Summary of sentMail
360
-     *
361
-     * @param Request $request
362
-     */
363
-    public function sentMail(Request $request)
364
-    {
365
-        $this->send($this->currentUser->getUsername()
366
-            . " sent an email related to Request {$request->getId()} ({$request->getName()})");
367
-    }
368
-
369
-    #endregion
370
-
371
-    #region reservations
372
-
373
-    /**
374
-     * Summary of requestReserved
375
-     *
376
-     * @param Request $request
377
-     */
378
-    public function requestReserved(Request $request)
379
-    {
380
-        $username = $this->currentUser->getUsername();
381
-
382
-        $this->send("Request {$request->getId()} ({$request->getName()}) reserved by {$username}");
383
-    }
384
-
385
-    /**
386
-     * Summary of requestReserveBroken
387
-     *
388
-     * @param Request $request
389
-     */
390
-    public function requestReserveBroken(Request $request)
391
-    {
392
-        $username = $this->currentUser->getUsername();
393
-
394
-        $this->send("Reservation on request {$request->getId()} ({$request->getName()}) broken by {$username}");
395
-    }
396
-
397
-    /**
398
-     * Summary of requestUnreserved
399
-     *
400
-     * @param Request $request
401
-     */
402
-    public function requestUnreserved(Request $request)
403
-    {
404
-        $this->send("Request {$request->getId()} ({$request->getName()}) is no longer being handled.");
405
-    }
406
-
407
-    /**
408
-     * Summary of requestReservationSent
409
-     *
410
-     * @param Request $request
411
-     * @param User    $target
412
-     */
413
-    public function requestReservationSent(Request $request, User $target)
414
-    {
415
-        $username = $this->currentUser->getUsername();
416
-
417
-        $this->send(
418
-            "Reservation of request {$request->getId()} ({$request->getName()}) sent to {$target->getUsername()} by "
419
-            . $username);
420
-    }
421
-
422
-    #endregion
423
-
424
-    #region comments
425
-
426
-    /**
427
-     * Summary of commentCreated
428
-     *
429
-     * @param Comment $comment
430
-     * @param Request $request
431
-     */
432
-    public function commentCreated(Comment $comment, Request $request)
433
-    {
434
-        $username = $this->currentUser->getUsername();
435
-        $visibility = ($comment->getVisibility() == "admin" ? "private " : "");
436
-
437
-        $this->send("{$username} posted a {$visibility}comment on request {$request->getId()} ({$request->getName()})");
438
-    }
439
-
440
-    /**
441
-     * Summary of commentEdited
442
-     *
443
-     * @param Comment $comment
444
-     * @param Request $request
445
-     */
446
-    public function commentEdited(Comment $comment, Request $request)
447
-    {
448
-        $username = $this->currentUser->getUsername();
449
-
450
-        $this->send(<<<TAG
29
+	/** @var PdoDatabase $notificationsDatabase */
30
+	private $notificationsDatabase;
31
+	/** @var PdoDatabase $primaryDatabase */
32
+	private $primaryDatabase;
33
+	/** @var bool $notificationsEnabled */
34
+	private $notificationsEnabled;
35
+	/** @var int $notificationType */
36
+	private $notificationType;
37
+	/** @var User $currentUser */
38
+	private $currentUser;
39
+	/** @var string $instanceName */
40
+	private $instanceName;
41
+	/** @var string */
42
+	private $baseUrl;
43
+	/** @var array */
44
+	private $requestStates;
45
+
46
+	/**
47
+	 * IrcNotificationHelper constructor.
48
+	 *
49
+	 * @param SiteConfiguration $siteConfiguration
50
+	 * @param PdoDatabase       $primaryDatabase
51
+	 * @param PdoDatabase       $notificationsDatabase
52
+	 */
53
+	public function __construct(
54
+		SiteConfiguration $siteConfiguration,
55
+		PdoDatabase $primaryDatabase,
56
+		PdoDatabase $notificationsDatabase = null
57
+	) {
58
+		$this->primaryDatabase = $primaryDatabase;
59
+
60
+		if ($notificationsDatabase !== null) {
61
+			$this->notificationsDatabase = $notificationsDatabase;
62
+			$this->notificationsEnabled = $siteConfiguration->getIrcNotificationsEnabled();
63
+		}
64
+		else {
65
+			$this->notificationsEnabled = false;
66
+		}
67
+
68
+		$this->notificationType = $siteConfiguration->getIrcNotificationType();
69
+		$this->instanceName = $siteConfiguration->getIrcNotificationsInstance();
70
+		$this->baseUrl = $siteConfiguration->getBaseUrl();
71
+		$this->requestStates = $siteConfiguration->getRequestStates();
72
+
73
+		$this->currentUser = User::getCurrent($primaryDatabase);
74
+	}
75
+
76
+	/**
77
+	 * Send a notification
78
+	 *
79
+	 * @param string $message The text to send
80
+	 */
81
+	protected function send($message)
82
+	{
83
+		$instanceName = $this->instanceName;
84
+
85
+		if (!$this->notificationsEnabled) {
86
+			return;
87
+		}
88
+
89
+		$blacklist = array("DCC", "CCTP", "PRIVMSG");
90
+		$message = str_replace($blacklist, "(IRC Blacklist)", $message); // Lets stop DCC etc
91
+
92
+		$msg = IrcColourCode::RESET . IrcColourCode::BOLD . "[$instanceName]" . IrcColourCode::RESET . ": $message";
93
+
94
+		try {
95
+			$notification = new Notification();
96
+			$notification->setDatabase($this->notificationsDatabase);
97
+			$notification->setType($this->notificationType);
98
+			$notification->setText($msg);
99
+
100
+			$notification->save();
101
+		}
102
+		catch (Exception $ex) {
103
+			// OK, so we failed to send the notification - that db might be down?
104
+			// This is non-critical, so silently fail.
105
+
106
+			// Disable notifications for remainder of request.
107
+			$this->notificationsEnabled = false;
108
+		}
109
+	}
110
+
111
+	#region user management
112
+
113
+	/**
114
+	 * send a new user notification
115
+	 *
116
+	 * @param User $user
117
+	 */
118
+	public function userNew(User $user)
119
+	{
120
+		$this->send("New user: {$user->getUsername()}");
121
+	}
122
+
123
+	/**
124
+	 * send an approved notification
125
+	 *
126
+	 * @param User $user
127
+	 */
128
+	public function userApproved(User $user)
129
+	{
130
+		$this->send("{$user->getUsername()} approved by " . $this->currentUser->getUsername());
131
+	}
132
+
133
+	/**
134
+	 * send a declined notification
135
+	 *
136
+	 * @param User   $user
137
+	 * @param string $reason the reason the user was declined
138
+	 */
139
+	public function userDeclined(User $user, $reason)
140
+	{
141
+		$this->send("{$user->getUsername()} declined by " . $this->currentUser->getUsername() . " ($reason)");
142
+	}
143
+
144
+	/**
145
+	 * send a suspended notification
146
+	 *
147
+	 * @param User   $user
148
+	 * @param string $reason The reason the user has been suspended
149
+	 */
150
+	public function userSuspended(User $user, $reason)
151
+	{
152
+		$this->send("{$user->getUsername()} suspended by " . $this->currentUser->getUsername() . " ($reason)");
153
+	}
154
+
155
+	/**
156
+	 * Send a preference change notification
157
+	 *
158
+	 * @param User $user
159
+	 */
160
+	public function userPrefChange(User $user)
161
+	{
162
+		$this->send("{$user->getUsername()}'s preferences were changed by " . $this->currentUser->getUsername());
163
+	}
164
+
165
+	/**
166
+	 * Send a user renamed notification
167
+	 *
168
+	 * @param User   $user
169
+	 * @param string $old
170
+	 */
171
+	public function userRenamed(User $user, $old)
172
+	{
173
+		$this->send($this->currentUser->getUsername() . " renamed $old to {$user->getUsername()}");
174
+	}
175
+
176
+	/**
177
+	 * @param User   $user
178
+	 * @param string $reason
179
+	 */
180
+	public function userRolesEdited(User $user, $reason)
181
+	{
182
+		$currentUser = $this->currentUser->getUsername();
183
+		$this->send("Active roles for {$user->getUsername()} changed by " . $currentUser . " ($reason)");
184
+	}
185
+
186
+	#endregion
187
+
188
+	#region Site Notice
189
+
190
+	/**
191
+	 * Summary of siteNoticeEdited
192
+	 */
193
+	public function siteNoticeEdited()
194
+	{
195
+		$this->send("Site notice edited by " . $this->currentUser->getUsername());
196
+	}
197
+	#endregion
198
+
199
+	#region Welcome Templates
200
+	/**
201
+	 * Summary of welcomeTemplateCreated
202
+	 *
203
+	 * @param WelcomeTemplate $template
204
+	 */
205
+	public function welcomeTemplateCreated(WelcomeTemplate $template)
206
+	{
207
+		$this->send("Welcome template {$template->getId()} created by " . $this->currentUser->getUsername());
208
+	}
209
+
210
+	/**
211
+	 * Summary of welcomeTemplateDeleted
212
+	 *
213
+	 * @param int $templateid
214
+	 */
215
+	public function welcomeTemplateDeleted($templateid)
216
+	{
217
+		$this->send("Welcome template {$templateid} deleted by " . $this->currentUser->getUsername());
218
+	}
219
+
220
+	/**
221
+	 * Summary of welcomeTemplateEdited
222
+	 *
223
+	 * @param WelcomeTemplate $template
224
+	 */
225
+	public function welcomeTemplateEdited(WelcomeTemplate $template)
226
+	{
227
+		$this->send("Welcome template {$template->getId()} edited by " . $this->currentUser->getUsername());
228
+	}
229
+
230
+	#endregion
231
+
232
+	#region bans
233
+	/**
234
+	 * Summary of banned
235
+	 *
236
+	 * @param Ban $ban
237
+	 */
238
+	public function banned(Ban $ban)
239
+	{
240
+		if ($ban->getDuration() === null) {
241
+			$duration = "indefinitely";
242
+		}
243
+		else {
244
+			$duration = "until " . date("F j, Y, g:i a", $ban->getDuration());
245
+		}
246
+
247
+		$username = $this->currentUser->getUsername();
248
+
249
+		$this->send("{$ban->getTarget()} banned by {$username} for '{$ban->getReason()}' {$duration}");
250
+	}
251
+
252
+	/**
253
+	 * Summary of unbanned
254
+	 *
255
+	 * @param Ban    $ban
256
+	 * @param string $unbanreason
257
+	 */
258
+	public function unbanned(Ban $ban, $unbanreason)
259
+	{
260
+		$this->send($ban->getTarget() . " unbanned by " . $this->currentUser
261
+				->getUsername() . " (" . $unbanreason . ")");
262
+	}
263
+
264
+	#endregion
265
+
266
+	#region request management
267
+
268
+	/**
269
+	 * Summary of requestReceived
270
+	 *
271
+	 * @param Request $request
272
+	 */
273
+	public function requestReceived(Request $request)
274
+	{
275
+		$this->send(
276
+			IrcColourCode::DARK_GREY . "[["
277
+			. IrcColourCode::DARK_GREEN . "acc:"
278
+			. IrcColourCode::ORANGE . $request->getId()
279
+			. IrcColourCode::DARK_GREY . "]]"
280
+			. IrcColourCode::RED . " N "
281
+			. IrcColourCode::DARK_BLUE . $this->baseUrl . "/internal.php/viewRequest?id={$request->getId()} "
282
+			. IrcColourCode::DARK_RED . "* "
283
+			. IrcColourCode::DARK_GREEN . $request->getName()
284
+			. IrcColourCode::DARK_RED . " * "
285
+			. IrcColourCode::RESET
286
+		);
287
+	}
288
+
289
+	/**
290
+	 * Summary of requestDeferred
291
+	 *
292
+	 * @param Request $request
293
+	 */
294
+	public function requestDeferred(Request $request)
295
+	{
296
+		$availableRequestStates = $this->requestStates;
297
+
298
+		$deferTo = $availableRequestStates[$request->getStatus()]['deferto'];
299
+		$username = $this->currentUser->getUsername();
300
+
301
+		$this->send("Request {$request->getId()} ({$request->getName()}) deferred to {$deferTo} by {$username}");
302
+	}
303
+
304
+	/**
305
+	 *
306
+	 * Summary of requestDeferredWithMail
307
+	 *
308
+	 * @param Request $request
309
+	 */
310
+	public function requestDeferredWithMail(Request $request)
311
+	{
312
+		$availableRequestStates = $this->requestStates;
313
+
314
+		$deferTo = $availableRequestStates[$request->getStatus()]['deferto'];
315
+		$username = $this->currentUser->getUsername();
316
+		$id = $request->getId();
317
+		$name = $request->getName();
318
+
319
+		$this->send("Request {$id} ({$name}) deferred to {$deferTo} with an email by {$username}");
320
+	}
321
+
322
+	/**
323
+	 * Summary of requestClosed
324
+	 *
325
+	 * @param Request $request
326
+	 * @param string  $closetype
327
+	 */
328
+	public function requestClosed(Request $request, $closetype)
329
+	{
330
+		$username = $this->currentUser->getUsername();
331
+
332
+		$this->send("Request {$request->getId()} ({$request->getName()}) closed ($closetype) by {$username}");
333
+	}
334
+
335
+	/**
336
+	 * Summary of requestClosed
337
+	 *
338
+	 * @param Request $request
339
+	 * @param string  $closetype
340
+	 */
341
+	public function requestCloseQueued(Request $request, $closetype)
342
+	{
343
+		$username = $this->currentUser->getUsername();
344
+
345
+		$this->send("Request {$request->getId()} ({$request->getName()}) queued for creation ($closetype) by {$username}");
346
+	}
347
+
348
+	/**
349
+	 * Summary of requestClosed
350
+	 *
351
+	 * @param Request $request
352
+	 */
353
+	public function requestCreationFailed(Request $request)
354
+	{
355
+		$this->send("Request {$request->getId()} ({$request->getName()}) failed auto-creation, and was sent to the hospital queue.");
356
+	}
357
+
358
+	/**
359
+	 * Summary of sentMail
360
+	 *
361
+	 * @param Request $request
362
+	 */
363
+	public function sentMail(Request $request)
364
+	{
365
+		$this->send($this->currentUser->getUsername()
366
+			. " sent an email related to Request {$request->getId()} ({$request->getName()})");
367
+	}
368
+
369
+	#endregion
370
+
371
+	#region reservations
372
+
373
+	/**
374
+	 * Summary of requestReserved
375
+	 *
376
+	 * @param Request $request
377
+	 */
378
+	public function requestReserved(Request $request)
379
+	{
380
+		$username = $this->currentUser->getUsername();
381
+
382
+		$this->send("Request {$request->getId()} ({$request->getName()}) reserved by {$username}");
383
+	}
384
+
385
+	/**
386
+	 * Summary of requestReserveBroken
387
+	 *
388
+	 * @param Request $request
389
+	 */
390
+	public function requestReserveBroken(Request $request)
391
+	{
392
+		$username = $this->currentUser->getUsername();
393
+
394
+		$this->send("Reservation on request {$request->getId()} ({$request->getName()}) broken by {$username}");
395
+	}
396
+
397
+	/**
398
+	 * Summary of requestUnreserved
399
+	 *
400
+	 * @param Request $request
401
+	 */
402
+	public function requestUnreserved(Request $request)
403
+	{
404
+		$this->send("Request {$request->getId()} ({$request->getName()}) is no longer being handled.");
405
+	}
406
+
407
+	/**
408
+	 * Summary of requestReservationSent
409
+	 *
410
+	 * @param Request $request
411
+	 * @param User    $target
412
+	 */
413
+	public function requestReservationSent(Request $request, User $target)
414
+	{
415
+		$username = $this->currentUser->getUsername();
416
+
417
+		$this->send(
418
+			"Reservation of request {$request->getId()} ({$request->getName()}) sent to {$target->getUsername()} by "
419
+			. $username);
420
+	}
421
+
422
+	#endregion
423
+
424
+	#region comments
425
+
426
+	/**
427
+	 * Summary of commentCreated
428
+	 *
429
+	 * @param Comment $comment
430
+	 * @param Request $request
431
+	 */
432
+	public function commentCreated(Comment $comment, Request $request)
433
+	{
434
+		$username = $this->currentUser->getUsername();
435
+		$visibility = ($comment->getVisibility() == "admin" ? "private " : "");
436
+
437
+		$this->send("{$username} posted a {$visibility}comment on request {$request->getId()} ({$request->getName()})");
438
+	}
439
+
440
+	/**
441
+	 * Summary of commentEdited
442
+	 *
443
+	 * @param Comment $comment
444
+	 * @param Request $request
445
+	 */
446
+	public function commentEdited(Comment $comment, Request $request)
447
+	{
448
+		$username = $this->currentUser->getUsername();
449
+
450
+		$this->send(<<<TAG
451 451
 Comment {$comment->getId()} on request {$request->getId()} ({$request->getName()}) edited by {$username}
452 452
 TAG
453
-        );
454
-    }
455
-
456
-    #endregion
457
-
458
-    #region email management (close reasons)
459
-
460
-    /**
461
-     * Summary of emailCreated
462
-     *
463
-     * @param EmailTemplate $template
464
-     */
465
-    public function emailCreated(EmailTemplate $template)
466
-    {
467
-        $username = $this->currentUser->getUsername();
468
-        $this->send("Email {$template->getId()} ({$template->getName()}) created by " . $username);
469
-    }
470
-
471
-    /**
472
-     * Summary of emailEdited
473
-     *
474
-     * @param EmailTemplate $template
475
-     */
476
-    public function emailEdited(EmailTemplate $template)
477
-    {
478
-        $username = $this->currentUser->getUsername();
479
-        $this->send("Email {$template->getId()} ({$template->getName()}) edited by " . $username);
480
-    }
481
-    #endregion
453
+		);
454
+	}
455
+
456
+	#endregion
457
+
458
+	#region email management (close reasons)
459
+
460
+	/**
461
+	 * Summary of emailCreated
462
+	 *
463
+	 * @param EmailTemplate $template
464
+	 */
465
+	public function emailCreated(EmailTemplate $template)
466
+	{
467
+		$username = $this->currentUser->getUsername();
468
+		$this->send("Email {$template->getId()} ({$template->getName()}) created by " . $username);
469
+	}
470
+
471
+	/**
472
+	 * Summary of emailEdited
473
+	 *
474
+	 * @param EmailTemplate $template
475
+	 */
476
+	public function emailEdited(EmailTemplate $template)
477
+	{
478
+		$username = $this->currentUser->getUsername();
479
+		$this->send("Email {$template->getId()} ({$template->getName()}) edited by " . $username);
480
+	}
481
+	#endregion
482 482
 }
Please login to merge, or discard this patch.
Braces   +2 added lines, -4 removed lines patch added patch discarded remove patch
@@ -60,8 +60,7 @@  discard block
 block discarded – undo
60 60
         if ($notificationsDatabase !== null) {
61 61
             $this->notificationsDatabase = $notificationsDatabase;
62 62
             $this->notificationsEnabled = $siteConfiguration->getIrcNotificationsEnabled();
63
-        }
64
-        else {
63
+        } else {
65 64
             $this->notificationsEnabled = false;
66 65
         }
67 66
 
@@ -239,8 +238,7 @@  discard block
 block discarded – undo
239 238
     {
240 239
         if ($ban->getDuration() === null) {
241 240
             $duration = "indefinitely";
242
-        }
243
-        else {
241
+        } else {
244 242
             $duration = "until " . date("F j, Y, g:i a", $ban->getDuration());
245 243
         }
246 244
 
Please login to merge, or discard this patch.
includes/Helpers/HttpHelper.php 2 patches
Indentation   +104 added lines, -104 removed lines patch added patch discarded remove patch
@@ -13,108 +13,108 @@
 block discarded – undo
13 13
 
14 14
 class HttpHelper
15 15
 {
16
-    private $curlHandle;
17
-
18
-    /**
19
-     * HttpHelper constructor.
20
-     *
21
-     * @param SiteConfiguration $siteConfiguration
22
-     * @param string            $cookieJar
23
-     */
24
-    public function __construct($siteConfiguration, $cookieJar = null)
25
-    {
26
-        $this->curlHandle = curl_init();
27
-
28
-        curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
29
-        curl_setopt($this->curlHandle, CURLOPT_USERAGENT, $siteConfiguration->getUserAgent());
30
-        curl_setopt($this->curlHandle, CURLOPT_FAILONERROR, true);
31
-
32
-        if ($siteConfiguration->getCurlDisableVerifyPeer()) {
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
-    }
16
+	private $curlHandle;
17
+
18
+	/**
19
+	 * HttpHelper constructor.
20
+	 *
21
+	 * @param SiteConfiguration $siteConfiguration
22
+	 * @param string            $cookieJar
23
+	 */
24
+	public function __construct($siteConfiguration, $cookieJar = null)
25
+	{
26
+		$this->curlHandle = curl_init();
27
+
28
+		curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true);
29
+		curl_setopt($this->curlHandle, CURLOPT_USERAGENT, $siteConfiguration->getUserAgent());
30
+		curl_setopt($this->curlHandle, CURLOPT_FAILONERROR, true);
31
+
32
+		if ($siteConfiguration->getCurlDisableVerifyPeer()) {
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
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@
 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
         }
Please login to merge, or discard this patch.