Merge "Don't check namespace in SpecialWantedtemplates"
[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 = array(
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, array( '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 $out->addModules( 'mediawiki.special.javaScriptTest' );
110
111 $method = 'view' . ucfirst( $framework );
112 $this->$method();
113 $out->setPageTitle( $this->msg(
114 'javascripttest-title',
115 // Messages: javascripttest-qunit-name
116 $this->msg( "javascripttest-$framework-name" )->plain()
117 ) );
118 }
119
120 /**
121 * Get a list of frameworks (including introduction paragraph and links
122 * to the framework run pages)
123 *
124 * @return string HTML
125 */
126 private function getFrameworkListHtml() {
127 $list = '<ul>';
128 foreach ( self::$frameworks as $framework ) {
129 $list .= Html::rawElement(
130 'li',
131 array(),
132 Linker::link(
133 $this->getPageTitle( $framework ),
134 // Message: javascripttest-qunit-name
135 $this->msg( "javascripttest-$framework-name" )->escaped()
136 )
137 );
138 }
139 $list .= '</ul>';
140
141 return $this->msg( 'javascripttest-pagetext-frameworks' )->rawParams( $list )
142 ->parseAsBlock();
143 }
144
145 /**
146 * Get summary text wrapped in a container
147 *
148 * @return string HTML
149 */
150 private function getSummaryHtml() {
151 $summary = $this->msg( 'javascripttest-qunit-intro' )
152 ->params( 'https://www.mediawiki.org/wiki/Manual:JavaScript_unit_testing' )
153 ->parseAsBlock();
154 return "<div id=\"mw-javascripttest-summary\">$summary</div>";
155 }
156
157 /**
158 * Run the test suite on the Special page.
159 *
160 * Rendered by OutputPage and Skin.
161 */
162 private function viewQUnit() {
163 $out = $this->getOutput();
164
165 $modules = $out->getResourceLoader()->getTestModuleNames( 'qunit' );
166
167 $baseHtml = <<<HTML
168 <div class="mw-content-ltr">
169 <div id="qunit"></div>
170 </div>
171 HTML;
172
173 $out->addHtml( $this->getSummaryHtml() . $baseHtml );
174
175 // The testrunner configures QUnit and essentially depends on it. However, test suites
176 // are reusable in environments that preload QUnit (or a compatibility interface to
177 // another framework). Therefore we have to load it ourselves.
178 $out->addHtml( ResourceLoader::makeInlineScript(
179 Xml::encodeJsCall( 'mw.loader.using', array(
180 array( 'jquery.qunit', 'jquery.qunit.completenessTest' ),
181 new XmlJsCode(
182 'function () {' . Xml::encodeJsCall( 'mw.loader.load', array( $modules ) ) . '}'
183 )
184 ) )
185 ) );
186 }
187
188 /**
189 * Generate self-sufficient JavaScript payload to run the tests elsewhere.
190 *
191 * Includes startup module to request modules from ResourceLoader.
192 *
193 * Note: This modifies the registry to replace 'jquery.qunit' with an
194 * empty module to allow external environment to preload QUnit with any
195 * neccecary framework adapters (e.g. Karma). Loading it again would
196 * re-define QUnit and dereference event handlers from Karma.
197 */
198 private function exportQUnit() {
199 $out = $this->getOutput();
200 $out->disable();
201
202 $rl = $out->getResourceLoader();
203
204 $query = array(
205 'lang' => $this->getLanguage()->getCode(),
206 'skin' => $this->getSkin()->getSkinName(),
207 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
208 'target' => 'test',
209 );
210 $embedContext = new ResourceLoaderContext( $rl, new FauxRequest( $query ) );
211 $query['only'] = 'scripts';
212 $startupContext = new ResourceLoaderContext( $rl, new FauxRequest( $query ) );
213
214 $query['raw'] = true;
215
216 $modules = $rl->getTestModuleNames( 'qunit' );
217
218 // Disable autostart because we load modules asynchronously. By default, QUnit would start
219 // at domready when there are no tests loaded and also fire 'QUnit.done' which then instructs
220 // Karma to end the run before the tests even started.
221 $qunitConfig = 'QUnit.config.autostart = false;'
222 . 'if (window.__karma__) {'
223 // karma-qunit's use of autostart=false and QUnit.start conflicts with ours.
224 // Hack around this by replacing 'karma.loaded' with a no-op and call it ourselves later.
225 // See <https://github.com/karma-runner/karma-qunit/issues/27>.
226 . 'window.__karma__.loaded = function () {};'
227 . '}';
228
229 // The below is essentially a pure-javascript version of OutputPage::getHeadScripts.
230 $startup = $rl->makeModuleResponse( $startupContext, array(
231 'startup' => $rl->getModule( 'startup' ),
232 ) );
233 // Embed page-specific mw.config variables.
234 // The current Special page shouldn't be relevant to tests, but various modules (which
235 // are loaded before the test suites), reference mw.config while initialising.
236 $code = ResourceLoader::makeConfigSetScript( $out->getJSVars() );
237 // Embed private modules as they're not allowed to be loaded dynamically
238 $code .= $rl->makeModuleResponse( $embedContext, array(
239 'user.options' => $rl->getModule( 'user.options' ),
240 'user.tokens' => $rl->getModule( 'user.tokens' ),
241 ) );
242 // Catch exceptions (such as "dependency missing" or "unknown module") so that we
243 // always start QUnit. Re-throw so that they are caught and reported as global exceptions
244 // by QUnit and Karma.
245 $code .= '(function () {'
246 . 'var start = window.__karma__ ? window.__karma__.start : QUnit.start;'
247 . 'try {'
248 . 'mw.loader.using( ' . Xml::encodeJsVar( $modules ) . ' ).always( start );'
249 . '} catch ( e ) { start(); throw e; }'
250 . '}());';
251
252 header( 'Content-Type: text/javascript; charset=utf-8' );
253 header( 'Cache-Control: private, no-cache, must-revalidate' );
254 header( 'Pragma: no-cache' );
255 echo $qunitConfig;
256 echo $startup;
257 // The following has to be deferred via RLQ because the startup module is asynchronous.
258 echo ResourceLoader::makeLoaderConditionalScript( $code );
259 }
260
261 private function plainQUnit() {
262 $out = $this->getOutput();
263 $out->disable();
264
265 $styles = $out->makeResourceLoaderLink( 'jquery.qunit',
266 ResourceLoaderModule::TYPE_STYLES
267 );
268
269 // Use 'raw' because QUnit loads before ResourceLoader initialises (omit mw.loader.state call)
270 // Use 'test' to ensure OutputPage doesn't use the "async" attribute because QUnit must
271 // load before qunit/export.
272 $scripts = $out->makeResourceLoaderLink( 'jquery.qunit',
273 ResourceLoaderModule::TYPE_SCRIPTS,
274 array( 'raw' => true, 'sync' => true )
275 );
276
277 $head = implode( "\n", array_merge( $styles['html'], $scripts['html'] ) );
278 $summary = $this->getSummaryHtml();
279 $html = <<<HTML
280 <!DOCTYPE html>
281 <title>QUnit</title>
282 $head
283 $summary
284 <div id="qunit"></div>
285 HTML;
286
287 $url = $this->getPageTitle( 'qunit/export' )->getFullURL( array(
288 'debug' => ResourceLoader::inDebugMode() ? 'true' : 'false',
289 ) );
290 $html .= "\n" . Html::linkedScript( $url );
291
292 header( 'Content-Type: text/html; charset=utf-8' );
293 echo $html;
294 }
295
296 /**
297 * Return an array of subpages that this special page will accept.
298 *
299 * @return string[] subpages
300 */
301 public function getSubpagesForPrefixSearch() {
302 return self::$frameworks;
303 }
304
305 protected function getGroupName() {
306 return 'other';
307 }
308 }