aboutsummaryrefslogtreecommitdiff
path: root/Vote.php
blob: 8265604096bf88416dafbd87494ea379f4ccc8e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
use MediaWiki\MediaWikiServices;

class VoteHooks {
	public static $options = ['yes', 'no', 'abstain'];

	public static function onParserFirstCallInit( Parser $parser ) {
		$parser->setHook( 'vote', [ self::class, 'renderVoteTag' ] );
	}

	public static function onParserPreSaveTransformComplete( Parser $parser, string &$text ) {
		// workaround for https://phabricator.wikimedia.org/T319221
		$sigText = $parser->getUserSig(RequestContext::getMain()->getUser());
		$datetime = getFormattedTimestamp($parser);
		$text = preg_replace('/(?<!<nowiki>)(?<!<pre>)~~~~/', "$sigText $datetime", $text);
		// NOTE: this regex obviously matches false positives, however since
		// it's quite uncommon for ~~~~ to occur in wiki pages this is deemed good enough
		// until T319221 is addressed and this workaround is no longer necessary
	}

	// Render <vote>
	public static function renderVoteTag( $input, array $args, Parser $parser, PPFrame $frame ) {

		$msg = function (...$args) use ($parser) {
			// wfMessage() uses the interface language by default ... but since
			// MediaWiki caches the rendered page we of course want to use the
			// page content language instead. This closure is just for convenience.
			return wfMessage(...$args)->inLanguage($parser->getTargetLanguage());
		};

		$addErrorCategory = function () use ($parser) {
			$parser->addTrackingCategory('pages-with-vote-errors-category', $parser->getTitle());
		};

		$voteClosed = false;
		$endDate = null;

		$end = $args['end'] ?? null;
		unset($args['end']);
		$cancel = $args['cancel'] ?? null;
		unset($args['cancel']);

		$text = '';

		if ($cancel !== null) {
			$voteClosed = $msg('vote-cancelled');
		} else if ($end) {
			$endDate = DateTime::createFromFormat('Y-m-d', $end);
			if (!$endDate) {
				$addErrorCategory();
				return formatError($msg('vote-error-end'));
			}

			$endDate->setTime(23, 59);
			$now = new Datetime();
			$tz = date_default_timezone_get();

			if ($now > $endDate) {
				$voteClosed = $msg('vote-ended', $endDate->format('jS F Y, H:i') . " ($tz)");
			} else {
				$text .= $msg('vote-will-end', $endDate->format('jS F Y, H:i') . " ($tz)");
				$parser->getOutput()->updateCacheExpiry($endDate->getTimestamp() - $now->getTimestamp());
			}
		}


		if (!empty($args)) {
			$addErrorCategory();
			return formatError($msg('vote-error-unknown-attribute', array_keys($args)[0]));
		}

		if (!str_ends_with($input, "\n")) {
			$addErrorCategory();
			return formatError($msg('vote-error-missing-newline'));
		}

		// Parse the passed text into $lines.
		// Sidenote: We parse and render in two steps because we need both:
		// * lookahead (gray out votes that are superseded), as well as
		// * lookbehind (prefix "I changed my mind" for superseding votes).
		$lines = [];

		foreach (explode("\n", $input) as $line) {
			if (str_starts_with($line, '* ')) {
				$line = substr($line, 2);
				$vote = self::parseVote($line);

				if (!$vote['date']) {
					array_push($lines, ['error' => $msg('vote-error-invalid-date'), 'line' => $line]);
					continue;
				}
				if ($endDate && $vote['date'] > $endDate) {
					array_push($lines, ['error' => $msg('vote-error-too-late'), 'line' => $line]);
					continue;
				}
				if (!in_array($vote['vote'], self::$options)) {
					array_push($lines, ['error' => $msg('vote-error-invalid-vote', '(YES, NO, ABSTAIN)'), 'line' => $line]);
					continue;
				}

				array_push($lines, $vote);
				continue;
			}

			array_push($lines, ['raw' => $line . "\n"]);
		}

		// Render the parsed $lines into $voteText.
		$voteText = '';
		$votes = [];

		foreach ($lines as $idx => $line) {
			if (array_key_exists('raw', $line)) {
				$voteText .= $parser->recursiveTagParse($line['raw']);
			} elseif (array_key_exists('error', $line)) {
				$addErrorCategory();
				$voteText .= '* ' . formatError($line['error'] . ':') . " " . $line['line'] . "\n";
			} else {
				$user = $line['user'];
				$vote = $line['vote'];

				$voteText .= '* ';
				$class = '';
				for ($i = $idx + 1; $i < count($lines); $i++) {
					if (($lines[$i]['user'] ?? null) == $user) {
						$class = 'uncounted-vote';
					}
				}
				$voteText .= "<span class=$class>";
				if (array_key_exists($user, $votes)) {
					if ($votes[$user] == $vote) {
						$voteText .= "(" . $msg('vote-repeated') . ') ';
					} else {
						$voteText .= $msg('vote-changed') . ', ';
					}
				}
				$votes[$user] = $vote;
				$voteText .= $msg('vote-option-' . $vote) . ' ';
				if ($line['comment']) {
					$voteText .= $parser->recursiveTagParse($line['comment']);
				}

				$userLink = $parser->getLinkRenderer()->makeLink($line['userTitle'], $user);
				$voteText .= " --$userLink ". $line['date']->format('H:i, j F Y');
				$voteText .= "</span>\n";
			}
		}

		$voteCounts = ['yes' => 0, 'no' => 0, 'abstain' => 0];

		foreach (array_values($votes) as $vote) {
			$voteCounts[$vote] += 1;
		}

		if (!$voteClosed && $parser->getOutput()->getExtensionData('vote-open')) {
			$voteClosed = formatError($msg('vote-error-one-vote-per-page'));
			$addErrorCategory();
		}
		$parser->getOutput()->appendExtensionData('vote-open', true);

		$text .= '<div>';
		if (array_sum(array_values($voteCounts)) == 0 && !$voteClosed) {
			$text .= $msg('vote-call-to-vote');
		} else {
			$text .= $msg('vote-tally', $voteCounts['yes'], $voteCounts['no'], $voteCounts['abstain']);
		}
		$text .= '</div>';

		$text .= $voteText;

		if ($voteClosed) {
			$text .= $voteClosed;
		} else {
			$text .= self::votingFormHtml($parser, $votes);
			$parser->addTrackingCategory('pages-with-open-votes-category', $parser->getTitle());
		}

		$parser->getOutput()->addModules(['ext.vote-css']);

		return $text;
	}

