Ugrás a tartalomhoz

MediaWiki:Common.js

A Wikipédiából, a szabad enciklopédiából
A lap korábbi változatát látod, amilyen Krenair (vitalap | szerkesztései) 2017. augusztus 13., 05:04-kor történt szerkesztése után volt. Ez a változat jelentősen eltérhet az aktuális változattól. (Maintenance: mw:RL/MGU / mw:RL/JD - phab:T169385 - deprecated in jQuery 3.0)

Megjegyzés: közzététel után frissítened kell a böngésződ gyorsítótárát, hogy lásd a változásokat.

  • Firefox / Safari: tartsd lenyomva a Shift gombot és kattints a Frissítés gombra a címsorban, vagy használd a Ctrl–F5 vagy Ctrl–R (Macen ⌘–R) billentyűkombinációt
  • Google Chrome: használd a Ctrl–Shift–R (Macen ⌘–Shift–R) billentyűkombinációt
  • Edge: tartsd nyomva a Ctrl-t, és kattints a Frissítés gombra, vagy nyomj Ctrl–F5-öt
/* Az ide elhelyezett JavaScript kód minden felhasználó számára lefut az oldalak betöltésekor. */
/* <nowiki> kategorizálás megakadályozására */

/*
 Wikis függvények és segédletek ($.wiki)
*/
(function($){
	$.wiki =  {};
	
	/* $.wiki.contentSelector: visszaadja magát a szócikket tartalmazó
	 elem szelektorát a skintől függően */
	var skin = mw.config.get('skin');
	if (skin == "modern") $.wiki.contentSelector = "#mw_contentholder";
	else if (skin == "standard" || skin == "nostalgia" || skin == "cologneblue") $.wiki.contentSelector = "#article";
	else $.wiki.contentSelector = "#bodyContent";
	
	/* Ajaxon keresztül lekéri a megadott oldalt opcionális paraméterekkel */
	$.wiki.getPage = function(settings) {
		if (typeof(settings.pageName) === "undefined" || settings.pageName === "")
			settings.error.call();
		var ajaxSettings = {
			url: $.wiki.wikiEntryLink(settings.pageName, (typeof(settings.params) == "undefined" ? {} : settings.params))
		};
		if (typeof(settings.async) != "undefined") ajaxSettings = $.extend(ajaxSettings, {async: settings.async});
		if (typeof(settings.success) != "undefined") ajaxSettings = $.extend(ajaxSettings, {success: settings.success});
		if (typeof(settings.error) != "undefined") ajaxSettings = $.extend(ajaxSettings, {error: settings.error});
		return $.ajax(ajaxSettings);
	};
	
	/* Ajaxon keresztül lekéri a megadott oldal nyers változatát opcionális további paraméterekkel */
	$.wiki.getPageRaw = function(settings) {
		if (typeof(settings.params) != "undefined")
			settings.params.action = "raw";
		else
			settings.params = {action: "raw"};
		return $.wiki.getPage(settings);
	};
	
	/* Egyszerű wikilink generálása lapnévből: https://hu.wikipedia.org/wiki/Pagename */
	$.wiki.wikiLink = function(page) {
		var prep = page.replace(/ /g, "_");
		return mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace(/\$1/g, prep);
	};
	
	/* Link a belépési ponthoz (index.php): https://hu.wikipedia.org/w/index.php?title=Pagename
	 Opcionálisan további paraméterekkel
	*/
	$.wiki.wikiEntryLink = function(page, args) {
		var prep = page.replace(/ /g, "_");
		prep = mw.config.get('wgServer') + mw.config.get('wgScript') + "?title=" + prep;
		$.each(args, function(key, value) {
			prep = prep + "&" + key + "=" + value;
		});
		return prep;
	};
})(jQuery);

/*
== Segédfüggvények ==
*/
function addLoadEvent( func ) {
	mw.log.warn( 'Elavult addLoadEvent(), használj helyette $()-t vagy mw.hook(...).add()-et. Stack trace:\n', new Error().stack );
	$( func );
}

