summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/Translate/resources/js/ext.translate.special.pagepreparation.js
blob: 03c4385d6413e0782b994f087ebb74077c9e9e53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
( function () {
	'use strict';

	/**
	 * Save the page with a given page name and given content to the wiki.
	 *
	 * @param {string} pageName Page title
	 * @param {string} pageContent Content of the page to be saved
	 * @return {jQuery.Promise}
	 */
	function savePage( pageName, pageContent ) {
		var api = new mw.Api();

		return api.postWithToken( 'csrf', {
			action: 'edit',
			title: pageName,
			text: pageContent,
			summary: $( '#pp-summary' ).val()
		} ).promise();
	}

	/**
	 * Get the diff between the current revision and the prepared page content.
	 *
	 * @param {string} pageName Page title
	 * @param {string} pageContent Content of the page to be saved
	 * @return {jQuery.Promise}
	 * @return {Function} return.done
	 * @return {string} return.done.data
	 */
	function getDiff( pageName, pageContent ) {
		var api = new mw.Api();

		return api.post( {
			action: 'query',
			prop: 'revisions',
			rvprop: 'content',
			rvlimit: '1',
			titles: pageName,
			rvdifftotext: pageContent
		} ).then( function ( data ) {
			var page, obj, diff;

			for ( page in data.query.pages ) {
				obj = data.query.pages[ page ];
			}

			diff = obj.revisions[ 0 ].diff[ '*' ];

			return diff;
		} );
	}

	/**
	 * Remove all the <translate> tags and {{translation}} templates before
	 * preparing the page. The tool will add them back wherever needed.
	 *
	 * @param {string} pageContent
	 * @return {string}
	 */
	function cleanupTags( pageContent ) {
		pageContent = pageContent.replace( /<\/?translate>\n?/gi, '' );
		return pageContent;
	}

	/**
	 * Add the <languages/> bar at the top of the page, if not present.
	 * Remove the old {{languages}} template, if present.
	 *
	 * @param {string} pageContent
	 * @return {string}
	 */
	function addLanguageBar( pageContent ) {
		if ( !pageContent.match( /<languages\/>/gi ) ) {
			pageContent = '<languages/>\n' + pageContent;
		}
		pageContent = pageContent.replace( /\{\{languages.*?\}\}/gi, '' );
		return pageContent;
	}

	/**
	 * Add <translate> tags around Categories to make them a part of the page template
	 * and tag them with the {{translation}} template.
	 *
	 * @param {string} pageContent
	 * @return {jQuery.Promise}
	 */
	function doCategories( pageContent ) {
		return getNamespaceAliases( 14 ).then( function ( aliases ) {
			var i, aliasList, categoryRegex;

			aliases.push( 'category' );
			for ( i = 0; i < aliases.length; i++ ) {
				aliases[ i ] = mw.RegExp.escape( aliases[ i ] );
			}

			aliasList = aliases.join( '|' );
			// Regex: https://regex101.com/r/sJ3gZ4/2
			categoryRegex = new RegExp( '\\[\\[((' + aliasList + ')' +
				':[^\\|]+)(\\|[^\\|]*?)?\\]\\]', 'gi' );
			pageContent = pageContent.replace( categoryRegex, '\n</translate>\n' +
				'[[$1{{#translation:}}$3]]\n<translate>\n' );

			return pageContent;
		} );
	}

	/**
	 * Add the <translate> and </translate> tags at the start and end of the page.
	 * The opening tag is added immediately after the <languages/> tag.
	 *
	 * @param {string} pageContent
	 * @return {string}
	 */
	function addTranslateTags( pageContent ) {
		pageContent = pageContent.replace( /(<languages\/>\n)/gi, '$1<translate>\n' );
		pageContent = pageContent + '\n</translate>';
		return pageContent;
	}

	/**
	 * Add newlines before and after section headers. Extra newlines resulting after
	 * this operation are cleaned up in postPreparationCleanup() function.
	 *
	 * @param {string} pageContent
	 * @return {string}
	 */
	function addNewLines( pageContent ) {
		pageContent = pageContent.replace( /^(==.*==)\n*/gm, '\n$1\n\n' );
		return pageContent;
	}

	/**
	 * Add an anchor to a section header with the given headerText
	 *
	 * @param {string} headerText
	 * @param {string} pageContent
	 * @return {string}
	 */
	function addAnchor( headerText, pageContent ) {
		var headerSearchRegex, anchorID, replaceAnchorRegex,
			spanSearchRegex;

		anchorID = headerText.replace( ' ', '-' ).toLowerCase();

		headerText = mw.RegExp.escape( headerText );
		// Search for the header having text as headerText
		// Regex: https://regex101.com/r/fD6iL1
		headerSearchRegex = new RegExp( '(==+[ ]*' + headerText + '[ ]*==+)', 'gi' );
		// This is to ensure the tags and the anchor are added only once

		if ( pageContent.indexOf( '<span id="' + mw.html.escape( anchorID ) + '"' ) === -1 ) {
			pageContent = pageContent.replace( headerSearchRegex, '</translate>\n' +
				'<span id="' + mw.html.escape( anchorID ) + '"></span>\n<translate>\n$1' );
		}

		// This is to add back the tags which were removed in cleanupTags()
		if ( pageContent.indexOf( '</translate>\n<span id="' + anchorID + '"' ) === -1 ) {
			spanSearchRegex = new RegExp( '(<span id="' + mw.RegExp.escape( anchorID ) + '"></span>)', 'gi' );
			pageContent = pageContent.replace( spanSearchRegex, '\n</translate>\n$1\n</translate>\n' );
		}

		// Replace the link text with the anchorID defined above
		// Regex: https://regex101.com/r/kB5bK3
		replaceAnchorRegex = new RegExp( '(\\[\\[#)' + headerText + '(.*\\]\\])', 'gi' );
		pageContent = pageContent.replace( replaceAnchorRegex, '$1' +
			anchorID.replace( '$', '$$$' ) + '$2' );

		return pageContent;
	}

	/**
	 * Convert all the links into two-party form and add the 'Special:MyLanguage/' prefix
	 * to links in valid namespaces for the wiki. For example, [[Example]] would be converted
	 * to [[Special:MyLanguage/Example|Example]].
	 *
	 * @param {string} pageContent
	 * @return {string}
	 */
	function fixInternalLinks( pageContent ) {

		var normalizeRegex, linkPrefixRegex, sectionLinksRegex,
			match, searchText, namespaces, nsString;
		searchText = pageContent;

		normalizeRegex = new RegExp( /\[\[(?!Category)([^|]*?)\]\]/gi );
		// First convert all links into two-party form. If a link is not having a pipe,
		// add a pipe and duplicate the link text
		// Regex: https://regex101.com/r/pO9nN2
		pageContent = pageContent.replace( normalizeRegex, '[[$1|$1]]' );

		namespaces = getNamespaces();
		nsString = namespaces.join( '|' );
		// Finds all the links to sections on the same page.
		// Regex: https://regex101.com/r/cX6jT3
		sectionLinksRegex = new RegExp( /\[\[#(.*?)(\|(.*?))?\]\]/gi );
		match = sectionLinksRegex.exec( searchText );
		while ( match !== null ) {
			pageContent = addAnchor( match[ 1 ], pageContent );
			match = sectionLinksRegex.exec( searchText );
		}

		linkPrefixRegex = new RegExp( '\\[\\[((?:(?:special(?!:MyLanguage\\b)|' + nsString +
			'):)?[^:]*?)\\]\\]', 'gi' );
		// Add the 'Special:MyLanguage/' prefix for all internal links of valid namespaces and
		// mainspace.
		// Regex: https://regex101.com/r/zZ9jH9
		pageContent = pageContent.replace( linkPrefixRegex, '[[Special:MyLanguage/$1]]' );
		return pageContent;
	}

	/**
	 * Fetch all the aliases for a given namespace on the wiki.
	 *
	 * @param {number} namespaceID
	 * @return {jQuery.Promise}
	 * @return {Function} return.done
	 * @return {Array} return.done.data
	 */
	function getNamespaceAliases( namespaceID ) {
		var api = new mw.Api();

		return api.get( {
			action: 'query',
			meta: 'siteinfo',
			siprop: 'namespacealiases'
		} ).then( function ( data ) {
			var alias, aliases = [];

			for ( alias in data.query.namespacealiases ) {
				if ( data.query.namespacealiases[ alias ].id === namespaceID ) {
					aliases.push( data.query.namespacealiases[ alias ][ '*' ] );
				}
			}

			return aliases;
		} );
	}

	/**
	 * Add translate tags around only translatable content for files and keep everything else
	 * as a part of the page template.
	 *
	 * @param {string} pageContent
	 * @return {jQuery.Promise}
	 */
	function doFiles( pageContent ) {
		return getNamespaceAliases( 6 ).then( function ( aliases ) {
			var i, aliasList, captionFilesRegex, fileRegex;

			aliases.push( 'file' );

			for ( i = 0; i < aliases.length; i++ ) {
				aliases[ i ] = mw.RegExp.escape( aliases[ i ] );
			}

			aliasList = aliases.join( '|' );

			// Add translate tags for files with captions
			captionFilesRegex = new RegExp( '\\[\\[(' + aliasList + ')(.*\\|)(.*?)\\]\\]', 'gi' );
			pageContent = pageContent.replace( captionFilesRegex,
				'</translate>\n[[$1$2<translate>$3</translate>]]\n<translate>' );

			// Add translate tags for files without captions
			fileRegex = new RegExp( '/\\[\\[((' + aliasList + ')[^\\|]*?)\\]\\]', 'gi' );
			pageContent = pageContent.replace( fileRegex, '\n</translate>[[$1]]\n<translate>' );

			return pageContent;
		} );
	}

	/**
	 * Keep templates outside <translate>....</translate> tags
	 * Does not deal with nested templates, needs manual changes.
	 *
	 * @param {string} pageContent
	 * @return {string} pageContent
	 */
	function doTemplates( pageContent ) {
		var templateRegex;
		// Regex: https://regex101.com/r/wA3iX0
		templateRegex = new RegExp( /^({{[\s\S]*?}})/gm );

		pageContent = pageContent.replace( templateRegex, '</translate>\n$1\n<translate>' );
		return pageContent;
	}

	/**
	 * Cleanup done after the page is prepared for translation by the tool.
	 *
	 * @param {string} pageContent
	 * @return {string}
	 */
	function postPreparationCleanup( pageContent ) {
		// Removes any extra newlines introduced by the tool
		pageContent = pageContent.replace( /\n\n+/gi, '\n\n' );
		// Removes redundant <translate> tags
		pageContent = pageContent.replace( /\n<translate>(\n*?)<\/translate>/gi, '' );
		// Removes the Special:MyLanguage/ prefix for section links
		pageContent = pageContent.replace( /Special:MyLanguage\/#/gi, '#' );
		return pageContent;
	}

	/**
	 * Get the current revision for the given page.
	 *
	 * @param {string} pageName
	 * @return {jQuery.Promise}
	 * @return {Function} return.done
	 * @return {string} return.done.value The current revision
	 */
	function getPageContent( pageName ) {
		var obj,
			api = new mw.Api();

		return api.get( {
			action: 'query',
			prop: 'revisions',
			rvprop: 'content',
			rvlimit: '1',
			titles: pageName
		} ).then( function ( data ) {
			var page;

			for ( page in data.query.pages ) {
				obj = data.query.pages[ page ];
			}

			return obj.revisions[ 0 ][ '*' ];
		} );
	}

	/**
	 * Get the list of valid namespaces for the wiki and remove unwanted
	 * ones from the list.
	 *
	 * @return {Array} Array of valid namespaces
	 */
	function getNamespaces() {
		var key, namespacesObject, i,
			namespaces = [];

		namespacesObject = mw.config.get( 'wgNamespaceIds' );
		for ( key in namespacesObject ) {
			namespaces.push( key );
		}

		// Remove all what has been already handled somewhere else
		[ '', 'category', 'category_talk', 'special', 'file', 'file_talk' ].forEach( function ( ns ) {
			namespaces.splice( namespaces.indexOf( ns ), 1 );
		} );

		for ( i = 0; i < namespaces.length; i++ ) {
			namespaces[ i ] = mw.RegExp.escape( namespaces[ i ] );
		}
		return namespaces;
	}

	$( function () {
		var pageContent,
			$input = $( '#page' );

		$( '#action-cancel' ).click( function () {
			document.location.reload( true );
		} );

		$( '#action-save' ).click( function () {
			var pageName,
				pageUrl = '';

			pageName = $input.val().trim();
			savePage( pageName, pageContent ).done( function () {
				pageUrl = mw.Title.newFromText( pageName ).getUrl( { action: 'edit' } );
				$( '.messageDiv' )
					.empty()
					.append( mw.message( 'pp-save-message', pageUrl ).parseDom() )
					.show();
				$( '.divDiff' ).hide( 'fast' );
				$( '#action-prepare' ).show();
				$input.val( '' );
				$( '#action-save' ).hide();
				$( '#action-cancel' ).hide();
			} );
		} );

		$( '#action-prepare' ).click( function () {
			var pageName, messageDiv = $( '.messageDiv' );

			pageName = $input.val().trim();
			messageDiv.hide();
			if ( pageName === '' ) {
				// eslint-disable-next-line no-alert
				alert( mw.msg( 'pp-pagename-missing' ) );
				return;
			}

			$.when( getPageContent( pageName ) ).done( function ( content ) {
				pageContent = content;
				pageContent = pageContent.trim();
				pageContent = cleanupTags( pageContent );
				pageContent = addLanguageBar( pageContent );
				pageContent = addTranslateTags( pageContent );
				pageContent = addNewLines( pageContent );
				pageContent = fixInternalLinks( pageContent );
				pageContent = doTemplates( pageContent );
				doFiles( pageContent ).then( doCategories ).done( function ( pageContent ) {
					pageContent = postPreparationCleanup( pageContent );
					pageContent = pageContent.trim();
					getDiff( pageName, pageContent ).done( function ( diff ) {
						$( '.diff tbody' ).append( diff );
						$( '.divDiff' ).show( 'fast' );
						if ( diff !== '' ) {
							messageDiv.text( mw.msg( 'pp-prepare-message' ) ).show();
							$( '#action-prepare' ).hide();
							$( '#action-save' ).show();
							$( '#action-cancel' ).show();
						} else {
							messageDiv.text( mw.msg( 'pp-already-prepared-message' ) ).show();
						}
					} );
				} );
			} );
		} );
	} );

}() );