PageRenderTime 64ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/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
  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 configuration options may add output buffer
  1567. * layers which cannot be removed; these are left in place.
  1568. *
  1569. * @param $resetGzipEncoding Bool
  1570. */
  1571. function wfResetOutputBuffers( $resetGzipEncoding = true ) {
  1572. if( $resetGzipEncoding ) {
  1573. // Suppress Content-Encoding and Content-Length
  1574. // headers from 1.10+s wfOutputHandler
  1575. global $wgDisableOutputCompression;
  1576. $wgDisableOutputCompression = true;
  1577. }
  1578. while( $status = ob_get_status() ) {
  1579. if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
  1580. // Probably from zlib.output_compression or other
  1581. // PHP-internal setting which can't be removed.
  1582. //
  1583. // Give up, and hope the result doesn't break
  1584. // output behavior.
  1585. break;
  1586. }
  1587. if( !ob_end_clean() ) {
  1588. // Could not remove output buffer handler; abort now
  1589. // to avoid getting in some kind of infinite loop.
  1590. break;
  1591. }
  1592. if( $resetGzipEncoding ) {
  1593. if( $status['name'] == 'ob_gzhandler' ) {
  1594. // Reset the 'Content-Encoding' field set by this handler
  1595. // so we can start fresh.
  1596. if ( function_exists( 'header_remove' ) ) {
  1597. // Available since PHP 5.3.0
  1598. header_remove( 'Content-Encoding' );
  1599. } else {
  1600. // We need to provide a valid content-coding. See bug 28069
  1601. header( 'Content-Encoding: identity' );
  1602. }
  1603. break;
  1604. }
  1605. }
  1606. }
  1607. }
  1608. /**
  1609. * More legible than passing a 'false' parameter to wfResetOutputBuffers():
  1610. *
  1611. * Clear away output buffers, but keep the Content-Encoding header
  1612. * produced by ob_gzhandler, if any.
  1613. *
  1614. * This should be used for HTTP 304 responses, where you need to
  1615. * preserve the Content-Encoding header of the real result, but
  1616. * also need to suppress the output of ob_gzhandler to keep to spec
  1617. * and avoid breaking Firefox in rare cases where the headers and
  1618. * body are broken over two packets.
  1619. */
  1620. function wfClearOutputBuffers() {
  1621. wfResetOutputBuffers( false );
  1622. }
  1623. /**
  1624. * Converts an Accept-* header into an array mapping string values to quality
  1625. * factors
  1626. */
  1627. function wfAcceptToPrefs( $accept, $def = '*/*' ) {
  1628. # No arg means accept anything (per HTTP spec)
  1629. if( !$accept ) {
  1630. return array( $def => 1.0 );
  1631. }
  1632. $prefs = array();
  1633. $parts = explode( ',', $accept );
  1634. foreach( $parts as $part ) {
  1635. # FIXME: doesn't deal with params like 'text/html; level=1'
  1636. @list( $value, $qpart ) = explode( ';', trim( $part ) );
  1637. $match = array();
  1638. if( !isset( $qpart ) ) {
  1639. $prefs[$value] = 1.0;
  1640. } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
  1641. $prefs[$value] = floatval( $match[1] );
  1642. }
  1643. }
  1644. return $prefs;
  1645. }
  1646. /**
  1647. * Checks if a given MIME type matches any of the keys in the given
  1648. * array. Basic wildcards are accepted in the array keys.
  1649. *
  1650. * Returns the matching MIME type (or wildcard) if a match, otherwise
  1651. * NULL if no match.
  1652. *
  1653. * @param $type String
  1654. * @param $avail Array
  1655. * @return string
  1656. * @private
  1657. */
  1658. function mimeTypeMatch( $type, $avail ) {
  1659. if( array_key_exists( $type, $avail ) ) {
  1660. return $type;
  1661. } else {
  1662. $parts = explode( '/', $type );
  1663. if( array_key_exists( $parts[0] . '/*', $avail ) ) {
  1664. return $parts[0] . '/*';
  1665. } elseif( array_key_exists( '*/*', $avail ) ) {
  1666. return '*/*';
  1667. } else {
  1668. return null;
  1669. }
  1670. }
  1671. }
  1672. /**
  1673. * Returns the 'best' match between a client's requested internet media types
  1674. * and the server's list of available types. Each list should be an associative
  1675. * array of type to preference (preference is a float between 0.0 and 1.0).
  1676. * Wildcards in the types are acceptable.
  1677. *
  1678. * @param $cprefs Array: client's acceptable type list
  1679. * @param $sprefs Array: server's offered types
  1680. * @return string
  1681. *
  1682. * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
  1683. * XXX: generalize to negotiate other stuff
  1684. */
  1685. function wfNegotiateType( $cprefs, $sprefs ) {
  1686. $combine = array();
  1687. foreach( array_keys($sprefs) as $type ) {
  1688. $parts = explode( '/', $type );
  1689. if( $parts[1] != '*' ) {
  1690. $ckey = mimeTypeMatch( $type, $cprefs );
  1691. if( $ckey ) {
  1692. $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
  1693. }
  1694. }
  1695. }
  1696. foreach( array_keys( $cprefs ) as $type ) {
  1697. $parts = explode( '/', $type );
  1698. if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
  1699. $skey = mimeTypeMatch( $type, $sprefs );
  1700. if( $skey ) {
  1701. $combine[$type] = $sprefs[$skey] * $cprefs[$type];
  1702. }
  1703. }
  1704. }
  1705. $bestq = 0;
  1706. $besttype = null;
  1707. foreach( array_keys( $combine ) as $type ) {
  1708. if( $combine[$type] > $bestq ) {
  1709. $besttype = $type;
  1710. $bestq = $combine[$type];
  1711. }
  1712. }
  1713. return $besttype;
  1714. }
  1715. /**
  1716. * Array lookup
  1717. * Returns an array where the values in the first array are replaced by the
  1718. * values in the second array with the corresponding keys
  1719. *
  1720. * @return array
  1721. */
  1722. function wfArrayLookup( $a, $b ) {
  1723. return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
  1724. }
  1725. /**
  1726. * Convenience function; returns MediaWiki timestamp for the present time.
  1727. * @return string
  1728. */
  1729. function wfTimestampNow() {
  1730. # return NOW
  1731. return wfTimestamp( TS_MW, time() );
  1732. }
  1733. /**
  1734. * Reference-counted warning suppression
  1735. */
  1736. function wfSuppressWarnings( $end = false ) {
  1737. static $suppressCount = 0;
  1738. static $originalLevel = false;
  1739. if ( $end ) {
  1740. if ( $suppressCount ) {
  1741. --$suppressCount;
  1742. if ( !$suppressCount ) {
  1743. error_reporting( $originalLevel );
  1744. }
  1745. }
  1746. } else {
  1747. if ( !$suppressCount ) {
  1748. $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE ) );
  1749. }
  1750. ++$suppressCount;
  1751. }
  1752. }
  1753. /**
  1754. * Restore error level to previous value
  1755. */
  1756. function wfRestoreWarnings() {
  1757. wfSuppressWarnings( true );
  1758. }
  1759. # Autodetect, convert and provide timestamps of various types
  1760. /**
  1761. * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
  1762. */
  1763. define( 'TS_UNIX', 0 );
  1764. /**
  1765. * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
  1766. */
  1767. define( 'TS_MW', 1 );
  1768. /**
  1769. * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
  1770. */
  1771. define( 'TS_DB', 2 );
  1772. /**
  1773. * RFC 2822 format, for E-mail and HTTP headers
  1774. */
  1775. define( 'TS_RFC2822', 3 );
  1776. /**
  1777. * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
  1778. *
  1779. * This is used by Special:Export
  1780. */
  1781. define( 'TS_ISO_8601', 4 );
  1782. /**
  1783. * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
  1784. *
  1785. * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
  1786. * DateTime tag and page 36 for the DateTimeOriginal and
  1787. * DateTimeDigitized tags.
  1788. */
  1789. define( 'TS_EXIF', 5 );
  1790. /**
  1791. * Oracle format time.
  1792. */
  1793. define( 'TS_ORACLE', 6 );
  1794. /**
  1795. * Postgres format time.
  1796. */
  1797. define( 'TS_POSTGRES', 7 );
  1798. /**
  1799. * DB2 format time
  1800. */
  1801. define( 'TS_DB2', 8 );
  1802. /**
  1803. * ISO 8601 basic format with no timezone: 19860209T200000Z
  1804. *
  1805. * This is used by ResourceLoader
  1806. */
  1807. define( 'TS_ISO_8601_BASIC', 9 );
  1808. /**
  1809. * @param $outputtype Mixed: A timestamp in one of the supported formats, the
  1810. * function will autodetect which format is supplied and act
  1811. * accordingly.
  1812. * @param $ts Mixed: the timestamp to convert or 0 for the current timestamp
  1813. * @return Mixed: String / false The same date in the format specified in $outputtype or false
  1814. */
  1815. function wfTimestamp( $outputtype = TS_UNIX, $ts = 0 ) {
  1816. $uts = 0;
  1817. $da = array();
  1818. $strtime = '';
  1819. if ( !$ts ) { // We want to catch 0, '', null... but not date strings starting with a letter.
  1820. $uts = time();
  1821. $strtime = "@$uts";
  1822. } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
  1823. # TS_DB
  1824. } elseif ( preg_match( '/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D', $ts, $da ) ) {
  1825. # TS_EXIF
  1826. } elseif ( preg_match( '/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D', $ts, $da ) ) {
  1827. # TS_MW
  1828. } elseif ( preg_match( '/^-?\d{1,13}$/D', $ts ) ) {
  1829. # TS_UNIX
  1830. $uts = $ts;
  1831. $strtime = "@$ts"; // Undocumented?
  1832. } elseif ( preg_match( '/^\d{2}-\d{2}-\d{4} \d{2}:\d{2}:\d{2}.\d{6}$/', $ts ) ) {
  1833. # TS_ORACLE // session altered to DD-MM-YYYY HH24:MI:SS.FF6
  1834. $strtime = preg_replace( '/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
  1835. str_replace( '+00:00', 'UTC', $ts ) );
  1836. } elseif ( preg_match( '/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
  1837. # TS_ISO_8601
  1838. } elseif ( preg_match( '/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(?:\.*\d*)?Z$/', $ts, $da ) ) {
  1839. #TS_ISO_8601_BASIC
  1840. } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/', $ts, $da ) ) {
  1841. # TS_POSTGRES
  1842. } elseif ( preg_match( '/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/', $ts, $da ) ) {
  1843. # TS_POSTGRES
  1844. } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.\d\d\d$/',$ts,$da)) {
  1845. # TS_DB2
  1846. } elseif ( preg_match( '/^[ \t\r\n]*([A-Z][a-z]{2},[ \t\r\n]*)?' . # Day of week
  1847. '\d\d?[ \t\r\n]*[A-Z][a-z]{2}[ \t\r\n]*\d{2}(?:\d{2})?' . # dd Mon yyyy
  1848. '[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d[ \t\r\n]*:[ \t\r\n]*\d\d/S', $ts ) ) { # hh:mm:ss
  1849. # TS_RFC2822, accepting a trailing comment. See http://www.squid-cache.org/mail-archive/squid-users/200307/0122.html / r77171
  1850. # The regex is a superset of rfc2822 for readability
  1851. $strtime = strtok( $ts, ';' );
  1852. } elseif ( preg_match( '/^[A-Z][a-z]{5,8}, \d\d-[A-Z][a-z]{2}-\d{2} \d\d:\d\d:\d\d/', $ts ) ) {
  1853. # TS_RFC850
  1854. $strtime = $ts;
  1855. } elseif ( preg_match( '/^[A-Z][a-z]{2} [A-Z][a-z]{2} +\d{1,2} \d\d:\d\d:\d\d \d{4}/', $ts ) ) {
  1856. # asctime
  1857. $strtime = $ts;
  1858. } else {
  1859. # Bogus value...
  1860. wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
  1861. return false;
  1862. }
  1863. static $formats = array(
  1864. TS_UNIX => 'U',
  1865. TS_MW => 'YmdHis',
  1866. TS_DB => 'Y-m-d H:i:s',
  1867. TS_ISO_8601 => 'Y-m-d\TH:i:s\Z',
  1868. TS_ISO_8601_BASIC => 'Ymd\THis\Z',
  1869. TS_EXIF => 'Y:m:d H:i:s', // This shouldn't ever be used, but is included for completeness
  1870. TS_RFC2822 => 'D, d M Y H:i:s',
  1871. TS_ORACLE => 'd-m-Y H:i:s.000000', // Was 'd-M-y h.i.s A' . ' +00:00' before r51500
  1872. TS_POSTGRES => 'Y-m-d H:i:s',
  1873. TS_DB2 => 'Y-m-d H:i:s',
  1874. );
  1875. if ( !isset( $formats[$outputtype] ) ) {
  1876. throw new MWException( 'wfTimestamp() called with illegal output type.' );
  1877. }
  1878. if ( function_exists( "date_create" ) ) {
  1879. if ( count( $da ) ) {
  1880. $ds = sprintf("%04d-%02d-%02dT%02d:%02d:%02d.00+00:00",
  1881. (int)$da[1], (int)$da[2], (int)$da[3],
  1882. (int)$da[4], (int)$da[5], (int)$da[6]);
  1883. $d = date_create( $ds, new DateTimeZone( 'GMT' ) );
  1884. } elseif ( $strtime ) {
  1885. $d = date_create( $strtime, new DateTimeZone( 'GMT' ) );
  1886. } else {
  1887. return false;
  1888. }
  1889. if ( !$d ) {
  1890. wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
  1891. return false;
  1892. }
  1893. $output = $d->format( $formats[$outputtype] );
  1894. } else {
  1895. if ( count( $da ) ) {
  1896. // Warning! gmmktime() acts oddly if the month or day is set to 0
  1897. // We may want to handle that explicitly at some point
  1898. $uts = gmmktime( (int)$da[4], (int)$da[5], (int)$da[6],
  1899. (int)$da[2], (int)$da[3], (int)$da[1] );
  1900. } elseif ( $strtime ) {
  1901. $uts = strtotime( $strtime );
  1902. }
  1903. if ( $uts === false ) {
  1904. wfDebug("wfTimestamp() can't parse the timestamp (non 32-bit time? Update php): $outputtype; $ts\n");
  1905. return false;
  1906. }
  1907. if ( TS_UNIX == $outputtype ) {
  1908. return $uts;
  1909. }
  1910. $output = gmdate( $formats[$outputtype], $uts );
  1911. }
  1912. if ( ( $outputtype == TS_RFC2822 ) || ( $outputtype == TS_POSTGRES ) ) {
  1913. $output .= ' GMT';
  1914. }
  1915. return $output;
  1916. }
  1917. /**
  1918. * Return a formatted timestamp, or null if input is null.
  1919. * For dealing with nullable timestamp columns in the database.
  1920. * @param $outputtype Integer
  1921. * @param $ts String
  1922. * @return String
  1923. */
  1924. function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
  1925. if( is_null( $ts ) ) {
  1926. return null;
  1927. } else {
  1928. return wfTimestamp( $outputtype, $ts );
  1929. }
  1930. }
  1931. /**
  1932. * Check if the operating system is Windows
  1933. *
  1934. * @return Bool: true if it's Windows, False otherwise.
  1935. */
  1936. function wfIsWindows() {
  1937. static $isWindows = null;
  1938. if ( $isWindows === null ) {
  1939. $isWindows = substr( php_uname(), 0, 7 ) == 'Windows';
  1940. }
  1941. return $isWindows;
  1942. }
  1943. /**
  1944. * Swap two variables
  1945. */
  1946. function swap( &$x, &$y ) {
  1947. $z = $x;
  1948. $x = $y;
  1949. $y = $z;
  1950. }
  1951. function wfGetCachedNotice( $name ) {
  1952. global $wgOut, $wgRenderHashAppend, $parserMemc;
  1953. $fname = 'wfGetCachedNotice';
  1954. wfProfileIn( $fname );
  1955. $needParse = false;
  1956. if( $name === 'default' ) {
  1957. // special case
  1958. global $wgSiteNotice;
  1959. $notice = $wgSiteNotice;
  1960. if( empty( $notice ) ) {
  1961. wfProfileOut( $fname );
  1962. return false;
  1963. }
  1964. } else {
  1965. $notice = wfMsgForContentNoTrans( $name );
  1966. if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
  1967. wfProfileOut( $fname );
  1968. return( false );
  1969. }
  1970. }
  1971. // Use the extra hash appender to let eg SSL variants separately cache.
  1972. $key = wfMemcKey( $name . $wgRenderHashAppend );
  1973. $cachedNotice = $parserMemc->get( $key );
  1974. if( is_array( $cachedNotice ) ) {
  1975. if( md5( $notice ) == $cachedNotice['hash'] ) {
  1976. $notice = $cachedNotice['html'];
  1977. } else {
  1978. $needParse = true;
  1979. }
  1980. } else {
  1981. $needParse = true;
  1982. }
  1983. if( $needParse ) {
  1984. if( is_object( $wgOut ) ) {
  1985. $parsed = $wgOut->parse( $notice );
  1986. $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
  1987. $notice = $parsed;
  1988. } else {
  1989. wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' . "\n" );
  1990. $notice = '';
  1991. }
  1992. }
  1993. $notice = '<div id="localNotice">' .$notice . '</div>';
  1994. wfProfileOut( $fname );
  1995. return $notice;
  1996. }
  1997. function wfGetNamespaceNotice() {
  1998. global $wgTitle;
  1999. # Paranoia
  2000. if ( !isset( $wgTitle ) || !is_object( $wgTitle ) ) {
  2001. return '';
  2002. }
  2003. $fname = 'wfGetNamespaceNotice';
  2004. wfProfileIn( $fname );
  2005. $key = 'namespacenotice-' . $wgTitle->getNsText();
  2006. $namespaceNotice = wfGetCachedNotice( $key );
  2007. if ( $namespaceNotice && substr( $namespaceNotice, 0, 7 ) != '<p>&lt;' ) {
  2008. $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . '</div>';
  2009. } else {
  2010. $namespaceNotice = '';
  2011. }
  2012. wfProfileOut( $fname );
  2013. return $namespaceNotice;
  2014. }
  2015. function wfGetSiteNotice() {
  2016. global $wgUser;
  2017. $fname = 'wfGetSiteNotice';
  2018. wfProfileIn( $fname );
  2019. $siteNotice = '';
  2020. if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
  2021. if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
  2022. $siteNotice = wfGetCachedNotice( 'sitenotice' );
  2023. } else {
  2024. $anonNotice = wfGetCachedNotice( 'anonnotice' );
  2025. if( !$anonNotice ) {
  2026. $siteNotice = wfGetCachedNotice( 'sitenotice' );
  2027. } else {
  2028. $siteNotice = $anonNotice;
  2029. }
  2030. }
  2031. if( !$siteNotice ) {
  2032. $siteNotice = wfGetCachedNotice( 'default' );
  2033. }
  2034. }
  2035. wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
  2036. wfProfileOut( $fname );
  2037. return $siteNotice;
  2038. }
  2039. /**
  2040. * BC wrapper for MimeMagic::singleton()
  2041. * @deprecated No longer needed as of 1.17 (r68836).
  2042. */
  2043. function &wfGetMimeMagic() {
  2044. wfDeprecated( __FUNCTION__ );
  2045. return MimeMagic::singleton();
  2046. }
  2047. /**
  2048. * Tries to get the system directory for temporary files. The TMPDIR, TMP, and
  2049. * TEMP environment variables are then checked in sequence, and if none are set
  2050. * try sys_get_temp_dir() for PHP >= 5.2.1. All else fails, return /tmp for Unix
  2051. * or C:\Windows\Temp for Windows and hope for the best.
  2052. * It is common to call it with tempnam().
  2053. *
  2054. * NOTE: When possible, use instead the tmpfile() function to create
  2055. * temporary files to avoid race conditions on file creation, etc.
  2056. *
  2057. * @return String
  2058. */
  2059. function wfTempDir() {
  2060. foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
  2061. $tmp = getenv( $var );
  2062. if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
  2063. return $tmp;
  2064. }
  2065. }
  2066. if( function_exists( 'sys_get_temp_dir' ) ) {
  2067. return sys_get_temp_dir();
  2068. }
  2069. # Usual defaults
  2070. return wfIsWindows() ? 'C:\Windows\Temp' : '/tmp';
  2071. }
  2072. /**
  2073. * Make directory, and make all parent directories if they don't exist
  2074. *
  2075. * @param $dir String: full path to directory to create
  2076. * @param $mode Integer: chmod value to use, default is $wgDirectoryMode
  2077. * @param $caller String: optional caller param for debugging.
  2078. * @return bool
  2079. */
  2080. function wfMkdirParents( $dir, $mode = null, $caller = null ) {
  2081. global $wgDirectoryMode;
  2082. if ( !is_null( $caller ) ) {
  2083. wfDebug( "$caller: called wfMkdirParents($dir)" );
  2084. }
  2085. if( strval( $dir ) === '' || file_exists( $dir ) ) {
  2086. return true;
  2087. }
  2088. $dir = str_replace( array( '\\', '/' ), DIRECTORY_SEPARATOR, $dir );
  2089. if ( is_null( $mode ) ) {
  2090. $mode = $wgDirectoryMode;
  2091. }
  2092. // Turn off the normal warning, we're doing our own below
  2093. wfSuppressWarnings();
  2094. $ok = mkdir( $dir, $mode, true ); // PHP5 <3
  2095. wfRestoreWarnings();
  2096. if( !$ok ) {
  2097. // PHP doesn't report the path in its warning message, so add our own to aid in diagnosis.
  2098. trigger_error( __FUNCTION__ . ": failed to mkdir \"$dir\" mode $mode", E_USER_WARNING );
  2099. }
  2100. return $ok;
  2101. }
  2102. /**
  2103. * Increment a statistics counter
  2104. */
  2105. function wfIncrStats( $key ) {
  2106. global $wgStatsMethod;
  2107. if( $wgStatsMethod == 'udp' ) {
  2108. global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
  2109. static $socket;
  2110. if ( !$socket ) {
  2111. $socket = socket_create( AF_INET, SOCK_DGRAM, SOL_UDP );
  2112. $statline = "stats/{$wgDBname} - 1 1 1 1 1 -total\n";
  2113. socket_sendto(
  2114. $socket,
  2115. $statline,
  2116. strlen( $statline ),
  2117. 0,
  2118. $wgUDPProfilerHost,
  2119. $wgUDPProfilerPort
  2120. );
  2121. }
  2122. $statline = "stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
  2123. wfSuppressWarnings();
  2124. socket_sendto(
  2125. $socket,
  2126. $statline,
  2127. strlen( $statline ),
  2128. 0,
  2129. $wgUDPProfilerHost,
  2130. $wgUDPProfilerPort
  2131. );
  2132. wfRestoreWarnings();
  2133. } elseif( $wgStatsMethod == 'cache' ) {
  2134. global $wgMemc;
  2135. $key = wfMemcKey( 'stats', $key );
  2136. if ( is_null( $wgMemc->incr( $key ) ) ) {
  2137. $wgMemc->add( $key, 1 );
  2138. }
  2139. } else {
  2140. // Disabled
  2141. }
  2142. }
  2143. /**
  2144. * @param $nr Mixed: the number to format
  2145. * @param $acc Integer: the number of digits after the decimal point, default 2
  2146. * @param $round Boolean: whether or not to round the value, default true
  2147. * @return float
  2148. */
  2149. function wfPercent( $nr, $acc = 2, $round = true ) {
  2150. $ret = sprintf( "%.${acc}f", $nr );
  2151. return $round ? round( $ret, $acc ) . '%' : "$ret%";
  2152. }
  2153. /**
  2154. * Encrypt a username/password.
  2155. *
  2156. * @param $userid Integer: ID of the user
  2157. * @param $password String: password of the user
  2158. * @return String: hashed password
  2159. * @deprecated Use User::crypt() or User::oldCrypt() instead
  2160. */
  2161. function wfEncryptPassword( $userid, $password ) {
  2162. wfDeprecated(__FUNCTION__);
  2163. # Just wrap around User::oldCrypt()
  2164. return User::oldCrypt( $password, $userid );
  2165. }
  2166. /**
  2167. * Appends to second array if $value differs from that in $default
  2168. */
  2169. function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
  2170. if ( is_null( $changed ) ) {
  2171. throw new MWException( 'GlobalFunctions::wfAppendToArrayIfNotDefault got null' );
  2172. }
  2173. if ( $default[$key] !== $value ) {
  2174. $changed[$key] = $value;
  2175. }
  2176. }
  2177. /**
  2178. * Since wfMsg() and co suck, they don't return false if the message key they
  2179. * looked up didn't exist but a XHTML string, this function checks for the
  2180. * nonexistance of messages by looking at wfMsg() output
  2181. *
  2182. * @param $key String: the message key looked up
  2183. * @return Boolean True if the message *doesn't* exist.
  2184. */
  2185. function wfEmptyMsg( $key ) {
  2186. global $wgMessageCache;
  2187. return $wgMessageCache->get( $key, /*useDB*/true, /*content*/false ) === false;
  2188. }
  2189. /**
  2190. * Find out whether or not a mixed variable exists in a string
  2191. *
  2192. * @param $needle String
  2193. * @param $str String
  2194. * @return Boolean
  2195. */
  2196. function in_string( $needle, $str ) {
  2197. return strpos( $str, $needle ) !== false;
  2198. }
  2199. function wfSpecialList( $page, $details ) {
  2200. global $wgContLang;
  2201. $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : '';
  2202. return $page . $details;
  2203. }
  2204. /**
  2205. * Returns a regular expression of url protocols
  2206. *
  2207. * @return String
  2208. */
  2209. function wfUrlProtocols() {
  2210. global $wgUrlProtocols;
  2211. static $retval = null;
  2212. if ( !is_null( $retval ) ) {
  2213. return $retval;
  2214. }
  2215. // Support old-style $wgUrlProtocols strings, for backwards compatibility
  2216. // with LocalSettings files from 1.5
  2217. if ( is_array( $wgUrlProtocols ) ) {
  2218. $protocols = array();
  2219. foreach ( $wgUrlProtocols as $protocol ) {
  2220. $protocols[] = preg_quote( $protocol, '/' );
  2221. }
  2222. $retval = implode( '|', $protocols );
  2223. } else {
  2224. $retval = $wgUrlProtocols;
  2225. }
  2226. return $retval;
  2227. }
  2228. /**
  2229. * Safety wrapper around ini_get() for boolean settings.
  2230. * The values returned from ini_get() are pre-normalized for settings
  2231. * set via php.ini or php_flag/php_admin_flag... but *not*
  2232. * for those set via php_value/php_admin_value.
  2233. *
  2234. * It's fairly common for people to use php_value instead of php_flag,
  2235. * which can leave you with an 'off' setting giving a false positive
  2236. * for code that just takes the ini_get() return value as a boolean.
  2237. *
  2238. * To make things extra interesting, setting via php_value accepts
  2239. * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
  2240. * Unrecognized values go false... again opposite PHP's own coercion
  2241. * from string to bool.
  2242. *
  2243. * Luckily, 'properly' set settings will always come back as '0' or '1',
  2244. * so we only have to worry about them and the 'improper' settings.
  2245. *
  2246. * I frickin' hate PHP... :P
  2247. *
  2248. * @param $setting String
  2249. * @return Bool
  2250. */
  2251. function wfIniGetBool( $setting ) {
  2252. $val = ini_get( $setting );
  2253. // 'on' and 'true' can't have whitespace around them, but '1' can.
  2254. return strtolower( $val ) == 'on'
  2255. || strtolower( $val ) == 'true'
  2256. || strtolower( $val ) == 'yes'
  2257. || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
  2258. }
  2259. /**
  2260. * Wrapper function for PHP's dl(). This doesn't work in most situations from
  2261. * PHP 5.3 onward, and is usually disabled in shared environments anyway.
  2262. *
  2263. * @param $extension String A PHP extension. The file suffix (.so or .dll)
  2264. * should be omitted
  2265. * @return Bool - Whether or not the extension is loaded
  2266. */
  2267. function wfDl( $extension ) {
  2268. if( extension_loaded( $extension ) ) {
  2269. return true;
  2270. }
  2271. $canDl = ( function_exists( 'dl' ) && is_callable( 'dl' )
  2272. && wfIniGetBool( 'enable_dl' ) && !wfIniGetBool( 'safe_mode' ) );
  2273. if( $canDl ) {
  2274. wfSuppressWarnings();
  2275. dl( $extension . '.' . PHP_SHLIB_SUFFIX );
  2276. wfRestoreWarnings();
  2277. }
  2278. return extension_loaded( $extension );
  2279. }
  2280. /**
  2281. * Execute a shell command, with time and memory limits mirrored from the PHP
  2282. * configuration if supported.
  2283. * @param $cmd String Command line, properly escaped for shell.
  2284. * @param &$retval optional, will receive the program's exit code.
  2285. * (non-zero is usually failure)
  2286. * @param $environ Array optional environment variables which should be
  2287. * added to the executed command environment.
  2288. * @return collected stdout as a string (trailing newlines stripped)
  2289. */
  2290. function wfShellExec( $cmd, &$retval = null, $environ = array() ) {
  2291. global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
  2292. static $disabled;
  2293. if ( is_null( $disabled ) ) {
  2294. $disabled = false;
  2295. if( wfIniGetBool( 'safe_mode' ) ) {
  2296. wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
  2297. $disabled = 'safemode';
  2298. } else {
  2299. $functions = explode( ',', ini_get( 'disable_functions' ) );
  2300. $functions = array_map( 'trim', $functions );
  2301. $functions = array_map( 'strtolower', $functions );
  2302. if ( in_array( 'passthru', $functions ) ) {
  2303. wfDebug( "passthru is in disabled_functions\n" );
  2304. $disabled = 'passthru';
  2305. }
  2306. }
  2307. }
  2308. if ( $disabled ) {
  2309. $retval = 1;
  2310. return $disabled == 'safemode' ?
  2311. 'Unable to run external programs in safe mode.' :
  2312. 'Unable to run external programs, passthru() is disabled.';
  2313. }
  2314. wfInitShellLocale();
  2315. $envcmd = '';
  2316. foreach( $environ as $k => $v ) {
  2317. if ( wfIsWindows() ) {
  2318. /* Surrounding a set in quotes (method used by wfEscapeShellArg) makes the quotes themselves
  2319. * appear in the environment variable, so we must use carat escaping as documented in
  2320. * http://technet.microsoft.com/en-us/library/cc723564.aspx
  2321. * Note however that the quote isn't listed there, but is needed, and the parentheses
  2322. * are listed there but doesn't appear to need it.
  2323. */
  2324. $envcmd .= "set $k=" . preg_replace( '/([&|()<>^"])/', '^\\1', $v ) . '&& ';
  2325. } else {
  2326. /* Assume this is a POSIX shell, thus required to accept variable assignments before the command
  2327. * http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_09_01
  2328. */
  2329. $envcmd .= "$k=" . escapeshellarg( $v ) . ' ';
  2330. }
  2331. }
  2332. $cmd = $envcmd . $cmd;
  2333. if ( wfIsWindows() ) {
  2334. if ( version_compare( PHP_VERSION, '5.3.0', '<' ) && /* Fixed in 5.3.0 :) */
  2335. ( version_compare( PHP_VERSION, '5.2.1', '>=' ) || php_uname( 's' ) == 'Windows NT' ) )
  2336. {
  2337. # Hack to work around PHP's flawed invocation of cmd.exe
  2338. # http://news.php.net/php.internals/21796
  2339. # Windows 9x doesn't accept any kind of quotes
  2340. $cmd = '"' . $cmd . '"';
  2341. }
  2342. } elseif ( php_uname( 's' ) == 'Linux' ) {
  2343. $time = intval( $wgMaxShellTime );
  2344. $mem = intval( $wgMaxShellMemory );
  2345. $filesize = intval( $wgMaxShellFileSize );
  2346. if ( $time > 0 && $mem > 0 ) {
  2347. $script = "$IP/bin/ulimit4.sh";
  2348. if ( is_executable( $script ) ) {
  2349. $cmd = '/bin/bash ' . escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
  2350. }
  2351. }
  2352. }
  2353. wfDebug( "wfShellExec: $cmd\n" );
  2354. $retval = 1; // error by default?
  2355. ob_start();
  2356. passthru( $cmd, $retval );
  2357. $output = ob_get_contents();
  2358. ob_end_clean();
  2359. if ( $retval == 127 ) {
  2360. wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
  2361. }
  2362. return $output;
  2363. }
  2364. /**
  2365. * Workaround for http://bugs.php.net/bug.php?id=45132
  2366. * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
  2367. */
  2368. function wfInitShellLocale() {
  2369. static $done = false;
  2370. if ( $done ) {
  2371. return;
  2372. }
  2373. $done = true;
  2374. global $wgShellLocale;
  2375. if ( !wfIniGetBool( 'safe_mode' ) ) {
  2376. putenv( "LC_CTYPE=$wgShellLocale" );
  2377. setlocale( LC_CTYPE, $wgShellLocale );
  2378. }
  2379. }
  2380. /**
  2381. * This function works like "use VERSION" in Perl, the program will die with a
  2382. * backtrace if the current version of PHP is less than the version provided
  2383. *
  2384. * This is useful for extensions which due to their nature are not kept in sync
  2385. * with releases, and might depend on other versions of PHP than the main code
  2386. *
  2387. * Note: PHP might die due to parsing errors in some cases before it ever
  2388. * manages to call this function, such is life
  2389. *
  2390. * @see perldoc -f use
  2391. *
  2392. * @param $req_ver Mixed: the version to check, can be a string, an integer, or
  2393. * a float
  2394. */
  2395. function wfUsePHP( $req_ver ) {
  2396. $php_ver = PHP_VERSION;
  2397. if ( version_compare( $php_ver, (string)$req_ver, '<' ) ) {
  2398. throw new MWException( "PHP $req_ver required--this is only $php_ver" );
  2399. }
  2400. }
  2401. /**
  2402. * This function works like "use VERSION" in Perl except it checks the version
  2403. * of MediaWiki, the program will die with a backtrace if the current version
  2404. * of MediaWiki is less than the version provided.
  2405. *
  2406. * This is useful for extensions which due to their nature are not kept in sync
  2407. * with releases
  2408. *
  2409. * @see perldoc -f use
  2410. *
  2411. * @param $req_ver Mixed: the version to check, can be a string, an integer, or
  2412. * a float
  2413. */
  2414. function wfUseMW( $req_ver ) {
  2415. global $wgVersion;
  2416. if ( version_compare( $wgVersion, (string)$req_ver, '<' ) ) {
  2417. throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
  2418. }
  2419. }
  2420. /**
  2421. * Return the final portion of a pathname.
  2422. * Reimplemented because PHP5's basename() is buggy with multibyte text.
  2423. * http://bugs.php.net/bug.php?id=33898
  2424. *
  2425. * PHP's basename() only considers '\' a pathchar on Windows and Netware.
  2426. * We'll consider it so always, as we don't want \s in our Unix paths either.
  2427. *
  2428. * @param $path String
  2429. * @param $suffix String: to remove if present
  2430. * @return String
  2431. */
  2432. function wfBaseName( $path, $suffix = '' ) {
  2433. $encSuffix = ( $suffix == '' )
  2434. ? ''
  2435. : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
  2436. $matches = array();
  2437. if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
  2438. return $matches[1];
  2439. } else {
  2440. return '';
  2441. }
  2442. }
  2443. /**
  2444. * Generate a relative path name to the given file.
  2445. * May explode on non-matching case-insensitive paths,
  2446. * funky symlinks, etc.
  2447. *
  2448. * @param $path String: absolute destination path including target filename
  2449. * @param $from String: Absolute source path, directory only
  2450. * @return String
  2451. */
  2452. function wfRelativePath( $path, $from ) {
  2453. // Normalize mixed input on Windows...
  2454. $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
  2455. $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
  2456. // Trim trailing slashes -- fix for drive root
  2457. $path = rtrim( $path, DIRECTORY_SEPARATOR );
  2458. $from = rtrim( $from, DIRECTORY_SEPARATOR );
  2459. $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
  2460. $against = explode( DIRECTORY_SEPARATOR, $from );
  2461. if( $pieces[0] !== $against[0] ) {
  2462. // Non-matching Windows drive letters?
  2463. // Return a full path.
  2464. return $path;
  2465. }
  2466. // Trim off common prefix
  2467. while( count( $pieces ) && count( $against )
  2468. && $pieces[0] == $against[0] ) {
  2469. array_shift( $pieces );
  2470. array_shift( $against );
  2471. }
  2472. // relative dots to bump us to the parent
  2473. while( count( $against ) ) {
  2474. array_unshift( $pieces, '..' );
  2475. array_shift( $against );
  2476. }
  2477. array_push( $pieces, wfBaseName( $path ) );
  2478. return implode( DIRECTORY_SEPARATOR, $pieces );
  2479. }
  2480. /**
  2481. * Backwards array plus for people who haven't bothered to read the PHP manual
  2482. * XXX: will not darn your socks for you.
  2483. *
  2484. * @param $array1 Array
  2485. * @param [$array2, [...]] Arrays
  2486. * @return Array
  2487. */
  2488. function wfArrayMerge( $array1/* ... */ ) {
  2489. $args = func_get_args();
  2490. $args = array_reverse( $args, true );
  2491. $out = array();
  2492. foreach ( $args as $arg ) {
  2493. $out += $arg;
  2494. }
  2495. return $out;
  2496. }
  2497. /**
  2498. * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
  2499. * e.g.
  2500. * wfMergeErrorArrays(
  2501. * array( array( 'x' ) ),
  2502. * array( array( 'x', '2' ) ),
  2503. * array( array( 'x' ) ),
  2504. * array( array( 'y') )
  2505. * );
  2506. * returns:
  2507. * array(
  2508. * array( 'x', '2' ),
  2509. * array( 'x' ),
  2510. * array( 'y' )
  2511. * )
  2512. */
  2513. function wfMergeErrorArrays( /*...*/ ) {
  2514. $args = func_get_args();
  2515. $out = array();
  2516. foreach ( $args as $errors ) {
  2517. foreach ( $errors as $params ) {
  2518. # FIXME: sometimes get nested arrays for $params,
  2519. # which leads to E_NOTICEs
  2520. $spec = implode( "\t", $params );
  2521. $out[$spec] = $params;
  2522. }
  2523. }
  2524. return array_values( $out );
  2525. }
  2526. /**
  2527. * parse_url() work-alike, but non-broken. Differences:
  2528. *
  2529. * 1) Does not raise warnings on bad URLs (just returns false)
  2530. * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
  2531. * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
  2532. *
  2533. * @param $url String: a URL to parse
  2534. * @return Array: bits of the URL in an associative array, per PHP docs
  2535. */
  2536. function wfParseUrl( $url ) {
  2537. global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
  2538. wfSuppressWarnings();
  2539. $bits = parse_url( $url );
  2540. wfRestoreWarnings();
  2541. if ( !$bits ) {
  2542. return false;
  2543. }
  2544. // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
  2545. if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
  2546. $bits['delimiter'] = '://';
  2547. } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
  2548. $bits['delimiter'] = ':';
  2549. // parse_url detects for news: and mailto: the host part of an url as path
  2550. // We have to correct this wrong detection
  2551. if ( isset( $bits['path'] ) ) {
  2552. $bits['host'] = $bits['path'];
  2553. $bits['path'] = '';
  2554. }
  2555. } else {
  2556. return false;
  2557. }
  2558. return $bits;
  2559. }
  2560. /**
  2561. * Make a URL index, appropriate for the el_index field of externallinks.
  2562. */
  2563. function wfMakeUrlIndex( $url ) {
  2564. $bits = wfParseUrl( $url );
  2565. // Reverse the labels in the hostname, convert to lower case
  2566. // For emails reverse domainpart only
  2567. if ( $bits['scheme'] == 'mailto' ) {
  2568. $mailparts = explode( '@', $bits['host'], 2 );
  2569. if ( count( $mailparts ) === 2 ) {
  2570. $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
  2571. } else {
  2572. // No domain specified, don't mangle it
  2573. $domainpart = '';
  2574. }
  2575. $reversedHost = $domainpart . '@' . $mailparts[0];
  2576. } else {
  2577. $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
  2578. }
  2579. // Add an extra dot to the end
  2580. // Why? Is it in wrong place in mailto links?
  2581. if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
  2582. $reversedHost .= '.';
  2583. }
  2584. // Reconstruct the pseudo-URL
  2585. $prot = $bits['scheme'];
  2586. $index = $prot . $bits['delimiter'] . $reversedHost;
  2587. // Leave out user and password. Add the port, path, query and fragment
  2588. if ( isset( $bits['port'] ) ) {
  2589. $index .= ':' . $bits['port'];
  2590. }
  2591. if ( isset( $bits['path'] ) ) {
  2592. $index .= $bits['path'];
  2593. } else {
  2594. $index .= '/';
  2595. }
  2596. if ( isset( $bits['query'] ) ) {
  2597. $index .= '?' . $bits['query'];
  2598. }
  2599. if ( isset( $bits['fragment'] ) ) {
  2600. $index .= '#' . $bits['fragment'];
  2601. }
  2602. return $index;
  2603. }
  2604. /**
  2605. * Do any deferred updates and clear the list
  2606. *
  2607. * @param $commit Boolean: commit after every update to prevent lock contention
  2608. */
  2609. function wfDoUpdates( $commit = false ) {
  2610. global $wgDeferredUpdateList;
  2611. wfProfileIn( __METHOD__ );
  2612. // No need to get master connections in case of empty updates array
  2613. if ( !count( $wgDeferredUpdateList ) ) {
  2614. wfProfileOut( __METHOD__ );
  2615. return;
  2616. }
  2617. if ( $commit ) {
  2618. $dbw = wfGetDB( DB_MASTER );
  2619. }
  2620. foreach ( $wgDeferredUpdateList as $update ) {
  2621. $update->doUpdate();
  2622. if ( $commit && $dbw->trxLevel() ) {
  2623. $dbw->commit();
  2624. }
  2625. }
  2626. $wgDeferredUpdateList = array();
  2627. wfProfileOut( __METHOD__ );
  2628. }
  2629. /**
  2630. * Convert an arbitrarily-long digit string from one numeric base
  2631. * to another, optionally zero-padding to a minimum column width.
  2632. *
  2633. * Supports base 2 through 36; digit values 10-36 are represented
  2634. * as lowercase letters a-z. Input is case-insensitive.
  2635. *
  2636. * @param $input String: of digits
  2637. * @param $sourceBase Integer: 2-36
  2638. * @param $destBase Integer: 2-36
  2639. * @param $pad Integer: 1 or greater
  2640. * @param $lowercase Boolean
  2641. * @return String or false on invalid input
  2642. */
  2643. function wfBaseConvert( $input, $sourceBase, $destBase, $pad = 1, $lowercase = true ) {
  2644. $input = strval( $input );
  2645. if( $sourceBase < 2 ||
  2646. $sourceBase > 36 ||
  2647. $destBase < 2 ||
  2648. $destBase > 36 ||
  2649. $pad < 1 ||
  2650. $sourceBase != intval( $sourceBase ) ||
  2651. $destBase != intval( $destBase ) ||
  2652. $pad != intval( $pad ) ||
  2653. !is_string( $input ) ||
  2654. $input == '' ) {
  2655. return false;
  2656. }
  2657. $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  2658. $inDigits = array();
  2659. $outChars = '';
  2660. // Decode and validate input string
  2661. $input = strtolower( $input );
  2662. for( $i = 0; $i < strlen( $input ); $i++ ) {
  2663. $n = strpos( $digitChars, $input{$i} );
  2664. if( $n === false || $n > $sourceBase ) {
  2665. return false;
  2666. }
  2667. $inDigits[] = $n;
  2668. }
  2669. // Iterate over the input, modulo-ing out an output digit
  2670. // at a time until input is gone.
  2671. while( count( $inDigits ) ) {
  2672. $work = 0;
  2673. $workDigits = array();
  2674. // Long division...
  2675. foreach( $inDigits as $digit ) {
  2676. $work *= $sourceBase;
  2677. $work += $digit;
  2678. if( $work < $destBase ) {
  2679. // Gonna need to pull another digit.
  2680. if( count( $workDigits ) ) {
  2681. // Avoid zero-padding; this lets us find
  2682. // the end of the input very easily when
  2683. // length drops to zero.
  2684. $workDigits[] = 0;
  2685. }
  2686. } else {
  2687. // Finally! Actual division!
  2688. $workDigits[] = intval( $work / $destBase );
  2689. // Isn't it annoying that most programming languages
  2690. // don't have a single divide-and-remainder operator,
  2691. // even though the CPU implements it that way?
  2692. $work = $work % $destBase;
  2693. }
  2694. }
  2695. // All that division leaves us with a remainder,
  2696. // which is conveniently our next output digit.
  2697. $outChars .= $digitChars[$work];
  2698. // And we continue!
  2699. $inDigits = $workDigits;
  2700. }
  2701. while( strlen( $outChars ) < $pad ) {
  2702. $outChars .= '0';
  2703. }
  2704. return strrev( $outChars );
  2705. }
  2706. /**
  2707. * Create an object with a given name and an array of construct parameters
  2708. * @param $name String
  2709. * @param $p Array: parameters
  2710. */
  2711. function wfCreateObject( $name, $p ) {
  2712. $p = array_values( $p );
  2713. switch ( count( $p ) ) {
  2714. case 0:
  2715. return new $name;
  2716. case 1:
  2717. return new $name( $p[0] );
  2718. case 2:
  2719. return new $name( $p[0], $p[1] );
  2720. case 3:
  2721. return new $name( $p[0], $p[1], $p[2] );
  2722. case 4:
  2723. return new $name( $p[0], $p[1], $p[2], $p[3] );
  2724. case 5:
  2725. return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
  2726. case 6:
  2727. return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
  2728. default:
  2729. throw new MWException( 'Too many arguments to construtor in wfCreateObject' );
  2730. }
  2731. }
  2732. function wfHttpOnlySafe() {
  2733. global $wgHttpOnlyBlacklist;
  2734. if( !version_compare( '5.2', PHP_VERSION, '<' ) ) {
  2735. return false;
  2736. }
  2737. if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
  2738. foreach( $wgHttpOnlyBlacklist as $regex ) {
  2739. if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
  2740. return false;
  2741. }
  2742. }
  2743. }
  2744. return true;
  2745. }
  2746. /**
  2747. * Initialise php session
  2748. */
  2749. function wfSetupSession( $sessionId = false ) {
  2750. global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain,
  2751. $wgCookieSecure, $wgCookieHttpOnly, $wgSessionHandler;
  2752. if( $wgSessionsInMemcached ) {
  2753. require_once( 'MemcachedSessions.php' );
  2754. } elseif( $wgSessionHandler && $wgSessionHandler != ini_get( 'session.save_handler' ) ) {
  2755. # Only set this if $wgSessionHandler isn't null and session.save_handler
  2756. # hasn't already been set to the desired value (that causes errors)
  2757. ini_set( 'session.save_handler', $wgSessionHandler );
  2758. }
  2759. $httpOnlySafe = wfHttpOnlySafe();
  2760. wfDebugLog( 'cookie',
  2761. 'session_set_cookie_params: "' . implode( '", "',
  2762. array(
  2763. 0,
  2764. $wgCookiePath,
  2765. $wgCookieDomain,
  2766. $wgCookieSecure,
  2767. $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
  2768. if( $httpOnlySafe && $wgCookieHttpOnly ) {
  2769. session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
  2770. } else {
  2771. // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
  2772. session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
  2773. }
  2774. session_cache_limiter( 'private, must-revalidate' );
  2775. if ( $sessionId ) {
  2776. session_id( $sessionId );
  2777. }
  2778. wfSuppressWarnings();
  2779. session_start();
  2780. wfRestoreWarnings();
  2781. }
  2782. /**
  2783. * Get an object from the precompiled serialized directory
  2784. *
  2785. * @return Mixed: the variable on success, false on failure
  2786. */
  2787. function wfGetPrecompiledData( $name ) {
  2788. global $IP;
  2789. $file = "$IP/serialized/$name";
  2790. if ( file_exists( $file ) ) {
  2791. $blob = file_get_contents( $file );
  2792. if ( $blob ) {
  2793. return unserialize( $blob );
  2794. }
  2795. }
  2796. return false;
  2797. }
  2798. function wfGetCaller( $level = 2 ) {
  2799. $backtrace = wfDebugBacktrace();
  2800. if ( isset( $backtrace[$level] ) ) {
  2801. return wfFormatStackFrame( $backtrace[$level] );
  2802. } else {
  2803. $caller = 'unknown';
  2804. }
  2805. return $caller;
  2806. }
  2807. /**
  2808. * Return a string consisting of callers in the stack. Useful sometimes
  2809. * for profiling specific points.
  2810. *
  2811. * @param $limit The maximum depth of the stack frame to return, or false for
  2812. * the entire stack.
  2813. */
  2814. function wfGetAllCallers( $limit = 3 ) {
  2815. $trace = array_reverse( wfDebugBacktrace() );
  2816. if ( !$limit || $limit > count( $trace ) - 1 ) {
  2817. $limit = count( $trace ) - 1;
  2818. }
  2819. $trace = array_slice( $trace, -$limit - 1, $limit );
  2820. return implode( '/', array_map( 'wfFormatStackFrame', $trace ) );
  2821. }
  2822. /**
  2823. * Return a string representation of frame
  2824. */
  2825. function wfFormatStackFrame( $frame ) {
  2826. return isset( $frame['class'] ) ?
  2827. $frame['class'] . '::' . $frame['function'] :
  2828. $frame['function'];
  2829. }
  2830. /**
  2831. * Get a cache key
  2832. */
  2833. function wfMemcKey( /*... */ ) {
  2834. $args = func_get_args();
  2835. $key = wfWikiID() . ':' . implode( ':', $args );
  2836. $key = str_replace( ' ', '_', $key );
  2837. return $key;
  2838. }
  2839. /**
  2840. * Get a cache key for a foreign DB
  2841. */
  2842. function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
  2843. $args = array_slice( func_get_args(), 2 );
  2844. if ( $prefix ) {
  2845. $key = "$db-$prefix:" . implode( ':', $args );
  2846. } else {
  2847. $key = $db . ':' . implode( ':', $args );
  2848. }
  2849. return $key;
  2850. }
  2851. /**
  2852. * Get an ASCII string identifying this wiki
  2853. * This is used as a prefix in memcached keys
  2854. */
  2855. function wfWikiID() {
  2856. global $wgDBprefix, $wgDBname;
  2857. if ( $wgDBprefix ) {
  2858. return "$wgDBname-$wgDBprefix";
  2859. } else {
  2860. return $wgDBname;
  2861. }
  2862. }
  2863. /**
  2864. * Split a wiki ID into DB name and table prefix
  2865. */
  2866. function wfSplitWikiID( $wiki ) {
  2867. $bits = explode( '-', $wiki, 2 );
  2868. if ( count( $bits ) < 2 ) {
  2869. $bits[] = '';
  2870. }
  2871. return $bits;
  2872. }
  2873. /**
  2874. * Get a Database object.
  2875. * @param $db Integer: index of the connection to get. May be DB_MASTER for the
  2876. * master (for write queries), DB_SLAVE for potentially lagged read
  2877. * queries, or an integer >= 0 for a particular server.
  2878. *
  2879. * @param $groups Mixed: query groups. An array of group names that this query
  2880. * belongs to. May contain a single string if the query is only
  2881. * in one group.
  2882. *
  2883. * @param $wiki String: the wiki ID, or false for the current wiki
  2884. *
  2885. * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
  2886. * will always return the same object, unless the underlying connection or load
  2887. * balancer is manually destroyed.
  2888. *
  2889. * @return DatabaseBase
  2890. */
  2891. function &wfGetDB( $db, $groups = array(), $wiki = false ) {
  2892. return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
  2893. }
  2894. /**
  2895. * Get a load balancer object.
  2896. *
  2897. * @param $wiki String: wiki ID, or false for the current wiki
  2898. * @return LoadBalancer
  2899. */
  2900. function wfGetLB( $wiki = false ) {
  2901. return wfGetLBFactory()->getMainLB( $wiki );
  2902. }
  2903. /**
  2904. * Get the load balancer factory object
  2905. */
  2906. function &wfGetLBFactory() {
  2907. return LBFactory::singleton();
  2908. }
  2909. /**
  2910. * Find a file.
  2911. * Shortcut for RepoGroup::singleton()->findFile()
  2912. * @param $title String or Title object
  2913. * @param $options Associative array of options:
  2914. * time: requested time for an archived image, or false for the
  2915. * current version. An image object will be returned which was
  2916. * created at the specified time.
  2917. *
  2918. * ignoreRedirect: If true, do not follow file redirects
  2919. *
  2920. * private: If true, return restricted (deleted) files if the current
  2921. * user is allowed to view them. Otherwise, such files will not
  2922. * be found.
  2923. *
  2924. * bypassCache: If true, do not use the process-local cache of File objects
  2925. *
  2926. * @return File, or false if the file does not exist
  2927. */
  2928. function wfFindFile( $title, $options = array() ) {
  2929. return RepoGroup::singleton()->findFile( $title, $options );
  2930. }
  2931. /**
  2932. * Get an object referring to a locally registered file.
  2933. * Returns a valid placeholder object if the file does not exist.
  2934. * @param $title Title or String
  2935. * @return File, or null if passed an invalid Title
  2936. */
  2937. function wfLocalFile( $title ) {
  2938. return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
  2939. }
  2940. /**
  2941. * Should low-performance queries be disabled?
  2942. *
  2943. * @return Boolean
  2944. */
  2945. function wfQueriesMustScale() {
  2946. global $wgMiserMode;
  2947. return $wgMiserMode
  2948. || ( SiteStats::pages() > 100000
  2949. && SiteStats::edits() > 1000000
  2950. && SiteStats::users() > 10000 );
  2951. }
  2952. /**
  2953. * Get the path to a specified script file, respecting file
  2954. * extensions; this is a wrapper around $wgScriptExtension etc.
  2955. *
  2956. * @param $script String: script filename, sans extension
  2957. * @return String
  2958. */
  2959. function wfScript( $script = 'index' ) {
  2960. global $wgScriptPath, $wgScriptExtension;
  2961. return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
  2962. }
  2963. /**
  2964. * Get the script URL.
  2965. *
  2966. * @return script URL
  2967. */
  2968. function wfGetScriptUrl() {
  2969. if( isset( $_SERVER['SCRIPT_NAME'] ) ) {
  2970. #
  2971. # as it was called, minus the query string.
  2972. #
  2973. # Some sites use Apache rewrite rules to handle subdomains,
  2974. # and have PHP set up in a weird way that causes PHP_SELF
  2975. # to contain the rewritten URL instead of the one that the
  2976. # outside world sees.
  2977. #
  2978. # If in this mode, use SCRIPT_URL instead, which mod_rewrite
  2979. # provides containing the "before" URL.
  2980. return $_SERVER['SCRIPT_NAME'];
  2981. } else {
  2982. return $_SERVER['URL'];
  2983. }
  2984. }
  2985. /**
  2986. * Convenience function converts boolean values into "true"
  2987. * or "false" (string) values
  2988. *
  2989. * @param $value Boolean
  2990. * @return String
  2991. */
  2992. function wfBoolToStr( $value ) {
  2993. return $value ? 'true' : 'false';
  2994. }
  2995. /**
  2996. * Load an extension messages file
  2997. * @deprecated in 1.16 (warnings in 1.18, removed in ?)
  2998. */
  2999. function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
  3000. }
  3001. /**
  3002. * Get a platform-independent path to the null file, e.g.
  3003. * /dev/null
  3004. *
  3005. * @return string
  3006. */
  3007. function wfGetNull() {
  3008. return wfIsWindows()
  3009. ? 'NUL'
  3010. : '/dev/null';
  3011. }
  3012. /**
  3013. * Displays a maxlag error
  3014. *
  3015. * @param $host String: server that lags the most
  3016. * @param $lag Integer: maxlag (actual)
  3017. * @param $maxLag Integer: maxlag (requested)
  3018. */
  3019. function wfMaxlagError( $host, $lag, $maxLag ) {
  3020. global $wgShowHostnames;
  3021. header( 'HTTP/1.1 503 Service Unavailable' );
  3022. header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
  3023. header( 'X-Database-Lag: ' . intval( $lag ) );
  3024. header( 'Content-Type: text/plain' );
  3025. if( $wgShowHostnames ) {
  3026. echo "Waiting for $host: $lag seconds lagged\n";
  3027. } else {
  3028. echo "Waiting for a database server: $lag seconds lagged\n";
  3029. }
  3030. }
  3031. /**
  3032. * Throws a warning that $function is deprecated
  3033. * @param $function String
  3034. * @return null
  3035. */
  3036. function wfDeprecated( $function ) {
  3037. static $functionsWarned = array();
  3038. if ( !isset( $functionsWarned[$function] ) ) {
  3039. $functionsWarned[$function] = true;
  3040. wfWarn( "Use of $function is deprecated.", 2 );
  3041. }
  3042. }
  3043. /**
  3044. * Send a warning either to the debug log or in a PHP error depending on
  3045. * $wgDevelopmentWarnings
  3046. *
  3047. * @param $msg String: message to send
  3048. * @param $callerOffset Integer: number of itmes to go back in the backtrace to
  3049. * find the correct caller (1 = function calling wfWarn, ...)
  3050. * @param $level Integer: PHP error level; only used when $wgDevelopmentWarnings
  3051. * is true
  3052. */
  3053. function wfWarn( $msg, $callerOffset = 1, $level = E_USER_NOTICE ) {
  3054. $callers = wfDebugBacktrace();
  3055. if( isset( $callers[$callerOffset + 1] ) ){
  3056. $callerfunc = $callers[$callerOffset + 1];
  3057. $callerfile = $callers[$callerOffset];
  3058. if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ) {
  3059. $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
  3060. } else {
  3061. $file = '(internal function)';
  3062. }
  3063. $func = '';
  3064. if( isset( $callerfunc['class'] ) ) {
  3065. $func .= $callerfunc['class'] . '::';
  3066. }
  3067. if( isset( $callerfunc['function'] ) ) {
  3068. $func .= $callerfunc['function'];
  3069. }
  3070. $msg .= " [Called from $func in $file]";
  3071. }
  3072. global $wgDevelopmentWarnings;
  3073. if ( $wgDevelopmentWarnings ) {
  3074. trigger_error( $msg, $level );
  3075. } else {
  3076. wfDebug( "$msg\n" );
  3077. }
  3078. }
  3079. /**
  3080. * Sleep until the worst slave's replication lag is less than or equal to
  3081. * $maxLag, in seconds. Use this when updating very large numbers of rows, as
  3082. * in maintenance scripts, to avoid causing too much lag. Of course, this is
  3083. * a no-op if there are no slaves.
  3084. *
  3085. * Every time the function has to wait for a slave, it will print a message to
  3086. * that effect (and then sleep for a little while), so it's probably not best
  3087. * to use this outside maintenance scripts in its present form.
  3088. *
  3089. * @param $maxLag Integer
  3090. * @param $wiki mixed Wiki identifier accepted by wfGetLB
  3091. * @return null
  3092. */
  3093. function wfWaitForSlaves( $maxLag, $wiki = false ) {
  3094. if( $maxLag ) {
  3095. $lb = wfGetLB( $wiki );
  3096. list( $host, $lag ) = $lb->getMaxLag( $wiki );
  3097. while( $lag > $maxLag ) {
  3098. wfSuppressWarnings();
  3099. $name = gethostbyaddr( $host );
  3100. wfRestoreWarnings();
  3101. if( $name !== false ) {
  3102. $host = $name;
  3103. }
  3104. print "Waiting for $host (lagged $lag seconds)...\n";
  3105. sleep( $maxLag );
  3106. list( $host, $lag ) = $lb->getMaxLag();
  3107. }
  3108. }
  3109. }
  3110. /**
  3111. * Used to be used for outputting text in the installer/updater
  3112. * @deprecated Warnings in 1.19, removal in 1.20
  3113. */
  3114. function wfOut( $s ) {
  3115. global $wgCommandLineMode;
  3116. if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
  3117. echo $s;
  3118. } else {
  3119. echo htmlspecialchars( $s );
  3120. }
  3121. flush();
  3122. }
  3123. /**
  3124. * Count down from $n to zero on the terminal, with a one-second pause
  3125. * between showing each number. For use in command-line scripts.
  3126. */
  3127. function wfCountDown( $n ) {
  3128. for ( $i = $n; $i >= 0; $i-- ) {
  3129. if ( $i != $n ) {
  3130. echo str_repeat( "\x08", strlen( $i + 1 ) );
  3131. }
  3132. echo $i;
  3133. flush();
  3134. if ( $i ) {
  3135. sleep( 1 );
  3136. }
  3137. }
  3138. echo "\n";
  3139. }
  3140. /**
  3141. * Generate a random 32-character hexadecimal token.
  3142. * @param $salt Mixed: some sort of salt, if necessary, to add to random
  3143. * characters before hashing.
  3144. */
  3145. function wfGenerateToken( $salt = '' ) {
  3146. $salt = serialize( $salt );
  3147. return md5( mt_rand( 0, 0x7fffffff ) . $salt );
  3148. }
  3149. /**
  3150. * Replace all invalid characters with -
  3151. * @param $name Mixed: filename to process
  3152. */
  3153. function wfStripIllegalFilenameChars( $name ) {
  3154. global $wgIllegalFileChars;
  3155. $name = wfBaseName( $name );
  3156. $name = preg_replace(
  3157. "/[^" . Title::legalChars() . "]" .
  3158. ( $wgIllegalFileChars ? "|[" . $wgIllegalFileChars . "]" : '' ) .
  3159. "/",
  3160. '-',
  3161. $name
  3162. );
  3163. return $name;
  3164. }
  3165. /**
  3166. * Insert array into another array after the specified *KEY*
  3167. * @param $array Array: The array.
  3168. * @param $insert Array: The array to insert.
  3169. * @param $after Mixed: The key to insert after
  3170. */
  3171. function wfArrayInsertAfter( $array, $insert, $after ) {
  3172. // Find the offset of the element to insert after.
  3173. $keys = array_keys( $array );
  3174. $offsetByKey = array_flip( $keys );
  3175. $offset = $offsetByKey[$after];
  3176. // Insert at the specified offset
  3177. $before = array_slice( $array, 0, $offset + 1, true );
  3178. $after = array_slice( $array, $offset + 1, count( $array ) - $offset, true );
  3179. $output = $before + $insert + $after;
  3180. return $output;
  3181. }
  3182. /* Recursively converts the parameter (an object) to an array with the same data */
  3183. function wfObjectToArray( $objOrArray, $recursive = true ) {
  3184. $array = array();
  3185. if( is_object( $objOrArray ) ) {
  3186. $objOrArray = get_object_vars( $objOrArray );
  3187. }
  3188. foreach ( $objOrArray as $key => $value ) {
  3189. if ( $recursive && ( is_object( $value ) || is_array( $value ) ) ) {
  3190. $value = wfObjectToArray( $value );
  3191. }
  3192. $array[$key] = $value;
  3193. }
  3194. return $array;
  3195. }
  3196. /**
  3197. * Set PHP's memory limit to the larger of php.ini or $wgMemoryLimit;
  3198. * @return Integer value memory was set to.
  3199. */
  3200. function wfMemoryLimit() {
  3201. global $wgMemoryLimit;
  3202. $memlimit = wfShorthandToInteger( ini_get( 'memory_limit' ) );
  3203. if( $memlimit != -1 ) {
  3204. $conflimit = wfShorthandToInteger( $wgMemoryLimit );
  3205. if( $conflimit == -1 ) {
  3206. wfDebug( "Removing PHP's memory limit\n" );
  3207. wfSuppressWarnings();
  3208. ini_set( 'memory_limit', $conflimit );
  3209. wfRestoreWarnings();
  3210. return $conflimit;
  3211. } elseif ( $conflimit > $memlimit ) {
  3212. wfDebug( "Raising PHP's memory limit to $conflimit bytes\n" );
  3213. wfSuppressWarnings();
  3214. ini_set( 'memory_limit', $conflimit );
  3215. wfRestoreWarnings();
  3216. return $conflimit;
  3217. }
  3218. }
  3219. return $memlimit;
  3220. }
  3221. /**
  3222. * Converts shorthand byte notation to integer form
  3223. * @param $string String
  3224. * @return Integer
  3225. */
  3226. function wfShorthandToInteger( $string = '' ) {
  3227. $string = trim( $string );
  3228. if( $string === '' ) {
  3229. return -1;
  3230. }
  3231. $last = $string[strlen( $string ) - 1];
  3232. $val = intval( $string );
  3233. switch( $last ) {
  3234. case 'g':
  3235. case 'G':
  3236. $val *= 1024;
  3237. // break intentionally missing
  3238. case 'm':
  3239. case 'M':
  3240. $val *= 1024;
  3241. // break intentionally missing
  3242. case 'k':
  3243. case 'K':
  3244. $val *= 1024;
  3245. }
  3246. return $val;
  3247. }
  3248. /**
  3249. * Get the normalised IETF language tag
  3250. * @param $code String: The language code.
  3251. * @return $langCode String: The language code which complying with BCP 47 standards.
  3252. */
  3253. function wfBCP47( $code ) {
  3254. $codeSegment = explode( '-', $code );
  3255. foreach ( $codeSegment as $segNo => $seg ) {
  3256. if ( count( $codeSegment ) > 0 ) {
  3257. // ISO 3166 country code
  3258. if ( ( strlen( $seg ) == 2 ) && ( $segNo > 0 ) ) {
  3259. $codeBCP[$segNo] = strtoupper( $seg );
  3260. // ISO 15924 script code
  3261. } elseif ( ( strlen( $seg ) == 4 ) && ( $segNo > 0 ) ) {
  3262. $codeBCP[$segNo] = ucfirst( $seg );
  3263. // Use lowercase for other cases
  3264. } else {
  3265. $codeBCP[$segNo] = strtolower( $seg );
  3266. }
  3267. } else {
  3268. // Use lowercase for single segment
  3269. $codeBCP[$segNo] = strtolower( $seg );
  3270. }
  3271. }
  3272. $langCode = implode( '-', $codeBCP );
  3273. return $langCode;
  3274. }
  3275. function wfArrayMap( $function, $input ) {
  3276. $ret = array_map( $function, $input );
  3277. foreach ( $ret as $key => $value ) {
  3278. $taint = istainted( $input[$key] );
  3279. if ( $taint ) {
  3280. taint( $ret[$key], $taint );
  3281. }
  3282. }
  3283. return $ret;
  3284. }