Debian Codegraph @

extensions/Echo/maintenance/generateSampleNotifications.php

raw symbols SCIP
1 <?php
2 // phpcs:disable Generic.Files.LineLength -- Long html test examples
3 // @phan-file-suppress PhanUndeclaredClassMethod, PhanUndeclaredClassConstant Other extensions used for testing purposes
4
5 use MediaWiki\Content\WikitextContent;
6 use MediaWiki\Extension\Notifications\Model\Event;
7 use MediaWiki\Maintenance\Maintenance;
8 use MediaWiki\Registration\ExtensionRegistry;
9 use MediaWiki\Revision\RevisionRecord;
10 use MediaWiki\Revision\SlotRecord;
11 use MediaWiki\Title\Title;
12 use MediaWiki\User\User;
13 use Wikimedia\Rdbms\IDBAccessObject;
14
15 $IP = getenv( 'MW_INSTALL_PATH' );
16 if ( $IP === false ) {
17 $IP = __DIR__ . '/../../..';
18 }
19 require_once "$IP/maintenance/Maintenance.php";
20
21 /**
22 * A maintenance script that generates sample notifications for testing purposes.
23 */
24 class GenerateSampleNotifications extends Maintenance {
25
26 /** @var string[] */
27 private $supportedNotificationTypes = [
28 'welcome',
29 'edit-user-talk',
30 'mention',
31 'page-linked',
32 'reverted',
33 'email',
34 'user-rights',
35 'cx',
36 'osm',
37 'edit-thanks',
38 'edu',
39 'page-connection',
40 ];
41
42 /** @var int */
43 private $timestampCounter = 5;
44
45 public function __construct() {
46 parent::__construct();
47 $this->addDescription( "Generate sample notifications" );
48
49 $this->addOption(
50 'force',
51 'Bypass confirmation',
52 false, false, 'f' );
53
54 $allTypes = implode( ',', $this->supportedNotificationTypes );
55 $this->addOption(
56 'types',
57 "Comma-separated list of notification types to generate ($allTypes)",
58 false, true, 't' );
59
60 $this->addOption(
61 'user',
62 'Name of the user receiving the notifications',
63 true, true, 'u' );
64
65 $this->addOption(
66 'agent',
67 'Name of the user creating the notifications',
68 true, true, 'a' );
69
70 $this->addOption(
71 'other',
72 'Name of another user involved with the notifications',
73 true, true, 'o' );
74
75 $this->requireExtension( 'Echo' );
76
77 $this->addOption(
78 'timestamp',
79 'Add notification timestamps (Epoch time format). All notifications that are not ' .
80 'related directly to edits will be created with a timestamp starting 5 minutes ' .
81 'before the given timestamp, and increasing by 1 minute per notification.',
82 false, false, 'k' );
83 }
84
85 public function execute() {
86 $user = $this->getOptionUser( 'user' );
87 $agent = $this->getOptionUser( 'agent' );
88 $otherUser = $this->getOptionUser( 'other' );
89 $title = Title::newFromText( 'This is a pretty long page title lets see if it is going to be truncated' );
90
91 $types = $this->getOption( 'types' );
92 if ( $types ) {
93 $types = explode( ',', $types );
94 } else {
95 $types = $this->supportedNotificationTypes;
96 }
97
98 $this->confirm();
99
100 $this->output( "Started processing...\n" );
101
102 if ( $this->shouldGenerate( 'welcome', $types ) ) {
103 $this->generateWelcome( $user );
104 }
105
106 if ( $this->shouldGenerate( 'edit-user-talk', $types ) ) {
107 $this->generateEditUserTalk( $user, $agent );
108 }
109
110 if ( $this->shouldGenerate( 'mention', $types ) ) {
111 $this->generateMention( $user, $agent, $otherUser, $title );
112 }
113
114 if ( $this->shouldGenerate( 'page-linked', $types ) ) {
115 $this->generatePageLink( $user, $agent );
116 }
117
118 if ( $this->shouldGenerate( 'reverted', $types ) ) {
119 $this->generateReverted( $user, $agent );
120 }
121
122 if ( $this->shouldGenerate( 'email', $types ) ) {
123 $this->generateEmail( $user, $agent );
124 }
125
126 if ( $this->shouldGenerate( 'user-rights', $types ) ) {
127 $this->generateUserRights( $user, $agent );
128 }
129
130 if ( $this->shouldGenerate( 'cx', $types ) ) {
131 $this->generateContentTranslation( $user );
132 }
133
134 if ( $this->shouldGenerate( 'osm', $types ) ) {
135 $this->generateOpenStackManager( $user, $agent );
136 }
137
138 if ( $this->shouldGenerate( 'edit-thanks', $types ) ) {
139 $this->generateEditThanks( $user, $agent, $otherUser );
140 }
141
142 if ( $this->shouldGenerate( 'edu', $types ) ) {
143 $this->generateEducationProgram( $user, $agent );
144 }
145
146 if ( $this->shouldGenerate( 'page-connection', $types ) ) {
147 $this->generateWikibase( $user, $agent );
148 }
149
150 $this->output( "Completed \n" );
151 }
152
153 /**
154 * Get the set timestamp of the event
155 *
156 * @param bool $getEpoch Get the epoch value
157 * @return int Timestamp for the operation
158 */
159 private function getTimestamp( $getEpoch = false ) {
160 $startTime = $this->getOption( 'timestamp' ) ?: time();
161
162 // Incrementally decrease X minutes from start time
163 $timestamp = strtotime( '-' . $this->timestampCounter++ . ' minute', $startTime );
164
165 return $getEpoch ? $timestamp : (int)wfTimestamp( TS_UNIX, $timestamp );
166 }
167
168 /**
169 * Add a timestamp string to the output, if a timestamp option was given,
170 * to note the time of the new generated event.
171 *
172 * @param string $output New output message with timestamp
173 * @return string
174 */
175 private function addTimestampToOutput( $output ) {
176 if ( $this->getOption( 'timestamp' ) ) {
177 $output .= ' (Using timestamp: ' . date( 'Y-m-d H:i:s', $this->getTimestamp( true ) ) . ')';
178 }
179 return $output;
180 }
181
182 private function generateEditUserTalk( User $user, User $agent ) {
183 $this->output( "{$agent->getName()} is writing on {$user->getName()}'s user talk page\n" );
184 $editId = $this->generateRandomString();
185 $section = "== section $editId ==\n\nthis is the text $editId\n\n~~~~\n\n";
186 $this->addToUserTalk( $user, $agent, $section );
187 }
188
189 private function getOptionUser( $optionName ) {
190 $username = $this->getOption( $optionName );
191 $user = User::newFromName( $username );
192 if ( !$user->isRegistered() ) {
193 $this->fatalError( "User $username does not seem to exist in this wiki" );
194 }
195 return $user;
196 }
197
198 private function generateRandomString( $length = 10 ) {
199 return substr( str_shuffle( "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ), 0, $length );
200 }
201
202 protected function confirm() {
203 if ( $this->getOption( 'force', false ) ) {
204 return;
205 }
206 $this->output( "=== WARNING ===\n" );
207 $this->output( "This script modifies the content of several pages,\n" );
208 $this->output( "including user's talk pages.\n" );
209 $this->output( "ONLY RUN ON TEST WIKIS\n" );
210 $this->output( "Enter 'yes' if you wish to continue or any other key to exit\n" );
211 $confirm = $this->readconsole();
212 if ( $confirm !== 'yes' ) {
213 $this->fatalError( 'Safe decision' );
214 }
215 }
216
217 private function addToUserTalk( User $user, User $agent, $contentText ) {
218 $this->addToPageContent( $user->getTalkPage(), $agent, $contentText );
219 }
220
221 private function addToPageContent( Title $title, User $agent, $contentText ) {
222 $page = $this->getServiceContainer()->getWikiPageFactory()->newFromTitle( $title );
223 $previousContent = "";
224 $page->loadPageData( IDBAccessObject::READ_LATEST );
225 $revision = $page->getRevisionRecord();
226 if ( $revision ) {
227 $content = $revision->getContent( SlotRecord::MAIN, RevisionRecord::FOR_PUBLIC );
228 if ( $content instanceof WikitextContent ) {
229 $previousContent = $content->getText();
230 }
231 }
232 $status = $page->doUserEditContent(
233 new WikitextContent( $contentText . $previousContent ),
234 $agent,
235 'generating sample notifications'
236 );
237
238 if ( !$status->isGood() ) {
239 $this->error( "Failed to edit {$title->getPrefixedText()}: {$status->getMessage()->text()}" );
240 }
241
242 return $status->getValue()['revision-record'];
243 }
244
245 private function generateMention( User $user, User $agent, User $otherUser, Title $title ) {
246 $mention = "== section {$this->generateRandomString()} ==\nHello [[User:{$user->getName()}]] \n~~~~\n";
247
248 // article talk
249 $this->output( "{$agent->getName()} is mentioning {$user->getName()} on {$title->getTalkPage()->getPrefixedText()}\n" );
250 $this->addToPageContent( $title->getTalkPage(), $agent, $mention );
251
252 // agent talk
253 $this->output( "{$agent->getName()} is mentioning {$user->getName()} on {$agent->getTalkPage()->getPrefixedText()}\n" );
254 $this->addToPageContent( $agent->getTalkPage(), $agent, $mention );
255
256 // user talk
257 $this->output( "{$agent->getName()} is mentioning {$user->getName()} on {$otherUser->getTalkPage()->getPrefixedText()}\n" );
258 $this->addToPageContent( $otherUser->getTalkPage(), $agent, $mention );
259
260 // any other page
261 $this->output( "{$agent->getName()} is mentioning {$user->getName()} on {$title->getPrefixedText()}\n" );
262 $this->addToPageContent( $title, $agent, $mention );
263 }
264
265 private function generatePageLink( User $user, User $agent ) {
266 $this->generateOnePageLink( $user, $agent );
267 $this->generateMultiplePageLinks( $user, $agent );
268 }
269
270 private function generateNewPageTitle() {
271 return Title::newFromText( $this->generateRandomString() );
272 }
273
274 private function generateReverted( User $user, User $agent ) {
275 $services = $this->getServiceContainer();
276 $services->getUserGroupManager()->addUserToGroup( $agent, 'sysop' );
277
278 // revert (undo)
279 $moai = Title::newFromText( 'Moai' );
280 $page = $services->getWikiPageFactory()->newFromTitle( $moai );
281 $this->output( "{$agent->getName()} is reverting {$user->getName()}'s edit on {$moai->getPrefixedText()}\n" );
282 $this->addToPageContent( $moai, $agent, "\ncreating a good revision here\n" );
283 $this->addToPageContent( $moai, $user, "\nadding a line here\n" );
284
285 $undoRev = $page->getRevisionRecord();
286 $previous = $services->getRevisionLookup()
287 ->getPreviousRevision( $undoRev );
288
289 $handler = $services->getContentHandlerFactory()
290 ->getContentHandler(
291 $undoRev->getSlot( SlotRecord::MAIN, RevisionRecord::RAW )
292 ->getModel()
293 );
294 $undoContent = $undoRev->getContent( SlotRecord::MAIN );
295 $previousContent = $previous->getContent( SlotRecord::MAIN );
296
297 if ( !$undoContent ) {
298 $this->error( "Failed to undo {$moai->getPrefixedText()}: undoContent is null." );
299 return;
300 }
301
302 if ( !$previousContent ) {
303 $this->error( "Failed to undo {$moai->getPrefixedText()}: previousContent is null." );
304 return;
305 }
306
307 $content = $handler->getUndoContent(
308 $undoContent,
309 $undoContent,
310 $previousContent,
311 // undoIsLatest
312 true
313 );
314
315 $status = $page->doUserEditContent(
316 $content,
317 $agent,
318 'undo',
319 // $flags
320 0,
321 // $originalRevId
322 false,
323 // $tags
324 [],
325 $undoRev->getId()
326 );
327
328 if ( !$status->isGood() ) {
329 $this->error( "Failed to undo {$moai->getPrefixedText()}: {$status->getMessage()->text()}" );
330 }
331 }
332
333 private function generateWelcome( User $user ) {
334 $this->output( "Welcoming {$user->getName()}\n" );
335 Event::create( [
336 'type' => 'welcome',
337 'agent' => $user,
338 'timestamp' => $this->getTimestamp(),
339 ] );
340 }
341
342 private function generateEmail( User $user, User $agent ) {
343 $output = $this->addTimestampToOutput( "{$agent->getName()} is emailing {$user->getName()}" );
344 $this->output( "$output\n" );
345 Event::create( [
346 'type' => 'emailuser',
347 'extra' => [
348 'to-user-id' => $user->getId(),
349 'subject' => 'Long time no see',
350 ],
351 'agent' => $agent,
352 'timestamp' => $this->getTimestamp(),
353 ] );
354 }
355
356 private function generateUserRights( User $user, User $agent ) {
357 $output = $this->addTimestampToOutput( "{$agent->getName()} is changing {$user->getName()}'s rights" );
358 $this->output( "$output\n" );
359 $this->createUserRightsNotification( $user, $agent, [ 'OnlyAdd-1' ], null );
360 $this->createUserRightsNotification( $user, $agent, null, [ 'JustRemove-1', 'JustRemove-2' ] );
361 $this->createUserRightsNotification( $user, $agent, [ 'Add-1', 'Add-2' ], [ 'Remove-1', 'Remove-2' ] );
362 }
363
364 private function createUserRightsNotification( User $user, User $agent, $add, $remove ) {
365 Event::create(
366 [
367 'type' => 'user-rights',
368 'extra' => [
369 'user' => $user->getId(),
370 'add' => $add,
371 'remove' => $remove,
372 'reason' => 'This is the [[reason]] for changing your user rights.',
373 ],
374 'agent' => $agent,
375 'timestamp' => $this->getTimestamp(),
376 ]
377 );
378 }
379
380 private function generateContentTranslation( User $user ) {
381 if ( !ExtensionRegistry::getInstance()->isLoaded( 'ContentTranslation' ) ) {
382 return;
383 }
384
385 $this->output( "Generating CX notifications\n" );
386 foreach ( [ 'cx-first-translation', 'cx-tenth-translation', 'cx-hundredth-translation' ] as $eventType ) {
387 Event::create(
388 [
389 'type' => $eventType,
390 'extra' => [
391 'recipient' => $user->getId(),
392 ],
393 'timestamp' => $this->getTimestamp(),
394 ]
395 );
396 }
397
398 Event::create(
399 [
400 'type' => 'cx-suggestions-available',
401 'extra' => [
402 'recipient' => $user->getId(),
403 'lastTranslationTitle' => 'History of the People\'s Republic of China'
404 ],
405 'timestamp' => $this->getTimestamp(),
406 ]
407 );
408 }
409
410 private function generateOnePageLink( User $user, User $agent ) {
411 $pageBeingLinked = $this->generateNewPageTitle();
412 $this->addToPageContent( $pageBeingLinked, $user, "this is a new page" );
413
414 $pageLinking = $this->generateNewPageTitle();
415 $content = "checkout [[{$pageBeingLinked->getPrefixedText()}]]!";
416 $this->output( "{$agent->getName()} is linking to {$pageBeingLinked->getPrefixedText()} from {$pageLinking->getPrefixedText()}\n" );
417 $this->addToPageContent( $pageLinking, $agent, $content );
418 }
419
420 private function generateMultiplePageLinks( User $user, User $agent ) {
421 $pageBeingLinked = $this->generateNewPageTitle();
422 $this->addToPageContent( $pageBeingLinked, $user, "this is a new page" );
423
424 $content = "checkout [[{$pageBeingLinked->getPrefixedText()}]]!";
425 $this->output( "{$agent->getName()} is linking to {$pageBeingLinked->getPrefixedText()} from multiple pages\n" );
426 $this->addToPageContent( $this->generateNewPageTitle(), $agent, $content );
427 // @phan-suppress-next-line PhanPluginDuplicateAdjacentStatement
428 $this->addToPageContent( $this->generateNewPageTitle(), $agent, $content );
429 // @phan-suppress-next-line PhanPluginDuplicateAdjacentStatement
430 $this->addToPageContent( $this->generateNewPageTitle(), $agent, $content );
431 }
432
433 private function generateOpenStackManager( User $user, User $agent ) {
434 if ( !ExtensionRegistry::getInstance()->isLoaded( 'OpenStackManager' ) ) {
435 return;
436 }
437
438 $this->output( "Generating OpenStackManager notifications\n" );
439
440 foreach ( [ 'build-completed', 'reboot-completed', 'deleted' ] as $action ) {
441 Event::create( [
442 'type' => "osm-instance-$action",
443 'title' => Title::newFromText( "Moai" ),
444 'agent' => $user,
445 'extra' => [
446 'instanceName' => 'instance1',
447 'projectName' => 'TheProject',
448 'notifyAgent' => true,
449 ],
450 'timestamp' => $this->getTimestamp(),
451 ] );
452 }
453
454 Event::create( [
455 'type' => 'osm-projectmembers-add',
456 'title' => Title::newFromText( "Moai" ),
457 'agent' => $agent,
458 'extra' => [ 'userAdded' => $user->getId() ],
459 'timestamp' => $this->getTimestamp(),
460 ] );
461 }
462
463 private function shouldGenerate( $type, array $types ) {
464 return in_array( $type, $types );
465 }
466
467 private function generateEditThanks( User $user, User $agent, User $otherUser ) {
468 $this->generateOneEditThanks( $user, $agent );
469 $this->generateMultipleEditThanks( $user, $agent, $otherUser );
470 }
471
472 private function generateOneEditThanks( User $user, User $agent ) {
473 if ( !ExtensionRegistry::getInstance()->isLoaded( 'Thanks' ) ) {
474 return;
475 }
476 // make an edit, thank it once
477 $title = $this->generateNewPageTitle();
478 $revisionRecord = $this->addToPageContent( $title, $user, "an awesome edit! ~~~~" );
479 Event::create( [
480 'type' => 'edit-thank',
481 'title' => $title,
482 'extra' => [
483 'revid' => $revisionRecord->getId(),
484 'thanked-user-id' => $user->getId(),
485 'source' => 'generateSampleNotifications.php',
486 ],
487 'agent' => $agent,
488 'timestamp' => $this->getTimestamp(),
489 ] );
490 $output = $this->addTimestampToOutput( "{$agent->getName()} is thanking {$user->getName()} for edit {$revisionRecord->getId()} on {$title->getPrefixedText()}" );
491 $this->output( "$output\n" );
492 }
493
494 private function generateMultipleEditThanks( User $user, User $agent, User $otherUser ) {
495 if ( !ExtensionRegistry::getInstance()->isLoaded( 'Thanks' ) ) {
496 return;
497 }
498 // make an edit, thank it twice
499 $title = $this->generateNewPageTitle();
500 $revisionRecord = $this->addToPageContent( $title, $user, "an even better edit! ~~~~" );
501 Event::create( [
502 'type' => 'edit-thank',
503 'title' => $title,
504 'extra' => [
505 'revid' => $revisionRecord->getId(),
506 'thanked-user-id' => $user->getId(),
507 'source' => 'generateSampleNotifications.php',
508 ],
509 'agent' => $agent,
510 'timestamp' => $this->getTimestamp(),
511 ] );
512 Event::create( [
513 'type' => 'edit-thank',
514 'title' => $title,
515 'extra' => [
516 'revid' => $revisionRecord->getId(),
517 'thanked-user-id' => $user->getId(),
518 'source' => 'generateSampleNotifications.php',
519 ],
520 'agent' => $otherUser,
521 'timestamp' => $this->getTimestamp(),
522 ] );
523 $output = $this->addTimestampToOutput( "{$agent->getName()} and {$otherUser->getName()} are thanking {$user->getName()} for edit {$revisionRecord->getId()} on {$title->getPrefixedText()}" );
524 $this->output( "$output\n" );
525 }
526
527 private function generateEducationProgram( User $user, User $agent ) {
528 if ( !ExtensionRegistry::getInstance()->isLoaded( 'EducationProgram' ) ) {
529 $this->output( "Skipping EducationProgram. Extension not installed.\n" );
530 return;
531 }
532
533 $chem101 = Title::newFromText( 'School/Chemistry101' );
534 if ( !$chem101->exists() ) {
535 $this->addToPageContent( $chem101, $agent, "\nThis is the main page for the Chemistry 101 course\n" );
536 }
537
538 $notificationManager = EducationProgram\Extension::globalInstance()->getNotificationsManager();
539
540 $output = $this->addTimestampToOutput( "{$agent->getName()} is adding {$user->getName()} to {$chem101->getPrefixedText()} as instructor, student, campus volunteer and online volunteer" );
541 $this->output( "$output\n" );
542
543 $types = [
544 'ep-instructor-add-notification',
545 'ep-online-add-notification',
546 'ep-campus-add-notification',
547 'ep-student-add-notification',
548 ];
549 foreach ( $types as $type ) {
550 $notificationManager->trigger(
551 $type,
552 [
553 'role-add-title' => $chem101,
554 'agent' => $agent,
555 'users' => [ $user->getId() ],
556 ]
557 );
558 }
559
560 // NOTE: Not generating 'ep-course-talk-notification' for now
561 // as it requires a full setup to actually work (institution, course, instructors, students).
562 }
563
564 private function generateWikibase( User $user, User $agent ) {
565 if ( !ExtensionRegistry::getInstance()->isLoaded( 'WikibaseClient' ) ) {
566 $this->output( "Skipping Wikibase. Extension not installed.\n" );
567 return;
568 }
569
570 $title = $this->generateNewPageTitle();
571 $this->addToPageContent( $title, $user, "this is a new page" );
572 $helpPage = Title::newFromText( 'Project:Wikidata' );
573 $this->addToPageContent( $helpPage, $user, "this is the help page" );
574
575 $output = $this->addTimestampToOutput( "{$agent->getName()} is connecting {$user->getName()}'s page {$title->getPrefixedText()} to an item" );
576 $this->output( "$output\n" );
577 Event::create( [
578 'type' => EchoNotificationsHandlers::NOTIFICATION_TYPE,
579 'title' => $title,
580 'extra' => [
581 'url' => Title::newFromText( 'Item:Q1' )->getFullURL(),
582 'repoSiteName' => 'Wikidata',
583 'entity' => 'Q1',
584 ],
585 'agent' => $agent,
586 'timestamp' => $this->getTimestamp(),
587 ] );
588 }
589 }
590
591 $maintClass = GenerateSampleNotifications::class;
592 require_once RUN_MAINTENANCE_IF_MAIN;