מדיה ויקי:Gadget-checkVoteRights.js

מתוך אקו-ויקי, מקום מפגש בנושאי אקולוגיה, חברה וכלכלה.
קפיצה לניווט קפיצה לחיפוש

הערה: לאחר השמירה, ייתכן שיהיה צורך לנקות את זיכרון המטמון (cache) של הדפדפן כדי להבחין בשינויים.

  • פיירפוקס / ספארי: להחזיק את המקש Shift בעת לחיצה על טעינה מחדש (Reload), או ללחוץ על צירוף המקשים Ctrl-F5 או Ctrl-R (במחשב מק: ⌘-R).
  • גוגל כרום: ללחוץ על צירוף המקשים Ctrl-Shift-R (במחשב מק: ⌘-Shift-R).
  • אינטרנט אקספלורר: להחזיק את המקש Ctrl בעת לחיצה על רענן (Refresh), או ללחוץ על צירוף המקשים Ctrl-F5.
  • אופרה: לפתוח תפריט ← הגדרות (במחשב מק: Opera ← העדפות) ואז ללחוץ על פרטיות ואבטחה ← מחק היסטוריית גלישה ← Cached images and files.
/**
 * סקריפט לבדיקת זכות הצבעה בדפי משתמש ובדפי הצבעה
 * נכתב על ידי קובי כרמל
 * version: 1.4
**/

'use strict';

