-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Expand file tree
/
Copy pathGlobalFunctions.php
More file actions
1799 lines (1669 loc) · 55.4 KB
/
Copy pathGlobalFunctions.php
File metadata and controls
1799 lines (1669 loc) · 55.4 KB
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
/**
* Global functions used everywhere.
*
* @license GPL-2.0-or-later
* @file
*/
use MediaWiki\Debug\MWDebug;
use MediaWiki\Exception\ProcOpenError;
use MediaWiki\FileRepo\File\File;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\Logger\LoggerFactory;
use MediaWiki\MediaWikiServices;
use MediaWiki\Message\Message;
use MediaWiki\Registration\ExtensionRegistry;
use MediaWiki\Request\ContentSecurityPolicy;
use MediaWiki\Shell\Shell;
use MediaWiki\Title\Title;
use Wikimedia\ArrayUtils\ArrayUtils;
use Wikimedia\FileBackend\FileBackend;
use Wikimedia\FileBackend\FSFile\TempFSFile;
use Wikimedia\Http\HttpStatus;
use Wikimedia\Message\MessageParam;
use Wikimedia\Message\MessageSpecifier;
use Wikimedia\ParamValidator\TypeDef\ExpiryDef;
use Wikimedia\RequestTimeout\RequestTimeout;
use Wikimedia\Timestamp\ConvertibleTimestamp;
use Wikimedia\Timestamp\TimestampFormat as TS;
/**
* Load an extension
*
* This queues an extension to be loaded through
* the ExtensionRegistry system.
*
* @param string $ext Name of the extension to load
* @param string|null $path Absolute path of where to find the extension.json file
* @since 1.25
*/
function wfLoadExtension( $ext, $path = null ) {
if ( !$path ) {
global $wgExtensionDirectory;
$path = "$wgExtensionDirectory/$ext/extension.json";
}
ExtensionRegistry::getInstance()->queue( $path );
}
/**
* Load multiple extensions at once
*
* Same as wfLoadExtension, but more efficient if you
* are loading multiple extensions.
*
* If you want to specify custom paths, you should interact with
* ExtensionRegistry directly.
*
* @see wfLoadExtension
* @param string[] $exts Array of extension names to load
* @since 1.25
*/
function wfLoadExtensions( array $exts ) {
global $wgExtensionDirectory;
$registry = ExtensionRegistry::getInstance();
foreach ( $exts as $ext ) {
$registry->queue( "$wgExtensionDirectory/$ext/extension.json" );
}
}
/**
* Load a skin
*
* @see wfLoadExtension
* @param string $skin Name of the extension to load
* @param string|null $path Absolute path of where to find the skin.json file
* @since 1.25
*/
function wfLoadSkin( $skin, $path = null ) {
if ( !$path ) {
global $wgStyleDirectory;
$path = "$wgStyleDirectory/$skin/skin.json";
}
ExtensionRegistry::getInstance()->queue( $path );
}
/**
* Load multiple skins at once
*
* @see wfLoadExtensions
* @param string[] $skins Array of extension names to load
* @since 1.25
*/
function wfLoadSkins( array $skins ) {
global $wgStyleDirectory;
$registry = ExtensionRegistry::getInstance();
foreach ( $skins as $skin ) {
$registry->queue( "$wgStyleDirectory/$skin/skin.json" );
}
}
/**
* Insert an array into another array after the specified key. If the key is
* not present in the input array, it is returned without modification.
*
* @param array $array
* @param array $insert The array to insert.
* @param mixed $after The key to insert after.
* @return array
* @deprecated since 1.46, hard-deprecated since 1.47, use ArrayUtils::insertAfter
*/
function wfArrayInsertAfter( array $array, array $insert, $after ) {
wfDeprecated( __FUNCTION__, '1.46' );
return ArrayUtils::insertAfter( $array, $insert, $after );
}
/**
* Recursively converts the parameter (an object) to an array with the same data
*
* @phpcs:ignore MediaWiki.Commenting.FunctionComment.ObjectTypeHintParam
* @param object|array $objOrArray
* @param bool $recursive
* @return array
*/
function wfObjectToArray( $objOrArray, $recursive = true ) {
$array = [];
if ( is_object( $objOrArray ) ) {
$objOrArray = get_object_vars( $objOrArray );
}
foreach ( $objOrArray as $key => $value ) {
if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
$value = wfObjectToArray( $value );
}
$array[$key] = $value;
}
return $array;
}
/**
* Get a random decimal value in the domain of [0, 1), in a way
* not likely to give duplicate values for any realistic
* number of articles.
*
* @note This is designed for use in relation to Special:RandomPage
* and the page_random database field.
*
* @return string
*/
function wfRandom() {
// The maximum random value is "only" 2^31-1, so get two random
// values to reduce the chance of dupes
$max = mt_getrandmax() + 1;
$rand = number_format( ( mt_rand() * $max + mt_rand() ) / $max / $max, 12, '.', '' );
return $rand;
}
/**
* Get a random string containing a number of pseudo-random hex characters.
*
* @note This is not secure, if you are trying to generate some sort
* of token please use MWCryptRand instead.
*
* @param int $length The length of the string to generate
* @return string
* @since 1.20
*/
function wfRandomString( $length = 32 ) {
$str = '';
for ( $n = 0; $n < $length; $n += 7 ) {
$str .= sprintf( '%07x', mt_rand() & 0xfffffff );
}
return substr( $str, 0, $length );
}
/**
* We want some things to be included as literal characters in our title URLs
* for prettiness, which urlencode encodes by default. According to RFC 1738,
* all of the following should be safe:
*
* ;:@&=$-_.+!*'(),
*
* RFC 1738 says ~ is unsafe, however RFC 3986 considers it an unreserved
* character which should not be encoded. More importantly, google chrome
* always converts %7E back to ~, and converting it in this function can
* cause a redirect loop (T105265).
*
* But + is not safe because it's used to indicate a space; &= are only safe in
* paths and not in queries (and we don't distinguish here); ' seems kind of
* scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
* is reserved, we don't care. So the list we unescape is:
*
* ;:@$!*(),/~
*
* However, IIS7 redirects fail when the url contains a colon (see T24709),
* so no fancy : for IIS7.
*
* %2F in the page titles seems to fatally break for some reason.
*
* @param string $s
* @return string
*/
function wfUrlencode( $s ) {
static $needle;
if ( $s === null ) {
// Reset $needle for testing.
$needle = null;
return '';
}
if ( $needle === null ) {
$needle = [ '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F', '%7E' ];
if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) ||
!str_contains( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' )
) {
$needle[] = '%3A';
}
}
$s = urlencode( $s );
$s = str_ireplace(
$needle,
[ ';', '@', '$', '!', '*', '(', ')', ',', '/', '~', ':' ],
$s
);
return $s;
}
/**
* This function takes one or two arrays as input, and returns a CGI-style string, e.g.
* "days=7&limit=100". Options in the first array override options in the second.
* Options set to null or false will not be output.
*
* @param array $array1 ( String|Array )
* @param array|null $array2 ( String|Array )
* @param string $prefix
* @return string
*/
function wfArrayToCgi( $array1, $array2 = null, $prefix = '' ) {
if ( $array2 !== null ) {
$array1 += $array2;
}
$cgi = '';
foreach ( $array1 as $key => $value ) {
if ( $value !== null && $value !== false ) {
if ( $cgi != '' ) {
$cgi .= '&';
}
if ( $prefix !== '' ) {
$key = $prefix . "[$key]";
}
if ( is_array( $value ) ) {
$firstTime = true;
foreach ( $value as $k => $v ) {
$cgi .= $firstTime ? '' : '&';
if ( is_array( $v ) ) {
$cgi .= wfArrayToCgi( $v, null, $key . "[$k]" );
} else {
$cgi .= urlencode( $key . "[$k]" ) . '=' . urlencode( $v );
}
$firstTime = false;
}
} else {
if ( is_object( $value ) ) {
$value = $value->__toString();
}
$cgi .= urlencode( $key ) . '=' . urlencode( $value );
}
}
}
return $cgi;
}
/**
* This is the logical opposite of wfArrayToCgi(): it accepts a query string as
* its argument and returns the same string in array form. This allows compatibility
* with legacy functions that accept raw query strings instead of nice
* arrays. Of course, keys and values are urldecode()d.
*
* @param string $query Query string
* @return string[] Array version of input
*/
function wfCgiToArray( $query ) {
if ( isset( $query[0] ) && $query[0] == '?' ) {
$query = substr( $query, 1 );
}
$bits = explode( '&', $query );
$ret = [];
foreach ( $bits as $bit ) {
if ( $bit === '' ) {
continue;
}
if ( !str_contains( $bit, '=' ) ) {
// Pieces like &qwerty become 'qwerty' => '' (at least this is what php does)
$key = $bit;
$value = '';
} else {
[ $key, $value ] = explode( '=', $bit );
}
$key = urldecode( $key );
$value = urldecode( $value );
if ( str_contains( $key, '[' ) ) {
$keys = array_reverse( explode( '[', $key ) );
$key = array_pop( $keys );
$temp = $value;
foreach ( $keys as $k ) {
$k = substr( $k, 0, -1 );
$temp = [ $k => $temp ];
}
if ( isset( $ret[$key] ) && is_array( $ret[$key] ) ) {
$ret[$key] = array_merge( $ret[$key], $temp );
} else {
$ret[$key] = $temp;
}
} else {
$ret[$key] = $value;
}
}
return $ret;
}
/**
* Append a query string to an existing URL, which may or may not already
* have query string parameters already. If so, they will be combined.
*
* @param string $url
* @param string|array $query String or associative array
* @return string
*/
function wfAppendQuery( $url, $query ) {
if ( is_array( $query ) ) {
$query = wfArrayToCgi( $query );
}
if ( $query != '' ) {
// Remove the fragment, if there is one
$fragment = false;
$hashPos = strpos( $url, '#' );
if ( $hashPos !== false ) {
$fragment = substr( $url, $hashPos );
$url = substr( $url, 0, $hashPos );
}
// Add parameter
if ( !str_contains( $url, '?' ) ) {
$url .= '?';
} else {
$url .= '&';
}
$url .= $query;
// Put the fragment back
if ( $fragment !== false ) {
$url .= $fragment;
}
}
return $url;
}
/**
* Sends a line to the debug log if enabled or, optionally, to a comment in output.
* In normal operation this is a NOP.
*
* Controlling globals:
* $wgDebugLogFile - points to the log file
* $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
* $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
*
* @since 1.25 support for additional context data
*
* @param string $text
* @param string|bool $dest Destination of the message:
* - 'all': both to the log and HTML (debug toolbar or HTML comments)
* - 'private': excluded from HTML output
* For backward compatibility, it can also take a boolean:
* - true: same as 'all'
* - false: same as 'private'
* @param array $context Additional logging context data
*/
function wfDebug( $text, $dest = 'all', array $context = [] ) {
global $wgDebugRawPage, $wgDebugLogPrefix;
if ( !$wgDebugRawPage && wfIsDebugRawPage() ) {
return;
}
$text = trim( $text );
if ( $wgDebugLogPrefix !== '' ) {
$context['prefix'] = $wgDebugLogPrefix;
}
$context['private'] = ( $dest === false || $dest === 'private' );
$logger = LoggerFactory::getInstance( 'wfDebug' );
$logger->debug( $text, $context );
}
/**
* Returns true if debug logging should be suppressed if $wgDebugRawPage = false
* @return bool
*/
function wfIsDebugRawPage() {
static $cache;
if ( $cache !== null ) {
return $cache;
}
// Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
// phpcs:ignore MediaWiki.Usage.SuperGlobalsUsage.SuperGlobals
if ( ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' )
|| MW_ENTRY_POINT === 'load'
) {
$cache = true;
} else {
$cache = false;
}
return $cache;
}
/**
* Send a line to a supplementary debug log file, if configured, or main debug
* log if not.
*
* To configure a supplementary log file, set $wgDebugLogGroups[$logGroup] to
* a string filename or an associative array mapping 'destination' to the
* desired filename. The associative array may also contain a 'sample' key
* with an integer value, specifying a sampling factor. Sampled log events
* will be emitted with a 1 in N random chance.
*
* @since 1.23 support for sampling log messages via $wgDebugLogGroups.
* @since 1.25 support for additional context data
* @since 1.25 sample behavior dependent on configured $wgMWLoggerDefaultSpi
*
* @param string $logGroup
* @param string $text
* @param string|bool $dest Destination of the message:
* - 'all': both to the log and HTML (debug toolbar or HTML comments)
* - 'private': only to the specific log if set in $wgDebugLogGroups and
* discarded otherwise
* For backward compatibility, it can also take a boolean:
* - true: same as 'all'
* - false: same as 'private'
* @param array $context Additional logging context data
*/
function wfDebugLog(
$logGroup, $text, $dest = 'all', array $context = []
) {
$text = trim( $text );
$logger = LoggerFactory::getInstance( $logGroup );
$context['private'] = ( $dest === false || $dest === 'private' );
$logger->info( $text, $context );
}
/**
* Log for database errors
*
* @since 1.25 support for additional context data
*
* @param string $text Database error message.
* @param array $context Additional logging context data
*/
function wfLogDBError( $text, array $context = [] ) {
$logger = LoggerFactory::getInstance( 'wfLogDBError' );
$logger->error( trim( $text ), $context );
}
/**
* Logs a warning that a deprecated feature was used.
*
* To write a custom deprecation message, use wfDeprecatedMsg() instead.
*
* @param string $function Feature that is deprecated.
* @param string|false $version Version of MediaWiki that the feature
* was deprecated in (Added in 1.19).
* @param string|bool $component Component to which the feature belongs.
* If false, it is assumed the function is in MediaWiki core (Added in 1.19).
* @param int $callerOffset How far up the call stack is the original
* caller. 2 = function that called the function that called
* wfDeprecated (Added in 1.20).
* @throws InvalidArgumentException If the MediaWiki version
* number specified by $version is neither a string nor false.
*/
function wfDeprecated( $function, $version = false, $component = false, $callerOffset = 2 ) {
if ( !is_string( $version ) && $version !== false ) {
throw new InvalidArgumentException(
"MediaWiki version must either be a string or false. " .
"Example valid version: '1.33'"
);
}
MWDebug::deprecated( $function, $version, $component, $callerOffset + 1 );
}
/**
* Log a deprecation warning with arbitrary message text. A caller
* description will be appended. If the message has already been sent for
* this caller, it won't be sent again.
*
* Although there are component and version parameters, they are not
* automatically appended to the message. The message text should include
* information about when the thing was deprecated. The component and version
* are just used to implement $wgDeprecationReleaseLimit.
*
* @since 1.35
* @param string $msg The message
* @param string|false $version Version of MediaWiki that the function
* was deprecated in.
* @param string|bool $component Component to which the function belongs.
* If false, it is assumed the function is in MediaWiki core.
* @param int|false $callerOffset How far up the call stack is the original
* caller. 2 = function that called the function that called us. If false,
* the caller description will not be appended.
*/
function wfDeprecatedMsg( $msg, $version = false, $component = false, $callerOffset = 2 ) {
MWDebug::deprecatedMsg( $msg, $version, $component,
$callerOffset === false ? false : $callerOffset + 1 );
}
/**
* Send a warning either to the debug log or in a PHP error depending on
* $wgDevelopmentWarnings. To log warnings in production, use wfLogWarning() instead.
*
* @param string $msg Message to send
* @param int $callerOffset Number of items to go back in the backtrace to
* find the correct caller (1 = function calling wfWarn, ...)
* @param int $level PHP error level; defaults to E_USER_NOTICE;
* only used when $wgDevelopmentWarnings is true
*/
function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
MWDebug::warning( $msg, $callerOffset + 1, $level, 'auto' );
}
/**
* Send a warning as a PHP error and the debug log. This is intended for logging
* warnings in production. For logging development warnings, use WfWarn instead.
*
* @param string $msg Message to send
* @param int $callerOffset Number of items to go back in the backtrace to
* find the correct caller (1 = function calling wfLogWarning, ...)
* @param int $level PHP error level; defaults to E_USER_WARNING
*/
function wfLogWarning( $msg, $callerOffset = 1, $level = E_USER_WARNING ) {
MWDebug::warning( $msg, $callerOffset + 1, $level, 'production' );
}
/**
* This is the function for getting translated interface messages.
*
* @see Message class for documentation how to use them.
* @see https://www.mediawiki.org/wiki/Manual:Messages_API
*
* This function replaces all old wfMsg* functions.
*
* When the MessageSpecifier object is an instance of Message, a clone of the object is returned.
* This is unlike the `new Message( … )` constructor, which returns a new object constructed from
* scratch with the same key. This difference is mostly relevant when the passed object is an
* instance of a subclass like RawMessage or ApiMessage.
*
* @param string|string[]|MessageSpecifier $key Message key, or array of keys, or a MessageSpecifier
* @param MessageParam|MessageSpecifier|string|int|float|list<MessageParam|MessageSpecifier|string|int|float> ...$params
* See Message::params()
* @return Message
*
* @since 1.17
*
* @see Message::__construct
*/
function wfMessage( $key, ...$params ) {
if ( is_array( $key ) ) {
// Fallback keys are not allowed in message specifiers
$message = wfMessageFallback( ...$key );
} else {
$message = Message::newFromSpecifier( $key );
}
// We call Message::params() to reduce code duplication
if ( $params ) {
$message->params( ...$params );
}
return $message;
}
/**
* This function accepts multiple message keys and returns a message instance
* for the first message which is non-empty. If all messages are empty then an
* instance of the last message key is returned.
*
* @param string ...$keys Message keys
* @return Message
*
* @since 1.18
*
* @see Message::newFallbackSequence
*/
function wfMessageFallback( ...$keys ) {
return Message::newFallbackSequence( ...$keys );
}
/**
* Replace message parameter keys on the given formatted output.
*
* @param string $message
* @param array $args
* @return string
* @internal
*/
function wfMsgReplaceArgs( $message, $args ) {
# Fix windows line-endings
# Some messages are split with explode("\n", $msg)
$message = str_replace( "\r", '', $message );
// Replace arguments
if ( is_array( $args ) && $args ) {
if ( is_array( $args[0] ) ) {
$args = array_values( $args[0] );
}
$replacementKeys = [];
foreach ( $args as $n => $param ) {
$replacementKeys['$' . ( $n + 1 )] = $param;
}
$message = strtr( $message, $replacementKeys );
}
return $message;
}
/**
* Get host name of the current machine, for use in error reporting.
*
* This helps to know which machine in a data center generated the
* current page.
*
* @return string
*/
function wfHostname() {
// Hostname overriding
global $wgOverrideHostname;
if ( $wgOverrideHostname !== false ) {
return $wgOverrideHostname;
}
return php_uname( 'n' ) ?: 'unknown';
}
/**
* Safety wrapper for debug_backtrace().
*
* Will return an empty array if debug_backtrace is disabled, otherwise
* the output from debug_backtrace() (trimmed).
*
* @param int $limit This parameter can be used to limit the number of stack frames returned
*
* @return array Array of backtrace information
*/
function wfDebugBacktrace( $limit = 0 ) {
static $disabled = null;
if ( $disabled === null ) {
$disabled = !function_exists( 'debug_backtrace' );
if ( $disabled ) {
wfDebug( "debug_backtrace() is disabled" );
}
}
if ( $disabled ) {
return [];
}
if ( $limit ) {
return array_slice( debug_backtrace( DEBUG_BACKTRACE_PROVIDE_OBJECT, $limit + 1 ), 1 );
} else {
return array_slice( debug_backtrace(), 1 );
}
}
/**
* Get a debug backtrace as a string
*
* @param bool|null $raw If true, the return value is plain text. If false, HTML.
* Defaults to true if MW_ENTRY_POINT is 'cli', otherwise false.
* @return string
* @since 1.25 Supports $raw parameter.
*/
function wfBacktrace( $raw = null ) {
$raw ??= MW_ENTRY_POINT === 'cli';
if ( $raw ) {
$frameFormat = "%s line %s calls %s()\n";
$traceFormat = "%s";
} else {
$frameFormat = "<li>%s line %s calls %s()</li>\n";
$traceFormat = "<ul>\n%s</ul>\n";
}
$frames = array_map( static function ( $frame ) use ( $frameFormat ) {
$file = !empty( $frame['file'] ) ? basename( $frame['file'] ) : '-';
$line = $frame['line'] ?? '-';
$call = $frame['function'];
if ( !empty( $frame['class'] ) ) {
$call = $frame['class'] . $frame['type'] . $call;
}
return sprintf( $frameFormat, $file, $line, $call );
}, wfDebugBacktrace() );
return sprintf( $traceFormat, implode( '', $frames ) );
}
/**
* Get the name of the function which called this function
* wfGetCaller( 1 ) is the function with the wfGetCaller() call (ie. __FUNCTION__)
* wfGetCaller( 2 ) [default] is the caller of the function running wfGetCaller()
* wfGetCaller( 3 ) is the parent of that.
*
* The format will be the same as for {@see wfFormatStackFrame()}.
* @param int $level
* @return string function name or 'unknown'
*/
function wfGetCaller( $level = 2 ) {
$backtrace = wfDebugBacktrace( $level + 1 );
if ( isset( $backtrace[$level] ) ) {
return wfFormatStackFrame( $backtrace[$level] );
} else {
return 'unknown';
}
}
/**
* Return a string consisting of callers in the stack. Useful sometimes
* for profiling specific points.
*
* @param int|false $limit The maximum depth of the stack frame to return, or false for the entire stack.
* @return string
*/
function wfGetAllCallers( $limit = 3 ) {
$limit = $limit ? $limit + 1 : 0;
// Strip the own "wfGetAllCallers" from the list
$trace = array_reverse( array_slice( wfDebugBacktrace( $limit ), 1 ) );
return implode( '/', array_map( wfFormatStackFrame( ... ), $trace ) );
}
/**
* Return a string representation of frame
*
* Typically, the returned value will be in one of these formats:
* - method
* - Fully\Qualified\method
* - Fully\Qualified\Class->method
* - Fully\Qualified\Class::method
*
* @param array $frame
* @return string
*/
function wfFormatStackFrame( $frame ) {
if ( !isset( $frame['function'] ) ) {
return 'NO_FUNCTION_GIVEN';
}
return isset( $frame['class'] ) && isset( $frame['type'] ) ?
$frame['class'] . $frame['type'] . $frame['function'] :
$frame['function'];
}
/**
* Whether the client accept gzip encoding
*
* Uses the Accept-Encoding header to check if the client supports gzip encoding.
* Use this when considering to send a gzip-encoded response to the client.
*
* @param bool $force Forces another check even if we already have a cached result.
* @return bool
*/
function wfClientAcceptsGzip( $force = false ) {
static $result = null;
if ( $result === null || $force ) {
$result = false;
if ( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
# @todo FIXME: We may want to disallow some broken browsers
$m = [];
if ( preg_match(
'/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
$_SERVER['HTTP_ACCEPT_ENCODING'],
$m
)
) {
if ( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
return $result;
}
wfDebug( "wfClientAcceptsGzip: client accepts gzip." );
$result = true;
}
}
}
return $result;
}
/**
* Escapes the given text so that it may be output using addWikiText()
* without any linking, formatting, etc. making its way through. This
* is achieved by substituting certain characters with HTML entities.
* As required by the callers, "<nowiki>" is not used.
*
* @param string|null|false $input Text to be escaped
* @param-taint $input escapes_html
* @return string
*/
function wfEscapeWikiText( $input ): string {
global $wgEnableMagicLinks;
static $repl = null, $repl2 = null, $repl3 = null, $repl4 = null;
if ( $repl === null || defined( 'MW_PHPUNIT_TEST' ) ) {
// Tests depend upon being able to change $wgEnableMagicLinks, so don't cache
// in those situations
$repl = [
'"' => '"', '&' => '&', "'" => ''', '<' => '<',
'=' => '=', '>' => '>', '[' => '[', ']' => ']',
'{' => '{', '|' => '|', '}' => '}',
';' => ';', // a token inside language converter brackets
'!!' => '!!', // a token inside table context
"\n!" => "\n!", "\r!" => "\r!", // a token inside table context
"\n#" => "\n#", "\r#" => "\r#",
"\n*" => "\n*", "\r*" => "\r*",
"\n:" => "\n:", "\r:" => "\r:",
"\n " => "\n ", "\r " => "\r ",
"\n\n" => "\n ", "\r\n" => " \n",
"\n\r" => "\n ", "\r\r" => "\r ",
"\n\t" => "\n	", "\r\t" => "\r	", // "\n\t\n" is treated like "\n\n"
"\n----" => "\n----", "\r----" => "\r----",
'__' => '__', '://' => '://',
// Japanese magic words start w/ wide underscore
'_' => '_',
'~~~' => '~~~', // protect from PST, just to be safe(r)
];
$magicLinks = array_keys( array_filter( $wgEnableMagicLinks ) );
// We have to catch everything "\s" matches in PCRE
foreach ( $magicLinks as $magic ) {
$repl["$magic "] = "$magic ";
$repl["$magic\t"] = "$magic	";
$repl["$magic\r"] = "$magic ";
$repl["$magic\n"] = "$magic ";
$repl["$magic\f"] = "$magic";
}
// Additionally escape the following characters at the beginning of the
// string, in case they merge to form tokens when spliced into a
// string. Tokens like -{ {{ [[ {| etc are already escaped because
// the second character is escaped above, but the following tokens
// are handled here: |+ |- __FOO__ ~~~
// (Only single-byte characters can go here; multibyte characters
// like 'wide underscore' must go into $repl above.)
$repl3 = [
'+' => '+', '-' => '-', '_' => '_', '~' => '~',
];
// Similarly, protect the following characters at the end of the
// string, which could turn form the start of `__FOO__` or `~~~~`
// A trailing newline could also form the unintended start of a
// paragraph break if it is glued to a newline in the following
// context. Again, only single-byte characters can be protected
// here; 'wide underscore' is protected by $repl above.
$repl4 = [
'_' => '_', '~' => '~',
"\n" => " ", "\r" => " ",
"\t" => "	", // "\n\t\n" is treated like "\n\n"
];
// And handle protocols that don't use "://"
global $wgUrlProtocols;
$repl2 = [];
foreach ( $wgUrlProtocols as $prot ) {
if ( substr( $prot, -1 ) === ':' ) {
$repl2[] = preg_quote( substr( $prot, 0, -1 ), '/' );
}
}
$repl2 = $repl2 ? '/\b(' . implode( '|', $repl2 ) . '):/i' : '/^(?!)/';
}
// Tell phan that $repl2, $repl3 and $repl4 will also be non-null here
'@phan-var string $repl2';
'@phan-var string $repl3';
'@phan-var string $repl4';
// This will also stringify input in case it's not a string
$text = substr( strtr( "\n$input", $repl ), 1 );
if ( $text === '' ) {
return $text;
}
$first = strtr( $text[0], $repl3 ); // protect first character
if ( strlen( $text ) > 1 ) {
$text = $first . substr( $text, 1, -1 ) .
strtr( substr( $text, -1 ), $repl4 ); // protect last character
} else {
// special case for single-character strings
$text = strtr( $first, $repl4 ); // protect last character
}
$text = preg_replace( $repl2, '$1:', $text );
return $text;
}
/**
* Sets dest to source and returns the original value of dest
* If source is NULL, it just returns the value, it doesn't set the variable
* If force is true, it will set the value even if source is NULL
*
* @param mixed &$dest
* @param mixed $source
* @param bool $force
* @return mixed
*/
function wfSetVar( &$dest, $source, $force = false ) {
$temp = $dest;
if ( $source !== null || $force ) {
$dest = $source;
}
return $temp;
}
/**
* As for wfSetVar except setting a bit
*
* @param int &$dest
* @param int $bit
* @param bool $state
*
* @return bool
*/
function wfSetBit( &$dest, $bit, $state = true ) {
$temp = (bool)( $dest & $bit );
if ( $state !== null ) {
if ( $state ) {
$dest |= $bit;
} else {
$dest &= ~$bit;
}
}
return $temp;
}
/**
* A wrapper around the PHP function var_export().
* Either print it or add it to the regular output ($wgOut).
*
* @param mixed $var A PHP variable to dump.
*/
function wfVarDump( $var ) {
global $wgOut;
$s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
if ( headers_sent() || $wgOut === null || !is_object( $wgOut ) ) {
print $s;
} else {
$wgOut->addHTML( $s );
}
}
/**
* Provide a simple HTTP error.
*
* @param int|string $code
* @param string $label
* @param string $desc
*/
function wfHttpError( $code, $label, $desc ) {
global $wgOut;
HttpStatus::header( $code );
if ( $wgOut ) {
$wgOut->disable();
$wgOut->sendCacheControl();
}
\MediaWiki\Request\HeaderCallback::warnIfHeadersSent();
header( 'Content-type: text/html; charset=utf-8' );
ContentSecurityPolicy::sendRestrictiveHeader();
ob_start();
print '<!DOCTYPE html>' .
'<html><head><title>' .
htmlspecialchars( $label ) .
'</title><meta name="color-scheme" content="light dark" /></head><body><h1>' .
htmlspecialchars( $label ) .
'</h1><p>' .
nl2br( htmlspecialchars( $desc ) ) .
"</p></body></html>\n";
header( 'Content-Length: ' . ob_get_length() );
ob_end_flush();
}
/**
* Clear away any user-level output buffers, discarding contents.
*
* Suitable for 'starting afresh', for instance when streaming
* relatively large amounts of data without buffering, or wanting to
* output image files without ob_gzhandler's compression.
*
* The optional $resetGzipEncoding parameter controls suppression of
* the Content-Encoding header sent by ob_gzhandler; by default it
* is left. This should be used for HTTP 304 responses, where you need to
* preserve the Content-Encoding header of the real result, but
* also need to suppress the output of ob_gzhandler to keep to spec
* and avoid breaking Firefox in rare cases where the headers and
* body are broken over two packets.
*
* Note that some PHP configuration options may add output buffer
* layers which cannot be removed; these are left in place.
*
* Does nothing during unit tests.
*