User:4nn1l2/tagPersonalityRight.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
/**
 * Tag images with {{personality rights}} fast
 * [[m:User:Hoo man]]; 2013-03-04
 *
 */
$( document ).ready( function() {
	if ( mw.config.get( 'wgAction' ) === 'view' && mw.config.get( 'wgNamespaceNumber' ) === 6 ) {
		$( mw.util.addPortletLink( 'p-tb', '#', '+personality rights' ) )
			.click( function( event ) {
				event.preventDefault();

				mw.loader.using( [ 'mediawiki.util', 'mediawiki.api', 'user.options' ], function() {
					var i, section, api,
						// The h2 with the license has a different id for every language...
						licensingIDs = [
						// en
						'Licensing',
						'Licensing\\:',
						// de
						'Lizenz',
						'Lizenz\\:'
					];

					for( i = 0; i < licensingIDs.length; i++ ) {
						if ( $( '#' + licensingIDs[i] ).length ) {
							section = '#' + licensingIDs[i];
							break;
						}
					}

					if ( !section ) {
						alert( "Couldn't find a licensing section on page" );
						return;
					}

					section = mw.util.getParamValue(
						'section',
						$( section )
							.parent()
							.find( 'span.editsection a' )
							.attr( 'href' )
					);

					if ( !section ) {
						alert( "Couldn't find a licensing section on page" );
						return;
					}

					$.ajax( {
						url: mw.config.get( 'wgServer' ) + mw.config.get( 'wgScript' ),
						data: {
							title: mw.config.get( 'wgPageName' ),
							section: section,
							action: 'raw'
						},
						cache: false
					} )
					.done( function( text ) {
						api = new mw.Api();

						if ( text.indexOf( '}}' ) !== -1 ) {
							text = text.split('').reverse().join('').replace(
								'}}',
								'}}\n{{personality rights}}'.split('').reverse().join('')
							).split('').reverse().join('');
						} else {
							text += '\n{{personality rights}}';
						}

						api.post( {
							action: 'edit',
							title: mw.config.get( 'wgPageName' ),
							section: section,
							text: text,
							summary: '/* {{int:license-header}} */ +personality rights using [[User:Steinsplitter/tagPersonalityRight.js|tagPersonalityRight.js]]',
							token: mw.user.tokens.get( 'csrfToken' ),
							nocreate: true
						} )
						.done( function() {
							window.location.href =
								mw.config.get( 'wgServer' ) + mw.config.get( 'wgArticlePath' ).replace( /\$1/g, mw.config.get( 'wgPageName' ) );
						} )
						.fail( function() {
							alert( "An error occured while editing the page" );
						} );
					} )
					.fail( function() {
						alert( "An error occured while editing the page" );
					} );
				} );
			} );
	}
} );