PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/mediawiki-integration/source/php/mediawiki/includes/GlobalFunctions.php

https://code.google.com/
PHP | 2138 lines | 1330 code | 187 blank | 621 comment | 235 complexity | 9e9da7beed22b14b341fa62a233d4e05 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0
  1. <?php
  2. /**
  3. * Global functions used everywhere
  4. * @package MediaWiki
  5. */
  6. /**
  7. * Some globals and requires needed
  8. */
  9. /** Total number of articles */
  10. $wgNumberOfArticles = -1; # Unset
  11. /** Total number of views */
  12. $wgTotalViews = -1;
  13. /** Total number of edits */
  14. $wgTotalEdits = -1;
  15. require_once( 'LogPage.php' );
  16. require_once( 'normal/UtfNormalUtil.php' );
  17. require_once( 'XmlFunctions.php' );
  18. /**
  19. * Compatibility functions
  20. *
  21. * We more or less support PHP 5.0.x and up.
  22. * Re-implementations of newer functions or functions in non-standard
  23. * PHP extensions may be included here.
  24. */
  25. if( !function_exists('iconv') ) {
  26. # iconv support is not in the default configuration and so may not be present.
  27. # Assume will only ever use utf-8 and iso-8859-1.
  28. # This will *not* work in all circumstances.
  29. function iconv( $from, $to, $string ) {
  30. if(strcasecmp( $from, $to ) == 0) return $string;
  31. if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
  32. if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
  33. return $string;
  34. }
  35. }
  36. # UTF-8 substr function based on a PHP manual comment
  37. if ( !function_exists( 'mb_substr' ) ) {
  38. function mb_substr( $str, $start ) {
  39. $ar = array();
  40. preg_match_all( '/./us', $str, $ar );
  41. if( func_num_args() >= 3 ) {
  42. $end = func_get_arg( 2 );
  43. return join( '', array_slice( $ar[0], $start, $end ) );
  44. } else {
  45. return join( '', array_slice( $ar[0], $start ) );
  46. }
  47. }
  48. }
  49. if ( !function_exists( 'array_diff_key' ) ) {
  50. /**
  51. * Exists in PHP 5.1.0+
  52. * Not quite compatible, two-argument version only
  53. * Null values will cause problems due to this use of isset()
  54. */
  55. function array_diff_key( $left, $right ) {
  56. $result = $left;
  57. foreach ( $left as $key => $unused ) {
  58. if ( isset( $right[$key] ) ) {
  59. unset( $result[$key] );
  60. }
  61. }
  62. return $result;
  63. }
  64. }
  65. /**
  66. * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
  67. * PHP 5 won't let you declare a 'clone' function, even conditionally,
  68. * so it has to be a wrapper with a different name.
  69. */
  70. function wfClone( $object ) {
  71. return clone( $object );
  72. }
  73. /**
  74. * Where as we got a random seed
  75. */
  76. $wgRandomSeeded = false;
  77. /**
  78. * Seed Mersenne Twister
  79. * No-op for compatibility; only necessary in PHP < 4.2.0
  80. */
  81. function wfSeedRandom() {
  82. /* No-op */
  83. }
  84. /**
  85. * Get a random decimal value between 0 and 1, in a way
  86. * not likely to give duplicate values for any realistic
  87. * number of articles.
  88. *
  89. * @return string
  90. */
  91. function wfRandom() {
  92. # The maximum random value is "only" 2^31-1, so get two random
  93. # values to reduce the chance of dupes
  94. $max = mt_getrandmax() + 1;
  95. $rand = number_format( (mt_rand() * $max + mt_rand())
  96. / $max / $max, 12, '.', '' );
  97. return $rand;
  98. }
  99. /**
  100. * We want / and : to be included as literal characters in our title URLs.
  101. * %2F in the page titles seems to fatally break for some reason.
  102. *
  103. * @param $s String:
  104. * @return string
  105. */
  106. function wfUrlencode ( $s ) {
  107. $s = urlencode( $s );
  108. $s = preg_replace( '/%3[Aa]/', ':', $s );
  109. $s = preg_replace( '/%2[Ff]/', '/', $s );
  110. return $s;
  111. }
  112. /**
  113. * Sends a line to the debug log if enabled or, optionally, to a comment in output.
  114. * In normal operation this is a NOP.
  115. *
  116. * Controlling globals:
  117. * $wgDebugLogFile - points to the log file
  118. * $wgProfileOnly - if set, normal debug messages will not be recorded.
  119. * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
  120. * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
  121. *
  122. * @param $text String
  123. * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
  124. */
  125. function wfDebug( $text, $logonly = false ) {
  126. global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
  127. static $recursion = 0;
  128. # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
  129. if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
  130. return;
  131. }
  132. if ( $wgDebugComments && !$logonly ) {
  133. if ( !isset( $wgOut ) ) {
  134. return;
  135. }
  136. if ( !StubObject::isRealObject( $wgOut ) ) {
  137. if ( $recursion ) {
  138. return;
  139. }
  140. $recursion++;
  141. $wgOut->_unstub();
  142. $recursion--;
  143. }
  144. $wgOut->debug( $text );
  145. }
  146. if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
  147. # Strip unprintables; they can switch terminal modes when binary data
  148. # gets dumped, which is pretty annoying.
  149. $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
  150. @error_log( $text, 3, $wgDebugLogFile );
  151. }
  152. }
  153. /**
  154. * Send a line to a supplementary debug log file, if configured, or main debug log if not.
  155. * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
  156. *
  157. * @param $logGroup String
  158. * @param $text String
  159. * @param $public Bool: whether to log the event in the public log if no private
  160. * log file is specified, (default true)
  161. */
  162. function wfDebugLog( $logGroup, $text, $public = true ) {
  163. global $wgDebugLogGroups;
  164. if( $text{strlen( $text ) - 1} != "\n" ) $text .= "\n";
  165. if( isset( $wgDebugLogGroups[$logGroup] ) ) {
  166. $time = wfTimestamp( TS_DB );
  167. $wiki = wfWikiID();
  168. @error_log( "$time $wiki: $text", 3, $wgDebugLogGroups[$logGroup] );
  169. } else if ( $public === true ) {
  170. wfDebug( $text, true );
  171. }
  172. }
  173. /**
  174. * Log for database errors
  175. * @param $text String: database error message.
  176. */
  177. function wfLogDBError( $text ) {
  178. global $wgDBerrorLog;
  179. if ( $wgDBerrorLog ) {
  180. $host = trim(`hostname`);
  181. $text = date('D M j G:i:s T Y') . "\t$host\t".$text;
  182. error_log( $text, 3, $wgDBerrorLog );
  183. }
  184. }
  185. /**
  186. * @todo document
  187. */
  188. function wfLogProfilingData() {
  189. global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
  190. global $wgProfiling, $wgUser;
  191. if ( $wgProfiling ) {
  192. $now = wfTime();
  193. $elapsed = $now - $wgRequestTime;
  194. $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
  195. $forward = '';
  196. if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
  197. $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
  198. if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
  199. $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
  200. if( !empty( $_SERVER['HTTP_FROM'] ) )
  201. $forward .= ' from ' . $_SERVER['HTTP_FROM'];
  202. if( $forward )
  203. $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
  204. // Don't unstub $wgUser at this late stage just for statistics purposes
  205. if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
  206. $forward .= ' anon';
  207. $log = sprintf( "%s\t%04.3f\t%s\n",
  208. gmdate( 'YmdHis' ), $elapsed,
  209. urldecode( $wgRequest->getRequestURL() . $forward ) );
  210. if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
  211. error_log( $log . $prof, 3, $wgDebugLogFile );
  212. }
  213. }
  214. }
  215. /**
  216. * Check if the wiki read-only lock file is present. This can be used to lock
  217. * off editing functions, but doesn't guarantee that the database will not be
  218. * modified.
  219. * @return bool
  220. */
  221. function wfReadOnly() {
  222. global $wgReadOnlyFile, $wgReadOnly;
  223. if ( !is_null( $wgReadOnly ) ) {
  224. return (bool)$wgReadOnly;
  225. }
  226. if ( '' == $wgReadOnlyFile ) {
  227. return false;
  228. }
  229. // Set $wgReadOnly for faster access next time
  230. if ( is_file( $wgReadOnlyFile ) ) {
  231. $wgReadOnly = file_get_contents( $wgReadOnlyFile );
  232. } else {
  233. $wgReadOnly = false;
  234. }
  235. return (bool)$wgReadOnly;
  236. }
  237. /**
  238. * Get a message from anywhere, for the current user language.
  239. *
  240. * Use wfMsgForContent() instead if the message should NOT
  241. * change depending on the user preferences.
  242. *
  243. * Note that the message may contain HTML, and is therefore
  244. * not safe for insertion anywhere. Some functions such as
  245. * addWikiText will do the escaping for you. Use wfMsgHtml()
  246. * if you need an escaped message.
  247. *
  248. * @param $key String: lookup key for the message, usually
  249. * defined in languages/Language.php
  250. *
  251. * This function also takes extra optional parameters (not
  252. * shown in the function definition), which can by used to
  253. * insert variable text into the predefined message.
  254. */
  255. function wfMsg( $key ) {
  256. $args = func_get_args();
  257. array_shift( $args );
  258. return wfMsgReal( $key, $args, true );
  259. }
  260. /**
  261. * Same as above except doesn't transform the message
  262. */
  263. function wfMsgNoTrans( $key ) {
  264. $args = func_get_args();
  265. array_shift( $args );
  266. return wfMsgReal( $key, $args, true, false, false );
  267. }
  268. /**
  269. * Get a message from anywhere, for the current global language
  270. * set with $wgLanguageCode.
  271. *
  272. * Use this if the message should NOT change dependent on the
  273. * language set in the user's preferences. This is the case for
  274. * most text written into logs, as well as link targets (such as
  275. * the name of the copyright policy page). Link titles, on the
  276. * other hand, should be shown in the UI language.
  277. *
  278. * Note that MediaWiki allows users to change the user interface
  279. * language in their preferences, but a single installation
  280. * typically only contains content in one language.
  281. *
  282. * Be wary of this distinction: If you use wfMsg() where you should
  283. * use wfMsgForContent(), a user of the software may have to
  284. * customize over 70 messages in order to, e.g., fix a link in every
  285. * possible language.
  286. *
  287. * @param $key String: lookup key for the message, usually
  288. * defined in languages/Language.php
  289. */
  290. function wfMsgForContent( $key ) {
  291. global $wgForceUIMsgAsContentMsg;
  292. $args = func_get_args();
  293. array_shift( $args );
  294. $forcontent = true;
  295. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  296. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  297. $forcontent = false;
  298. return wfMsgReal( $key, $args, true, $forcontent );
  299. }
  300. /**
  301. * Same as above except doesn't transform the message
  302. */
  303. function wfMsgForContentNoTrans( $key ) {
  304. global $wgForceUIMsgAsContentMsg;
  305. $args = func_get_args();
  306. array_shift( $args );
  307. $forcontent = true;
  308. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  309. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  310. $forcontent = false;
  311. return wfMsgReal( $key, $args, true, $forcontent, false );
  312. }
  313. /**
  314. * Get a message from the language file, for the UI elements
  315. */
  316. function wfMsgNoDB( $key ) {
  317. $args = func_get_args();
  318. array_shift( $args );
  319. return wfMsgReal( $key, $args, false );
  320. }
  321. /**
  322. * Get a message from the language file, for the content
  323. */
  324. function wfMsgNoDBForContent( $key ) {
  325. global $wgForceUIMsgAsContentMsg;
  326. $args = func_get_args();
  327. array_shift( $args );
  328. $forcontent = true;
  329. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  330. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  331. $forcontent = false;
  332. return wfMsgReal( $key, $args, false, $forcontent );
  333. }
  334. /**
  335. * Really get a message
  336. * @param $key String: key to get.
  337. * @param $args
  338. * @param $useDB Boolean
  339. * @param $transform Boolean: Whether or not to transform the message.
  340. * @param $forContent Boolean
  341. * @return String: the requested message.
  342. */
  343. function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
  344. $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
  345. $message = wfMsgReplaceArgs( $message, $args );
  346. return $message;
  347. }
  348. /**
  349. * This function provides the message source for messages to be edited which are *not* stored in the database.
  350. * @param $key String:
  351. */
  352. function wfMsgWeirdKey ( $key ) {
  353. $subsource = str_replace ( ' ' , '_' , $key ) ;
  354. $source = wfMsgForContentNoTrans( $subsource ) ;
  355. if ( wfEmptyMsg( $subsource, $source) ) {
  356. # Try again with first char lower case
  357. $subsource = strtolower ( substr ( $subsource , 0 , 1 ) ) . substr ( $subsource , 1 ) ;
  358. $source = wfMsgForContentNoTrans( $subsource ) ;
  359. }
  360. if ( wfEmptyMsg( $subsource, $source ) ) {
  361. # Didn't work either, return blank text
  362. $source = "" ;
  363. }
  364. return $source ;
  365. }
  366. /**
  367. * Fetch a message string value, but don't replace any keys yet.
  368. * @param string $key
  369. * @param bool $useDB
  370. * @param bool $forContent
  371. * @return string
  372. * @private
  373. */
  374. function wfMsgGetKey( $key, $useDB, $forContent = false, $transform = true ) {
  375. global $wgParser, $wgContLang, $wgMessageCache, $wgLang;
  376. if ( is_object( $wgMessageCache ) )
  377. $transstat = $wgMessageCache->getTransform();
  378. if( is_object( $wgMessageCache ) ) {
  379. if ( ! $transform )
  380. $wgMessageCache->disableTransform();
  381. $message = $wgMessageCache->get( $key, $useDB, $forContent );
  382. } else {
  383. if( $forContent ) {
  384. $lang = &$wgContLang;
  385. } else {
  386. $lang = &$wgLang;
  387. }
  388. wfSuppressWarnings();
  389. if( is_object( $lang ) ) {
  390. $message = $lang->getMessage( $key );
  391. } else {
  392. $message = false;
  393. }
  394. wfRestoreWarnings();
  395. if($message === false)
  396. $message = Language::getMessage($key);
  397. if ( $transform && strstr( $message, '{{' ) !== false ) {
  398. $message = $wgParser->transformMsg($message, $wgMessageCache->getParserOptions() );
  399. }
  400. }
  401. if ( is_object( $wgMessageCache ) && ! $transform )
  402. $wgMessageCache->setTransform( $transstat );
  403. return $message;
  404. }
  405. /**
  406. * Replace message parameter keys on the given formatted output.
  407. *
  408. * @param string $message
  409. * @param array $args
  410. * @return string
  411. * @private
  412. */
  413. function wfMsgReplaceArgs( $message, $args ) {
  414. # Fix windows line-endings
  415. # Some messages are split with explode("\n", $msg)
  416. $message = str_replace( "\r", '', $message );
  417. // Replace arguments
  418. if ( count( $args ) ) {
  419. if ( is_array( $args[0] ) ) {
  420. foreach ( $args[0] as $key => $val ) {
  421. $message = str_replace( '$' . $key, $val, $message );
  422. }
  423. } else {
  424. foreach( $args as $n => $param ) {
  425. $replacementKeys['$' . ($n + 1)] = $param;
  426. }
  427. $message = strtr( $message, $replacementKeys );
  428. }
  429. }
  430. return $message;
  431. }
  432. /**
  433. * Return an HTML-escaped version of a message.
  434. * Parameter replacements, if any, are done *after* the HTML-escaping,
  435. * so parameters may contain HTML (eg links or form controls). Be sure
  436. * to pre-escape them if you really do want plaintext, or just wrap
  437. * the whole thing in htmlspecialchars().
  438. *
  439. * @param string $key
  440. * @param string ... parameters
  441. * @return string
  442. */
  443. function wfMsgHtml( $key ) {
  444. $args = func_get_args();
  445. array_shift( $args );
  446. return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
  447. }
  448. /**
  449. * Return an HTML version of message
  450. * Parameter replacements, if any, are done *after* parsing the wiki-text message,
  451. * so parameters may contain HTML (eg links or form controls). Be sure
  452. * to pre-escape them if you really do want plaintext, or just wrap
  453. * the whole thing in htmlspecialchars().
  454. *
  455. * @param string $key
  456. * @param string ... parameters
  457. * @return string
  458. */
  459. function wfMsgWikiHtml( $key ) {
  460. global $wgOut;
  461. $args = func_get_args();
  462. array_shift( $args );
  463. return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
  464. }
  465. /**
  466. * Returns message in the requested format
  467. * @param string $key Key of the message
  468. * @param array $options Processing rules:
  469. * <i>parse<i>: parses wikitext to html
  470. * <i>parseinline<i>: parses wikitext to html and removes the surrounding p's added by parser or tidy
  471. * <i>escape<i>: filters message trough htmlspecialchars
  472. * <i>replaceafter<i>: parameters are substituted after parsing or escaping
  473. * <i>parsemag<i>: ??
  474. */
  475. function wfMsgExt( $key, $options ) {
  476. global $wgOut, $wgParser;
  477. $args = func_get_args();
  478. array_shift( $args );
  479. array_shift( $args );
  480. if( !is_array($options) ) {
  481. $options = array($options);
  482. }
  483. $string = wfMsgGetKey( $key, true, false, false );
  484. if( !in_array('replaceafter', $options) ) {
  485. $string = wfMsgReplaceArgs( $string, $args );
  486. }
  487. if( in_array('parse', $options) ) {
  488. $string = $wgOut->parse( $string, true, true );
  489. } elseif ( in_array('parseinline', $options) ) {
  490. $string = $wgOut->parse( $string, true, true );
  491. $m = array();
  492. if( preg_match( "~^<p>(.*)\n?</p>$~", $string, $m ) ) {
  493. $string = $m[1];
  494. }
  495. } elseif ( in_array('parsemag', $options) ) {
  496. global $wgMessageCache;
  497. if ( isset( $wgMessageCache ) ) {
  498. $string = $wgMessageCache->transform( $string );
  499. }
  500. }
  501. if ( in_array('escape', $options) ) {
  502. $string = htmlspecialchars ( $string );
  503. }
  504. if( in_array('replaceafter', $options) ) {
  505. $string = wfMsgReplaceArgs( $string, $args );
  506. }
  507. return $string;
  508. }
  509. /**
  510. * Just like exit() but makes a note of it.
  511. * Commits open transactions except if the error parameter is set
  512. *
  513. * @obsolete Please return control to the caller or throw an exception
  514. */
  515. function wfAbruptExit( $error = false ){
  516. global $wgLoadBalancer;
  517. static $called = false;
  518. if ( $called ){
  519. exit( -1 );
  520. }
  521. $called = true;
  522. $bt = wfDebugBacktrace();
  523. if( $bt ) {
  524. for($i = 0; $i < count($bt) ; $i++){
  525. $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
  526. $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
  527. wfDebug("WARNING: Abrupt exit in $file at line $line\n");
  528. }
  529. } else {
  530. wfDebug('WARNING: Abrupt exit\n');
  531. }
  532. wfLogProfilingData();
  533. if ( !$error ) {
  534. $wgLoadBalancer->closeAll();
  535. }
  536. exit( -1 );
  537. }
  538. /**
  539. * @obsolete Please return control the caller or throw an exception
  540. */
  541. function wfErrorExit() {
  542. wfAbruptExit( true );
  543. }
  544. /**
  545. * Print a simple message and die, returning nonzero to the shell if any.
  546. * Plain die() fails to return nonzero to the shell if you pass a string.
  547. * @param string $msg
  548. */
  549. function wfDie( $msg='' ) {
  550. echo $msg;
  551. die( 1 );
  552. }
  553. /**
  554. * Throw a debugging exception. This function previously once exited the process,
  555. * but now throws an exception instead, with similar results.
  556. *
  557. * @param string $msg Message shown when dieing.
  558. */
  559. function wfDebugDieBacktrace( $msg = '' ) {
  560. throw new MWException( $msg );
  561. }
  562. /**
  563. * Fetch server name for use in error reporting etc.
  564. * Use real server name if available, so we know which machine
  565. * in a server farm generated the current page.
  566. * @return string
  567. */
  568. function wfHostname() {
  569. if ( function_exists( 'posix_uname' ) ) {
  570. // This function not present on Windows
  571. $uname = @posix_uname();
  572. } else {
  573. $uname = false;
  574. }
  575. if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
  576. return $uname['nodename'];
  577. } else {
  578. # This may be a virtual server.
  579. return $_SERVER['SERVER_NAME'];
  580. }
  581. }
  582. /**
  583. * Returns a HTML comment with the elapsed time since request.
  584. * This method has no side effects.
  585. * @return string
  586. */
  587. function wfReportTime() {
  588. global $wgRequestTime;
  589. $now = wfTime();
  590. $elapsed = $now - $wgRequestTime;
  591. $com = sprintf( "<!-- Served by %s in %01.3f secs. -->",
  592. wfHostname(), $elapsed );
  593. return $com;
  594. }
  595. /**
  596. * Safety wrapper for debug_backtrace().
  597. *
  598. * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
  599. * murky circumstances, which may be triggered in part by stub objects
  600. * or other fancy talkin'.
  601. *
  602. * Will return an empty array if Zend Optimizer is detected, otherwise
  603. * the output from debug_backtrace() (trimmed).
  604. *
  605. * @return array of backtrace information
  606. */
  607. function wfDebugBacktrace() {
  608. if( extension_loaded( 'Zend Optimizer' ) ) {
  609. wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
  610. return array();
  611. } else {
  612. return array_slice( debug_backtrace(), 1 );
  613. }
  614. }
  615. function wfBacktrace() {
  616. global $wgCommandLineMode;
  617. if ( $wgCommandLineMode ) {
  618. $msg = '';
  619. } else {
  620. $msg = "<ul>\n";
  621. }
  622. $backtrace = wfDebugBacktrace();
  623. foreach( $backtrace as $call ) {
  624. if( isset( $call['file'] ) ) {
  625. $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
  626. $file = $f[count($f)-1];
  627. } else {
  628. $file = '-';
  629. }
  630. if( isset( $call['line'] ) ) {
  631. $line = $call['line'];
  632. } else {
  633. $line = '-';
  634. }
  635. if ( $wgCommandLineMode ) {
  636. $msg .= "$file line $line calls ";
  637. } else {
  638. $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
  639. }
  640. if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
  641. $msg .= $call['function'] . '()';
  642. if ( $wgCommandLineMode ) {
  643. $msg .= "\n";
  644. } else {
  645. $msg .= "</li>\n";
  646. }
  647. }
  648. if ( $wgCommandLineMode ) {
  649. $msg .= "\n";
  650. } else {
  651. $msg .= "</ul>\n";
  652. }
  653. return $msg;
  654. }
  655. /* Some generic result counters, pulled out of SearchEngine */
  656. /**
  657. * @todo document
  658. */
  659. function wfShowingResults( $offset, $limit ) {
  660. global $wgLang;
  661. return wfMsg( 'showingresults', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ) );
  662. }
  663. /**
  664. * @todo document
  665. */
  666. function wfShowingResultsNum( $offset, $limit, $num ) {
  667. global $wgLang;
  668. return wfMsg( 'showingresultsnum', $wgLang->formatNum( $limit ), $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
  669. }
  670. /**
  671. * @todo document
  672. */
  673. function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
  674. global $wgLang;
  675. $fmtLimit = $wgLang->formatNum( $limit );
  676. $prev = wfMsg( 'prevn', $fmtLimit );
  677. $next = wfMsg( 'nextn', $fmtLimit );
  678. if( is_object( $link ) ) {
  679. $title =& $link;
  680. } else {
  681. $title = Title::newFromText( $link );
  682. if( is_null( $title ) ) {
  683. return false;
  684. }
  685. }
  686. if ( 0 != $offset ) {
  687. $po = $offset - $limit;
  688. if ( $po < 0 ) { $po = 0; }
  689. $q = "limit={$limit}&offset={$po}";
  690. if ( '' != $query ) { $q .= '&'.$query; }
  691. $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$prev}</a>";
  692. } else { $plink = $prev; }
  693. $no = $offset + $limit;
  694. $q = 'limit='.$limit.'&offset='.$no;
  695. if ( '' != $query ) { $q .= '&'.$query; }
  696. if ( $atend ) {
  697. $nlink = $next;
  698. } else {
  699. $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$next}</a>";
  700. }
  701. $nums = wfNumLink( $offset, 20, $title, $query ) . ' | ' .
  702. wfNumLink( $offset, 50, $title, $query ) . ' | ' .
  703. wfNumLink( $offset, 100, $title, $query ) . ' | ' .
  704. wfNumLink( $offset, 250, $title, $query ) . ' | ' .
  705. wfNumLink( $offset, 500, $title, $query );
  706. return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
  707. }
  708. /**
  709. * @todo document
  710. */
  711. function wfNumLink( $offset, $limit, &$title, $query = '' ) {
  712. global $wgLang;
  713. if ( '' == $query ) { $q = ''; }
  714. else { $q = $query.'&'; }
  715. $q .= 'limit='.$limit.'&offset='.$offset;
  716. $fmtLimit = $wgLang->formatNum( $limit );
  717. $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\">{$fmtLimit}</a>";
  718. return $s;
  719. }
  720. /**
  721. * @todo document
  722. * @todo FIXME: we may want to blacklist some broken browsers
  723. *
  724. * @return bool Whereas client accept gzip compression
  725. */
  726. function wfClientAcceptsGzip() {
  727. global $wgUseGzip;
  728. if( $wgUseGzip ) {
  729. # FIXME: we may want to blacklist some broken browsers
  730. $m = array();
  731. if( preg_match(
  732. '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
  733. $_SERVER['HTTP_ACCEPT_ENCODING'],
  734. $m ) ) {
  735. if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
  736. wfDebug( " accepts gzip\n" );
  737. return true;
  738. }
  739. }
  740. return false;
  741. }
  742. /**
  743. * Obtain the offset and limit values from the request string;
  744. * used in special pages
  745. *
  746. * @param $deflimit Default limit if none supplied
  747. * @param $optionname Name of a user preference to check against
  748. * @return array
  749. *
  750. */
  751. function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
  752. global $wgRequest;
  753. return $wgRequest->getLimitOffset( $deflimit, $optionname );
  754. }
  755. /**
  756. * Escapes the given text so that it may be output using addWikiText()
  757. * without any linking, formatting, etc. making its way through. This
  758. * is achieved by substituting certain characters with HTML entities.
  759. * As required by the callers, <nowiki> is not used. It currently does
  760. * not filter out characters which have special meaning only at the
  761. * start of a line, such as "*".
  762. *
  763. * @param string $text Text to be escaped
  764. */
  765. function wfEscapeWikiText( $text ) {
  766. $text = str_replace(
  767. array( '[', '|', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ),
  768. array( '&#91;', '&#124;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
  769. htmlspecialchars($text) );
  770. return $text;
  771. }
  772. /**
  773. * @todo document
  774. */
  775. function wfQuotedPrintable( $string, $charset = '' ) {
  776. # Probably incomplete; see RFC 2045
  777. if( empty( $charset ) ) {
  778. global $wgInputEncoding;
  779. $charset = $wgInputEncoding;
  780. }
  781. $charset = strtoupper( $charset );
  782. $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
  783. $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
  784. $replace = $illegal . '\t ?_';
  785. if( !preg_match( "/[$illegal]/", $string ) ) return $string;
  786. $out = "=?$charset?Q?";
  787. $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
  788. $out .= '?=';
  789. return $out;
  790. }
  791. /**
  792. * @todo document
  793. * @return float
  794. */
  795. function wfTime() {
  796. return microtime(true);
  797. }
  798. /**
  799. * Sets dest to source and returns the original value of dest
  800. * If source is NULL, it just returns the value, it doesn't set the variable
  801. */
  802. function wfSetVar( &$dest, $source ) {
  803. $temp = $dest;
  804. if ( !is_null( $source ) ) {
  805. $dest = $source;
  806. }
  807. return $temp;
  808. }
  809. /**
  810. * As for wfSetVar except setting a bit
  811. */
  812. function wfSetBit( &$dest, $bit, $state = true ) {
  813. $temp = (bool)($dest & $bit );
  814. if ( !is_null( $state ) ) {
  815. if ( $state ) {
  816. $dest |= $bit;
  817. } else {
  818. $dest &= ~$bit;
  819. }
  820. }
  821. return $temp;
  822. }
  823. /**
  824. * This function takes two arrays as input, and returns a CGI-style string, e.g.
  825. * "days=7&limit=100". Options in the first array override options in the second.
  826. * Options set to "" will not be output.
  827. */
  828. function wfArrayToCGI( $array1, $array2 = NULL )
  829. {
  830. if ( !is_null( $array2 ) ) {
  831. $array1 = $array1 + $array2;
  832. }
  833. $cgi = '';
  834. foreach ( $array1 as $key => $value ) {
  835. if ( '' !== $value ) {
  836. if ( '' != $cgi ) {
  837. $cgi .= '&';
  838. }
  839. $cgi .= urlencode( $key ) . '=' . urlencode( $value );
  840. }
  841. }
  842. return $cgi;
  843. }
  844. /**
  845. * This is obsolete, use SquidUpdate::purge()
  846. * @deprecated
  847. */
  848. function wfPurgeSquidServers ($urlArr) {
  849. SquidUpdate::purge( $urlArr );
  850. }
  851. /**
  852. * Windows-compatible version of escapeshellarg()
  853. * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
  854. * function puts single quotes in regardless of OS
  855. */
  856. function wfEscapeShellArg( ) {
  857. $args = func_get_args();
  858. $first = true;
  859. $retVal = '';
  860. foreach ( $args as $arg ) {
  861. if ( !$first ) {
  862. $retVal .= ' ';
  863. } else {
  864. $first = false;
  865. }
  866. if ( wfIsWindows() ) {
  867. // Escaping for an MSVC-style command line parser
  868. // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
  869. // Double the backslashes before any double quotes. Escape the double quotes.
  870. $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
  871. $arg = '';
  872. $delim = false;
  873. foreach ( $tokens as $token ) {
  874. if ( $delim ) {
  875. $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
  876. } else {
  877. $arg .= $token;
  878. }
  879. $delim = !$delim;
  880. }
  881. // Double the backslashes before the end of the string, because
  882. // we will soon add a quote
  883. $m = array();
  884. if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
  885. $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
  886. }
  887. // Add surrounding quotes
  888. $retVal .= '"' . $arg . '"';
  889. } else {
  890. $retVal .= escapeshellarg( $arg );
  891. }
  892. }
  893. return $retVal;
  894. }
  895. /**
  896. * wfMerge attempts to merge differences between three texts.
  897. * Returns true for a clean merge and false for failure or a conflict.
  898. */
  899. function wfMerge( $old, $mine, $yours, &$result ){
  900. global $wgDiff3;
  901. # This check may also protect against code injection in
  902. # case of broken installations.
  903. if(! file_exists( $wgDiff3 ) ){
  904. wfDebug( "diff3 not found\n" );
  905. return false;
  906. }
  907. # Make temporary files
  908. $td = wfTempDir();
  909. $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
  910. $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
  911. $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
  912. fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
  913. fwrite( $mytextFile, $mine ); fclose( $mytextFile );
  914. fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
  915. # Check for a conflict
  916. $cmd = $wgDiff3 . ' -a --overlap-only ' .
  917. wfEscapeShellArg( $mytextName ) . ' ' .
  918. wfEscapeShellArg( $oldtextName ) . ' ' .
  919. wfEscapeShellArg( $yourtextName );
  920. $handle = popen( $cmd, 'r' );
  921. if( fgets( $handle, 1024 ) ){
  922. $conflict = true;
  923. } else {
  924. $conflict = false;
  925. }
  926. pclose( $handle );
  927. # Merge differences
  928. $cmd = $wgDiff3 . ' -a -e --merge ' .
  929. wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
  930. $handle = popen( $cmd, 'r' );
  931. $result = '';
  932. do {
  933. $data = fread( $handle, 8192 );
  934. if ( strlen( $data ) == 0 ) {
  935. break;
  936. }
  937. $result .= $data;
  938. } while ( true );
  939. pclose( $handle );
  940. unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
  941. if ( $result === '' && $old !== '' && $conflict == false ) {
  942. wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
  943. $conflict = true;
  944. }
  945. return ! $conflict;
  946. }
  947. /**
  948. * @todo document
  949. */
  950. function wfVarDump( $var ) {
  951. global $wgOut;
  952. $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
  953. if ( headers_sent() || !@is_object( $wgOut ) ) {
  954. print $s;
  955. } else {
  956. $wgOut->addHTML( $s );
  957. }
  958. }
  959. /**
  960. * Provide a simple HTTP error.
  961. */
  962. function wfHttpError( $code, $label, $desc ) {
  963. global $wgOut;
  964. $wgOut->disable();
  965. header( "HTTP/1.0 $code $label" );
  966. header( "Status: $code $label" );
  967. $wgOut->sendCacheControl();
  968. header( 'Content-type: text/html; charset=utf-8' );
  969. print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
  970. "<html><head><title>" .
  971. htmlspecialchars( $label ) .
  972. "</title></head><body><h1>" .
  973. htmlspecialchars( $label ) .
  974. "</h1><p>" .
  975. nl2br( htmlspecialchars( $desc ) ) .
  976. "</p></body></html>\n";
  977. }
  978. /**
  979. * Clear away any user-level output buffers, discarding contents.
  980. *
  981. * Suitable for 'starting afresh', for instance when streaming
  982. * relatively large amounts of data without buffering, or wanting to
  983. * output image files without ob_gzhandler's compression.
  984. *
  985. * The optional $resetGzipEncoding parameter controls suppression of
  986. * the Content-Encoding header sent by ob_gzhandler; by default it
  987. * is left. See comments for wfClearOutputBuffers() for why it would
  988. * be used.
  989. *
  990. * Note that some PHP configuration options may add output buffer
  991. * layers which cannot be removed; these are left in place.
  992. *
  993. * @parameter bool $resetGzipEncoding
  994. */
  995. function wfResetOutputBuffers( $resetGzipEncoding=true ) {
  996. while( $status = ob_get_status() ) {
  997. if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
  998. // Probably from zlib.output_compression or other
  999. // PHP-internal setting which can't be removed.
  1000. //
  1001. // Give up, and hope the result doesn't break
  1002. // output behavior.
  1003. break;
  1004. }
  1005. if( !ob_end_clean() ) {
  1006. // Could not remove output buffer handler; abort now
  1007. // to avoid getting in some kind of infinite loop.
  1008. break;
  1009. }
  1010. if( $resetGzipEncoding ) {
  1011. if( $status['name'] == 'ob_gzhandler' ) {
  1012. // Reset the 'Content-Encoding' field set by this handler
  1013. // so we can start fresh.
  1014. header( 'Content-Encoding:' );
  1015. }
  1016. }
  1017. }
  1018. }
  1019. /**
  1020. * More legible than passing a 'false' parameter to wfResetOutputBuffers():
  1021. *
  1022. * Clear away output buffers, but keep the Content-Encoding header
  1023. * produced by ob_gzhandler, if any.
  1024. *
  1025. * This should be used for HTTP 304 responses, where you need to
  1026. * preserve the Content-Encoding header of the real result, but
  1027. * also need to suppress the output of ob_gzhandler to keep to spec
  1028. * and avoid breaking Firefox in rare cases where the headers and
  1029. * body are broken over two packets.
  1030. */
  1031. function wfClearOutputBuffers() {
  1032. wfResetOutputBuffers( false );
  1033. }
  1034. /**
  1035. * Converts an Accept-* header into an array mapping string values to quality
  1036. * factors
  1037. */
  1038. function wfAcceptToPrefs( $accept, $def = '*/*' ) {
  1039. # No arg means accept anything (per HTTP spec)
  1040. if( !$accept ) {
  1041. return array( $def => 1 );
  1042. }
  1043. $prefs = array();
  1044. $parts = explode( ',', $accept );
  1045. foreach( $parts as $part ) {
  1046. # FIXME: doesn't deal with params like 'text/html; level=1'
  1047. @list( $value, $qpart ) = explode( ';', $part );
  1048. $match = array();
  1049. if( !isset( $qpart ) ) {
  1050. $prefs[$value] = 1;
  1051. } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
  1052. $prefs[$value] = $match[1];
  1053. }
  1054. }
  1055. return $prefs;
  1056. }
  1057. /**
  1058. * Checks if a given MIME type matches any of the keys in the given
  1059. * array. Basic wildcards are accepted in the array keys.
  1060. *
  1061. * Returns the matching MIME type (or wildcard) if a match, otherwise
  1062. * NULL if no match.
  1063. *
  1064. * @param string $type
  1065. * @param array $avail
  1066. * @return string
  1067. * @private
  1068. */
  1069. function mimeTypeMatch( $type, $avail ) {
  1070. if( array_key_exists($type, $avail) ) {
  1071. return $type;
  1072. } else {
  1073. $parts = explode( '/', $type );
  1074. if( array_key_exists( $parts[0] . '/*', $avail ) ) {
  1075. return $parts[0] . '/*';
  1076. } elseif( array_key_exists( '*/*', $avail ) ) {
  1077. return '*/*';
  1078. } else {
  1079. return NULL;
  1080. }
  1081. }
  1082. }
  1083. /**
  1084. * Returns the 'best' match between a client's requested internet media types
  1085. * and the server's list of available types. Each list should be an associative
  1086. * array of type to preference (preference is a float between 0.0 and 1.0).
  1087. * Wildcards in the types are acceptable.
  1088. *
  1089. * @param array $cprefs Client's acceptable type list
  1090. * @param array $sprefs Server's offered types
  1091. * @return string
  1092. *
  1093. * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
  1094. * XXX: generalize to negotiate other stuff
  1095. */
  1096. function wfNegotiateType( $cprefs, $sprefs ) {
  1097. $combine = array();
  1098. foreach( array_keys($sprefs) as $type ) {
  1099. $parts = explode( '/', $type );
  1100. if( $parts[1] != '*' ) {
  1101. $ckey = mimeTypeMatch( $type, $cprefs );
  1102. if( $ckey ) {
  1103. $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
  1104. }
  1105. }
  1106. }
  1107. foreach( array_keys( $cprefs ) as $type ) {
  1108. $parts = explode( '/', $type );
  1109. if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
  1110. $skey = mimeTypeMatch( $type, $sprefs );
  1111. if( $skey ) {
  1112. $combine[$type] = $sprefs[$skey] * $cprefs[$type];
  1113. }
  1114. }
  1115. }
  1116. $bestq = 0;
  1117. $besttype = NULL;
  1118. foreach( array_keys( $combine ) as $type ) {
  1119. if( $combine[$type] > $bestq ) {
  1120. $besttype = $type;
  1121. $bestq = $combine[$type];
  1122. }
  1123. }
  1124. return $besttype;
  1125. }
  1126. /**
  1127. * Array lookup
  1128. * Returns an array where the values in the first array are replaced by the
  1129. * values in the second array with the corresponding keys
  1130. *
  1131. * @return array
  1132. */
  1133. function wfArrayLookup( $a, $b ) {
  1134. return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
  1135. }
  1136. /**
  1137. * Convenience function; returns MediaWiki timestamp for the present time.
  1138. * @return string
  1139. */
  1140. function wfTimestampNow() {
  1141. # return NOW
  1142. return wfTimestamp( TS_MW, time() );
  1143. }
  1144. /**
  1145. * Reference-counted warning suppression
  1146. */
  1147. function wfSuppressWarnings( $end = false ) {
  1148. static $suppressCount = 0;
  1149. static $originalLevel = false;
  1150. if ( $end ) {
  1151. if ( $suppressCount ) {
  1152. --$suppressCount;
  1153. if ( !$suppressCount ) {
  1154. error_reporting( $originalLevel );
  1155. }
  1156. }
  1157. } else {
  1158. if ( !$suppressCount ) {
  1159. $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
  1160. }
  1161. ++$suppressCount;
  1162. }
  1163. }
  1164. /**
  1165. * Restore error level to previous value
  1166. */
  1167. function wfRestoreWarnings() {
  1168. wfSuppressWarnings( true );
  1169. }
  1170. # Autodetect, convert and provide timestamps of various types
  1171. /**
  1172. * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
  1173. */
  1174. define('TS_UNIX', 0);
  1175. /**
  1176. * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
  1177. */
  1178. define('TS_MW', 1);
  1179. /**
  1180. * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
  1181. */
  1182. define('TS_DB', 2);
  1183. /**
  1184. * RFC 2822 format, for E-mail and HTTP headers
  1185. */
  1186. define('TS_RFC2822', 3);
  1187. /**
  1188. * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
  1189. *
  1190. * This is used by Special:Export
  1191. */
  1192. define('TS_ISO_8601', 4);
  1193. /**
  1194. * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
  1195. *
  1196. * @url http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
  1197. * DateTime tag and page 36 for the DateTimeOriginal and
  1198. * DateTimeDigitized tags.
  1199. */
  1200. define('TS_EXIF', 5);
  1201. /**
  1202. * Oracle format time.
  1203. */
  1204. define('TS_ORACLE', 6);
  1205. /**
  1206. * Postgres format time.
  1207. */
  1208. define('TS_POSTGRES', 7);
  1209. /**
  1210. * @param mixed $outputtype A timestamp in one of the supported formats, the
  1211. * function will autodetect which format is supplied
  1212. * and act accordingly.
  1213. * @return string Time in the format specified in $outputtype
  1214. */
  1215. function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
  1216. $uts = 0;
  1217. $da = array();
  1218. if ($ts==0) {
  1219. $uts=time();
  1220. } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
  1221. # TS_DB
  1222. $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
  1223. (int)$da[2],(int)$da[3],(int)$da[1]);
  1224. } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
  1225. # TS_EXIF
  1226. $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
  1227. (int)$da[2],(int)$da[3],(int)$da[1]);
  1228. } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
  1229. # TS_MW
  1230. $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
  1231. (int)$da[2],(int)$da[3],(int)$da[1]);
  1232. } elseif (preg_match('/^(\d{1,13})$/D',$ts,$da)) {
  1233. # TS_UNIX
  1234. $uts = $ts;
  1235. } elseif (preg_match('/^(\d{1,2})-(...)-(\d\d(\d\d)?) (\d\d)\.(\d\d)\.(\d\d)/', $ts, $da)) {
  1236. # TS_ORACLE
  1237. $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
  1238. str_replace("+00:00", "UTC", $ts)));
  1239. } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $ts, $da)) {
  1240. # TS_ISO_8601
  1241. $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
  1242. (int)$da[2],(int)$da[3],(int)$da[1]);
  1243. } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)[\+\- ](\d\d)$/',$ts,$da)) {
  1244. # TS_POSTGRES
  1245. $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
  1246. (int)$da[2],(int)$da[3],(int)$da[1]);
  1247. } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/',$ts,$da)) {
  1248. # TS_POSTGRES
  1249. $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
  1250. (int)$da[2],(int)$da[3],(int)$da[1]);
  1251. } else {
  1252. # Bogus value; fall back to the epoch...
  1253. wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
  1254. $uts = 0;
  1255. }
  1256. switch($outputtype) {
  1257. case TS_UNIX:
  1258. return $uts;
  1259. case TS_MW:
  1260. return gmdate( 'YmdHis', $uts );
  1261. case TS_DB:
  1262. return gmdate( 'Y-m-d H:i:s', $uts );
  1263. case TS_ISO_8601:
  1264. return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
  1265. // This shouldn't ever be used, but is included for completeness
  1266. case TS_EXIF:
  1267. return gmdate( 'Y:m:d H:i:s', $uts );
  1268. case TS_RFC2822:
  1269. return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
  1270. case TS_ORACLE:
  1271. return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
  1272. case TS_POSTGRES:
  1273. return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
  1274. default:
  1275. throw new MWException( 'wfTimestamp() called with illegal output type.');
  1276. }
  1277. }
  1278. /**
  1279. * Return a formatted timestamp, or null if input is null.
  1280. * For dealing with nullable timestamp columns in the database.
  1281. * @param int $outputtype
  1282. * @param string $ts
  1283. * @return string
  1284. */
  1285. function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
  1286. if( is_null( $ts ) ) {
  1287. return null;
  1288. } else {
  1289. return wfTimestamp( $outputtype, $ts );
  1290. }
  1291. }
  1292. /**
  1293. * Check if the operating system is Windows
  1294. *
  1295. * @return bool True if it's Windows, False otherwise.
  1296. */
  1297. function wfIsWindows() {
  1298. if (substr(php_uname(), 0, 7) == 'Windows') {
  1299. return true;
  1300. } else {
  1301. return false;
  1302. }
  1303. }
  1304. /**
  1305. * Swap two variables
  1306. */
  1307. function swap( &$x, &$y ) {
  1308. $z = $x;
  1309. $x = $y;
  1310. $y = $z;
  1311. }
  1312. function wfGetCachedNotice( $name ) {
  1313. global $wgOut, $parserMemc;
  1314. $fname = 'wfGetCachedNotice';
  1315. wfProfileIn( $fname );
  1316. $needParse = false;
  1317. if( $name === 'default' ) {
  1318. // special case
  1319. global $wgSiteNotice;
  1320. $notice = $wgSiteNotice;
  1321. if( empty( $notice ) ) {
  1322. wfProfileOut( $fname );
  1323. return false;
  1324. }
  1325. } else {
  1326. $notice = wfMsgForContentNoTrans( $name );
  1327. if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
  1328. wfProfileOut( $fname );
  1329. return( false );
  1330. }
  1331. }
  1332. $cachedNotice = $parserMemc->get( wfMemcKey( $name ) );
  1333. if( is_array( $cachedNotice ) ) {
  1334. if( md5( $notice ) == $cachedNotice['hash'] ) {
  1335. $notice = $cachedNotice['html'];
  1336. } else {
  1337. $needParse = true;
  1338. }
  1339. } else {
  1340. $needParse = true;
  1341. }
  1342. if( $needParse ) {
  1343. if( is_object( $wgOut ) ) {
  1344. $parsed = $wgOut->parse( $notice );
  1345. $parserMemc->set( wfMemcKey( $name ), array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
  1346. $notice = $parsed;
  1347. } else {
  1348. wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available' );
  1349. $notice = '';
  1350. }
  1351. }
  1352. wfProfileOut( $fname );
  1353. return $notice;
  1354. }
  1355. function wfGetNamespaceNotice() {
  1356. global $wgTitle;
  1357. # Paranoia
  1358. if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
  1359. return "";
  1360. $fname = 'wfGetNamespaceNotice';
  1361. wfProfileIn( $fname );
  1362. $key = "namespacenotice-" . $wgTitle->getNsText();
  1363. $namespaceNotice = wfGetCachedNotice( $key );
  1364. if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
  1365. $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
  1366. } else {
  1367. $namespaceNotice = "";
  1368. }
  1369. wfProfileOut( $fname );
  1370. return $namespaceNotice;
  1371. }
  1372. function wfGetSiteNotice() {
  1373. global $wgUser, $wgSiteNotice;
  1374. $fname = 'wfGetSiteNotice';
  1375. wfProfileIn( $fname );
  1376. $siteNotice = '';
  1377. if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
  1378. if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
  1379. $siteNotice = wfGetCachedNotice( 'sitenotice' );
  1380. } else {
  1381. $anonNotice = wfGetCachedNotice( 'anonnotice' );
  1382. if( !$anonNotice ) {
  1383. $siteNotice = wfGetCachedNotice( 'sitenotice' );
  1384. } else {
  1385. $siteNotice = $anonNotice;
  1386. }
  1387. }
  1388. if( !$siteNotice ) {
  1389. $siteNotice = wfGetCachedNotice( 'default' );
  1390. }
  1391. }
  1392. wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
  1393. wfProfileOut( $fname );
  1394. return $siteNotice;
  1395. }
  1396. /**
  1397. * BC wrapper for MimeMagic::singleton()
  1398. * @deprecated
  1399. */
  1400. function &wfGetMimeMagic() {
  1401. return MimeMagic::singleton();
  1402. }
  1403. /**
  1404. * Tries to get the system directory for temporary files.
  1405. * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
  1406. * and if none are set /tmp is returned as the generic Unix default.
  1407. *
  1408. * NOTE: When possible, use the tempfile() function to create temporary
  1409. * files to avoid race conditions on file creation, etc.
  1410. *
  1411. * @return string
  1412. */
  1413. function wfTempDir() {
  1414. foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
  1415. $tmp = getenv( $var );
  1416. if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
  1417. return $tmp;
  1418. }
  1419. }
  1420. # Hope this is Unix of some kind!
  1421. return '/tmp';
  1422. }
  1423. /**
  1424. * Make directory, and make all parent directories if they don't exist
  1425. */
  1426. function wfMkdirParents( $fullDir, $mode = 0777 ) {
  1427. if ( strval( $fullDir ) === '' ) {
  1428. return true;
  1429. }
  1430. # Go back through the paths to find the first directory that exists
  1431. $currentDir = $fullDir;
  1432. $createList = array();
  1433. while ( strval( $currentDir ) !== '' && !file_exists( $currentDir ) ) {
  1434. # Strip trailing slashes
  1435. $currentDir = rtrim( $currentDir, '/\\' );
  1436. # Add to create list
  1437. $createList[] = $currentDir;
  1438. # Find next delimiter searching from the end
  1439. $p = max( strrpos( $currentDir, '/' ), strrpos( $currentDir, '\\' ) );
  1440. if ( $p === false ) {
  1441. $currentDir = false;
  1442. } else {
  1443. $currentDir = substr( $currentDir, 0, $p );
  1444. }
  1445. }
  1446. if ( count( $createList ) == 0 ) {
  1447. # Directory specified already exists
  1448. return true;
  1449. } elseif ( $currentDir === false ) {
  1450. # Went all the way back to root and it apparently doesn't exist
  1451. return false;
  1452. }
  1453. # Now go forward creating directories
  1454. $createList = array_reverse( $createList );
  1455. foreach ( $createList as $dir ) {
  1456. # use chmod to override the umask, as suggested by the PHP manual
  1457. if ( !mkdir( $dir, $mode ) || !chmod( $dir, $mode ) ) {
  1458. return false;
  1459. }
  1460. }
  1461. return true;
  1462. }
  1463. /**
  1464. * Increment a statistics counter
  1465. */
  1466. function wfIncrStats( $key ) {
  1467. global $wgMemc;
  1468. $key = wfMemcKey( 'stats', $key );
  1469. if ( is_null( $wgMemc->incr( $key ) ) ) {
  1470. $wgMemc->add( $key, 1 );
  1471. }
  1472. }
  1473. /**
  1474. * @param mixed $nr The number to format
  1475. * @param int $acc The number of digits after the decimal point, default 2
  1476. * @param bool $round Whether or not to round the value, default true
  1477. * @return float
  1478. */
  1479. function wfPercent( $nr, $acc = 2, $round = true ) {
  1480. $ret = sprintf( "%.${acc}f", $nr );
  1481. return $round ? round( $ret, $acc ) . '%' : "$ret%";
  1482. }
  1483. /**
  1484. * Encrypt a username/password.
  1485. *
  1486. * @param string $userid ID of the user
  1487. * @param string $password Password of the user
  1488. * @return string Hashed password
  1489. */
  1490. function wfEncryptPassword( $userid, $password ) {
  1491. global $wgPasswordSalt;
  1492. $p = md5( $password);
  1493. if($wgPasswordSalt)
  1494. return md5( "{$userid}-{$p}" );
  1495. else
  1496. return $p;
  1497. }
  1498. /**
  1499. * Appends to second array if $value differs from that in $default
  1500. */
  1501. function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
  1502. if ( is_null( $changed ) ) {
  1503. throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
  1504. }
  1505. if ( $default[$key] !== $value ) {
  1506. $changed[$key] = $value;
  1507. }
  1508. }
  1509. /**
  1510. * Since wfMsg() and co suck, they don't return false if the message key they
  1511. * looked up didn't exist but a XHTML string, this function checks for the
  1512. * nonexistance of messages by looking at wfMsg() output
  1513. *
  1514. * @param $msg The message key looked up
  1515. * @param $wfMsgOut The output of wfMsg*()
  1516. * @return bool
  1517. */
  1518. function wfEmptyMsg( $msg, $wfMsgOut ) {
  1519. return $wfMsgOut === "&lt;$msg&gt;";
  1520. }
  1521. /**
  1522. * Find out whether or not a mixed variable exists in a string
  1523. *
  1524. * @param mixed needle
  1525. * @param string haystack
  1526. * @return bool
  1527. */
  1528. function in_string( $needle, $str ) {
  1529. return strpos( $str, $needle ) !== false;
  1530. }
  1531. function wfSpecialList( $page, $details ) {
  1532. global $wgContLang;
  1533. $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
  1534. return $page . $details;
  1535. }
  1536. /**
  1537. * Returns a regular expression of url protocols
  1538. *
  1539. * @return string
  1540. */
  1541. function wfUrlProtocols() {
  1542. global $wgUrlProtocols;
  1543. // Support old-style $wgUrlProtocols strings, for backwards compatibility
  1544. // with LocalSettings files from 1.5
  1545. if ( is_array( $wgUrlProtocols ) ) {
  1546. $protocols = array();
  1547. foreach ($wgUrlProtocols as $protocol)
  1548. $protocols[] = preg_quote( $protocol, '/' );
  1549. return implode( '|', $protocols );
  1550. } else {
  1551. return $wgUrlProtocols;
  1552. }
  1553. }
  1554. /**
  1555. * Execute a shell command, with time and memory limits mirrored from the PHP
  1556. * configuration if supported.
  1557. * @param $cmd Command line, properly escaped for shell.
  1558. * @param &$retval optional, will receive the program's exit code.
  1559. * (non-zero is usually failure)
  1560. * @return collected stdout as a string (trailing newlines stripped)
  1561. */
  1562. function wfShellExec( $cmd, &$retval=null ) {
  1563. global $IP, $wgMaxShellMemory, $wgMaxShellFileSize;
  1564. if( ini_get( 'safe_mode' ) ) {
  1565. wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
  1566. $retval = 1;
  1567. return "Unable to run external programs in safe mode.";
  1568. }
  1569. if ( php_uname( 's' ) == 'Linux' ) {
  1570. $time = ini_get( 'max_execution_time' );
  1571. $mem = intval( $wgMaxShellMemory );
  1572. $filesize = intval( $wgMaxShellFileSize );
  1573. if ( $time > 0 && $mem > 0 ) {
  1574. $script = "$IP/bin/ulimit-tvf.sh";
  1575. if ( is_executable( $script ) ) {
  1576. $cmd = escapeshellarg( $script ) . " $time $mem $filesize $cmd";
  1577. }
  1578. }
  1579. } elseif ( php_uname( 's' ) == 'Windows NT' ) {
  1580. # This is a hack to work around PHP's flawed invocation of cmd.exe
  1581. # http://news.php.net/php.internals/21796
  1582. $cmd = '"' . $cmd . '"';
  1583. }
  1584. wfDebug( "wfShellExec: $cmd\n" );
  1585. $output = array();
  1586. $retval = 1; // error by default?
  1587. exec( $cmd, $output, $retval ); // returns the last line of output.
  1588. return implode( "\n", $output );
  1589. }
  1590. /**
  1591. * This function works like "use VERSION" in Perl, the program will die with a
  1592. * backtrace if the current version of PHP is less than the version provided
  1593. *
  1594. * This is useful for extensions which due to their nature are not kept in sync
  1595. * with releases, and might depend on other versions of PHP than the main code
  1596. *
  1597. * Note: PHP might die due to parsing errors in some cases before it ever
  1598. * manages to call this function, such is life
  1599. *
  1600. * @see perldoc -f use
  1601. *
  1602. * @param mixed $version The version to check, can be a string, an integer, or
  1603. * a float
  1604. */
  1605. function wfUsePHP( $req_ver ) {
  1606. $php_ver = PHP_VERSION;
  1607. if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
  1608. throw new MWException( "PHP $req_ver required--this is only $php_ver" );
  1609. }
  1610. /**
  1611. * This function works like "use VERSION" in Perl except it checks the version
  1612. * of MediaWiki, the program will die with a backtrace if the current version
  1613. * of MediaWiki is less than the version provided.
  1614. *
  1615. * This is useful for extensions which due to their nature are not kept in sync
  1616. * with releases
  1617. *
  1618. * @see perldoc -f use
  1619. *
  1620. * @param mixed $version The version to check, can be a string, an integer, or
  1621. * a float
  1622. */
  1623. function wfUseMW( $req_ver ) {
  1624. global $wgVersion;
  1625. if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
  1626. throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
  1627. }
  1628. /**
  1629. * @deprecated use StringUtils::escapeRegexReplacement
  1630. */
  1631. function wfRegexReplacement( $string ) {
  1632. return StringUtils::escapeRegexReplacement( $string );
  1633. }
  1634. /**
  1635. * Return the final portion of a pathname.
  1636. * Reimplemented because PHP5's basename() is buggy with multibyte text.
  1637. * http://bugs.php.net/bug.php?id=33898
  1638. *
  1639. * PHP's basename() only considers '\' a pathchar on Windows and Netware.
  1640. * We'll consider it so always, as we don't want \s in our Unix paths either.
  1641. *
  1642. * @param string $path
  1643. * @return string
  1644. */
  1645. function wfBaseName( $path ) {
  1646. $matches = array();
  1647. if( preg_match( '#([^/\\\\]*)[/\\\\]*$#', $path, $matches ) ) {
  1648. return $matches[1];
  1649. } else {
  1650. return '';
  1651. }
  1652. }
  1653. /**
  1654. * Make a URL index, appropriate for the el_index field of externallinks.
  1655. */
  1656. function wfMakeUrlIndex( $url ) {
  1657. wfSuppressWarnings();
  1658. $bits = parse_url( $url );
  1659. wfRestoreWarnings();
  1660. if ( !$bits || $bits['scheme'] !== 'http' ) {
  1661. return false;
  1662. }
  1663. // Reverse the labels in the hostname, convert to lower case
  1664. $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
  1665. // Add an extra dot to the end
  1666. if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
  1667. $reversedHost .= '.';
  1668. }
  1669. // Reconstruct the pseudo-URL
  1670. $index = "http://$reversedHost";
  1671. // Leave out user and password. Add the port, path, query and fragment
  1672. if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
  1673. if ( isset( $bits['path'] ) ) {
  1674. $index .= $bits['path'];
  1675. } else {
  1676. $index .= '/';
  1677. }
  1678. if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
  1679. if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
  1680. return $index;
  1681. }
  1682. /**
  1683. * Do any deferred updates and clear the list
  1684. * TODO: This could be in Wiki.php if that class made any sense at all
  1685. */
  1686. function wfDoUpdates()
  1687. {
  1688. global $wgPostCommitUpdateList, $wgDeferredUpdateList;
  1689. foreach ( $wgDeferredUpdateList as $update ) {
  1690. $update->doUpdate();
  1691. }
  1692. foreach ( $wgPostCommitUpdateList as $update ) {
  1693. $update->doUpdate();
  1694. }
  1695. $wgDeferredUpdateList = array();
  1696. $wgPostCommitUpdateList = array();
  1697. }
  1698. /**
  1699. * @deprecated use StringUtils::explodeMarkup
  1700. */
  1701. function wfExplodeMarkup( $separator, $text ) {
  1702. return StringUtils::explodeMarkup( $separator, $text );
  1703. }
  1704. /**
  1705. * Convert an arbitrarily-long digit string from one numeric base
  1706. * to another, optionally zero-padding to a minimum column width.
  1707. *
  1708. * Supports base 2 through 36; digit values 10-36 are represented
  1709. * as lowercase letters a-z. Input is case-insensitive.
  1710. *
  1711. * @param $input string of digits
  1712. * @param $sourceBase int 2-36
  1713. * @param $destBase int 2-36
  1714. * @param $pad int 1 or greater
  1715. * @return string or false on invalid input
  1716. */
  1717. function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1 ) {
  1718. if( $sourceBase < 2 ||
  1719. $sourceBase > 36 ||
  1720. $destBase < 2 ||
  1721. $destBase > 36 ||
  1722. $pad < 1 ||
  1723. $sourceBase != intval( $sourceBase ) ||
  1724. $destBase != intval( $destBase ) ||
  1725. $pad != intval( $pad ) ||
  1726. !is_string( $input ) ||
  1727. $input == '' ) {
  1728. return false;
  1729. }
  1730. $digitChars = '0123456789abcdefghijklmnopqrstuvwxyz';
  1731. $inDigits = array();
  1732. $outChars = '';
  1733. // Decode and validate input string
  1734. $input = strtolower( $input );
  1735. for( $i = 0; $i < strlen( $input ); $i++ ) {
  1736. $n = strpos( $digitChars, $input{$i} );
  1737. if( $n === false || $n > $sourceBase ) {
  1738. return false;
  1739. }
  1740. $inDigits[] = $n;
  1741. }
  1742. // Iterate over the input, modulo-ing out an output digit
  1743. // at a time until input is gone.
  1744. while( count( $inDigits ) ) {
  1745. $work = 0;
  1746. $workDigits = array();
  1747. // Long division...
  1748. foreach( $inDigits as $digit ) {
  1749. $work *= $sourceBase;
  1750. $work += $digit;
  1751. if( $work < $destBase ) {
  1752. // Gonna need to pull another digit.
  1753. if( count( $workDigits ) ) {
  1754. // Avoid zero-padding; this lets us find
  1755. // the end of the input very easily when
  1756. // length drops to zero.
  1757. $workDigits[] = 0;
  1758. }
  1759. } else {
  1760. // Finally! Actual division!
  1761. $workDigits[] = intval( $work / $destBase );
  1762. // Isn't it annoying that most programming languages
  1763. // don't have a single divide-and-remainder operator,
  1764. // even though the CPU implements it that way?
  1765. $work = $work % $destBase;
  1766. }
  1767. }
  1768. // All that division leaves us with a remainder,
  1769. // which is conveniently our next output digit.
  1770. $outChars .= $digitChars[$work];
  1771. // And we continue!
  1772. $inDigits = $workDigits;
  1773. }
  1774. while( strlen( $outChars ) < $pad ) {
  1775. $outChars .= '0';
  1776. }
  1777. return strrev( $outChars );
  1778. }
  1779. /**
  1780. * Create an object with a given name and an array of construct parameters
  1781. * @param string $name
  1782. * @param array $p parameters
  1783. */
  1784. function wfCreateObject( $name, $p ){
  1785. $p = array_values( $p );
  1786. switch ( count( $p ) ) {
  1787. case 0:
  1788. return new $name;
  1789. case 1:
  1790. return new $name( $p[0] );
  1791. case 2:
  1792. return new $name( $p[0], $p[1] );
  1793. case 3:
  1794. return new $name( $p[0], $p[1], $p[2] );
  1795. case 4:
  1796. return new $name( $p[0], $p[1], $p[2], $p[3] );
  1797. case 5:
  1798. return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
  1799. case 6:
  1800. return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
  1801. default:
  1802. throw new MWException( "Too many arguments to construtor in wfCreateObject" );
  1803. }
  1804. }
  1805. /**
  1806. * Aliases for modularized functions
  1807. */
  1808. function wfGetHTTP( $url, $timeout = 'default' ) {
  1809. return Http::get( $url, $timeout );
  1810. }
  1811. function wfIsLocalURL( $url ) {
  1812. return Http::isLocalURL( $url );
  1813. }
  1814. /**
  1815. * Initialise php session
  1816. */
  1817. function wfSetupSession() {
  1818. global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
  1819. if( $wgSessionsInMemcached ) {
  1820. require_once( 'MemcachedSessions.php' );
  1821. } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
  1822. # If it's left on 'user' or another setting from another
  1823. # application, it will end up failing. Try to recover.
  1824. ini_set ( 'session.save_handler', 'files' );
  1825. }
  1826. session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
  1827. session_cache_limiter( 'private, must-revalidate' );
  1828. @session_start();
  1829. }
  1830. /**
  1831. * Get an object from the precompiled serialized directory
  1832. *
  1833. * @return mixed The variable on success, false on failure
  1834. */
  1835. function wfGetPrecompiledData( $name ) {
  1836. global $IP;
  1837. $file = "$IP/serialized/$name";
  1838. if ( file_exists( $file ) ) {
  1839. $blob = file_get_contents( $file );
  1840. if ( $blob ) {
  1841. return unserialize( $blob );
  1842. }
  1843. }
  1844. return false;
  1845. }
  1846. function wfGetCaller( $level = 2 ) {
  1847. $backtrace = wfDebugBacktrace();
  1848. if ( isset( $backtrace[$level] ) ) {
  1849. if ( isset( $backtrace[$level]['class'] ) ) {
  1850. $caller = $backtrace[$level]['class'] . '::' . $backtrace[$level]['function'];
  1851. } else {
  1852. $caller = $backtrace[$level]['function'];
  1853. }
  1854. } else {
  1855. $caller = 'unknown';
  1856. }
  1857. return $caller;
  1858. }
  1859. /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
  1860. function wfGetAllCallers() {
  1861. return implode('/', array_map(
  1862. create_function('$frame','
  1863. return isset( $frame["class"] )?
  1864. $frame["class"]."::".$frame["function"]:
  1865. $frame["function"];
  1866. '),
  1867. array_reverse(wfDebugBacktrace())));
  1868. }
  1869. /**
  1870. * Get a cache key
  1871. */
  1872. function wfMemcKey( /*... */ ) {
  1873. global $wgDBprefix, $wgDBname;
  1874. $args = func_get_args();
  1875. if ( $wgDBprefix ) {
  1876. $key = "$wgDBname-$wgDBprefix:" . implode( ':', $args );
  1877. } else {
  1878. $key = $wgDBname . ':' . implode( ':', $args );
  1879. }
  1880. return $key;
  1881. }
  1882. /**
  1883. * Get a cache key for a foreign DB
  1884. */
  1885. function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
  1886. $args = array_slice( func_get_args(), 2 );
  1887. if ( $prefix ) {
  1888. $key = "$db-$prefix:" . implode( ':', $args );
  1889. } else {
  1890. $key = $db . ':' . implode( ':', $args );
  1891. }
  1892. return $key;
  1893. }
  1894. /**
  1895. * Get an ASCII string identifying this wiki
  1896. * This is used as a prefix in memcached keys
  1897. */
  1898. function wfWikiID() {
  1899. global $wgDBprefix, $wgDBname;
  1900. if ( $wgDBprefix ) {
  1901. return "$wgDBname-$wgDBprefix";
  1902. } else {
  1903. return $wgDBname;
  1904. }
  1905. }
  1906. /*
  1907. * Get a Database object
  1908. * @param integer $db Index of the connection to get. May be DB_MASTER for the
  1909. * master (for write queries), DB_SLAVE for potentially lagged
  1910. * read queries, or an integer >= 0 for a particular server.
  1911. *
  1912. * @param mixed $groups Query groups. An array of group names that this query
  1913. * belongs to. May contain a single string if the query is only
  1914. * in one group.
  1915. */
  1916. function &wfGetDB( $db = DB_LAST, $groups = array() ) {
  1917. global $wgLoadBalancer;
  1918. $ret = $wgLoadBalancer->getConnection( $db, true, $groups );
  1919. return $ret;
  1920. }
  1921. ?>