	private static function parseVote($line) {
		$date = DateTime::createFromFormat('Y-m-d H:i', substr($line, 0, strlen('2022-10-03 10:00')));
		$parts = explode(' ', substr($line, strlen('2022-10-03 10:00 ')), 3);
		$userTitle = Title::newFromText('User:' . rtrim(array_shift($parts), ':'));
		$user = $userTitle ? $userTitle->getText() : null;
		$vote = strtolower(array_shift($parts));
		$comment = array_shift($parts);
		return ['date' => $date, 'userTitle' => $userTitle, 'user' => $user, 'vote' => $vote, 'comment' => $comment];
	}

	private static function votingFormHtml($parser, $votes) {
		$previewMode = $parser->getRevisionId() == null;

		$formDescriptor = [
			'vote' => [
				'type' => 'radio',
				'options' => array_reduce(self::$options, function($result, $opt) use ($parser) {
					$result[wfMessage('vote-option-' . $opt)->inLanguage($parser->getTargetLanguage())->parse()] = $opt;
					return $result;
				}),
				// ideally we would set 'required' => true here but unfortunately that doesn't work
				// see https://phabricator.wikimedia.org/T319216
				'disabled' => $previewMode,
			],
			'comment' => [
				'type' => 'textarea',
				'rows' => 3,
				'label' => wfMessage('vote-comment')->inLanguage($parser->getTargetLanguage()),
				'disabled' => $previewMode,
				'cssclass' => 'vote-comment-textarea',
			],
			'page' => [
				'type' => 'hidden',
				'name' => 'page',
				'default' => $parser->getTitle()
			]
		];

		$parser->getOutput()->addModules(['ext.vote-js']);

		$form = new HTMLForm( $formDescriptor );

		if ($previewMode)
			$form->suppressDefaultSubmit();

		$form->mFieldData = [];

		$form
			->setId('vote-form')
			->setTitle(Title::newFromText('Special:InsertVote'))
			->setSubmitText( 'Submit' )
			->setAutocomplete('off')
			->setDisplayFormat('div')
			->addHeaderHtml('<h3>' . wfMessage('vote-add-your-vote')->inLanguage($parser->getTargetLanguage()) . '</h3>')
			->addFooterHtml('<script type="application/json" data-votes>'. json_encode($votes) . '</script>');

		// The MobileFrontend extension requires the mw-ui-button CSS class for
		// buttons to look good.  Xml::submitButton however only adds that CSS
		// class when the global variable $wgUseMediaWikiUIEverywhere is set to
		// true ... and MobileFrontend for some reason doesn't set that variable,
		// so we just set it here ... ¯\_(ツ)_/¯
		global $wgUseMediaWikiUIEverywhere;
		$wgUseMediaWikiUIEverywhere = true;

		$html = $form->getHTML(false);

		// dirty hack to work around https://phabricator.wikimedia.org/T319216
		$html = str_replace('type="radio"', 'type="radio" required', $html);

		return $html;
	}
}

