/
WikimediaEventsHooks.php
707 lines (627 loc) · 21.7 KB
/
WikimediaEventsHooks.php
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
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
<?php
use MediaWiki\MediaWikiServices;
use WikimediaEvents\PageViews;
/**
* Hooks used for Wikimedia-related logging
*
* @author Ori Livneh <ori@wikimedia.org>
* @author Matthew Flaschen <mflaschen@wikimedia.org>
* @author Benny Situ <bsitu@wikimedia.org>
*/
class WikimediaEventsHooks {
/**
* @param OutputPage $out
* @param Skin $skin
*/
public static function onBeforePageDisplay( OutputPage $out, Skin $skin ) {
global $wgWMEUnderstandingFirstDay;
if ( $wgWMEUnderstandingFirstDay ) {
PageViews::deferredLog();
}
$out->addModules( 'ext.wikimediaEvents' );
if ( $out->getUser()->isLoggedIn() ) {
$out->addModules( 'ext.wikimediaEvents.loggedin' );
}
if ( defined( 'WB_VERSION' ) ) {
// If we are in Wikibase Repo, load Wikibase module
$out->addModules( 'ext.wikimediaEvents.wikibase' );
}
}
/**
* UserLogout hook handler.
* @see https://www.mediawiki.org/wiki/Manual:Hooks/UserLogout
*
* @param User $user
* @return bool
*/
public static function onUserLogout( User $user ) {
global $wgWMEUnderstandingFirstDay;
if ( $wgWMEUnderstandingFirstDay ) {
PageViews::deferredLog( $user->getId() );
}
return true;
}
/**
* BeforePageRedirect hook handler.
* @see https://www.mediawiki.org/wiki/Manual:Hooks/BeforePageRedirect
*
* @param OutputPage $out
* @param string &$redirect URL string, modifiable
* @param string &$code HTTP code, modifiable
* @return bool
*/
public static function onBeforePageRedirect( $out, &$redirect, &$code ) {
global $wgWMEUnderstandingFirstDay;
if ( $wgWMEUnderstandingFirstDay ) {
PageViews::deferredLog();
}
return true;
}
/**
* LocalUserCreated hook handler.
*
* @param User $user
* @param bool $autocreated
*/
public static function onLocalUserCreated( User $user, $autocreated ) {
global $wgWMEUnderstandingFirstDay;
if ( $wgWMEUnderstandingFirstDay && !$autocreated ) {
$context = new DerivativeContext( RequestContext::getMain() );
$context->setUser( $user );
$pageViews = new PageViews( $context );
// We don't need to check the cohort, since we know the user is not autocreated
// and the account was just created.
$pageViews->setUserHashingSalt();
}
}
/**
* On XAnalyticsHeader
*
* When adding new headers here please update the docs:
* https://wikitech.wikimedia.org/wiki/X-Analytics
*
* Insert a 'page_id' key with the page ID as value (if the request is for a page with a pageid)
* Insert a 'ns' key with the namespace ID as value (if the request is for a valid title)
* Insert a 'special' key with the resolved name of the special page (if the request is for a
* special page)
*
* Add a 'loggedIn' key with the value of 1 if the user is logged in
* @param OutputPage $out
* @param array &$headerItems
*/
public static function onXAnalyticsHeader( OutputPage $out, array &$headerItems ) {
$title = $out->getTitle();
if ( $title !== null ) {
$pageId = $title->getArticleID();
$headerItems['ns'] = $title->getNamespace();
if ( is_int( $pageId ) && $pageId > 0 ) {
$headerItems['page_id'] = $pageId;
}
if ( $title->isSpecialPage() ) {
list( $name, /* $subpage */ ) = MediaWikiServices::getInstance()->getSpecialPageFactory()
->resolveAlias( $title->getDBkey() );
if ( $name !== null ) {
$headerItems['special'] = $name;
}
}
}
if ( $out->getUser()->isLoggedIn() ) {
$headerItems['loggedIn'] = 1;
}
}
/**
* Log server-side event on successful page edit.
*
* Imported from EventLogging extension
*
* @param WikiPage $wikiPage
* @param User $user
* @param Content $content
* @param string $summary
* @param bool $isMinor
* @param bool $isWatch
* @param string $section
* @param int $flags
* @param Revision $revision
* @param Status $status
* @param int $baseRevId
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/PageContentSaveComplete
*/
public static function onPageContentSaveComplete(
WikiPage $wikiPage, $user, $content, $summary,
$isMinor, $isWatch, $section, $flags, $revision, $status, $baseRevId
) {
if ( !$revision ) {
return;
}
$title = $wikiPage->getTitle();
$stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
if ( PHP_SAPI !== 'cli' ) {
if ( $user->isBot() ) {
$accType = 'bot'; // registered bot
} elseif ( RequestContext::getMain()->getRequest()->getCheck( 'maxlag' ) ) {
$accType = 'throttled'; // probably an unregistered bot
} else {
$accType = 'normal';
}
if ( in_array( $content->getModel(), [ 'wikibase-item', 'wikibase-property' ] ) ) {
$nsType = 'entity';
} elseif ( MWNamespace::isContent( $title->getNamespace() ) ) {
$nsType = 'content';
} elseif ( MWNamespace::isTalk( $title->getNamespace() ) ) {
$nsType = 'talk';
} else {
$nsType = 'meta';
}
$size = $content->getSize();
if ( defined( 'MW_API' ) ) {
$entry = 'api';
} elseif ( defined( 'MEDIAWIKI_JOB_RUNNER' ) ) {
$entry = 'job';
} elseif ( PHP_SAPI === 'cli' ) {
$entry = 'cli';
} else {
$entry = 'index';
}
// Null edits are both slow (due to user name mismatch reparses) and are
// not the focus of this benchmark, which is about actual edits to pages
$edit = $status->hasMessage( 'edit-no-change' ) ? 'nullEdit' : 'edit';
DeferredUpdates::addCallableUpdate(
function () use ( $stats, $size, $nsType, $accType, $entry, $edit ) {
$timing = RequestContext::getMain()->getTiming();
$measure = $timing->measure(
'editResponseTime', 'requestStart', 'requestShutdown' );
if ( $measure === false ) {
return;
}
$timeMs = $measure['duration'] * 1000;
$stats->timing( "timing.{$edit}ResponseTime", $timeMs );
$stats->timing( "timing.{$edit}ResponseTime.page.$nsType", $timeMs );
$stats->timing( "timing.{$edit}ResponseTime.user.$accType", $timeMs );
$stats->timing( "timing.{$edit}ResponseTime.entry.$entry", $timeMs );
if ( $edit === 'edit' ) {
$msPerKb = $timeMs / ( max( $size, 1 ) / 1e3 ); // T224686
$stats->timing( "timing.editResponseTimePerKB.page.$nsType", $msPerKb );
$stats->timing( "timing.editResponseTimePerKB.user.$accType", $msPerKb );
$stats->timing( "timing.editResponseTimePerKB.entry.$entry", $msPerKb );
}
}
);
}
}
/**
* Log and update statistics whenever an editor reaches the active editor
* threshold for this month.
*
* @see https://meta.wikimedia.org/wiki/Schema:EditorActivation
* @see https://www.mediawiki.org/wiki/Analytics/Metric_definitions#Active_editor
*
* @param Revision $revision
* @param string $data
* @param array $flags
*/
public static function onRevisionInsertComplete( $revision, $data, $flags ) {
$user = User::newFromId( $revision->getUser( Revision::RAW ) );
// Anonymous users and bots don't count (sorry!)
if ( $user->isAnon() || $user->isAllowed( 'bot' ) ) {
return;
}
// Only mainspace edits qualify
if ( !$revision->getTitle()->inNamespace( NS_MAIN ) ) {
return;
}
// Check if this is the user's fifth mainspace edit this month.
// If it is, then this editor has just made the cut as an active
// editor for this wiki for this month.
DeferredUpdates::addCallableUpdate( function () use ( $user ) {
$db = wfGetDB( DB_MASTER );
$revWhere = ActorMigration::newMigration()->getWhere( $db, 'rev_user', $user );
$since = $db->addQuotes( $db->timestamp( date( 'Ym' ) . '00000000' ) );
$numMainspaceEditsThisMonth = 0;
foreach ( $revWhere['orconds'] as $key => $cond ) {
$tsField = $key === 'actor' ? 'revactor_timestamp' : 'rev_timestamp';
$numMainspaceEditsThisMonth += $db->selectRowCount(
[ 'revision', 'page' ] + $revWhere['tables'],
'1',
[
$cond,
$tsField . ' >= ' . $since,
'page_namespace' => NS_MAIN,
],
__FILE__ . ':' . __LINE__,
[ 'LIMIT' => 6 - $numMainspaceEditsThisMonth ],
[ 'page' => [ 'INNER JOIN', 'rev_page = page_id' ] ] + $revWhere['joins']
);
if ( $numMainspaceEditsThisMonth >= 6 ) {
break;
}
}
if ( $numMainspaceEditsThisMonth === 5 ) {
$month = date( 'm-Y' );
MediaWikiServices::getInstance()
->getStatsdDataFactory()->increment( 'editor.activation.' . $month );
EventLogging::logEvent( 'EditorActivation', 14208837, [
'userId' => $user->getId(),
'month' => $month,
] );
}
} );
}
/**
* Helper method to verify that hook is triggered on special page
* @param OutputPage $out Output page
* @return bool Returns true, if request is sent to one of $allowedPages special page
*/
private static function isKnownSettingsPage( OutputPage $out ) {
$allowedPages = [ 'Preferences', 'MobileOptions' ];
$title = $out->getTitle();
if ( $title === null ) {
return false;
}
foreach ( $allowedPages as $page ) {
if ( $title->isSpecial( $page ) ) {
return true;
}
}
return false;
}
/**
* Handler for UserSaveOptions hook.
* @see https://www.mediawiki.org/wiki/Manual:Hooks/UserSaveOptions
* @param User $user user whose options are being saved
* @param array &$options Options being saved
* @return bool true in all cases
*/
public static function onUserSaveOptions( $user, &$options ) {
// Modified version of original method from the Echo extension
$out = RequestContext::getMain()->getOutput();
// Capture user options saved via Special:Preferences, Special:MobileOptions or ApiOptions
// TODO (mattflaschen, 2013-06-13): Ideally this would be done more cleanly without
// looking explicitly at page names and URL parameters.
// Maybe a userInitiated flag passed to saveSettings would work.
if ( self::isKnownSettingsPage( $out )
|| ( defined( 'MW_API' ) && $out->getRequest()->getVal( 'action' ) === 'options' )
) {
// $clone is the current user object before the new option values are set
$clone = User::newFromId( $user->getId() );
$commonData = [
'version' => '1',
'userId' => $user->getId(),
'saveTimestamp' => wfTimestampNow(),
];
foreach ( $options as $optName => $optValue ) {
// loose comparision is required since some of the values
// are not consistent in the two variables, eg, '' vs false
if ( $clone->getOption( $optName ) != $optValue ) {
$event = [
'property' => $optName,
// Encode value as JSON.
// This is parseable and allows a consistent type for validation.
'value' => FormatJson::encode( $optValue ),
'isDefault' => User::getDefaultOption( $optName ) == $optValue,
] + $commonData;
EventLogging::logEvent( 'PrefUpdate', 5563398, $event );
}
}
}
return true;
}
/**
* Logs edit conflicts with the EditConflict schema.
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/EditPageBeforeConflictDiff
* @see https://meta.wikimedia.org/wiki/Schema:EditConflict
* @param EditPage $editPage
* @param OutputPage &$out
* @return bool true in all cases
*/
public static function onEditPageBeforeConflictDiff( EditPage $editPage, &$out ) {
$user = $out->getUser();
$title = $out->getTitle();
EventLogging::logEvent( 'EditConflict', 8860941, [
'userId' => $user->getId(),
'userText' => $user->getName(),
'pageId' => $title->getArticleID(),
'namespace' => $title->getNamespace(),
'title' => $title->getDBkey(),
'revId' => (int)$title->getLatestRevID(),
] );
return true;
}
/**
* Set static (not request-specific) JS configuration variables
*
* @see https://www.mediawiki.org/wiki/Manual:Hooks/ResourceLoaderGetConfigVars
* @param array &$vars Array of variables to be added into the output of the startup module
* @param string $skinName Current skin name to restrict config variables to a certain skin
*/
public static function onResourceLoaderGetConfigVars( &$vars, $skinName ) {
global $wgWMEStatsdBaseUri, $wgWMEReadingDepthSamplingRate,
$wgWMEReadingDepthEnabled, $wgWMEPrintSamplingRate,
$wgWMEPrintEnabled, $wgWMECitationUsagePopulationSize,
$wgWMECitationUsagePageLoadPopulationSize,
$wgWMESchemaEditAttemptStepSamplingRate, $wgWMEMobileWebUIActionsTracking,
$wgWMEWikidataCompletionSearchClicks;
$vars['wgWMEStatsdBaseUri'] = $wgWMEStatsdBaseUri;
$vars['wgWMEReadingDepthSamplingRate'] = $wgWMEReadingDepthSamplingRate;
$vars['wgWMEReadingDepthEnabled'] = $wgWMEReadingDepthEnabled;
$vars['wgWMEPrintSamplingRate'] = $wgWMEPrintSamplingRate;
$vars['wgWMEPrintEnabled'] = $wgWMEPrintEnabled;
$vars['wgWMECitationUsagePopulationSize'] = $wgWMECitationUsagePopulationSize;
$vars['wgWMECitationUsagePageLoadPopulationSize'] = $wgWMECitationUsagePageLoadPopulationSize;
$vars['wgWMESchemaEditAttemptStepSamplingRate'] = $wgWMESchemaEditAttemptStepSamplingRate;
$vars['wgWMEWikidataCompletionSearchClicks'] = $wgWMEWikidataCompletionSearchClicks;
if ( $skinName === 'minerva' ) {
$vars['wgWMEMobileWebUIActionsTracking'] = $wgWMEMobileWebUIActionsTracking;
}
}
/**
* Register change tags.
*
* @param array &$tags
* @return bool
*/
public static function onListDefinedTags( &$tags ) {
if ( wfWikiID() === 'commonswiki' ) {
$tags[] = 'cross-wiki-upload';
// For A/B test
$tags[] = 'cross-wiki-upload-1';
$tags[] = 'cross-wiki-upload-2';
$tags[] = 'cross-wiki-upload-3';
$tags[] = 'cross-wiki-upload-4';
}
return true;
}
/**
* Mark active change tags.
*
* @param array &$tags
* @return bool
*/
public static function onChangeTagsListActive( &$tags ) {
if ( wfWikiID() === 'commonswiki' ) {
$tags[] = 'cross-wiki-upload';
// For A/B test
$tags[] = 'cross-wiki-upload-1';
$tags[] = 'cross-wiki-upload-2';
$tags[] = 'cross-wiki-upload-3';
$tags[] = 'cross-wiki-upload-4';
}
return true;
}
public static function onSpecialSearchGoResult( $term, Title $title, &$url ) {
$request = RequestContext::getMain()->getRequest();
$wprov = $request->getVal( 'wprov' );
if ( $wprov ) {
$url = $title->getFullURL( [ 'wprov' => $wprov ] );
}
return true;
}
/**
* The javascript that records search metrics needs to know if it is on a
* SERP or not. This ends up being non-trivial due to localization, so
* make it trivial by injecting a boolean value to check.
* @param string $term
* @param SearchResultSet $titleMatches
* @param SearchResultSet $textMatches
* @return true
*/
public static function onSpecialSearchResults( $term, $titleMatches, $textMatches ) {
global $wgOut;
$wgOut->addJsConfigVars( [
'wgIsSearchResultPage' => true,
] );
return true;
}
/**
* Add a change tag 'cross-wiki-upload' to cross-wiki uploads to Commons, to track usage of the
* new feature. (Both to track adoption, and to let Commons editors review the uploads.) (T115328)
*
* @param RecentChange $recentChange
* @return bool
*/
public static function onRecentChangeSaveCrossWikiUpload( RecentChange $recentChange ) {
if ( !defined( 'MW_API' ) || wfWikiID() !== 'commonswiki' ) {
return true;
}
if (
$recentChange->getAttribute( 'rc_log_type' ) !== 'upload' ||
$recentChange->getAttribute( 'rc_log_action' ) !== 'upload'
) {
return true;
}
$request = RequestContext::getMain()->getRequest();
if ( !$request->response()->getHeader( 'Access-Control-Allow-Origin' ) ) {
return true;
}
// A/B test
$bucket = $request->getVal( 'bucket' );
if ( !in_array( $bucket, [ '1', '2', '3', '4' ] ) ) {
$bucket = null;
}
$tags = [ 'cross-wiki-upload' ];
if ( $bucket ) {
$tags[] = "cross-wiki-upload-$bucket";
}
$recentChange->addTags( $tags );
return true;
}
/**
* Add a change tag 'campaign-...' to edits made via edit campaigns (identified by an URL
* parameter passed to the API via VisualEditor). (T209132)
*
* @param RecentChange $recentChange
* @return bool
*/
public static function onRecentChangeSaveEditCampaign( RecentChange $recentChange ) {
global $wgWMEEditCampaigns;
if ( !defined( 'MW_API' ) ) {
return true;
}
$request = RequestContext::getMain()->getRequest();
$campaign = $request->getVal( 'campaign' );
if ( !in_array( $campaign, $wgWMEEditCampaigns ) ) {
return true;
}
$tags = [ "campaign-$campaign" ];
$recentChange->addTags( $tags );
return true;
}
public static function onResourceLoaderRegisterModules( ResourceLoader $resourceLoader ) {
if ( !ExtensionRegistry::getInstance()->isLoaded( 'VisualEditor' ) ) {
return;
}
$dir = dirname( __DIR__ ) . DIRECTORY_SEPARATOR;
$resourceLoader->register( "ext.wikimediaEvents.visualEditor", [
'localBasePath' => $dir . 'modules',
'remoteExtPath' => 'WikimediaEvents/modules',
"scripts" => "ve-wme/campaigns.js",
"dependencies" => "ext.visualEditor.targetLoader",
"targets" => [ "desktop", "mobile" ],
] );
}
public static function onArticleViewHeader() {
DeferredUpdates::addCallableUpdate( function () {
$context = RequestContext::getMain();
$timing = $context->getTiming();
if ( ExtensionRegistry::getInstance()->isLoaded( 'MobileFrontend' )
&& MobileContext::singleton()->shouldDisplayMobileView()
) {
$platform = 'mobile';
} else {
$platform = 'desktop';
}
$measure = $timing->measure( 'viewResponseTime', 'requestStart', 'requestShutdown' );
if ( $measure !== false ) {
MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
"timing.viewResponseTime.{$platform}", $measure['duration'] * 1000 );
}
} );
}
public static function onMakeGlobalVariablesScript( array &$vars, OutputPage $out ) {
global $wgWMESearchRelevancePages;
if ( $vars['wgAction'] === 'view' ) {
$articleId = $out->getTitle()->getArticleID();
if ( isset( $wgWMESearchRelevancePages[$articleId] ) ) {
$vars['wgWMESearchRelevancePages'] = $wgWMESearchRelevancePages[$articleId];
}
}
$vars['wgWMESchemaEditAttemptStepOversample'] =
static::shouldSchemaEditAttemptStepOversample( $out->getContext() );
return true;
}
public static function shouldSchemaEditAttemptStepOversample( IContextSource $context ) {
global $wgWMEUnderstandingFirstDay;
// Conditions under which Schema:EditAttemptStep should oversample (always log)
// Oversample when UnderstandingFirstDay is enabled and the user is in the UFD cohort
$pageViews = new PageViews( $context );
$userInCohort = $wgWMEUnderstandingFirstDay && $pageViews->userIsInCohort();
// The editingStatsOversample request parameter can trigger oversampling
$fromRequest = $context->getRequest()->getBool( 'editingStatsOversample' );
$shouldOversample = $userInCohort || $fromRequest;
Hooks::run(
'WikimediaEventsShouldSchemaEditAttemptStepOversample',
[ $context, &$shouldOversample ]
);
return $shouldOversample;
}
/**
* WMDE runs banner campaigns to encourage users to create an account and edit.
* The tracking already implemented in the Campaigns extension doesn't quite cover the WMDE
* usecase as they have a wikipage landing page before the user progresses to registration.
* This could one day be factored out into its own extension or part of Campaigns.
*
* The task for adding this functionality to the Campaigns extension can be found below:
* https://phabricator.wikimedia.org/T174939
*
* The series of banner campaigns can be seen on Phabricator:
* https://phabricator.wikimedia.org/project/subprojects/2821/
*
* @author addshore on behalf of WMDE
*
* @param Title $title
* @param mixed $unused
* @param OutputPage $output
* @param User $user
* @param WebRequest $request
* @param MediaWiki $mediaWiki
*/
public static function onBeforeInitializeWMDECampaign(
$title,
$unused,
$output,
$user,
$request,
$mediaWiki
) {
// Only run for dewiki
if ( wfWikiID() !== 'dewiki' ) {
return;
}
/**
* Setup the campaign prefix.
* Everything below this block is agnostic to which tour is being run.
*/
$campaignPrefix = 'WMDE_';
$cookieName = 'wmdecampaign-' . $campaignPrefix;
$hasCampaignGetValue = strstr( $request->getVal( 'campaign' ), $campaignPrefix ) !== false;
$hasCampaignCookie = $request->getCookie( $cookieName ) !== null;
// Get the campaign name from either the URL params or cookie
$campaign = 'NULL';
if ( $hasCampaignGetValue ) {
$campaign = $request->getVal( 'campaign' );
}
if ( $hasCampaignCookie ) {
$campaign = $request->getCookie( $cookieName );
}
// Bail if this request has nothing to do with our campaign
if ( $campaign === 'NULL' ) {
return;
}
$stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
/**
* If an anon user clicks on the banner and doesn't yet have a session cookie then
* add a session cookie and count the click.
*/
if ( $hasCampaignGetValue && !$hasCampaignCookie && $user->isAnon() ) {
$request->response()->setCookie( $cookieName, $campaign, null );
$stats->increment( "wmde.campaign.$campaign.banner.click" );
wfDebugLog( 'WMDE', "$campaign - 1 - Banner click by anon user without cookie" );
}
/**
* If an anon user with the cookie, views the create account page without a campaign
* value set then inject it into the WebRequest object.
*/
if (
$hasCampaignCookie &&
!$hasCampaignGetValue &&
$user->isAnon() &&
$title->isSpecial( 'CreateAccount' )
) {
$request->setVal( 'campaign', $campaign );
wfDebugLog( 'WMDE', "$campaign - 2 - Inject campaign value on CreateAccount" );
}
}
/**
* Log user's selection on SpecialMute form via EventLogging
*
* @param array $data
*/
public static function onSpecialMuteSubmit( $data ) {
$event = [];
if ( isset( $data['email-blacklist'] ) ) {
$event['emailsBefore'] = $data['email-blacklist']['before'];
$event['emailsAfter'] = $data['email-blacklist']['after'];
}
if ( isset( $data['echo-notifications-blacklist'] ) ) {
$event['notificationsBefore'] = $data['echo-notifications-blacklist']['before'];
$event['notificationsAfter'] = $data['echo-notifications-blacklist']['after'];
}
DeferredUpdates::addCallableUpdate(
function () use ( $event ) {
EventLogging::logEvent( 'SpecialMuteSubmit', 19265572, $event );
}
);
}
}