Merge "Added result properties to action=paraminfo"
[lhc/web/wiklou.git] / maintenance / parse.php
1 <?php
2 /**
3 * CLI script to easily parse some wikitext.
4 * Wikitext can be given by stdin or using a file. The wikitext will be parsed
5 * using 'CLIParser' as a title. This can be overriden with --title option.
6 *
7 * Example1:
8 * @code
9 * $ php parse.php --title foo
10 * ''[[foo]]''^D
11 * <p><i><strong class="selflink">foo</strong></i>
12 * </p>
13 * @endcode
14 *
15 * Example2:
16 * @code
17 * $ echo "'''bold'''" > /tmp/foo.txt
18 * $ php parse.php /tmp/foo.txt
19 * <p><b>bold</b>
20 * </p>$
21 * @endcode
22 *
23 * Example3:
24 * @code
25 * $ cat /tmp/foo | php parse.php
26 * <p><b>bold</b>
27 * </p>$
28 * @endcode
29 *
30 * @ingroup Maintenance
31 * @author Antoine Musso <hashar at free dot fr>
32 * @license GNU General Public License 2.0 or later
33 */
34 require_once( dirname(__FILE__) . '/Maintenance.php' );
35
36 class CLIParser extends Maintenance {
37 protected $parser;
38
39 public function __construct() {
40 parent::__construct();
41 $this->mDescription = "Parse a given wikitext";
42 $this->addOption( 'title', 'Title name for the given wikitext (Default: \'CLIParser\')', false, true );
43 $this->addArg( 'file', 'File containing wikitext (Default: stdin)', false );
44 }
45
46 public function execute() {
47 $this->initParser();
48 print $this->render( $this->WikiText() );
49 }
50
51 /**
52 * @param string $wikitext Wikitext to get rendered
53 * @return string HTML Rendering
54 */
55 public function render( $wikitext ) {
56 return $this->parse( $wikitext )->getText();
57 }
58
59 /**
60 * Get wikitext from a the file passed as argument or STDIN
61 * @return string Wikitext
62 */
63 protected function Wikitext() {
64
65 $php_stdin = 'php://stdin';
66 $input_file = $this->getArg( 0, $php_stdin );
67
68 if( $input_file === $php_stdin ) {
69 $this->error( basename(__FILE__) .": warning: reading wikitext from STDIN\n" );
70 }
71
72 return file_get_contents( $input_file );
73 }
74
75 protected function initParser() {
76 global $wgParserConf;
77 $parserClass = $wgParserConf['class'];
78 $this->parser = new $parserClass();
79 }
80
81 /**
82 * Title object to use for CLI parsing.
83 * Default title is 'CLIParser', it can be overriden with the option
84 * --title <Your:Title>
85 *
86 * @return Title object
87 */
88 protected function getTitle( ) {
89 $title =
90 $this->getOption( 'title' )
91 ? $this->getOption( 'title' )
92 : 'CLIParser' ;
93 return Title::newFromText( $title );
94 }
95
96 /**
97 * @param string $wikitext Wikitext to parse
98 * @return ParserOutput
99 */
100 protected function parse( $wikitext ) {
101 return $this->parser->parse(
102 $wikitext
103 , $this->getTitle()
104 , new ParserOptions()
105 );
106 }
107 }
108
109 $maintClass = "CLIParser";
110 require_once( RUN_MAINTENANCE_IF_MAIN );