Debian Codegraph @

extensions/WikiEditor/includes/Hooks.php

raw symbols SCIP
1 <?php
2 /**
3 * Hooks for WikiEditor extension
4 *
5 * @file
6 * @ingroup Extensions
7 */
8
9 namespace MediaWiki\Extension\WikiEditor;
10
11 use Article;
12 use MediaWiki\Api\ApiMessage;
13 use MediaWiki\Cache\CacheKeyHelper;
14 use MediaWiki\ChangeTags\Hook\ChangeTagsListActiveHook;
15 use MediaWiki\ChangeTags\Hook\ListDefinedTagsHook;
16 use MediaWiki\Config\Config;
17 use MediaWiki\Content\Content;
18 use MediaWiki\Context\RequestContext;
19 use MediaWiki\EditPage\EditPage;
20 use MediaWiki\Extension\ConfirmEdit\Hooks as ConfirmEditHooks;
21 use MediaWiki\Extension\EventLogging\EventLogging;
22 use MediaWiki\Hook\EditPage__attemptSave_afterHook;
23 use MediaWiki\Hook\EditPage__attemptSaveHook;
24 use MediaWiki\Hook\EditPage__showEditForm_fieldsHook;
25 use MediaWiki\Hook\EditPage__showEditForm_initialHook;
26 use MediaWiki\Hook\EditPageGetPreviewContentHook;
27 use MediaWiki\Hook\RecentChange_saveHook;
28 use MediaWiki\Html\Html;
29 use MediaWiki\MediaWikiServices;
30 use MediaWiki\Output\OutputPage;
31 use MediaWiki\Preferences\Hook\GetPreferencesHook;
32 use MediaWiki\Registration\ExtensionRegistry;
33 use MediaWiki\Request\WebRequest;
34 use MediaWiki\ResourceLoader as RL;
35 use MediaWiki\Status\Status;
36 use MediaWiki\User\Options\UserOptionsLookup;
37 use MediaWiki\User\User;
38 use MediaWiki\User\UserEditTracker;
39 use MediaWiki\WikiMap\WikiMap;
40 use MessageLocalizer;
41 use MobileContext;
42 use MWCryptRand;
43 use RecentChange;
44 use WikimediaEvents\WikimediaEventsHooks;
45
46 /**
47 * @phpcs:disable MediaWiki.NamingConventions.LowerCamelFunctionsName.FunctionName
48 */
49 class Hooks implements
50 EditPage__showEditForm_initialHook,
51 EditPage__showEditForm_fieldsHook,
52 GetPreferencesHook,
53 EditPage__attemptSaveHook,
54 EditPage__attemptSave_afterHook,
55 EditPageGetPreviewContentHook,
56 ListDefinedTagsHook,
57 ChangeTagsListActiveHook,
58 RecentChange_saveHook
59 {
60
61 /** @var string|bool ID used for grouping entries all of a session's entries together in EventLogging. */
62 private static $statsId = false;
63
64 /** @var string[] */
65 private static $tags = [ 'wikieditor' ];
66
67 private Config $config;
68 private UserEditTracker $userEditTracker;
69 private UserOptionsLookup $userOptionsLookup;
70 private ?MobileContext $mobileContext;
71
72 public function __construct(
73 Config $config,
74 UserEditTracker $userEditTracker,
75 UserOptionsLookup $userOptionsLookup,
76 ?MobileContext $mobileContext
77 ) {
78 $this->config = $config;
79 $this->userEditTracker = $userEditTracker;
80 $this->userOptionsLookup = $userOptionsLookup;
81 $this->mobileContext = $mobileContext;
82 }
83
84 /**
85 * Should the current session be sampled for EventLogging?
86 *
87 * @param string $sessionId
88 * @return bool Whether to sample the session
89 */
90 protected function inEventSample( string $sessionId ): bool {
91 // Sample 6.25%
92 $samplingRate = $this->config->has( 'WMESchemaEditAttemptStepSamplingRate' ) ?
93 $this->config->get( 'WMESchemaEditAttemptStepSamplingRate' ) : 0.0625;
94
95 // (T314896) Convert whatever we've been given to a string of hex, as that's what EL needs
96 $hexValue = hash( 'md5', $sessionId, false );
97
98 $inSample = EventLogging::sessionInSample(
99 (int)( 1 / $samplingRate ), $hexValue
100 );
101 return $inSample;
102 }
103
104 /**
105 * Log stuff to the eventlogging_EditAttemptStep stream in a shape that conforms to the
106 * analytics/legacy/editattemptstep schema.
107 *
108 * If the EventLogging extension is not loaded, then this is a NOP.
109 *
110 * @see https://meta.wikimedia.org/wiki/Schema:EditAttemptStep
111 *
112 * @param string $action
113 * @param Article $article Which article (with full context, page, title, etc.)
114 * @param array $data Data to log for this action
115 * @return void
116 */
117 public function doEventLogging(
118 string $action,
119 Article $article,
120 array $data = []
121 ): void {
122 if ( defined( 'MW_PHPUNIT_TEST' ) ) {
123 return;
124 }
125
126 $extensionRegistry = ExtensionRegistry::getInstance();
127 if ( !$extensionRegistry->isLoaded( 'EventLogging' ) || !$extensionRegistry->isLoaded( 'WikimediaEvents' ) ) {
128 return;
129 }
130 if ( $extensionRegistry->isLoaded( 'MobileFrontend' ) && $this->mobileContext ) {
131 if ( $this->mobileContext->shouldDisplayMobileView() ) {
132 // on a MobileFrontend page the logging should be handled by it
133 return;
134 }
135 }
136 $inSample = $this->inEventSample( $data['editing_session_id'] );
137 $shouldOversample = WikimediaEventsHooks::shouldSchemaEditAttemptStepOversample( $article->getContext() );
138
139 $user = $article->getContext()->getUser();
140 $page = $article->getPage();
141 $title = $article->getTitle();
142 $revisionRecord = $page->getRevisionRecord();
143 $skin = $article->getContext()->getSkin();
144
145 $data = [
146 'action' => $action,
147 'version' => 1,
148 'is_oversample' => !$inSample,
149 'editor_interface' => 'wikitext',
150 // @todo FIXME for other than 'desktop'. T249944
151 'platform' => 'desktop',
152 'integration' => 'page',
153 'page_id' => $page->getId(),
154 'page_title' => $title->getPrefixedText(),
155 'page_ns' => $title->getNamespace(),
156 'revision_id' => $revisionRecord ? $revisionRecord->getId() : 0,
157 'user_id' => $user->getId(),
158 'user_is_temp' => $user->isTemp(),
159 'user_editcount' => $this->userEditTracker->getUserEditCount( $user ) ?: 0,
160 'mw_version' => MW_VERSION,
161 'skin' => $skin ? $skin->getSkinName() : null,
162 'is_bot' => $user->isRegistered() && $user->isBot(),
163 'is_anon' => $user->isAnon(),
164 'wiki' => WikiMap::getCurrentWikiId(),
165 ] + $data;
166
167 if ( $user->isAnon() ) {
168 $data['user_class'] = 'IP';
169 }
170
171 if ( !$inSample && !$shouldOversample ) {
172 return;
173 }
174
175 EventLogging::submit(
176 'eventlogging_EditAttemptStep',
177 [
178 '$schema' => '/analytics/legacy/editattemptstep/2.0.2',
179 'event' => $data,
180 ]
181 );
182 }
183
184 /**
185 * Log stuff to EventLogging's Schema:VisualEditorFeatureUse -
186 * see https://meta.wikimedia.org/wiki/Schema:VisualEditorFeatureUse
187 * If you don't have EventLogging and WikimediaEvents installed, does nothing.
188 *
189 * @param string $feature
190 * @param string $action
191 * @param Article $article Which article (with full context, page, title, etc.)
192 * @param string $sessionId Session identifier
193 * @return bool Whether the event was logged or not.
194 */
195 public function doVisualEditorFeatureUseLogging(
196 string $feature,
197 string $action,
198 Article $article,
199 string $sessionId
200 ): bool {
201 $extensionRegistry = ExtensionRegistry::getInstance();
202 if ( !$extensionRegistry->isLoaded( 'EventLogging' ) || !$extensionRegistry->isLoaded( 'WikimediaEvents' ) ) {
203 return false;
204 }
205 $inSample = $this->inEventSample( $sessionId );
206 $shouldOversample = WikimediaEventsHooks::shouldSchemaEditAttemptStepOversample( $article->getContext() );
207 if ( !$inSample && !$shouldOversample ) {
208 return false;
209 }
210
211 $user = $article->getContext()->getUser();
212 $editCount = $this->userEditTracker->getUserEditCount( $user );
213 $data = [
214 'feature' => $feature,
215 'action' => $action,
216 'editingSessionId' => $sessionId,
217 // @todo FIXME for other than 'desktop'. T249944
218 'platform' => 'desktop',
219 'integration' => 'page',
220 'editor_interface' => 'wikitext',
221 'user_id' => $user->getId(),
222 'user_is_temp' => $user->isTemp(),
223 'user_editcount' => $editCount ?: 0,
224 ];
225
226 // NOTE: The 'VisualEditorFeatureUse' event was migrated to the Event Platform and is no
227 // longer using the legacy EventLogging schema from metawiki. $revId is actually
228 // overridden by the EventLoggingSchemas extension attribute in
229 // WikimediaEvents/extension.json.
230 return EventLogging::logEvent( 'VisualEditorFeatureUse', -1, $data );
231 }
232
233 /**
234 * EditPage::showEditForm:initial hook
235 *
236 * Adds the modules to the edit form
237 *
238 * @param EditPage $editPage the current EditPage object.
239 * @param OutputPage $outputPage object.
240 */
241 public function onEditPage__showEditForm_initial( $editPage, $outputPage ) {
242 if ( $editPage->contentModel !== CONTENT_MODEL_WIKITEXT ) {
243 return;
244 }
245
246 $article = $editPage->getArticle();
247 $request = $article->getContext()->getRequest();
248
249 // Add modules if enabled
250 $user = $article->getContext()->getUser();
251 if ( $this->userOptionsLookup->getBoolOption( $user, 'usebetatoolbar' ) ) {
252 $outputPage->addModuleStyles( 'ext.wikiEditor.styles' );
253 $outputPage->addModules( 'ext.wikiEditor' );
254 if ( $this->config->get( 'WikiEditorRealtimePreview' ) ) {
255 $outputPage->addModules( 'ext.wikiEditor.realtimepreview' );
256 }
257 }
258
259 // Don't run this if the request was posted - we don't want to log 'init' when the
260 // user just pressed 'Show preview' or 'Show changes', or switched from VE keeping
261 // changes.
262 if ( ExtensionRegistry::getInstance()->isLoaded( 'EventLogging' ) && !$request->wasPosted() ) {
263 $data = [];
264 $data['editing_session_id'] = self::getEditingStatsId( $request );
265 $section = $request->getRawVal( 'section' );
266 if ( $section !== null ) {
267 $data['init_type'] = 'section';
268 } else {
269 $data['init_type'] = 'page';
270 }
271 if ( $request->getHeader( 'Referer' ) ) {
272 if (
273 $section === 'new'
274 || !$article->getPage()->exists()
275 ) {
276 $data['init_mechanism'] = 'new';
277 } else {
278 $data['init_mechanism'] = 'click';
279 }
280 } else {
281 if (
282 $section === 'new'
283 || !$article->getPage()->exists()
284 ) {
285 $data['init_mechanism'] = 'url-new';
286 } else {
287 $data['init_mechanism'] = 'url';
288 }
289 }
290 if ( $request->getRawVal( 'wvprov' ) === 'sticky-header' ) {
291 $data['init_mechanism'] .= '-sticky-header';
292 }
293
294 $this->doEventLogging( 'init', $article, $data );
295 }
296 }
297
298 /**
299 * EditPage::showEditForm:fields hook
300 *
301 * Adds the event fields to the edit form
302 *
303 * @param EditPage $editPage the current EditPage object.
304 * @param OutputPage $outputPage object.
305 */
306 public function onEditPage__showEditForm_fields( $editPage, $outputPage ) {
307 $outputPage->addHTML(
308 Html::hidden(
309 'wikieditorUsed',
310 '',
311 [ 'id' => 'wikieditorUsed' ]
312 )
313 );
314
315 if ( $editPage->contentModel !== CONTENT_MODEL_WIKITEXT
316 || !ExtensionRegistry::getInstance()->isLoaded( 'EventLogging' ) ) {
317 return;
318 }
319
320 $req = $outputPage->getRequest();
321 $editingStatsId = self::getEditingStatsId( $req );
322
323 $shouldOversample = ExtensionRegistry::getInstance()->isLoaded( 'WikimediaEvents' ) &&
324 WikimediaEventsHooks::shouldSchemaEditAttemptStepOversample( $outputPage->getContext() );
325
326 $outputPage->addHTML(
327 Html::hidden(
328 'editingStatsId',
329 $editingStatsId,
330 [ 'id' => 'editingStatsId' ]
331 )
332 );
333
334 if ( $shouldOversample ) {
335 $outputPage->addHTML(
336 Html::hidden(
337 'editingStatsOversample',
338 1,
339 [ 'id' => 'editingStatsOversample' ]
340 )
341 );
342 }
343 }
344
345 /**
346 * GetPreferences hook
347 *
348 * Adds WikiEditor-related items to the preferences
349 *
350 * @param User $user current user
351 * @param array &$defaultPreferences list of default user preference controls
352 */
353 public function onGetPreferences( $user, &$defaultPreferences ) {
354 // Ideally this key would be 'wikieditor-toolbar'
355 $defaultPreferences['usebetatoolbar'] = [
356 'type' => 'toggle',
357 'label-message' => 'wikieditor-toolbar-preference',
358 'help-message' => 'wikieditor-toolbar-preference-help',
359 'section' => 'editing/editor',
360 ];
361 $defaultPreferences['wikieditor-realtimepreview'] = [
362 'type' => 'api',
363 ];
364 }
365
366 /**
367 * @param RL\Context $context
368 * @param Config $config
369 * @return array
370 */
371 public static function getModuleData( RL\Context $context, Config $config ): array {
372 return [
373 // expose magic words for use by the wikieditor toolbar
374 'magicWords' => self::getMagicWords(),
375 'signature' => self::getSignatureMessage( $context ),
376 'realtimeDebounce' => $config->get( 'WikiEditorRealtimePreviewDebounce' ),
377 'realtimeDisableDuration' => $config->get( 'WikiEditorRealtimeDisableDuration' ),
378 ];
379 }
380
381 /**
382 * @param RL\Context $context
383 * @param Config $config
384 * @return array
385 */
386 public static function getModuleDataSummary( RL\Context $context, Config $config ): array {
387 return [
388 'magicWords' => self::getMagicWords(),
389 'signature' => self::getSignatureMessage( $context, true ),
390 'realtimeDebounce' => $config->get( 'WikiEditorRealtimePreviewDebounce' ),
391 'realtimeDisableDuration' => $config->get( 'WikiEditorRealtimeDisableDuration' ),
392 ];
393 }
394
395 /**
396 * @param MessageLocalizer $ml
397 * @param bool $raw
398 * @return string
399 */
400 private static function getSignatureMessage( MessageLocalizer $ml, bool $raw = false ): string {
401 $msg = $ml->msg( 'sig-text' )->params( '~~~~' )->inContentLanguage();
402 return $raw ? $msg->plain() : $msg->text();
403 }
404
405 /**
406 * Expose useful magic words which are used by the wikieditor toolbar
407 * @return string[][]
408 */
409 private static function getMagicWords(): array {
410 $requiredMagicWords = [
411 'redirect',
412 'img_alt',
413 'img_right',
414 'img_left',
415 'img_none',
416 'img_center',
417 'img_thumbnail',
418 'img_framed',
419 'img_frameless',
420 ];
421 $magicWords = [];
422 $factory = MediaWikiServices::getInstance()->getMagicWordFactory();
423 foreach ( $requiredMagicWords as $name ) {
424 $magicWords[$name] = $factory->get( $name )->getSynonyms();
425 }
426 return $magicWords;
427 }
428
429 /**
430 * Gets a 32 character alphanumeric random string to be used for stats.
431 * @param WebRequest $request
432 * @return string
433 */
434 private static function getEditingStatsId( WebRequest $request ): string {
435 $fromRequest = $request->getRawVal( 'editingStatsId' );
436 if ( $fromRequest !== null ) {
437 return $fromRequest;
438 }
439 if ( !self::$statsId ) {
440 self::$statsId = MWCryptRand::generateHex( 32 );
441 }
442 return self::$statsId;
443 }
444
445 /**
446 * This is attached to the MediaWiki 'EditPage::attemptSave' hook.
447 *
448 * @param EditPage $editPage
449 */
450 public function onEditPage__attemptSave( $editPage ) {
451 $article = $editPage->getArticle();
452 $request = $article->getContext()->getRequest();
453 $statsId = $request->getRawVal( 'editingStatsId' );
454 if ( $statsId !== null ) {
455 $this->doEventLogging(
456 'saveAttempt',
457 $article,
458 [ 'editing_session_id' => $statsId ]
459 );
460 }
461 }
462
463 /**
464 * This is attached to the MediaWiki 'EditPage::attemptSave:after' hook.
465 *
466 * @param EditPage $editPage
467 * @param Status $status
468 * @param array $resultDetails
469 */
470 public function onEditPage__attemptSave_after( $editPage, $status, $resultDetails ) {
471 $article = $editPage->getArticle();
472 $request = $article->getContext()->getRequest();
473 $statsId = $request->getRawVal( 'editingStatsId' );
474 if ( $statsId !== null ) {
475 $data = [];
476 $data['editing_session_id'] = $statsId;
477
478 if ( $status->isOK() ) {
479 $action = 'saveSuccess';
480
481 if ( $request->getRawVal( 'wikieditorUsed' ) === 'yes' ) {
482 $this->doVisualEditorFeatureUseLogging(
483 'mwSave', 'source-has-js', $article, $statsId
484 );
485 }
486 } else {
487 $action = 'saveFailure';
488
489 // Compare to ve.init.mw.ArticleTargetEvents.js in VisualEditor.
490 $typeMap = [
491 'badtoken' => 'userBadToken',
492 'assertanonfailed' => 'userNewUser',
493 'assertuserfailed' => 'userNewUser',
494 'assertnameduserfailed' => 'userNewUser',
495 'abusefilter-disallowed' => 'extensionAbuseFilter',
496 'abusefilter-warning' => 'extensionAbuseFilter',
497 'captcha' => 'extensionCaptcha',
498 'spamblacklist' => 'extensionSpamBlacklist',
499 'titleblacklist-forbidden' => 'extensionTitleBlacklist',
500 'pagedeleted' => 'editPageDeleted',
501 'editconflict' => 'editConflict'
502 ];
503
504 $errors = $status->getErrorsArray();
505 // Replicate how the API generates error codes, in order to log data that is consistent with
506 // all other tools (which save changes via the API)
507 if ( isset( $errors[0] ) ) {
508 $code = ApiMessage::create( $errors[0] )->getApiCode();
509 } else {
510 $code = 'unknown';
511 }
512
513 $wikiPage = $editPage->getArticle()->getPage();
514
515 if ( ExtensionRegistry::getInstance()->isLoaded( 'ConfirmEdit' ) ) {
516 $key = CacheKeyHelper::getKeyForPage( $wikiPage );
517 /** @var SimpleCaptcha $captcha */
518 $captcha = ConfirmEditHooks::getInstance();
519 $activatedCaptchas = $captcha->getActivatedCaptchas();
520 if ( isset( $activatedCaptchas[$key] ) ) {
521 // TODO: :(
522 $code = 'captcha';
523 }
524 }
525
526 $data['save_failure_message'] = $code;
527 $data['save_failure_type'] = $typeMap[ $code ] ?? 'responseUnknown';
528 }
529
530 $this->doEventLogging( $action, $article, $data );
531 }
532 }
533
534 /**
535 * Log a 'preview-nonlive' action when a page is previewed via the non-ajax full-page preview.
536 *
537 * @param EditPage $editPage
538 * @param Content &$content Content object to be previewed (may be replaced by hook function)
539 * @return bool|void True or no return value to continue or false to abort
540 */
541 public function onEditPageGetPreviewContent( $editPage, &$content ) {
542 // This hook is only called for non-live previews, so we don't need to check the uselivepreview user option.
543 $editingStatsId = $editPage->getContext()->getRequest()->getRawVal( 'editingStatsId' );
544 if ( $editingStatsId !== null ) {
545 $article = $editPage->getArticle();
546 $this->doVisualEditorFeatureUseLogging( 'preview', 'preview-nonlive', $article, $editingStatsId );
547 }
548 }
549
550 /**
551 * @param string[] &$tags
552 * @return bool|void
553 */
554 public function onChangeTagsListActive( &$tags ) {
555 $this->registerTags( $tags );
556 }
557
558 /**
559 * @param string[] &$tags
560 * @return bool|void
561 */
562 public function onListDefinedTags( &$tags ) {
563 $this->registerTags( $tags );
564 }
565
566 /**
567 * @param string[] &$tags
568 */
569 protected function registerTags( array &$tags ): void {
570 $tags = array_merge( $tags, static::$tags );
571 }
572
573 /**
574 * @param RecentChange $recentChange
575 * @return bool|void
576 */
577 public function onRecentChange_save( $recentChange ) {
578 $request = RequestContext::getMain()->getRequest();
579 if ( $request->getRawVal( 'wikieditorUsed' ) === 'yes' ) {
580 $recentChange->addTags( 'wikieditor' );
581 }
582 }
583 }