summaryrefslogtreecommitdiff
path: root/extensions/WikiEditor/WikiEditor.hooks.php
blob: 6dfdb6912aa1468ee6085b465d89d2c54f095321 (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
<?php
/**
 * Hooks for WikiEditor extension
 *
 * @file
 * @ingroup Extensions
 */

class WikiEditorHooks {
	// ID used for grouping entries all of a session's entries together in
	// EventLogging.
	private static $statsId = false;

	/* Protected Static Members */

	protected static $features = array(

		/* Toolbar Features */

		'toolbar' => array(
			'preferences' => array(
				// Ideally this key would be 'wikieditor-toolbar'
				'usebetatoolbar' => array(
					'type' => 'toggle',
					'label-message' => 'wikieditor-toolbar-preference',
					'section' => 'editing/editor',
				),
			),
			'requirements' => array(
				'usebetatoolbar' => true,
			),
			'modules' => array(
				'ext.wikiEditor.toolbar',
			),
			'stylemodules' => array(
				'ext.wikiEditor.toolbar.styles',
			),
		),
		'dialogs' => array(
			'preferences' => array(
				// Ideally this key would be 'wikieditor-toolbar-dialogs'
				'usebetatoolbar-cgd' => array(
					'type' => 'toggle',
					'label-message' => 'wikieditor-toolbar-dialogs-preference',
					'section' => 'editing/editor',
				),
			),
			'requirements' => array(
				'usebetatoolbar-cgd' => true,
				'usebetatoolbar' => true,
			),
			'modules' => array(
				'ext.wikiEditor.dialogs',
			),
		),
		'hidesig' => array(
			'preferences' => array(
				'wikieditor-toolbar-hidesig' => array(
					'type' => 'toggle',
					'label-message' => 'wikieditor-toolbar-hidesig',
					'section' => 'editing/editor',
				),
			),
			'requirements' => array(
				'wikieditor-toolbar-hidesig' => true,
				'usebetatoolbar' => true,
			),
			'modules' => array(
				'ext.wikiEditor.toolbar.hideSig',
			),
		),

		/* Labs Features */

		'preview' => array(
			'preferences' => array(
				'wikieditor-preview' => array(
					'type' => 'toggle',
					'label-message' => 'wikieditor-preview-preference',
					'section' => 'editing/labs',
				),
			),
			'requirements' => array(
				'wikieditor-preview' => true,
			),
			'modules' => array(
				'ext.wikiEditor.preview',
			),
		),
		'publish' => array(
			'preferences' => array(
				'wikieditor-publish' => array(
					'type' => 'toggle',
					'label-message' => 'wikieditor-publish-preference',
					'section' => 'editing/labs',
				),
			),
			'requirements' => array(
				'wikieditor-publish' => true,
			),
			'modules' => array(
				'ext.wikiEditor.publish',
			),
		)
	);

	/* Static Methods */

	/**
	 * T99257: Extension registration does not properly support 2d arrays so set it as a global for now
	 */
	public static function onRegistration() {
		// Each module may be configured individually to be globally on/off or user preference based
		$features = array(

			/* Textarea / i-frame compatible (OK to deploy) */

			'toolbar' => array( 'global' => false, 'user' => true ),
			// Provides interactive tools
			'dialogs' => array( 'global' => false, 'user' => true ),
			// Hide signature button from main namespace
			'hidesig' => array( 'global' => true, 'user' => false ),

			/* Textarea / i-frame compatible, but still experimental and unstable (do not deploy!) */

			// Adds a tab for previewing in-line
			'preview' => array( 'global' => false, 'user' => true ),
			// Adds a button and dialog for step-by-step publishing
			'publish' => array( 'global' => false, 'user' => true ),
		);

		// Eww, do a 2d array merge so we don't wipe out settings
		global $wgWikiEditorFeatures;
		if ( $wgWikiEditorFeatures ) {
			foreach ( $features as $name => $settings ) {
				if ( isset( $wgWikiEditorFeatures[$name] ) ) {
					$wgWikiEditorFeatures[$name] += $settings;
				} else {
					$wgWikiEditorFeatures[$name] = $settings;
				}
			}
		} else {
			$wgWikiEditorFeatures = $features;
		}

	}

	/**
	 * Checks if a certain option is enabled
	 *
	 * This method is public to allow other extensions that use WikiEditor to use the
	 * same configuration as WikiEditor itself
	 *
	 * @param $name string Name of the feature, should be a key of $features
	 * @return bool
	 */
	public static function isEnabled( $name ) {
		global $wgWikiEditorFeatures, $wgUser;

		// Features with global set to true are always enabled
		if ( !isset( $wgWikiEditorFeatures[$name] ) || $wgWikiEditorFeatures[$name]['global'] ) {
			return true;
		}
		// Features with user preference control can have any number of preferences
		// to be specific values to be enabled
		if ( $wgWikiEditorFeatures[$name]['user'] ) {
			if ( isset( self::$features[$name]['requirements'] ) ) {
				foreach ( self::$features[$name]['requirements'] as $requirement => $value ) {
					// Important! We really do want fuzzy evaluation here
					if ( $wgUser->getOption( $requirement ) != $value ) {
						return false;
					}
				}
			}
			return true;
		}
		// Features controlled by $wgWikiEditorFeatures with both global and user
		// set to false are always disabled
		return false;
	}

	/**
	 * Log stuff to EventLogging's Schema:Edit - see https://meta.wikimedia.org/wiki/Schema:Edit
	 * If you don't have EventLogging installed, does nothing.
	 *
	 * @param string $action
	 * @param Article $article Which article (with full context, page, title, etc.)
	 * @param array $data Data to log for this action
	 * @return bool Whether the event was logged or not.
	 */
	public static function doEventLogging( $action, $article, $data = array() ) {
		global $wgVersion;
		if ( !class_exists( 'EventLogging' ) ) {
			return false;
		}

		$user = $article->getContext()->getUser();
		$page = $article->getPage();
		$title = $article->getTitle();

		$data = array(
			'action' => $action,
			'version' => 1,
			'editor' => 'wikitext',
			'platform' => 'desktop', // FIXME
			'integration' => 'page',
			'page.length' => -1, // FIXME
			'page.id' => $page->getId(),
			'page.title' => $title->getPrefixedText(),
			'page.ns' => $title->getNamespace(),
			'page.revid' => $page->getRevision() ? $page->getRevision()->getId() : 0,
			'user.id' => $user->getId(),
			'user.editCount' => $user->getEditCount() ?: 0,
			'mediawiki.version' => $wgVersion
		) + $data;

		if ( $user->isAnon() ) {
			$data['user.class'] = 'IP';
		}

		return EventLogging::logEvent( 'Edit', 11448630, $data );
	}

	/**
	 * EditPage::showEditForm:initial hook
	 *
	 * Adds the modules to the edit form
	 *
	 * @param EditPage $editPage the current EditPage object.
	 * @param OutputPage $outputPage object.
	 * @return bool
	 */
	public static function editPageShowEditFormInitial( $editPage, $outputPage ) {
		if ( $editPage->contentModel !== CONTENT_MODEL_WIKITEXT ) {
			return true;
		}

		// Add modules for enabled features
		foreach ( self::$features as $name => $feature ) {
			if ( !self::isEnabled( $name ) ) {
				continue;
			}
			if ( isset( $feature['stylemodules'] ) ) {
				$outputPage->addModuleStyles( $feature['stylemodules'] );
			}
			if ( isset( $feature['modules'] ) ) {
				$outputPage->addModules( $feature['modules'] );
			}
		}

		$article = $editPage->getArticle();
		$request = $article->getContext()->getRequest();
		// Don't run this if the request was posted - we don't want to log 'init' when the
		// user just pressed 'Show preview' or 'Show changes', or switched from VE keeping
		// changes.
		if ( class_exists( 'EventLogging' ) && !$request->wasPosted() ) {
			$data = array();
			$data['editingSessionId'] = self::getEditingStatsId();
			if ( $request->getVal( 'section' ) ) {
				$data['action.init.type'] = 'section';
			} else {
				$data['action.init.type'] = 'page';
			}
			if ( $request->getHeader( 'Referer' ) ) {
				if ( $request->getVal( 'section' ) === 'new' || !$article->exists() ) {
					$data['action.init.mechanism'] = 'new';
				} else {
					$data['action.init.mechanism'] = 'click';
				}
			} else {
				$data['action.init.mechanism'] = 'url';
			}

			self::doEventLogging( 'init', $article, $data );
		}

		return true;
	}

	/**
	 * EditPage::showEditForm:fields hook
	 *
	 * Adds the event fields to the edit form
	 *
	 * @param EditPage $editPage the current EditPage object.
	 * @param OutputPage $outputPage object.
	 * @return bool
	 */
	public static function editPageShowEditFormFields( $editPage, $outputPage ) {
		if ( $editPage->contentModel !== CONTENT_MODEL_WIKITEXT ) {
			return true;
		}

		$req = $outputPage->getContext()->getRequest();
		$editingStatsId = $req->getVal( 'editingStatsId' );
		if ( !$editingStatsId ) {
			$editingStatsId = self::getEditingStatsId();
		}
		$outputPage->addHTML(
			Xml::element(
				'input',
				array(
					'type' => 'hidden',
					'name' => 'editingStatsId',
					'id' => 'editingStatsId',
					'value' => $editingStatsId
				)
			)
		);
		return true;
	}

	/**
	 * EditPageBeforeEditToolbar hook
	 *
	 * Disable the old toolbar if the new one is enabled
	 *
	 * @param $toolbar html
	 * @return bool
	 */
	public static function EditPageBeforeEditToolbar( &$toolbar ) {
		if ( self::isEnabled( 'toolbar' ) ) {
			$toolbar = Html::rawElement(
				'div', array(
					'class' => 'wikiEditor-oldToolbar'
				),
				$toolbar
			);
		}
		return true;
	}

	/**
	 * GetPreferences hook
	 *
	 * Adds WikiEditor-related items to the preferences
	 *
	 * @param User $user current user
	 * @param array $defaultPreferences list of default user preference controls
	 * @return bool
	 */
	public static function getPreferences( $user, &$defaultPreferences ) {
		global $wgWikiEditorFeatures;

		foreach ( self::$features as $name => $feature ) {
			if (
				isset( $feature['preferences'] ) &&
				( !isset( $wgWikiEditorFeatures[$name] ) || $wgWikiEditorFeatures[$name]['user'] )
			) {
				foreach ( $feature['preferences'] as $key => $options ) {
					$defaultPreferences[$key] = $options;
				}
			}
		}
		return true;
	}

	/**
	 * @param $vars array
	 * @return bool
	 */
	public static function resourceLoaderGetConfigVars( &$vars ) {
		// expose magic words for use by the wikieditor toolbar
		WikiEditorHooks::getMagicWords( $vars );
		return true;
	}

	/**
	 * ResourceLoaderTestModules hook
	 *
	 * Registers JavaScript test modules
	 *
	 * @param $testModules array of javascript testing modules. 'qunit' is fed using
	 * tests/qunit/QUnitTestResources.php.
	 * @param $resourceLoader object
	 * @return bool
	 */
	public static function resourceLoaderTestModules( &$testModules, &$resourceLoader ) {
		$testModules['qunit']['ext.wikiEditor.toolbar.test'] = array(
			'scripts' => array( 'tests/qunit/ext.wikiEditor.toolbar.test.js' ),
			'dependencies' => array( 'ext.wikiEditor.toolbar' ),
			'localBasePath' => __DIR__,
			'remoteExtPath' => 'WikiEditor',
		);
		return true;
	}

	/**
	 * MakeGlobalVariablesScript hook
	 *
	 * Adds enabled/disabled switches for WikiEditor modules
	 * @param $vars array
	 * @return bool
	 */
	public static function makeGlobalVariablesScript( &$vars ) {
		// Build and export old-style wgWikiEditorEnabledModules object for back compat
		$enabledModules = array();
		foreach ( self::$features as $name => $feature ) {
			$enabledModules[$name] = self::isEnabled( $name );
		}

		$vars['wgWikiEditorEnabledModules'] = $enabledModules;
		return true;
	}

	/**
	 * Expose useful magic words which are used by the wikieditor toolbar
	 * @param $vars array
	 * @return bool
	 */
	private static function getMagicWords( &$vars ) {
		$requiredMagicWords = array(
			'redirect',
			'img_right',
			'img_left',
			'img_none',
			'img_center',
			'img_thumbnail',
			'img_framed',
			'img_frameless',
		);
		$magicWords = array();
		foreach ( $requiredMagicWords as $name ) {
			$magicWords[$name] = MagicWord::get( $name )->getSynonym( 0 );
		}
		$vars['wgWikiEditorMagicWords'] = $magicWords;
	}


	/**
	 * Adds WikiEditor JS to the output.
	 *
	 * This is attached to the MediaWiki 'BeforePageDisplay' hook.
	 *
	 * @param OutputPage $output
	 * @param Skin $skin
	 * @return boolean
	 */
	public static function onBeforePageDisplay( OutputPage &$output, Skin &$skin ) {
		$output->addModules( array( 'ext.wikiEditor.init' ) );
		return true;
	}

	/**
	 * Gets a 32 character alphanumeric random string to be used for stats.
	 * @return string
	 */
	private static function getEditingStatsId() {
		if ( self::$statsId ) {
			return self::$statsId;
		}
		return self::$statsId = MWCryptRand::generateHex( 32 );
	}

	/**
	 * This is attached to the MediaWiki 'EditPage::attemptSave' hook.
	 *
	 * @param EditPage $editPage
	 * @param Status $status
	 * @return boolean
	 */
	public static function editPageAttemptSave( EditPage $editPage ) {
		$article = $editPage->getArticle();
		$request = $article->getContext()->getRequest();
		if ( $request->getVal( 'editingStatsId' ) ) {
			self::doEventLogging(
				'saveAttempt',
				$article,
				array( 'editingSessionId' => $request->getVal( 'editingStatsId' ) )
			);
		}

		return true;
	}

	/**
	 * This is attached to the MediaWiki 'EditPage::attemptSave:after' hook.
	 *
	 * @param EditPage $editPage
	 * @param Status $status
	 * @return boolean
	 */
	public static function editPageAttemptSaveAfter( EditPage $editPage, Status $status ) {
		$article = $editPage->getArticle();
		$request = $article->getContext()->getRequest();
		if ( $request->getVal( 'editingStatsId' ) ) {
			$data = array();
			$data['editingSessionId'] = $request->getVal( 'editingStatsId' );

			if ( $status->isOK() ) {
				$action = 'saveSuccess';
			} else {
				$action = 'saveFailure';
				$errors = $status->getErrorsArray();

				if ( isset( $errors[0][0] ) ) {
					$data['action.saveFailure.message'] = $errors[0][0];
				}

				if ( $status->value === EditPage::AS_CONFLICT_DETECTED ) {
					$data['action.saveFailure.type'] = 'editConflict';
				} elseif ( $status->value === EditPage::AS_ARTICLE_WAS_DELETED ) {
					$data['action.saveFailure.type'] = 'editPageDeleted';
				} elseif ( isset( $errors[0][0] ) && $errors[0][0] === 'abusefilter-disallowed' ) {
					$data['action.saveFailure.type'] = 'extensionAbuseFilter';
				} elseif ( isset( $editPage->getArticle()->getPage()->ConfirmEdit_ActivateCaptcha ) ) {
					// TODO: :(
					$data['action.saveFailure.type'] = 'extensionCaptcha';
				} elseif ( isset( $errors[0][0] ) && $errors[0][0] === 'spamprotectiontext' ) {
					$data['action.saveFailure.type'] = 'extensionSpamBlacklist';
				} else {
					// Catch everything else... We don't seem to get userBadToken or
					// userNewUser through this hook.
					$data['action.saveFailure.type'] = 'responseUnknown';
				}
			}
			self::doEventLogging( $action, $article, $data );
		}

		return true;
	}
}