/
Banner.php
1507 lines (1307 loc) · 39.6 KB
/
Banner.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
/**
* This file is part of the CentralNotice Extension to MediaWiki
* https://www.mediawiki.org/wiki/Extension:CentralNotice
*
* @section LICENSE
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
*/
/**
* CentralNotice banner object. Banners are pieces of rendered wikimarkup
* injected as HTML onto MediaWiki pages via the sitenotice hook.
*
* - They are allowed to be specific to devices and user status.
* - They allow 'mixins', pieces of javascript that add additional standard
* functionality to the banner.
* - They have a concept of 'messages' which are translatable strings marked
* out by {{{name}}} in the banner body.
*
* @see BannerMessage
* @see BannerRenderer
* @see BannerMixin
*/
class Banner {
/**
* Keys indicate a group of properties (which should be a 1-to-1 match to
* a database table.) If the value is null it means the data is not yet
* loaded. True means the data is clean and not modified. False means the
* data should be saved on the next call to save().
*
* Most functions should only ever set the flag to true; flags will be
* reset to false in save().
*
* @var null|bool[]
*/
protected $dirtyFlags = [
'content' => null,
'messages' => null,
'basic' => null,
'devices' => null,
'mixins' => null,
'prioritylang' => null,
];
// <editor-fold desc="Properties">
// !!! NOTE !!! It is not recommended to use directly. It is almost always more
// correct to use the accessor/setter function.
/** @var int Unique database identifier key. */
protected $id = null;
/** @var string Unique human friendly name of banner. */
protected $name = null;
/** @var bool True if the banner should be allocated to anonymous users. */
protected $allocateAnon = false;
/** @var bool True if the banner should be allocated to logged in users. */
protected $allocateLoggedIn = false;
/** @var string Category that the banner belongs to. Will be special value expanded. */
protected $category = '{{{campaign}}}';
/** @var bool True if archived and hidden from default view. */
protected $archived = false;
/** @var string[] Devices this banner should be allocated to in the form
* {Device ID => Device header name} */
protected $devices = [];
/** @var string[] Names of enabled mixins */
protected $mixins = [];
/** @var string[] Language codes considered a priority for translation. */
protected $priorityLanguages = [];
/** @var string Wikitext content of the banner */
protected $bodyContent = '';
protected $runTranslateJob = false;
// </editor-fold>
// <editor-fold desc="Constructors">
/**
* Create a banner object from a known ID. Must already be
* an object in the database. If a fully new banner is to be created
* use @see newFromName().
*
* @param int $id Unique database ID of the banner
*
* @return Banner
*/
public static function fromId( $id ) {
$obj = new Banner();
$obj->id = $id;
return $obj;
}
/**
* Create a banner object from a known banner name. Must already be
* an object in the database. If a fully new banner is to be created
* use @see newFromName().
*
* @param $name
*
* @return Banner
* @throws BannerDataException
*/
public static function fromName( $name ) {
if ( !Banner::isValidBannerName( $name ) ) {
throw new BannerDataException( "Invalid banner name supplied." );
}
$obj = new Banner();
$obj->name = $name;
return $obj;
}
/**
* Create a brand new banner object.
*
* @param $name
*
* @return Banner
* @throws BannerDataException
*/
public static function newFromName( $name ) {
if ( !Banner::isValidBannerName( $name ) ) {
throw new BannerDataException( "Invalid banner name supplied." );
}
$obj = new Banner();
$obj->name = $name;
foreach ( $obj->dirtyFlags as $flag => &$value ) {
$value = true;
}
return $obj;
}
// </editor-fold>
// <editor-fold desc="Basic metadata getters/setters">
/**
* Get the unique ID for this banner.
*
* @return int
*/
public function getId() {
$this->populateBasicData();
return $this->id;
}
/**
* Get the unique name for this banner.
*
* This specifically does not include namespace or other prefixing.
*
* @return null|string
*/
public function getName() {
$this->populateBasicData();
return $this->name;
}
/**
* Should we allocate this banner to anonymous users.
*
* @return bool
*/
public function allocateToAnon() {
$this->populateBasicData();
return $this->allocateAnon;
}
/**
* Should we allocate this banner to logged in users.
*
* @return bool
*/
public function allocateToLoggedIn() {
$this->populateBasicData();
return $this->allocateLoggedIn;
}
/**
* Set user state allocation properties for this banner
*
* @param bool $anon Should the banner be allocated to logged out users.
* @param bool $loggedIn Should the banner be allocated to logged in users.
*
* @return $this
*/
public function setAllocation( $anon, $loggedIn ) {
$this->populateBasicData();
if ( ( $this->allocateAnon !== $anon ) || ( $this->allocateLoggedIn !== $loggedIn ) ) {
$this->setBasicDataDirty();
$this->allocateAnon = $anon;
$this->allocateLoggedIn = $loggedIn;
}
return $this;
}
/**
* Get the banner category.
*
* The category is the name of the cookie stored on the users computer. In this way
* banners in the same category may share settings.
*
* @return string
*/
public function getCategory() {
$this->populateBasicData();
return $this->category;
}
/**
* Set the banner category.
*
* @see Banner->getCategory()
*
* @param string $value
*
* @return $this
*/
public function setCategory( $value ) {
$this->populateBasicData();
if ( $this->category !== $value ) {
$this->setBasicDataDirty();
$this->category = $value;
}
return $this;
}
/**
* Obtain an array of all categories currently seen attached to banners
* @return string[]
*/
public static function getAllUsedCategories() {
$db = CNDatabase::getDb();
$res = $db->select(
'cn_templates',
'tmp_category',
'',
__METHOD__,
[ 'DISTINCT', 'ORDER BY tmp_category ASC' ]
);
$categories = [];
foreach ( $res as $row ) {
$categories[$row->tmp_category] = $row->tmp_category;
}
return $categories;
}
/**
* Remove invalid characters from a category string that has been magic
* word expanded.
*
* @param string $cat Category string to sanitize
*
* @return string
*/
public static function sanitizeRenderedCategory( $cat ) {
return preg_replace( '/[^a-zA-Z0-9_]/', '', $cat );
}
/**
* Should the banner be considered archived and hidden from default view
*
* @return bool
*/
public function isArchived() {
$this->populateBasicData();
return $this->archived;
}
/**
* Populates basic banner data by querying the cn_templates table
*
* @throws BannerDataException If neither a name or ID can be used to query for data
* @throws BannerExistenceException If no banner data was received
*/
protected function populateBasicData() {
if ( $this->dirtyFlags['basic'] !== null ) {
return;
}
$db = CNDatabase::getDb();
// What are we using to select on?
if ( $this->name !== null ) {
$selector = [ 'tmp_name' => $this->name ];
} elseif ( $this->id !== null ) {
$selector = [ 'tmp_id' => $this->id ];
} else {
throw new BannerDataException( 'Cannot retrieve banner data without name or ID.' );
}
// Query!
$rowRes = $db->select(
[ 'templates' => 'cn_templates' ],
[
'tmp_id',
'tmp_name',
'tmp_display_anon',
'tmp_display_account',
'tmp_archived',
'tmp_category'
],
$selector,
__METHOD__
);
// Extract the dataz!
$row = $db->fetchObject( $rowRes );
if ( $row ) {
$this->id = (int)$row->tmp_id;
$this->name = $row->tmp_name;
$this->allocateAnon = (bool)$row->tmp_display_anon;
$this->allocateLoggedIn = (bool)$row->tmp_display_account;
$this->archived = (bool)$row->tmp_archived;
$this->category = $row->tmp_category;
} else {
$keystr = [];
foreach ( $selector as $key => $value ) {
$keystr[] = "{$key} = {$value}";
}
$keystr = implode( " AND ", $keystr );
throw new BannerExistenceException(
"No banner exists where {$keystr}. Could not load."
);
}
// Set the dirty flag to not dirty because we just loaded clean data
$this->setBasicDataDirty( false );
}
/**
* Sets the flag which will save basic metadata on next save()
*/
protected function setBasicDataDirty( $dirty = true ) {
$this->dirtyFlags['basic'] = $dirty;
}
/**
* Helper function to initializeDbForNewBanner()
*
* @param IDatabase $db
*/
protected function initializeDbBasicData( IDatabase $db ) {
$db->insert( 'cn_templates', [ 'tmp_name' => $this->name ], __METHOD__ );
$this->id = $db->insertId();
}
/**
* Helper function to saveBannerInternal() for saving basic banner metadata
* @param IDatabase $db
*/
protected function saveBasicData( IDatabase $db ) {
if ( $this->dirtyFlags['basic'] ) {
$db->update( 'cn_templates',
[
'tmp_display_anon' => (int)$this->allocateAnon,
'tmp_display_account' => (int)$this->allocateLoggedIn,
'tmp_archived' => (int)$this->archived,
'tmp_category' => $this->category,
],
[
'tmp_id' => $this->id
],
__METHOD__
);
}
}
// </editor-fold>
// <editor-fold desc="Device targeting">
/**
* Get the devices that this banner should be allocated to.
*
* Array is in the form of {Device internal ID => Device header name}
*
* @return string[]
*/
public function getDevices() {
$this->populateDeviceTargetData();
return $this->devices;
}
/**
* Set the devices that this banner should be allocated to.
*
* @param string[]|string $devices Header name of devices. E.g. {'android', 'desktop'}
*
* @return $this
* @throws BannerDataException on unknown device header name.
*/
public function setDevices( $devices ) {
$this->populateDeviceTargetData();
$knownDevices = CNDeviceTarget::getAvailableDevices( true );
$devices = (array)$devices;
$devices = array_unique( array_values( $devices ) );
sort( $devices );
if ( $devices != $this->devices ) {
$this->devices = [];
foreach ( $devices as $device ) {
if ( !$device ) {
// Empty...
continue;
} elseif ( !array_key_exists( $device, $knownDevices ) ) {
throw new BannerDataException( "Device name '$device' not known! Cannot add." );
} else {
$this->devices[$knownDevices[$device]['id']] = $device;
}
}
$this->markDeviceTargetDataDirty();
}
return $this;
}
/**
* Populates device targeting data by querying the cn_template_devices table.
*
* @see CNDeviceTarget for more information about mapping.
*/
protected function populateDeviceTargetData() {
if ( $this->dirtyFlags['devices'] !== null ) {
return;
}
$db = CNDatabase::getDb();
$rowObj = $db->select(
[
'tdev' => 'cn_template_devices',
'devices' => 'cn_known_devices'
],
[ 'devices.dev_id', 'dev_name' ],
[
'tdev.tmp_id' => $this->getId(),
'tdev.dev_id = devices.dev_id'
],
__METHOD__
);
foreach ( $rowObj as $row ) {
$this->devices[ intval( $row->dev_id ) ] = $row->dev_name;
}
$this->markDeviceTargetDataDirty( false );
}
/**
* Sets the flag which will force saving of device targeting data on next save()
*/
protected function markDeviceTargetDataDirty( $dirty = true ) {
$this->dirtyFlags['devices'] = $dirty;
}
/**
* Helper function to saveBannerInternal()
*
* @param IDatabase $db
*/
protected function saveDeviceTargetData( IDatabase $db ) {
if ( $this->dirtyFlags['devices'] ) {
// Remove all entries from the table for this banner
$db->delete( 'cn_template_devices', [ 'tmp_id' => $this->getId() ], __METHOD__ );
// Add the new device mappings
if ( $this->devices ) {
$modifyArray = [];
foreach ( $this->devices as $deviceId => $deviceName ) {
$modifyArray[] = [ 'tmp_id' => $this->getId(), 'dev_id' => $deviceId ];
}
$db->insert( 'cn_template_devices', $modifyArray, __METHOD__ );
}
}
}
// </editor-fold>
// <editor-fold desc="Mixin management">
/**
* @return array Keys are names of enabled mixins; valeus are mixin params.
* @see $wgCentralNoticeBannerMixins
*/
public function getMixins() {
$this->populateMixinData();
return $this->mixins;
}
/**
* Set the banner mixins to enable.
*
* @param array $mixins Names of mixins to enable on this banner. Valid values
* come from @see $wgCentralNoticeBannerMixins
*
* @throws RangeException
* @return $this
*/
function setMixins( $mixins ) {
global $wgCentralNoticeBannerMixins;
$this->populateMixinData();
$mixins = array_unique( $mixins );
sort( $mixins );
if ( $this->mixins != $mixins ) {
$this->markMixinDataDirty();
}
$this->mixins = [];
foreach ( $mixins as $mixin ) {
if ( !array_key_exists( $mixin, $wgCentralNoticeBannerMixins ) ) {
throw new RangeException( "Mixin does not exist: {$mixin}" );
}
$this->mixins[$mixin] = $wgCentralNoticeBannerMixins[$mixin];
}
return $this;
}
/**
* Populates mixin data from the cn_template_mixins table.
*/
protected function populateMixinData() {
global $wgCentralNoticeBannerMixins;
if ( $this->dirtyFlags['mixins'] !== null ) {
return;
}
$dbr = CNDatabase::getDb();
$result = $dbr->select( 'cn_template_mixins', 'mixin_name',
[
"tmp_id" => $this->getId(),
],
__METHOD__
);
$this->mixins = [];
foreach ( $result as $row ) {
if ( !array_key_exists( $row->mixin_name, $wgCentralNoticeBannerMixins ) ) {
// We only want to warn here otherwise we'd never be able to
// edit the banner to fix the issue! The editor should warn
// when a deprecated mixin is being used; but also when we
// do deprecate something we should make sure nothing is using
// it!
wfLogWarning(
"Mixin does not exist: {$row->mixin_name}, included from banner {$this->name}"
);
}
$this->mixins[$row->mixin_name] = $wgCentralNoticeBannerMixins[$row->mixin_name];
}
$this->markMixinDataDirty( false );
}
/**
* Sets the flag which will force saving of mixin data upon next save()
*/
protected function markMixinDataDirty( $dirty = true ) {
$this->dirtyFlags['mixins'] = $dirty;
}
/**
* @param IDatabase $db
*/
protected function saveMixinData( IDatabase $db ) {
if ( $this->dirtyFlags['mixins'] ) {
$db->delete( 'cn_template_mixins',
[ 'tmp_id' => $this->getId() ],
__METHOD__
);
foreach ( $this->mixins as $name => $params ) {
$name = trim( $name );
if ( !$name ) {
continue;
}
$db->insert( 'cn_template_mixins',
[
'tmp_id' => $this->getId(),
'page_id' => 0, // TODO: What were we going to use this for again?
'mixin_name' => $name,
],
__METHOD__
);
}
}
}
// </editor-fold>
// <editor-fold desc="Priority languages">
/**
* Returns language codes that are considered a priority for translations.
*
* If a language is in this list it means that the translation UI will promote
* translating them, and discourage translating other languages.
*
* @return string[]
*/
public function getPriorityLanguages() {
$this->populatePriorityLanguageData();
return $this->priorityLanguages;
}
/**
* Set language codes that should be considered a priority for translation.
*
* If a language is in this list it means that the translation UI will promote
* translating them, and discourage translating other languages.
*
* @param string[] $languageCodes
*
* @return $this
*/
public function setPriorityLanguages( $languageCodes ) {
$this->populatePriorityLanguageData();
$languageCodes = array_unique( (array)$languageCodes );
sort( $languageCodes );
if ( $this->priorityLanguages != $languageCodes ) {
$this->priorityLanguages = $languageCodes;
$this->markPriorityLanguageDataDirty();
}
return $this;
}
protected function populatePriorityLanguageData() {
global $wgNoticeUseTranslateExtension;
if ( $this->dirtyFlags['prioritylang'] !== null ) {
return;
}
if ( $wgNoticeUseTranslateExtension ) {
$langs = TranslateMetadata::get(
BannerMessageGroup::getTranslateGroupName( $this->getName() ),
'prioritylangs'
);
if ( !$langs ) {
// If priority langs is not set; TranslateMetadata::get will return false
$langs = '';
}
$this->priorityLanguages = explode( ',', $langs );
}
$this->markPriorityLanguageDataDirty( false );
}
protected function markPriorityLanguageDataDirty( $dirty = true ) {
$this->dirtyFlags['prioritylang'] = $dirty;
}
protected function savePriorityLanguageData() {
global $wgNoticeUseTranslateExtension;
if ( $wgNoticeUseTranslateExtension && $this->dirtyFlags['prioritylang'] ) {
TranslateMetadata::set(
BannerMessageGroup::getTranslateGroupName( $this->getName() ),
'prioritylangs',
implode( ',', $this->priorityLanguages )
);
}
}
// </editor-fold>
// <editor-fold desc="Banner body content">
public function getDbKey() {
$name = $this->getName();
return "Centralnotice-template-{$name}";
}
public function getTitle() {
return Title::newFromText( $this->getDbKey(), NS_MEDIAWIKI );
}
/**
* Return the names of campaigns that this banner is currently used in.
*
* @return string[]
*/
public function getCampaignNames() {
$dbr = CNDatabase::getDb();
$result = $dbr->select(
[
'notices' => 'cn_notices',
'assignments' => 'cn_assignments',
],
'notices.not_name',
[
'assignments.tmp_id' => $this->getId(),
],
__METHOD__,
[],
[
'assignments' =>
[
'INNER JOIN', 'notices.not_id = assignments.not_id'
]
]
);
$campaigns = [];
foreach ( $result as $row ) {
$campaigns[] = $row->not_name;
}
return $campaigns;
}
/**
* Returns an array of Title objects that have been included as templates
* in this banner.
*
* @return array of Title
*/
public function getIncludedTemplates() {
return $this->getTitle()->getTemplateLinksFrom();
}
/**
* Get the raw body HTML for the banner.
*
* @return string HTML
*/
public function getBodyContent() {
$this->populateBodyContent();
return $this->bodyContent;
}
/**
* Set the raw body HTML for the banner.
*
* @param string $text HTML
*
* @return $this
*/
public function setBodyContent( $text ) {
$this->populateBodyContent();
if ( $this->bodyContent !== $text ) {
$this->bodyContent = $text;
$this->markBodyContentDirty();
}
return $this;
}
protected function populateBodyContent() {
if ( $this->dirtyFlags['content'] !== null ) {
return;
}
$bodyPage = $this->getTitle();
$curRev = Revision::newFromTitle( $bodyPage );
if ( !$curRev ) {
throw new BannerContentException( "No content for banner: {$this->name}" );
}
$this->bodyContent = ContentHandler::getContentText( $curRev->getContent() );
$this->markBodyContentDirty( false );
}
/**
* @param boolean $dirty If true, we're storing a flag that means the
* in-memory banner content is newer than what's stored in the database.
* If false, we're clearing that bit.
*/
protected function markBodyContentDirty( $dirty = true ) {
$this->dirtyFlags['content'] = $dirty;
}
protected function saveBodyContent( $summary = null ) {
global $wgNoticeUseTranslateExtension;
if ( $this->dirtyFlags['content'] ) {
$wikiPage = new WikiPage( $this->getTitle() );
if ( $summary === null ) {
$summary = '';
}
$contentObj = ContentHandler::makeContent( $this->bodyContent, $wikiPage->getTitle() );
$pageResult =
$wikiPage->doEditContent( $contentObj, $summary, EDIT_FORCE_BOT );
if ( $wgNoticeUseTranslateExtension ) {
// Get the revision and page ID of the page that was created/modified
if ( $pageResult->value['revision'] ) {
$revision = $pageResult->value['revision'];
$revisionId = $revision->getId();
$pageId = $revision->getPage();
// If the banner includes translatable messages, tag it for translation
$fields = $this->extractMessageFields();
if ( count( $fields ) > 0 ) {
// Tag the banner for translation
Banner::addTag( 'banner:translate', $revisionId, $pageId, $this->getId() );
$this->runTranslateJob = true;
}
}
}
}
}
// </editor-fold>
// <editor-fold desc="Banner message fields">
function getMessageField( $field_name ) {
return new BannerMessage( $this->getName(), $field_name );
}
/**
* Returns all the message fields in a banner
*
* Check the cache first, then calculate if necessary. Will always prefer the cache.
* @see Banner::extractMessageFields()
*
* @return array
*/
public function getMessageFieldsFromCache() {
$data = ObjectCache::getMainStashInstance()
->get( $this->getMessageFieldsCacheKey() );
if ( $data !== false ) {
$data = json_decode( $data, true );
} else {
$data = $this->extractMessageFields();
}
return $data;
}
protected function getMessageFieldsCacheKey() {
return ObjectCache::getMainStashInstance()
->makeKey( 'centralnotice', 'bannerfields', $this->getName() );
}
/**
* Extract the raw fields and field names from the banner body source.
*
* Always recalculate. If you want the cached value, please use getMessageFieldsFromCache.
*
* @return array
*/
public function extractMessageFields() {
global $wgParser;
$expanded = $wgParser->parse(
$this->getBodyContent(), $this->getTitle(),
ParserOptions::newFromContext( RequestContext::getMain() )
)->getText();
// Also search the preload js for fields.
$renderer = new BannerRenderer( RequestContext::getMain(), $this );
$expanded .= $renderer->getPreloadJsRaw();
// Extract message fields from the banner body
$fields = [];
$allowedChars = Title::legalChars();
// We're using a janky custom syntax to pass arguments to a field message:
// "{{{fieldname:arg1|arg2}}}"
$allowedChars = str_replace( ':', '', $allowedChars );
preg_match_all( "/{{{([$allowedChars]+)(:[^}]*)?}}}/u", $expanded, $fields );
// Remove duplicate keys and count occurrences
$unique_fields = array_unique( array_flip( $fields[1] ) );
$fields = array_intersect_key( array_count_values( $fields[1] ), $unique_fields );
$fields = array_diff_key( $fields, array_flip( $renderer->getMagicWords() ) );
// Save in the cache.
ObjectCache::getMainStashInstance()
->set( $this->getMessageFieldsCacheKey(), json_encode( $fields ) );
return $fields;
}
/**
* Returns a list of messages that are either published or in the CNBanner translation
*
* @param bool $inTranslation If true and using group translation this will return
* all the messages that are in the translation system
*
* @return array A list of languages with existing field translations
*/
function getAvailableLanguages( $inTranslation = false ) {
global $wgLanguageCode;
$availableLangs = [];
// Bit of an ugly hack to get just the banner prefix
$prefix = $this->getMessageField( '' )
->getDbKey( null, $inTranslation ? NS_CN_BANNER : NS_MEDIAWIKI );
$db = CNDatabase::getDb();
$result = $db->select( 'page',
'page_title',
[
'page_namespace' => $inTranslation ? NS_CN_BANNER : NS_MEDIAWIKI,
'page_title' . $db->buildLike( $prefix, $db->anyString() ),
],
__METHOD__
);
foreach ( $result as $row ) {
if (
preg_match(
"/\Q{$prefix}\E([^\/]+)(?:\/([a-z_]+))?/", $row->page_title,
$matches
)
) {
if ( isset( $matches[2] ) ) {
$lang = $matches[2];
} else {
$lang = $wgLanguageCode;
}
$availableLangs[$lang] = true;
}
}
return array_keys( $availableLangs );
}
// </editor-fold>
// <editor-fold desc="Banner actions">
// <editor-fold desc="Saving">
/**
* Saves any changes made to the banner object into the database
*
* @param User $user
* @param string $summary Summary (comment) to associate with all changes,
* including banner content and messages (which are implemented as wiki
* pages).
*
* @return $this
* @throws Exception
*/
public function save( $user = null, $summary = null ) {
global $wgUser;
$db = CNDatabase::getDb();
$action = 'modified';
if ( $user === null ) {
$user = $wgUser;
}
try {
// Don't move this to saveBannerInternal--can't be in a transaction
// TODO: explain why not. Is text in another database?
$this->saveBodyContent( $summary );
// Open a transaction so that everything is consistent
$db->startAtomic( __METHOD__ );
if ( !$this->exists() ) {
$action = 'created';
$this->initializeDbForNewBanner( $db );
}
$this->saveBannerInternal( $db );
$this->logBannerChange( $action, $user, $summary );
$db->endAtomic( __METHOD__ );
// Clear the dirty flags
foreach ( $this->dirtyFlags as $flag => &$value ) {
$value = false;
}
if ( $this->runTranslateJob ) {