BotMediaWikiClient::ensureLoggedIn()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
dl 0
loc 22
rs 9.8666
c 1
b 0
f 0
cc 4
nc 4
nop 0
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\DataObjects\Domain;
12
use Waca\Exceptions\ApplicationLogicException;
13
use Waca\Exceptions\CurlException;
14
use Waca\Exceptions\MediaWikiApiException;
15
use Waca\Helpers\Interfaces\IMediaWikiClient;
16
use Waca\SiteConfiguration;
17
18
class BotMediaWikiClient implements IMediaWikiClient
19
{
20
    /**
21
     * @var HttpHelper
22
     */
23
    private $httpHelper;
24
    /** @var string */
25
    private $mediawikiWebServiceEndpoint;
26
    /** @var string */
27
    private $creationBotUsername;
28
    /** @var string */
29
    private $creationBotPassword;
30
    /** @var bool */
31
    private $knownLoggedIn = false;
32
33
    /**
34
     * BotMediaWikiClient constructor.
35
     *
36
     * @param SiteConfiguration        $siteConfiguration
37
     * @param Domain $domain
38
     */
39
    public function __construct(SiteConfiguration $siteConfiguration, Domain $domain)
40
    {
41
        $this->mediawikiWebServiceEndpoint = $domain->getWikiApiPath();
42
43
        $this->creationBotUsername = $siteConfiguration->getCreationBotUsername();
44
        $this->creationBotPassword = $siteConfiguration->getCreationBotPassword();
45
46
        $this->httpHelper = new HttpHelper(
47
            $siteConfiguration,
48
            $siteConfiguration->getCurlCookieJar()
49
        );
50
    }
51
52
    public function doApiCall($apiParams, $method = 'GET')
53
    {
54
        $this->ensureLoggedIn();
55
        $apiParams['assert'] = 'user';
56
57
        return $this->callApi($apiParams, $method);
58
    }
59
60
    private function ensureLoggedIn()
61
    {
62
        if ($this->knownLoggedIn) {
63
            return;
64
        }
65
66
        $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
67
        if (isset($userinfoResult->query->userinfo->anon)) {
68
            // not logged in.
69
            $this->logIn();
70
71
            // retest
72
            $userinfoResult = $this->callApi(array('action' => 'query', 'meta' => 'userinfo'), 'GET');
73
            if (isset($userinfoResult->query->userinfo->anon)) {
74
                throw new MediaWikiApiException('Unable to log in.');
75
            }
76
            else {
77
                $this->knownLoggedIn = true;
78
            }
79
        }
80
        else {
81
            $this->knownLoggedIn = true;
82
        }
83
    }
84
85
    /**
86
     * @param $apiParams
87
     * @param $method
88
     *
89
     * @return mixed
90
     * @throws ApplicationLogicException
91
     * @throws CurlException
92
     */
93
    private function callApi($apiParams, $method)
94
    {
95
        $apiParams['format'] = 'json';
96
97
        if ($method == 'GET') {
98
            $data = $this->httpHelper->get($this->mediawikiWebServiceEndpoint, $apiParams);
99
        }
100
        elseif ($method == 'POST') {
101
            $data = $this->httpHelper->post($this->mediawikiWebServiceEndpoint, $apiParams);
102
        }
103
        else {
104
            throw new ApplicationLogicException('Unsupported HTTP Method');
105
        }
106
107
        if ($data === false) {
0 ignored issues
show
introduced by
The condition $data === false is always false.
Loading history...
108
            throw new CurlException('Curl error: ' . $this->httpHelper->getError());
109
        }
110
111
        $result = json_decode($data);
112
113
        return $result;
114
    }
115
116
    private function logIn()
117
    {
118
        // get token
119
        $tokenParams = array(
120
            'action' => 'query',
121
            'meta'   => 'tokens',
122
            'type'   => 'login',
123
        );
124
125
        $response = $this->callApi($tokenParams, 'POST');
126
127
        if (isset($response->error)) {
128
            throw new MediaWikiApiException($response->error->code . ': ' . $response->error->info);
129
        }
130
131
        $token = $response->query->tokens->logintoken;
132
133
        if ($token === null) {
134
            throw new MediaWikiApiException('Edit token could not be acquired');
135
        }
136
137
        $params = array(
138
            'action' => 'login',
139
            'lgname' => $this->creationBotUsername,
140
            'lgpassword' => $this->creationBotPassword,
141
            'lgtoken' => $token,
142
        );
143
144
        $loginResponse = $this->callApi($params, 'POST');
145
146
        if ($loginResponse->login->result == 'Success') {
147
            return;
148
        }
149
150
        throw new ApplicationLogicException(json_encode($loginResponse));
151
    }
152
}
153