Merge "Fix accidential variable overriding in manualWordsTable"
[lhc/web/wiklou.git] / includes / specials / SpecialJavaScriptTest.php
1 <?php
2 /**
3 * Implements Special:JavaScriptTest
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 * @ingroup SpecialPage
26 */
27 class SpecialJavaScriptTest extends SpecialPage {
28 /**
29 * @var array Supported frameworks.
30 */
31 private static $frameworks = [
32 'qunit',
33 ];
34
35 public function __construct() {
36 parent::__construct( 'JavaScriptTest' );
37 }
38
39 public function execute( $par ) {
40 $out = $this->getOutput();
41
42 $this->setHeaders();
43 $out->disallowUserJs();
44
45 if ( $par === null ) {
46 // No framework specified
47 // If only one framework is configured, redirect to it. Otherwise display a list.
48 if ( count( self::$frameworks ) === 1 ) {
49 $out->redirect( $this->getPageTitle( self::$frameworks[0] . '/plain' )->getLocalURL() );
50 return;
51 }
52 $out->setStatusCode( 404 );
53 $out->setPageTitle( $this->msg( 'javascripttest' ) );
54 $out->addHTML(
55 $this->msg( 'javascripttest-pagetext-noframework' )->parseAsBlock()
56 . $this->getFrameworkListHtml()
57 );
58 return;
59 }
60
61 // Determine framework and mode
62 $pars = explode( '/', $par, 2 );
63
64 $framework = $pars[0];
65 if ( !in_array( $framework, self::$frameworks ) ) {
66 // Framework not found
67 $out->setStatusCode( 404 );
68 $out->addHTML(
69 '<div class="error">'
70 . $this->msg( 'javascripttest-pagetext-unknownframework' )
71 ->plaintextParams( $par )->parseAsBlock()
72 . '</div>'
73 . $this->getFrameworkListHtml()
74 );
75 return;
76 }
77
78 // This special page is disabled by default ($wgEnableJavaScriptTest), and contains
79 // no sensitive data. In order to allow TestSwarm to embed it into a test client window,
80 // we need to allow iframing of this page.
81 $out->allowClickjacking();
82 if ( count( self::$frameworks ) !== 1 ) {
83 // If there's only one framework, don't set the subtitle since it
84 // is going to redirect back to this page
85 $out->setSubtitle(
86 $this->msg( 'javascripttest-backlink' )
87 ->rawParams( Linker::linkKnown( $this->getPageTitle() ) )
88 );
89 }
90
91 // Custom actions
92 if ( isset( $pars[1] ) ) {
93 $action = $pars[1];
94 if ( !in_array( $action, [ 'export', 'plain' ] ) ) {
95 $out->setStatusCode( 404 );
96 $out->addHTML(
97 '<div class="error">'
98 . $this->msg( 'javascripttest-pagetext-unknownaction' )
99 ->plaintextParams( $action )->parseAsBlock()
100 . '</div>'
101 );
102 return;
103 }
104 $method = $action . ucfirst( $framework );
105 $this->$method();
106 return;
107 }
108
109 $method = 'view' . ucfirst( $framework );
110 $this->$method();
111 $out->setPageTitle( $this->msg(
112 'javascripttest-title',
113 // Messages: javascripttest-qunit-name
114 $this->msg( "javascripttest-$framework-name" )->plain()
115 ) );
116 }
117
118 /**
119 * Get a list of frameworks (including introduction paragraph and links
120 * to the framework run pages)
121 *
122 * @return string HTML
123 */
124 private function getFrameworkListHtml() {
125 $list = '<ul>';
126 foreach ( self::$frameworks as $framework ) {
127 $list .= Html::rawElement(
128 'li',
129 [],
130 Linker::link(
131 $this->getPageTitle( $framework ),
132 // Message: javascripttest-qunit-name
133 $this->msg( "javascripttest-$framework-name" )->escaped()
134 )
135 );
136 }
137 $list .= '</ul>';
138
139 return $this->msg( 'javascripttest-pagetext-frameworks' )->rawParams( $list )
140 ->parseAsBlock();
141 }
142
143 /**
144 * Get summary text wrapped in a container
145 *
146 * @return string HTML
147 */
148 private function getSummaryHtml() {
149 $summary = $this->msg( 'javascripttest-qunit-intro' )
150 ->params( 'https://www.mediawiki.org/wiki/Manual:JavaScript_unit_testing' )
151 ->parseAsBlock();
152 return "<div id=\"mw-javascripttest-summary\">$summary</div>";
153 }
154
155 /**
156 * Run the test suite on the Special page.
157 *
158 * Rendered by OutputPage and Skin.
159 */
160 private function viewQUnit() {
161 $out = $this->getOutput();
162
163 $modules = $out->getResourceLoader()->getTestModuleNames( 'qunit' );
164
165 $baseHtml = <<<HTML
166 <div class="mw-content-ltr">
167 <div id="qunit"></div>
168 </div>
169 HTML;
170
171 $out->addHTML( $this->getSummaryHtml() . $baseHtml );
172
173 // The testrunner configures QUnit and essentially depends on it. However, test suites
174 // are reusable in environments that preload QUnit (or a compatibility interface to
175 // another framework). Therefore we have to load it ourselves.
176 $out->addHTML( ResourceLoader::makeInlineScript(
177 Xml::encodeJsCall( 'mw.loader.using', [
178 [ 'jquery.qunit', 'jquery.qunit.completenessTest' ],
179 new XmlJsCode(
180 'function () {' . Xml::encodeJsCall( 'mw.loader.load', [ $modules ] ) . '}'
181 )
182 ] )
183 ) );
184 }
185
186 /**
187 * Generate self-sufficient JavaScript payload to run the tests elsewhere.
188 *
189 * Includes startup module to request modules from ResourceLoader.
190 *
191 * Note: This modifies the registry to replace 'jquery.qunit' with an
192 * empty module to allow external environment to preload QUnit with any
193 * neccecary framework adapters (e.g. Karma). Loading it again would
194 * re-define QUnit and dereference event handlers from Karma.
195 */
196 private function exportQUnit() {
197 $out = $this->getOutput();
198 $out->disable();
199
200 $rl = $out->getResourceLoader();
201
202 $query = [
203 'lang' => $this->getLanguage()->getCode(),
204 'skin' => $this->getSkin()->getSkinName(),
205 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
206 'target' => 'test',
207 ];
208 $embedContext = new ResourceLoaderContext( $rl, new FauxRequest( $query ) );
209 $query['only'] = 'scripts';
210 $startupContext = new ResourceLoaderContext( $rl, new FauxRequest( $query ) );
211
212 $query['raw'] = true;
213
214 $modules = $rl->getTestModuleNames( 'qunit' );
215
216 // Disable autostart because we load modules asynchronously. By default, QUnit would start
217 // at domready when there are no tests loaded and also fire 'QUnit.done' which then instructs
218 // Karma to end the run before the tests even started.
219 $qunitConfig = 'QUnit.config.autostart = false;'
220 . 'if (window.__karma__) {'
221 // karma-qunit's use of autostart=false and QUnit.start conflicts with ours.
222 // Hack around this by replacing 'karma.loaded' with a no-op and call it ourselves later.
223 // See <https://github.com/karma-runner/karma-qunit/issues/27>.
224 . 'window.__karma__.loaded = function () {};'
225 . '}';
226
227 // The below is essentially a pure-javascript version of OutputPage::getHeadScripts.
228 $startup = $rl->makeModuleResponse( $startupContext, [
229 'startup' => $rl->getModule( 'startup' ),
230 ] );
231 // Embed page-specific mw.config variables.
232 // The current Special page shouldn't be relevant to tests, but various modules (which
233 // are loaded before the test suites), reference mw.config while initialising.
234 $code = ResourceLoader::makeConfigSetScript( $out->getJSVars() );
235 // Embed private modules as they're not allowed to be loaded dynamically
236 $code .= $rl->makeModuleResponse( $embedContext, [
237 'user.options' => $rl->getModule( 'user.options' ),
238 'user.tokens' => $rl->getModule( 'user.tokens' ),
239 ] );
240 // Catch exceptions (such as "dependency missing" or "unknown module") so that we
241 // always start QUnit. Re-throw so that they are caught and reported as global exceptions
242 // by QUnit and Karma.
243 $code .= '(function () {'
244 . 'var start = window.__karma__ ? window.__karma__.start : QUnit.start;'
245 . 'try {'
246 . 'mw.loader.using( ' . Xml::encodeJsVar( $modules ) . ' ).always( start );'
247 . '} catch ( e ) { start(); throw e; }'
248 . '}());';
249
250 header( 'Content-Type: text/javascript; charset=utf-8' );
251 header( 'Cache-Control: private, no-cache, must-revalidate' );
252 header( 'Pragma: no-cache' );
253 echo $qunitConfig;
254 echo $startup;
255 // The following has to be deferred via RLQ because the startup module is asynchronous.
256 echo ResourceLoader::makeLoaderConditionalScript( $code );
257 }
258
259 private function plainQUnit() {
260 $out = $this->getOutput();
261 $out->disable();
262
263 $styles = $out->makeResourceLoaderLink( 'jquery.qunit',
264 ResourceLoaderModule::TYPE_STYLES
265 );
266
267 // Use 'raw' because QUnit loads before ResourceLoader initialises (omit mw.loader.state call)
268 // Use 'test' to ensure OutputPage doesn't use the "async" attribute because QUnit must
269 // load before qunit/export.
270 $scripts = $out->makeResourceLoaderLink( 'jquery.qunit',
271 ResourceLoaderModule::TYPE_SCRIPTS,
272 [ 'raw' => true, 'sync' => true ]
273 );
274
275 $head = implode( "\n", array_merge( $styles['html'], $scripts['html'] ) );
276 $summary = $this->getSummaryHtml();
277 $html = <<<HTML
278 <!DOCTYPE html>
279 <title>QUnit</title>
280 $head
281 $summary
282 <div id="qunit"></div>
283 HTML;
284
285 $url = $this->getPageTitle( 'qunit/export' )->getFullURL( [
286 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
287 ] );
288 $html .= "\n" . Html::linkedScript( $url );
289
290 header( 'Content-Type: text/html; charset=utf-8' );
291 echo $html;
292 }
293
294 /**
295 * Return an array of subpages that this special page will accept.
296 *
297 * @return string[] subpages
298 */
299 public function getSubpagesForPrefixSearch() {
300 return self::$frameworks;
301 }
302
303 protected function getGroupName() {
304 return 'other';
305 }
306 }