Passed
Push — master ( 15004c...cc9b5c )
by Daimona
02:30 queued 44s
created

Wiki::setDomain()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php declare( strict_types=1 );
2
3
namespace BotRiconferme\Wiki;
4
5
use BotRiconferme\Config;
6
use BotRiconferme\Exception\EditException;
7
use BotRiconferme\Exception\LoginException;
8
use BotRiconferme\Exception\APIRequestException;
9
use BotRiconferme\Exception\MissingPageException;
10
use BotRiconferme\Exception\MissingSectionException;
11
use BotRiconferme\Request\RequestBase;
12
use Psr\Log\LoggerInterface;
13
14
/**
15
 * Class for wiki interaction, contains some requests shorthands
16
 */
17
class Wiki {
18
	/** @var bool */
19
	private static $loggedIn = false;
20
	/** @var LoggerInterface */
21
	private $logger;
22
	/** @var string */
23
	private $domain;
24
	/** @var string[] */
25
	private $tokens;
26
27
	/**
28
	 * @param LoggerInterface $logger
29
	 * @param string $domain The URL of the wiki, if different from default
30
	 */
31
	public function __construct( LoggerInterface $logger, string $domain = DEFAULT_URL ) {
32
		$this->logger = $logger;
33
		$this->domain = $domain;
34
	}
35
36
	/**
37
	 * Gets the content of a wiki page
38
	 *
39
	 * @param string $title
40
	 * @param int|null $section
41
	 * @return string
42
	 * @throws MissingPageException
43
	 * @throws MissingSectionException
44
	 */
45
	public function getPageContent( string $title, int $section = null ) : string {
46
		$msg = "Retrieving content of $title" . ( $section !== null ? ", section $section" : '' );
47
		$this->logger->debug( $msg );
48
		$params = [
49
			'action' => 'query',
50
			'titles' => $title,
51
			'prop' => 'revisions',
52
			'rvslots' => 'main',
53
			'rvprop' => 'content'
54
		];
55
56
		if ( $section !== null ) {
57
			$params['rvsection'] = $section;
58
		}
59
60
		$req = RequestBase::newFromParams( $params )->setUrl( $this->domain );
61
		$data = $req->execute();
62
		$page = reset( $data->query->pages );
63
		if ( isset( $page->missing ) ) {
64
			throw new MissingPageException( $title );
65
		}
66
67
		$mainSlot = $page->revisions[0]->slots->main;
68
69
		// @phan-suppress-next-line PhanImpossibleTypeComparison $section can be null
70
		if ( $section !== null && isset( $mainSlot->nosuchsection ) ) {
71
			throw new MissingSectionException( $title, $section );
72
		}
73
		return $mainSlot->{ '*' };
74
	}
75
76
	/**
77
	 * Basically a wrapper for action=edit
78
	 *
79
	 * @param array $params
80
	 * @throws EditException
81
	 */
82
	public function editPage( array $params ) {
83
		$this->login();
84
85
		$params = [
86
			'action' => 'edit',
87
			'token' => $this->getToken( 'csrf' ),
88
		] + $params;
89
90
		if ( Config::getInstance()->get( 'bot-edits' ) ) {
91
			$params['bot'] = 1;
92
		}
93
94
		$res = RequestBase::newFromParams( $params )
95
			->setUrl( $this->domain )
96
			->setPost()
97
			->execute();
98
99
		$editData = $res->edit;
100
		if ( $editData->result !== 'Success' ) {
101
			if ( isset( $editData->captcha ) ) {
102
				throw new EditException( 'Got captcha!' );
103
			}
104
			throw new EditException( $editData->info ?? reset( $editData ) );
105
		}
106
	}
107
108
	/**
109
	 * Login wrapper. Checks if we're already logged in and clears tokens cache
110
	 * @throws LoginException
111
	 */
112
	public function login() {
113
		if ( self::$loggedIn ) {
114
			return;
115
		}
116
117
		// Yes, this is an easter egg.
118
		$this->logger->info( 'Logging in. Username: BotRiconferme, password: correctHorseBatteryStaple' );
119
120
		$params = [
121
			'action' => 'login',
122
			'lgname' => Config::getInstance()->get( 'username' ),
123
			'lgpassword' => Config::getInstance()->get( 'password' ),
124
			'lgtoken' => $this->getToken( 'login' )
125
		];
126
127
		try {
128
			$res = RequestBase::newFromParams( $params )->setUrl( $this->domain )->setPost()->execute();
129
		} catch ( APIRequestException $e ) {
130
			throw new LoginException( $e->getMessage() );
131
		}
132
133
		if ( !isset( $res->login->result ) || $res->login->result !== 'Success' ) {
134
			throw new LoginException( 'Unknown error' );
135
		}
136
137
		self::$loggedIn = true;
138
		// Clear tokens cache
139
		$this->tokens = [];
140
		$this->logger->info( 'Login succeeded' );
141
	}
142
143
	/**
144
	 * Get a token, cached.
145
	 *
146
	 * @param string $type
147
	 * @return string
148
	 */
149
	public function getToken( string $type ) : string {
150
		if ( !isset( $this->tokens[ $type ] ) ) {
151
			$params = [
152
				'action' => 'query',
153
				'meta'   => 'tokens',
154
				'type'   => $type
155
			];
156
157
			$req = RequestBase::newFromParams( $params )->setUrl( $this->domain );
158
			$res = $req->execute();
159
160
			$this->tokens[ $type ] = $res->query->tokens->{ "{$type}token" };
161
		}
162
163
		return $this->tokens[ $type ];
164
	}
165
166
	/**
167
	 * Get the timestamp of the creation of the given page
168
	 *
169
	 * @param string $title
170
	 * @return int
171
	 */
172
	public function getPageCreationTS( string $title ) : int {
173
		$params = [
174
			'action' => 'query',
175
			'prop' => 'revisions',
176
			'titles' => $title,
177
			'rvprop' => 'timestamp',
178
			'rvslots' => 'main',
179
			'rvlimit' => 1,
180
			'rvdir' => 'newer'
181
		];
182
183
		$res = RequestBase::newFromParams( $params )->setUrl( $this->domain )->execute();
184
		$data = $res->query->pages;
185
		return strtotime( reset( $data )->revisions[0]->timestamp );
186
	}
187
188
	/**
189
	 * Sysop-level inifinite protection for a given page
190
	 *
191
	 * @param string $title
192
	 * @param string $reason
193
	 */
194
	public function protectPage( string $title, string $reason ) {
195
		$this->logger->info( "Protecting page $title" );
196
		$this->login();
197
198
		$params = [
199
			'action' => 'protect',
200
			'title' => $title,
201
			'protections' => 'edit=sysop|move=sysop',
202
			'expiry' => 'infinite',
203
			'reason' => $reason,
204
			'token' => $this->getToken( 'csrf' )
205
		];
206
207
		RequestBase::newFromParams( $params )->setUrl( $this->domain )->setPost()->execute();
208
	}
209
}
210