Passed
Push — master ( 33a572...6f44ea )
by Daimona
01:49
created

WikiController::getTimeWithArticle()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php declare( strict_types=1 );
2
3
namespace BotRiconferme;
4
5
use BotRiconferme\Exception\EditException;
6
use BotRiconferme\Exception\LoginException;
7
use BotRiconferme\Exception\APIRequestException;
8
use BotRiconferme\Exception\MissingPageException;
9
use BotRiconferme\Request\RequestBase;
10
11
/**
12
 * Class for wiki interaction, contains some requests shorthands
13
 */
14
class WikiController {
15
	/** @var bool */
16
	private static $loggedIn = false;
17
	/** @var Logger */
18
	private $logger;
19
	/** @var string[] */
20
	private $tokens;
21
22
	public function __construct() {
23
		$this->logger = new Logger;
24
	}
25
26
	/**
27
	 * Gets the content of a wiki page
28
	 *
29
	 * @param string $title
30
	 * @return string
31
	 * @throws MissingPageException
32
	 */
33
	public function getPageContent( string $title ) : string {
34
		$this->logger->debug( "Retrieving page $title" );
35
		$params = [
36
			'action' => 'query',
37
			'titles' => $title,
38
			'prop' => 'revisions',
39
			'rvslots' => 'main',
40
			'rvprop' => 'content'
41
		];
42
43
		$req = RequestBase::newFromParams( $params );
44
		$data = $req->execute();
45
		$page = reset( $data->query->pages );
46
		if ( isset( $page->missing ) ) {
47
			throw new MissingPageException( $title );
48
		}
49
50
		return $page->revisions[0]->slots->main->{ '*' };
51
	}
52
53
	/**
54
	 * Basically a wrapper for action=edit
55
	 *
56
	 * @param array $params
57
	 * @throws EditException
58
	 */
59
	public function editPage( array $params ) {
60
		$this->login();
61
62
		$params = [
63
			'action' => 'edit',
64
			'token' => $this->getToken( 'csrf' ),
65
			'bot' => Config::getInstance()->get( 'bot-edits' )
66
		] + $params;
67
68
		$res = RequestBase::newFromParams( $params, true )->execute();
69
		if ( $res->edit->result !== 'Success' ) {
70
			throw new EditException( $res->edit->info );
71
		}
72
	}
73
74
	/**
75
	 * Get a localized version of article + day + time
76
	 *
77
	 * @param int $timestamp
78
	 * @return string
79
	 * @fixme Not the right place for this
80
	 */
81
	public static function getTimeWithArticle( int $timestamp ) : string {
82
		$oldLoc = setlocale( LC_TIME, 'it_IT', 'Italian_Italy', 'Italian' );
83
		$timeString = strftime( '%e %B alle %R', $timestamp );
84
		// Remove the left space if day has a single digit
85
		$timeString = ltrim( $timeString );
86
		$artic = in_array( date( 'j', $timestamp ), [ 8, 11 ] ) ? "l'" : "il ";
87
		setlocale( LC_TIME, $oldLoc );
88
89
		return $artic . $timeString;
90
	}
91
92
	/**
93
	 * Get a timestamp from a localized time string
94
	 *
95
	 * @param string $timeString
96
	 * @return int
97
	 * @fixme Not the right place for this
98
	 * @todo Is there a better way?
99
	 */
100
	public static function getTimestampFromLocalTime( string $timeString ) : int {
101
		$oldLoc = setlocale( LC_TIME, 'it_IT', 'Italian_Italy', 'Italian' );
102
		$bits = strptime( $timeString, '%e %m %Y alle %H:%M' );
103
		$timestamp = mktime(
104
			$bits['tm_hour'],
105
			$bits['tm_min'],
106
			0,
107
			$bits['tm_mon'] + 1,
108
			$bits['tm_mday'],
109
			$bits['tm_year'] + 1900
110
		);
111
		setlocale( LC_TIME, $oldLoc );
112
113
		return $timestamp;
114
	}
115
	/**
116
	 * Login wrapper. Checks if we're already logged in and clears tokens cache
117
	 * @throws LoginException
118
	 */
119
	public function login() {
120
		if ( self::$loggedIn ) {
121
			$this->logger->debug( 'Already logged in' );
122
			return;
123
		}
124
125
		$this->logger->info( 'Logging in' );
126
127
		$params = [
128
			'action' => 'login',
129
			'lgname' => Config::getInstance()->get( 'username' ),
130
			'lgpassword' => Config::getInstance()->get( 'password' ),
131
			'lgtoken' => $this->getToken( 'login' )
132
		];
133
134
		try {
135
			$res = RequestBase::newFromParams( $params, true )->execute();
136
		} catch ( APIRequestException $e ) {
137
			throw new LoginException( $e->getMessage() );
138
		}
139
140
		if ( !isset( $res->login->result ) || $res->login->result !== 'Success' ) {
141
			throw new LoginException( 'Unknown error' );
142
		}
143
144
		self::$loggedIn = true;
145
		// Clear tokens cache
146
		$this->tokens = [];
147
		$this->logger->info( 'Login succeeded' );
148
	}
149
150
	/**
151
	 * Get a token, cached.
152
	 *
153
	 * @param string $type
154
	 * @return string
155
	 */
156
	public function getToken( string $type ) : string {
157
		if ( !isset( $this->tokens[ $type ] ) ) {
158
			$params = [
159
				'action' => 'query',
160
				'meta'   => 'tokens',
161
				'type'   => $type
162
			];
163
164
			$req = RequestBase::newFromParams( $params );
165
			$res = $req->execute();
166
167
			$this->tokens[ $type ] = $res->query->tokens->{ "{$type}token" };
168
		}
169
170
		return $this->tokens[ $type ];
171
	}
172
173
	/**
174
	 * Get the timestamp of the creation of the given page
175
	 *
176
	 * @param string $title
177
	 * @return int
178
	 */
179
	public function getPageCreationTS( string $title ) : int {
180
		$params = [
181
			'action' => 'query',
182
			'prop' => 'revisions',
183
			'titles' => $title,
184
			'rvprop' => 'timestamp',
185
			'rvslots' => 'main',
186
			'rvlimit' => 1,
187
			'rvdir' => 'newer'
188
		];
189
190
		$res = ( RequestBase::newFromParams( $params ) )->execute();
191
		$data = $res->query->pages;
192
		return strtotime( reset( $data )->revisions[0]->timestamp );
193
	}
194
195
	/**
196
	 * Sysop-level inifinite protection for a given page
197
	 *
198
	 * @param string $title
199
	 * @param string $reason
200
	 */
201
	public function protectPage( string $title, string $reason ) {
202
		$this->logger->info( "Protecting page $title" );
203
		$this->login();
204
205
		$params = [
206
			'action' => 'protect',
207
			'title' => $title,
208
			'protections' => 'edit=sysop|move=sysop',
209
			'expiry' => 'infinite',
210
			'reason' => $reason,
211
			'token' => $this->getToken( 'csrf' )
212
		];
213
214
		RequestBase::newFromParams( $params, true )->execute();
215
	}
216
}
217