МедиаУики:Gadget-wikibugs.js

Ескерту: Сақтағаннан кейін өзгерістерді көру үшін браузеріңіздің бүркемесін (кэшін) тазарту керек болуы мүмкін.

  • Firefox / Safari: Қайта жүктеуді нұқығанда  Shift пернесін басып тұрыңыз немесе Ctrl+F5 не Ctrl+ Shift+R екеуінің біреуін басыңыз
    (Mac — +R)
  • Google Chrome: Ctrl+ Shift+R басыңыз (Mac — + Shift+R)
  • Internet Explorer: Жаңарту батырмасын нұқығанда Ctrl пернесін басып тұрыңыз немесе Ctrl+F5 басыңыз, не F5 пернесін басыңыз
  • Opera: Құралдар → Бапталымдар дегеннен бүркемесін тазарту керек.
/*
 * @author: [[:pl:User:Dodek]] (idea and text)
 * @author: [[:pl:User:Adziura]] (idea and text)
 * @author: [[:pl:User:Nux]] (implementation)
 * @author: [[:pl:User:Saper]] (implementation)
 * @author: [[:pl:User:Beau]] (implementation)
 * @author: [[:pt:User:Helder.wiki]] (implementation)
 * Қазақшаға бейімдеген [[User:Arystanbek]]
 */

/* Translatable strings */
mw.messages.set( {
	'wikibugs-dialog-title': 'Қате туралы хабарлау',
	'wikibugs-open-form-button': 'Қате туралы хабарлау',
	'wikibugs-edit-page-button': 'Өз бетіңізбен түзету',
	'wikibugs-cancel-button': 'Болдырмау',
	'wikibugs-submit-report-button': 'Жіберу',
	'wikibugs-ip-address-notice': '<b>Назар аударыңыз:</b> Сіздің IP мекенжайыңыз беттің өңделу тарихына жазылып алынады.',
	'wikibugs-page-name-label': 'Бет атауы:<br/><small>(егер сіз файлдағы қате туралы хабарламақшы болсаңыз "Сурет:" дегенді қосып жазыңыз)</small>',
	'wikibugs-report-content-label': 'Хабарлама мәтіні:',
	'wikibugs-report-content-placeholder': 'Қате туралы мүмкіндігінше дәлме-дәл жазыңыз. Егер мүмкін болса ақпараттың қайнарын беріңіз',
	'wikibugs-signature-label': 'Қолтаңбаңыз:',
	'wikibugs-edit-error': '',
	'wikibugs-token-error': '',
	'wikibugs-unknown-token-error': '',
	'wikibugs-ajax-error': 'Ескертпені жіберуде қате кездесті. Өтініш, тағы жіберіп көріңіз .',
	'wikibugs-incomplete-information': 'Қате: енгізілген сипаттамасы тым қысқа, - дәл сипаттаңыз.',
	'wikibugs-invalid-page': 'Бет атауын енгізіңіз.',
	'wikibugs-reported-by': ' Хабарландыру жіберген: $1',
	'wikibugs-file-section-line': '<!-- Файл қателерін бұл жолдан төмен енгізіңіз. Жаңасы басына -->',
	'wikibugs-page-section-line': '<!-- Мақалалардағы қателерді бұл жолдан төмен енгізіңіз. Жаңасы басына. -->',
	'wikibugs-bad-reports-text': '<p>Қателер туралы басқа сайттарда ' +
		'(мысалы <a href="' + mw.util.getUrl( 'әлеуметтік желілер' ) + '">әлеуметтік желілерде</a><p>)' + 
		' хабарламаңыз. Олар еленбейді.</p> ' +
        '<p>Уикипедия ешқандай сұраққа жауап бермейді. ' +
		'Егер сіз кеңес алғыңыз келсе оны мұнда хабарламаңыз.</p>' +
		'<p>Өзіңізге қатысты емес, Уикипедияға қатысты сұрақтарыңыз болса келесі бетке өтіңіз:</p>' +
		'<ul><li><a href="' + mw.util.getUrl( 'Уикипедия:Форум/Сұрақтар' ) + '">Уикипедия:Форум/Сұрақтар</a></li></ul>',
	'wikibugs-article-intro': '<p style="margin-top:0px;">Сіз Уикипедия мақалаларындағы қателер туралы ' +
		'хабарлай аласыз, бірақ есіңізде болсын, Уикипедия ' +
		'<a href="' + mw.util.getUrl( 'уики' ) + '">уики</a> технологиясын қолданатын сайт ' +
		'болғандықтан өз бетіңізше қатені түзете аласыз! Егер мүмкін болса, ' + 
		'қайнар мәліметті қосымша ретінде енгізсеңіз негізгі қатені түзеткеніңіз. ' +
		'Түрлі себептермен Уикипедияның кейбір оқырмандары ' +
		'мақалаларды өз бетінше жетілдіруді қаламайтынын білеміз.</p><p><b>Егер сіз қатені түзете алсаңыз ' +
		'– оны мұнда хабарламаңыз.</b></p>',
	'wikibugs-image-intro': '<p style="margin-top:0px;">Tu możesz zgłaszać grafiki, które łamią licencję, ' +
		'mają swoje lepsze odpowiedniki w Commons, są błędnie opisane itp.</p>' +
		'<p><b>Jeżeli potrafisz poprawić błąd - nie zgłaszaj go tutaj.</b></p>',
	'wikibugs-already-reported-notice': '<p><b>Түсініктеме:</b> Егер сіз қате туралы хабарласаңыз ' +
		'ол міндетті түрде түзетіледі. <ul>' +
		'<li><a href="' + mw.util.getUrl( 'Уикипедия:Форум/Қателер туралы хабарлау' ) + '">' +
		'Қазіргі хабарланған қателер тізімін</a> және</li>' +
		'<li><a href="' + mw.util.getUrl( 'Уикипедия:Форум/Қателер туралы хабарлау' ) + '?action=history">' +
		'бұл беттің өзгеріс тарихын</a> қараңыз</li></ul>',
	'wikibugs-footer': '',
	'wikibugs-new-report': 'Жаңа хабарлама: $1'
} );

