PageRenderTime 25ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/Message.php

https://github.com/daevid/MWFork
PHP | 488 lines | 208 code | 40 blank | 240 comment | 33 complexity | e89e529a121ee4d7a7aebac00c921e83 MD5 | raw file
  1. <?php
  2. /**
  3. * This class provides methods for fetching interface messages and
  4. * processing them into variety of formats that are needed in MediaWiki.
  5. *
  6. * It is intented to replace the old wfMsg* functions that over time grew
  7. * unusable.
  8. *
  9. * Examples:
  10. * Fetching a message text for interface message
  11. * $button = Xml::button( wfMessage( 'submit' )->text() );
  12. * </pre>
  13. * Messages can have parameters:
  14. * wfMessage( 'welcome-to' )->params( $wgSitename )->text();
  15. * {{GRAMMAR}} and friends work correctly
  16. * wfMessage( 'are-friends', $user, $friend );
  17. * wfMessage( 'bad-message' )->rawParams( '<script>...</script>' )->escaped();
  18. * </pre>
  19. * Sometimes the message text ends up in the database, so content language is needed.
  20. * wfMessage( 'file-log', $user, $filename )->inContentLanguage()->text()
  21. * </pre>
  22. * Checking if message exists:
  23. * wfMessage( 'mysterious-message' )->exists()
  24. * </pre>
  25. * If you want to use a different language:
  26. * wfMessage( 'email-header' )->inLanguage( $user->getOption( 'language' ) )->plain()
  27. * Note that you cannot parse the text except in the content or interface
  28. * languages
  29. * </pre>
  30. *
  31. *
  32. * Comparison with old wfMsg* functions:
  33. *
  34. * Use full parsing.
  35. * wfMsgExt( 'key', array( 'parseinline' ), 'apple' );
  36. * === wfMessage( 'key', 'apple' )->parse();
  37. * </pre>
  38. * Parseinline is used because it is more useful when pre-building html.
  39. * In normal use it is better to use OutputPage::(add|wrap)WikiMsg.
  40. *
  41. * Places where html cannot be used. {{-transformation is done.
  42. * wfMsgExt( 'key', array( 'parsemag' ), 'apple', 'pear' );
  43. * === wfMessage( 'key', 'apple', 'pear' )->text();
  44. * </pre>
  45. *
  46. * Shortcut for escaping the message too, similar to wfMsgHTML, but
  47. * parameters are not replaced after escaping by default.
  48. * $escaped = wfMessage( 'key' )->rawParams( 'apple' )->escaped();
  49. * </pre>
  50. *
  51. * @todo
  52. * - test, can we have tests?
  53. *
  54. * @since 1.17
  55. * @author Niklas Laxström
  56. */
  57. class Message {
  58. /**
  59. * In which language to get this message. True, which is the default,
  60. * means the current interface language, false content language.
  61. */
  62. protected $interface = true;
  63. /**
  64. * In which language to get this message. Overrides the $interface
  65. * variable.
  66. *
  67. * @var Language
  68. */
  69. protected $language = null;
  70. /**
  71. * The message key.
  72. */
  73. protected $key;
  74. /**
  75. * List of parameters which will be substituted into the message.
  76. */
  77. protected $parameters = array();
  78. /**
  79. * Format for the message.
  80. * Supported formats are:
  81. * * text (transform)
  82. * * escaped (transform+htmlspecialchars)
  83. * * block-parse
  84. * * parse (default)
  85. * * plain
  86. */
  87. protected $format = 'parse';
  88. /**
  89. * Whether database can be used.
  90. */
  91. protected $useDatabase = true;
  92. /**
  93. * Title object to use as context
  94. */
  95. protected $title = null;
  96. /**
  97. * Constructor.
  98. * @param $key: message key, or array of message keys to try and use the first non-empty message for
  99. * @param $params Array message parameters
  100. * @return Message: $this
  101. */
  102. public function __construct( $key, $params = array() ) {
  103. global $wgLang;
  104. $this->key = $key;
  105. $this->parameters = array_values( $params );
  106. $this->language = $wgLang;
  107. }
  108. /**
  109. * Factory function that is just wrapper for the real constructor. It is
  110. * intented to be used instead of the real constructor, because it allows
  111. * chaining method calls, while new objects don't.
  112. * @param $key String: message key
  113. * @param Varargs: parameters as Strings
  114. * @return Message: $this
  115. */
  116. public static function newFromKey( $key /*...*/ ) {
  117. $params = func_get_args();
  118. array_shift( $params );
  119. return new self( $key, $params );
  120. }
  121. /**
  122. * Factory function accepting multiple message keys and returning a message instance
  123. * for the first message which is non-empty. If all messages are empty then an
  124. * instance of the first message key is returned.
  125. * @param Varargs: message keys
  126. * @return Message: $this
  127. */
  128. public static function newFallbackSequence( /*...*/ ) {
  129. $keys = func_get_args();
  130. if ( func_num_args() == 1 ) {
  131. if ( is_array($keys[0]) ) {
  132. // Allow an array to be passed as the first argument instead
  133. $keys = array_values($keys[0]);
  134. } else {
  135. // Optimize a single string to not need special fallback handling
  136. $keys = $keys[0];
  137. }
  138. }
  139. return new self( $keys );
  140. }
  141. /**
  142. * Adds parameters to the parameter list of this message.
  143. * @param Varargs: parameters as Strings
  144. * @return Message: $this
  145. */
  146. public function params( /*...*/ ) {
  147. $args = func_get_args();
  148. if ( isset( $args[0] ) && is_array( $args[0] ) ) {
  149. $args = $args[0];
  150. }
  151. $args_values = array_values( $args );
  152. $this->parameters = array_merge( $this->parameters, $args_values );
  153. return $this;
  154. }
  155. /**
  156. * Add parameters that are substituted after parsing or escaping.
  157. * In other words the parsing process cannot access the contents
  158. * of this type of parameter, and you need to make sure it is
  159. * sanitized beforehand. The parser will see "$n", instead.
  160. * @param Varargs: raw parameters as Strings
  161. * @return Message: $this
  162. */
  163. public function rawParams( /*...*/ ) {
  164. $params = func_get_args();
  165. if ( isset( $params[0] ) && is_array( $params[0] ) ) {
  166. $params = $params[0];
  167. }
  168. foreach( $params as $param ) {
  169. $this->parameters[] = self::rawParam( $param );
  170. }
  171. return $this;
  172. }
  173. /**
  174. * Add parameters that are numeric and will be passed through
  175. * Language::formatNum before substitution
  176. * @param Varargs: numeric parameters
  177. * @return Message: $this
  178. */
  179. public function numParams( /*...*/ ) {
  180. $params = func_get_args();
  181. if ( isset( $params[0] ) && is_array( $params[0] ) ) {
  182. $params = $params[0];
  183. }
  184. foreach( $params as $param ) {
  185. $this->parameters[] = self::numParam( $param );
  186. }
  187. return $this;
  188. }
  189. /**
  190. * Request the message in any language that is supported.
  191. * As a side effect interface message status is unconditionally
  192. * turned off.
  193. * @param $lang Mixed: language code or Language object.
  194. * @return Message: $this
  195. */
  196. public function inLanguage( $lang ) {
  197. if ( $lang instanceof Language || $lang instanceof StubUserLang ) {
  198. $this->language = $lang;
  199. } elseif ( is_string( $lang ) ) {
  200. if( $this->language->getCode() != $lang ) {
  201. $this->language = Language::factory( $lang );
  202. }
  203. } else {
  204. $type = gettype( $lang );
  205. throw new MWException( __METHOD__ . " must be "
  206. . "passed a String or Language object; $type given"
  207. );
  208. }
  209. $this->interface = false;
  210. return $this;
  211. }
  212. /**
  213. * Request the message in the wiki's content language,
  214. * unless it is disabled for this message.
  215. * @see $wgForceUIMsgAsContentMsg
  216. * @return Message: $this
  217. */
  218. public function inContentLanguage() {
  219. global $wgForceUIMsgAsContentMsg;
  220. if ( in_array( $this->key, (array)$wgForceUIMsgAsContentMsg ) ) {
  221. return $this;
  222. }
  223. global $wgContLang;
  224. $this->interface = false;
  225. $this->language = $wgContLang;
  226. return $this;
  227. }
  228. /**
  229. * Enable or disable database use.
  230. * @param $value Boolean
  231. * @return Message: $this
  232. */
  233. public function useDatabase( $value ) {
  234. $this->useDatabase = (bool) $value;
  235. return $this;
  236. }
  237. /**
  238. * Set the Title object to use as context when transforming the message
  239. *
  240. * @param $title Title object
  241. * @return Message: $this
  242. */
  243. public function title( $title ) {
  244. $this->title = $title;
  245. return $this;
  246. }
  247. /**
  248. * Returns the message parsed from wikitext to HTML.
  249. * @return String: HTML
  250. */
  251. public function toString() {
  252. $string = $this->getMessageText();
  253. # Replace parameters before text parsing
  254. $string = $this->replaceParameters( $string, 'before' );
  255. # Maybe transform using the full parser
  256. if( $this->format === 'parse' ) {
  257. $string = $this->parseText( $string );
  258. $m = array();
  259. if( preg_match( '/^<p>(.*)\n?<\/p>\n?$/sU', $string, $m ) ) {
  260. $string = $m[1];
  261. }
  262. } elseif( $this->format === 'block-parse' ){
  263. $string = $this->parseText( $string );
  264. } elseif( $this->format === 'text' ){
  265. $string = $this->transformText( $string );
  266. } elseif( $this->format === 'escaped' ){
  267. $string = $this->transformText( $string );
  268. $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8', false );
  269. }
  270. # Raw parameter replacement
  271. $string = $this->replaceParameters( $string, 'after' );
  272. return $string;
  273. }
  274. /**
  275. * Magic method implementation of the above (for PHP >= 5.2.0), so we can do, eg:
  276. * $foo = Message::get($key);
  277. * $string = "<abbr>$foo</abbr>";
  278. * @return String
  279. */
  280. public function __toString() {
  281. return $this->toString();
  282. }
  283. /**
  284. * Fully parse the text from wikitext to HTML
  285. * @return String parsed HTML
  286. */
  287. public function parse() {
  288. $this->format = 'parse';
  289. return $this->toString();
  290. }
  291. /**
  292. * Returns the message text. {{-transformation is done.
  293. * @return String: Unescaped message text.
  294. */
  295. public function text() {
  296. $this->format = 'text';
  297. return $this->toString();
  298. }
  299. /**
  300. * Returns the message text as-is, only parameters are subsituted.
  301. * @return String: Unescaped untransformed message text.
  302. */
  303. public function plain() {
  304. $this->format = 'plain';
  305. return $this->toString();
  306. }
  307. /**
  308. * Returns the parsed message text which is always surrounded by a block element.
  309. * @return String: HTML
  310. */
  311. public function parseAsBlock() {
  312. $this->format = 'block-parse';
  313. return $this->toString();
  314. }
  315. /**
  316. * Returns the message text. {{-transformation is done and the result
  317. * is escaped excluding any raw parameters.
  318. * @return String: Escaped message text.
  319. */
  320. public function escaped() {
  321. $this->format = 'escaped';
  322. return $this->toString();
  323. }
  324. /**
  325. * Check whether a message key has been defined currently.
  326. * @return Bool: true if it is and false if not.
  327. */
  328. public function exists() {
  329. return $this->fetchMessage() !== false;
  330. }
  331. /**
  332. * Check whether a message does not exist, or is an empty string
  333. * @return Bool: true if is is and false if not
  334. * @todo FIXME: Merge with isDisabled()?
  335. */
  336. public function isBlank() {
  337. $message = $this->fetchMessage();
  338. return $message === false || $message === '';
  339. }
  340. /**
  341. * Check whether a message does not exist, is an empty string, or is "-"
  342. * @return Bool: true if is is and false if not
  343. */
  344. public function isDisabled() {
  345. $message = $this->fetchMessage();
  346. return $message === false || $message === '' || $message === '-';
  347. }
  348. /**
  349. * @param $value
  350. * @return array
  351. */
  352. public static function rawParam( $value ) {
  353. return array( 'raw' => $value );
  354. }
  355. /**
  356. * @param $value
  357. * @return array
  358. */
  359. public static function numParam( $value ) {
  360. return array( 'num' => $value );
  361. }
  362. /**
  363. * Substitutes any paramaters into the message text.
  364. * @param $message String: the message text
  365. * @param $type String: either before or after
  366. * @return String
  367. */
  368. protected function replaceParameters( $message, $type = 'before' ) {
  369. $replacementKeys = array();
  370. foreach( $this->parameters as $n => $param ) {
  371. list( $paramType, $value ) = $this->extractParam( $param );
  372. if ( $type === $paramType ) {
  373. $replacementKeys['$' . ($n + 1)] = $value;
  374. }
  375. }
  376. $message = strtr( $message, $replacementKeys );
  377. return $message;
  378. }
  379. /**
  380. * Extracts the parameter type and preprocessed the value if needed.
  381. * @param $param String|Array: Parameter as defined in this class.
  382. * @return Tuple(type, value)
  383. * @throws MWException
  384. */
  385. protected function extractParam( $param ) {
  386. if ( is_array( $param ) && isset( $param['raw'] ) ) {
  387. return array( 'after', $param['raw'] );
  388. } elseif ( is_array( $param ) && isset( $param['num'] ) ) {
  389. // Replace number params always in before step for now.
  390. // No support for combined raw and num params
  391. return array( 'before', $this->language->formatNum( $param['num'] ) );
  392. } elseif ( !is_array( $param ) ) {
  393. return array( 'before', $param );
  394. } else {
  395. throw new MWException( "Invalid message parameter" );
  396. }
  397. }
  398. /**
  399. * Wrapper for what ever method we use to parse wikitext.
  400. * @param $string String: Wikitext message contents
  401. * @return string Wikitext parsed into HTML
  402. */
  403. protected function parseText( $string ) {
  404. return MessageCache::singleton()->parse( $string, $this->title, /*linestart*/true, $this->interface, $this->language )->getText();
  405. }
  406. /**
  407. * Wrapper for what ever method we use to {{-transform wikitext.
  408. * @param $string String: Wikitext message contents
  409. * @return string Wikitext with {{-constructs replaced with their values.
  410. */
  411. protected function transformText( $string ) {
  412. return MessageCache::singleton()->transform( $string, $this->interface, $this->language, $this->title );
  413. }
  414. /**
  415. * Returns the textual value for the message.
  416. * @return Message contents or placeholder
  417. */
  418. protected function getMessageText() {
  419. $message = $this->fetchMessage();
  420. if ( $message === false ) {
  421. return '&lt;' . htmlspecialchars( is_array($this->key) ? $this->key[0] : $this->key ) . '&gt;';
  422. } else {
  423. return $message;
  424. }
  425. }
  426. /**
  427. * Wrapper for what ever method we use to get message contents
  428. *
  429. * @return string
  430. */
  431. protected function fetchMessage() {
  432. if ( !isset( $this->message ) ) {
  433. $cache = MessageCache::singleton();
  434. if ( is_array($this->key) ) {
  435. foreach ( $this->key as $key ) {
  436. $message = $cache->get( $key, $this->useDatabase, $this->language );
  437. if ( $message !== false && $message !== '' ) {
  438. break;
  439. }
  440. }
  441. $this->message = $message;
  442. } else {
  443. $this->message = $cache->get( $this->key, $this->useDatabase, $this->language );
  444. }
  445. }
  446. return $this->message;
  447. }
  448. }