PageRenderTime 1679ms CodeModel.GetById 44ms RepoModel.GetById 1ms app.codeStats 1ms

/includes/GlobalFunctions.php

https://bitbucket.org/kgrashad/thawrapedia
PHP | 3619 lines | 2297 code | 285 blank | 1037 comment | 395 complexity | 5380fae10701aef4cdee98dc40ab1add MD5 | raw file
Possible License(s): GPL-2.0, Apache-2.0, LGPL-3.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Global functions used everywhere
  4. * @file
  5. */
  6. if ( !defined( 'MEDIAWIKI' ) ) {
  7. die( "This file is part of MediaWiki, it is not a valid entry point" );
  8. }
  9. require_once dirname( __FILE__ ) . '/normal/UtfNormalUtil.php';
  10. // Hide compatibility functions from Doxygen
  11. /// @cond
  12. /**
  13. * Compatibility functions
  14. *
  15. * We support PHP 5.1.x and up.
  16. * Re-implementations of newer functions or functions in non-standard
  17. * PHP extensions may be included here.
  18. */
  19. if( !function_exists( 'iconv' ) ) {
  20. # iconv support is not in the default configuration and so may not be present.
  21. # Assume will only ever use utf-8 and iso-8859-1.
  22. # This will *not* work in all circumstances.
  23. function iconv( $from, $to, $string ) {
  24. if ( substr( $to, -8 ) == '//IGNORE' ) {
  25. $to = substr( $to, 0, strlen( $to ) - 8 );
  26. }
  27. if( strcasecmp( $from, $to ) == 0 ) {
  28. return $string;
  29. }
  30. if( strcasecmp( $from, 'utf-8' ) == 0 ) {
  31. return utf8_decode( $string );
  32. }
  33. if( strcasecmp( $to, 'utf-8' ) == 0 ) {
  34. return utf8_encode( $string );
  35. }
  36. return $string;
  37. }
  38. }
  39. if ( !function_exists( 'mb_substr' ) ) {
  40. /**
  41. * Fallback implementation for mb_substr, hardcoded to UTF-8.
  42. * Attempts to be at least _moderately_ efficient; best optimized
  43. * for relatively small offset and count values -- about 5x slower
  44. * than native mb_string in my testing.
  45. *
  46. * Larger offsets are still fairly efficient for Latin text, but
  47. * can be up to 100x slower than native if the text is heavily
  48. * multibyte and we have to slog through a few hundred kb.
  49. */
  50. function mb_substr( $str, $start, $count='end' ) {
  51. if( $start != 0 ) {
  52. $split = mb_substr_split_unicode( $str, intval( $start ) );
  53. $str = substr( $str, $split );
  54. }
  55. if( $count !== 'end' ) {
  56. $split = mb_substr_split_unicode( $str, intval( $count ) );
  57. $str = substr( $str, 0, $split );
  58. }
  59. return $str;
  60. }
  61. function mb_substr_split_unicode( $str, $splitPos ) {
  62. if( $splitPos == 0 ) {
  63. return 0;
  64. }
  65. $byteLen = strlen( $str );
  66. if( $splitPos > 0 ) {
  67. if( $splitPos > 256 ) {
  68. // Optimize large string offsets by skipping ahead N bytes.
  69. // This will cut out most of our slow time on Latin-based text,
  70. // and 1/2 to 1/3 on East European and Asian scripts.
  71. $bytePos = $splitPos;
  72. while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
  73. ++$bytePos;
  74. }
  75. $charPos = mb_strlen( substr( $str, 0, $bytePos ) );
  76. } else {
  77. $charPos = 0;
  78. $bytePos = 0;
  79. }
  80. while( $charPos++ < $splitPos ) {
  81. ++$bytePos;
  82. // Move past any tail bytes
  83. while ( $bytePos < $byteLen && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
  84. ++$bytePos;
  85. }
  86. }
  87. } else {
  88. $splitPosX = $splitPos + 1;
  89. $charPos = 0; // relative to end of string; we don't care about the actual char position here
  90. $bytePos = $byteLen;
  91. while( $bytePos > 0 && $charPos-- >= $splitPosX ) {
  92. --$bytePos;
  93. // Move past any tail bytes
  94. while ( $bytePos > 0 && $str{$bytePos} >= "\x80" && $str{$bytePos} < "\xc0" ) {
  95. --$bytePos;
  96. }
  97. }
  98. }
  99. return $bytePos;
  100. }
  101. }
  102. if ( !function_exists( 'mb_strlen' ) ) {
  103. /**
  104. * Fallback implementation of mb_strlen, hardcoded to UTF-8.
  105. * @param string $str
  106. * @param string $enc optional encoding; ignored
  107. * @return int
  108. */
  109. function mb_strlen( $str, $enc = '' ) {
  110. $counts = count_chars( $str );
  111. $total = 0;
  112. // Count ASCII bytes
  113. for( $i = 0; $i < 0x80; $i++ ) {
  114. $total += $counts[$i];
  115. }
  116. // Count multibyte sequence heads
  117. for( $i = 0xc0; $i < 0xff; $i++ ) {
  118. $total += $counts[$i];
  119. }
  120. return $total;
  121. }
  122. }
  123. if( !function_exists( 'mb_strpos' ) ) {
  124. /**
  125. * Fallback implementation of mb_strpos, hardcoded to UTF-8.
  126. * @param $haystack String
  127. * @param $needle String
  128. * @param $offset String: optional start position
  129. * @param $encoding String: optional encoding; ignored
  130. * @return int
  131. */
  132. function mb_strpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
  133. $needle = preg_quote( $needle, '/' );
  134. $ar = array();
  135. preg_match( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
  136. if( isset( $ar[0][1] ) ) {
  137. return $ar[0][1];
  138. } else {
  139. return false;
  140. }
  141. }
  142. }
  143. if( !function_exists( 'mb_strrpos' ) ) {
  144. /**
  145. * Fallback implementation of mb_strrpos, hardcoded to UTF-8.
  146. * @param $haystack String
  147. * @param $needle String
  148. * @param $offset String: optional start position
  149. * @param $encoding String: optional encoding; ignored
  150. * @return int
  151. */
  152. function mb_strrpos( $haystack, $needle, $offset = 0, $encoding = '' ) {
  153. $needle = preg_quote( $needle, '/' );
  154. $ar = array();
  155. preg_match_all( '/' . $needle . '/u', $haystack, $ar, PREG_OFFSET_CAPTURE, $offset );
  156. if( isset( $ar[0] ) && count( $ar[0] ) > 0 &&
  157. isset( $ar[0][count( $ar[0] ) - 1][1] ) ) {
  158. return $ar[0][count( $ar[0] ) - 1][1];
  159. } else {
  160. return false;
  161. }
  162. }
  163. }
  164. // Support for Wietse Venema's taint feature
  165. if ( !function_exists( 'istainted' ) ) {
  166. function istainted( $var ) {
  167. return 0;
  168. }
  169. function taint( $var, $level = 0 ) {}
  170. function untaint( $var, $level = 0 ) {}
  171. define( 'TC_HTML', 1 );
  172. define( 'TC_SHELL', 1 );
  173. define( 'TC_MYSQL', 1 );
  174. define( 'TC_PCRE', 1 );
  175. define( 'TC_SELF', 1 );
  176. }
  177. // array_fill_keys() was only added in 5.2, but people use it anyway
  178. // add a back-compat layer for 5.1. See bug 27781
  179. if( !function_exists( 'array_fill_keys' ) ) {
  180. function array_fill_keys( $keys, $value ) {
  181. return array_combine( $keys, array_fill( 0, count( $keys ), $value ) );
  182. }
  183. }
  184. /// @endcond
  185. /**
  186. * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
  187. */
  188. function wfArrayDiff2( $a, $b ) {
  189. return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
  190. }
  191. function wfArrayDiff2_cmp( $a, $b ) {
  192. if ( !is_array( $a ) ) {
  193. return strcmp( $a, $b );
  194. } elseif ( count( $a ) !== count( $b ) ) {
  195. return count( $a ) < count( $b ) ? -1 : 1;
  196. } else {
  197. reset( $a );
  198. reset( $b );
  199. while( ( list( , $valueA ) = each( $a ) ) && ( list( , $valueB ) = each( $b ) ) ) {
  200. $cmp = strcmp( $valueA, $valueB );
  201. if ( $cmp !== 0 ) {
  202. return $cmp;
  203. }
  204. }
  205. return 0;
  206. }
  207. }
  208. /**
  209. * Seed Mersenne Twister
  210. * No-op for compatibility; only necessary in PHP < 4.2.0
  211. * @deprecated. Remove in 1.18
  212. */
  213. function wfSeedRandom() {
  214. wfDeprecated(__FUNCTION__);
  215. }
  216. /**
  217. * Get a random decimal value between 0 and 1, in a way
  218. * not likely to give duplicate values for any realistic
  219. * number of articles.
  220. *
  221. * @return string
  222. */
  223. function wfRandom() {
  224. # The maximum random value is "only" 2^31-1, so get two random
  225. # values to reduce the chance of dupes
  226. $max = mt_getrandmax() + 1;
  227. $rand = number_format( ( mt_rand() * $max + mt_rand() )
  228. / $max / $max, 12, '.', '' );
  229. return $rand;
  230. }
  231. /**
  232. * We want some things to be included as literal characters in our title URLs
  233. * for prettiness, which urlencode encodes by default. According to RFC 1738,
  234. * all of the following should be safe:
  235. *
  236. * ;:@&=$-_.+!*'(),
  237. *
  238. * But + is not safe because it's used to indicate a space; &= are only safe in
  239. * paths and not in queries (and we don't distinguish here); ' seems kind of
  240. * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
  241. * is reserved, we don't care. So the list we unescape is:
  242. *
  243. * ;:@$!*(),/
  244. *
  245. * However, IIS7 redirects fail when the url contains a colon (Bug 22709),
  246. * so no fancy : for IIS7.
  247. *
  248. * %2F in the page titles seems to fatally break for some reason.
  249. *
  250. * @param $s String:
  251. * @return string
  252. */
  253. function wfUrlencode( $s ) {
  254. static $needle;
  255. if ( is_null( $needle ) ) {
  256. $needle = array( '%3B', '%40', '%24', '%21', '%2A', '%28', '%29', '%2C', '%2F' );
  257. if ( !isset( $_SERVER['SERVER_SOFTWARE'] ) || ( strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS/7' ) === false ) ) {
  258. $needle[] = '%3A';
  259. }
  260. }
  261. $s = urlencode( $s );
  262. $s = str_ireplace(
  263. $needle,
  264. array( ';', '@', '$', '!', '*', '(', ')', ',', '/', ':' ),
  265. $s
  266. );
  267. return $s;
  268. }
  269. /**
  270. * Sends a line to the debug log if enabled or, optionally, to a comment in output.
  271. * In normal operation this is a NOP.
  272. *
  273. * Controlling globals:
  274. * $wgDebugLogFile - points to the log file
  275. * $wgProfileOnly - if set, normal debug messages will not be recorded.
  276. * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
  277. * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
  278. *
  279. * @param $text String
  280. * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
  281. */
  282. function wfDebug( $text, $logonly = false ) {
  283. global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
  284. global $wgDebugLogPrefix, $wgShowDebug;
  285. static $recursion = 0;
  286. static $cache = array(); // Cache of unoutputted messages
  287. $text = wfDebugTimer() . $text;
  288. # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
  289. if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
  290. return;
  291. }
  292. if ( ( $wgDebugComments || $wgShowDebug ) && !$logonly ) {
  293. $cache[] = $text;
  294. if ( !isset( $wgOut ) ) {
  295. return;
  296. }
  297. if ( !StubObject::isRealObject( $wgOut ) ) {
  298. if ( $recursion ) {
  299. return;
  300. }
  301. $recursion++;
  302. $wgOut->_unstub();
  303. $recursion--;
  304. }
  305. // add the message and possible cached ones to the output
  306. array_map( array( $wgOut, 'debug' ), $cache );
  307. $cache = array();
  308. }
  309. if ( $wgDebugLogFile != '' && !$wgProfileOnly ) {
  310. # Strip unprintables; they can switch terminal modes when binary data
  311. # gets dumped, which is pretty annoying.
  312. $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
  313. $text = $wgDebugLogPrefix . $text;
  314. wfErrorLog( $text, $wgDebugLogFile );
  315. }
  316. }
  317. function wfDebugTimer() {
  318. global $wgDebugTimestamps;
  319. if ( !$wgDebugTimestamps ) {
  320. return '';
  321. }
  322. static $start = null;
  323. if ( $start === null ) {
  324. $start = microtime( true );
  325. $prefix = "\n$start";
  326. } else {
  327. $prefix = sprintf( "%6.4f", microtime( true ) - $start );
  328. }
  329. return $prefix . ' ';
  330. }
  331. /**
  332. * Send a line giving PHP memory usage.
  333. * @param $exact Bool: print exact values instead of kilobytes (default: false)
  334. */
  335. function wfDebugMem( $exact = false ) {
  336. $mem = memory_get_usage();
  337. if( !$exact ) {
  338. $mem = floor( $mem / 1024 ) . ' kilobytes';
  339. } else {
  340. $mem .= ' bytes';
  341. }
  342. wfDebug( "Memory usage: $mem\n" );
  343. }
  344. /**
  345. * Send a line to a supplementary debug log file, if configured, or main debug log if not.
  346. * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
  347. *
  348. * @param $logGroup String
  349. * @param $text String
  350. * @param $public Bool: whether to log the event in the public log if no private
  351. * log file is specified, (default true)
  352. */
  353. function wfDebugLog( $logGroup, $text, $public = true ) {
  354. global $wgDebugLogGroups, $wgShowHostnames;
  355. $text = trim( $text ) . "\n";
  356. if( isset( $wgDebugLogGroups[$logGroup] ) ) {
  357. $time = wfTimestamp( TS_DB );
  358. $wiki = wfWikiID();
  359. if ( $wgShowHostnames ) {
  360. $host = wfHostname();
  361. } else {
  362. $host = '';
  363. }
  364. wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
  365. } elseif ( $public === true ) {
  366. wfDebug( $text, true );
  367. }
  368. }
  369. /**
  370. * Log for database errors
  371. * @param $text String: database error message.
  372. */
  373. function wfLogDBError( $text ) {
  374. global $wgDBerrorLog, $wgDBname;
  375. if ( $wgDBerrorLog ) {
  376. $host = trim(`hostname`);
  377. $text = date( 'D M j G:i:s T Y' ) . "\t$host\t$wgDBname\t$text";
  378. wfErrorLog( $text, $wgDBerrorLog );
  379. }
  380. }
  381. /**
  382. * Log to a file without getting "file size exceeded" signals.
  383. *
  384. * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
  385. * send lines to the specified port, prefixed by the specified prefix and a space.
  386. */
  387. function wfErrorLog( $text, $file ) {
  388. if ( substr( $file, 0, 4 ) == 'udp:' ) {
  389. # Needs the sockets extension
  390. if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
  391. // IPv6 bracketed host
  392. $host = $m[2];
  393. $port = intval( $m[3] );
  394. $prefix = isset( $m[4] ) ? $m[4] : false;
  395. $domain = AF_INET6;
  396. } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
  397. $host = $m[2];
  398. if ( !IP::isIPv4( $host ) ) {
  399. $host = gethostbyname( $host );
  400. }
  401. $port = intval( $m[3] );
  402. $prefix = isset( $m[4] ) ? $m[4] : false;
  403. $domain = AF_INET;
  404. } else {
  405. throw new MWException( __METHOD__ . ': Invalid UDP specification' );
  406. }
  407. // Clean it up for the multiplexer
  408. if ( strval( $prefix ) !== '' ) {
  409. $text = preg_replace( '/^/m', $prefix . ' ', $text );
  410. if ( substr( $text, -1 ) != "\n" ) {
  411. $text .= "\n";
  412. }
  413. }
  414. $sock = socket_create( $domain, SOCK_DGRAM, SOL_UDP );
  415. if ( !$sock ) {
  416. return;
  417. }
  418. socket_sendto( $sock, $text, strlen( $text ), 0, $host, $port );
  419. socket_close( $sock );
  420. } else {
  421. wfSuppressWarnings();
  422. $exists = file_exists( $file );
  423. $size = $exists ? filesize( $file ) : false;
  424. if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
  425. error_log( $text, 3, $file );
  426. }
  427. wfRestoreWarnings();
  428. }
  429. }
  430. /**
  431. * @todo document
  432. */
  433. function wfLogProfilingData() {
  434. global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
  435. global $wgProfiler, $wgProfileLimit, $wgUser;
  436. # Profiling must actually be enabled...
  437. if( is_null( $wgProfiler ) ) {
  438. return;
  439. }
  440. # Get total page request time
  441. $now = wfTime();
  442. $elapsed = $now - $wgRequestTime;
  443. # Only show pages that longer than $wgProfileLimit time (default is 0)
  444. if( $elapsed <= $wgProfileLimit ) {
  445. return;
  446. }
  447. $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
  448. $forward = '';
  449. if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
  450. $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
  451. }
  452. if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
  453. $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
  454. }
  455. if( !empty( $_SERVER['HTTP_FROM'] ) ) {
  456. $forward .= ' from ' . $_SERVER['HTTP_FROM'];
  457. }
  458. if( $forward ) {
  459. $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
  460. }
  461. // Don't unstub $wgUser at this late stage just for statistics purposes
  462. // FIXME: We can detect some anons even if it is not loaded. See User::getId()
  463. if( $wgUser->mDataLoaded && $wgUser->isAnon() ) {
  464. $forward .= ' anon';
  465. }
  466. $log = sprintf( "%s\t%04.3f\t%s\n",
  467. gmdate( 'YmdHis' ), $elapsed,
  468. urldecode( $wgRequest->getRequestURL() . $forward ) );
  469. if ( $wgDebugLogFile != '' && ( $wgRequest->getVal( 'action' ) != 'raw' || $wgDebugRawPage ) ) {
  470. wfErrorLog( $log . $prof, $wgDebugLogFile );
  471. }
  472. }
  473. /**
  474. * Check if the wiki read-only lock file is present. This can be used to lock
  475. * off editing functions, but doesn't guarantee that the database will not be
  476. * modified.
  477. * @return bool
  478. */
  479. function wfReadOnly() {
  480. global $wgReadOnlyFile, $wgReadOnly;
  481. if ( !is_null( $wgReadOnly ) ) {
  482. return (bool)$wgReadOnly;
  483. }
  484. if ( $wgReadOnlyFile == '' ) {
  485. return false;
  486. }
  487. // Set $wgReadOnly for faster access next time
  488. if ( is_file( $wgReadOnlyFile ) ) {
  489. $wgReadOnly = file_get_contents( $wgReadOnlyFile );
  490. } else {
  491. $wgReadOnly = false;
  492. }
  493. return (bool)$wgReadOnly;
  494. }
  495. function wfReadOnlyReason() {
  496. global $wgReadOnly;
  497. wfReadOnly();
  498. return $wgReadOnly;
  499. }
  500. /**
  501. * Return a Language object from $langcode
  502. * @param $langcode Mixed: either:
  503. * - a Language object
  504. * - code of the language to get the message for, if it is
  505. * a valid code create a language for that language, if
  506. * it is a string but not a valid code then make a basic
  507. * language object
  508. * - a boolean: if it's false then use the current users
  509. * language (as a fallback for the old parameter
  510. * functionality), or if it is true then use the wikis
  511. * @return Language object
  512. */
  513. function wfGetLangObj( $langcode = false ) {
  514. # Identify which language to get or create a language object for.
  515. # Using is_object here due to Stub objects.
  516. if( is_object( $langcode ) ) {
  517. # Great, we already have the object (hopefully)!
  518. return $langcode;
  519. }
  520. global $wgContLang, $wgLanguageCode;
  521. if( $langcode === true || $langcode === $wgLanguageCode ) {
  522. # $langcode is the language code of the wikis content language object.
  523. # or it is a boolean and value is true
  524. return $wgContLang;
  525. }
  526. global $wgLang;
  527. if( $langcode === false || $langcode === $wgLang->getCode() ) {
  528. # $langcode is the language code of user language object.
  529. # or it was a boolean and value is false
  530. return $wgLang;
  531. }
  532. $validCodes = array_keys( Language::getLanguageNames() );
  533. if( in_array( $langcode, $validCodes ) ) {
  534. # $langcode corresponds to a valid language.
  535. return Language::factory( $langcode );
  536. }
  537. # $langcode is a string, but not a valid language code; use content language.
  538. wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
  539. return $wgContLang;
  540. }
  541. /**
  542. * Use this instead of $wgContLang, when working with user interface.
  543. * User interface is currently hard coded according to wiki content language
  544. * in many ways, especially regarding to text direction. There is lots stuff
  545. * to fix, hence this function to keep the old behaviour unless the global
  546. * $wgBetterDirectionality is enabled (or removed when everything works).
  547. */
  548. function wfUILang() {
  549. global $wgBetterDirectionality;
  550. return wfGetLangObj( !$wgBetterDirectionality );
  551. }
  552. /**
  553. * This is the new function for getting translated interface messages.
  554. * See the Message class for documentation how to use them.
  555. * The intention is that this function replaces all old wfMsg* functions.
  556. * @param $key \string Message key.
  557. * Varargs: normal message parameters.
  558. * @return \type{Message}
  559. * @since 1.17
  560. */
  561. function wfMessage( $key /*...*/) {
  562. $params = func_get_args();
  563. array_shift( $params );
  564. if ( isset( $params[0] ) && is_array( $params[0] ) ) {
  565. $params = $params[0];
  566. }
  567. return new Message( $key, $params );
  568. }
  569. /**
  570. * Get a message from anywhere, for the current user language.
  571. *
  572. * Use wfMsgForContent() instead if the message should NOT
  573. * change depending on the user preferences.
  574. *
  575. * @param $key String: lookup key for the message, usually
  576. * defined in languages/Language.php
  577. *
  578. * This function also takes extra optional parameters (not
  579. * shown in the function definition), which can be used to
  580. * insert variable text into the predefined message.
  581. */
  582. function wfMsg( $key ) {
  583. $args = func_get_args();
  584. array_shift( $args );
  585. return wfMsgReal( $key, $args, true );
  586. }
  587. /**
  588. * Same as above except doesn't transform the message
  589. */
  590. function wfMsgNoTrans( $key ) {
  591. $args = func_get_args();
  592. array_shift( $args );
  593. return wfMsgReal( $key, $args, true, false, false );
  594. }
  595. /**
  596. * Get a message from anywhere, for the current global language
  597. * set with $wgLanguageCode.
  598. *
  599. * Use this if the message should NOT change dependent on the
  600. * language set in the user's preferences. This is the case for
  601. * most text written into logs, as well as link targets (such as
  602. * the name of the copyright policy page). Link titles, on the
  603. * other hand, should be shown in the UI language.
  604. *
  605. * Note that MediaWiki allows users to change the user interface
  606. * language in their preferences, but a single installation
  607. * typically only contains content in one language.
  608. *
  609. * Be wary of this distinction: If you use wfMsg() where you should
  610. * use wfMsgForContent(), a user of the software may have to
  611. * customize potentially hundreds of messages in
  612. * order to, e.g., fix a link in every possible language.
  613. *
  614. * @param $key String: lookup key for the message, usually
  615. * defined in languages/Language.php
  616. */
  617. function wfMsgForContent( $key ) {
  618. global $wgForceUIMsgAsContentMsg;
  619. $args = func_get_args();
  620. array_shift( $args );
  621. $forcontent = true;
  622. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  623. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  624. {
  625. $forcontent = false;
  626. }
  627. return wfMsgReal( $key, $args, true, $forcontent );
  628. }
  629. /**
  630. * Same as above except doesn't transform the message
  631. */
  632. function wfMsgForContentNoTrans( $key ) {
  633. global $wgForceUIMsgAsContentMsg;
  634. $args = func_get_args();
  635. array_shift( $args );
  636. $forcontent = true;
  637. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  638. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  639. {
  640. $forcontent = false;
  641. }
  642. return wfMsgReal( $key, $args, true, $forcontent, false );
  643. }
  644. /**
  645. * Get a message from the language file, for the UI elements
  646. */
  647. function wfMsgNoDB( $key ) {
  648. $args = func_get_args();
  649. array_shift( $args );
  650. return wfMsgReal( $key, $args, false );
  651. }
  652. /**
  653. * Get a message from the language file, for the content
  654. */
  655. function wfMsgNoDBForContent( $key ) {
  656. global $wgForceUIMsgAsContentMsg;
  657. $args = func_get_args();
  658. array_shift( $args );
  659. $forcontent = true;
  660. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  661. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  662. {
  663. $forcontent = false;
  664. }
  665. return wfMsgReal( $key, $args, false, $forcontent );
  666. }
  667. /**
  668. * Really get a message
  669. * @param $key String: key to get.
  670. * @param $args
  671. * @param $useDB Boolean
  672. * @param $forContent Mixed: Language code, or false for user lang, true for content lang.
  673. * @param $transform Boolean: Whether or not to transform the message.
  674. * @return String: the requested message.
  675. */
  676. function wfMsgReal( $key, $args, $useDB = true, $forContent = false, $transform = true ) {
  677. wfProfileIn( __METHOD__ );
  678. $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
  679. $message = wfMsgReplaceArgs( $message, $args );
  680. wfProfileOut( __METHOD__ );
  681. return $message;
  682. }
  683. /**
  684. * This function provides the message source for messages to be edited which are *not* stored in the database.
  685. * @param $key String:
  686. */
  687. function wfMsgWeirdKey( $key ) {
  688. $source = wfMsgGetKey( $key, false, true, false );
  689. if ( wfEmptyMsg( $key, $source ) ) {
  690. return '';
  691. } else {
  692. return $source;
  693. }
  694. }
  695. /**
  696. * Fetch a message string value, but don't replace any keys yet.
  697. * @param $key String
  698. * @param $useDB Bool
  699. * @param $langCode String: Code of the language to get the message for, or
  700. * behaves as a content language switch if it is a boolean.
  701. * @param $transform Boolean: whether to parse magic words, etc.
  702. * @return string
  703. */
  704. function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
  705. global $wgMessageCache;
  706. wfRunHooks( 'NormalizeMessageKey', array( &$key, &$useDB, &$langCode, &$transform ) );
  707. if ( !is_object( $wgMessageCache ) ) {
  708. throw new MWException( 'Trying to get message before message cache is initialised' );
  709. }
  710. $message = $wgMessageCache->get( $key, $useDB, $langCode );
  711. if( $message === false ) {
  712. $message = '&lt;' . htmlspecialchars( $key ) . '&gt;';
  713. } elseif ( $transform ) {
  714. $message = $wgMessageCache->transform( $message );
  715. }
  716. return $message;
  717. }
  718. /**
  719. * Replace message parameter keys on the given formatted output.
  720. *
  721. * @param $message String
  722. * @param $args Array
  723. * @return string
  724. * @private
  725. */
  726. function wfMsgReplaceArgs( $message, $args ) {
  727. # Fix windows line-endings
  728. # Some messages are split with explode("\n", $msg)
  729. $message = str_replace( "\r", '', $message );
  730. // Replace arguments
  731. if ( count( $args ) ) {
  732. if ( is_array( $args[0] ) ) {
  733. $args = array_values( $args[0] );
  734. }
  735. $replacementKeys = array();
  736. foreach( $args as $n => $param ) {
  737. $replacementKeys['$' . ( $n + 1 )] = $param;
  738. }
  739. $message = strtr( $message, $replacementKeys );
  740. }
  741. return $message;
  742. }
  743. /**
  744. * Return an HTML-escaped version of a message.
  745. * Parameter replacements, if any, are done *after* the HTML-escaping,
  746. * so parameters may contain HTML (eg links or form controls). Be sure
  747. * to pre-escape them if you really do want plaintext, or just wrap
  748. * the whole thing in htmlspecialchars().
  749. *
  750. * @param $key String
  751. * @param string ... parameters
  752. * @return string
  753. */
  754. function wfMsgHtml( $key ) {
  755. $args = func_get_args();
  756. array_shift( $args );
  757. return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
  758. }
  759. /**
  760. * Return an HTML version of message
  761. * Parameter replacements, if any, are done *after* parsing the wiki-text message,
  762. * so parameters may contain HTML (eg links or form controls). Be sure
  763. * to pre-escape them if you really do want plaintext, or just wrap
  764. * the whole thing in htmlspecialchars().
  765. *
  766. * @param $key String
  767. * @param string ... parameters
  768. * @return string
  769. */
  770. function wfMsgWikiHtml( $key ) {
  771. global $wgOut;
  772. $args = func_get_args();
  773. array_shift( $args );
  774. return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
  775. }
  776. /**
  777. * Returns message in the requested format
  778. * @param $key String: key of the message
  779. * @param $options Array: processing rules. Can take the following options:
  780. * <i>parse</i>: parses wikitext to HTML
  781. * <i>parseinline</i>: parses wikitext to HTML and removes the surrounding
  782. * p's added by parser or tidy
  783. * <i>escape</i>: filters message through htmlspecialchars
  784. * <i>escapenoentities</i>: same, but allows entity references like &#160; through
  785. * <i>replaceafter</i>: parameters are substituted after parsing or escaping
  786. * <i>parsemag</i>: transform the message using magic phrases
  787. * <i>content</i>: fetch message for content language instead of interface
  788. * Also can accept a single associative argument, of the form 'language' => 'xx':
  789. * <i>language</i>: Language object or language code to fetch message for
  790. * (overriden by <i>content</i>), its behaviour with parse, parseinline
  791. * and parsemag is undefined.
  792. * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
  793. */
  794. function wfMsgExt( $key, $options ) {
  795. global $wgOut;
  796. $args = func_get_args();
  797. array_shift( $args );
  798. array_shift( $args );
  799. $options = (array)$options;
  800. foreach( $options as $arrayKey => $option ) {
  801. if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
  802. # An unknown index, neither numeric nor "language"
  803. wfWarn( "wfMsgExt called with incorrect parameter key $arrayKey", 1, E_USER_WARNING );
  804. } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
  805. array( 'parse', 'parseinline', 'escape', 'escapenoentities',
  806. 'replaceafter', 'parsemag', 'content' ) ) ) {
  807. # A numeric index with unknown value
  808. wfWarn( "wfMsgExt called with incorrect parameter $option", 1, E_USER_WARNING );
  809. }
  810. }
  811. if( in_array( 'content', $options, true ) ) {
  812. $forContent = true;
  813. $langCode = true;
  814. } elseif( array_key_exists( 'language', $options ) ) {
  815. $forContent = false;
  816. $langCode = wfGetLangObj( $options['language'] );
  817. } else {
  818. $forContent = false;
  819. $langCode = false;
  820. }
  821. $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
  822. if( !in_array( 'replaceafter', $options, true ) ) {
  823. $string = wfMsgReplaceArgs( $string, $args );
  824. }
  825. if( in_array( 'parse', $options, true ) ) {
  826. $string = $wgOut->parse( $string, true, !$forContent );
  827. } elseif ( in_array( 'parseinline', $options, true ) ) {
  828. $string = $wgOut->parse( $string, true, !$forContent );
  829. $m = array();
  830. if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
  831. $string = $m[1];
  832. }
  833. } elseif ( in_array( 'parsemag', $options, true ) ) {
  834. global $wgMessageCache;
  835. if ( isset( $wgMessageCache ) ) {
  836. $string = $wgMessageCache->transform( $string,
  837. !$forContent,
  838. is_object( $langCode ) ? $langCode : null );
  839. }
  840. }
  841. if ( in_array( 'escape', $options, true ) ) {
  842. $string = htmlspecialchars ( $string );
  843. } elseif ( in_array( 'escapenoentities', $options, true ) ) {
  844. $string = Sanitizer::escapeHtmlAllowEntities( $string );
  845. }
  846. if( in_array( 'replaceafter', $options, true ) ) {
  847. $string = wfMsgReplaceArgs( $string, $args );
  848. }
  849. return $string;
  850. }
  851. /**
  852. * Just like exit() but makes a note of it.
  853. * Commits open transactions except if the error parameter is set
  854. *
  855. * @deprecated Please return control to the caller or throw an exception. Will
  856. * be removed in 1.19.
  857. */
  858. function wfAbruptExit( $error = false ) {
  859. static $called = false;
  860. if ( $called ) {
  861. exit( -1 );
  862. }
  863. $called = true;
  864. wfDeprecated( __FUNCTION__ );
  865. $bt = wfDebugBacktrace();
  866. if( $bt ) {
  867. for( $i = 0; $i < count( $bt ); $i++ ) {
  868. $file = isset( $bt[$i]['file'] ) ? $bt[$i]['file'] : 'unknown';
  869. $line = isset( $bt[$i]['line'] ) ? $bt[$i]['line'] : 'unknown';
  870. wfDebug( "WARNING: Abrupt exit in $file at line $line\n");
  871. }
  872. } else {
  873. wfDebug( "WARNING: Abrupt exit\n" );
  874. }
  875. wfLogProfilingData();
  876. if ( !$error ) {
  877. wfGetLB()->closeAll();
  878. }
  879. exit( -1 );
  880. }
  881. /**
  882. * @deprecated Please return control the caller or throw an exception. Will
  883. * be removed in 1.19.
  884. */
  885. function wfErrorExit() {
  886. wfDeprecated( __FUNCTION__ );
  887. wfAbruptExit( true );
  888. }
  889. /**
  890. * Print a simple message and die, returning nonzero to the shell if any.
  891. * Plain die() fails to return nonzero to the shell if you pass a string.
  892. * @param $msg String
  893. */
  894. function wfDie( $msg = '' ) {
  895. echo $msg;
  896. die( 1 );
  897. }
  898. /**
  899. * Throw a debugging exception. This function previously once exited the process,
  900. * but now throws an exception instead, with similar results.
  901. *
  902. * @param $msg String: message shown when dieing.
  903. */
  904. function wfDebugDieBacktrace( $msg = '' ) {
  905. throw new MWException( $msg );
  906. }
  907. /**
  908. * Fetch server name for use in error reporting etc.
  909. * Use real server name if available, so we know which machine
  910. * in a server farm generated the current page.
  911. * @return string
  912. */
  913. function wfHostname() {
  914. static $host;
  915. if ( is_null( $host ) ) {
  916. if ( function_exists( 'posix_uname' ) ) {
  917. // This function not present on Windows
  918. $uname = @posix_uname();
  919. } else {
  920. $uname = false;
  921. }
  922. if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
  923. $host = $uname['nodename'];
  924. } elseif ( getenv( 'COMPUTERNAME' ) ) {
  925. # Windows computer name
  926. $host = getenv( 'COMPUTERNAME' );
  927. } else {
  928. # This may be a virtual server.
  929. $host = $_SERVER['SERVER_NAME'];
  930. }
  931. }
  932. return $host;
  933. }
  934. /**
  935. * Returns a HTML comment with the elapsed time since request.
  936. * This method has no side effects.
  937. * @return string
  938. */
  939. function wfReportTime() {
  940. global $wgRequestTime, $wgShowHostnames;
  941. $now = wfTime();
  942. $elapsed = $now - $wgRequestTime;
  943. return $wgShowHostnames
  944. ? sprintf( '<!-- Served by %s in %01.3f secs. -->', wfHostname(), $elapsed )
  945. : sprintf( '<!-- Served in %01.3f secs. -->', $elapsed );
  946. }
  947. /**
  948. * Safety wrapper for debug_backtrace().
  949. *
  950. * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
  951. * murky circumstances, which may be triggered in part by stub objects
  952. * or other fancy talkin'.
  953. *
  954. * Will return an empty array if Zend Optimizer is detected or if
  955. * debug_backtrace is disabled, otherwise the output from
  956. * debug_backtrace() (trimmed).
  957. *
  958. * @return array of backtrace information
  959. */
  960. function wfDebugBacktrace() {
  961. static $disabled = null;
  962. if( extension_loaded( 'Zend Optimizer' ) ) {
  963. wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
  964. return array();
  965. }
  966. if ( is_null( $disabled ) ) {
  967. $disabled = false;
  968. $functions = explode( ',', ini_get( 'disable_functions' ) );
  969. $functions = array_map( 'trim', $functions );
  970. $functions = array_map( 'strtolower', $functions );
  971. if ( in_array( 'debug_backtrace', $functions ) ) {
  972. wfDebug( "debug_backtrace is in disabled_functions\n" );
  973. $disabled = true;
  974. }
  975. }
  976. if ( $disabled ) {
  977. return array();
  978. }
  979. return array_slice( debug_backtrace(), 1 );
  980. }
  981. function wfBacktrace() {
  982. global $wgCommandLineMode;
  983. if ( $wgCommandLineMode ) {
  984. $msg = '';
  985. } else {
  986. $msg = "<ul>\n";
  987. }
  988. $backtrace = wfDebugBacktrace();
  989. foreach( $backtrace as $call ) {
  990. if( isset( $call['file'] ) ) {
  991. $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
  992. $file = $f[count( $f ) - 1];
  993. } else {
  994. $file = '-';
  995. }
  996. if( isset( $call['line'] ) ) {
  997. $line = $call['line'];
  998. } else {
  999. $line = '-';
  1000. }
  1001. if ( $wgCommandLineMode ) {
  1002. $msg .= "$file line $line calls ";
  1003. } else {
  1004. $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
  1005. }
  1006. if( !empty( $call['class'] ) ) {
  1007. $msg .= $call['class'] . '::';
  1008. }
  1009. $msg .= $call['function'] . '()';
  1010. if ( $wgCommandLineMode ) {
  1011. $msg .= "\n";
  1012. } else {
  1013. $msg .= "</li>\n";
  1014. }
  1015. }
  1016. if ( $wgCommandLineMode ) {
  1017. $msg .= "\n";
  1018. } else {
  1019. $msg .= "</ul>\n";
  1020. }
  1021. return $msg;
  1022. }
  1023. /* Some generic result counters, pulled out of SearchEngine */
  1024. /**
  1025. * @todo document
  1026. */
  1027. function wfShowingResults( $offset, $limit ) {
  1028. global $wgLang;
  1029. return wfMsgExt(
  1030. 'showingresults',
  1031. array( 'parseinline' ),
  1032. $wgLang->formatNum( $limit ),
  1033. $wgLang->formatNum( $offset + 1 )
  1034. );
  1035. }
  1036. /**
  1037. * @todo document
  1038. */
  1039. function wfShowingResultsNum( $offset, $limit, $num ) {
  1040. global $wgLang;
  1041. return wfMsgExt(
  1042. 'showingresultsnum',
  1043. array( 'parseinline' ),
  1044. $wgLang->formatNum( $limit ),
  1045. $wgLang->formatNum( $offset + 1 ),
  1046. $wgLang->formatNum( $num )
  1047. );
  1048. }
  1049. /**
  1050. * Generate (prev x| next x) (20|50|100...) type links for paging
  1051. * @param $offset String
  1052. * @param $limit Integer
  1053. * @param $link String
  1054. * @param $query String: optional URL query parameter string
  1055. * @param $atend Bool: optional param for specified if this is the last page
  1056. */
  1057. function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
  1058. global $wgLang;
  1059. $fmtLimit = $wgLang->formatNum( $limit );
  1060. // FIXME: Why on earth this needs one message for the text and another one for tooltip??
  1061. # Get prev/next link display text
  1062. $prev = wfMsgExt( 'prevn', array( 'parsemag', 'escape' ), $fmtLimit );
  1063. $next = wfMsgExt( 'nextn', array( 'parsemag', 'escape' ), $fmtLimit );
  1064. # Get prev/next link title text
  1065. $pTitle = wfMsgExt( 'prevn-title', array( 'parsemag', 'escape' ), $fmtLimit );
  1066. $nTitle = wfMsgExt( 'nextn-title', array( 'parsemag', 'escape' ), $fmtLimit );
  1067. # Fetch the title object
  1068. if( is_object( $link ) ) {
  1069. $title =& $link;
  1070. } else {
  1071. $title = Title::newFromText( $link );
  1072. if( is_null( $title ) ) {
  1073. return false;
  1074. }
  1075. }
  1076. # Make 'previous' link
  1077. if( 0 != $offset ) {
  1078. $po = $offset - $limit;
  1079. $po = max( $po, 0 );
  1080. $q = "limit={$limit}&offset={$po}";
  1081. if( $query != '' ) {
  1082. $q .= '&' . $query;
  1083. }
  1084. $plink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
  1085. } else {
  1086. $plink = $prev;
  1087. }
  1088. # Make 'next' link
  1089. $no = $offset + $limit;
  1090. $q = "limit={$limit}&offset={$no}";
  1091. if( $query != '' ) {
  1092. $q .= '&' . $query;
  1093. }
  1094. if( $atend ) {
  1095. $nlink = $next;
  1096. } else {
  1097. $nlink = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
  1098. }
  1099. # Make links to set number of items per page
  1100. $nums = $wgLang->pipeList( array(
  1101. wfNumLink( $offset, 20, $title, $query ),
  1102. wfNumLink( $offset, 50, $title, $query ),
  1103. wfNumLink( $offset, 100, $title, $query ),
  1104. wfNumLink( $offset, 250, $title, $query ),
  1105. wfNumLink( $offset, 500, $title, $query )
  1106. ) );
  1107. return wfMsgHtml( 'viewprevnext', $plink, $nlink, $nums );
  1108. }
  1109. /**
  1110. * Generate links for (20|50|100...) items-per-page links
  1111. * @param $offset String
  1112. * @param $limit Integer
  1113. * @param $title Title
  1114. * @param $query String: optional URL query parameter string
  1115. */
  1116. function wfNumLink( $offset, $limit, $title, $query = '' ) {
  1117. global $wgLang;
  1118. if( $query == '' ) {
  1119. $q = '';
  1120. } else {
  1121. $q = $query.'&';
  1122. }
  1123. $q .= "limit={$limit}&offset={$offset}";
  1124. $fmtLimit = $wgLang->formatNum( $limit );
  1125. $lTitle = wfMsgExt( 'shown-title', array( 'parsemag', 'escape' ), $limit );
  1126. $s = '<a href="' . $title->escapeLocalURL( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
  1127. return $s;
  1128. }
  1129. /**
  1130. * @todo document
  1131. * @todo FIXME: we may want to blacklist some broken browsers
  1132. *
  1133. * @return bool Whereas client accept gzip compression
  1134. */
  1135. function wfClientAcceptsGzip() {
  1136. static $result = null;
  1137. if ( $result === null ) {
  1138. $result = false;
  1139. if( isset( $_SERVER['HTTP_ACCEPT_ENCODING'] ) ) {
  1140. # FIXME: we may want to blacklist some broken browsers
  1141. $m = array();
  1142. if( preg_match(
  1143. '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
  1144. $_SERVER['HTTP_ACCEPT_ENCODING'],
  1145. $m )
  1146. )
  1147. {
  1148. if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) {
  1149. $result = false;
  1150. return $result;
  1151. }
  1152. wfDebug( " accepts gzip\n" );
  1153. $result = true;
  1154. }
  1155. }
  1156. }
  1157. return $result;
  1158. }
  1159. /**
  1160. * Obtain the offset and limit values from the request string;
  1161. * used in special pages
  1162. *
  1163. * @param $deflimit Default limit if none supplied
  1164. * @param $optionname Name of a user preference to check against
  1165. * @return array
  1166. *
  1167. */
  1168. function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
  1169. global $wgRequest;
  1170. return $wgRequest->getLimitOffset( $deflimit, $optionname );
  1171. }
  1172. /**
  1173. * Escapes the given text so that it may be output using addWikiText()
  1174. * without any linking, formatting, etc. making its way through. This
  1175. * is achieved by substituting certain characters with HTML entities.
  1176. * As required by the callers, <nowiki> is not used. It currently does
  1177. * not filter out characters which have special meaning only at the
  1178. * start of a line, such as "*".
  1179. *
  1180. * @param $text String: text to be escaped
  1181. */
  1182. function wfEscapeWikiText( $text ) {
  1183. $text = str_replace(
  1184. array( '[', '|', ']', '\'', 'ISBN ',
  1185. 'RFC ', '://', "\n=", '{{', '}}' ),
  1186. array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;',
  1187. 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;', '&#125;&#125;' ),
  1188. htmlspecialchars( $text )
  1189. );
  1190. return $text;
  1191. }
  1192. /**
  1193. * @todo document
  1194. */
  1195. function wfQuotedPrintable( $string, $charset = '' ) {
  1196. # Probably incomplete; see RFC 2045
  1197. if( empty( $charset ) ) {
  1198. global $wgInputEncoding;
  1199. $charset = $wgInputEncoding;
  1200. }
  1201. $charset = strtoupper( $charset );
  1202. $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
  1203. $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
  1204. $replace = $illegal . '\t ?_';
  1205. if( !preg_match( "/[$illegal]/", $string ) ) {
  1206. return $string;
  1207. }
  1208. $out = "=?$charset?Q?";
  1209. $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
  1210. $out .= '?=';
  1211. return $out;
  1212. }
  1213. /**
  1214. * @todo document
  1215. * @return float
  1216. */
  1217. function wfTime() {
  1218. return microtime( true );
  1219. }
  1220. /**
  1221. * Sets dest to source and returns the original value of dest
  1222. * If source is NULL, it just returns the value, it doesn't set the variable
  1223. */
  1224. function wfSetVar( &$dest, $source ) {
  1225. $temp = $dest;
  1226. if ( !is_null( $source ) ) {
  1227. $dest = $source;
  1228. }
  1229. return $temp;
  1230. }
  1231. /**
  1232. * As for wfSetVar except setting a bit
  1233. */
  1234. function wfSetBit( &$dest, $bit, $state = true ) {
  1235. $temp = (bool)( $dest & $bit );
  1236. if ( !is_null( $state ) ) {
  1237. if ( $state ) {
  1238. $dest |= $bit;
  1239. } else {
  1240. $dest &= ~$bit;
  1241. }
  1242. }
  1243. return $temp;
  1244. }
  1245. /**
  1246. * This function takes two arrays as input, and returns a CGI-style string, e.g.
  1247. * "days=7&limit=100". Options in the first array override options in the second.
  1248. * Options set to "" will not be output.
  1249. */
  1250. function wfArrayToCGI( $array1, $array2 = null ) {
  1251. if ( !is_null( $array2 ) ) {
  1252. $array1 = $array1 + $array2;
  1253. }
  1254. $cgi = '';
  1255. foreach ( $array1 as $key => $value ) {
  1256. if ( $value !== '' ) {
  1257. if ( $cgi != '' ) {
  1258. $cgi .= '&';
  1259. }
  1260. if ( is_array( $value ) ) {
  1261. $firstTime = true;
  1262. foreach ( $value as $v ) {
  1263. $cgi .= ( $firstTime ? '' : '&') .
  1264. urlencode( $key . '[]' ) . '=' .
  1265. urlencode( $v );
  1266. $firstTime = false;
  1267. }
  1268. } else {
  1269. if ( is_object( $value ) ) {
  1270. $value = $value->__toString();
  1271. }
  1272. $cgi .= urlencode( $key ) . '=' .
  1273. urlencode( $value );
  1274. }
  1275. }
  1276. }
  1277. return $cgi;
  1278. }
  1279. /**
  1280. * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
  1281. * its argument and returns the same string in array form. This allows compa-
  1282. * tibility with legacy functions that accept raw query strings instead of nice
  1283. * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
  1284. * valid query strings, or it will explode.
  1285. *
  1286. * @param $query String: query string
  1287. * @return array Array version of input
  1288. */
  1289. function wfCgiToArray( $query ) {
  1290. if( isset( $query[0] ) && $query[0] == '?' ) {
  1291. $query = substr( $query, 1 );
  1292. }
  1293. $bits = explode( '&', $query );
  1294. $ret = array();
  1295. foreach( $bits as $bit ) {
  1296. if( $bit === '' ) {
  1297. continue;
  1298. }
  1299. list( $key, $value ) = explode( '=', $bit );
  1300. $key = urldecode( $key );
  1301. $value = urldecode( $value );
  1302. $ret[$key] = $value;
  1303. }
  1304. return $ret;
  1305. }
  1306. /**
  1307. * Append a query string to an existing URL, which may or may not already
  1308. * have query string parameters already. If so, they will be combined.
  1309. *
  1310. * @param $url String
  1311. * @param $query Mixed: string or associative array
  1312. * @return string
  1313. */
  1314. function wfAppendQuery( $url, $query ) {
  1315. if ( is_array( $query ) ) {
  1316. $query = wfArrayToCGI( $query );
  1317. }
  1318. if( $query != '' ) {
  1319. if( false === strpos( $url, '?' ) ) {
  1320. $url .= '?';
  1321. } else {
  1322. $url .= '&';
  1323. }
  1324. $url .= $query;
  1325. }
  1326. return $url;
  1327. }
  1328. /**
  1329. * Expand a potentially local URL to a fully-qualified URL. Assumes $wgServer
  1330. * and $wgProto are correct.
  1331. *
  1332. * @todo this won't work with current-path-relative URLs
  1333. * like "subdir/foo.html", etc.
  1334. *
  1335. * @param $url String: either fully-qualified or a local path + query
  1336. * @return string Fully-qualified URL
  1337. */
  1338. function wfExpandUrl( $url ) {
  1339. if( substr( $url, 0, 2 ) == '//' ) {
  1340. global $wgProto;
  1341. return $wgProto . ':' . $url;
  1342. } elseif( substr( $url, 0, 1 ) == '/' ) {
  1343. global $wgServer;
  1344. return $wgServer . $url;
  1345. } else {
  1346. return $url;
  1347. }
  1348. }
  1349. /**
  1350. * Windows-compatible version of escapeshellarg()
  1351. * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
  1352. * function puts single quotes in regardless of OS.
  1353. *
  1354. * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
  1355. * earlier distro releases of PHP)
  1356. */
  1357. function wfEscapeShellArg( ) {
  1358. wfInitShellLocale();
  1359. $args = func_get_args();
  1360. $first = true;
  1361. $retVal = '';
  1362. foreach ( $args as $arg ) {
  1363. if ( !$first ) {
  1364. $retVal .= ' ';
  1365. } else {
  1366. $first = false;
  1367. }
  1368. if ( wfIsWindows() ) {
  1369. // Escaping for an MSVC-style command line parser
  1370. // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
  1371. // Double the backslashes before any double quotes. Escape the double quotes.
  1372. $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
  1373. $arg = '';
  1374. $iteration = 0;
  1375. foreach ( $tokens as $token ) {
  1376. if ( $iteration % 2 == 1 ) {
  1377. // Delimiter, a double quote preceded by zero or more slashes
  1378. $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
  1379. } elseif ( $iteration % 4 == 2 ) {
  1380. // ^ in $token will be outside quotes, need to be escaped
  1381. $arg .= str_replace( '^', '^^', $token );
  1382. } else { // $iteration % 4 == 0
  1383. // ^ in $token will appear inside double quotes, so leave as is
  1384. $arg .= $token;
  1385. }
  1386. $iteration++;
  1387. }
  1388. // Double the backslashes before the end of the string, because
  1389. // we will soon add a quote
  1390. $m = array();
  1391. if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
  1392. $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
  1393. }
  1394. // Add surrounding quotes
  1395. $retVal .= '"' . $arg . '"';
  1396. } else {
  1397. $retVal .= escapeshellarg( $arg );
  1398. }
  1399. }
  1400. return $retVal;
  1401. }
  1402. /**
  1403. * wfMerge attempts to merge differences between three texts.
  1404. * Returns true for a clean merge and false for failure or a conflict.
  1405. */
  1406. function wfMerge( $old, $mine, $yours, &$result ) {
  1407. global $wgDiff3;
  1408. # This check may also protect against code injection in
  1409. # case of broken installations.
  1410. wfSuppressWarnings();
  1411. $haveDiff3 = $wgDiff3 && file_exists( $wgDiff3 );
  1412. wfRestoreWarnings();
  1413. if( !$haveDiff3 ) {
  1414. wfDebug( "diff3 not found\n" );
  1415. return false;
  1416. }
  1417. # Make temporary files
  1418. $td = wfTempDir();
  1419. $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
  1420. $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
  1421. $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
  1422. fwrite( $oldtextFile, $old );
  1423. fclose( $oldtextFile );
  1424. fwrite( $mytextFile, $mine );
  1425. fclose( $mytextFile );
  1426. fwrite( $yourtextFile, $yours );
  1427. fclose( $yourtextFile );
  1428. # Check for a conflict
  1429. $cmd = $wgDiff3 . ' -a --overlap-only ' .
  1430. wfEscapeShellArg( $mytextName ) . ' ' .
  1431. wfEscapeShellArg( $oldtextName ) . ' ' .
  1432. wfEscapeShellArg( $yourtextName );
  1433. $handle = popen( $cmd, 'r' );
  1434. if( fgets( $handle, 1024 ) ) {
  1435. $conflict = true;
  1436. } else {
  1437. $conflict = false;
  1438. }
  1439. pclose( $handle );
  1440. # Merge differences
  1441. $cmd = $wgDiff3 . ' -a -e --merge ' .
  1442. wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
  1443. $handle = popen( $cmd, 'r' );
  1444. $result = '';
  1445. do {
  1446. $data = fread( $handle, 8192 );
  1447. if ( strlen( $data ) == 0 ) {
  1448. break;
  1449. }
  1450. $result .= $data;
  1451. } while ( true );
  1452. pclose( $handle );
  1453. unlink( $mytextName );
  1454. unlink( $oldtextName );
  1455. unlink( $yourtextName );
  1456. if ( $result === '' && $old !== '' && !$conflict ) {
  1457. wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
  1458. $conflict = true;
  1459. }
  1460. return !$conflict;
  1461. }
  1462. /**
  1463. * Returns unified plain-text diff of two texts.
  1464. * Useful for machine processing of diffs.
  1465. * @param $before String: the text before the changes.
  1466. * @param $after String: the text after the changes.
  1467. * @param $params String: command-line options for the diff command.
  1468. * @return String: unified diff of $before and $after
  1469. */
  1470. function wfDiff( $before, $after, $params = '-u' ) {
  1471. if ( $before == $after ) {
  1472. return '';
  1473. }
  1474. global $wgDiff;
  1475. wfSuppressWarnings();
  1476. $haveDiff = $wgDiff && file_exists( $wgDiff );
  1477. wfRestoreWarnings();
  1478. # This check may also protect against code injection in
  1479. # case of broken installations.
  1480. if( !$haveDiff ) {
  1481. wfDebug( "diff executable not found\n" );
  1482. $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
  1483. $format = new UnifiedDiffFormatter();
  1484. return $format->format( $diffs );
  1485. }
  1486. # Make temporary files
  1487. $td = wfTempDir();
  1488. $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
  1489. $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
  1490. fwrite( $oldtextFile, $before );
  1491. fclose( $oldtextFile );
  1492. fwrite( $newtextFile, $after );
  1493. fclose( $newtextFile );
  1494. // Get the diff of the two files
  1495. $cmd = "$wgDiff " . $params . ' ' . wfEscapeShellArg( $oldtextName, $newtextName );
  1496. $h = popen( $cmd, 'r' );
  1497. $diff = '';
  1498. do {
  1499. $data = fread( $h, 8192 );
  1500. if ( strlen( $data ) == 0 ) {
  1501. break;
  1502. }
  1503. $diff .= $data;
  1504. } while ( true );
  1505. // Clean up
  1506. pclose( $h );
  1507. unlink( $oldtextName );
  1508. unlink( $newtextName );
  1509. // Kill the --- and +++ lines. They're not useful.
  1510. $diff_lines = explode( "\n", $diff );
  1511. if ( strpos( $diff_lines[0], '---' ) === 0 ) {
  1512. unset( $diff_lines[0] );
  1513. }
  1514. if ( strpos( $diff_lines[1], '+++' ) === 0 ) {
  1515. unset( $diff_lines[1] );
  1516. }
  1517. $diff = implode( "\n", $diff_lines );
  1518. return $diff;
  1519. }
  1520. /**
  1521. * A wrapper around the PHP function var_export().
  1522. * Either print it or add it to the regular output ($wgOut).
  1523. *
  1524. * @param $var A PHP variable to dump.
  1525. */
  1526. function wfVarDump( $var ) {
  1527. global $wgOut;
  1528. $s = str_replace( "\n", "<br />\n", var_export( $var, true ) . "\n" );
  1529. if ( headers_sent() || !@is_object( $wgOut ) ) {
  1530. print $s;
  1531. } else {
  1532. $wgOut->addHTML( $s );
  1533. }
  1534. }
  1535. /**
  1536. * Provide a simple HTTP error.
  1537. */
  1538. function wfHttpError( $code, $label, $desc ) {
  1539. global $wgOut;
  1540. $wgOut->disable();
  1541. header( "HTTP/1.0 $code $label" );
  1542. header( "Status: $code $label" );
  1543. $wgOut->sendCacheControl();
  1544. header( 'Content-type: text/html; charset=utf-8' );
  1545. print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
  1546. '<html><head><title>' .
  1547. htmlspecialchars( $label ) .
  1548. '</title></head><body><h1>' .
  1549. htmlspecialchars( $label ) .
  1550. '</h1><p>' .
  1551. nl2br( htmlspecialchars( $desc ) ) .
  1552. "</p></body></html>\n";
  1553. }
  1554. /**
  1555. * Clear away any user-level output buffers, discarding contents.
  1556. *
  1557. * Suitable for 'starting afresh', for instance when streaming
  1558. * relatively large amounts of data without buffering, or wanting to
  1559. * output image files without ob_gzhandler's compression.
  1560. *
  1561. * The optional $resetGzipEncoding parameter controls suppression of
  1562. * the Content-Encoding header sent by ob_gzhandler; by default it
  1563. * is left. See comments for wfClearOutputBuffers() for why it would
  1564. * be used.
  1565. *
  1566. * Note that some PHP configuratiā€¦

Large files files are truncated, but you can click here to view the full file