GlobalFunctions.php 83 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040
  1. <?php
  2. if ( !defined( 'MEDIAWIKI' ) ) {
  3. die( "This file is part of MediaWiki, it is not a valid entry point" );
  4. }
  5. /**
  6. * Global functions used everywhere
  7. */
  8. require_once dirname(__FILE__) . '/normal/UtfNormalUtil.php';
  9. require_once dirname(__FILE__) . '/XmlFunctions.php';
  10. // Hide compatibility functions from Doxygen
  11. /// @cond
  12. /**
  13. * Compatibility functions
  14. *
  15. * We more or less support PHP 5.0.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(strcasecmp( $from, $to ) == 0) return $string;
  25. if(strcasecmp( $from, 'utf-8' ) == 0) return utf8_decode( $string );
  26. if(strcasecmp( $to, 'utf-8' ) == 0) return utf8_encode( $string );
  27. return $string;
  28. }
  29. }
  30. # UTF-8 substr function based on a PHP manual comment
  31. if ( !function_exists( 'mb_substr' ) ) {
  32. function mb_substr( $str, $start ) {
  33. $ar = array();
  34. preg_match_all( '/./us', $str, $ar );
  35. if( func_num_args() >= 3 ) {
  36. $end = func_get_arg( 2 );
  37. return join( '', array_slice( $ar[0], $start, $end ) );
  38. } else {
  39. return join( '', array_slice( $ar[0], $start ) );
  40. }
  41. }
  42. }
  43. if ( !function_exists( 'mb_strlen' ) ) {
  44. /**
  45. * Fallback implementation of mb_strlen, hardcoded to UTF-8.
  46. * @param string $str
  47. * @param string $enc optional encoding; ignored
  48. * @return int
  49. */
  50. function mb_strlen( $str, $enc="" ) {
  51. $counts = count_chars( $str );
  52. $total = 0;
  53. // Count ASCII bytes
  54. for( $i = 0; $i < 0x80; $i++ ) {
  55. $total += $counts[$i];
  56. }
  57. // Count multibyte sequence heads
  58. for( $i = 0xc0; $i < 0xff; $i++ ) {
  59. $total += $counts[$i];
  60. }
  61. return $total;
  62. }
  63. }
  64. if ( !function_exists( 'array_diff_key' ) ) {
  65. /**
  66. * Exists in PHP 5.1.0+
  67. * Not quite compatible, two-argument version only
  68. * Null values will cause problems due to this use of isset()
  69. */
  70. function array_diff_key( $left, $right ) {
  71. $result = $left;
  72. foreach ( $left as $key => $unused ) {
  73. if ( isset( $right[$key] ) ) {
  74. unset( $result[$key] );
  75. }
  76. }
  77. return $result;
  78. }
  79. }
  80. // Support for Wietse Venema's taint feature
  81. if ( !function_exists( 'istainted' ) ) {
  82. function istainted( $var ) {
  83. return 0;
  84. }
  85. function taint( $var, $level = 0 ) {}
  86. function untaint( $var, $level = 0 ) {}
  87. define( 'TC_HTML', 1 );
  88. define( 'TC_SHELL', 1 );
  89. define( 'TC_MYSQL', 1 );
  90. define( 'TC_PCRE', 1 );
  91. define( 'TC_SELF', 1 );
  92. }
  93. /// @endcond
  94. /**
  95. * Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
  96. */
  97. function wfArrayDiff2( $a, $b ) {
  98. return array_udiff( $a, $b, 'wfArrayDiff2_cmp' );
  99. }
  100. function wfArrayDiff2_cmp( $a, $b ) {
  101. if ( !is_array( $a ) ) {
  102. return strcmp( $a, $b );
  103. } elseif ( count( $a ) !== count( $b ) ) {
  104. return count( $a ) < count( $b ) ? -1 : 1;
  105. } else {
  106. reset( $a );
  107. reset( $b );
  108. while( ( list( $keyA, $valueA ) = each( $a ) ) && ( list( $keyB, $valueB ) = each( $b ) ) ) {
  109. $cmp = strcmp( $valueA, $valueB );
  110. if ( $cmp !== 0 ) {
  111. return $cmp;
  112. }
  113. }
  114. return 0;
  115. }
  116. }
  117. /**
  118. * Wrapper for clone(), for compatibility with PHP4-friendly extensions.
  119. * PHP 5 won't let you declare a 'clone' function, even conditionally,
  120. * so it has to be a wrapper with a different name.
  121. */
  122. function wfClone( $object ) {
  123. return clone( $object );
  124. }
  125. /**
  126. * Seed Mersenne Twister
  127. * No-op for compatibility; only necessary in PHP < 4.2.0
  128. */
  129. function wfSeedRandom() {
  130. /* No-op */
  131. }
  132. /**
  133. * Get a random decimal value between 0 and 1, in a way
  134. * not likely to give duplicate values for any realistic
  135. * number of articles.
  136. *
  137. * @return string
  138. */
  139. function wfRandom() {
  140. # The maximum random value is "only" 2^31-1, so get two random
  141. # values to reduce the chance of dupes
  142. $max = mt_getrandmax() + 1;
  143. $rand = number_format( (mt_rand() * $max + mt_rand())
  144. / $max / $max, 12, '.', '' );
  145. return $rand;
  146. }
  147. /**
  148. * We want some things to be included as literal characters in our title URLs
  149. * for prettiness, which urlencode encodes by default. According to RFC 1738,
  150. * all of the following should be safe:
  151. *
  152. * ;:@&=$-_.+!*'(),
  153. *
  154. * But + is not safe because it's used to indicate a space; &= are only safe in
  155. * paths and not in queries (and we don't distinguish here); ' seems kind of
  156. * scary; and urlencode() doesn't touch -_. to begin with. Plus, although /
  157. * is reserved, we don't care. So the list we unescape is:
  158. *
  159. * ;:@$!*(),/
  160. *
  161. * %2F in the page titles seems to fatally break for some reason.
  162. *
  163. * @param $s String:
  164. * @return string
  165. */
  166. function wfUrlencode( $s ) {
  167. $s = urlencode( $s );
  168. $s = str_ireplace(
  169. array( '%3B','%3A','%40','%24','%21','%2A','%28','%29','%2C','%2F' ),
  170. array( ';', ':', '@', '$', '!', '*', '(', ')', ',', '/' ),
  171. $s
  172. );
  173. return $s;
  174. }
  175. /**
  176. * Sends a line to the debug log if enabled or, optionally, to a comment in output.
  177. * In normal operation this is a NOP.
  178. *
  179. * Controlling globals:
  180. * $wgDebugLogFile - points to the log file
  181. * $wgProfileOnly - if set, normal debug messages will not be recorded.
  182. * $wgDebugRawPage - if false, 'action=raw' hits will not result in debug output.
  183. * $wgDebugComments - if on, some debug items may appear in comments in the HTML output.
  184. *
  185. * @param $text String
  186. * @param $logonly Bool: set true to avoid appearing in HTML when $wgDebugComments is set
  187. */
  188. function wfDebug( $text, $logonly = false ) {
  189. global $wgOut, $wgDebugLogFile, $wgDebugComments, $wgProfileOnly, $wgDebugRawPage;
  190. global $wgDebugLogPrefix;
  191. static $recursion = 0;
  192. static $cache = array(); // Cache of unoutputted messages
  193. # Check for raw action using $_GET not $wgRequest, since the latter might not be initialised yet
  194. if ( isset( $_GET['action'] ) && $_GET['action'] == 'raw' && !$wgDebugRawPage ) {
  195. return;
  196. }
  197. if ( $wgDebugComments && !$logonly ) {
  198. $cache[] = $text;
  199. if ( !isset( $wgOut ) ) {
  200. return;
  201. }
  202. if ( !StubObject::isRealObject( $wgOut ) ) {
  203. if ( $recursion ) {
  204. return;
  205. }
  206. $recursion++;
  207. $wgOut->_unstub();
  208. $recursion--;
  209. }
  210. // add the message and possible cached ones to the output
  211. array_map( array( $wgOut, 'debug' ), $cache );
  212. $cache = array();
  213. }
  214. if ( '' != $wgDebugLogFile && !$wgProfileOnly ) {
  215. # Strip unprintables; they can switch terminal modes when binary data
  216. # gets dumped, which is pretty annoying.
  217. $text = preg_replace( '![\x00-\x08\x0b\x0c\x0e-\x1f]!', ' ', $text );
  218. $text = $wgDebugLogPrefix . $text;
  219. wfErrorLog( $text, $wgDebugLogFile );
  220. }
  221. }
  222. /**
  223. * Send a line giving PHP memory usage.
  224. * @param $exact Bool : print exact values instead of kilobytes (default: false)
  225. */
  226. function wfDebugMem( $exact = false ) {
  227. $mem = memory_get_usage();
  228. if( !$exact ) {
  229. $mem = floor( $mem / 1024 ) . ' kilobytes';
  230. } else {
  231. $mem .= ' bytes';
  232. }
  233. wfDebug( "Memory usage: $mem\n" );
  234. }
  235. /**
  236. * Send a line to a supplementary debug log file, if configured, or main debug log if not.
  237. * $wgDebugLogGroups[$logGroup] should be set to a filename to send to a separate log.
  238. *
  239. * @param $logGroup String
  240. * @param $text String
  241. * @param $public Bool: whether to log the event in the public log if no private
  242. * log file is specified, (default true)
  243. */
  244. function wfDebugLog( $logGroup, $text, $public = true ) {
  245. global $wgDebugLogGroups, $wgShowHostnames;
  246. $text = trim($text)."\n";
  247. if( isset( $wgDebugLogGroups[$logGroup] ) ) {
  248. $time = wfTimestamp( TS_DB );
  249. $wiki = wfWikiID();
  250. if ( $wgShowHostnames ) {
  251. $host = wfHostname();
  252. } else {
  253. $host = '';
  254. }
  255. wfErrorLog( "$time $host $wiki: $text", $wgDebugLogGroups[$logGroup] );
  256. } else if ( $public === true ) {
  257. wfDebug( $text, true );
  258. }
  259. }
  260. /**
  261. * Log for database errors
  262. * @param $text String: database error message.
  263. */
  264. function wfLogDBError( $text ) {
  265. global $wgDBerrorLog, $wgDBname;
  266. if ( $wgDBerrorLog ) {
  267. $host = trim(`hostname`);
  268. $text = date('D M j G:i:s T Y') . "\t$host\t$wgDBname\t$text";
  269. wfErrorLog( $text, $wgDBerrorLog );
  270. }
  271. }
  272. /**
  273. * Log to a file without getting "file size exceeded" signals.
  274. *
  275. * Can also log to TCP or UDP with the syntax udp://host:port/prefix. This will
  276. * send lines to the specified port, prefixed by the specified prefix and a space.
  277. */
  278. function wfErrorLog( $text, $file ) {
  279. if ( substr( $file, 0, 4 ) == 'udp:' ) {
  280. if ( preg_match( '!^(tcp|udp):(?://)?\[([0-9a-fA-F:]+)\]:(\d+)(?:/(.*))?$!', $file, $m ) ) {
  281. // IPv6 bracketed host
  282. $protocol = $m[1];
  283. $host = $m[2];
  284. $port = $m[3];
  285. $prefix = isset( $m[4] ) ? $m[4] : false;
  286. } elseif ( preg_match( '!^(tcp|udp):(?://)?([a-zA-Z0-9.-]+):(\d+)(?:/(.*))?$!', $file, $m ) ) {
  287. $protocol = $m[1];
  288. $host = $m[2];
  289. $port = $m[3];
  290. $prefix = isset( $m[4] ) ? $m[4] : false;
  291. } else {
  292. throw new MWException( __METHOD__.": Invalid UDP specification" );
  293. }
  294. // Clean it up for the multiplexer
  295. if ( strval( $prefix ) !== '' ) {
  296. $text = preg_replace( '/^/m', $prefix . ' ', $text );
  297. if ( substr( $text, -1 ) != "\n" ) {
  298. $text .= "\n";
  299. }
  300. }
  301. $sock = fsockopen( "$protocol://$host", $port );
  302. if ( !$sock ) {
  303. return;
  304. }
  305. fwrite( $sock, $text );
  306. fclose( $sock );
  307. } else {
  308. wfSuppressWarnings();
  309. $exists = file_exists( $file );
  310. $size = $exists ? filesize( $file ) : false;
  311. if ( !$exists || ( $size !== false && $size + strlen( $text ) < 0x7fffffff ) ) {
  312. error_log( $text, 3, $file );
  313. }
  314. wfRestoreWarnings();
  315. }
  316. }
  317. /**
  318. * @todo document
  319. */
  320. function wfLogProfilingData() {
  321. global $wgRequestTime, $wgDebugLogFile, $wgDebugRawPage, $wgRequest;
  322. global $wgProfiler, $wgProfileLimit, $wgUser;
  323. # Profiling must actually be enabled...
  324. if( !isset( $wgProfiler ) ) return;
  325. # Get total page request time
  326. $now = wfTime();
  327. $elapsed = $now - $wgRequestTime;
  328. # Only show pages that longer than $wgProfileLimit time (default is 0)
  329. if( $elapsed <= $wgProfileLimit ) return;
  330. $prof = wfGetProfilingOutput( $wgRequestTime, $elapsed );
  331. $forward = '';
  332. if( !empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) )
  333. $forward = ' forwarded for ' . $_SERVER['HTTP_X_FORWARDED_FOR'];
  334. if( !empty( $_SERVER['HTTP_CLIENT_IP'] ) )
  335. $forward .= ' client IP ' . $_SERVER['HTTP_CLIENT_IP'];
  336. if( !empty( $_SERVER['HTTP_FROM'] ) )
  337. $forward .= ' from ' . $_SERVER['HTTP_FROM'];
  338. if( $forward )
  339. $forward = "\t(proxied via {$_SERVER['REMOTE_ADDR']}{$forward})";
  340. // Don't unstub $wgUser at this late stage just for statistics purposes
  341. if( StubObject::isRealObject($wgUser) && $wgUser->isAnon() )
  342. $forward .= ' anon';
  343. $log = sprintf( "%s\t%04.3f\t%s\n",
  344. gmdate( 'YmdHis' ), $elapsed,
  345. urldecode( $wgRequest->getRequestURL() . $forward ) );
  346. if ( '' != $wgDebugLogFile && ( $wgRequest->getVal('action') != 'raw' || $wgDebugRawPage ) ) {
  347. wfErrorLog( $log . $prof, $wgDebugLogFile );
  348. }
  349. }
  350. /**
  351. * Check if the wiki read-only lock file is present. This can be used to lock
  352. * off editing functions, but doesn't guarantee that the database will not be
  353. * modified.
  354. * @return bool
  355. */
  356. function wfReadOnly() {
  357. global $wgReadOnlyFile, $wgReadOnly;
  358. if ( !is_null( $wgReadOnly ) ) {
  359. return (bool)$wgReadOnly;
  360. }
  361. if ( '' == $wgReadOnlyFile ) {
  362. return false;
  363. }
  364. // Set $wgReadOnly for faster access next time
  365. if ( is_file( $wgReadOnlyFile ) ) {
  366. $wgReadOnly = file_get_contents( $wgReadOnlyFile );
  367. } else {
  368. $wgReadOnly = false;
  369. }
  370. return (bool)$wgReadOnly;
  371. }
  372. function wfReadOnlyReason() {
  373. global $wgReadOnly;
  374. wfReadOnly();
  375. return $wgReadOnly;
  376. }
  377. /**
  378. * Return a Language object from $langcode
  379. * @param $langcode Mixed: either:
  380. * - a Language object
  381. * - code of the language to get the message for, if it is
  382. * a valid code create a language for that language, if
  383. * it is a string but not a valid code then make a basic
  384. * language object
  385. * - a boolean: if it's false then use the current users
  386. * language (as a fallback for the old parameter
  387. * functionality), or if it is true then use the wikis
  388. * @return Language object
  389. */
  390. function wfGetLangObj( $langcode = false ){
  391. # Identify which language to get or create a language object for.
  392. if( $langcode instanceof Language )
  393. # Great, we already have the object!
  394. return $langcode;
  395. global $wgContLang;
  396. if( $langcode === $wgContLang->getCode() || $langcode === true )
  397. # $langcode is the language code of the wikis content language object.
  398. # or it is a boolean and value is true
  399. return $wgContLang;
  400. global $wgLang;
  401. if( $langcode === $wgLang->getCode() || $langcode === false )
  402. # $langcode is the language code of user language object.
  403. # or it was a boolean and value is false
  404. return $wgLang;
  405. $validCodes = array_keys( Language::getLanguageNames() );
  406. if( in_array( $langcode, $validCodes ) )
  407. # $langcode corresponds to a valid language.
  408. return Language::factory( $langcode );
  409. # $langcode is a string, but not a valid language code; use content language.
  410. wfDebug( "Invalid language code passed to wfGetLangObj, falling back to content language.\n" );
  411. return $wgContLang;
  412. }
  413. /**
  414. * Get a message from anywhere, for the current user language.
  415. *
  416. * Use wfMsgForContent() instead if the message should NOT
  417. * change depending on the user preferences.
  418. *
  419. * @param $key String: lookup key for the message, usually
  420. * defined in languages/Language.php
  421. *
  422. * This function also takes extra optional parameters (not
  423. * shown in the function definition), which can by used to
  424. * insert variable text into the predefined message.
  425. */
  426. function wfMsg( $key ) {
  427. $args = func_get_args();
  428. array_shift( $args );
  429. return wfMsgReal( $key, $args, true );
  430. }
  431. /**
  432. * Same as above except doesn't transform the message
  433. */
  434. function wfMsgNoTrans( $key ) {
  435. $args = func_get_args();
  436. array_shift( $args );
  437. return wfMsgReal( $key, $args, true, false, false );
  438. }
  439. /**
  440. * Get a message from anywhere, for the current global language
  441. * set with $wgLanguageCode.
  442. *
  443. * Use this if the message should NOT change dependent on the
  444. * language set in the user's preferences. This is the case for
  445. * most text written into logs, as well as link targets (such as
  446. * the name of the copyright policy page). Link titles, on the
  447. * other hand, should be shown in the UI language.
  448. *
  449. * Note that MediaWiki allows users to change the user interface
  450. * language in their preferences, but a single installation
  451. * typically only contains content in one language.
  452. *
  453. * Be wary of this distinction: If you use wfMsg() where you should
  454. * use wfMsgForContent(), a user of the software may have to
  455. * customize over 70 messages in order to, e.g., fix a link in every
  456. * possible language.
  457. *
  458. * @param $key String: lookup key for the message, usually
  459. * defined in languages/Language.php
  460. */
  461. function wfMsgForContent( $key ) {
  462. global $wgForceUIMsgAsContentMsg;
  463. $args = func_get_args();
  464. array_shift( $args );
  465. $forcontent = true;
  466. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  467. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  468. $forcontent = false;
  469. return wfMsgReal( $key, $args, true, $forcontent );
  470. }
  471. /**
  472. * Same as above except doesn't transform the message
  473. */
  474. function wfMsgForContentNoTrans( $key ) {
  475. global $wgForceUIMsgAsContentMsg;
  476. $args = func_get_args();
  477. array_shift( $args );
  478. $forcontent = true;
  479. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  480. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  481. $forcontent = false;
  482. return wfMsgReal( $key, $args, true, $forcontent, false );
  483. }
  484. /**
  485. * Get a message from the language file, for the UI elements
  486. */
  487. function wfMsgNoDB( $key ) {
  488. $args = func_get_args();
  489. array_shift( $args );
  490. return wfMsgReal( $key, $args, false );
  491. }
  492. /**
  493. * Get a message from the language file, for the content
  494. */
  495. function wfMsgNoDBForContent( $key ) {
  496. global $wgForceUIMsgAsContentMsg;
  497. $args = func_get_args();
  498. array_shift( $args );
  499. $forcontent = true;
  500. if( is_array( $wgForceUIMsgAsContentMsg ) &&
  501. in_array( $key, $wgForceUIMsgAsContentMsg ) )
  502. $forcontent = false;
  503. return wfMsgReal( $key, $args, false, $forcontent );
  504. }
  505. /**
  506. * Really get a message
  507. * @param $key String: key to get.
  508. * @param $args
  509. * @param $useDB Boolean
  510. * @param $transform Boolean: Whether or not to transform the message.
  511. * @param $forContent Boolean
  512. * @return String: the requested message.
  513. */
  514. function wfMsgReal( $key, $args, $useDB = true, $forContent=false, $transform = true ) {
  515. wfProfileIn( __METHOD__ );
  516. $message = wfMsgGetKey( $key, $useDB, $forContent, $transform );
  517. $message = wfMsgReplaceArgs( $message, $args );
  518. wfProfileOut( __METHOD__ );
  519. return $message;
  520. }
  521. /**
  522. * This function provides the message source for messages to be edited which are *not* stored in the database.
  523. * @param $key String:
  524. */
  525. function wfMsgWeirdKey ( $key ) {
  526. $source = wfMsgGetKey( $key, false, true, false );
  527. if ( wfEmptyMsg( $key, $source ) )
  528. return "";
  529. else
  530. return $source;
  531. }
  532. /**
  533. * Fetch a message string value, but don't replace any keys yet.
  534. * @param string $key
  535. * @param bool $useDB
  536. * @param string $langcode Code of the language to get the message for, or
  537. * behaves as a content language switch if it is a
  538. * boolean.
  539. * @return string
  540. * @private
  541. */
  542. function wfMsgGetKey( $key, $useDB, $langCode = false, $transform = true ) {
  543. global $wgContLang, $wgMessageCache;
  544. wfRunHooks('NormalizeMessageKey', array(&$key, &$useDB, &$langCode, &$transform));
  545. # If $wgMessageCache isn't initialised yet, try to return something sensible.
  546. if( is_object( $wgMessageCache ) ) {
  547. $message = $wgMessageCache->get( $key, $useDB, $langCode );
  548. if ( $transform ) {
  549. $message = $wgMessageCache->transform( $message );
  550. }
  551. } else {
  552. $lang = wfGetLangObj( $langCode );
  553. # MessageCache::get() does this already, Language::getMessage() doesn't
  554. # ISSUE: Should we try to handle "message/lang" here too?
  555. $key = str_replace( ' ' , '_' , $wgContLang->lcfirst( $key ) );
  556. if( is_object( $lang ) ) {
  557. $message = $lang->getMessage( $key );
  558. } else {
  559. $message = false;
  560. }
  561. }
  562. return $message;
  563. }
  564. /**
  565. * Replace message parameter keys on the given formatted output.
  566. *
  567. * @param string $message
  568. * @param array $args
  569. * @return string
  570. * @private
  571. */
  572. function wfMsgReplaceArgs( $message, $args ) {
  573. # Fix windows line-endings
  574. # Some messages are split with explode("\n", $msg)
  575. $message = str_replace( "\r", '', $message );
  576. // Replace arguments
  577. if ( count( $args ) ) {
  578. if ( is_array( $args[0] ) ) {
  579. $args = array_values( $args[0] );
  580. }
  581. $replacementKeys = array();
  582. foreach( $args as $n => $param ) {
  583. $replacementKeys['$' . ($n + 1)] = $param;
  584. }
  585. $message = strtr( $message, $replacementKeys );
  586. }
  587. return $message;
  588. }
  589. /**
  590. * Return an HTML-escaped version of a message.
  591. * Parameter replacements, if any, are done *after* the HTML-escaping,
  592. * so parameters may contain HTML (eg links or form controls). Be sure
  593. * to pre-escape them if you really do want plaintext, or just wrap
  594. * the whole thing in htmlspecialchars().
  595. *
  596. * @param string $key
  597. * @param string ... parameters
  598. * @return string
  599. */
  600. function wfMsgHtml( $key ) {
  601. $args = func_get_args();
  602. array_shift( $args );
  603. return wfMsgReplaceArgs( htmlspecialchars( wfMsgGetKey( $key, true ) ), $args );
  604. }
  605. /**
  606. * Return an HTML version of message
  607. * Parameter replacements, if any, are done *after* parsing the wiki-text message,
  608. * so parameters may contain HTML (eg links or form controls). Be sure
  609. * to pre-escape them if you really do want plaintext, or just wrap
  610. * the whole thing in htmlspecialchars().
  611. *
  612. * @param string $key
  613. * @param string ... parameters
  614. * @return string
  615. */
  616. function wfMsgWikiHtml( $key ) {
  617. global $wgOut;
  618. $args = func_get_args();
  619. array_shift( $args );
  620. return wfMsgReplaceArgs( $wgOut->parse( wfMsgGetKey( $key, true ), /* can't be set to false */ true ), $args );
  621. }
  622. /**
  623. * Returns message in the requested format
  624. * @param string $key Key of the message
  625. * @param array $options Processing rules. Can take the following options:
  626. * <i>parse</i>: parses wikitext to html
  627. * <i>parseinline</i>: parses wikitext to html and removes the surrounding
  628. * p's added by parser or tidy
  629. * <i>escape</i>: filters message through htmlspecialchars
  630. * <i>escapenoentities</i>: same, but allows entity references like &nbsp; through
  631. * <i>replaceafter</i>: parameters are substituted after parsing or escaping
  632. * <i>parsemag</i>: transform the message using magic phrases
  633. * <i>content</i>: fetch message for content language instead of interface
  634. * Also can accept a single associative argument, of the form 'language' => 'xx':
  635. * <i>language</i>: Language object or language code to fetch message for
  636. * (overriden by <i>content</i>), its behaviour with parser, parseinline
  637. * and parsemag is undefined.
  638. * Behavior for conflicting options (e.g., parse+parseinline) is undefined.
  639. */
  640. function wfMsgExt( $key, $options ) {
  641. global $wgOut;
  642. $args = func_get_args();
  643. array_shift( $args );
  644. array_shift( $args );
  645. $options = (array)$options;
  646. foreach( $options as $arrayKey => $option ) {
  647. if( !preg_match( '/^[0-9]+|language$/', $arrayKey ) ) {
  648. # An unknown index, neither numeric nor "language"
  649. trigger_error( "wfMsgExt called with incorrect parameter key $arrayKey", E_USER_WARNING );
  650. } elseif( preg_match( '/^[0-9]+$/', $arrayKey ) && !in_array( $option,
  651. array( 'parse', 'parseinline', 'escape', 'escapenoentities',
  652. 'replaceafter', 'parsemag', 'content' ) ) ) {
  653. # A numeric index with unknown value
  654. trigger_error( "wfMsgExt called with incorrect parameter $option", E_USER_WARNING );
  655. }
  656. }
  657. if( in_array('content', $options, true ) ) {
  658. $forContent = true;
  659. $langCode = true;
  660. } elseif( array_key_exists('language', $options) ) {
  661. $forContent = false;
  662. $langCode = wfGetLangObj( $options['language'] );
  663. } else {
  664. $forContent = false;
  665. $langCode = false;
  666. }
  667. $string = wfMsgGetKey( $key, /*DB*/true, $langCode, /*Transform*/false );
  668. if( !in_array('replaceafter', $options, true ) ) {
  669. $string = wfMsgReplaceArgs( $string, $args );
  670. }
  671. if( in_array('parse', $options, true ) ) {
  672. $string = $wgOut->parse( $string, true, !$forContent );
  673. } elseif ( in_array('parseinline', $options, true ) ) {
  674. $string = $wgOut->parse( $string, true, !$forContent );
  675. $m = array();
  676. if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
  677. $string = $m[1];
  678. }
  679. } elseif ( in_array('parsemag', $options, true ) ) {
  680. global $wgMessageCache;
  681. if ( isset( $wgMessageCache ) ) {
  682. $string = $wgMessageCache->transform( $string,
  683. !$forContent,
  684. is_object( $langCode ) ? $langCode : null );
  685. }
  686. }
  687. if ( in_array('escape', $options, true ) ) {
  688. $string = htmlspecialchars ( $string );
  689. } elseif ( in_array( 'escapenoentities', $options, true ) ) {
  690. $string = Sanitizer::escapeHtmlAllowEntities( $string );
  691. }
  692. if( in_array('replaceafter', $options, true ) ) {
  693. $string = wfMsgReplaceArgs( $string, $args );
  694. }
  695. return $string;
  696. }
  697. /**
  698. * Just like exit() but makes a note of it.
  699. * Commits open transactions except if the error parameter is set
  700. *
  701. * @deprecated Please return control to the caller or throw an exception
  702. */
  703. function wfAbruptExit( $error = false ){
  704. static $called = false;
  705. if ( $called ){
  706. exit( -1 );
  707. }
  708. $called = true;
  709. $bt = wfDebugBacktrace();
  710. if( $bt ) {
  711. for($i = 0; $i < count($bt) ; $i++){
  712. $file = isset($bt[$i]['file']) ? $bt[$i]['file'] : "unknown";
  713. $line = isset($bt[$i]['line']) ? $bt[$i]['line'] : "unknown";
  714. wfDebug("WARNING: Abrupt exit in $file at line $line\n");
  715. }
  716. } else {
  717. wfDebug("WARNING: Abrupt exit\n");
  718. }
  719. wfLogProfilingData();
  720. if ( !$error ) {
  721. wfGetLB()->closeAll();
  722. }
  723. exit( -1 );
  724. }
  725. /**
  726. * @deprecated Please return control the caller or throw an exception
  727. */
  728. function wfErrorExit() {
  729. wfAbruptExit( true );
  730. }
  731. /**
  732. * Print a simple message and die, returning nonzero to the shell if any.
  733. * Plain die() fails to return nonzero to the shell if you pass a string.
  734. * @param string $msg
  735. */
  736. function wfDie( $msg='' ) {
  737. echo $msg;
  738. die( 1 );
  739. }
  740. /**
  741. * Throw a debugging exception. This function previously once exited the process,
  742. * but now throws an exception instead, with similar results.
  743. *
  744. * @param string $msg Message shown when dieing.
  745. */
  746. function wfDebugDieBacktrace( $msg = '' ) {
  747. throw new MWException( $msg );
  748. }
  749. /**
  750. * Fetch server name for use in error reporting etc.
  751. * Use real server name if available, so we know which machine
  752. * in a server farm generated the current page.
  753. * @return string
  754. */
  755. function wfHostname() {
  756. static $host;
  757. if ( is_null( $host ) ) {
  758. if ( function_exists( 'posix_uname' ) ) {
  759. // This function not present on Windows
  760. $uname = @posix_uname();
  761. } else {
  762. $uname = false;
  763. }
  764. if( is_array( $uname ) && isset( $uname['nodename'] ) ) {
  765. $host = $uname['nodename'];
  766. } elseif ( getenv( 'COMPUTERNAME' ) ) {
  767. # Windows computer name
  768. $host = getenv( 'COMPUTERNAME' );
  769. } else {
  770. # This may be a virtual server.
  771. $host = $_SERVER['SERVER_NAME'];
  772. }
  773. }
  774. return $host;
  775. }
  776. /**
  777. * Returns a HTML comment with the elapsed time since request.
  778. * This method has no side effects.
  779. * @return string
  780. */
  781. function wfReportTime() {
  782. global $wgRequestTime, $wgShowHostnames;
  783. $now = wfTime();
  784. $elapsed = $now - $wgRequestTime;
  785. return $wgShowHostnames
  786. ? sprintf( "<!-- Served by %s in %01.3f secs. -->", wfHostname(), $elapsed )
  787. : sprintf( "<!-- Served in %01.3f secs. -->", $elapsed );
  788. }
  789. /**
  790. * Safety wrapper for debug_backtrace().
  791. *
  792. * With Zend Optimizer 3.2.0 loaded, this causes segfaults under somewhat
  793. * murky circumstances, which may be triggered in part by stub objects
  794. * or other fancy talkin'.
  795. *
  796. * Will return an empty array if Zend Optimizer is detected or if
  797. * debug_backtrace is disabled, otherwise the output from
  798. * debug_backtrace() (trimmed).
  799. *
  800. * @return array of backtrace information
  801. */
  802. function wfDebugBacktrace() {
  803. static $disabled = null;
  804. if( extension_loaded( 'Zend Optimizer' ) ) {
  805. wfDebug( "Zend Optimizer detected; skipping debug_backtrace for safety.\n" );
  806. return array();
  807. }
  808. if ( is_null( $disabled ) ) {
  809. $disabled = false;
  810. $functions = explode( ',', ini_get( 'disable_functions' ) );
  811. $functions = array_map( 'trim', $functions );
  812. $functions = array_map( 'strtolower', $functions );
  813. if ( in_array( 'debug_backtrace', $functions ) ) {
  814. wfDebug( "debug_backtrace is in disabled_functions\n" );
  815. $disabled = true;
  816. }
  817. }
  818. if ( $disabled ) {
  819. return array();
  820. }
  821. return array_slice( debug_backtrace(), 1 );
  822. }
  823. function wfBacktrace() {
  824. global $wgCommandLineMode;
  825. if ( $wgCommandLineMode ) {
  826. $msg = '';
  827. } else {
  828. $msg = "<ul>\n";
  829. }
  830. $backtrace = wfDebugBacktrace();
  831. foreach( $backtrace as $call ) {
  832. if( isset( $call['file'] ) ) {
  833. $f = explode( DIRECTORY_SEPARATOR, $call['file'] );
  834. $file = $f[count($f)-1];
  835. } else {
  836. $file = '-';
  837. }
  838. if( isset( $call['line'] ) ) {
  839. $line = $call['line'];
  840. } else {
  841. $line = '-';
  842. }
  843. if ( $wgCommandLineMode ) {
  844. $msg .= "$file line $line calls ";
  845. } else {
  846. $msg .= '<li>' . $file . ' line ' . $line . ' calls ';
  847. }
  848. if( !empty( $call['class'] ) ) $msg .= $call['class'] . '::';
  849. $msg .= $call['function'] . '()';
  850. if ( $wgCommandLineMode ) {
  851. $msg .= "\n";
  852. } else {
  853. $msg .= "</li>\n";
  854. }
  855. }
  856. if ( $wgCommandLineMode ) {
  857. $msg .= "\n";
  858. } else {
  859. $msg .= "</ul>\n";
  860. }
  861. return $msg;
  862. }
  863. /* Some generic result counters, pulled out of SearchEngine */
  864. /**
  865. * @todo document
  866. */
  867. function wfShowingResults( $offset, $limit ) {
  868. global $wgLang;
  869. return wfMsgExt( 'showingresults', array( 'parseinline' ), $wgLang->formatNum( $limit ),
  870. $wgLang->formatNum( $offset+1 ) );
  871. }
  872. /**
  873. * @todo document
  874. */
  875. function wfShowingResultsNum( $offset, $limit, $num ) {
  876. global $wgLang;
  877. return wfMsgExt( 'showingresultsnum', array( 'parseinline' ), $wgLang->formatNum( $limit ),
  878. $wgLang->formatNum( $offset+1 ), $wgLang->formatNum( $num ) );
  879. }
  880. /**
  881. * Generate (prev x| next x) (20|50|100...) type links for paging
  882. * @param $offset string
  883. * @param $limit int
  884. * @param $link string
  885. * @param $query string, optional URL query parameter string
  886. * @param $atend bool, optional param for specified if this is the last page
  887. */
  888. function wfViewPrevNext( $offset, $limit, $link, $query = '', $atend = false ) {
  889. global $wgLang;
  890. $fmtLimit = $wgLang->formatNum( $limit );
  891. # Get prev/next link display text
  892. $prev = wfMsgHtml( 'prevn', $fmtLimit );
  893. $next = wfMsgHtml( 'nextn', $fmtLimit );
  894. # Get prev/next link title text
  895. $pTitle = wfMsgExt( 'prevn-title', array('parsemag','escape'), $fmtLimit );
  896. $nTitle = wfMsgExt( 'nextn-title', array('parsemag','escape'), $fmtLimit );
  897. # Fetch the title object
  898. if( is_object( $link ) ) {
  899. $title =& $link;
  900. } else {
  901. $title = Title::newFromText( $link );
  902. if( is_null( $title ) ) {
  903. return false;
  904. }
  905. }
  906. # Make 'previous' link
  907. if( 0 != $offset ) {
  908. $po = $offset - $limit;
  909. $po = max($po,0);
  910. $q = "limit={$limit}&offset={$po}";
  911. if( $query != '' ) {
  912. $q .= '&'.$query;
  913. }
  914. $plink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$pTitle}\" class=\"mw-prevlink\">{$prev}</a>";
  915. } else {
  916. $plink = $prev;
  917. }
  918. # Make 'next' link
  919. $no = $offset + $limit;
  920. $q = "limit={$limit}&offset={$no}";
  921. if( $query != '' ) {
  922. $q .= '&'.$query;
  923. }
  924. if( $atend ) {
  925. $nlink = $next;
  926. } else {
  927. $nlink = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$nTitle}\" class=\"mw-nextlink\">{$next}</a>";
  928. }
  929. # Make links to set number of items per page
  930. $nums = $wgLang->pipeList( array(
  931. wfNumLink( $offset, 20, $title, $query ),
  932. wfNumLink( $offset, 50, $title, $query ),
  933. wfNumLink( $offset, 100, $title, $query ),
  934. wfNumLink( $offset, 250, $title, $query ),
  935. wfNumLink( $offset, 500, $title, $query )
  936. ) );
  937. return wfMsg( 'viewprevnext', $plink, $nlink, $nums );
  938. }
  939. /**
  940. * Generate links for (20|50|100...) items-per-page links
  941. * @param $offset string
  942. * @param $limit int
  943. * @param $title Title
  944. * @param $query string, optional URL query parameter string
  945. */
  946. function wfNumLink( $offset, $limit, $title, $query = '' ) {
  947. global $wgLang;
  948. if( $query == '' ) {
  949. $q = '';
  950. } else {
  951. $q = $query.'&';
  952. }
  953. $q .= "limit={$limit}&offset={$offset}";
  954. $fmtLimit = $wgLang->formatNum( $limit );
  955. $lTitle = wfMsgExt('shown-title',array('parsemag','escape'),$limit);
  956. $s = '<a href="' . $title->escapeLocalUrl( $q ) . "\" title=\"{$lTitle}\" class=\"mw-numlink\">{$fmtLimit}</a>";
  957. return $s;
  958. }
  959. /**
  960. * @todo document
  961. * @todo FIXME: we may want to blacklist some broken browsers
  962. *
  963. * @return bool Whereas client accept gzip compression
  964. */
  965. function wfClientAcceptsGzip() {
  966. global $wgUseGzip;
  967. if( $wgUseGzip ) {
  968. # FIXME: we may want to blacklist some broken browsers
  969. $m = array();
  970. if( preg_match(
  971. '/\bgzip(?:;(q)=([0-9]+(?:\.[0-9]+)))?\b/',
  972. $_SERVER['HTTP_ACCEPT_ENCODING'],
  973. $m ) ) {
  974. if( isset( $m[2] ) && ( $m[1] == 'q' ) && ( $m[2] == 0 ) ) return false;
  975. wfDebug( " accepts gzip\n" );
  976. return true;
  977. }
  978. }
  979. return false;
  980. }
  981. /**
  982. * Obtain the offset and limit values from the request string;
  983. * used in special pages
  984. *
  985. * @param $deflimit Default limit if none supplied
  986. * @param $optionname Name of a user preference to check against
  987. * @return array
  988. *
  989. */
  990. function wfCheckLimits( $deflimit = 50, $optionname = 'rclimit' ) {
  991. global $wgRequest;
  992. return $wgRequest->getLimitOffset( $deflimit, $optionname );
  993. }
  994. /**
  995. * Escapes the given text so that it may be output using addWikiText()
  996. * without any linking, formatting, etc. making its way through. This
  997. * is achieved by substituting certain characters with HTML entities.
  998. * As required by the callers, <nowiki> is not used. It currently does
  999. * not filter out characters which have special meaning only at the
  1000. * start of a line, such as "*".
  1001. *
  1002. * @param string $text Text to be escaped
  1003. */
  1004. function wfEscapeWikiText( $text ) {
  1005. $text = str_replace(
  1006. array( '[', '|', ']', '\'', 'ISBN ', 'RFC ', '://', "\n=", '{{' ), # }}
  1007. array( '&#91;', '&#124;', '&#93;', '&#39;', 'ISBN&#32;', 'RFC&#32;', '&#58;//', "\n&#61;", '&#123;&#123;' ),
  1008. htmlspecialchars($text) );
  1009. return $text;
  1010. }
  1011. /**
  1012. * @todo document
  1013. */
  1014. function wfQuotedPrintable( $string, $charset = '' ) {
  1015. # Probably incomplete; see RFC 2045
  1016. if( empty( $charset ) ) {
  1017. global $wgInputEncoding;
  1018. $charset = $wgInputEncoding;
  1019. }
  1020. $charset = strtoupper( $charset );
  1021. $charset = str_replace( 'ISO-8859', 'ISO8859', $charset ); // ?
  1022. $illegal = '\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\xff=';
  1023. $replace = $illegal . '\t ?_';
  1024. if( !preg_match( "/[$illegal]/", $string ) ) return $string;
  1025. $out = "=?$charset?Q?";
  1026. $out .= preg_replace( "/([$replace])/e", 'sprintf("=%02X",ord("$1"))', $string );
  1027. $out .= '?=';
  1028. return $out;
  1029. }
  1030. /**
  1031. * @todo document
  1032. * @return float
  1033. */
  1034. function wfTime() {
  1035. return microtime(true);
  1036. }
  1037. /**
  1038. * Sets dest to source and returns the original value of dest
  1039. * If source is NULL, it just returns the value, it doesn't set the variable
  1040. */
  1041. function wfSetVar( &$dest, $source ) {
  1042. $temp = $dest;
  1043. if ( !is_null( $source ) ) {
  1044. $dest = $source;
  1045. }
  1046. return $temp;
  1047. }
  1048. /**
  1049. * As for wfSetVar except setting a bit
  1050. */
  1051. function wfSetBit( &$dest, $bit, $state = true ) {
  1052. $temp = (bool)($dest & $bit );
  1053. if ( !is_null( $state ) ) {
  1054. if ( $state ) {
  1055. $dest |= $bit;
  1056. } else {
  1057. $dest &= ~$bit;
  1058. }
  1059. }
  1060. return $temp;
  1061. }
  1062. /**
  1063. * This function takes two arrays as input, and returns a CGI-style string, e.g.
  1064. * "days=7&limit=100". Options in the first array override options in the second.
  1065. * Options set to "" will not be output.
  1066. */
  1067. function wfArrayToCGI( $array1, $array2 = NULL )
  1068. {
  1069. if ( !is_null( $array2 ) ) {
  1070. $array1 = $array1 + $array2;
  1071. }
  1072. $cgi = '';
  1073. foreach ( $array1 as $key => $value ) {
  1074. if ( '' !== $value ) {
  1075. if ( '' != $cgi ) {
  1076. $cgi .= '&';
  1077. }
  1078. if(is_array($value))
  1079. {
  1080. $firstTime = true;
  1081. foreach($value as $v)
  1082. {
  1083. $cgi .= ($firstTime ? '' : '&') .
  1084. urlencode( $key . '[]' ) . '=' .
  1085. urlencode( $v );
  1086. $firstTime = false;
  1087. }
  1088. }
  1089. else
  1090. $cgi .= urlencode( $key ) . '=' .
  1091. urlencode( $value );
  1092. }
  1093. }
  1094. return $cgi;
  1095. }
  1096. /**
  1097. * This is the logical opposite of wfArrayToCGI(): it accepts a query string as
  1098. * its argument and returns the same string in array form. This allows compa-
  1099. * tibility with legacy functions that accept raw query strings instead of nice
  1100. * arrays. Of course, keys and values are urldecode()d. Don't try passing in-
  1101. * valid query strings, or it will explode.
  1102. *
  1103. * @param $query string Query string
  1104. * @return array Array version of input
  1105. */
  1106. function wfCgiToArray( $query ) {
  1107. if( isset( $query[0] ) and $query[0] == '?' ) {
  1108. $query = substr( $query, 1 );
  1109. }
  1110. $bits = explode( '&', $query );
  1111. $ret = array();
  1112. foreach( $bits as $bit ) {
  1113. if( $bit === '' ) {
  1114. continue;
  1115. }
  1116. list( $key, $value ) = explode( '=', $bit );
  1117. $key = urldecode( $key );
  1118. $value = urldecode( $value );
  1119. $ret[$key] = $value;
  1120. }
  1121. return $ret;
  1122. }
  1123. /**
  1124. * Append a query string to an existing URL, which may or may not already
  1125. * have query string parameters already. If so, they will be combined.
  1126. *
  1127. * @param string $url
  1128. * @param string $query
  1129. * @return string
  1130. */
  1131. function wfAppendQuery( $url, $query ) {
  1132. if( $query != '' ) {
  1133. if( false === strpos( $url, '?' ) ) {
  1134. $url .= '?';
  1135. } else {
  1136. $url .= '&';
  1137. }
  1138. $url .= $query;
  1139. }
  1140. return $url;
  1141. }
  1142. /**
  1143. * Expand a potentially local URL to a fully-qualified URL.
  1144. * Assumes $wgServer is correct. :)
  1145. * @param string $url, either fully-qualified or a local path + query
  1146. * @return string Fully-qualified URL
  1147. */
  1148. function wfExpandUrl( $url ) {
  1149. if( substr( $url, 0, 1 ) == '/' ) {
  1150. global $wgServer;
  1151. return $wgServer . $url;
  1152. } else {
  1153. return $url;
  1154. }
  1155. }
  1156. /**
  1157. * This is obsolete, use SquidUpdate::purge()
  1158. * @deprecated
  1159. */
  1160. function wfPurgeSquidServers ($urlArr) {
  1161. SquidUpdate::purge( $urlArr );
  1162. }
  1163. /**
  1164. * Windows-compatible version of escapeshellarg()
  1165. * Windows doesn't recognise single-quotes in the shell, but the escapeshellarg()
  1166. * function puts single quotes in regardless of OS.
  1167. *
  1168. * Also fixes the locale problems on Linux in PHP 5.2.6+ (bug backported to
  1169. * earlier distro releases of PHP)
  1170. */
  1171. function wfEscapeShellArg( ) {
  1172. wfInitShellLocale();
  1173. $args = func_get_args();
  1174. $first = true;
  1175. $retVal = '';
  1176. foreach ( $args as $arg ) {
  1177. if ( !$first ) {
  1178. $retVal .= ' ';
  1179. } else {
  1180. $first = false;
  1181. }
  1182. if ( wfIsWindows() ) {
  1183. // Escaping for an MSVC-style command line parser
  1184. // Ref: http://mailman.lyra.org/pipermail/scite-interest/2002-March/000436.html
  1185. // Double the backslashes before any double quotes. Escape the double quotes.
  1186. $tokens = preg_split( '/(\\\\*")/', $arg, -1, PREG_SPLIT_DELIM_CAPTURE );
  1187. $arg = '';
  1188. $delim = false;
  1189. foreach ( $tokens as $token ) {
  1190. if ( $delim ) {
  1191. $arg .= str_replace( '\\', '\\\\', substr( $token, 0, -1 ) ) . '\\"';
  1192. } else {
  1193. $arg .= $token;
  1194. }
  1195. $delim = !$delim;
  1196. }
  1197. // Double the backslashes before the end of the string, because
  1198. // we will soon add a quote
  1199. $m = array();
  1200. if ( preg_match( '/^(.*?)(\\\\+)$/', $arg, $m ) ) {
  1201. $arg = $m[1] . str_replace( '\\', '\\\\', $m[2] );
  1202. }
  1203. // Add surrounding quotes
  1204. $retVal .= '"' . $arg . '"';
  1205. } else {
  1206. $retVal .= escapeshellarg( $arg );
  1207. }
  1208. }
  1209. return $retVal;
  1210. }
  1211. /**
  1212. * wfMerge attempts to merge differences between three texts.
  1213. * Returns true for a clean merge and false for failure or a conflict.
  1214. */
  1215. function wfMerge( $old, $mine, $yours, &$result ){
  1216. global $wgDiff3;
  1217. # This check may also protect against code injection in
  1218. # case of broken installations.
  1219. if( !$wgDiff3 || !file_exists( $wgDiff3 ) ) {
  1220. wfDebug( "diff3 not found\n" );
  1221. return false;
  1222. }
  1223. # Make temporary files
  1224. $td = wfTempDir();
  1225. $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
  1226. $mytextFile = fopen( $mytextName = tempnam( $td, 'merge-mine-' ), 'w' );
  1227. $yourtextFile = fopen( $yourtextName = tempnam( $td, 'merge-your-' ), 'w' );
  1228. fwrite( $oldtextFile, $old ); fclose( $oldtextFile );
  1229. fwrite( $mytextFile, $mine ); fclose( $mytextFile );
  1230. fwrite( $yourtextFile, $yours ); fclose( $yourtextFile );
  1231. # Check for a conflict
  1232. $cmd = $wgDiff3 . ' -a --overlap-only ' .
  1233. wfEscapeShellArg( $mytextName ) . ' ' .
  1234. wfEscapeShellArg( $oldtextName ) . ' ' .
  1235. wfEscapeShellArg( $yourtextName );
  1236. $handle = popen( $cmd, 'r' );
  1237. if( fgets( $handle, 1024 ) ){
  1238. $conflict = true;
  1239. } else {
  1240. $conflict = false;
  1241. }
  1242. pclose( $handle );
  1243. # Merge differences
  1244. $cmd = $wgDiff3 . ' -a -e --merge ' .
  1245. wfEscapeShellArg( $mytextName, $oldtextName, $yourtextName );
  1246. $handle = popen( $cmd, 'r' );
  1247. $result = '';
  1248. do {
  1249. $data = fread( $handle, 8192 );
  1250. if ( strlen( $data ) == 0 ) {
  1251. break;
  1252. }
  1253. $result .= $data;
  1254. } while ( true );
  1255. pclose( $handle );
  1256. unlink( $mytextName ); unlink( $oldtextName ); unlink( $yourtextName );
  1257. if ( $result === '' && $old !== '' && $conflict == false ) {
  1258. wfDebug( "Unexpected null result from diff3. Command: $cmd\n" );
  1259. $conflict = true;
  1260. }
  1261. return ! $conflict;
  1262. }
  1263. /**
  1264. * Returns unified plain-text diff of two texts.
  1265. * Useful for machine processing of diffs.
  1266. * @param $before string The text before the changes.
  1267. * @param $after string The text after the changes.
  1268. * @param $params string Command-line options for the diff command.
  1269. * @return string Unified diff of $before and $after
  1270. */
  1271. function wfDiff( $before, $after, $params = '-u' ) {
  1272. global $wgDiff;
  1273. # This check may also protect against code injection in
  1274. # case of broken installations.
  1275. if( !file_exists( $wgDiff ) ){
  1276. wfDebug( "diff executable not found\n" );
  1277. $diffs = new Diff( explode( "\n", $before ), explode( "\n", $after ) );
  1278. $format = new UnifiedDiffFormatter();
  1279. return $format->format( $diffs );
  1280. }
  1281. # Make temporary files
  1282. $td = wfTempDir();
  1283. $oldtextFile = fopen( $oldtextName = tempnam( $td, 'merge-old-' ), 'w' );
  1284. $newtextFile = fopen( $newtextName = tempnam( $td, 'merge-your-' ), 'w' );
  1285. fwrite( $oldtextFile, $before ); fclose( $oldtextFile );
  1286. fwrite( $newtextFile, $after ); fclose( $newtextFile );
  1287. // Get the diff of the two files
  1288. $cmd = "$wgDiff " . $params . ' ' .wfEscapeShellArg( $oldtextName, $newtextName );
  1289. $h = popen( $cmd, 'r' );
  1290. $diff = '';
  1291. do {
  1292. $data = fread( $h, 8192 );
  1293. if ( strlen( $data ) == 0 ) {
  1294. break;
  1295. }
  1296. $diff .= $data;
  1297. } while ( true );
  1298. // Clean up
  1299. pclose( $h );
  1300. unlink( $oldtextName );
  1301. unlink( $newtextName );
  1302. // Kill the --- and +++ lines. They're not useful.
  1303. $diff_lines = explode( "\n", $diff );
  1304. if (strpos( $diff_lines[0], '---' ) === 0) {
  1305. unset($diff_lines[0]);
  1306. }
  1307. if (strpos( $diff_lines[1], '+++' ) === 0) {
  1308. unset($diff_lines[1]);
  1309. }
  1310. $diff = implode( "\n", $diff_lines );
  1311. return $diff;
  1312. }
  1313. /**
  1314. * A wrapper around the PHP function var_export().
  1315. * Either print it or add it to the regular output ($wgOut).
  1316. *
  1317. * @param $var A PHP variable to dump.
  1318. */
  1319. function wfVarDump( $var ) {
  1320. global $wgOut;
  1321. $s = str_replace("\n","<br />\n", var_export( $var, true ) . "\n");
  1322. if ( headers_sent() || !@is_object( $wgOut ) ) {
  1323. print $s;
  1324. } else {
  1325. $wgOut->addHTML( $s );
  1326. }
  1327. }
  1328. /**
  1329. * Provide a simple HTTP error.
  1330. */
  1331. function wfHttpError( $code, $label, $desc ) {
  1332. global $wgOut;
  1333. $wgOut->disable();
  1334. header( "HTTP/1.0 $code $label" );
  1335. header( "Status: $code $label" );
  1336. $wgOut->sendCacheControl();
  1337. header( 'Content-type: text/html; charset=utf-8' );
  1338. print "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">".
  1339. "<html><head><title>" .
  1340. htmlspecialchars( $label ) .
  1341. "</title></head><body><h1>" .
  1342. htmlspecialchars( $label ) .
  1343. "</h1><p>" .
  1344. nl2br( htmlspecialchars( $desc ) ) .
  1345. "</p></body></html>\n";
  1346. }
  1347. /**
  1348. * Clear away any user-level output buffers, discarding contents.
  1349. *
  1350. * Suitable for 'starting afresh', for instance when streaming
  1351. * relatively large amounts of data without buffering, or wanting to
  1352. * output image files without ob_gzhandler's compression.
  1353. *
  1354. * The optional $resetGzipEncoding parameter controls suppression of
  1355. * the Content-Encoding header sent by ob_gzhandler; by default it
  1356. * is left. See comments for wfClearOutputBuffers() for why it would
  1357. * be used.
  1358. *
  1359. * Note that some PHP configuration options may add output buffer
  1360. * layers which cannot be removed; these are left in place.
  1361. *
  1362. * @param bool $resetGzipEncoding
  1363. */
  1364. function wfResetOutputBuffers( $resetGzipEncoding=true ) {
  1365. if( $resetGzipEncoding ) {
  1366. // Suppress Content-Encoding and Content-Length
  1367. // headers from 1.10+s wfOutputHandler
  1368. global $wgDisableOutputCompression;
  1369. $wgDisableOutputCompression = true;
  1370. }
  1371. while( $status = ob_get_status() ) {
  1372. if( $status['type'] == 0 /* PHP_OUTPUT_HANDLER_INTERNAL */ ) {
  1373. // Probably from zlib.output_compression or other
  1374. // PHP-internal setting which can't be removed.
  1375. //
  1376. // Give up, and hope the result doesn't break
  1377. // output behavior.
  1378. break;
  1379. }
  1380. if( !ob_end_clean() ) {
  1381. // Could not remove output buffer handler; abort now
  1382. // to avoid getting in some kind of infinite loop.
  1383. break;
  1384. }
  1385. if( $resetGzipEncoding ) {
  1386. if( $status['name'] == 'ob_gzhandler' ) {
  1387. // Reset the 'Content-Encoding' field set by this handler
  1388. // so we can start fresh.
  1389. header( 'Content-Encoding:' );
  1390. break;
  1391. }
  1392. }
  1393. }
  1394. }
  1395. /**
  1396. * More legible than passing a 'false' parameter to wfResetOutputBuffers():
  1397. *
  1398. * Clear away output buffers, but keep the Content-Encoding header
  1399. * produced by ob_gzhandler, if any.
  1400. *
  1401. * This should be used for HTTP 304 responses, where you need to
  1402. * preserve the Content-Encoding header of the real result, but
  1403. * also need to suppress the output of ob_gzhandler to keep to spec
  1404. * and avoid breaking Firefox in rare cases where the headers and
  1405. * body are broken over two packets.
  1406. */
  1407. function wfClearOutputBuffers() {
  1408. wfResetOutputBuffers( false );
  1409. }
  1410. /**
  1411. * Converts an Accept-* header into an array mapping string values to quality
  1412. * factors
  1413. */
  1414. function wfAcceptToPrefs( $accept, $def = '*/*' ) {
  1415. # No arg means accept anything (per HTTP spec)
  1416. if( !$accept ) {
  1417. return array( $def => 1.0 );
  1418. }
  1419. $prefs = array();
  1420. $parts = explode( ',', $accept );
  1421. foreach( $parts as $part ) {
  1422. # FIXME: doesn't deal with params like 'text/html; level=1'
  1423. @list( $value, $qpart ) = explode( ';', trim( $part ) );
  1424. $match = array();
  1425. if( !isset( $qpart ) ) {
  1426. $prefs[$value] = 1.0;
  1427. } elseif( preg_match( '/q\s*=\s*(\d*\.\d+)/', $qpart, $match ) ) {
  1428. $prefs[$value] = floatval($match[1]);
  1429. }
  1430. }
  1431. return $prefs;
  1432. }
  1433. /**
  1434. * Checks if a given MIME type matches any of the keys in the given
  1435. * array. Basic wildcards are accepted in the array keys.
  1436. *
  1437. * Returns the matching MIME type (or wildcard) if a match, otherwise
  1438. * NULL if no match.
  1439. *
  1440. * @param string $type
  1441. * @param array $avail
  1442. * @return string
  1443. * @private
  1444. */
  1445. function mimeTypeMatch( $type, $avail ) {
  1446. if( array_key_exists($type, $avail) ) {
  1447. return $type;
  1448. } else {
  1449. $parts = explode( '/', $type );
  1450. if( array_key_exists( $parts[0] . '/*', $avail ) ) {
  1451. return $parts[0] . '/*';
  1452. } elseif( array_key_exists( '*/*', $avail ) ) {
  1453. return '*/*';
  1454. } else {
  1455. return NULL;
  1456. }
  1457. }
  1458. }
  1459. /**
  1460. * Returns the 'best' match between a client's requested internet media types
  1461. * and the server's list of available types. Each list should be an associative
  1462. * array of type to preference (preference is a float between 0.0 and 1.0).
  1463. * Wildcards in the types are acceptable.
  1464. *
  1465. * @param array $cprefs Client's acceptable type list
  1466. * @param array $sprefs Server's offered types
  1467. * @return string
  1468. *
  1469. * @todo FIXME: doesn't handle params like 'text/plain; charset=UTF-8'
  1470. * XXX: generalize to negotiate other stuff
  1471. */
  1472. function wfNegotiateType( $cprefs, $sprefs ) {
  1473. $combine = array();
  1474. foreach( array_keys($sprefs) as $type ) {
  1475. $parts = explode( '/', $type );
  1476. if( $parts[1] != '*' ) {
  1477. $ckey = mimeTypeMatch( $type, $cprefs );
  1478. if( $ckey ) {
  1479. $combine[$type] = $sprefs[$type] * $cprefs[$ckey];
  1480. }
  1481. }
  1482. }
  1483. foreach( array_keys( $cprefs ) as $type ) {
  1484. $parts = explode( '/', $type );
  1485. if( $parts[1] != '*' && !array_key_exists( $type, $sprefs ) ) {
  1486. $skey = mimeTypeMatch( $type, $sprefs );
  1487. if( $skey ) {
  1488. $combine[$type] = $sprefs[$skey] * $cprefs[$type];
  1489. }
  1490. }
  1491. }
  1492. $bestq = 0;
  1493. $besttype = NULL;
  1494. foreach( array_keys( $combine ) as $type ) {
  1495. if( $combine[$type] > $bestq ) {
  1496. $besttype = $type;
  1497. $bestq = $combine[$type];
  1498. }
  1499. }
  1500. return $besttype;
  1501. }
  1502. /**
  1503. * Array lookup
  1504. * Returns an array where the values in the first array are replaced by the
  1505. * values in the second array with the corresponding keys
  1506. *
  1507. * @return array
  1508. */
  1509. function wfArrayLookup( $a, $b ) {
  1510. return array_flip( array_intersect( array_flip( $a ), array_keys( $b ) ) );
  1511. }
  1512. /**
  1513. * Convenience function; returns MediaWiki timestamp for the present time.
  1514. * @return string
  1515. */
  1516. function wfTimestampNow() {
  1517. # return NOW
  1518. return wfTimestamp( TS_MW, time() );
  1519. }
  1520. /**
  1521. * Reference-counted warning suppression
  1522. */
  1523. function wfSuppressWarnings( $end = false ) {
  1524. static $suppressCount = 0;
  1525. static $originalLevel = false;
  1526. if ( $end ) {
  1527. if ( $suppressCount ) {
  1528. --$suppressCount;
  1529. if ( !$suppressCount ) {
  1530. error_reporting( $originalLevel );
  1531. }
  1532. }
  1533. } else {
  1534. if ( !$suppressCount ) {
  1535. $originalLevel = error_reporting( E_ALL & ~( E_WARNING | E_NOTICE ) );
  1536. }
  1537. ++$suppressCount;
  1538. }
  1539. }
  1540. /**
  1541. * Restore error level to previous value
  1542. */
  1543. function wfRestoreWarnings() {
  1544. wfSuppressWarnings( true );
  1545. }
  1546. # Autodetect, convert and provide timestamps of various types
  1547. /**
  1548. * Unix time - the number of seconds since 1970-01-01 00:00:00 UTC
  1549. */
  1550. define('TS_UNIX', 0);
  1551. /**
  1552. * MediaWiki concatenated string timestamp (YYYYMMDDHHMMSS)
  1553. */
  1554. define('TS_MW', 1);
  1555. /**
  1556. * MySQL DATETIME (YYYY-MM-DD HH:MM:SS)
  1557. */
  1558. define('TS_DB', 2);
  1559. /**
  1560. * RFC 2822 format, for E-mail and HTTP headers
  1561. */
  1562. define('TS_RFC2822', 3);
  1563. /**
  1564. * ISO 8601 format with no timezone: 1986-02-09T20:00:00Z
  1565. *
  1566. * This is used by Special:Export
  1567. */
  1568. define('TS_ISO_8601', 4);
  1569. /**
  1570. * An Exif timestamp (YYYY:MM:DD HH:MM:SS)
  1571. *
  1572. * @see http://exif.org/Exif2-2.PDF The Exif 2.2 spec, see page 28 for the
  1573. * DateTime tag and page 36 for the DateTimeOriginal and
  1574. * DateTimeDigitized tags.
  1575. */
  1576. define('TS_EXIF', 5);
  1577. /**
  1578. * Oracle format time.
  1579. */
  1580. define('TS_ORACLE', 6);
  1581. /**
  1582. * Postgres format time.
  1583. */
  1584. define('TS_POSTGRES', 7);
  1585. /**
  1586. * DB2 format time
  1587. */
  1588. define('TS_DB2', 8);
  1589. /**
  1590. * @param mixed $outputtype A timestamp in one of the supported formats, the
  1591. * function will autodetect which format is supplied
  1592. * and act accordingly.
  1593. * @return string Time in the format specified in $outputtype
  1594. */
  1595. function wfTimestamp($outputtype=TS_UNIX,$ts=0) {
  1596. $uts = 0;
  1597. $da = array();
  1598. if ($ts==0) {
  1599. $uts=time();
  1600. } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
  1601. # TS_DB
  1602. } elseif (preg_match('/^(\d{4}):(\d\d):(\d\d) (\d\d):(\d\d):(\d\d)$/D',$ts,$da)) {
  1603. # TS_EXIF
  1604. } elseif (preg_match('/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/D',$ts,$da)) {
  1605. # TS_MW
  1606. } elseif (preg_match('/^\d{1,13}$/D',$ts)) {
  1607. # TS_UNIX
  1608. $uts = $ts;
  1609. } elseif (preg_match('/^\d{1,2}-...-\d\d(?:\d\d)? \d\d\.\d\d\.\d\d/', $ts)) {
  1610. # TS_ORACLE
  1611. $uts = strtotime(preg_replace('/(\d\d)\.(\d\d)\.(\d\d)(\.(\d+))?/', "$1:$2:$3",
  1612. str_replace("+00:00", "UTC", $ts)));
  1613. } elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.*\d*)?Z$/', $ts, $da)) {
  1614. # TS_ISO_8601
  1615. } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d*[\+\- ](\d\d)$/',$ts,$da)) {
  1616. # TS_POSTGRES
  1617. } elseif (preg_match('/^(\d{4})\-(\d\d)\-(\d\d) (\d\d):(\d\d):(\d\d)\.*\d* GMT$/',$ts,$da)) {
  1618. # TS_POSTGRES
  1619. } else {
  1620. # Bogus value; fall back to the epoch...
  1621. wfDebug("wfTimestamp() fed bogus time value: $outputtype; $ts\n");
  1622. $uts = 0;
  1623. }
  1624. if (count( $da ) ) {
  1625. // Warning! gmmktime() acts oddly if the month or day is set to 0
  1626. // We may want to handle that explicitly at some point
  1627. $uts=gmmktime((int)$da[4],(int)$da[5],(int)$da[6],
  1628. (int)$da[2],(int)$da[3],(int)$da[1]);
  1629. }
  1630. switch($outputtype) {
  1631. case TS_UNIX:
  1632. return $uts;
  1633. case TS_MW:
  1634. return gmdate( 'YmdHis', $uts );
  1635. case TS_DB:
  1636. return gmdate( 'Y-m-d H:i:s', $uts );
  1637. case TS_ISO_8601:
  1638. return gmdate( 'Y-m-d\TH:i:s\Z', $uts );
  1639. // This shouldn't ever be used, but is included for completeness
  1640. case TS_EXIF:
  1641. return gmdate( 'Y:m:d H:i:s', $uts );
  1642. case TS_RFC2822:
  1643. return gmdate( 'D, d M Y H:i:s', $uts ) . ' GMT';
  1644. case TS_ORACLE:
  1645. return gmdate( 'd-M-y h.i.s A', $uts) . ' +00:00';
  1646. case TS_POSTGRES:
  1647. return gmdate( 'Y-m-d H:i:s', $uts) . ' GMT';
  1648. case TS_DB2:
  1649. return gmdate( 'Y-m-d H:i:s', $uts);
  1650. default:
  1651. throw new MWException( 'wfTimestamp() called with illegal output type.');
  1652. }
  1653. }
  1654. /**
  1655. * Return a formatted timestamp, or null if input is null.
  1656. * For dealing with nullable timestamp columns in the database.
  1657. * @param int $outputtype
  1658. * @param string $ts
  1659. * @return string
  1660. */
  1661. function wfTimestampOrNull( $outputtype = TS_UNIX, $ts = null ) {
  1662. if( is_null( $ts ) ) {
  1663. return null;
  1664. } else {
  1665. return wfTimestamp( $outputtype, $ts );
  1666. }
  1667. }
  1668. /**
  1669. * Check if the operating system is Windows
  1670. *
  1671. * @return bool True if it's Windows, False otherwise.
  1672. */
  1673. function wfIsWindows() {
  1674. if (substr(php_uname(), 0, 7) == 'Windows') {
  1675. return true;
  1676. } else {
  1677. return false;
  1678. }
  1679. }
  1680. /**
  1681. * Swap two variables
  1682. */
  1683. function swap( &$x, &$y ) {
  1684. $z = $x;
  1685. $x = $y;
  1686. $y = $z;
  1687. }
  1688. function wfGetCachedNotice( $name ) {
  1689. global $wgOut, $wgRenderHashAppend, $parserMemc;
  1690. $fname = 'wfGetCachedNotice';
  1691. wfProfileIn( $fname );
  1692. $needParse = false;
  1693. if( $name === 'default' ) {
  1694. // special case
  1695. global $wgSiteNotice;
  1696. $notice = $wgSiteNotice;
  1697. if( empty( $notice ) ) {
  1698. wfProfileOut( $fname );
  1699. return false;
  1700. }
  1701. } else {
  1702. $notice = wfMsgForContentNoTrans( $name );
  1703. if( wfEmptyMsg( $name, $notice ) || $notice == '-' ) {
  1704. wfProfileOut( $fname );
  1705. return( false );
  1706. }
  1707. }
  1708. // Use the extra hash appender to let eg SSL variants separately cache.
  1709. $key = wfMemcKey( $name . $wgRenderHashAppend );
  1710. $cachedNotice = $parserMemc->get( $key );
  1711. if( is_array( $cachedNotice ) ) {
  1712. if( md5( $notice ) == $cachedNotice['hash'] ) {
  1713. $notice = $cachedNotice['html'];
  1714. } else {
  1715. $needParse = true;
  1716. }
  1717. } else {
  1718. $needParse = true;
  1719. }
  1720. if( $needParse ) {
  1721. if( is_object( $wgOut ) ) {
  1722. $parsed = $wgOut->parse( $notice );
  1723. $parserMemc->set( $key, array( 'html' => $parsed, 'hash' => md5( $notice ) ), 600 );
  1724. $notice = $parsed;
  1725. } else {
  1726. wfDebug( 'wfGetCachedNotice called for ' . $name . ' with no $wgOut available'."\n" );
  1727. $notice = '';
  1728. }
  1729. }
  1730. wfProfileOut( $fname );
  1731. return $notice;
  1732. }
  1733. function wfGetNamespaceNotice() {
  1734. global $wgTitle;
  1735. # Paranoia
  1736. if ( !isset( $wgTitle ) || !is_object( $wgTitle ) )
  1737. return "";
  1738. $fname = 'wfGetNamespaceNotice';
  1739. wfProfileIn( $fname );
  1740. $key = "namespacenotice-" . $wgTitle->getNsText();
  1741. $namespaceNotice = wfGetCachedNotice( $key );
  1742. if ( $namespaceNotice && substr ( $namespaceNotice , 0 ,7 ) != "<p>&lt;" ) {
  1743. $namespaceNotice = '<div id="namespacebanner">' . $namespaceNotice . "</div>";
  1744. } else {
  1745. $namespaceNotice = "";
  1746. }
  1747. wfProfileOut( $fname );
  1748. return $namespaceNotice;
  1749. }
  1750. function wfGetSiteNotice() {
  1751. global $wgUser, $wgSiteNotice;
  1752. $fname = 'wfGetSiteNotice';
  1753. wfProfileIn( $fname );
  1754. $siteNotice = '';
  1755. if( wfRunHooks( 'SiteNoticeBefore', array( &$siteNotice ) ) ) {
  1756. if( is_object( $wgUser ) && $wgUser->isLoggedIn() ) {
  1757. $siteNotice = wfGetCachedNotice( 'sitenotice' );
  1758. } else {
  1759. $anonNotice = wfGetCachedNotice( 'anonnotice' );
  1760. if( !$anonNotice ) {
  1761. $siteNotice = wfGetCachedNotice( 'sitenotice' );
  1762. } else {
  1763. $siteNotice = $anonNotice;
  1764. }
  1765. }
  1766. if( !$siteNotice ) {
  1767. $siteNotice = wfGetCachedNotice( 'default' );
  1768. }
  1769. }
  1770. wfRunHooks( 'SiteNoticeAfter', array( &$siteNotice ) );
  1771. wfProfileOut( $fname );
  1772. return $siteNotice;
  1773. }
  1774. /**
  1775. * BC wrapper for MimeMagic::singleton()
  1776. * @deprecated
  1777. */
  1778. function &wfGetMimeMagic() {
  1779. return MimeMagic::singleton();
  1780. }
  1781. /**
  1782. * Tries to get the system directory for temporary files.
  1783. * The TMPDIR, TMP, and TEMP environment variables are checked in sequence,
  1784. * and if none are set /tmp is returned as the generic Unix default.
  1785. *
  1786. * NOTE: When possible, use the tempfile() function to create temporary
  1787. * files to avoid race conditions on file creation, etc.
  1788. *
  1789. * @return string
  1790. */
  1791. function wfTempDir() {
  1792. foreach( array( 'TMPDIR', 'TMP', 'TEMP' ) as $var ) {
  1793. $tmp = getenv( $var );
  1794. if( $tmp && file_exists( $tmp ) && is_dir( $tmp ) && is_writable( $tmp ) ) {
  1795. return $tmp;
  1796. }
  1797. }
  1798. # Hope this is Unix of some kind!
  1799. return '/tmp';
  1800. }
  1801. /**
  1802. * Make directory, and make all parent directories if they don't exist
  1803. *
  1804. * @param string $dir Full path to directory to create
  1805. * @param int $mode Chmod value to use, default is $wgDirectoryMode
  1806. * @param string $caller Optional caller param for debugging.
  1807. * @return bool
  1808. */
  1809. function wfMkdirParents( $dir, $mode = null, $caller = null ) {
  1810. global $wgDirectoryMode;
  1811. if ( !is_null( $caller ) ) {
  1812. wfDebug( "$caller: called wfMkdirParents($dir)" );
  1813. }
  1814. if( strval( $dir ) === '' || file_exists( $dir ) )
  1815. return true;
  1816. if ( is_null( $mode ) )
  1817. $mode = $wgDirectoryMode;
  1818. return mkdir( $dir, $mode, true ); // PHP5 <3
  1819. }
  1820. /**
  1821. * Increment a statistics counter
  1822. */
  1823. function wfIncrStats( $key ) {
  1824. global $wgStatsMethod;
  1825. if( $wgStatsMethod == 'udp' ) {
  1826. global $wgUDPProfilerHost, $wgUDPProfilerPort, $wgDBname;
  1827. static $socket;
  1828. if (!$socket) {
  1829. $socket=socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
  1830. $statline="stats/{$wgDBname} - 1 1 1 1 1 -total\n";
  1831. socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
  1832. }
  1833. $statline="stats/{$wgDBname} - 1 1 1 1 1 {$key}\n";
  1834. @socket_sendto($socket,$statline,strlen($statline),0,$wgUDPProfilerHost,$wgUDPProfilerPort);
  1835. } elseif( $wgStatsMethod == 'cache' ) {
  1836. global $wgMemc;
  1837. $key = wfMemcKey( 'stats', $key );
  1838. if ( is_null( $wgMemc->incr( $key ) ) ) {
  1839. $wgMemc->add( $key, 1 );
  1840. }
  1841. } else {
  1842. // Disabled
  1843. }
  1844. }
  1845. /**
  1846. * @param mixed $nr The number to format
  1847. * @param int $acc The number of digits after the decimal point, default 2
  1848. * @param bool $round Whether or not to round the value, default true
  1849. * @return float
  1850. */
  1851. function wfPercent( $nr, $acc = 2, $round = true ) {
  1852. $ret = sprintf( "%.${acc}f", $nr );
  1853. return $round ? round( $ret, $acc ) . '%' : "$ret%";
  1854. }
  1855. /**
  1856. * Encrypt a username/password.
  1857. *
  1858. * @param string $userid ID of the user
  1859. * @param string $password Password of the user
  1860. * @return string Hashed password
  1861. * @deprecated Use User::crypt() or User::oldCrypt() instead
  1862. */
  1863. function wfEncryptPassword( $userid, $password ) {
  1864. wfDeprecated(__FUNCTION__);
  1865. # Just wrap around User::oldCrypt()
  1866. return User::oldCrypt($password, $userid);
  1867. }
  1868. /**
  1869. * Appends to second array if $value differs from that in $default
  1870. */
  1871. function wfAppendToArrayIfNotDefault( $key, $value, $default, &$changed ) {
  1872. if ( is_null( $changed ) ) {
  1873. throw new MWException('GlobalFunctions::wfAppendToArrayIfNotDefault got null');
  1874. }
  1875. if ( $default[$key] !== $value ) {
  1876. $changed[$key] = $value;
  1877. }
  1878. }
  1879. /**
  1880. * Since wfMsg() and co suck, they don't return false if the message key they
  1881. * looked up didn't exist but a XHTML string, this function checks for the
  1882. * nonexistance of messages by looking at wfMsg() output
  1883. *
  1884. * @param $msg The message key looked up
  1885. * @param $wfMsgOut The output of wfMsg*()
  1886. * @return bool
  1887. */
  1888. function wfEmptyMsg( $msg, $wfMsgOut ) {
  1889. return $wfMsgOut === htmlspecialchars( "<$msg>" );
  1890. }
  1891. /**
  1892. * Find out whether or not a mixed variable exists in a string
  1893. *
  1894. * @param mixed needle
  1895. * @param string haystack
  1896. * @return bool
  1897. */
  1898. function in_string( $needle, $str ) {
  1899. return strpos( $str, $needle ) !== false;
  1900. }
  1901. function wfSpecialList( $page, $details ) {
  1902. global $wgContLang;
  1903. $details = $details ? ' ' . $wgContLang->getDirMark() . "($details)" : "";
  1904. return $page . $details;
  1905. }
  1906. /**
  1907. * Returns a regular expression of url protocols
  1908. *
  1909. * @return string
  1910. */
  1911. function wfUrlProtocols() {
  1912. global $wgUrlProtocols;
  1913. // Support old-style $wgUrlProtocols strings, for backwards compatibility
  1914. // with LocalSettings files from 1.5
  1915. if ( is_array( $wgUrlProtocols ) ) {
  1916. $protocols = array();
  1917. foreach ($wgUrlProtocols as $protocol)
  1918. $protocols[] = preg_quote( $protocol, '/' );
  1919. return implode( '|', $protocols );
  1920. } else {
  1921. return $wgUrlProtocols;
  1922. }
  1923. }
  1924. /**
  1925. * Safety wrapper around ini_get() for boolean settings.
  1926. * The values returned from ini_get() are pre-normalized for settings
  1927. * set via php.ini or php_flag/php_admin_flag... but *not*
  1928. * for those set via php_value/php_admin_value.
  1929. *
  1930. * It's fairly common for people to use php_value instead of php_flag,
  1931. * which can leave you with an 'off' setting giving a false positive
  1932. * for code that just takes the ini_get() return value as a boolean.
  1933. *
  1934. * To make things extra interesting, setting via php_value accepts
  1935. * "true" and "yes" as true, but php.ini and php_flag consider them false. :)
  1936. * Unrecognized values go false... again opposite PHP's own coercion
  1937. * from string to bool.
  1938. *
  1939. * Luckily, 'properly' set settings will always come back as '0' or '1',
  1940. * so we only have to worry about them and the 'improper' settings.
  1941. *
  1942. * I frickin' hate PHP... :P
  1943. *
  1944. * @param string $setting
  1945. * @return bool
  1946. */
  1947. function wfIniGetBool( $setting ) {
  1948. $val = ini_get( $setting );
  1949. // 'on' and 'true' can't have whitespace around them, but '1' can.
  1950. return strtolower( $val ) == 'on'
  1951. || strtolower( $val ) == 'true'
  1952. || strtolower( $val ) == 'yes'
  1953. || preg_match( "/^\s*[+-]?0*[1-9]/", $val ); // approx C atoi() function
  1954. }
  1955. /**
  1956. * Execute a shell command, with time and memory limits mirrored from the PHP
  1957. * configuration if supported.
  1958. * @param $cmd Command line, properly escaped for shell.
  1959. * @param &$retval optional, will receive the program's exit code.
  1960. * (non-zero is usually failure)
  1961. * @return collected stdout as a string (trailing newlines stripped)
  1962. */
  1963. function wfShellExec( $cmd, &$retval=null ) {
  1964. global $IP, $wgMaxShellMemory, $wgMaxShellFileSize, $wgMaxShellTime;
  1965. static $disabled;
  1966. if ( is_null( $disabled ) ) {
  1967. $disabled = false;
  1968. if( wfIniGetBool( 'safe_mode' ) ) {
  1969. wfDebug( "wfShellExec can't run in safe_mode, PHP's exec functions are too broken.\n" );
  1970. $disabled = true;
  1971. }
  1972. $functions = explode( ',', ini_get( 'disable_functions' ) );
  1973. $functions = array_map( 'trim', $functions );
  1974. $functions = array_map( 'strtolower', $functions );
  1975. if ( in_array( 'passthru', $functions ) ) {
  1976. wfDebug( "passthru is in disabled_functions\n" );
  1977. $disabled = true;
  1978. }
  1979. }
  1980. if ( $disabled ) {
  1981. $retval = 1;
  1982. return "Unable to run external programs in safe mode.";
  1983. }
  1984. wfInitShellLocale();
  1985. if ( php_uname( 's' ) == 'Linux' ) {
  1986. $time = intval( $wgMaxShellTime );
  1987. $mem = intval( $wgMaxShellMemory );
  1988. $filesize = intval( $wgMaxShellFileSize );
  1989. if ( $time > 0 && $mem > 0 ) {
  1990. $script = "$IP/bin/ulimit4.sh";
  1991. if ( is_executable( $script ) ) {
  1992. $cmd = escapeshellarg( $script ) . " $time $mem $filesize " . escapeshellarg( $cmd );
  1993. }
  1994. }
  1995. } elseif ( php_uname( 's' ) == 'Windows NT' ) {
  1996. # This is a hack to work around PHP's flawed invocation of cmd.exe
  1997. # http://news.php.net/php.internals/21796
  1998. $cmd = '"' . $cmd . '"';
  1999. }
  2000. wfDebug( "wfShellExec: $cmd\n" );
  2001. $retval = 1; // error by default?
  2002. ob_start();
  2003. passthru( $cmd, $retval );
  2004. $output = ob_get_contents();
  2005. ob_end_clean();
  2006. if ( $retval == 127 ) {
  2007. wfDebugLog( 'exec', "Possibly missing executable file: $cmd\n" );
  2008. }
  2009. return $output;
  2010. }
  2011. /**
  2012. * Workaround for http://bugs.php.net/bug.php?id=45132
  2013. * escapeshellarg() destroys non-ASCII characters if LANG is not a UTF-8 locale
  2014. */
  2015. function wfInitShellLocale() {
  2016. static $done = false;
  2017. if ( $done ) return;
  2018. $done = true;
  2019. global $wgShellLocale;
  2020. if ( !wfIniGetBool( 'safe_mode' ) ) {
  2021. putenv( "LC_CTYPE=$wgShellLocale" );
  2022. setlocale( LC_CTYPE, $wgShellLocale );
  2023. }
  2024. }
  2025. /**
  2026. * This function works like "use VERSION" in Perl, the program will die with a
  2027. * backtrace if the current version of PHP is less than the version provided
  2028. *
  2029. * This is useful for extensions which due to their nature are not kept in sync
  2030. * with releases, and might depend on other versions of PHP than the main code
  2031. *
  2032. * Note: PHP might die due to parsing errors in some cases before it ever
  2033. * manages to call this function, such is life
  2034. *
  2035. * @see perldoc -f use
  2036. *
  2037. * @param mixed $version The version to check, can be a string, an integer, or
  2038. * a float
  2039. */
  2040. function wfUsePHP( $req_ver ) {
  2041. $php_ver = PHP_VERSION;
  2042. if ( version_compare( $php_ver, (string)$req_ver, '<' ) )
  2043. throw new MWException( "PHP $req_ver required--this is only $php_ver" );
  2044. }
  2045. /**
  2046. * This function works like "use VERSION" in Perl except it checks the version
  2047. * of MediaWiki, the program will die with a backtrace if the current version
  2048. * of MediaWiki is less than the version provided.
  2049. *
  2050. * This is useful for extensions which due to their nature are not kept in sync
  2051. * with releases
  2052. *
  2053. * @see perldoc -f use
  2054. *
  2055. * @param mixed $version The version to check, can be a string, an integer, or
  2056. * a float
  2057. */
  2058. function wfUseMW( $req_ver ) {
  2059. global $wgVersion;
  2060. if ( version_compare( $wgVersion, (string)$req_ver, '<' ) )
  2061. throw new MWException( "MediaWiki $req_ver required--this is only $wgVersion" );
  2062. }
  2063. /**
  2064. * @deprecated use StringUtils::escapeRegexReplacement
  2065. */
  2066. function wfRegexReplacement( $string ) {
  2067. return StringUtils::escapeRegexReplacement( $string );
  2068. }
  2069. /**
  2070. * Return the final portion of a pathname.
  2071. * Reimplemented because PHP5's basename() is buggy with multibyte text.
  2072. * http://bugs.php.net/bug.php?id=33898
  2073. *
  2074. * PHP's basename() only considers '\' a pathchar on Windows and Netware.
  2075. * We'll consider it so always, as we don't want \s in our Unix paths either.
  2076. *
  2077. * @param string $path
  2078. * @param string $suffix to remove if present
  2079. * @return string
  2080. */
  2081. function wfBaseName( $path, $suffix='' ) {
  2082. $encSuffix = ($suffix == '')
  2083. ? ''
  2084. : ( '(?:' . preg_quote( $suffix, '#' ) . ')?' );
  2085. $matches = array();
  2086. if( preg_match( "#([^/\\\\]*?){$encSuffix}[/\\\\]*$#", $path, $matches ) ) {
  2087. return $matches[1];
  2088. } else {
  2089. return '';
  2090. }
  2091. }
  2092. /**
  2093. * Generate a relative path name to the given file.
  2094. * May explode on non-matching case-insensitive paths,
  2095. * funky symlinks, etc.
  2096. *
  2097. * @param string $path Absolute destination path including target filename
  2098. * @param string $from Absolute source path, directory only
  2099. * @return string
  2100. */
  2101. function wfRelativePath( $path, $from ) {
  2102. // Normalize mixed input on Windows...
  2103. $path = str_replace( '/', DIRECTORY_SEPARATOR, $path );
  2104. $from = str_replace( '/', DIRECTORY_SEPARATOR, $from );
  2105. // Trim trailing slashes -- fix for drive root
  2106. $path = rtrim( $path, DIRECTORY_SEPARATOR );
  2107. $from = rtrim( $from, DIRECTORY_SEPARATOR );
  2108. $pieces = explode( DIRECTORY_SEPARATOR, dirname( $path ) );
  2109. $against = explode( DIRECTORY_SEPARATOR, $from );
  2110. if( $pieces[0] !== $against[0] ) {
  2111. // Non-matching Windows drive letters?
  2112. // Return a full path.
  2113. return $path;
  2114. }
  2115. // Trim off common prefix
  2116. while( count( $pieces ) && count( $against )
  2117. && $pieces[0] == $against[0] ) {
  2118. array_shift( $pieces );
  2119. array_shift( $against );
  2120. }
  2121. // relative dots to bump us to the parent
  2122. while( count( $against ) ) {
  2123. array_unshift( $pieces, '..' );
  2124. array_shift( $against );
  2125. }
  2126. array_push( $pieces, wfBaseName( $path ) );
  2127. return implode( DIRECTORY_SEPARATOR, $pieces );
  2128. }
  2129. /**
  2130. * Backwards array plus for people who haven't bothered to read the PHP manual
  2131. * XXX: will not darn your socks for you.
  2132. *
  2133. * @param array $array1, [$array2, [...]]
  2134. * @return array
  2135. */
  2136. function wfArrayMerge( $array1/* ... */ ) {
  2137. $args = func_get_args();
  2138. $args = array_reverse( $args, true );
  2139. $out = array();
  2140. foreach ( $args as $arg ) {
  2141. $out += $arg;
  2142. }
  2143. return $out;
  2144. }
  2145. /**
  2146. * Merge arrays in the style of getUserPermissionsErrors, with duplicate removal
  2147. * e.g.
  2148. * wfMergeErrorArrays(
  2149. * array( array( 'x' ) ),
  2150. * array( array( 'x', '2' ) ),
  2151. * array( array( 'x' ) ),
  2152. * array( array( 'y') )
  2153. * );
  2154. * returns:
  2155. * array(
  2156. * array( 'x', '2' ),
  2157. * array( 'x' ),
  2158. * array( 'y' )
  2159. * )
  2160. */
  2161. function wfMergeErrorArrays(/*...*/) {
  2162. $args = func_get_args();
  2163. $out = array();
  2164. foreach ( $args as $errors ) {
  2165. foreach ( $errors as $params ) {
  2166. $spec = implode( "\t", $params );
  2167. $out[$spec] = $params;
  2168. }
  2169. }
  2170. return array_values( $out );
  2171. }
  2172. /**
  2173. * parse_url() work-alike, but non-broken. Differences:
  2174. *
  2175. * 1) Does not raise warnings on bad URLs (just returns false)
  2176. * 2) Handles protocols that don't use :// (e.g., mailto: and news:) correctly
  2177. * 3) Adds a "delimiter" element to the array, either '://' or ':' (see (2))
  2178. *
  2179. * @param string $url A URL to parse
  2180. * @return array Bits of the URL in an associative array, per PHP docs
  2181. */
  2182. function wfParseUrl( $url ) {
  2183. global $wgUrlProtocols; // Allow all protocols defined in DefaultSettings/LocalSettings.php
  2184. wfSuppressWarnings();
  2185. $bits = parse_url( $url );
  2186. wfRestoreWarnings();
  2187. if ( !$bits ) {
  2188. return false;
  2189. }
  2190. // most of the protocols are followed by ://, but mailto: and sometimes news: not, check for it
  2191. if ( in_array( $bits['scheme'] . '://', $wgUrlProtocols ) ) {
  2192. $bits['delimiter'] = '://';
  2193. } elseif ( in_array( $bits['scheme'] . ':', $wgUrlProtocols ) ) {
  2194. $bits['delimiter'] = ':';
  2195. // parse_url detects for news: and mailto: the host part of an url as path
  2196. // We have to correct this wrong detection
  2197. if ( isset ( $bits['path'] ) ) {
  2198. $bits['host'] = $bits['path'];
  2199. $bits['path'] = '';
  2200. }
  2201. } else {
  2202. return false;
  2203. }
  2204. return $bits;
  2205. }
  2206. /**
  2207. * Make a URL index, appropriate for the el_index field of externallinks.
  2208. */
  2209. function wfMakeUrlIndex( $url ) {
  2210. $bits = wfParseUrl( $url );
  2211. // Reverse the labels in the hostname, convert to lower case
  2212. // For emails reverse domainpart only
  2213. if ( $bits['scheme'] == 'mailto' ) {
  2214. $mailparts = explode( '@', $bits['host'], 2 );
  2215. if ( count($mailparts) === 2 ) {
  2216. $domainpart = strtolower( implode( '.', array_reverse( explode( '.', $mailparts[1] ) ) ) );
  2217. } else {
  2218. // No domain specified, don't mangle it
  2219. $domainpart = '';
  2220. }
  2221. $reversedHost = $domainpart . '@' . $mailparts[0];
  2222. } else {
  2223. $reversedHost = strtolower( implode( '.', array_reverse( explode( '.', $bits['host'] ) ) ) );
  2224. }
  2225. // Add an extra dot to the end
  2226. // Why? Is it in wrong place in mailto links?
  2227. if ( substr( $reversedHost, -1, 1 ) !== '.' ) {
  2228. $reversedHost .= '.';
  2229. }
  2230. // Reconstruct the pseudo-URL
  2231. $prot = $bits['scheme'];
  2232. $index = $prot . $bits['delimiter'] . $reversedHost;
  2233. // Leave out user and password. Add the port, path, query and fragment
  2234. if ( isset( $bits['port'] ) ) $index .= ':' . $bits['port'];
  2235. if ( isset( $bits['path'] ) ) {
  2236. $index .= $bits['path'];
  2237. } else {
  2238. $index .= '/';
  2239. }
  2240. if ( isset( $bits['query'] ) ) $index .= '?' . $bits['query'];
  2241. if ( isset( $bits['fragment'] ) ) $index .= '#' . $bits['fragment'];
  2242. return $index;
  2243. }
  2244. /**
  2245. * Do any deferred updates and clear the list
  2246. * TODO: This could be in Wiki.php if that class made any sense at all
  2247. */
  2248. function wfDoUpdates()
  2249. {
  2250. global $wgPostCommitUpdateList, $wgDeferredUpdateList;
  2251. foreach ( $wgDeferredUpdateList as $update ) {
  2252. $update->doUpdate();
  2253. }
  2254. foreach ( $wgPostCommitUpdateList as $update ) {
  2255. $update->doUpdate();
  2256. }
  2257. $wgDeferredUpdateList = array();
  2258. $wgPostCommitUpdateList = array();
  2259. }
  2260. /**
  2261. * @deprecated use StringUtils::explodeMarkup
  2262. */
  2263. function wfExplodeMarkup( $separator, $text ) {
  2264. return StringUtils::explodeMarkup( $separator, $text );
  2265. }
  2266. /**
  2267. * Convert an arbitrarily-long digit string from one numeric base
  2268. * to another, optionally zero-padding to a minimum column width.
  2269. *
  2270. * Supports base 2 through 36; digit values 10-36 are represented
  2271. * as lowercase letters a-z. Input is case-insensitive.
  2272. *
  2273. * @param $input string of digits
  2274. * @param $sourceBase int 2-36
  2275. * @param $destBase int 2-36
  2276. * @param $pad int 1 or greater
  2277. * @param $lowercase bool
  2278. * @return string or false on invalid input
  2279. */
  2280. function wfBaseConvert( $input, $sourceBase, $destBase, $pad=1, $lowercase=true ) {
  2281. $input = strval( $input );
  2282. if( $sourceBase < 2 ||
  2283. $sourceBase > 36 ||
  2284. $destBase < 2 ||
  2285. $destBase > 36 ||
  2286. $pad < 1 ||
  2287. $sourceBase != intval( $sourceBase ) ||
  2288. $destBase != intval( $destBase ) ||
  2289. $pad != intval( $pad ) ||
  2290. !is_string( $input ) ||
  2291. $input == '' ) {
  2292. return false;
  2293. }
  2294. $digitChars = ( $lowercase ) ? '0123456789abcdefghijklmnopqrstuvwxyz' : '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  2295. $inDigits = array();
  2296. $outChars = '';
  2297. // Decode and validate input string
  2298. $input = strtolower( $input );
  2299. for( $i = 0; $i < strlen( $input ); $i++ ) {
  2300. $n = strpos( $digitChars, $input{$i} );
  2301. if( $n === false || $n > $sourceBase ) {
  2302. return false;
  2303. }
  2304. $inDigits[] = $n;
  2305. }
  2306. // Iterate over the input, modulo-ing out an output digit
  2307. // at a time until input is gone.
  2308. while( count( $inDigits ) ) {
  2309. $work = 0;
  2310. $workDigits = array();
  2311. // Long division...
  2312. foreach( $inDigits as $digit ) {
  2313. $work *= $sourceBase;
  2314. $work += $digit;
  2315. if( $work < $destBase ) {
  2316. // Gonna need to pull another digit.
  2317. if( count( $workDigits ) ) {
  2318. // Avoid zero-padding; this lets us find
  2319. // the end of the input very easily when
  2320. // length drops to zero.
  2321. $workDigits[] = 0;
  2322. }
  2323. } else {
  2324. // Finally! Actual division!
  2325. $workDigits[] = intval( $work / $destBase );
  2326. // Isn't it annoying that most programming languages
  2327. // don't have a single divide-and-remainder operator,
  2328. // even though the CPU implements it that way?
  2329. $work = $work % $destBase;
  2330. }
  2331. }
  2332. // All that division leaves us with a remainder,
  2333. // which is conveniently our next output digit.
  2334. $outChars .= $digitChars[$work];
  2335. // And we continue!
  2336. $inDigits = $workDigits;
  2337. }
  2338. while( strlen( $outChars ) < $pad ) {
  2339. $outChars .= '0';
  2340. }
  2341. return strrev( $outChars );
  2342. }
  2343. /**
  2344. * Create an object with a given name and an array of construct parameters
  2345. * @param string $name
  2346. * @param array $p parameters
  2347. */
  2348. function wfCreateObject( $name, $p ){
  2349. $p = array_values( $p );
  2350. switch ( count( $p ) ) {
  2351. case 0:
  2352. return new $name;
  2353. case 1:
  2354. return new $name( $p[0] );
  2355. case 2:
  2356. return new $name( $p[0], $p[1] );
  2357. case 3:
  2358. return new $name( $p[0], $p[1], $p[2] );
  2359. case 4:
  2360. return new $name( $p[0], $p[1], $p[2], $p[3] );
  2361. case 5:
  2362. return new $name( $p[0], $p[1], $p[2], $p[3], $p[4] );
  2363. case 6:
  2364. return new $name( $p[0], $p[1], $p[2], $p[3], $p[4], $p[5] );
  2365. default:
  2366. throw new MWException( "Too many arguments to construtor in wfCreateObject" );
  2367. }
  2368. }
  2369. /**
  2370. * Alias for modularized function
  2371. * @deprecated Use Http::get() instead
  2372. */
  2373. function wfGetHTTP( $url, $timeout = 'default' ) {
  2374. wfDeprecated(__FUNCTION__);
  2375. return Http::get( $url, $timeout );
  2376. }
  2377. /**
  2378. * Alias for modularized function
  2379. * @deprecated Use Http::isLocalURL() instead
  2380. */
  2381. function wfIsLocalURL( $url ) {
  2382. wfDeprecated(__FUNCTION__);
  2383. return Http::isLocalURL( $url );
  2384. }
  2385. function wfHttpOnlySafe() {
  2386. global $wgHttpOnlyBlacklist;
  2387. if( !version_compare("5.2", PHP_VERSION, "<") )
  2388. return false;
  2389. if( isset( $_SERVER['HTTP_USER_AGENT'] ) ) {
  2390. foreach( $wgHttpOnlyBlacklist as $regex ) {
  2391. if( preg_match( $regex, $_SERVER['HTTP_USER_AGENT'] ) ) {
  2392. return false;
  2393. }
  2394. }
  2395. }
  2396. return true;
  2397. }
  2398. /**
  2399. * Initialise php session
  2400. */
  2401. function wfSetupSession() {
  2402. global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly;
  2403. if( $wgSessionsInMemcached ) {
  2404. require_once( 'MemcachedSessions.php' );
  2405. } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
  2406. # If it's left on 'user' or another setting from another
  2407. # application, it will end up failing. Try to recover.
  2408. ini_set ( 'session.save_handler', 'files' );
  2409. }
  2410. $httpOnlySafe = wfHttpOnlySafe();
  2411. wfDebugLog( 'cookie',
  2412. 'session_set_cookie_params: "' . implode( '", "',
  2413. array(
  2414. 0,
  2415. $wgCookiePath,
  2416. $wgCookieDomain,
  2417. $wgCookieSecure,
  2418. $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
  2419. if( $httpOnlySafe && $wgCookieHttpOnly ) {
  2420. session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookieHttpOnly );
  2421. } else {
  2422. // PHP 5.1 throws warnings if you pass the HttpOnly parameter for 5.2.
  2423. session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
  2424. }
  2425. session_cache_limiter( 'private, must-revalidate' );
  2426. wfSuppressWarnings();
  2427. session_start();
  2428. wfRestoreWarnings();
  2429. }
  2430. /**
  2431. * Get an object from the precompiled serialized directory
  2432. *
  2433. * @return mixed The variable on success, false on failure
  2434. */
  2435. function wfGetPrecompiledData( $name ) {
  2436. global $IP;
  2437. $file = "$IP/serialized/$name";
  2438. if ( file_exists( $file ) ) {
  2439. $blob = file_get_contents( $file );
  2440. if ( $blob ) {
  2441. return unserialize( $blob );
  2442. }
  2443. }
  2444. return false;
  2445. }
  2446. function wfGetCaller( $level = 2 ) {
  2447. $backtrace = wfDebugBacktrace();
  2448. if ( isset( $backtrace[$level] ) ) {
  2449. return wfFormatStackFrame($backtrace[$level]);
  2450. } else {
  2451. $caller = 'unknown';
  2452. }
  2453. return $caller;
  2454. }
  2455. /** Return a string consisting all callers in stack, somewhat useful sometimes for profiling specific points */
  2456. function wfGetAllCallers() {
  2457. return implode('/', array_map('wfFormatStackFrame',array_reverse(wfDebugBacktrace())));
  2458. }
  2459. /** Return a string representation of frame */
  2460. function wfFormatStackFrame($frame) {
  2461. return isset( $frame["class"] )?
  2462. $frame["class"]."::".$frame["function"]:
  2463. $frame["function"];
  2464. }
  2465. /**
  2466. * Get a cache key
  2467. */
  2468. function wfMemcKey( /*... */ ) {
  2469. $args = func_get_args();
  2470. $key = wfWikiID() . ':' . implode( ':', $args );
  2471. return $key;
  2472. }
  2473. /**
  2474. * Get a cache key for a foreign DB
  2475. */
  2476. function wfForeignMemcKey( $db, $prefix /*, ... */ ) {
  2477. $args = array_slice( func_get_args(), 2 );
  2478. if ( $prefix ) {
  2479. $key = "$db-$prefix:" . implode( ':', $args );
  2480. } else {
  2481. $key = $db . ':' . implode( ':', $args );
  2482. }
  2483. return $key;
  2484. }
  2485. /**
  2486. * Get an ASCII string identifying this wiki
  2487. * This is used as a prefix in memcached keys
  2488. */
  2489. function wfWikiID( $db = null ) {
  2490. if( $db instanceof Database ) {
  2491. return $db->getWikiID();
  2492. } else {
  2493. global $wgDBprefix, $wgDBname;
  2494. if ( $wgDBprefix ) {
  2495. return "$wgDBname-$wgDBprefix";
  2496. } else {
  2497. return $wgDBname;
  2498. }
  2499. }
  2500. }
  2501. /**
  2502. * Split a wiki ID into DB name and table prefix
  2503. */
  2504. function wfSplitWikiID( $wiki ) {
  2505. $bits = explode( '-', $wiki, 2 );
  2506. if ( count( $bits ) < 2 ) {
  2507. $bits[] = '';
  2508. }
  2509. return $bits;
  2510. }
  2511. /*
  2512. * Get a Database object.
  2513. * @param integer $db Index of the connection to get. May be DB_MASTER for the
  2514. * master (for write queries), DB_SLAVE for potentially lagged
  2515. * read queries, or an integer >= 0 for a particular server.
  2516. *
  2517. * @param mixed $groups Query groups. An array of group names that this query
  2518. * belongs to. May contain a single string if the query is only
  2519. * in one group.
  2520. *
  2521. * @param string $wiki The wiki ID, or false for the current wiki
  2522. *
  2523. * Note: multiple calls to wfGetDB(DB_SLAVE) during the course of one request
  2524. * will always return the same object, unless the underlying connection or load
  2525. * balancer is manually destroyed.
  2526. */
  2527. function &wfGetDB( $db, $groups = array(), $wiki = false ) {
  2528. return wfGetLB( $wiki )->getConnection( $db, $groups, $wiki );
  2529. }
  2530. /**
  2531. * Get a load balancer object.
  2532. *
  2533. * @param array $groups List of query groups
  2534. * @param string $wiki Wiki ID, or false for the current wiki
  2535. * @return LoadBalancer
  2536. */
  2537. function wfGetLB( $wiki = false ) {
  2538. return wfGetLBFactory()->getMainLB( $wiki );
  2539. }
  2540. /**
  2541. * Get the load balancer factory object
  2542. */
  2543. function &wfGetLBFactory() {
  2544. return LBFactory::singleton();
  2545. }
  2546. /**
  2547. * Find a file.
  2548. * Shortcut for RepoGroup::singleton()->findFile()
  2549. * @param mixed $title Title object or string. May be interwiki.
  2550. * @param mixed $time Requested time for an archived image, or false for the
  2551. * current version. An image object will be returned which
  2552. * was created at the specified time.
  2553. * @param mixed $flags FileRepo::FIND_ flags
  2554. * @param boolean $bypass Bypass the file cache even if it could be used
  2555. * @return File, or false if the file does not exist
  2556. */
  2557. function wfFindFile( $title, $time = false, $flags = 0, $bypass = false ) {
  2558. if( !$time && !$flags && !$bypass ) {
  2559. return FileCache::singleton()->findFile( $title );
  2560. } else {
  2561. return RepoGroup::singleton()->findFile( $title, $time, $flags );
  2562. }
  2563. }
  2564. /**
  2565. * Get an object referring to a locally registered file.
  2566. * Returns a valid placeholder object if the file does not exist.
  2567. */
  2568. function wfLocalFile( $title ) {
  2569. return RepoGroup::singleton()->getLocalRepo()->newFile( $title );
  2570. }
  2571. /**
  2572. * Should low-performance queries be disabled?
  2573. *
  2574. * @return bool
  2575. */
  2576. function wfQueriesMustScale() {
  2577. global $wgMiserMode;
  2578. return $wgMiserMode
  2579. || ( SiteStats::pages() > 100000
  2580. && SiteStats::edits() > 1000000
  2581. && SiteStats::users() > 10000 );
  2582. }
  2583. /**
  2584. * Get the path to a specified script file, respecting file
  2585. * extensions; this is a wrapper around $wgScriptExtension etc.
  2586. *
  2587. * @param string $script Script filename, sans extension
  2588. * @return string
  2589. */
  2590. function wfScript( $script = 'index' ) {
  2591. global $wgScriptPath, $wgScriptExtension;
  2592. return "{$wgScriptPath}/{$script}{$wgScriptExtension}";
  2593. }
  2594. /**
  2595. * Convenience function converts boolean values into "true"
  2596. * or "false" (string) values
  2597. *
  2598. * @param bool $value
  2599. * @return string
  2600. */
  2601. function wfBoolToStr( $value ) {
  2602. return $value ? 'true' : 'false';
  2603. }
  2604. /**
  2605. * Load an extension messages file
  2606. *
  2607. * @param string $extensionName Name of extension to load messages from\for.
  2608. * @param string $langcode Language to load messages for, or false for default
  2609. * behvaiour (en, content language and user language).
  2610. * @since r24808 (v1.11) Using this method of loading extension messages will not work
  2611. * on MediaWiki prior to that
  2612. */
  2613. function wfLoadExtensionMessages( $extensionName, $langcode = false ) {
  2614. global $wgExtensionMessagesFiles, $wgMessageCache, $wgLang, $wgContLang;
  2615. #For recording whether extension message files have been loaded in a given language.
  2616. static $loaded = array();
  2617. if( !array_key_exists( $extensionName, $loaded ) ) {
  2618. $loaded[$extensionName] = array();
  2619. }
  2620. if ( !isset($wgExtensionMessagesFiles[$extensionName]) ) {
  2621. throw new MWException( "Messages file for extensions $extensionName is not defined" );
  2622. }
  2623. if( !$langcode && !array_key_exists( '*', $loaded[$extensionName] ) ) {
  2624. # Just do en, content language and user language.
  2625. $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], false );
  2626. # Mark that they have been loaded.
  2627. $loaded[$extensionName]['en'] = true;
  2628. $loaded[$extensionName][$wgLang->getCode()] = true;
  2629. $loaded[$extensionName][$wgContLang->getCode()] = true;
  2630. # Mark that this part has been done to avoid weird if statements.
  2631. $loaded[$extensionName]['*'] = true;
  2632. } elseif( is_string( $langcode ) && !array_key_exists( $langcode, $loaded[$extensionName] ) ) {
  2633. # Load messages for specified language.
  2634. $wgMessageCache->loadMessagesFile( $wgExtensionMessagesFiles[$extensionName], $langcode );
  2635. # Mark that they have been loaded.
  2636. $loaded[$extensionName][$langcode] = true;
  2637. }
  2638. }
  2639. /**
  2640. * Get a platform-independent path to the null file, e.g.
  2641. * /dev/null
  2642. *
  2643. * @return string
  2644. */
  2645. function wfGetNull() {
  2646. return wfIsWindows()
  2647. ? 'NUL'
  2648. : '/dev/null';
  2649. }
  2650. /**
  2651. * Displays a maxlag error
  2652. *
  2653. * @param string $host Server that lags the most
  2654. * @param int $lag Maxlag (actual)
  2655. * @param int $maxLag Maxlag (requested)
  2656. */
  2657. function wfMaxlagError( $host, $lag, $maxLag ) {
  2658. global $wgShowHostnames;
  2659. header( 'HTTP/1.1 503 Service Unavailable' );
  2660. header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
  2661. header( 'X-Database-Lag: ' . intval( $lag ) );
  2662. header( 'Content-Type: text/plain' );
  2663. if( $wgShowHostnames ) {
  2664. echo "Waiting for $host: $lag seconds lagged\n";
  2665. } else {
  2666. echo "Waiting for a database server: $lag seconds lagged\n";
  2667. }
  2668. }
  2669. /**
  2670. * Throws an E_USER_NOTICE saying that $function is deprecated
  2671. * @param string $function
  2672. * @return null
  2673. */
  2674. function wfDeprecated( $function ) {
  2675. global $wgDebugLogFile;
  2676. if ( !$wgDebugLogFile ) {
  2677. return;
  2678. }
  2679. $callers = wfDebugBacktrace();
  2680. if( isset( $callers[2] ) ){
  2681. $callerfunc = $callers[2];
  2682. $callerfile = $callers[1];
  2683. if( isset( $callerfile['file'] ) && isset( $callerfile['line'] ) ){
  2684. $file = $callerfile['file'] . ' at line ' . $callerfile['line'];
  2685. } else {
  2686. $file = '(internal function)';
  2687. }
  2688. $func = '';
  2689. if( isset( $callerfunc['class'] ) )
  2690. $func .= $callerfunc['class'] . '::';
  2691. $func .= @$callerfunc['function'];
  2692. $msg = "Use of $function is deprecated. Called from $func in $file";
  2693. } else {
  2694. $msg = "Use of $function is deprecated.";
  2695. }
  2696. wfDebug( "$msg\n" );
  2697. }
  2698. /**
  2699. * Sleep until the worst slave's replication lag is less than or equal to
  2700. * $maxLag, in seconds. Use this when updating very large numbers of rows, as
  2701. * in maintenance scripts, to avoid causing too much lag. Of course, this is
  2702. * a no-op if there are no slaves.
  2703. *
  2704. * Every time the function has to wait for a slave, it will print a message to
  2705. * that effect (and then sleep for a little while), so it's probably not best
  2706. * to use this outside maintenance scripts in its present form.
  2707. *
  2708. * @param int $maxLag
  2709. * @return null
  2710. */
  2711. function wfWaitForSlaves( $maxLag ) {
  2712. if( $maxLag ) {
  2713. $lb = wfGetLB();
  2714. list( $host, $lag ) = $lb->getMaxLag();
  2715. while( $lag > $maxLag ) {
  2716. $name = @gethostbyaddr( $host );
  2717. if( $name !== false ) {
  2718. $host = $name;
  2719. }
  2720. print "Waiting for $host (lagged $lag seconds)...\n";
  2721. sleep($maxLag);
  2722. list( $host, $lag ) = $lb->getMaxLag();
  2723. }
  2724. }
  2725. }
  2726. /**
  2727. * Output some plain text in command-line mode or in the installer (updaters.inc).
  2728. * Do not use it in any other context, its behaviour is subject to change.
  2729. */
  2730. function wfOut( $s ) {
  2731. static $lineStarted = false;
  2732. global $wgCommandLineMode;
  2733. if ( $wgCommandLineMode && !defined( 'MEDIAWIKI_INSTALL' ) ) {
  2734. echo $s;
  2735. } else {
  2736. echo htmlspecialchars( $s );
  2737. }
  2738. flush();
  2739. }
  2740. /** Generate a random 32-character hexadecimal token.
  2741. * @param mixed $salt Some sort of salt, if necessary, to add to random characters before hashing.
  2742. */
  2743. function wfGenerateToken( $salt = '' ) {
  2744. $salt = serialize($salt);
  2745. return md5( mt_rand( 0, 0x7fffffff ) . $salt );
  2746. }
  2747. /**
  2748. * Replace all invalid characters with -
  2749. * @param mixed $title Filename to process
  2750. */
  2751. function wfStripIllegalFilenameChars( $name ) {
  2752. $name = wfBaseName( $name );
  2753. $name = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $name );
  2754. return $name;
  2755. }