function getCookie(name) {
	mw.log.warn( 'Elavult getCookie(), használj helyette mw.cookie.get()-et. Stack trace:\n', new Error().stack );
	var cookieText;
	var cookiePos = document.cookie.indexOf(name + '=');
	if(cookiePos!=-1) {
		var results = document.cookie.match(name+'=(.*?)(;|$)');
		if(results) cookieText = decodeURIComponent(results[1]);
		return cookieText;
	} else return null;
}
function setCookie(name, text, expires) {
	mw.log.warn( 'Elavult setCookie(), használj helyette mw.cookie.set()-et. Stack trace:\n', new Error().stack );
	mw.cookie.set( name, text, { expires: expires, prefix: '' } );
}

function cleanHtmlTags(str) {
	return str.replace(/<>/g, '');
}

$.fn.log = function(msg) {
	if (!window.console || !console.log) return;
	if (msg) {
		if (typeof msg == 'string') {
			console.log('%s: %o', msg, this);
		} else {
			console.log('%o -> %o', this, msg);
		}
	} else {
		console.log(this);
	}
	return this;
};

// for inlog gadget
$.startInlog = $.fn.startInlog = function(config) {
	if (!$.inlog) return;
	$.inlog({
		enabled: true,
		thisValue: true
	});
	return this;
};
$.endInlog = $.fn.endInlog = function(config) {
	if (!$.inlog) return;
	$.inlog(false);
	return this;
};

/*
== Kezdőlap összes Wikipédia listája ==
*/
( function ( mw ) {
	var conf = mw.config.get( [ 'wgTitle', 'wgMainPageTitle', 'wgNamespaceNumber' ] );
	if ( conf.wgTitle === conf.wgMainPageTitle && conf.wgNamespaceNumber === 0 ) {
		mw.loader.using( 'mediawiki.util', function () {
			$( function () {
				mw.util.addPortletLink( 'p-lang', '//meta.wikimedia.org/wiki/List_of_Wikipedias',
				                        'Teljes lista', 'interwiki-completelist', 'A Wikipédiák teljes listája' );
			} );
		} );
	}
}( mediaWiki ) );

/*
== Elrejthető üzenetek ==
*/
window.addHideButton = ( function ( mw, $ ) {
	function hideElement( e ) {
		var $this = $( this ),
			$box = $this.parent(),
			name = $box.attr( 'id' );
		
		mw.cookie.set( 'hide-' + name, '1', 7*24*3600 ); // 1 hét
		$this.hide();
		$box.hide();
		e.preventDefault();
		return false;
	}
	
	function addHideButton( element ) {
		var $this = $( element );
		if ( !$this.length ) return;
		var isHidden = mw.cookie.get( 'hide-' + $this.attr( 'id' ) );
		if ( isHidden ) {
			$this.hide();
		} else {
			var $button = $( '<a>' )
				.attr( 'href', '#' )
				.attr( 'id', 'hide-' + $this.attr( 'id' ) )
				.addClass( 'hideButton' )
				.attr( 'title', 'Üzenet elrejtése egy hétre' )
				.click( hideElement )
				.text( '[elrejt]' )
				.appendTo( $this );
		}
	}
	return addHideButton;
}( mediaWiki, jQuery ) );

