Debian Codegraph @

extensions/VisualEditor/modules/ve-mw/preinit/ve.init.mw.ArticleTargetSaver.js

raw symbols SCIP
1 /*!
2 * VisualEditor MediaWiki ArticleTargetSaver.
3 *
4 * @copyright See AUTHORS.txt
5 * @license The MIT License (MIT); see LICENSE.txt
6 */
7
8 /**
9 * Target saver.
10 *
11 * Light-weight saver.
12 *
13 * @class mw.libs.ve.targetSaver
14 * @singleton
15 * @hideconstructor
16 */
17 ( function () {
18 mw.libs.ve = mw.libs.ve || {};
19
20 mw.libs.ve.targetSaver = {
21 /**
22 * Preload the library required for deflating so the user doesn't
23 * have to wait when postHtml is called.
24 */
25 preloadDeflate: function () {
26 mw.loader.load( 'mediawiki.deflate' );
27 },
28
29 /**
30 * Compress a string with deflate.
31 *
32 * @param {string} html HTML to deflate
33 * @return {jQuery.Promise} Promise resolved with deflated HTML
34 */
35 deflate: function ( html ) {
36 return mw.loader.using( 'mediawiki.deflate' ).then( () => mw.deflate( html ) );
37
38 },
39
40 /**
41 * Get HTML to send to Parsoid.
42 *
43 * If the document was generated from scratch (e.g. inside VisualEditor's converter), the
44 * source document can be passed in to transplant the head tag, as well as the attributes
45 * on the html and body tags.
46 *
47 * @param {HTMLDocument} newDoc Document generated by ve.dm.Converter. Will be modified.
48 * @param {HTMLDocument} [oldDoc] Old document to copy attributes from.
49 * @return {string} Full HTML document
50 */
51 getHtml: function ( newDoc, oldDoc ) {
52 function copyAttributes( from, to ) {
53 Array.prototype.forEach.call( from.attributes, ( attr ) => {
54 to.setAttribute( attr.name, attr.value );
55 } );
56 }
57
58 if ( oldDoc ) {
59 // Copy the head from the old document
60 for ( let i = 0, len = oldDoc.head.childNodes.length; i < len; i++ ) {
61 newDoc.head.appendChild( oldDoc.head.childNodes[ i ].cloneNode( true ) );
62 }
63 // Copy attributes from the old document for the html, head and body
64 copyAttributes( oldDoc.documentElement, newDoc.documentElement );
65 copyAttributes( oldDoc.head, newDoc.head );
66 copyAttributes( oldDoc.body, newDoc.body );
67 }
68
69 // Filter out junk that may have been added by browser plugins
70 $( newDoc )
71 .find( [
72 'script', // T54884, T65229, T96533, T103430
73 'noscript', // T144891
74 'object', // T65229
75 'style:not( [ data-mw ] ):not( [ data-mw-deduplicate ] )', // T55252, but allow <style data-mw(-deduplicate)/> e.g. TemplateStyles T188143
76 'embed', // T53521, T54791, T65121
77 'a[href^="javascript:"]', // T200971
78 'img[src^="data:"]', // T192392
79 'div[id="myEventWatcherDiv"]', // T53423
80 'div[id="sendToInstapaperResults"]', // T63776
81 'div[id="kloutify"]', // T69006
82 'div[id^="mittoHidden"]', // T70900
83 'div.hon.certificateLink', // HON (T209619)
84 'div.donut-container', // Web of Trust (T189148)
85 'div.shield-container' // Web of Trust (T297862)
86 ].join( ',' ) )
87 .each( ( j, el ) => {
88 function truncate( text, l ) {
89 return text.length > l ? text.slice( 0, l ) + '…' : text;
90 }
91 const errorMessage = 'DOM content matching deny list found:\n' + truncate( el.outerHTML, 100 ) +
92 '\nContext:\n' + truncate( el.parentNode.outerHTML, 200 );
93 mw.log.error( errorMessage );
94 const err = new Error( errorMessage );
95 err.name = 'VeDomDenyListWarning';
96 mw.errorLogger.logError( err, 'error.visualeditor' );
97 $( el ).remove();
98 } );
99
100 // data-mw-section-id is copied to headings by mw.libs.ve.unwrapParsoidSections
101 // Remove these to avoid triggering selser.
102 $( newDoc ).find( '[data-mw-section-id]:not( section )' ).removeAttr( 'data-mw-section-id' );
103
104 // Deduplicate styles (we re-duplicated them in ve.init.mw.Target.static.parseDocument)
105 // to let selser recognize the nodes and avoid dirty diffs.
106 mw.libs.ve.deduplicateStyles( newDoc.body );
107
108 // Add doctype manually
109 // ve.properOuterHtml is loaded separately in ve.utils.parsing.js
110 // eslint-disable-next-line no-undef
111 return '<!doctype html>' + ve.properOuterHtml( newDoc.documentElement );
112 },
113
114 /**
115 * Serialize and deflate an HTML document
116 *
117 * @param {HTMLDocument} doc Document generated by ve.dm.Converter. Will be modified.
118 * @param {HTMLDocument} [oldDoc] Old document to copy attributes from.
119 * @return {jQuery.Promise} Promise resolved with deflated HTML
120 */
121 deflateDoc: function ( doc, oldDoc ) {
122 return this.deflate( this.getHtml( doc, oldDoc ) );
123 },
124
125 /**
126 * Post an HTML document to the API.
127 *
128 * Serializes the document to HTML, deflates it, then passes to #postHtml.
129 *
130 * @param {HTMLDocument} doc Document to save
131 * @param {Object} [extraData] Extra data to send to the API
132 * @param {Object} [options]
133 * @return {jQuery.Promise} Promise which resolves if the post was successful
134 */
135 saveDoc: function ( doc, extraData, options ) {
136 return this.deflateDoc( doc ).then( ( html ) => this.postHtml(
137 html,
138 null,
139 extraData,
140 options
141 ) );
142 },
143
144 /**
145 * Post wikitext to the API.
146 *
147 * By default uses action=visualeditoredit, paction=save.
148 *
149 * @param {string} wikitext Wikitext to post. Deflating is optional but recommended.
150 * @param {Object} [extraData] Extra data to send to the API
151 * @param {Object} [options]
152 * @param {mw.Api} [options.api] Api to use
153 * @param {Function} [options.now] Function returning current time in milliseconds for tracking, e.g. ve.now
154 * @param {Function} [options.track] Tracking function
155 * @param {string} [options.eventName] Event name for tracking
156 * @return {jQuery.Promise} Promise which resolves with API save data, or rejects with error details
157 */
158 postWikitext: function ( wikitext, extraData, options ) {
159 return this.postContent( $.extend( { wikitext: wikitext }, extraData ), options );
160 },
161
162 /**
163 * Post HTML to the API.
164 *
165 * By default uses action=visualeditoredit, paction=save.
166 *
167 * @param {string} html HTML to post. Deflating is optional but recommended.
168 * Should be included for retries even if a cache key is provided.
169 * @param {string} [cacheKey] Optional cache key of HTML stashed on server.
170 * @param {Object} [extraData] Extra data to send to the API
171 * @param {Object} [options]
172 * @return {jQuery.Promise} Promise which resolves with API save data, or rejects with error details
173 */
174 postHtml: function ( html, cacheKey, extraData, options ) {
175 options = options || {};
176 let data;
177 if ( cacheKey ) {
178 data = $.extend( { cachekey: cacheKey }, extraData );
179 } else {
180 data = $.extend( { html: html }, extraData );
181 }
182 return this.postContent( data, options ).then(
183 null,
184 ( code, response ) => {
185 // This cache key is evidently bad, clear it
186 if ( options.onCacheKeyFail ) {
187 options.onCacheKeyFail();
188 }
189 if ( code === 'badcachekey' ) {
190 // If the cache key failed, try again without the cache key
191 return this.postHtml(
192 html,
193 null,
194 extraData,
195 options
196 );
197 }
198 // Failed for some other reason - let caller handle it.
199 return $.Deferred().reject( code, response ).promise();
200 }
201 );
202 },
203
204 /**
205 * Post content to the API, using mw.Api#postWithToken to retry automatically when encountering
206 * a 'badtoken' error.
207 *
208 * By default uses action=visualeditoredit, paction=save.
209 *
210 * @param {string} data Content data
211 * @param {Object} [options]
212 * @param {mw.Api} [options.api] Api to use
213 * @param {Function} [options.now] Function returning current time in milliseconds for tracking, e.g. ve.now
214 * @param {Function} [options.track] Tracking function
215 * @param {string} [options.eventName] Event name for tracking
216 * @return {jQuery.Promise} Promise which resolves with API save data, or rejects with error details
217 */
218 postContent: function ( data, options ) {
219 options = options || {};
220 const api = options.api || new mw.Api();
221
222 let start;
223 if ( options.now ) {
224 start = options.now();
225 }
226
227 data = $.extend(
228 {
229 action: 'visualeditoredit',
230 paction: 'save',
231 useskin: mw.config.get( 'skin' ),
232 // Same as OO.ui.isMobile()
233 mobileformat: !!mw.config.get( 'wgMFMode' ),
234 formatversion: 2,
235 errorformat: 'html',
236 errorlang: mw.config.get( 'wgUserLanguage' ),
237 errorsuselocal: true
238 },
239 data
240 );
241
242 const action = data.action;
243
244 const request = api.postWithToken( 'csrf', data, {
245 contentType: 'multipart/form-data',
246 trackEditAttemptStepSessionId: true
247 } );
248
249 return request.then(
250 ( response, jqxhr ) => {
251 const responseData = response[ action ];
252
253 // Log data about the request if eventName was set
254 if ( options.track && options.eventName ) {
255 const eventData = {
256 bytes: require( 'mediawiki.String' ).byteLength( jqxhr.responseText ),
257 duration: options.now() - start
258 };
259 const fullEventName = 'performance.system.' + options.eventName +
260 ( responseData.cachekey ? '.withCacheKey' : '.withoutCacheKey' );
261 options.track( fullEventName, eventData );
262 }
263
264 let error;
265 if ( !responseData ) {
266 error = {
267 code: 'invalidresponse',
268 html: mw.message( 'api-clientside-error-invalidresponse' ).parse()
269 };
270 } else if ( responseData.result !== 'success' ) {
271 // This should only happen when saving an edit and getting a captcha from ConfirmEdit
272 // extension (`data.result === 'error'`). It's a silly special case...
273 return $.Deferred().reject( 'no-error-no-success', response ).promise();
274 } else {
275 // paction specific errors
276 switch ( responseData.paction ) {
277 case 'save':
278 case 'serialize':
279 if ( typeof responseData.content !== 'string' ) {
280 error = {
281 code: 'invalidcontent',
282 html: mw.message( 'api-clientside-error-invalidresponse' ).parse()
283 };
284 }
285 break;
286 case 'diff':
287 if ( typeof responseData.diff !== 'string' ) {
288 error = {
289 code: 'invalidcontent',
290 html: mw.message( 'api-clientside-error-invalidresponse' ).parse()
291 };
292 }
293 break;
294 }
295 }
296
297 if ( error ) {
298 // Use the same format as API errors
299 return $.Deferred().reject( error.code, { errors: [ error ] } ).promise();
300 }
301 return responseData;
302 },
303 ( code, response ) => {
304 const responseText = OO.getProp( response, 'xhr', 'responseText' );
305
306 if ( responseText && options.track && options.eventName ) {
307 const eventData = {
308 bytes: require( 'mediawiki.String' ).byteLength( responseText ),
309 duration: options.now() - start
310 };
311 let fullEventName;
312 if ( code === 'badcachekey' ) {
313 fullEventName = 'performance.system.' + options.eventName + '.badCacheKey';
314 } else {
315 fullEventName = 'performance.system.' + options.eventName + '.withoutCacheKey';
316 }
317 options.track( fullEventName, eventData );
318 }
319 return $.Deferred().reject( code, response ).promise();
320 }
321 );
322 }
323 };
324 }() );