/*! * VisualEditor MediaWiki Initialization Target class. * * @copyright 2011-2015 VisualEditor Team and others; see AUTHORS.txt * @license The MIT License (MIT); see LICENSE.txt */ /*global EasyDeflate, alert */ /** * Initialization MediaWiki target. * * @class * @extends ve.init.Target * * @constructor * @param {string} pageName Name of target page * @param {string} [revisionId] If the editor should load a revision of the page, pass the * revision id here. Defaults to loading the latest version (see #load). * @param {Object} [config] Configuration options */ ve.init.mw.Target = function VeInitMwTarget( pageName, revisionId, config ) { config = config || {}; config.toolbarConfig = $.extend( { shadow: true, actions: true, floatable: true }, config.toolbarConfig ); // Parent constructor ve.init.mw.Target.super.call( this, config ); // Properties this.saveDialog = null; this.saveDeferred = null; this.captcha = null; this.docToSave = null; this.toolbarSaveButton = null; this.pageName = pageName; this.pageExists = mw.config.get( 'wgArticleId', 0 ) !== 0; this.toolbarScrollOffset = mw.config.get( 'wgVisualEditorToolbarScrollOffset', 0 ); // Sometimes we actually don't want to send a useful oldid // if we do, PostEdit will give us a 'page restored' message this.requestedRevId = revisionId; this.revid = revisionId || mw.config.get( 'wgCurRevisionId' ); this.restoring = !!revisionId; this.pageDeletedWarning = false; this.editToken = mw.user.tokens.get( 'editToken' ); this.submitUrl = ( new mw.Uri( mw.util.getUrl( this.pageName ) ) ) .extend( { action: 'submit' } ); this.events = { track: $.noop, trackActivationStart: $.noop, trackActivationComplete: $.noop }; this.preparedCacheKeyPromise = null; this.clearState(); this.generateCitationFeatures(); // Initialization this.$element.addClass( 've-init-mw-target' ); // Events this.connect( this, { surfaceReady: 'onSurfaceReady' } ); }; /* Inheritance */ OO.inheritClass( ve.init.mw.Target, ve.init.Target ); /* Events */ /** * @event editConflict */ /** * @event save */ /** * @event showChanges */ /** * @event noChanges */ /** * @event saveErrorEmpty * Fired when save API returns no data object */ /** * @event saveErrorSpamBlacklist * Fired when save is considered spam or blacklisted */ /** * @event saveErrorAbuseFilter * Fired when AbuseFilter throws warnings */ /** * @event saveErrorBadToken * Fired on save if we have to fetch a new edit token * this is mainly for analytical purposes. */ /** * @event saveErrorNewUser * Fired when user is logged in as a new user */ /** * @event saveErrorCaptcha * Fired when saveError indicates captcha field is required */ /** * @event saveErrorUnknown * Fired for any other type of save error */ /** * @event saveErrorPageDeleted * Fired when user tries to save page that was deleted after opening VE */ /** * @event saveErrorTitleBlacklist * Fired when the user tries to save page in violation of the TitleBlacklist */ /** * @event loadError */ /** * @event showChangesError */ /** * @event serializeError */ /** * @event serializeComplete * Fired when serialization is complete */ /* Static Properties */ ve.init.mw.Target.static.citationToolsLimit = 5; ve.init.mw.Target.static.toolbarGroups = [ // History { include: [ 'undo', 'redo' ] }, // Format { classes: [ 've-test-toolbar-format' ], type: 'menu', indicator: 'down', title: OO.ui.deferMsg( 'visualeditor-toolbar-format-tooltip' ), include: [ { group: 'format' } ], promote: [ 'paragraph' ], demote: [ 'preformatted', 'blockquote', 'heading1' ] }, // Style { classes: [ 've-test-toolbar-style' ], type: 'list', icon: 'textStyle', indicator: 'down', title: OO.ui.deferMsg( 'visualeditor-toolbar-style-tooltip' ), include: [ { group: 'textStyle' }, 'language', 'clear' ], forceExpand: [ 'bold', 'italic', 'clear' ], promote: [ 'bold', 'italic' ], demote: [ 'strikethrough', 'code', 'underline', 'language', 'clear' ] }, // Link { include: [ 'link' ] }, // Cite { classes: [ 've-test-toolbar-cite' ], type: 'list', label: OO.ui.deferMsg( 'visualeditor-toolbar-cite-label' ), indicator: 'down', include: [ { group: 'cite' }, 'reference', 'reference/existing' ], demote: [ 'reference', 'reference/existing' ] }, // Structure { classes: [ 've-test-toolbar-structure' ], type: 'list', icon: 'listBullet', indicator: 'down', include: [ { group: 'structure' } ], demote: [ 'outdent', 'indent' ] }, // Insert { classes: [ 've-test-toolbar-insert' ], label: OO.ui.deferMsg( 'visualeditor-toolbar-insert' ), indicator: 'down', include: '*', forceExpand: [ 'media', 'transclusion', 'insertTable' ], promote: [ 'media', 'transclusion', 'insertTable' ] }, // Table { header: OO.ui.deferMsg( 'visualeditor-toolbar-table' ), type: 'list', icon: 'table', indicator: 'down', include: [ { group: 'table' } ], demote: [ 'deleteTable' ] }, // SpecialCharacter { include: [ 'specialCharacter' ] } ]; ve.init.mw.Target.static.importRules = { external: { blacklist: [ // Annotations 'link', 'textStyle/span', 'textStyle/font', 'textStyle/underline', 'meta/language', // Nodes 'div', 'alienInline', 'alienBlock', 'comment' ], removeOriginalDomElements: true }, all: null }; /** * Name of target class. Used by TargetEvents to identify which target we are tracking. * * @static * @property {string} * @inheritable */ ve.init.mw.Target.static.name = 'mwTarget'; /** * Type of integration. Used by ve.init.mw.trackSubscriber.js for event tracking. * * @static * @property {string} * @inheritable */ ve.init.mw.Target.static.integrationType = 'page'; /** * Type of platform. Used by ve.init.mw.trackSubscriber.js for event tracking. * * @static * @property {string} * @inheritable */ ve.init.mw.Target.static.platformType = 'other'; /* Static Methods */ /** * Fix the base URL from Parsoid if necessary. * * Absolutizes the base URL if it's relative, and sets a base URL based on wgArticlePath * if there was no base URL at all. * * @param {HTMLDocument} doc Parsoid document */ ve.init.mw.Target.static.fixBase = function ( doc ) { ve.fixBase( doc, document, ve.resolveUrl( // Don't replace $1 with the page name, because that'll break if // the page name contains a slash mw.config.get( 'wgArticlePath' ).replace( '$1', '' ), document ) ); }; /* Methods */ /** * Handle response to a successful load request. * * This method is called within the context of a target instance. If successful the DOM from the * server will be parsed, stored in {this.doc} and then {this.onReady} will be called. * * @method * @param {Object} response API response data * @param {string} status Text status message */ ve.init.mw.Target.prototype.loadSuccess = function ( response ) { var i, len, linkData, aboutDoc, docRevId, docRevIdMatches, data = response ? response.visualeditor : null; if ( typeof data.content !== 'string' ) { this.loadFail( 've-api', 'No HTML content in response from server' ); } else { ve.track( 'trace.parseResponse.enter' ); this.originalHtml = data.content; this.etag = data.etag; this.fromEditedState = data.fromEditedState; this.doc = ve.parseXhtml( this.originalHtml ); // Fix relative or missing base URL if needed this.constructor.static.fixBase( this.doc ); this.remoteNotices = ve.getObjectValues( data.notices ); this.protectedClasses = data.protectedClasses; this.baseTimeStamp = data.basetimestamp; this.startTimeStamp = data.starttimestamp; this.revid = data.oldid; aboutDoc = this.doc.documentElement.getAttribute( 'about' ); if ( aboutDoc ) { docRevIdMatches = aboutDoc.match( /revision\/([0-9]*)$/ ); if ( docRevIdMatches.length >= 2 ) { docRevId = parseInt( docRevIdMatches[ 1 ] ); } } if ( docRevId && docRevId !== this.revid ) { if ( this.retriedRevIdConflict ) { // Retried already, just error the second time. this.loadFail( 've-api', 'Revision IDs (doc=' + docRevId + ',api=' + this.revid + ') ' + 'returned by server do not match' ); } else { this.retriedRevIdConflict = true; // TODO this retries both requests, in RESTbase mode we should only retry // the request that gave us the lower revid this.loading = false; // HACK: Load with explicit revid to hopefully prevent this from happening again if ( !this.requestedRevId ) { this.requestedRevId = Math.max( docRevId, this.revid ); } this.load(); } return; } else { // Set this to false after a successful load, so we don't immediately give up // if a subsequent load mismatches again this.retriedRevIdConflict = false; } // Populate link cache if ( data.links ) { // Format from the API: { missing: [titles], known: 1|[titles] } // Format expected by LinkCache: { title: { missing: true|false } } linkData = {}; for ( i = 0, len = data.links.missing.length; i < len; i++ ) { linkData[ data.links.missing[ i ] ] = { missing: true }; } if ( data.links.known === 1 ) { // Set back to false by onReady() ve.init.platform.linkCache.setAssumeExistence( true ); } else { for ( i = 0, len = data.links.known.length; i < len; i++ ) { linkData[ data.links.known[ i ] ] = { missing: false }; } } ve.init.platform.linkCache.setMissing( linkData ); } ve.track( 'trace.parseResponse.exit' ); // Everything worked, the page was loaded, continue initializing the editor this.onReady(); } }; /** * Handle both DOM and modules being loaded and ready. * * @fires surfaceReady */ ve.init.mw.Target.prototype.onReady = function () { var target = this; // We need to wait until onReady as local notices may require special messages this.editNotices = this.remoteNotices.concat( this.localNoticeMessages.map( function ( msgKey ) { return '
' + ve.init.platform.getParsedMessage( msgKey ) + '
'; } ) ); this.loading = false; this.edited = this.fromEditedState; this.setupSurface( this.doc, function () { // loadSuccess() may have called setAssumeExistence( true ); ve.init.platform.linkCache.setAssumeExistence( false ); target.getSurface().getModel().connect( target, { history: 'updateToolbarSaveButtonState' } ); target.emit( 'surfaceReady' ); } ); }; /** * Once surface is ready ready, init UI * * @method */ ve.init.mw.Target.prototype.onSurfaceReady = function () { this.setupToolbarSaveButton(); this.attachToolbarSaveButton(); this.restoreEditSection(); }; /** * Handle an unsuccessful load request. * * This method is called within the context of a target instance. * * @method * @param {string} errorTypeText Error type text from mw.Api * @param {Object} error Object containing xhr, textStatus and exception keys * @fires loadError */ ve.init.mw.Target.prototype.loadFail = function () { this.loading = false; this.emit( 'loadError' ); }; /** * Handle a successful save request. * * This method is called within the context of a target instance. * * @method * @param {HTMLDocument} doc HTML document we tried to save * @param {Object} saveData Options that were used * @param {Object} response Response data * @param {string} status Text status message */ ve.init.mw.Target.prototype.saveSuccess = function ( doc, saveData, response ) { var data = response.visualeditoredit; this.saving = false; if ( !data ) { this.saveFail( doc, saveData, null, 'Invalid response from server', response ); } else if ( data.result !== 'success' ) { // Note, this could be any of db failure, hookabort, badtoken or even a captcha this.saveFail( doc, saveData, null, 'Save failure', response ); } else if ( typeof data.content !== 'string' ) { this.saveFail( doc, saveData, null, 'Invalid HTML content in response from server', response ); } else { this.saveComplete( data.content, data.categorieshtml, data.newrevid, data.isRedirect, data.displayTitleHtml, data.lastModified, data.contentSub, data.modules, data.jsconfigvars ); } }; /** * Handle successful DOM save event. * * @method * @param {string} html Rendered page HTML from server * @param {string} categoriesHtml Rendered categories HTML from server * @param {number} newid New revision id, undefined if unchanged * @param {boolean} isRedirect Whether this page is a redirect or not * @param {string} displayTitle What HTML to show as the page title * @param {Object} lastModified Object containing user-formatted date * and time strings, or undefined if we made no change. * @param {string} contentSub HTML to show as the content subtitle * @param {Array} modules The modules to be loaded on the page * @param {Object} jsconfigvars The mw.config values needed on the page * @fires save */ ve.init.mw.Target.prototype.saveComplete = function () { this.saveDeferred.resolve(); this.emit( 'save' ); }; /** * Handle an unsuccessful save request. * * @method * @param {HTMLDocument} doc HTML document we tried to save * @param {Object} saveData Options that were used * @param {Object} jqXHR * @param {string} status Text status message * @param {Object|null} data API response data */ ve.init.mw.Target.prototype.saveFail = function ( doc, saveData, jqXHR, status, data ) { var api, editApi, target = this; this.saving = false; this.pageDeletedWarning = false; // Handle empty response if ( !data ) { this.saveErrorEmpty(); return; } editApi = data && data.visualeditoredit && data.visualeditoredit.edit; // Handle spam blacklist error (either from core or from Extension:SpamBlacklist) if ( editApi && editApi.spamblacklist ) { this.saveErrorSpamBlacklist( editApi ); return; } // Handle warnings/errors from Extension:AbuseFilter // TODO: Move this to a plugin if ( editApi && editApi.info && editApi.info.indexOf( 'Hit AbuseFilter:' ) === 0 && editApi.warning ) { this.saveErrorAbuseFilter( editApi ); return; } // Handle token errors if ( data.error && data.error.code === 'badtoken' ) { api = new mw.Api(); api.get( { // action=query&meta=userinfo and action=tokens&type=edit can't be combined // but action=query&meta=userinfo and action=query&prop=info can, however // that means we have to give it titles and deal with page ids. action: 'query', meta: 'userinfo', prop: 'info', // Try to send the normalised form so that it is less likely we get extra data like // data.normalised back that we don't need. titles: new mw.Title( target.pageName ).toText(), indexpageids: '', intoken: 'edit' } ) .always( function () { target.saveErrorBadToken(); } ) .done( function ( data ) { var userInfo = data.query && data.query.userinfo, pageInfo = data.query && data.query.pages && data.query.pageids && data.query.pageids[ 0 ] && data.query.pages[ data.query.pageids[ 0 ] ], editToken = pageInfo && pageInfo.edittoken, isAnon = mw.user.isAnon(); if ( userInfo && editToken ) { target.editToken = editToken; if ( ( isAnon && userInfo.anon !== undefined ) || // Comparing id instead of name to pretect against possible // normalisation and against case where the user got renamed. mw.config.get( 'wgUserId' ) === userInfo.id ) { // New session is the same user still target.save( doc, saveData ); } else { // The now current session is a different user if ( userInfo.anon !== undefined ) { // New session is an anonymous user mw.config.set( { // wgUserId is unset for anonymous users, not set to null wgUserId: undefined, // wgUserName is explicitly set to null for anonymous users, // functions like mw.user.isAnon rely on this. wgUserName: null } ); target.saveErrorNewUser( null ); } else { // New session is a different user mw.config.set( { wgUserId: userInfo.id, wgUserName: userInfo.name } ); target.saveErrorNewUser( userInfo.name ); } } } } ); return; } else if ( data.error && data.error.code === 'editconflict' ) { this.editConflict(); return; } else if ( data.error && data.error.code === 'pagedeleted' ) { this.saveErrorPageDeleted(); return; } else if ( data.error && data.error.code === 'titleblacklist-forbidden' ) { this.saveErrorTitleBlacklist(); return; } // Handle captcha // Captcha "errors" usually aren't errors. We simply don't know about them ahead of time, // so we save once, then (if required) we get an error with a captcha back and try again after // the user solved the captcha. // TODO: ConfirmEdit API is horrible, there is no reliable way to know whether it is a "math", // "question" or "fancy" type of captcha. They all expose differently named properties in the // API for different things in the UI. At this point we only support the SimpleCaptcha and FancyCaptcha // which we very intuitively detect by the presence of a "url" property. if ( editApi && editApi.captcha && ( editApi.captcha.url || editApi.captcha.type === 'simple' || editApi.captcha.type === 'math' || editApi.captcha.type === 'question' ) ) { this.saveErrorCaptcha( editApi ); return; } // Handle (other) unknown and/or unrecoverable errors this.saveErrorUnknown( editApi, data ); }; /** * Handle a successful show changes request. * * @method * @param {Object} response API response data * @param {string} status Text status message */ ve.init.mw.Target.prototype.showChangesSuccess = function ( response ) { var data = response.visualeditor; this.diffing = false; if ( !data && !response.error ) { this.showChangesFail( null, 'Invalid response from server', null ); } else if ( response.error ) { this.showChangesFail( null, 'Unsuccessful request: ' + response.error.info, null ); } else if ( data.result === 'nochanges' ) { this.noChanges(); } else if ( data.result !== 'success' ) { this.showChangesFail( null, 'Failed request: ' + data.result, null ); } else if ( typeof data.diff !== 'string' ) { this.showChangesFail( null, 'Invalid HTML content in response from server', null ); } else { this.showChangesDiff( data.diff ); } }; /** * Show changes diff HTML * * @param {string} diffHtml Diff HTML * @fires showChanges */ ve.init.mw.Target.prototype.showChangesDiff = function ( diffHtml ) { this.emit( 'showChanges' ); // Invalidate the viewer diff on next change this.getSurface().getModel().getDocument().once( 'transact', this.saveDialog.clearDiff.bind( this.saveDialog ) ); this.saveDialog.setDiffAndReview( diffHtml ); }; /** * Handle errors during showChanges action. * * @method * @this ve.init.mw.Target * @param {Object} jqXHR * @param {string} status Text status message * @param {Mixed} error HTTP status text * @fires showChangesError */ ve.init.mw.Target.prototype.showChangesFail = function ( jqXHR, status ) { this.diffing = false; this.emit( 'showChangesError' ); alert( ve.msg( 'visualeditor-differror', status ) ); this.saveDialog.popPending(); }; /** * Show an save process error message * * @method * @param {string|jQuery|Node[]} msg Message content (string of HTML, jQuery object or array of * Node objects) * @param {boolean} [allowReapply=true] Whether or not to allow the user to reapply. * Reset when swapping panels. Assumed to be true unless explicitly set to false. * @param {boolean} [warning=false] Whether or not this is a warning. */ ve.init.mw.Target.prototype.showSaveError = function ( msg, allowReapply, warning ) { this.saveDeferred.reject( [ new OO.ui.Error( msg, { recoverable: allowReapply, warning: warning } ) ] ); }; /** * Handle general save error * * @method * @fires saveErrorEmpty */ ve.init.mw.Target.prototype.saveErrorEmpty = function () { this.showSaveError( ve.msg( 'visualeditor-saveerror', 'Empty server response' ), false /* prevents reapply */ ); this.emit( 'saveErrorEmpty' ); }; /** * Handle spam blacklist error * * @method * @param {Object} editApi * @fires saveErrorSpamBlacklist */ ve.init.mw.Target.prototype.saveErrorSpamBlacklist = function ( editApi ) { this.showSaveError( $( $.parseHTML( editApi.sberrorparsed ) ), false // prevents reapply ); this.emit( 'saveErrorSpamBlacklist' ); }; /** * Handel abuse filter error * * @method * @param {Object} editApi * @fires saveErrorAbuseFilter */ ve.init.mw.Target.prototype.saveErrorAbuseFilter = function ( editApi ) { this.showSaveError( $( $.parseHTML( editApi.warning ) ) ); // Don't disable the save button. If the action is not disallowed the user may save the // edit by pressing Save again. The AbuseFilter API currently has no way to distinguish // between filter triggers that are and aren't disallowing the action. this.emit( 'saveErrorAbuseFilter' ); }; /** * Handle title blacklist save error * * @method * @fires saveErrorTitleBlacklist */ ve.init.mw.Target.prototype.saveErrorTitleBlacklist = function () { this.showSaveError( mw.msg( 'visualeditor-saveerror-titleblacklist' ) ); this.emit( 'saveErrorTitleBlacklist' ); }; /** * Handle token fetch indicating another user is logged in * * @method * @param {string|null} username Name of newly logged-in user, or null if anonymous * @fires saveErrorNewUser */ ve.init.mw.Target.prototype.saveErrorNewUser = function ( username ) { var badToken, userMsg; badToken = document.createTextNode( mw.msg( 'visualeditor-savedialog-error-badtoken' ) + ' ' ); if ( username === null ) { userMsg = 'visualeditor-savedialog-identify-anon'; } else { userMsg = 'visualeditor-savedialog-identify-user'; } this.showSaveError( $( badToken ).add( $.parseHTML( mw.message( userMsg, username ).parse() ) ) ); this.emit( 'saveErrorNewUser' ); }; /** * Handle unknown save error * * @method * @param {Object} editApi * @param {Object|null} data API response data * @fires onSaveErrorUnknown */ ve.init.mw.Target.prototype.saveErrorUnknown = function ( editApi, data ) { this.showSaveError( $( document.createTextNode( ( editApi && editApi.info ) || ( data.error && data.error.info ) || ( editApi && editApi.code ) || ( data.error && data.error.code ) || 'Unknown error' ) ), false // prevents reapply ); this.emit( 'onSaveErrorUnknown' ); }; /** * Handle a bad token * * @method * @fires saveErrorBadToken */ ve.init.mw.Target.prototype.saveErrorBadToken = function () { this.emit( 'saveErrorBadToken' ); }; /** * Handle captcha error * * @method * @param {Object} editApi * @fires saveErrorCaptcha */ ve.init.mw.Target.prototype.saveErrorCaptcha = function ( editApi ) { var $captchaDiv = $( '