function checkVoteRight(){

	var self = this,
		namespaceNumber = mw.config.get('wgNamespaceNumber');

	/** VARIABLES **/

	this.datetime = new Date(); // Date datetime details

	this.heMonths = ['ינואר', 'פברואר', 'מרץ', 'אפריל', 'מאי', 'יוני', 'יולי', 'אוגוסט', 'ספטמבר', 'אוקטובר', 'נובמבר', 'דצמבר']; // Object Array Hebrew months

	this.result = ''; // jQuery DOM Object

	this.user = ''; // String username

	this.voteStart = $('li:contains(תאריך תחילת ההצבעה)'); // jQuery DOM Object for vote pages

	/** METHODS **/

	Date.prototype.toMwDate = function(){ // converting to mw timestamp
		var format = self.format;
		return this.getFullYear() + format(this.getMonth() + 1) + format(this.getDate()) + format(this.getHours()) + format(this.getMinutes()) + '00';
	}

	this.addLink = function(){

		self.dpInit();
		var pl = mw.util.addPortletLink('p-tb', null, 'בדיקת זכות הצבעה', 't-checkvoterights')
		$(pl).click(function(e) {
			e.preventDefault();
			self.buildCvrPicker();
		});
	}

	this.buildCvrPicker = function(){

		if($('#cvr-dialog').length)
			return self.fillTime(), $('#cvr-dialog').show();

		var content = [
			$('<span>', {id: 'cvr-before'}),
			$('<span>', {id: 'cvr-after'}),
			$('<div>', {id: 'cvr-titlebar'}).append(
				'בחר תאריך ושעה:',
				$('<span>', {id: 'cvr-close', 'class': 'ui-icon ui-icon-closethick', title: 'סגירה'}).click(function(){
					$('#cvr-dialog').remove()
				})
			),
			$('<div>', {'class': 'cvr-row'}).append(
				$('<label>').text('תאריך:'),
				$('<input>', {'class': 'cvr-date'}).attr('maxlength', 10)
			),
			$('<div>', {'class': 'cvr-row'}).append(
				$('<label>').text('שעה:'),
				$('<select>', {id: 'cvr-hour'}),
				$('<select>', {id: 'cvr-minute'})
			),
			$('<div>', {id: 'cvr-result'}),
			$('<div>', {id: 'cvr-exec'}).html(
				$('<button>')
					.text('בדיקה')
					.click(function(){			
						if(namespaceNumber == 1 || namespaceNumber == 4){ // not a user (talk) page
							self.buildForVote();
							$('#cvr-dialog').hide();
						}
						else
							self.checkOne();
					})
			)
		];

		$('body').append($('<div>', {id: 'cvr-dialog'}).append(content));

		$('#cvr-dialog').css({
			top: $('#t-checkvoterights').offset().top - 37.5,
			left: $('#content').outerWidth() - $('#cvr-dialog').outerWidth()
		})

		$('.cvr-date').datepicker(); 

		$('.cvr-date').keypress(function(event){
			if(event.which == 8 || event.which == 47) // Backspace or Slash
				return;
			var val = this.value;
			if(val.length == 2 || val.length == 5)
				this.value += '/';
		});

		self.fillTime();
	}

	this.buildForVote = function(){
		$('.cvr-usersign').remove();
		self.links = mw.util.$content.find('a[href^="/wiki/%D7%9E%D7%A9%D7%AA%D7%9E%D7%A9"]');
		self.links.before(
			$('<span>', {'class': 'cvr-usersign'}).append(
				' (',
				$('<a>')
					.text('±')
					.click(function(){
						var check = new checkVoteRight();
						check.checkInVote($(this));
					}),
				') '
			)
		)
	}

	this.check = function(){

		self.setDateTime();

		if(isNaN(self.datetime))
			return self.updateStatus('יש להזין תאריך תקין', 'red');

		self.updateStatus('בודק מספר עריכות...', 'orange');
		var startDate = new Date(self.datetime);
		startDate.setDate(startDate.getDate() - 90);
		var param = {
			action: 'query',
			format: 'json',
			list: 'usercontribs',
			ucuser: self.user,
			ucprop: 'timestamp',
			ucnamespace: '0|6|8|10|12|14|100',
			ucdir: 'newer',
			uclimit: 100,
			ucstart: startDate.toMwDate(),
			ucend: self.datetime.toMwDate()
		}

		$.getJSON('/w/api.php', param, function(res){
			var contribs = res.query.usercontribs;

			if(contribs.length < 100) // no 100 edits
				return self.updateStatus('נכשל - אין 100 עריכות', 'red');
			self.checkSeniority();
		})
	}

	this.checkInVote = function(elem){
		self.result = elem;
		self.user = decodeURI(elem.parent().next().attr('href').split(':')[1]);
		self.check();
	}

	this.checkOne = function(){
		self.result = $('#cvr-result');
		self.user = mw.config.get( 'wgTitle' );
		self.check();
	}

	this.checkSeniority = function(){
		self.updateStatus('בודק ותק...', 'orange');
		var param = {
			action: 'query',
			format: 'json',
			list: 'usercontribs',
			ucuser: self.user,
			ucprop: 'timestamp',
			ucdir: 'newer',
			uclimit: 1
		}

		$.getJSON('/w/api.php', param, function(res){
			var firstEdit = new Date(res.query.usercontribs[0].timestamp),
				minSeniority = new Date(self.datetime);

			minSeniority.setDate(minSeniority.getDate() - 30);
			if(minSeniority < firstEdit)
				return self.updateStatus('נכשל - אין 30 ימי ותק', 'red');
			self.updateStatus('עבר', 'green');
		});
	}

	this.dpInit = function(){
		/* Hebrew initialisation for the UI Datepicker extension
		Written by Amir Hardon (ahardon at gmail dot com). */
		$.datepicker.regional['he'] = {
			closeText: 'סגור',
			prevText: '&#x3C;הקודם',
			nextText: 'הבא&#x3E;',
			currentText: 'היום',
			monthNames: self.heMonths,
			monthNamesShort: ['ינו','פבר','מרץ','אפר','מאי','יוני',
			'יולי','אוג','ספט','אוק','נוב','דצמ'],
			dayNames: ['ראשון','שני','שלישי','רביעי','חמישי','שישי','שבת'],
			dayNamesShort: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
			dayNamesMin: ['א\'','ב\'','ג\'','ד\'','ה\'','ו\'','שבת'],
			weekHeader: 'Wk',
			dateFormat: 'dd/mm/yy',
			firstDay: 0,
			isRTL: true,
			showMonthAfterYear: false,
			yearSuffix: ''
		};
		$.datepicker.setDefaults($.datepicker.regional['he']);
	}

	this.fillInVote = function(){
		var datetime = self.voteStart.text().split(':').splice(1,3).join(':').split(','),
			date = $.trim(datetime[1]).split(' '),
			time = $.trim(datetime[0]).split(':'),
			format = self.format;

		$('.cvr-date').val([format(date[0]), format($.inArray(date[1].substr(1), self.heMonths) + 1), date[2]].join('/'));

		$('#cvr-hour option').each(function(){
			this.selected = this.value == time[0];
		})

		$('#cvr-minute option').each(function(){
			this.selected = this.value == time[1];
		})
	}

	this.fillTime = function(){
		for(var h = 0; h < 24; h++)
			$('#cvr-hour').append($('<option>').text(self.format(h)));
		for(var m = 0; m < 60; m++)
			$('#cvr-minute').append($('<option>').text(self.format(m)));

		if(namespaceNumber == 4 && self.voteStart.length) // vote page with starting time
			self.fillInVote();
	}

	this.format = function(str){
		var num = '00' + str;
		return num.substr(num.length - 2);
	}

	this.setDateTime = function(){
		var date = $('.cvr-date').val().split('/'),
			datetime = new Date();
		datetime.setYear(date[2]);
		datetime.setMonth(date[1] - 1);
		datetime.setDate(date[0]);


		datetime.setHours($('#cvr-hour').val());
		datetime.setMinutes($('#cvr-minute').val());

		self.datetime = datetime;
	}

	this.updateStatus = function(result, color){
		self.result
			.text(result)
			.css('color', color);
	}
}

$(function(){
	
	var namespaceNumber = mw.config.get('wgNamespaceNumber');
	
	if(namespaceNumber >= 1 && namespaceNumber <= 4)
		mw.loader.using('jquery.ui', function(){
			var check = new checkVoteRight();
			check.addLink();
		})
})