Debian Codegraph @

extensions/TemplateData/modules/ext.templateDataGenerator.data/SourceHandler.js

raw symbols SCIP
1 const Model = require( './Model.js' );
2
3 /**
4 * TemplateData Source Handler
5 *
6 * Loads and validates the templatedata and template parameters
7 * whether in the page itself or from its parent.
8 *
9 * @class
10 * @extends OO.EventEmitter
11 *
12 * @constructor
13 * @param {Object} [config]
14 * @param {string} [config.fullPageName=""] The full name of the current page
15 * @param {string} [config.parentPage=""] The name of the parent page
16 * @param {string} [config.isPageSubLevel=false] The page is sub-level of another template
17 */
18 function SourceHandler( config ) {
19 config = config || {};
20
21 // Mixin constructors
22 OO.EventEmitter.call( this );
23
24 this.apiCache = {};
25 this.templateSourceCodePromise = null;
26 this.templateSourceCodeParams = [];
27
28 // Config
29 this.setParentPage( config.parentPage );
30 this.setPageSubLevel( config.isPageSubLevel );
31 this.setFullPageName( config.fullPageName );
32 }
33
34 /* Inheritance */
35
36 OO.mixinClass( SourceHandler, OO.EventEmitter );
37
38 /**
39 * Get information from the MediaWiki API
40 *
41 * @param {string} page Page name
42 * @param {boolean} [getTemplateData] Fetch the templatedata in the page.
43 * @return {jQuery.Promise} API promise
44 */
45 SourceHandler.prototype.getApi = function ( page, getTemplateData ) {
46 const type = getTemplateData ? 'templatedata' : 'query',
47 api = new mw.Api(),
48 baseConfig = {
49 action: type,
50 titles: page,
51 redirects: getTemplateData ? 1 : 0
52 };
53
54 let config;
55 if ( type === 'query' ) {
56 config = Object.assign( baseConfig, {
57 prop: 'revisions',
58 rvprop: 'content',
59 indexpageids: '1'
60 } );
61 }
62
63 // Cache
64 if ( !this.apiCache[ page ] || !this.apiCache[ page ][ type ] ) {
65 this.apiCache[ page ] = this.apiCache[ page ] || {};
66 this.apiCache[ page ][ type ] = api.get( config );
67 }
68 return this.apiCache[ page ][ type ];
69 };
70
71 /**
72 * Go over the current wikitext and build a new model.
73 *
74 * @param {string} [wikitext] Source of the template.
75 * @return {jQuery.Promise} Promise resolving into a new Model
76 * or is rejected if the model was impossible to create.
77 */
78 SourceHandler.prototype.buildModel = function ( wikitext ) {
79 const templateDataString = this.findModelInString( wikitext );
80
81 let tdObject = null;
82 if ( templateDataString !== null ) {
83 try {
84 tdObject = JSON.parse( templateDataString );
85 } catch ( err ) {
86 // The json object is invalid. There's no need to continue.
87 return $.Deferred().reject();
88 }
89 }
90
91 // Get parameters from source code
92 // Mostly used for the import option
93 return this.getParametersFromTemplateSource( wikitext )
94 // This is always successful by definition
95 .then( ( templateSourceCodeParams ) => Model.static.newFromObject(
96 tdObject,
97 templateSourceCodeParams
98 ) );
99 };
100
101 /**
102 * Retrieve parameters from the template code from source in this order:
103 *
104 * 1. Check if there's a template in the given 'wikitext' parameter. If not,
105 * 2. Check if there's a template in the current page. If not,
106 * 3. Check if the page is a subpage and go up a level to check for template code. If none found,
107 * 4. Repeat until we are in the root of the template
108 * 5. Save the name of the page where the template is taken from
109 *
110 * Cache the templateCodePromise so we don't have to do this all over again on each
111 * template code request.
112 *
113 * @param {string} [wikitext] Optional. Source of the template.
114 * @return {jQuery.Promise} Promise resolving into template parameter array
115 */
116 SourceHandler.prototype.getParametersFromTemplateSource = function ( wikitext ) {
117 let params = [];
118 if ( !this.templateSourceCodePromise ) {
119 // Check given page text first
120 if ( wikitext ) {
121 params = this.extractParametersFromTemplateCode( wikitext );
122 }
123
124 if ( params.length > 0 ) {
125 // There are parameters found; Resolve.
126 this.templateSourceCodePromise = $.Deferred().resolve( params );
127 } else if ( this.isPageSubLevel() && this.getParentPage() ) {
128 // Get the content of the parent
129 this.templateSourceCodePromise = this.getApi( this.getParentPage() ).then(
130 ( resp ) => {
131 let pageContent = '';
132
133 // Verify that we have a sane response from the API.
134 // This is particularly important for unit tests, since the
135 // requested page from the API is the Qunit module and has no content
136 if (
137 resp.query.pages[ resp.query.pageids[ 0 ] ].revisions &&
138 resp.query.pages[ resp.query.pageids[ 0 ] ].revisions[ 0 ]
139 ) {
140 pageContent = resp.query.pages[ resp.query.pageids[ 0 ] ].revisions[ 0 ][ '*' ];
141 }
142 return this.extractParametersFromTemplateCode( pageContent );
143 },
144 // Resolve an empty parameters array
145 () => $.Deferred().resolve( [] )
146
147 );
148 } else {
149 // No template found. Resolve to empty array of parameters
150 this.templateSourceCodePromise = $.Deferred().resolve( [] );
151 }
152 }
153
154 return this.templateSourceCodePromise;
155 };
156
157 /**
158 * Retrieve template parameters from the template code.
159 *
160 * Adapted from https://he.wikipedia.org/wiki/MediaWiki:Gadget-TemplateParamWizard.js
161 *
162 * @param {string} templateCode Source of the template.
163 * @return {string[]} An array of parameters that appear in the template code
164 */
165 SourceHandler.prototype.extractParametersFromTemplateCode = function ( templateCode ) {
166 const paramNames = [],
167 normalizedParamNames = [],
168 // This regex matches the one in TemplateDataBlob.php
169 paramExtractor = /{{{+([^\n#={|}]*?)([<|]|}}})/mg;
170
171 // Ignore non-wikitext content in comments and wikitext-escaping tags
172 templateCode = templateCode.replace( /<!--[\s\S]*?-->/g, '' )
173 .replace( /<nowiki\s*>[\s\S]*?<\/nowiki\s*>/g, '' )
174 .replace( /<pre\s*>[\s\S]*?<\/pre\s*>/g, '' );
175
176 let matches;
177 while ( ( matches = paramExtractor.exec( templateCode ) ) !== null ) {
178 // This normalization process is repeated in PHP in TemplateDataBlob.php
179 const normalizedParamName = matches[ 1 ].replace( /[-_ ]+/, ' ' ).trim().toLowerCase();
180 if ( !normalizedParamName || normalizedParamNames.indexOf( normalizedParamName ) !== -1 ) {
181 continue;
182 }
183 if ( paramNames.indexOf( matches[ 1 ] ) === -1 ) {
184 normalizedParamNames.push( normalizedParamName );
185 paramNames.push( matches[ 1 ].trim() );
186 }
187 }
188
189 return paramNames;
190 };
191
192 /**
193 * Look for a templatedata json string and return it, if it exists.
194 *
195 * @param {string} templateDataString Wikitext templatedata string
196 * @return {string|null} The isolated json string. Empty if no
197 * templatedata string was found.
198 */
199 SourceHandler.prototype.findModelInString = function ( templateDataString ) {
200 const parts = templateDataString.match(
201 /<templatedata>([\s\S]*?)<\/templatedata>/i
202 );
203
204 if ( parts && parts[ 1 ] && parts[ 1 ].trim().length > 0 ) {
205 return parts[ 1 ].trim();
206 } else {
207 return null;
208 }
209 };
210
211 /**
212 * Set the page as a sub page of the main template
213 *
214 * @param {boolean} [isSubLevel=false] Page is sublevel
215 */
216 SourceHandler.prototype.setPageSubLevel = function ( isSubLevel ) {
217 this.subLevel = !!isSubLevel;
218 };
219
220 /**
221 * Set the page as a sub page of the main template
222 *
223 * @return {boolean} Page is sublevel
224 */
225 SourceHandler.prototype.isPageSubLevel = function () {
226 return this.subLevel;
227 };
228
229 /**
230 * Get full page name
231 *
232 * @param {string} [pageName=""] Page name
233 */
234 SourceHandler.prototype.setFullPageName = function ( pageName ) {
235 this.fullPageName = pageName || '';
236 };
237
238 /**
239 * Get page full name
240 *
241 * @return {string} Page full name
242 */
243 SourceHandler.prototype.getFullPageName = function () {
244 return this.fullPageName;
245 };
246
247 /**
248 * Set parent page
249 *
250 * @param {string} [parent=""] Parent page
251 */
252 SourceHandler.prototype.setParentPage = function ( parent ) {
253 this.parentPage = parent || '';
254 };
255
256 /**
257 * Get parent page
258 *
259 * @return {string} Parent page
260 */
261 SourceHandler.prototype.getParentPage = function () {
262 return this.parentPage;
263 };
264
265 /**
266 * Set template source code parameters
267 *
268 * @param {string[]} params Parameters from the template source code
269 */
270 SourceHandler.prototype.setTemplateSourceCodeParams = function ( params ) {
271 this.templateSourceCodeParams = params;
272 };
273
274 /**
275 * Set template source code parameters
276 *
277 * @return {string[]} Parameters from the template source code
278 */
279 SourceHandler.prototype.getTemplateSourceCodeParams = function () {
280 return this.templateSourceCodeParams;
281 };
282
283 module.exports = SourceHandler;