/* 
== Képfeltöltés ==
*/
if ( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Upload' )
	mw.loader.load( 'ext.gadget.uploadpage' );

/*
== Legördülő menü és extra gombok az edittools-ba ==
*/
if ( mw.config.get( 'wgAction' ) in { edit: 1, submit: 1 } || mw.config.get( 'wgCanonicalSpecialPageName' ) == 'Upload' )
	mw.loader.load( 'ext.gadget.edittools' );
/*
== Ékezetes karakterek bejelentkezéshez ==
*/
( function ( mw, $ ) {
	if ( mw.config.get( 'wgCanonicalSpecialPageName' ) !== 'UserLogin' ) return;
	function insertText( e ) {
		e.preventDefault();
		mw.toolbar.insertTags( $( this ).text(), '', '' );
		return false;
	}
	
	function installLoginChars( $content ) {
		var $loginchars = $content.find( '#loginchars' );
		if ( !$loginchars.length ) return;
		mw.loader.using( 'mediawiki.toolbar', function () {
			$.each( 'áéíóöőúüűÁÉÍÓÖŐÚÜŰ'.split( '' ), function ( i, s ) {
				$loginchars.append(
					' ',
					$( '<a>' )
						.attr( 'href', '#' )
						.text( s )
						.click( insertText )
				);
			} );
			$loginchars.css( 'display', 'block' );
		} );
	}
	mw.hook( 'wikipage.content' ).add( installLoginChars );
}( mediaWiki, jQuery ) )

/*
== Címek javítása ==
*/
/**
 * For pages that have something like Template:Lowercase, replace the title, but
 * only if cut-and-pastable as a valid wikilink (e.g. iPod's title is updated but
 * C# is not an equivalent wikilink, so C Sharp doesn't have its main title changed).
 * 
 * The function looks for a banner like this:
 * <div id="RealTitleBanner"> ... <span id="RealTitle">title</span> ... </div>
 * An element #DisableRealTitle disables this function.
 */
/**
 * Set disableRealTitle = true in your common.js to disable.
 */
var disableRealTitle = false;
( function ( mw, $ ) {
	// Don't display the RealTitle when editing, as it's apparently inconsistent (doesn't show when editing sections or not previewing)
	if ( !mw.config.get( 'wgIsArticle' ) ) return;
	function fixArticleTitle( $content ) {
		var $realTitleBanner = $content.find( '#RealTitleBanner' );
		var $realTitle = $realTitleBanner.find( '#RealTitle' );
		if (
			disableRealTitle ||
			!$realTitleBanner.length ||
			!$realTitle.length ||
			$content.find( '#DisableRealTitle' ).length
		) return;
		var realTitleHTML = $realTitle.html();
		var realTitleText = $realTitle.text();
		
		// contains HTML that will be ignored when cut-n-pasted as a wikilink
		var containsTooMuchHTML = /</.test( realTitleHTML.replace( /<\/?(sub|sup|small|big)>/gi, '' ) );
		// Calculate whether the title is pasteable
		var verifyTitle = realTitleText.replace( /^ +/, '' ); // trim left spaces
		verifyTitle = verifyTitle[0].toUpperCase() + verifyTitle.slice( 1 ); // uppercase first character
		
		// If the namespace prefix is there, remove it on our verification copy.
		// If it isn't there, add it to the original realValue copy.
		if ( mw.config.get( 'wgNamespaceNumber' ) !== 0 ) {
			var localNamespace = mw.config.get( 'wgPageName' ).split( ':' )[ 0 ];
			var canonicalNamespace = mw.config.get( 'wgCanonicalNamespace' );
			if (
				canonicalNamespace == verifyTitle.slice( 0, canonicalNamespace.length ).replace( / /g, '_' ) &&
				verifyTitle.charAt( canonicalNamespace.length ) == ':'
			) {
				verifyTitle = verifyTitle.slice( canonicalNamespace.length + 1 );
			} else if (
				localNamespace == verifyTitle.slice( 0, localNamespace.length ).replace( / /g, '_' ) &&
				verifyTitle.charAt( localNamespace.length ) == ':'
			) {
				verifyTitle = verifyTitle.slice( localNamespace.length + 1 );
			} else {
				realTitleText = localNamespace.replace( /_/g, ' ' ) + ':' + realTitleText;
				realTitleHTML = localNamespace.replace( /_/g, ' ' ) + ':' + realTitleHTML;
			}
		}
		
		// Verify whether wgTitle matches
		verifyTitle = verifyTitle
			.replace( /[\s_]+/g, ' ' ) // underscores and multiple spaces to single spaces
			.replace( /^\s+/, '' ).replace( /\s+$/, '' ); // trim left and right spaces
		verifyTitle = verifyTitle[0].toUpperCase() + verifyTitle.slice( 1 ); // uppercase first character
		document.title = realTitleText + ' – Wikipédia';
		if ( verifyTitle !== mw.config.get( 'wgTitle' ) ) return;
		$( function () {
			var $h1 = $( 'h1:first' );
			if ( !$h1.length ) return;
			$h1.html( containsTooMuchHTML ? realTitleText : realTitleHTML );
			if ( !containsTooMuchHTML ) $realTitleBanner.hide();
		} );
	}
	
	mw.hook( 'wikipage.content' ).add( fixArticleTitle );
} ( mediaWiki, jQuery) );

/*
== IRC login ==
*/
// this script looks for the element with id "irclogon", and replaces its contents 
// with a login form that redirects to the Mibbit IRC gateway
( function () {
	if ( mw.config.get( 'wgAction' ) in { edit: 1, submit: 1 } ) {
		return;
	}
 
	function loadLoginForm( $content ) {
		$content.find( '#irclogin' ).empty().append(
			$( '<form>' ).attr( {
				method: 'get',
				action: '//webchat.freenode.net/',
				target: '_blank',
				name: 'loginform'
			} ).append(
				$( '<input type="text"> ').attr( {
					name: 'Nickname',
					size: 25
				} ).val( nickify( mw.config.get('wgUserName') ) ).focus( function () {
					clear_text(this);
				} ),
 
				$( '<input type="submit"> ').val( 'Belépés' ),
				$( '<input type="hidden"> ').attr( 'name', 'channels' ).val( '#wikipedia-hu' ),
				$( '<input type="hidden"> ').attr( 'name', 'prompt' ).val( '0' )
			)
		);
	}

	function nickify( s ) {
		if ( s == null ) {
			return 'anon' + Math.floor( Math.random() * 100 );
		}
		s = s.toLowerCase();
		s = s.replace(" ", "_");
		s = s.replace(/á/g, 'a');
		s = s.replace(/é/g, 'e');
		s = s.replace(/í/g, 'i');
		s = s.replace(/[óő]/g, 'o');
		s = s.replace(/[úű]/g, 'u');
		s = s.replace(/[^a-z0-9_-]/g, '');
		return s || 'badname' + Math.floor( Math.random() * 100 );
	}
 
	var irclogin_cleared = 0;
	function clear_text( field ) {
		if ( irclogin_cleared === 0 ) {
			irclogin_cleared = 1;
			field.value = '';
		}
	}

	mw.hook( 'wikipage.content' ).add( loadLoginForm );
} ) ();

/*
== Változtatható rendezésű táblázatok: ékezetes betűk, magyar írásmódú számok rendezése ==
*/

// buta, de legalább működik
// rendező kód: http://git.wikimedia.org/blob/mediawiki%2Fcore/master/resources%2Fjquery%2Fjquery.tablesorter.js
// okos, de nem működő kód: https://hu.wikipedia.org/w/index.php?title=MediaWiki:Common.js&diff=prev&oldid=14463042
(function() {
	var accented = 'áéíóúöőüűÁÉÍÓÚÖŐÜŰ',
	    basic = 'aeiouoouuAEIOUOOUU',
	    tableSorterCollation = {};
	for (var i = 0; i < accented.length; i++) {
		tableSorterCollation[accented[i]] = basic[i];
	}
	mw.config.set( 'tableSorterCollation', tableSorterCollation);
}());

/*
== Kéthasábos forráslista kikapcsolása, ha <4 forrás van ==
*/
function dynamicMultiColumn( $content ) {
	$content.find( 'div.ref-1col > div' ).each( function () {
		if ( $( this ).find( 'li' ).length < 4 ) {
			$( this ).css( {
				'-moz-column-count': '',
				'-webkit-column-count': '',
				'column-count': ''
			} );
		}
	} );
}
mw.hook( 'wikipage.content' ).add( dynamicMultiColumn );

/*
== Keresési kifejezések naplózása névtelenül a Squidek által ==
*/

// Change search forms so they send to an URL which has the search term in the 
// path (not just in the query part). This in necessary for getting search 
// statistics from the squid logs.
// Based on [[wikt:de:MediaWiki:If-search.js]].

function SubSearch(formId, inputId) {
  var form = $('#' + formId);
  var input = $('#' + inputId);
  if (input.val() == '') {
    delimiter = '';
  } else {
    delimiter = '/';
  }
  form.attr('action', mw.config.get('wgArticlePath').replace('$1', oSEAp + delimiter + encodeURIComponent(input.val())));
  // Try to remove <input name="title"> from the <form>
  form.find('input[name="title"]:first').remove();
}

function fixSearchForm(formId, inputId) {
  $('#' + formId).submit(function() {
    SubSearch(formId, inputId);
  });
}

$(document).ready(function() {
  fixSearchForm('searchform', 'searchInput');
  fixSearchForm('search', 'searchText');
  fixSearchForm('powersearch', 'powerSearchText');
  fixSearchForm('bodySearch', 'bodySearchIput');
  if (!$('#searchform').length) {
    oSEAp = '';
  } else if ($('#searchform').attr('action').indexOf(mw.config.get('wgScript')) > -1) {
    oSEAp = $('#searchform').find('input').val();
  } else {
    oSEAp = $('#searchform').attr('action').replace(/^.*\/([^\/]+)$/, '$1');
 }
});

/*
== Szerkesztői lapok testreszabása ==
- Megjelenő cím cseréje szerkesztő(vita), Wikipédia(-vita) és portálnévterekben
- Megjelenő alcím cseréje és virtuális kategóriák megjelenítése szerkesztőnévtérben
- Betűtípus és háttérszín módosítása szerkesztő(vita) névtérben
*/
if (
	[
		2, 3, // szerkesztői lap és vitája
		4, 5, // Wikipédia-lap és vitája
		100 // portál
	].indexOf( mw.config.get( 'wgNamespaceNumber' ) ) > -1
) {
	mw.loader.load( 'ext.gadget.userpage-customization' );
}

/*
== Erőforrástakarékos üzenet a TranslateWikin való MediaWiki-felület-fordításra ==
*/
$(document).ready(function() {
  if (mw.config.get('wgNamespaceNumber') == 8 && mw.config.get('wgPageName').match(/\.js$|\.css$/) === null) {
    $('<div></div>')
      .addClass('editwarning')
      .addClass('plainlinks')
      .addClass('translateWikiMessage')
      .html('<b>Ha olyan üzenetet fordítasz, amely nem Wikipédia-specifikus, akkor azt a <a href="//translatewiki.net" class="external text" style="color: #002bb8;" title="translatewiki.net" rel="nofollow">Translatewikiben</a> tedd, hogy így minden magyar nyelvű Wikimedia-projekt számára elérhető legyen!</b> (<a href="//translatewiki.net/wiki/' + mw.config.get('wgPageName') + '/hu" class="external text" style="color: #002bb8;" title="' + mw.config.get('wgPageName') + ' magyar változatának megtekintése a Translatewikiben" rel="nofollow">→ezen üzenet megtekintése a Translatewikiben</a>, <a href="//translatewiki.net/wiki/' + mw.config.get('wgPageName') + '/hu?action=edit" class="external text" style="color: #002bb8;" title="' + mw.config.get('wgPageName') + ' magyar változatának szerkesztése a Translatewikiben" rel="nofollow" style>szerkesztés</a>)')
      .appendTo($('#siteSub'));
  }
});

/*
== Flagrev bugfix ==
*/

$(function() {
//  $('#mw-fr-revisiontag').css("display", "block");
  $('#mw-fr-revisiontoggle').attr('title', null);
});

/*
== Figyelmeztető ikon a kezdőlap vitáján, ha hiányzó allapok vannak ==
*/

if (mw.config.get('wgPageName') == 'Vita:Kezdőlap') {
   $('#header-container').on('tabsetReady', function(e) {
      if ($.trim($('#urgent-tasks').text())) {
         $('#ts-headerTabs li a:contains("Tennivalók")').append(
            $('<img src="/media/wikipedia/commons/c/c0/Exclamation.png"/>').css('margin-left', '5px')
         );
      }
   });
}