Completed
Branch master (939199)
by
unknown
39:35
created

includes/specials/SpecialExpandTemplates.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * Implements Special:ExpandTemplates
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 2 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License along
16
 * with this program; if not, write to the Free Software Foundation, Inc.,
17
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18
 * http://www.gnu.org/copyleft/gpl.html
19
 *
20
 * @file
21
 * @ingroup SpecialPage
22
 */
23
24
/**
25
 * A special page that expands submitted templates, parser functions,
26
 * and variables, allowing easier debugging of these.
27
 *
28
 * @ingroup SpecialPage
29
 */
30
class SpecialExpandTemplates extends SpecialPage {
31
32
	/** @var bool Whether or not to show the XML parse tree */
33
	protected $generateXML;
34
35
	/** @var bool Whether or not to show the raw HTML code */
36
	protected $generateRawHtml;
37
38
	/** @var bool Whether or not to remove comments in the expanded wikitext */
39
	protected $removeComments;
40
41
	/** @var bool Whether or not to remove <nowiki> tags in the expanded wikitext */
42
	protected $removeNowiki;
43
44
	/** @var int Maximum size in bytes to include. 50MB allows fixing those huge pages */
45
	const MAX_INCLUDE_SIZE = 50000000;
46
47
	function __construct() {
48
		parent::__construct( 'ExpandTemplates' );
49
	}
50
51
	/**
52
	 * Show the special page
53
	 * @param string|null $subpage
54
	 */
55
	function execute( $subpage ) {
56
		global $wgParser;
57
58
		$this->setHeaders();
59
60
		$request = $this->getRequest();
61
		$titleStr = $request->getText( 'wpContextTitle' );
62
		$title = Title::newFromText( $titleStr );
63
64
		if ( !$title ) {
65
			$title = $this->getPageTitle();
66
		}
67
		$input = $request->getText( 'wpInput' );
68
		$this->generateXML = $request->getBool( 'wpGenerateXml' );
69
		$this->generateRawHtml = $request->getBool( 'wpGenerateRawHtml' );
70
71
		if ( strlen( $input ) ) {
72
			$this->removeComments = $request->getBool( 'wpRemoveComments', false );
73
			$this->removeNowiki = $request->getBool( 'wpRemoveNowiki', false );
74
			$options = ParserOptions::newFromContext( $this->getContext() );
75
			$options->setRemoveComments( $this->removeComments );
76
			$options->setTidy( true );
77
			$options->setMaxIncludeSize( self::MAX_INCLUDE_SIZE );
78
79
			if ( $this->generateXML ) {
80
				$wgParser->startExternalParse( $title, $options, Parser::OT_PREPROCESS );
81
				$dom = $wgParser->preprocessToDom( $input );
82
83
				if ( method_exists( $dom, 'saveXML' ) ) {
84
					$xml = $dom->saveXML();
85
				} else {
86
					$xml = $dom->__toString();
87
				}
88
			}
89
90
			$output = $wgParser->preprocess( $input, $title, $options );
91
		} else {
92
			$this->removeComments = $request->getBool( 'wpRemoveComments', true );
93
			$this->removeNowiki = $request->getBool( 'wpRemoveNowiki', false );
94
			$output = false;
95
		}
96
97
		$out = $this->getOutput();
98
99
		$this->makeForm( $titleStr, $input );
100
101
		if ( $output !== false ) {
102
			if ( $this->generateXML && strlen( $output ) > 0 ) {
103
				$out->addHTML( $this->makeOutput( $xml, 'expand_templates_xml_output' ) );
104
			}
105
106
			$tmp = $this->makeOutput( $output );
107
108
			if ( $this->removeNowiki ) {
109
				$tmp = preg_replace(
110
					[ '_&lt;nowiki&gt;_', '_&lt;/nowiki&gt;_', '_&lt;nowiki */&gt;_' ],
111
					'',
112
					$tmp
113
				);
114
			}
115
116
			$config = $this->getConfig();
117
			if ( $config->get( 'UseTidy' ) && $options->getTidy() ) {
0 ignored issues
show
The variable $options does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
118
				$tmp = MWTidy::tidy( $tmp );
119
			}
120
121
			$out->addHTML( $tmp );
122
123
			$pout = $this->generateHtml( $title, $output );
124
			$rawhtml = $pout->getText();
125
			if ( $this->generateRawHtml && strlen( $rawhtml ) > 0 ) {
126
				$out->addHTML( $this->makeOutput( $rawhtml, 'expand_templates_html_output' ) );
127
			}
128
129
			$this->showHtmlPreview( $title, $pout, $out );
130
		}
131
	}
132
133
	/**
134
	 * Callback for the HTMLForm used in self::makeForm.
135
	 * Checks, if the input was given, and if not, returns a fatal Status
136
	 * object with an error message.
137
	 *
138
	 * @param array $values The values submitted to the HTMLForm
139
	 * @return Status
140
	 */
141
	public function onSubmitInput( array $values ) {
142
		$status = Status::newGood();
143
		if ( !strlen( $values['input'] ) ) {
144
			$status = Status::newFatal( 'expand_templates_input_missing' );
145
		}
146
		return $status;
147
	}
148
149
	/**
150
	 * Generate a form allowing users to enter information
151
	 *
152
	 * @param string $title Value for context title field
153
	 * @param string $input Value for input textbox
154
	 * @return string
155
	 */
156
	private function makeForm( $title, $input ) {
157
		$fields = [
158
			'contexttitle' => [
159
				'type' => 'text',
160
				'label' => $this->msg( 'expand_templates_title' )->plain(),
161
				'name' => 'wpContextTitle',
162
				'id' => 'contexttitle',
163
				'size' => 60,
164
				'default' => $title,
165
				'autofocus' => true,
166
				'cssclass' => 'mw-ui-input-inline',
167
			],
168
			'input' => [
169
				'type' => 'textarea',
170
				'name' => 'wpInput',
171
				'label' => $this->msg( 'expand_templates_input' )->text(),
172
				'rows' => 10,
173
				'default' => $input,
174
				'id' => 'input',
175
			],
176
			'removecomments' => [
177
				'type' => 'check',
178
				'label' => $this->msg( 'expand_templates_remove_comments' )->text(),
179
				'name' => 'wpRemoveComments',
180
				'id' => 'removecomments',
181
				'default' => $this->removeComments,
182
			],
183
			'removenowiki' => [
184
				'type' => 'check',
185
				'label' => $this->msg( 'expand_templates_remove_nowiki' )->text(),
186
				'name' => 'wpRemoveNowiki',
187
				'id' => 'removenowiki',
188
				'default' => $this->removeNowiki,
189
			],
190
			'generate_xml' => [
191
				'type' => 'check',
192
				'label' => $this->msg( 'expand_templates_generate_xml' )->text(),
193
				'name' => 'wpGenerateXml',
194
				'id' => 'generate_xml',
195
				'default' => $this->generateXML,
196
			],
197
			'generate_rawhtml' => [
198
				'type' => 'check',
199
				'label' => $this->msg( 'expand_templates_generate_rawhtml' )->text(),
200
				'name' => 'wpGenerateRawHtml',
201
				'id' => 'generate_rawhtml',
202
				'default' => $this->generateRawHtml,
203
			],
204
		];
205
206
		$form = HTMLForm::factory( 'ooui', $fields, $this->getContext() );
207
		$form
208
			->setSubmitTextMsg( 'expand_templates_ok' )
209
			->setWrapperLegendMsg( 'expandtemplates' )
210
			->setHeaderText( $this->msg( 'expand_templates_intro' )->parse() )
211
			->setSubmitCallback( [ $this, 'onSubmitInput' ] )
212
			->showAlways();
213
	}
214
215
	/**
216
	 * Generate a nice little box with a heading for output
217
	 *
218
	 * @param string $output Wiki text output
219
	 * @param string $heading
220
	 * @return string
221
	 */
222
	private function makeOutput( $output, $heading = 'expand_templates_output' ) {
223
		$out = "<h2>" . $this->msg( $heading )->escaped() . "</h2>\n";
224
		$out .= Xml::textarea(
225
			'output',
226
			$output,
227
			10,
228
			10,
229
			[ 'id' => 'output', 'readonly' => 'readonly' ]
230
		);
231
232
		return $out;
233
	}
234
235
	/**
236
	 * Renders the supplied wikitext as html
237
	 *
238
	 * @param Title $title
239
	 * @param string $text
240
	 * @return ParserOutput
241
	 */
242
	private function generateHtml( Title $title, $text ) {
243
		global $wgParser;
244
245
		$popts = ParserOptions::newFromContext( $this->getContext() );
246
		$popts->setTargetLanguage( $title->getPageLanguage() );
247
		return $wgParser->parse( $text, $title, $popts );
248
	}
249
250
	/**
251
	 * Wraps the provided html code in a div and outputs it to the page
252
	 *
253
	 * @param Title $title
254
	 * @param ParserOutput $pout
255
	 * @param OutputPage $out
256
	 */
257
	private function showHtmlPreview( Title $title, ParserOutput $pout, OutputPage $out ) {
258
		$lang = $title->getPageViewLanguage();
259
		$out->addHTML( "<h2>" . $this->msg( 'expand_templates_preview' )->escaped() . "</h2>\n" );
260
261
		if ( $this->getConfig()->get( 'RawHtml' ) ) {
262
			$request = $this->getRequest();
263
			$user = $this->getUser();
264
265
			// To prevent cross-site scripting attacks, don't show the preview if raw HTML is
266
			// allowed and a valid edit token is not provided (bug 71111). However, MediaWiki
267
			// does not currently provide logged-out users with CSRF protection; in that case,
268
			// do not show the preview unless anonymous editing is allowed.
269
			if ( $user->isAnon() && !$user->isAllowed( 'edit' ) ) {
270
				$error = [ 'expand_templates_preview_fail_html_anon' ];
271
			} elseif ( !$user->matchEditToken( $request->getVal( 'wpEditToken' ), '', $request ) ) {
272
				$error = [ 'expand_templates_preview_fail_html' ];
273
			} else {
274
				$error = false;
275
			}
276
277
			if ( $error ) {
278
				$out->wrapWikiMsg( "<div class='previewnote'>\n$1\n</div>", $error );
279
				return;
280
			}
281
		}
282
283
		$out->addHTML( Html::openElement( 'div', [
284
			'class' => 'mw-content-' . $lang->getDir(),
285
			'dir' => $lang->getDir(),
286
			'lang' => $lang->getHtmlCode(),
287
		] ) );
288
		$out->addParserOutputContent( $pout );
289
		$out->addHTML( Html::closeElement( 'div' ) );
290
		$out->setCategoryLinks( $pout->getCategories() );
291
	}
292
293
	protected function getGroupName() {
294
		return 'wiki';
295
	}
296
}
297