summaryrefslogtreecommitdiff
blob: 897ce9c8469fb1dca8b9438539408015d7c9fcb2 (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
<?php
/*
 * Copyright (c) 2016 The MITRE Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */

namespace MediaWiki\Extension\CommentStreams;

use Article;
use DatabaseUpdater;
use MediaWiki;
use OutputPage;
use Parser;
use PPFrame;
use SearchResult;
use Skin;
use SMW\DIWikiPage;
use SMW\DIProperty;
use SMW\PropertyRegistry;
use SpecialSearch;
use Status;
use Title;
use User;
use WebRequest;
use WikiPage;

class CommentStreamsHooks {

	/**
	 * Implements LoadExtensionSchemaUpdates hook.
	 * See https://www.mediawiki.org/wiki/Manual:Hooks/LoadExtensionSchemaUpdates
	 * Updates database schema.
	 *
	 * @param DatabaseUpdater $updater database updater
	 * @return bool continue checking hooks
	 */
	public static function addCommentTableToDatabase( DatabaseUpdater $updater ) {
		$dir = $GLOBALS['wgExtensionDirectory'] . DIRECTORY_SEPARATOR .
			'CommentStreams' . DIRECTORY_SEPARATOR . 'sql' . DIRECTORY_SEPARATOR;
		$updater->addExtensionTable( 'cs_comment_data', $dir . 'commentData.sql' );
		$updater->addExtensionTable( 'cs_votes', $dir . 'votes.sql' );
		$updater->addExtensionTable( 'cs_watchlist', $dir . 'watch.sql' );
		$updater->modifyExtensionField( 'cs_comment_data', 'page_id',
			$dir . 'updateFieldNames.sql' );
		$updater->dropExtensionIndex( 'cs_comment_data', 'assoc_page_id',
			$dir . 'dropForeignKey1.sql' );
		$updater->dropExtensionIndex( 'cs_comment_data', 'cst_assoc_page_id',
			$dir . 'dropForeignKey2.sql' );
		return true;
	}

	/**
	 * Implements CanonicalNamespaces hook.
	 * See https://www.mediawiki.org/wiki/Manual:Hooks/CanonicalNamespaces
	 * Adds CommentStreams namespaces.
	 *
	 * @param array &$namespaces modifiable array of namespace numbers with
	 * corresponding canonical names
	 * @return bool continue checking hooks
	 */
	public static function addCommentStreamsNamespaces( array &$namespaces ) {
		$namespaces[NS_COMMENTSTREAMS] = 'CommentStreams';
		$namespaces[NS_COMMENTSTREAMS_TALK] = 'CommentStreams_Talk';
		return true;
	}

	/**
	 * Implement MediaWikiPerformAction hook.
	 * See https://www.mediawiki.org/wiki/Manual:Hooks/MediaWikiPerformAction
	 * Prevents comment pages from being edited or deleted. Displays
	 * comment title and link to associated page when comment is viewed.
	 *
	 * @param OutputPage $output OutputPage object
	 * @param Article $article Article object
	 * @param Title $title Title object
	 * @param User $user User object
	 * @param WebRequest $request WebRequest object
	 * @param MediaWiki $wiki MediaWiki object
	 * @return bool continue checking hooks
	 */
	public static function onMediaWikiPerformAction( OutputPage $output,
		Article $article, Title $title, User $user, WebRequest $request,
		MediaWiki $wiki ) {
		if ( $title->getNamespace() !== NS_COMMENTSTREAMS ) {
			return true;
		}
		$action = $wiki->getAction();
		if ( $action === 'info' || $action === 'history' ) {
			return true;
		}
		if ( $action !== 'view' ) {
			$message =
				wfMessage( 'commentstreams-error-prohibitedaction', $action )->text();
			$output->addHTML( '<p class="error">' . $message . '</p>' );
		}
		$wikipage = new WikiPage( $title );
		$comment = Comment::newFromWikiPage( $wikipage );
		if ( $comment !== null ) {
			$commentTitle = $comment->getCommentTitle();
			if ( $commentTitle !== null ) {
				$output->setPageTitle( $commentTitle );
			}
			$associatedTitle = Title::newFromId( $comment->getAssociatedId() );
			if ( $associatedTitle !== null ) {
				$values = [];
				if ( class_exists( 'PageProps' ) ) {
					$values = \PageProps::getInstance()->getProperties( $associatedTitle,
						'displaytitle' );
				}
				if ( array_key_exists( $comment->getAssociatedId(), $values ) ) {
					$displaytitle = $values[$comment->getAssociatedId()];
				} else {
					$displaytitle = $associatedTitle->getPrefixedText();
				}
				$output->setSubtitle(
					CommentStreamsUtils::link( $associatedTitle, '< ' . $displaytitle )
				);
			} else {
				$message =
					wfMessage( 'commentstreams-error-comment-on-deleted-page' )->text();
				$output->addHTML( '<p class="error">' . $message . '</p>' );
			}
			if ( method_exists( 'OutputPage', 'addWikiTextAsInterface' ) ) {
				$output->addWikiTextAsInterface( $comment->getHTML() );
			} else {
				$output->addWikiText( $comment->getHTML() );
			}
		}
		return false;
	}

	/**
	 * Implement MovePageIsValidMove hook.
	 * See https://www.mediawiki.org/wiki/Manual:Hooks/MovePageIsValidMove
	 * Prevents comment pages from being moved.
	 *
	 * @param Title $oldTitle Title object of the current (old) location
	 * @param Title $newTitle Title object of the new location
	 * @param Status $status Status object to pass error messages to
	 * @return bool continue checking hooks
	 */
	public static function onMovePageIsValidMove( Title $oldTitle,
		Title $newTitle, Status $status ) {
		if ( $oldTitle->getNamespace() === NS_COMMENTSTREAMS ||
			$newTitle->getNamespace() === NS_COMMENTSTREAMS ) {
			$status->fatal( wfMessage( 'commentstreams-error-prohibitedaction',
				'move' ) );
			return false;
		}
		return true;
	}

	/**
	 * Implements userCan hook.
	 * See https://www.mediawiki.org/wiki/Manual:Hooks/userCan
	 * Ensures that only the original author can edit a comment
	 *
	 * @param Title &$title the title object in question
	 * @param User &$user the user performing the action
	 * @param string $action the action being performed
	 * @param bool &$result true means the user is allowed, false means the
	 * user is not allowed, untouched means this hook has no opinion
	 * @return bool continue checking hooks
	 */
	public static function userCan( Title &$title, User &$user, $action,
		&$result ) {
		if ( $title->getNamespace() !== NS_COMMENTSTREAMS ) {
			return true;
		}

		$wikipage = new WikiPage( $title );

		if ( !$wikipage->exists() ) {
			return true;
		}

		if ( $user->isBlocked() ) {
			$result = false;
			return false;
		}

		if ( $action === 'cs-comment' ) {
			if ( $user->getId() === $wikipage->getOldestRevision()->getUser() ) {
				$result = true;
			} else {
				$result = false;
			}
			return false;
		}

		if ( $action === 'cs-moderator-edit' ) {
			if ( in_array( 'cs-moderator-edit', $user->getRights() ) ) {
				$result = true;
			} else {
				$result = false;
			}
			return false;
		}

		if ( $action === 'cs-moderator-delete' ) {
			if ( in_array( 'cs-moderator-delete', $user->getRights() ) ) {
				$result = true;
			} else {
				$result = false;
			}
			return false;
		}

		return true;
	}

	/**
	 * Implements ParserFirstCallInit hook.
	 * See https://www.mediawiki.org/wiki/Manual:Hooks/ParserFirstCallInit
	 * Adds comment-streams, no-comment-streams, and
	 * comment-streams-initially-collapsed magic words.
	 *
	 * @param Parser $parser the parser
	 * @return bool continue checking hooks
	 */
	public static function onParserSetup( Parser $parser ) {
		$parser->setHook( 'comment-streams',
			'MediaWiki\Extension\CommentStreams\CommentStreamsHooks::enableCommentStreams' );
		$parser->setHook( 'no-comment-streams',
			'MediaWiki\Extension\CommentStreams\CommentStreamsHooks::disableCommentStreams' );
		$parser->setHook( 'comment-streams-initially-collapsed',
			'MediaWiki\Extension\CommentStreams\CommentStreamsHooks::initiallyCollapseCommentStreams' );
		return true;
	}

	/**
	 * Implements tag function, <comment-streams/>, which enables
	 * CommentStreams on a page.
	 *
	 * @param string $input input between the tags (ignored)
	 * @param array $args tag arguments
	 * @param Parser $parser the parser
	 * @param PPFrame $frame the parent frame
	 * @return string to replace tag with
	 */
	public static function enableCommentStreams( $input, array $args,
		Parser $parser, PPFrame $frame ) {
		$parser->getOutput()->updateCacheExpiry( 0 );
		$cs = CommentStreams::singleton();
		$cs->enableCommentsOnPage();
		if ( isset( $args['location'] ) && $args['location'] === 'footer' ) {
			$ret = '';
		} else {
			$ret = '<div id="cs-comments"></div>';
		}
		return $ret;
	}

	/**
	 * Implements tag function, <no-comment-streams/>, which disables
	 * CommentStreams on a page.
	 *
	 * @param string $input input between the tags (ignored)
	 * @param array $args tag arguments
	 * @param Parser $parser the parser
	 * @param PPFrame $frame the parent frame
	 * @return string to replace tag with
	 */
	public static function disableCommentStreams( $input, array $args,
		Parser $parser, PPFrame $frame ) {
		$parser->getOutput()->updateCacheExpiry( 0 );
		$cs = CommentStreams::singleton();
		$cs->disableCommentsOnPage();
		return "";
	}

	/**
	 * Implements tag function, <comment-streams-initially-collapsed/>, which
	 * makes CommentStreams on a page start as collapsed when the page is viewed.
	 *
	 * @param string $input input between the tags (ignored)
	 * @param array $args tag arguments
	 * @param Parser $parser the parser
	 * @param PPFrame $frame the parent frame
	 * @return string to replace tag with
	 */
	public static function initiallyCollapseCommentStreams( $input, array $args,
		Parser $parser, PPFrame $frame ) {
		$parser->getOutput()->updateCacheExpiry( 0 );
		$cs = CommentStreams::singleton();
		$cs->initiallyCollapseCommentsOnPage();
		return "";
	}

	/**
	 * Implements BeforePageDisplay hook.
	 * See https://www.mediawiki.org/wiki/Manual:Hooks/BeforePageDisplay
	 * Gets comments for page and initializes variables to be passed to JavaScript.
	 *
	 * @param OutputPage &$output OutputPage object
	 * @param Skin &$skin Skin object that will be used to generate the page
	 * @return bool continue checking hooks
	 */
	public static function addCommentsAndInitializeJS( OutputPage &$output,
		Skin &$skin ) {
		$cs = CommentStreams::singleton();
		$cs->init( $output );
		return true;
	}

	/**
	 * Implements ShowSearchHitTitle hook.
	 * See https://www.mediawiki.org/wiki/Manual:Hooks/ShowSearchHitTitle
	 * Modifies search results pointing to comment pages to point to the
	 * associated content page instead.
	 *
	 * @param Title &$title title to link to
	 * @param string &$text text to use for the link
	 * @param SearchResult $result the search result
	 * @param array $terms the search terms entered
	 * @param SpecialSearch $page the SpecialSearch object
	 * @return bool continue checking hooks
	 */
	public static function showSearchHitTitle( Title &$title, &$text,
		SearchResult $result, array $terms, SpecialSearch $page ) {
		$comment = Comment::newFromWikiPage( WikiPage::factory( $title ) );
		if ( $comment !== null ) {
			$t = Title::newFromId( $comment->getAssociatedId() );
			if ( $t !== null ) {
				$title = $t;
			}
		}
		return true;
	}

	/**
	 * Implements SMW::Settings::BeforeInitializationComplete callback.
	 * See https://github.com/SemanticMediaWiki/SemanticMediaWiki/blob/master/docs/technical/hooks/hook.settings.beforeinitializationcomplete.md
	 * Defines CommentStreams namespace constants.
	 *
	 * @param array &$configuration An array of the configuration options
	 */
	public static function onSMWInitialization( array &$configuration ) {
		$namespace = $GLOBALS['wgCommentStreamsNamespaceIndex'];
		$configuration['smwgNamespacesWithSemanticLinks'][$namespace] = true;
	}

	/**
	 * Implements extension registration callback.
	 * See https://www.mediawiki.org/wiki/Manual:Extension_registration#Customizing_registration
	 * Sets configuration constants.
	 *
	 */
	public static function onRegistration() {
		define( 'NS_COMMENTSTREAMS', $GLOBALS['wgCommentStreamsNamespaceIndex'] );
		define( 'NS_COMMENTSTREAMS_TALK',
			$GLOBALS['wgCommentStreamsNamespaceIndex'] + 1 );
		$GLOBALS['wgNamespacesToBeSearchedDefault'][NS_COMMENTSTREAMS] = true;
		$found = false;
		foreach ( $GLOBALS['wgGroupPermissions'] as $groupperms ) {
			if ( isset( $groupperms['cs-comment'] ) ) {
				$found = true;
				break;
			}
		}
		if ( !$found ) {
			foreach ( $GLOBALS['wgGroupPermissions'] as $group => $groupperms ) {
				if ( isset( $groupperms['edit'] ) ) {
					$GLOBALS['wgGroupPermissions'][$group]['cs-comment'] =
						$groupperms['edit'];
				}
			}
		}
		if ( !isset( $GLOBALS['wgGroupPermissions']['csmoderator']
			['cs-moderator-delete'] ) ) {
			$GLOBALS['wgGroupPermissions']['csmoderator']['cs-moderator-delete'] =
				true;
		}
		if ( !isset( $GLOBALS['wgGroupPermissions']['csmoderator']
			['cs-moderator-edit'] ) ) {
			$GLOBALS['wgGroupPermissions']['csmoderator']['cs-moderator-edit'] =
				false;
		}
		$GLOBALS['wgAvailableRights'][] = 'cs-comment';
		$GLOBALS['wgAvailableRights'][] = 'cs-moderator-edit';
		$GLOBALS['wgAvailableRights'][] = 'cs-moderator-delete';
		$GLOBALS['wgLogTypes'][] = 'commentstreams';
		$GLOBALS['wgLogActionsHandlers']['commentstreams/*'] = 'LogFormatter';
	}

	/**
	 * Initialize extra Semantic MediaWiki properties.
	 * This won't get called unless Semantic MediaWiki is installed.
	 */
	public static function initProperties() {
		$pr = PropertyRegistry::getInstance();
		$pr->registerProperty( '___CS_ASSOCPG', '_wpg', 'Comment on' );
		$pr->registerProperty( '___CS_REPLYTO', '_wpg', 'Reply to' );
		$pr->registerProperty( '___CS_TITLE', '_txt', 'Comment title of' );
		$pr->registerProperty( '___CS_UPVOTES', '_num', 'Comment up votes' );
		$pr->registerProperty( '___CS_DOWNVOTES', '_num', 'Comment down votes' );
		$pr->registerProperty( '___CS_VOTEDIFF', '_num', 'Comment vote diff' );
	}

	/**
	 * Implements Semantic MediaWiki SMWStore::updateDataBefore callback.
	 * This won't get called unless Semantic MediaWiki is installed.
	 * If the comment has not been added to the database yet, which is indicated
	 * by a null associated page id, this function will return early, but it
	 * will be invoked again by an update job.
	 *
	 * @param SMW\Store $store semantic data store
	 * @param SMW\SemanticData $semanticData semantic data for page
	 * @return bool true to continue
	 */
	public static function updateData( $store, $semanticData ) {
		$subject = $semanticData->getSubject();
		if ( $subject !== null && $subject->getTitle() !== null &&
			$subject->getTitle()->getNamespace() === NS_COMMENTSTREAMS ) {
			$page_id = $subject->getTitle()->getArticleID( Title::GAID_FOR_UPDATE );
			$wikipage = WikiPage::newFromId( $page_id );
			$comment = Comment::newFromWikiPage( $wikipage );

			if ( $comment === null ) {
				return true;
			}

			$assoc_page_id = $comment->getAssociatedId();
			if ( $assoc_page_id !== null ) {
				$assoc_wikipage = WikiPage::newFromId( $assoc_page_id );
				if ( $assoc_wikipage !== null ) {
					$propertyDI = new DIProperty( '___CS_ASSOCPG' );
					$dataItem =
						DIWikiPage::newFromTitle( $assoc_wikipage->getTitle() );
					$semanticData->addPropertyObjectValue( $propertyDI, $dataItem );
				}
			}

			$parent_page_id = $comment->getParentId();
			if ( $parent_page_id !== null ) {
				$parent_wikipage = WikiPage::newFromId( $parent_page_id );
				if ( $parent_wikipage !== null ) {
					$propertyDI = new DIProperty( '___CS_REPLYTO' );
					$dataItem =
						DIWikiPage::newFromTitle( $parent_wikipage->getTitle() );
					$semanticData->addPropertyObjectValue( $propertyDI, $dataItem );
				}
			}

			$commentTitle = $comment->getCommentTitle();
			if ( $commentTitle !== null ) {
				$propertyDI = new DIProperty( '___CS_TITLE' );
				$dataItem = new SMWDIBlob( $comment->getCommentTitle() );
				$semanticData->addPropertyObjectValue( $propertyDI, $dataItem );
			}

			if ( $GLOBALS['wgCommentStreamsEnableVoting'] === true ) {
				$upvotes = $comment->getNumUpVotes();
				$propertyDI = new DIProperty( '___CS_UPVOTES' );
				$dataItem = new SMWDINumber( $upvotes );
				$semanticData->addPropertyObjectValue( $propertyDI, $dataItem );
				$downvotes = $comment->getNumDownVotes();
				$propertyDI = new DIProperty( '___CS_DOWNVOTES' );
				$dataItem = new SMWDINumber( $downvotes );
				$semanticData->addPropertyObjectValue( $propertyDI, $dataItem );
				$votediff = $upvotes - $downvotes;
				$propertyDI = new DIProperty( '___CS_VOTEDIFF' );
				$dataItem = new SMWDINumber( $votediff );
				$semanticData->addPropertyObjectValue( $propertyDI, $dataItem );
			}
		}
		return true;
	}

	/**
	 * @param array &$notifications notifications
	 * @param array &$notificationCategories notification categories
	 * @param array &$icons notification icons
	 */
	public static function onBeforeCreateEchoEvent( &$notifications,
		&$notificationCategories, &$icons ) {
		$notificationCategories['commentstreams-notification-category'] = [
			'priority' => 3
		];

		$notifications['commentstreams-comment-on-watched-page'] = [
			'category' => 'commentstreams-notification-category',
			'group' => 'positive',
			'section' => 'alert',
			'presentation-model' => EchoCSPresentationModel::class,
			'user-locators' => [ 'EchoUserLocator::locateUsersWatchingTitle' ]
		];

		$notifications['commentstreams-reply-on-watched-page'] = [
			'category' => 'commentstreams-notification-category',
			'group' => 'positive',
			'section' => 'alert',
			'presentation-model' => EchoCSPresentationModel::class,
			'user-locators' => [ 'EchoUserLocator::locateUsersWatchingTitle' ],
			'user-filters' => [ 'Comment::locateUsersWatchingComment' ]
		];

		$notifications['commentstreams-reply-to-watched-comment'] = [
			'category' => 'commentstreams-notification-category',
			'group' => 'positive',
			'section' => 'alert',
			'presentation-model' => EchoCSPresentationModel::class,
			'user-locators' => [ 'Comment::locateUsersWatchingComment' ]
		];
	}
}