// We need a special page to receive the submitted votes.
class SpecialInsertVote extends UnlistedSpecialPage {
	function __construct() {
		parent::__construct( 'InsertVote' );
	}

	function execute( $par ) {
		$request = $this->getRequest();
		$output = $this->getOutput();

		$page = $request->getVal('page');
		if ($page == null) {
			$output->setStatusCode(400);
			$output->prepareErrorPage('missing page parameter');
			return;
		}
		$vote = $request->getVal('wpvote');
		if ($vote == null) {
			$output->setStatusCode(400);
			$output->prepareErrorPage('missing wpvote parameter');
			return;
		}
		$comment = $request->getText('wpcomment');

		$services = MediaWikiServices::getInstance();
		$permissionManager = $services->getPermissionManager();

		if ($this->getUser()->isAnon()) {
			$loginPageTitle = Title::newFromText('Special:UserLogin');
			$this->getOutput()->redirect($loginPageTitle->getFullURL([
				'returnto' => 'Special:InsertVote',
				'returntoquery' => $request->getRawPostString()
			]));
			return;
		}

		$title = Title::newFromText($page);
		$permissionErrors = $permissionManager->getPermissionErrors('edit', $this->getUser(), $title);
		if (!empty($permissionErrors)) {
			$output->prepareErrorPage("You are not allowed to edit this page.");
			$output->setStatusCode(403);
			return;
		}
		$content = WikiPage::factory($title)->getContent();
		if ($content == null) {
			$output->prepareErrorPage("The page no longer exists.");
			$output->setStatusCode(500);
			return;
		}
		$content = ContentHandler::getContentText($content);

		$date = date('Y-m-d H:i');
		$username = str_replace(' ', '_', $this->getUser()->getName());
		$comment = str_replace("\n", ' ', $comment);
		$newLine = "* $date $username: " . strtoupper($vote);
		if ($comment)
			$newLine .= ' ' . $comment;

		// not using preg_replace because we don't want references like $1 in the comment to be interpreted
		preg_match(',^</vote *>?$,m', $content, $matches, PREG_OFFSET_CAPTURE);
		if (!$matches) {
			$output->prepareErrorPage("could not find </vote> tag, maybe someone has removed the vote in the meantime?");
			$output->setStatusCode(500);
			return;
		}
		$offset = $matches[0][1];
		$content = substr($content, 0, $offset) . $newLine . "\n" . substr($content, $offset);

		$page = WikiPage::factory($title);
		$pageLang = $page->getLanguage() ?? $services->getContentLanguage();
		$status = $page->doUserEditContent(
			new WikitextContent($content),
			$this->getUser(),
			wfMessage('vote-editmsg-' . $vote)->inLanguage($pageLang), EDIT_UPDATE, false, ['vote']
		);
		if ($status->isOK()) {
			$this->getOutput()->redirect($title->getFullURL());
		} else {
			$output->prepareErrorPage($status->getHTML());
			$output->setStatusCode(500);
		}
	}
}

function formatError($error) {
	// The CSS class is provided by MediaWiki.
	return "<span class=error>$error</span>";
}

function getFormattedTimestamp($parser) {
	// This function exists solely because of the onParserPreSaveTransformComplete workaround for https://phabricator.wikimedia.org/T319221.
	// It is supposed to mirror the behavior of https://gerrit.wikimedia.org/r/plugins/gitiles/mediawiki/core/+/refs/tags/1.38.4/includes/parser/Parser.php#4575.

	$ts = $parser->mOptions->getTimestamp();
	$timestamp = MWTimestamp::getLocalInstance( $ts );
	$ts = $timestamp->format( 'YmdHis' );
	$tzMsg = $timestamp->getTimezoneMessage()->inContentLanguage()->text();
	return $parser->getContentLanguage()->timeanddate( $ts, false, false ) . " ($tzMsg)";
}