-
Notifications
You must be signed in to change notification settings - Fork 10
/
Hooks.php
2095 lines (1864 loc) 路 62.4 KB
/
Hooks.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
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
namespace Flow;
use Article;
use ChangesList;
use Config;
use Content;
use ContentHandler;
use ContribsPager;
use DatabaseUpdater;
use DeferredUpdates;
use DeletedContribsPager;
use EchoEvent;
use EnhancedChangesList;
use Exception;
use ExtensionRegistry;
use FeedItem;
use Flow\Collection\PostCollection;
use Flow\Conversion\Utils;
use Flow\Data\Listener\RecentChangesListener;
use Flow\Exception\FlowException;
use Flow\Exception\InvalidInputException;
use Flow\Exception\PermissionException;
use Flow\Formatter\CheckUserQuery;
use Flow\Import\OptInController;
use Flow\Maintenance\FlowCreateTemplates;
use Flow\Maintenance\FlowFixLinks;
use Flow\Maintenance\FlowFixLog;
use Flow\Maintenance\FlowPopulateLinksTables;
use Flow\Maintenance\FlowPopulateRefId;
use Flow\Maintenance\FlowSetUserIp;
use Flow\Maintenance\FlowUpdateBetaFeaturePreference;
use Flow\Maintenance\FlowUpdateRecentChanges;
use Flow\Maintenance\FlowUpdateRevisionTypeId;
use Flow\Maintenance\FlowUpdateUserWiki;
use Flow\Maintenance\FlowUpdateWorkflowPageId;
use Flow\Model\UUID;
use Flow\SpamFilter\AbuseFilter;
use FormOptions;
use Html;
use IContextSource;
use LogEntry;
use MediaWiki\CheckUser\CheckUser\Pagers\AbstractCheckUserPager;
use MediaWiki\Extension\AbuseFilter\Variables\VariableHolder;
use MediaWiki\Extension\BetaFeatures\BetaFeatures;
use MediaWiki\Extension\GuidedTour\GuidedTourLauncher;
use MediaWiki\Linker\LinkTarget;
use MediaWiki\MediaWikiServices;
use MediaWiki\Revision\RevisionRecord;
use MediaWiki\Revision\SlotRecord;
use MediaWiki\User\UserIdentity;
use Message;
use MessageLocalizer;
use MWException;
use MWExceptionHandler;
use OldChangesList;
use OutputPage;
use RecentChange;
use RequestContext;
use ResourceLoader;
use Skin;
use SkinTemplate;
use Status;
use stdClass;
use Title;
use User;
use WikiImporter;
use WikiMap;
use WikiPage;
use XMLReader;
class Hooks {
/**
* @var OccupationController|null Initialized during extension initialization
*/
protected static $occupationController;
/**
* @var AbuseFilter|null Initialized during extension initialization
*/
protected static $abuseFilter;
public static function registerExtension() {
require_once dirname( __DIR__ ) . '/defines.php';
}
public static function onResourceLoaderRegisterModules( ResourceLoader &$resourceLoader ) {
// Register a dummy supportCheck module in case VE isn't loaded, as we attempt
// to load this module unconditionally on load.
if ( !$resourceLoader->isModuleRegistered( 'ext.visualEditor.supportCheck' ) ) {
$resourceLoader->register( 'ext.visualEditor.supportCheck', [ 'targets' => [ 'desktop', 'mobile' ] ] );
}
if ( ExtensionRegistry::getInstance()->isLoaded( 'GuidedTour' ) ) {
$resourceLoader->register( 'ext.guidedTour.tour.flowOptIn', [
'localBasePath' => dirname( __DIR__ ) . '/modules',
'remoteExtPath' => 'Flow/modules',
'scripts' => 'tours/flowOptIn.js',
'styles' => 'tours/flowOptIn.less',
'messages' => [
"flow-guidedtour-optin-welcome",
"flow-guidedtour-optin-welcome-description",
"flow-guidedtour-optin-find-old-conversations",
"flow-guidedtour-optin-find-old-conversations-description",
"flow-guidedtour-optin-feedback",
"flow-guidedtour-optin-feedback-description"
],
'dependencies' => 'ext.guidedTour',
] );
}
}
public static function onBeforePageDisplay( OutputPage &$out, Skin &$skin ) {
$title = $skin->getTitle();
// Register guided tour if needed
if (
// Check that the cookie for Flow opt-in tour exists
$out->getRequest()->getCookie( 'Flow_optIn_guidedTour' ) &&
// Check that the user is on their own talk page
$out->getUser()->getTalkPage()->equals( $title ) &&
// Check that we are on a flow board
$title->getContentModel() === CONTENT_MODEL_FLOW_BOARD &&
// Check that guided tour exists
ExtensionRegistry::getInstance()->isLoaded( 'GuidedTour' )
) {
// Activate tour
GuidedTourLauncher::launchTourByCookie( 'flowOptIn', 'newTopic' );
// Destroy Flow cookie
$out->getRequest()->response()->setCookie( 'Flow_optIn_guidedTour', '', time() - 3600 );
}
}
/**
* Constructed outside of the container so that non-flow pages
* don't load the container
*
* @return OccupationController
*/
public static function getOccupationController() {
if ( self::$occupationController === null ) {
self::$occupationController = new TalkpageManager( MediaWikiServices::getInstance()->getUserGroupManager() );
}
return self::$occupationController;
}
/**
* Initialized during extension initialization rather than
* in container so that non-flow pages don't load the container.
*
* @return AbuseFilter
*/
public static function getAbuseFilter() {
if ( self::$abuseFilter === null ) {
global $wgFlowAbuseFilterGroup,
$wgFlowAbuseFilterEmergencyDisableThreshold,
$wgFlowAbuseFilterEmergencyDisableCount,
$wgFlowAbuseFilterEmergencyDisableAge;
self::$abuseFilter = new AbuseFilter( $wgFlowAbuseFilterGroup );
self::$abuseFilter->setup( [
'threshold' => $wgFlowAbuseFilterEmergencyDisableThreshold,
'count' => $wgFlowAbuseFilterEmergencyDisableCount,
'age' => $wgFlowAbuseFilterEmergencyDisableAge,
] );
}
return self::$abuseFilter;
}
/**
* Initialize Flow extension with necessary data, this function is invoked
* from $wgExtensionFunctions
*/
public static function initFlowExtension() {
global $wgFlowContentFormat, $wgFlowAbuseFilterGroup;
// necessary to provide flow options in abuse filter on-wiki pages
// @phan-suppress-next-line PhanPossiblyUndeclaredVariable
if ( $wgFlowAbuseFilterGroup ) {
self::getAbuseFilter();
}
if ( $wgFlowContentFormat === 'html' && !Utils::isParsoidConfigured() ) {
wfDebugLog( 'Flow', __METHOD__ . ': Warning: $wgFlowContentFormat was set to \'html\', ' .
'but you do not have Parsoid enabled. Changing $wgFlowContentFormat to \'wikitext\'' );
$wgFlowContentFormat = 'wikitext';
}
}
/**
* Reset anything that happened in self::initFlowExtension for
* unit tests
*/
public static function resetFlowExtension() {
self::$abuseFilter = null;
self::$occupationController = null;
}
/**
* Hook: LoadExtensionSchemaUpdates
*
* @param DatabaseUpdater $updater
*/
public static function getSchemaUpdates( DatabaseUpdater $updater ) {
$dir = dirname( __DIR__ ) . '/sql';
$dbType = $updater->getDB()->getType();
$updater->addExtensionTable( 'flow_revision', "$dir/$dbType/tables-generated.sql" );
if ( $dbType === 'mysql' ) {
// 1.35 (backported to 1.34)
$updater->modifyExtensionField( 'flow_wiki_ref', 'ref_src_wiki',
"$dir/$dbType/patch-increase-varchar-flow_wiki_ref-ref_src_wiki.sql" );
$updater->modifyExtensionField( 'flow_ext_ref', 'ref_src_wiki',
"$dir/$dbType/patch-increase-varchar-flow_ext_ref-ref_src_wiki.sql" );
// 1.39
$updater->modifyExtensionField(
'flow_revision',
'rev_mod_timestamp',
"$dir/$dbType/patch-flow_revision-rev_mod_timestamp.sql"
);
}
$updater->addPostDatabaseUpdateMaintenance( FlowUpdateRecentChanges::class );
$updater->addPostDatabaseUpdateMaintenance( FlowSetUserIp::class );
$updater->addPostDatabaseUpdateMaintenance( FlowUpdateUserWiki::class );
$updater->addPostDatabaseUpdateMaintenance( FlowUpdateRevisionTypeId::class );
$updater->addPostDatabaseUpdateMaintenance( FlowPopulateLinksTables::class );
$updater->addPostDatabaseUpdateMaintenance( FlowFixLog::class );
$updater->addPostDatabaseUpdateMaintenance( FlowUpdateWorkflowPageId::class );
$updater->addPostDatabaseUpdateMaintenance( FlowCreateTemplates::class );
$updater->addPostDatabaseUpdateMaintenance( FlowFixLinks::class );
$updater->addPostDatabaseUpdateMaintenance( FlowUpdateBetaFeaturePreference::class );
$updater->addPostDatabaseUpdateMaintenance( FlowPopulateRefId::class );
}
/**
* Loads RecentChanges list metadata into a temporary cache for later use.
*
* @param ChangesList $changesList
* @param array $rows
*/
public static function onChangesListInitRows( ChangesList $changesList, $rows ) {
if ( !( $changesList instanceof OldChangesList || $changesList instanceof EnhancedChangesList ) ) {
return;
}
set_error_handler( new RecoverableErrorHandler, -1 );
try {
/** @var Formatter\ChangesListQuery $query */
$query = Container::get( 'query.changeslist' );
$query->loadMetadataBatch(
$rows,
$changesList->isWatchlist()
);
} catch ( Exception $e ) {
MWExceptionHandler::logException( $e );
} finally {
restore_error_handler();
}
}
/**
* Updates the given Flow topic line in an enhanced changes list (grouped RecentChanges).
*
* @param ChangesList &$changesList
* @param string &$articlelink
* @param string &$s
* @param RecentChange &$rc
* @param bool $unpatrolled
* @param bool $isWatchlist
* @return bool
*/
public static function onChangesListInsertArticleLink(
ChangesList &$changesList,
&$articlelink,
&$s,
&$rc,
$unpatrolled,
$isWatchlist
) {
if ( !( $changesList instanceof EnhancedChangesList ) ) {
// This method is only to update EnhancedChangesList.
// onOldChangesListRecentChangesLine allows updating OldChangesList,
// and supports adding wrapper classes.
return true;
}
$classes = null; // avoid pass-by-reference error
return self::processRecentChangesLine( $changesList, $articlelink, $rc, $classes, true );
}
/**
* Updates a Flow line in the old changes list (standard RecentChanges).
*
* @param ChangesList &$changesList
* @param string &$s
* @param RecentChange $rc
* @param array &$classes
* @return bool
*/
public static function onOldChangesListRecentChangesLine(
ChangesList &$changesList,
&$s,
RecentChange $rc,
&$classes = []
) {
return self::processRecentChangesLine( $changesList, $s, $rc, $classes );
}
/**
* Does the actual work for onOldChangesListRecentChangesLine and
* onChangesListInsertArticleLink hooks. Either updates an entire
* line with meta info (old changes), or simply updates the link to
* the topic (enhanced).
*
* @param ChangesList &$changesList
* @param string &$s
* @param RecentChange $rc
* @param array|null &$classes
* @param bool $topicOnly
* @return bool
*/
protected static function processRecentChangesLine(
ChangesList &$changesList,
&$s,
RecentChange $rc,
&$classes = null,
$topicOnly = false
) {
$source = $rc->getAttribute( 'rc_source' );
if ( $source === null ) {
$rcType = (int)$rc->getAttribute( 'rc_type' );
if ( $rcType !== RC_FLOW ) {
return true;
}
} elseif ( $source !== RecentChangesListener::SRC_FLOW ) {
return true;
}
set_error_handler( new RecoverableErrorHandler, -1 );
try {
/** @var Formatter\ChangesListQuery $query */
$query = Container::get( 'query.changeslist' );
$row = $query->getResult( $changesList, $rc, $changesList->isWatchlist() );
if ( $row === false ) {
restore_error_handler();
return false;
}
/** @var Formatter\ChangesListFormatter $formatter */
$formatter = Container::get( 'formatter.changeslist' );
$line = $formatter->format( $row, $changesList, $topicOnly );
} catch ( PermissionException $pe ) {
// It is expected that some rows won't be formatted because the current user
// doesn't have permission to see some of the data they contain.
return false;
} catch ( Exception $e ) {
wfDebugLog( 'Flow', __METHOD__ . ': Exception formatting rc ' .
$rc->getAttribute( 'rc_id' ) . ' ' . $e );
MWExceptionHandler::logException( $e );
return false;
} finally {
restore_error_handler();
}
if ( $line === false ) {
return false;
}
if ( is_array( $classes ) ) {
// Add the flow class to <li>
$classes[] = 'flow-recentchanges-line';
$classes[] = 'mw-changeslist-src-mw-edit';
}
// Update the line markup
$s = $line;
return true;
}
/**
* Alter the enhanced RC links: (n changes | history)
* The default diff links are incorrect!
*
* @param EnhancedChangesList $changesList
* @param array &$links
* @param RecentChange[] $block
* @return bool
*/
public static function onGetLogText( $changesList, &$links, $block ) {
$rc = $block[0];
// quit if non-flow
// FIXME: It could be that $rc is a non-Flow change (e.g. Wikidata), but $block still
// contains Flow changes. In that case we should probably process those?
if ( !self::isFlow( $rc ) ) {
return true;
}
set_error_handler( new RecoverableErrorHandler, -1 );
try {
/** @var Formatter\ChangesListQuery $query */
$query = Container::get( 'query.changeslist' );
$row = $query->getResult( $changesList, $rc, $changesList->isWatchlist() );
if ( $row === false ) {
restore_error_handler();
return false;
}
/** @var Formatter\ChangesListFormatter $formatter */
$formatter = Container::get( 'formatter.changeslist' );
$logTextLinks = $formatter->getLogTextLinks( $row, $changesList, $block, $links );
} catch ( Exception $e ) {
wfDebugLog( 'Flow', __METHOD__ . ': Exception formatting rc logtext ' .
$rc->getAttribute( 'rc_id' ) . ' ' . $e );
MWExceptionHandler::logException( $e );
return false;
} finally {
restore_error_handler();
}
if ( $logTextLinks === false ) {
return false;
}
$links = $logTextLinks;
return true;
}
/**
* @param EnhancedChangesList $changesList
* @param array &$data
* @param RecentChange[] $block
* @param RecentChange $rc
* @param string[] &$classes
* @return bool
*/
public static function onEnhancedChangesListModifyLineData( $changesList, &$data, $block, $rc, &$classes ) {
return static::modifyChangesListLine( $changesList, $data, $rc, $classes );
}
/**
* @param EnhancedChangesList $changesList
* @param array &$data
* @param RecentChange $rc
* @return bool
*/
public static function onEnhancedChangesListModifyBlockLineData( $changesList, &$data, $rc ) {
$classes = [];
return static::modifyChangesListLine( $changesList, $data, $rc, $classes );
}
/**
* @param ChangesList $changesList
* @param array &$data
* @param RecentChange $rc
* @param string[] &$classes
* @return bool
*/
private static function modifyChangesListLine( $changesList, &$data, $rc, &$classes ) {
// quit if non-flow
if ( !self::isFlow( $rc ) ) {
return true;
}
$query = Container::get( 'query.changeslist' );
$row = $query->getResult( $changesList, $rc, $changesList->isWatchlist() );
if ( $row === false ) {
return false;
}
/** @var Formatter\ChangesListFormatter $formatter */
$formatter = Container::get( 'formatter.changeslist' );
try {
$data['timestampLink'] = $formatter->getTimestampLink( $row, $changesList );
$data['recentChangesFlags'] = array_merge(
$data['recentChangesFlags'],
$formatter->getFlags( $row, $changesList )
);
$classes[] = 'mw-changeslist-src-mw-edit';
} catch ( PermissionException $e ) {
return false;
}
return true;
}
/**
* Checks if the given recent change entry is from Flow
* @param RecentChange $rc
* @return bool
*/
private static function isFlow( $rc ) {
$source = $rc->getAttribute( 'rc_source' );
if ( $source === null ) {
$rcType = (int)$rc->getAttribute( 'rc_type' );
return $rcType === RC_FLOW;
} else {
return $source === RecentChangesListener::SRC_FLOW;
}
}
public static function onSpecialCheckUserGetLinksFromRow( AbstractCheckUserPager $pager, $row, &$links ) {
if ( $row->cuc_type != RC_FLOW ) {
return;
}
$replacement = self::getReplacementRowItems( $pager->getContext(), $row );
if ( $replacement === null ) {
// some sort of failure, but this is a RC_FLOW so blank out hist/diff links
// which aren't correct
$links['history'] = '';
$links['diff'] = '';
} else {
$links = $replacement;
}
}
public static function onCheckUserFormatRow( IContextSource $context, $row, &$rowItems ) {
if ( $row->cuc_type != RC_FLOW ) {
return;
}
$replacement = self::getReplacementRowItems( $context, $row );
// These links are incorrect for Flow
$rowItems['links']['diffLink'] = '';
$rowItems['links']['historyLink'] = '';
if ( $replacement !== null ) {
array_unshift( $rowItems['links'], $replacement['links'] );
$rowItems['info']['titleLink'] = $replacement['title'];
}
}
/**
* @param IContextSource $context
* @param stdClass $row
* @return array|null
*/
private static function getReplacementRowItems( IContextSource $context, $row ): ?array {
set_error_handler( new RecoverableErrorHandler, -1 );
$replacement = null;
try {
/** @var CheckUserQuery $query */
$query = Container::get( 'query.checkuser' );
// @todo: create hook to allow batch-loading this data, instead of doing piecemeal like this
$query->loadMetadataBatch( [ $row ] );
$row = $query->getResult( $row );
if ( $row !== false ) {
/** @var Formatter\CheckUserFormatter $formatter */
$formatter = Container::get( 'formatter.checkuser' );
$replacement = $formatter->format( $row, $context );
}
} catch ( Exception $e ) {
wfDebugLog( 'Flow', __METHOD__ . ': Exception formatting cu ' . json_encode( $row ) . ' ' . $e );
MWExceptionHandler::logException( $e );
} finally {
restore_error_handler();
}
return $replacement;
}
/**
* Regular talk page "Create source" and "Add topic" links are quite useless
* in the context of Flow boards. Let's get rid of them.
*
* @param SkinTemplate &$template
* @param array &$links
*/
public static function onSkinTemplateNavigation( SkinTemplate &$template, &$links ) {
global $wgFlowCoreActionWhitelist,
$wgMFPageActions;
$title = $template->getTitle();
// if Flow is enabled on this talk page, overrule talk page red link
if ( $title->getContentModel() === CONTENT_MODEL_FLOW_BOARD ) {
// Turn off page actions in MobileFrontend.
// FIXME: Find more elegant standard way of doing this.
$wgMFPageActions = [];
// watch star & delete links are inside the topic itself
if ( $title->getNamespace() === NS_TOPIC ) {
unset( $links['actions']['watch'] );
unset( $links['actions']['unwatch'] );
unset( $links['actions']['delete'] );
}
// hide all views unless whitelisted
foreach ( $links['views'] as $action => $data ) {
if ( !in_array( $action, $wgFlowCoreActionWhitelist ) ) {
unset( $links['views'][$action] );
}
}
// hide all actions unless whitelisted
foreach ( $links['actions'] as $action => $data ) {
if ( !in_array( $action, $wgFlowCoreActionWhitelist ) ) {
unset( $links['actions'][$action] );
}
}
if ( isset( $links['namespaces']['topic_talk'] ) ) {
// hide discussion page in Topic namespace(which is already discussion)
unset( $links['namespaces']['topic_talk'] );
// hide protection (topic protection is done via moderation)
unset( $links['actions']['protect'] );
// topic pages are also not movable
unset( $links['actions']['move'] );
}
}
}
/**
* When a (talk) page does not exist, one of the checks being performed is
* to see if the page had once existed but was removed. In doing so, the
* deletion & move log is checked.
*
* In theory, a Flow board could overtake a non-existing talk page. If that
* board is later removed, this will be run to see if a message can be
* displayed to inform the user if the page has been deleted/moved.
*
* Since, in Flow, we also write (topic, post, ...) deletion to the deletion
* log, we don't want those to appear, since they're not actually actions
* related to that talk page (rather: they were actions on the board)
*
* @param array &$conds Array of conditions
* @param array $logTypes Array of log types
*/
public static function onMissingArticleConditions( array &$conds, array $logTypes ) {
global $wgLogActionsHandlers;
/** @var FlowActions $actions */
$actions = Container::get( 'flow_actions' );
foreach ( $actions->getActions() as $action ) {
foreach ( $logTypes as $logType ) {
// Check if Flow actions are defined for the requested log types
// and make sure they're ignored.
if ( isset( $wgLogActionsHandlers["$logType/flow-$action"] ) ) {
$conds[] = "log_action != " . wfGetDB( DB_REPLICA )->addQuotes( "flow-$action" );
}
}
}
}
/**
* Adds Flow entries to watchlists
*
* @param array &$types Type array to modify
*/
public static function onSpecialWatchlistGetNonRevisionTypes( &$types ) {
$types[] = RC_FLOW;
}
/**
* Make sure no user can register a flow-*-usertext username, to avoid
* confusion with a real user when we print e.g. "Suppressed" instead of a
* username. Additionally reserve the username used to add a revision on
* taking over a page.
*
* @param array &$names
*/
public static function onUserGetReservedNames( &$names ) {
$permissions = Model\AbstractRevision::$perms;
foreach ( $permissions as $permission ) {
$names[] = "msg:flow-$permission-usertext";
}
$names[] = 'msg:flow-system-usertext';
// Reserve the bot account we use during content model changes & LQT conversion
$names[] = FLOW_TALK_PAGE_MANAGER_USER;
}
/**
* Static variables that do not vary by request; delivered through startup module
* @param array &$vars
*/
public static function onResourceLoaderGetConfigVars( &$vars ) {
global $wgFlowAjaxTimeout;
$vars['wgFlowMaxTopicLength'] = Model\PostRevision::MAX_TOPIC_LENGTH;
$vars['wgFlowMentionTemplate'] = wfMessage( 'flow-ve-mention-template-title' )->inContentLanguage()->plain();
$vars['wgFlowAjaxTimeout'] = $wgFlowAjaxTimeout;
}
/**
* Intercept contribution entries and format those belonging to Flow
*
* @param IContextSource $pager
* @param string &$ret The HTML line
* @param stdClass $row The data for this line
* @param array &$classes the classes to add to the surrounding <li>
* @return bool
*/
public static function onDeletedContributionsLineEnding( $pager, &$ret, $row, &$classes ) {
if ( !$row instanceof Formatter\FormatterRow ) {
return true;
}
set_error_handler( new RecoverableErrorHandler, -1 );
try {
/** @var Formatter\ContributionsFormatter $formatter */
$formatter = Container::get( 'formatter.contributions' );
$line = $formatter->format( $row, $pager );
} catch ( Exception $e ) {
wfDebugLog( 'Flow', __METHOD__ . ': Failed formatting contribution ' .
json_encode( $row ) . ': ' . $e->getMessage() );
MWExceptionHandler::logException( $e );
$line = false;
} finally {
restore_error_handler();
}
if ( $line === false ) {
return false;
}
$classes[] = 'mw-flow-contribution';
$ret = $line;
// If we output one or more lines of contributions entries we also need to include
// the javascript that hooks into moderation actions.
$pager->getOutput()->addModules( [ 'ext.flow.contributions' ] );
$pager->getOutput()->addModuleStyles( [ 'ext.flow.contributions.styles' ] );
return true;
}
/**
* Intercept contribution entries and format those belonging to Flow
*
* @param IContextSource $pager
* @param string &$ret The HTML line
* @param stdClass $row The data for this line
* @param array &$classes the classes to add to the surrounding <li>
* @return bool
*/
public static function onContributionsLineEnding( $pager, &$ret, $row, &$classes ) {
return static::onDeletedContributionsLineEnding( $pager, $ret, $row, $classes );
}
/**
* Convert flow contributions entries into FeedItem instances
* for ApiFeedContributions
*
* @param object $row Single row of data from ContribsPager
* @param IContextSource $ctx The context to creat the feed item within
* @param FeedItem|null &$feedItem Return value holder for created feed item.
* @return bool
*/
public static function onContributionsFeedItem( $row, IContextSource $ctx, FeedItem &$feedItem = null ) {
if ( !$row instanceof Formatter\FormatterRow ) {
return true;
}
set_error_handler( new RecoverableErrorHandler, -1 );
try {
/** @var Formatter\FeedItemFormatter $formatter */
$formatter = Container::get( 'formatter.contributions.feeditem' );
$result = $formatter->format( $row, $ctx );
} catch ( Exception $e ) {
wfDebugLog( 'Flow', __METHOD__ . ': Failed formatting contribution ' .
json_encode( $row ) . ': ' . $e->getMessage() );
MWExceptionHandler::logException( $e );
return false;
} finally {
restore_error_handler();
}
if ( $result instanceof FeedItem ) {
$feedItem = $result;
return true;
} else {
// If we failed to render a flow row, cancel it. This could be
// either permissions or bugs.
return false;
}
}
/**
* Adds Flow contributions to the DeletedContributions special page
*
* @param array &$data an array of results of all contribs queries, to be
* merged to form all contributions data
* @param ContribsPager|DeletedContribsPager $pager Object hooked into
* @param string $offset Index offset, inclusive
* @param int $limit Exact query limit
* @param bool $descending Query direction, false for ascending, true for descending
* @return bool
*/
public static function onDeletedContributionsQuery( &$data, $pager, $offset, $limit, $descending ) {
set_error_handler( new RecoverableErrorHandler, -1 );
try {
/** @var Formatter\ContributionsQuery $query */
$query = Container::get( 'query.contributions' );
$results = $query->getResults( $pager, $offset, $limit, $descending );
} catch ( Exception $e ) {
wfDebugLog( 'Flow', __METHOD__ . ': Failed contributions query' );
MWExceptionHandler::logException( $e );
$results = false;
} finally {
restore_error_handler();
}
if ( $results === false ) {
return false;
}
$data[] = $results;
return true;
}
/**
* Adds Flow contributions to the Contributions special page
*
* @param array &$data an array of results of all contribs queries, to be
* merged to form all contributions data
* @param ContribsPager $pager Object hooked into
* @param string $offset Index offset, inclusive
* @param int $limit Exact query limit
* @param bool $descending Query direction, false for ascending, true for descending
* @return bool
*/
public static function onContributionsQuery( &$data, $pager, $offset, $limit, $descending ) {
// Flow has nothing to do with the tag filter, so ignore tag searches
if ( $pager->getTagFilter() != false ) {
return true;
}
return static::onDeletedContributionsQuery( $data, $pager, $offset, $limit, $descending );
}
/**
* Define and add descriptions for board-related variables
* @param array &$realValues
*/
public static function onAbuseFilterBuilder( &$realValues ) {
$realValues['vars'] += [
'board_id' => 'board-id',
'board_namespace' => 'board-namespace',
'board_title' => 'board-title',
'board_prefixedtitle' => 'board-prefixedtitle',
];
}
/**
* Add our deprecated variables
* @param array &$deprecatedVars
*/
public static function onAbuseFilterDeprecatedVariables( &$deprecatedVars ) {
$deprecatedVars += [
'board_articleid' => 'board_id',
'board_text' => 'board_title',
'board_prefixedtext' => 'board_prefixedtitle',
];
}
/**
* Adds lazy-load methods for AbstractRevision objects.
*
* @param string $method Method to generate the variable
* @param VariableHolder $vars
* @param array $parameters Parameters with data to compute the value
* @param mixed &$result Result of the computation
* @return bool
*/
public static function onAbuseFilterComputeVariable(
$method,
VariableHolder $vars,
$parameters,
&$result
) {
// fetch all lazy-load methods
$methods = self::$abuseFilter->lazyLoadMethods();
// method isn't known here
if ( !isset( $methods[$method] ) ) {
return true;
}
// fetch variable result from lazy-load method
$result = $methods[$method]( $vars, $parameters );
return false;
}
/**
* Abort notifications regarding occupied pages coming from the RecentChange class.
* Flow has its own notifications through Echo.
*
* Also don't notify for actions made by the talk page manager.
*
* @param User $editor
* @param Title $title
* @return bool false to abort email notification
*/
public static function onAbortEmailNotification( $editor, $title ) {
if ( $title->getContentModel() === CONTENT_MODEL_FLOW_BOARD ) {
// Since we are aborting the notification we need to manually update the watchlist
$config = RequestContext::getMain()->getConfig();
if ( $config->get( 'EnotifWatchlist' ) || $config->get( 'ShowUpdatedMarker' ) ) {
MediaWikiServices::getInstance()->getWatchedItemStore()->updateNotificationTimestamp(
$editor,
$title,
wfTimestampNow()
);
}
return false;
}
if ( !$editor instanceof UserIdentity ) {
return true;
}
if ( self::isTalkpageManagerUser( $editor ) ) {
return false;
}
return true;
}
/**
* Suppress all Echo notifications generated by the Talk page manager user
*
* @param EchoEvent $event
* @return bool
*/
public static function onBeforeEchoEventInsert( EchoEvent $event ) {
$agent = $event->getAgent();
if ( $agent === null ) {
return true;
}
if ( self::isTalkpageManagerUser( $agent ) ) {
return false;
}
return true;
}
/**
* Suppress the 'You have new messages!' indication when a change to a
* user talk page is done by the talk page manager user.
*
* @param WikiPage $page
* @param User $recipient
* @return bool
*/
public static function onArticleEditUpdateNewTalk( WikiPage $page, User $recipient ) {
$user = User::newFromId( $page->getUser( RevisionRecord::RAW ) );
if ( self::isTalkpageManagerUser( $user ) ) {
return false;
}
return true;
}
/**
* @param UserIdentity $user
* @return bool
*/
private static function isTalkpageManagerUser( UserIdentity $user ) {
return $user->getName() === FLOW_TALK_PAGE_MANAGER_USER;
}
/**
* Don't send email notifications that are imported from LiquidThreads. It will
* still be in their web notifications (if enabled), but they will never be
* notified via email (regardless of batching settings) for this particular
* notification.
* @param User $user
* @param EchoEvent $event
* @return bool
*/
public static function onEchoAbortEmailNotification( User $user, EchoEvent $event ) {
$extra = $event->getExtra();
return !isset( $extra['lqtThreadId'] );
}
/**
* Hides the orange alert indicating 'You have a new message'