summaryrefslogtreecommitdiff
blob: ef3a711ef656f53a7b974bb3c48f1b2c0e48fdde (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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
<?php
// phpcs:disable Generic.Files.LineLength -- Long html test examples
// @phan-file-suppress PhanUndeclaredClassMethod, PhanUndeclaredClassConstant Other extensions used for testing purposes

use MediaWiki\MediaWikiServices;
use MediaWiki\Revision\RevisionRecord;
use MediaWiki\Revision\SlotRecord;
use Wikibase\Client\Hooks\EchoNotificationsHandlers;

$IP = getenv( 'MW_INSTALL_PATH' );
if ( $IP === false ) {
	$IP = __DIR__ . '/../../..';
}
require_once "$IP/maintenance/Maintenance.php";

/**
 * A maintenance script that generates sample notifications for testing purposes.
 */
class GenerateSampleNotifications extends Maintenance {

	private $supportedNotificationTypes = [
		'welcome',
		'edit-user-talk',
		'mention',
		'page-linked',
		'reverted',
		'email',
		'user-rights',
		'cx',
		'osm',
		'edit-thanks',
		'edu',
		'page-connection',
	];

	private $timestampCounter = 5;

	public function __construct() {
		parent::__construct();
		$this->addDescription( "Generate sample notifications" );

		$this->addOption(
			'force',
			'Bypass confirmation',
			false, false, 'f' );

		$allTypes = implode( ',', $this->supportedNotificationTypes );
		$this->addOption(
			'types',
			"Comma-separated list of notification types to generate ($allTypes)",
			false, true, 't' );

		$this->addOption(
			'user',
			'Name of the user receiving the notifications',
			true, true, 'u' );

		$this->addOption(
			'agent',
			'Name of the user creating the notifications',
			true, true, 'a' );

		$this->addOption(
			'other',
			'Name of another user involved with the notifications',
			true, true, 'o' );

		$this->requireExtension( 'Echo' );

		$this->addOption(
			'timestamp',
			'Add notification timestamps (Epoch time format). All notifications that are not ' .
				'related directly to edits will be created with a timestamp starting 5 minutes ' .
				'before the given timestamp, and increasing by 1 minute per notification.',
			false, false, 'k' );
	}

	public function execute() {
		$user = $this->getOptionUser( 'user' );
		$agent = $this->getOptionUser( 'agent' );
		$otherUser = $this->getOptionUser( 'other' );
		$title = Title::newFromText( 'This is a pretty long page title lets see if it is going to be truncated' );

		$types = $this->getOption( 'types' );
		if ( $types ) {
			$types = explode( ',', $types );
		} else {
			$types = $this->supportedNotificationTypes;
		}

		$this->confirm();

		$this->output( "Started processing...\n" );

		if ( $this->shouldGenerate( 'welcome', $types ) ) {
			$this->generateWelcome( $user );
		}

		if ( $this->shouldGenerate( 'edit-user-talk', $types ) ) {
			$this->generateEditUserTalk( $user, $agent );
		}

		if ( $this->shouldGenerate( 'mention', $types ) ) {
			$this->generateMention( $user, $agent, $otherUser, $title );
		}

		if ( $this->shouldGenerate( 'page-linked', $types ) ) {
			$this->generatePageLink( $user, $agent );
		}

		if ( $this->shouldGenerate( 'reverted', $types ) ) {
			$this->generateReverted( $user, $agent );
		}

		if ( $this->shouldGenerate( 'email', $types ) ) {
			$this->generateEmail( $user, $agent );
		}

		if ( $this->shouldGenerate( 'user-rights', $types ) ) {
			$this->generateUserRights( $user, $agent );
		}

		if ( $this->shouldGenerate( 'cx', $types ) ) {
			$this->generateContentTranslation( $user );
		}

		if ( $this->shouldGenerate( 'osm', $types ) ) {
			$this->generateOpenStackManager( $user, $agent );
		}

		if ( $this->shouldGenerate( 'edit-thanks', $types ) ) {
			$this->generateEditThanks( $user, $agent, $otherUser );
		}

		if ( $this->shouldGenerate( 'edu', $types ) ) {
			$this->generateEducationProgram( $user, $agent );
		}

		if ( $this->shouldGenerate( 'page-connection', $types ) ) {
			$this->generateWikibase( $user, $agent );
		}

		$this->output( "Completed \n" );
	}

	/**
	 * Get the set timestamp of the event
	 *
	 * @param bool $getEpoch Get the epoch value
	 * @return int Timestamp for the operation
	 */
	private function getTimestamp( $getEpoch = false ) {
		$startTime = $this->getOption( 'timestamp' ) ?: time();

		// Incrementally decrease X minutes from start time
		$timestamp = strtotime( '-' . $this->timestampCounter++ . ' minute', $startTime );

		return $getEpoch ? $timestamp : (int)wfTimestamp( TS_UNIX, $timestamp );
	}

	/**
	 * Add a timestamp string to the output, if a timestamp option was given,
	 * to note the time of the new generated event.
	 *
	 * @param string $output New output message with timestamp
	 * @return string
	 */
	private function addTimestampToOutput( $output ) {
		if ( $this->getOption( 'timestamp' ) ) {
			$output .= ' (Using timestamp: ' . date( 'Y-m-d H:i:s', $this->getTimestamp( true ) ) . ')';
		}
		return $output;
	}

	private function generateEditUserTalk( User $user, User $agent ) {
		$this->output( "{$agent->getName()} is writing on {$user->getName()}'s user talk page\n" );
		$editId = $this->generateRandomString();
		$section = "== section $editId ==\n\nthis is the text $editId\n\n~~~~\n\n";
		$this->addToUserTalk( $user, $agent, $section );
	}

	private function getOptionUser( $optionName ) {
		$username = $this->getOption( $optionName );
		$user = User::newFromName( $username );
		if ( $user->isAnon() ) {
			$this->error( "User $username does not seem to exist in this wiki", 1 );
		}
		return $user;
	}

	private function generateRandomString( $length = 10 ) {
		return substr( str_shuffle( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ), 0, $length );
	}

	protected function confirm() {
		if ( $this->getOption( 'force', false ) ) {
			return;
		}
		$this->output( "===   WARNING   ===\n" );
		$this->output( "This script modifies the content of several pages,\n" );
		$this->output( "including user's talk pages.\n" );
		$this->output( "ONLY RUN ON TEST WIKIS\n" );
		$this->output( "Enter 'yes' if you wish to continue or any other key to exit\n" );
		$confirm = $this->readconsole();
		if ( $confirm !== 'yes' ) {
			$this->error( 'Safe decision', 1 );
		}
	}

	private function addToUserTalk( User $user, User $agent, $contentText ) {
		$this->addToPageContent( $user->getTalkPage(), $agent, $contentText );
	}

	private function addToPageContent( Title $title, User $agent, $contentText ) {
		$page = WikiPage::factory( $title );
		$previousContent = "";
		$page->loadPageData( WikiPage::READ_LATEST );
		$revision = $page->getRevisionRecord();
		if ( $revision ) {
			$content = $revision->getContent( SlotRecord::MAIN, RevisionRecord::FOR_PUBLIC );
			if ( $content instanceof WikitextContent ) {
				$previousContent = $content->getText();
			}
		}
		$status = $page->doEditContent(
			new WikitextContent( $contentText . $previousContent ),
			'generating sample notifications',
			0,
			false,
			$agent
		);

		if ( !$status->isGood() ) {
			$this->error( "Failed to edit {$title->getPrefixedText()}: {$status->getMessage()->text()}" );
		}

		return $status->getValue()['revision-record'];
	}

	private function generateMention( User $user, User $agent, User $otherUser, Title $title ) {
		$mention = "== section {$this->generateRandomString()} ==\nHello [[User:{$user->getName()}]] \n~~~~\n";

		// article talk
		$this->output( "{$agent->getName()} is mentioning {$user->getName()} on {$title->getTalkPage()->getPrefixedText()}\n" );
		$this->addToPageContent( $title->getTalkPage(), $agent, $mention );

		// agent tak
		$this->output( "{$agent->getName()} is mentioning {$user->getName()} on {$agent->getTalkPage()->getPrefixedText()}\n" );
		$this->addToPageContent( $agent->getTalkPage(), $agent, $mention );

		// user talk
		$this->output( "{$agent->getName()} is mentioning {$user->getName()} on {$otherUser->getTalkPage()->getPrefixedText()}\n" );
		$this->addToPageContent( $otherUser->getTalkPage(), $agent, $mention );

		// any other page
		$this->output( "{$agent->getName()} is mentioning {$user->getName()} on {$title->getPrefixedText()}\n" );
		$this->addToPageContent( $title, $agent, $mention );
	}

	private function generatePageLink( User $user, User $agent ) {
		$this->generateOnePageLink( $user, $agent );
		$this->generateMultiplePageLinks( $user, $agent );
	}

	private function generateNewPageTitle() {
		return Title::newFromText( $this->generateRandomString() );
	}

	private function generateReverted( User $user, User $agent ) {
		$agent->addGroup( 'sysop' );

		// revert (undo)
		$moai = Title::newFromText( 'Moai' );
		$page = WikiPage::factory( $moai );
		$this->output( "{$agent->getName()} is reverting {$user->getName()}'s edit on {$moai->getPrefixedText()}\n" );
		$this->addToPageContent( $moai, $agent, "\ncreating a good revision here\n" );
		$this->addToPageContent( $moai, $user, "\nadding a line here\n" );

		$undoRev = $page->getRevisionRecord();
		$previous = MediaWikiServices::getInstance()
			->getRevisionLookup()
			->getPreviousRevision( $undoRev );

		$handler = MediaWikiServices::getInstance()
			->getContentHandlerFactory()
			->getContentHandler(
				$undoRev->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )
					->getModel()
			);
		$undoContent = $undoRev->getContent( SlotRecord::MAIN );
		$previousContent = $previous->getContent( SlotRecord::MAIN );

		$content = $handler->getUndoContent(
			$undoContent,
			$undoContent,
			$previousContent,
			true // undoIsLatest
		);

		$status = $page->doEditContent( $content, 'undo', 0, false, $agent, null, [], $undoRev->getId() );
		if ( !$status->isGood() ) {
			$this->error( "Failed to undo {$moai->getPrefixedText()}: {$status->getMessage()->text()}" );
		}
	}

	private function generateWelcome( User $user ) {
		$this->output( "Welcoming {$user->getName()}\n" );
		EchoEvent::create( [
			'type' => 'welcome',
			'agent' => $user,
			'timestamp' => $this->getTimestamp(),
		] );
	}

	private function generateEmail( User $user, User $agent ) {
		$output = $this->addTimestampToOutput( "{$agent->getName()} is emailing {$user->getName()}" );
		$this->output( "$output\n" );
		EchoEvent::create( [
			'type' => 'emailuser',
			'extra' => [
				'to-user-id' => $user->getId(),
				'subject' => 'Long time no see',
			],
			'agent' => $agent,
			'timestamp' => $this->getTimestamp(),
		] );
	}

	private function generateUserRights( User $user, User $agent ) {
		$output = $this->addTimestampToOutput( "{$agent->getName()} is changing {$user->getName()}'s rights" );
		$this->output( "$output\n" );
		$this->createUserRightsNotification( $user, $agent, [ 'OnlyAdd-1' ], null );
		$this->createUserRightsNotification( $user, $agent, null, [ 'JustRemove-1', 'JustRemove-2' ] );
		$this->createUserRightsNotification( $user, $agent, [ 'Add-1', 'Add-2' ], [ 'Remove-1', 'Remove-2' ] );
	}

	private function createUserRightsNotification( User $user, User $agent, $add, $remove ) {
		EchoEvent::create(
			[
				'type' => 'user-rights',
				'extra' => [
					'user' => $user->getId(),
					'add' => $add,
					'remove' => $remove,
					'reason' => 'This is the [[reason]] for changing your user rights.',
				],
				'agent' => $agent,
				'timestamp' => $this->getTimestamp(),
			]
		);
	}

	private function generateContentTranslation( User $user ) {
		if ( !ExtensionRegistry::getInstance()->isLoaded( 'ContentTranslation' ) ) {
			return;
		}

		$this->output( "Generating CX notifications\n" );
		foreach ( [ 'cx-first-translation', 'cx-tenth-translation', 'cx-hundredth-translation' ] as $eventType ) {
			EchoEvent::create(
				[
					'type' => $eventType,
					'extra' => [
						'recipient' => $user->getId(),
					],
					'timestamp' => $this->getTimestamp(),
				]
			);
		}

		EchoEvent::create(
			[
				'type' => 'cx-suggestions-available',
				'extra' => [
					'recipient' => $user->getId(),
					'lastTranslationTitle' => 'History of the People\'s Republic of China'
				],
				'timestamp' => $this->getTimestamp(),
			]
		);
	}

	private function generateOnePageLink( User $user, User $agent ) {
		$pageBeingLinked = $this->generateNewPageTitle();
		$this->addToPageContent( $pageBeingLinked, $user, "this is a new page" );

		$pageLinking = $this->generateNewPageTitle();
		$content = "checkout [[{$pageBeingLinked->getPrefixedText()}]]!";
		$this->output( "{$agent->getName()} is linking to {$pageBeingLinked->getPrefixedText()} from {$pageLinking->getPrefixedText()}\n" );
		$this->addToPageContent( $pageLinking, $agent, $content );
	}

	private function generateMultiplePageLinks( User $user, User $agent ) {
		$pageBeingLinked = $this->generateNewPageTitle();
		$this->addToPageContent( $pageBeingLinked, $user, "this is a new page" );

		$content = "checkout [[{$pageBeingLinked->getPrefixedText()}]]!";
		$this->output( "{$agent->getName()} is linking to {$pageBeingLinked->getPrefixedText()} from multiple pages\n" );
		$this->addToPageContent( $this->generateNewPageTitle(), $agent, $content );
		$this->addToPageContent( $this->generateNewPageTitle(), $agent, $content );
		$this->addToPageContent( $this->generateNewPageTitle(), $agent, $content );
	}

	private function generateOpenStackManager( User $user, User $agent ) {
		if ( !ExtensionRegistry::getInstance()->isLoaded( 'OpenStackManager' ) ) {
			return;
		}

		$this->output( "Generating OpenStackManager notifications\n" );

		foreach ( [ 'build-completed', 'reboot-completed', 'deleted' ] as $action ) {
			EchoEvent::create( [
				'type' => "osm-instance-$action",
				'title' => Title::newFromText( "Moai" ),
				'agent' => $user,
				'extra' => [
					'instanceName' => 'instance1',
					'projectName' => 'TheProject',
					'notifyAgent' => true,
				],
				'timestamp' => $this->getTimestamp(),
			] );
		}

		EchoEvent::create( [
			'type' => 'osm-projectmembers-add',
			'title' => Title::newFromText( "Moai" ),
			'agent' => $agent,
			'extra' => [ 'userAdded' => $user->getId() ],
			'timestamp' => $this->getTimestamp(),
		] );
	}

	private function shouldGenerate( $type, array $types ) {
		return array_search( $type, $types ) !== false;
	}

	private function generateEditThanks( User $user, User $agent, User $otherUser ) {
		$this->generateOneEditThanks( $user, $agent );
		$this->generateMultipleEditThanks( $user, $agent, $otherUser );
	}

	private function generateOneEditThanks( User $user, User $agent ) {
		if ( !ExtensionRegistry::getInstance()->isLoaded( 'Thanks' ) ) {
			return;
		}
		// make an edit, thank it once
		$title = $this->generateNewPageTitle();
		$revisionRecord = $this->addToPageContent( $title, $user, "an awesome edit! ~~~~" );
		EchoEvent::create( [
			'type' => 'edit-thank',
			'title' => $title,
			'extra' => [
				'revid' => $revisionRecord->getId(),
				'thanked-user-id' => $user->getId(),
				'source' => 'generateSampleNotifications.php',
			],
			'agent' => $agent,
			'timestamp' => $this->getTimestamp(),
		] );
		$output = $this->addTimestampToOutput( "{$agent->getName()} is thanking {$user->getName()} for edit {$revisionRecord->getId()} on {$title->getPrefixedText()}" );
		$this->output( "$output\n" );
	}

	private function generateMultipleEditThanks( User $user, User $agent, User $otherUser ) {
		if ( !ExtensionRegistry::getInstance()->isLoaded( 'Thanks' ) ) {
			return;
		}
		// make an edit, thank it twice
		$title = $this->generateNewPageTitle();
		$revisionRecord = $this->addToPageContent( $title, $user, "an even better edit! ~~~~" );
		EchoEvent::create( [
			'type' => 'edit-thank',
			'title' => $title,
			'extra' => [
				'revid' => $revisionRecord->getId(),
				'thanked-user-id' => $user->getId(),
				'source' => 'generateSampleNotifications.php',
			],
			'agent' => $agent,
			'timestamp' => $this->getTimestamp(),
		] );
		EchoEvent::create( [
			'type' => 'edit-thank',
			'title' => $title,
			'extra' => [
				'revid' => $revisionRecord->getId(),
				'thanked-user-id' => $user->getId(),
				'source' => 'generateSampleNotifications.php',
			],
			'agent' => $otherUser,
			'timestamp' => $this->getTimestamp(),
		] );
		$output = $this->addTimestampToOutput( "{$agent->getName()} and {$otherUser->getName()} are thanking {$user->getName()} for edit {$revisionRecord->getId()} on {$title->getPrefixedText()}" );
		$this->output( "$output\n" );
	}

	private function generateEducationProgram( User $user, User $agent ) {
		if ( !ExtensionRegistry::getInstance()->isLoaded( 'EducationProgram' ) ) {
			$this->output( "Skipping EducationProgram. Extension not installed.\n" );
			return;
		}

		$chem101 = Title::newFromText( 'School/Chemistry101' );
		if ( !$chem101->exists() ) {
			$this->addToPageContent( $chem101, $agent, "\nThis is the main page for the Chemistry 101 course\n" );
		}

		$notificationManager = EducationProgram\Extension::globalInstance()->getNotificationsManager();

		$output = $this->addTimestampToOutput( "{$agent->getName()} is adding {$user->getName()} to {$chem101->getPrefixedText()} as instructor, student, campus volunteer and online volunteer" );
		$this->output( "$output\n" );

		$types = [
			'ep-instructor-add-notification',
			'ep-online-add-notification',
			'ep-campus-add-notification',
			'ep-student-add-notification',
		];
		foreach ( $types as $type ) {
			$notificationManager->trigger(
				$type,
				[
					'role-add-title' => $chem101,
					'agent' => $agent,
					'users' => [ $user->getId() ],
				]
			);
		}

		// NOTE: Not generating 'ep-course-talk-notification' for now
		// as it requires a full setup to actually work (institution, course, instructors, students).
	}

	private function generateWikibase( User $user, User $agent ) {
		if ( !class_exists( EchoNotificationsHandlers::class ) ) {
			// should use !ExtensionRegistry::getInstance()->isLoaded( 'Wikibase' ) when possible
			$this->output( "Skipping Wikibase. Extension not installed.\n" );
			return;
		}

		$title = $this->generateNewPageTitle();
		$this->addToPageContent( $title, $user, "this is a new page" );
		$helpPage = Title::newFromText( 'Project:Wikidata' );
		$this->addToPageContent( $helpPage, $user, "this is the help page" );

		$output = $this->addTimestampToOutput( "{$agent->getName()} is connecting {$user->getName()}'s page {$title->getPrefixedText()} to an item" );
		$this->output( "$output\n" );
		EchoEvent::create( [
			'type' => EchoNotificationsHandlers::NOTIFICATION_TYPE,
			'title' => $title,
			'extra' => [
				'url' => Title::newFromText( 'Item:Q1' )->getFullURL(),
				'repoSiteName' => 'Wikidata',
				'entity' => 'Q1',
			],
			'agent' => $agent,
			'timestamp' => $this->getTimestamp(),
		] );
	}
}

$maintClass = GenerateSampleNotifications::class;
require_once RUN_MAINTENANCE_IF_MAIN;