Test Failed
Push — newinternal ( 8c4587...b2f220 )
by Michael
15:41 queued 06:17
created

BotMediaWikiClient::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 6
c 1
b 0
f 0
dl 0
loc 10
rs 10
cc 1
nc 1
nop 1
1
<?php
2
/******************************************************************************
3
 * Wikipedia Account Creation Assistance tool                                 *
4
 *                                                                            *
5
 * All code in this file is released into the public domain by the ACC        *
6
 * Development Team. Please see team.json for a list of contributors.         *
7
 ******************************************************************************/
8
9
namespace Waca\Helpers;
10
11
use Waca\Exceptions\ApplicationLogicException;
12
use Waca\Exceptions\CurlException;
13
use Waca\Exceptions\MediaWikiApiException;
14
use Waca\Helpers\Interfaces\IMediaWikiClient;
15
use Waca\SiteConfiguration;
0 ignored issues
show
Bug introduced by
The type Waca\SiteConfiguration was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
17
class BotMediaWikiClient implements IMediaWikiClient
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) {
0 ignored issues
show
introduced by
The condition $data === false is always false.
Loading history...
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
}
151