window.wikiBugsGadget = {
	/**
	 * Version number of this gadget.
	 */
	version: 9,
	/**
	 * A name of a page where reports are saved.
	 */
	reportPage: 'Уикипедия:Форум/Қателер туралы хабарлау',
	/**
	 * Black list of pages which reports should not refer to.
	 */
	badPages: [
		'Уикипедия:Уикипедияға қош келдіңіз! ',
		'Уикипедия:Анықтама',
		],
	/**
	 * Define pages where it's not needed or tends to encourage submission of large
	 * volumes of unrelated errors; instead, these load CSS which hides the "Report A Bug" link
	 */
	excludedPages: [
		'Басты бет',
		],
	/**
	 * Message shown on pages in the main namespace.
	 */
	articleIntro: '<div id="wbBadReports">' +
		mw.msg( 'wikibugs-bad-reports-text' ) + '</div>' +
		mw.msg( 'wikibugs-article-intro' ) +
		mw.msg( 'wikibugs-already-reported-notice' ) +
		mw.msg( 'wikibugs-footer' ),
	/**
	 * Message shown on pages in the file namespace.
	 */
	imageIntro: '<div id="wbBadReports">' +
		mw.msg( 'wikibugs-bad-reports-text' ) + '</div>' +
		mw.msg( 'wikibugs-image-intro' ) +
		mw.msg( 'wikibugs-already-reported-notice' ) +
		mw.msg( 'wikibugs-footer' ),

	/**
	 * Checks if a title of the page is valid for a report.
	 * @param title A title of the page.
	 */
	isValidPageName: function( title ) {
		// Empty title is not valid
		if ( title === '' ) {
			return false;
		}
		// Special pages are not valid too
		if ( this.getPageNamespaceNumber( title ) === -1 ) {
			return false;
		}
		// Check black list
		title = this.getRefinedPageName( title );
		return jQuery.inArray( title, this.badPages ) === -1;
	},

	/**
	 * Returns a namespace number of a specifed page.
	 * @param title A title of the page.
	 */
	getPageNamespaceNumber: function( title ) {
		var matches = title.match( /^([^:]+)/ );
		if ( matches ) {
			var key = matches[1].toLowerCase();
			var namespaces = mw.config.get( 'wgNamespaceIds' );
			var result = namespaces[key];
			if ( result !== null ) {
				return result;
			}
		}
		return 0;
	},

	/**
	 * Returns a refined page title.
	 * @param title A title of the page.
	 */
	getRefinedPageName: function( title ) {
		return jQuery.trim( title.replace( /_/g, ' ' ) );
	},

	/**
	 * Sets up the gadget.
	 */
	init: function() {
		var that = this;
		var excluded = false;

		// Special pages and MediaWiki pages are excluded
		if ( jQuery.inArray( mw.config.get( 'wgNamespaceNumber' ), [-1, 8] ) > -1 ) {
			excluded = true;
		} else {
			var name = this.getRefinedPageName( mw.config.get( 'wgPageName' ) );
			excluded = jQuery.inArray( name, this.excludedPages ) !== -1;
		}

		// FIXME: This doesn't exists on "standard", "cologneblue" (no ids) and "nostalgia" (no sidebar)
		var $articleBugLink = jQuery( '#n-bug_in_article' );
		var $imageBugLink = jQuery( '#n-bad-image' );

		if ( excluded ) {
			// Hide the links
			$articleBugLink.hide();
			$imageBugLink.hide();
			return;
		}

		$articleBugLink.find( 'a' )
			.attr( 'href', '#' )
			.click( function( event ) {
				that.open( that.articleIntro );
				event.preventDefault();
			} );

		$imageBugLink.find( 'a' )
			.attr( 'href', '#' )
			.click( function( event ) {
				that.open( that.imageIntro );
				event.preventDefault();
			} );

		// Link on the report-an-error page itself
		jQuery( '#report-bug-link a' ).click( function( event ) {
			that.open( that.articleIntro );
			event.preventDefault();
		} );
	},

	/**
	 * Redirects to the edit page.
	 */
	goToEditPage: function() {
		var $editLink = jQuery( '#ca-edit' ).find( 'a' );
		window.location = $editLink.attr( 'href' ) || mw.util.getUrl( this.reportPage );
	},

	/**
	 * Shows the dialog window.
	 * @param infoHtml The message content.
	 */
	open: function( infoHtml ) {
		var that = this;

		var can_edit = document.getElementById( 'ca-edit' ) ? true : false;

		var $dialog = jQuery( '<div id="dialogContent"></div>' ).append( infoHtml );

		if ( mw.user.isAnon() ) {
			$dialog.append( '<p>' + mw.msg( 'wikibugs-ip-address-notice' ) + '</p>' );
		}

		var buttons = {};
		buttons[mw.msg( 'wikibugs-cancel-button' )] = function() {
			jQuery( this ).dialog( 'close' );
		};
		buttons[mw.msg( 'wikibugs-open-form-button' )] = function() {
			that.openForm( this );
		};
		if ( can_edit ) {
			buttons[mw.msg( 'wikibugs-edit-page-button' )] = function() {
				that.goToEditPage();
			};
		}

		$dialog.dialog( {
			width: 700,
			height: 500,
			modal: true,
			resizable: false,
			draggable: true,
			closeOnEscape: true,
			dialogClass: 'reportBugDialog',
			title: mw.msg( 'wikibugs-dialog-title' ),
			close: function() {
				jQuery( this ).dialog( 'destroy' ).remove();
			},
			buttons: buttons
		} );
		jQuery( 'div.reportBugDialog button:last' ).focus();
	},
	/**
	 * Shows the form in the dialog window.
	 */
	openForm: function( dialog ) {
		var that = this;

		jQuery( '#dialogContent' ).empty().append(
			'<form name="WikibugForm" enctype="multipart/form-data">' +
			'<fieldset>' +
			'<label for="wbPageTitle">' + mw.msg( 'wikibugs-page-name-label' ) + '</label>' +
			'<input id="wbPageTitle" type="text" name="wbPageTitle" class="text ui-widget-content ui-corner-all" />' +
			'<label for="wbText">' + mw.msg( 'wikibugs-report-content-label' ) + '</label>' +
			'<textarea id="wbText" name="wbText" rows="6" class="text ui-widget-content ui-corner-all">' +
			mw.msg( 'wikibugs-report-content-placeholder' ) + '</textarea>' +
			'<label for="wbAuthor">' + mw.msg( 'wikibugs-signature-label' ) + '</label>' +
			'<input id="wbAuthor" type="text" class="text ui-widget-content ui-corner-all"/>' +
			'</fieldset>' +
			'<img id="wikibugs-loading-icon" src="//upload.wikimedia.org/wikipedia/commons/4/49/Linux_Ubuntu_Loader.gif" style="display:none;"/>' +
			'</form>'
		);

		var buttons = {};
		buttons[mw.msg( 'wikibugs-cancel-button' )] = function() {
			jQuery( this ).dialog( 'close' );
		};
		buttons[mw.msg( 'wikibugs-submit-report-button' )] = function() {
			that.submitForm();
		};

		jQuery( dialog ).dialog( 'option', 'buttons', buttons );

		jQuery( '#wbText' ).focus( function() {
			if ( this.value === mw.msg( 'wikibugs-report-content-placeholder' ) ) {
				this.value = '';
			}
		} );

		if ( this.isValidPageName( mw.config.get( 'wgPageName' ) ) ) {
			jQuery( '#wbPageTitle' ).val( this.getRefinedPageName( mw.config.get( 'wgPageName' ) ) );
		}

		if ( !mw.user.isAnon() ) {
			var author = document.getElementById( 'wbAuthor' );
			author.value = '~~' + '~~';
			author.disabled = 'disabled';
		}
	},

	/**
	 * Indicates wheter submit should be ignored.
	 */
	suppressSubmit: false,

	/**
	 * Sends the contents of the form.
	 */
	submitForm: function() {
		if ( this.suppressSubmit ) {
		    return;
		}

		var form = document.forms.WikibugForm;
		var content = form.wbText.value;

		if ( content === mw.msg( 'wikibugs-report-content-placeholder' ) ||
		    content.length < 20 ||
		    !content.match( ' ' ) ) {
			// Description too short or unchanged
			alert( mw.msg( 'wikibugs-incomplete-information' ) );

			form.wbText.focus();
			return;
		}
		content = jQuery.trim( content );

		// Append a signature to the report
		if ( !mw.user.isAnon() ) {
			content += mw.msg( 'wikibugs-reported-by', '~~' + '~~' );
		} else {
			content += mw.msg( 'wikibugs-reported-by', form.wbAuthor.value + ' ~~' + '~~' );
		}

		var reportedPage = this.getRefinedPageName( form.wbPageTitle.value.replace( /[\[\]]/g, '' ) );
		var isFile = this.getPageNamespaceNumber( reportedPage ) === 6;

		if ( !this.isValidPageName( reportedPage ) ) {
			alert( mw.msg( 'wikibugs-invalid-page' ) );

			var refinedPageName = this.getRefinedPageName( mw.config.get( 'wgPageName' ) );
			if ( this.isValidPageName( refinedPageName ) ) {
				form.wbPageTitle.value = refinedPageName;
			} else {
				form.wbPageTitle.value = '';
				form.wbPageTitle.focus();
			}
			return;
		}

		this.suppressSubmit = true;
		var $loadingIcon = jQuery( '#wikibugs-loading-icon' );
		$loadingIcon.show();

		var toInsert = '== [[:' + reportedPage + ']] ==\n\n{{Талқылау статусы|жаңа}}\n' + content;

		//initialise the API
		var api = JsMwApi( mw.util.wikiScript( 'api' ) );
		//get the page object
		var pageHandler = api.page( this.reportPage );

		var reportPage = this.reportPage.replace( / /g, '_' );

		//EDIT THE "REPORT AN ERROR" PAGE
		pageHandler.edit( function( text, save_function, res ) {
			//process the wikitext of the page
			var sectionLine;
			if ( isFile ) {
				sectionLine = mw.msg( 'wikibugs-file-section-line' );
			} else {
				sectionLine = mw.msg( 'wikibugs-page-section-line' );
			}

			var newText = text.replace( sectionLine, sectionLine + '\n\n' + toInsert );
			if ( text === newText ) {
				// Could not find the section line - simply append;
				newText = text + '\n\n' + toInsert;
			}

			//save the new content
			save_function(
				newText, {
					summary: mw.msg( 'wikibugs-new-report', reportedPage ),
					minor: false
				}, function( res ) {
					if ( res && res.edit && res.edit.result && res.edit.result === 'Success' ) {
						//saved successfully - go to the report page
						window.location = mw.util.getUrl(reportPage) + '#' + encodeURIComponent(
							encodeURI( reportedPage ).replace( /%/g, '.' ) )
							.replace( /%/g, '.' )
							.replace( /\.3A/g, ':' )
							.replace( /\.20/g, '_' )
							.replace( /\(/g, '.28' )
							.replace( /\)/g, '.29' );

						if ( mw.config.get( 'wgPageName' ) === reportPage ) {
							//we're already there
							window.location.reload();
						}
					} else {
						//handle the error
						alert( mw.msg( 'wikibugs-ajax-error' ) );
						this.suppressSubmit = false;
						$loadingIcon.hide();
					}
			} );
		} );
	}
};

jQuery( document ).ready( function() {
	wikiBugsGadget.init();
} );