پرش به محتوا

مدیاویکی:Gadget-NewPagesFeed.js

از دانشنامه علوم انسانی
نسخهٔ تاریخ ۳۰ آوریل ۲۰۲۴، ساعت ۱۴:۲۲ توسط imported>Jeeputer (پیش‌نویس تابع پالایش)

نکته: پس از انتشار ممکن است برای دیدن تغییرات نیاز باشد که حافظهٔ نهانی مرورگر خود را پاک کنید.

  • فایرفاکس / سافاری: کلید Shift را نگه دارید و روی دکمهٔ Reload کلیک کنید، یا کلید‌های Ctrl-F5 یا Ctrl-R را با هم فشار دهید (در رایانه‌های اپل مکینتاش کلید‌های ⌘-R)
  • گوگل کروم: کلیدهای Ctrl+Shift+R را با هم فشار دهید (در رایانه‌های اپل مکینتاش کلید‌های ⌘-Shift-R)
  • Edge: کلید Ctrl را نگه‌دارید و روی دکمهٔ Refresh کلیک کنید، یا کلید‌های Ctrl-F5 را با هم فشار دهید
// Script to Modernize [[Special:NewPages]];
// Developed by [[User:Jeeputer]] and [[User:WASP-Outis]]

$.when(mw.loader.using(['mediawiki.api', 'mediawiki.util']), $.ready)
	.then(function() {
		
		if (mw.config.get('wgCanonicalSpecialPageName') !== "Newpages") return;
		
		mw.loader.load('https://fa.wikipedia.org/w/index.php?title=User:Jeeputer/newPagesFeed.css&action=raw&ctype=text/css', 'text/css');
		var api = new mw.Api();
		
		// To search for "<ref>" tags in text of each article
		function checkRefs(text) {
			var out = /(class=\"reference-text|id=\"cite_note|مشارکت‌کنندگان ویکی‌پدیا)/g.test(text) ? '' : ' • فاقد منبع';
			return out;
		}
		
		function filter(formValues) {
			var elemets = {
				patrolled: {
					display: $('.npf-article-box:not(.npf-notpatrolled)').css('display'),
					elelemt: $('.npf-article-box:not(.npf-notpatrolled)')
				}
			};
			
			for (var key in Object,keys(formValues)) {
				if (formValues[key].state) {
					if (elemets[key].display !== 'none') {
						elemets[key].element.slideUp('slow');
					}
				} else {
					elemets[key].element.slideDown('slow');
				}
			}
			
		}
		
		function liftWing(requirements) {
            var inferenceUrl = "https://api.wikimedia.org/service/lw/inference/v1/models/fawiki-damaging:predict";
            let headers = new Headers({
                "Content-Type": "application/json"
            });
            let liftWingData = {"rev_id": Number(requirements.id)};
            fetch(inferenceUrl, {
                method: "POST",
                headers: headers,
                body: JSON.stringify(liftWingData)
            }).then(
            	response => response.json()
    		).then(
    			inferenceData => {
                    var DamagingScore = inferenceData.fawiki.scores[requirements.id].damaging.score.probability.true; // Liftwing Score
                    if (requirements.ref != '') {                               // refrences Score
                        DamagingScore = DamagingScore + 0.85;
                    }
                    if (requirements.patrol && !requirements.csd) {				// Patrolled and there's no csd tag
                        DamagingScore = DamagingScore - 0.3;
                    }

                    if (DamagingScore > 0.5) {
                        $('#npf-ores-' + requirements.id).show();
                        $('#npf-ores-' + requirements.id).css('color', 'red');
                        $('#npf-ores-' + requirements.id).attr('title', 'احتمال خرابکاری زیاد');
                    }
                    else if (DamagingScore <= 0.5 && DamagingScore >= 0.11) {
                        $('#npf-ores-' + requirements.id).show();
                        $('#npf-ores-' + requirements.id).css('color', 'orange');
                        $('#npf-ores-' + requirements.id).attr('title', 'احتمال خرابکاری متوسط');
                    }
                    else if (DamagingScore < 0.11) {
                        $('#npf-ores-' + requirements.id).show();
                        $('#npf-ores-' + requirements.id).css('color', 'green');
                        $('#npf-ores-' + requirements.id).attr('title', 'احتمال خرابکاری کم');
                    }
                }
            );
		}
		
		function parsePage(id, firstid, notPatrolled) {
		    return api.get({
		    	action: 'parse',
		    	oldid: id, 
		    	format: 'json'
		    }).done(function(data) {
		    	var refTest = checkRefs(data.parse.text["*"]);
		    	var liftWingRequirements = {
		    		csd: false,
		    		ref: refTest,
		    		patrol: !notPatrolled,
		    		id: firstid
		    	};
		        var cats = data.parse.categories;
		        for (var c = 0; c < cats.length; c++) {
		        	var catName = cats[c]['*'];
		        	if (catName === 'مقاله‌های_نامزد_حذف_سریع') {
		        		var $csdElement = $('<span id="npf-csd-' + id + '">')
		        				.attr('title', 'این صفحه نامزد حذف سریع شده است')
		        				.css({
                                    'display': 'none',
                                    'width': '150px'
                                })
		        				.addClass('npf-row-content-left npf-csd')
		        				.text('نامزد حذف سریع');
		        		$('div#npf-comment-' + id).append($csdElement);
                        liftWingRequirements.csd = true;
		        		$csdElement.toggle(2000);
		        	} else if (catName === 'صفحه‌های_حذف_زمان‌دار') {
		        		var $prodElement = $('<span>')
		        				.attr('title', 'این صفحه نامزد حذف زمان‌دار شده است')
		        				.css('display', 'none')
		        				.addClass('npf-row-content-left npf-csd')
		        				.text('نامزد حذف زمان‌دار');
		        		$('div#npf-comment-' + id).append($prodElement);
		        		$prodElement.toggle(2000);
		        	} else if (catName === 'مقاله‌های_نامزد_حذف') {
		    			var afdUrl = $(data.parse.text['*']).find('a:contains("نظرخواهی مربوط به این صفحه")')[0].href;
		        		var $afdElement = $('<a>')
		        				.attr({
		        					'title': 'این صفحه در نظرخواهی برای حذف نامزد است',
		        					'href': afdUrl
		        				})
		        				.css('display', 'none')
		        				.addClass('npf-row-content-left npf-afd')
		        				.text('نظرخواهی برای حذف');
		        		$('div#npf-comment-' + id).append($afdElement);
		        		$afdElement.toggle(2000);
		        	}
		        }
		        
		        // Evaluate Lift Wing data
		        liftWing(liftWingRequirements);
		        
		        var contentCats = cats.filter(function(cat) {
		        	return typeof(cat.hidden) !== "string";
		        });
		        var langlinks = data.parse.langlinks || 0;
                var enLangLink = false;
                if (langlinks) {
	                for (var li = 0; li < langlinks.length; li++) {
	                    if (langlinks[li].lang === 'en') {
	                    	// [ url, English title ]
	                        enLangLink = [langlinks[li].url, langlinks[li]['*']];
	                        break;
	                    }
	                }
                }
                
		        var categoriesCount = contentCats.length ? mw.language.convertNumber(contentCats.length) : 'فاقد';
		        var langLinksCount = langlinks.length ? mw.language.convertNumber(langlinks.length) : 'فاقد';
		        // Replace "در حال تجزیهٔ صفحه…" with categories and langlinks count
		        $('#cat-iw-container-' + id).fadeOut(
		            1000,
		            function() {
		                $('#cat-iw-container-' + id).empty();
		                $('#cat-iw-container-' + id)
							.attr('title', 'اطلاعات رده‌ها و میان‌ویکی‌ها')
			                .append(
	                            '<span id="npf-cat-count-' + id + '">' + categoriesCount + ' رده</span> • ' +
	                            langLinksCount + ' میان‌ویکی' +
	                            // Append English language link if exists
	                            (enLangLink
	                            	? ' (<a href="' + enLangLink[0] + '" title="' + enLangLink[1] + '">en</a>)'
	                            	: ''
                            	) +
								'<span id="npf-ref-existenz-' + id + '">' + refTest + '</span>'
                        	);
                        // Font color = red if we have no categories
                        if (contentCats.length < 1) $('#npf-cat-count-' + id).addClass('npf-nocat');
                        // Show updated content
		                $('#cat-iw-container-' + id).fadeIn(1000);
		            }
				);
                ///// EXTLINKS SPAN
                $("#npf-extlinks-" + id).mouseenter(function() {        			// Outlinks mouse event handler
                    handleHover("#npf-extlinks-" + id, data.parse.externallinks);
				});
		    });
		}
		
		// Handle external links box
        function handleHover(spanid, extLinks) {
        	var listContent,
        		hasExtLinks = !!extLinks.length;
        	if (hasExtLinks) {
	        	var links = extLinks.map(function(link) {
	        		return '<a href="' + link + '" target="_blank">' + decodeURIComponent(link) + '</a>';
	        		
	        	});
	            listContent = '<li>' + links.join('</li><li>') + '</li>';
        	} else {
        		listContent = '<span>این صفحه فاقد پیوند بیرونی است</span>';
        	}
            
            var formattedText = '<ul>' + listContent + '</ul>';
            var spanpos = $(spanid).offset();
            
            var $box = $('<div>')
            	.html(formattedText)
            	.addClass('extlink-box')
            	.css({
	                top: spanpos.top + $(spanid).outerHeight() - 30 + "px",
	                left: spanpos.left + "px"
            	});

			$("body").append($box);
            $(spanid).add($box).mouseleave(function(event) {
                if (event.target === $box[0]) {
                    $box.remove();
				}
			});
        }
		
		// Utility function to create container div for each row
	    function createRow(content) {
	        var $row = $('<div>').addClass('npf-row').append(content);
	        return $row;
	    }
	    
		function createBox(ingredients) {
		    var htmlID = 'npf-box-' + ingredients.revid;						// Unique ID (e.g. npf-header-39298943) for each article box
		    var $box = $('<div>')
		        .attr('id', htmlID)
		        .addClass('npf-article-box');
		        
	        if (ingredients.notPatrolled) {										// Gray background for non-patrolled pages
	        	$box.addClass('npf-notpatrolled')
	        	.attr('title', 'مقالهٔ گشت نخورده');
	        }
	        
		    var $header = $('<div>')
		    	.attr('id', 'npf-header-' + ingredients.revid)
		    	.addClass('npf-flex-row')
                .append($('<span>')
                    .addClass('npf-row-content-right')
                    .css('display', 'inline-flex')
                    .append($('<span>')
                        .css('display', 'inline-flex')
                        .append(
        		            $('<a>')
        	                .attr({
        	                	'href': mw.util.getUrl(ingredients.title),
        	                	'title': ingredients.title
        	                })
        	                .addClass('npf-header-title')
        	                .text(ingredients.title)
        		        )
                        .append($('<span>')
                            .addClass('npf-ores-indicator')
                            .attr({
                                'id': 'npf-ores-' + ingredients.firstrevid
                            })
                            .css({
                                'display': 'none' // Adding the color yellow
                            })
                            .text('⚠')
                        )
                    )
                    .append(
                        $('<span>')
                        .addClass('npf-hist-link')
                        .append('(')
                        .append(
                            $('<a>')
                            .attr({
                                'href': mw.util.getUrl('Special:PageHistory/' + ingredients.title),
                                'title': 'تاریخچهٔ صفحهٔ ' + ingredients.title
                            })
                            .text('تاریخچه')
                        )
                        .append(')')
                    )
                    .append($('<span>')
                        .attr('title', 'حجم صفحه')
                        .css('margin-left', '5px')
                        .text(' · ' + ingredients.bytes + ' بایت')
                    )
                    .append($('<span>')
                        .attr({
                        	'title': 'پیوندهای بیرونی استفاده شده در این مقاله',
                        	'id': 'npf-extlinks-'+ ingredients.revid
                        })
                    	.append(' · ')
                        .append($('<span>')
                        	.css('border-bottom', '2px dotted Blue')
                        	.text('پیوندهای بیرونی')
                    	)
                    )
                )
		        .append($('<span>')
		        	.addClass('npf-row-content-left')
		        	.append($('<a>')
		        		.attr({
		        			'href': mw.util.getUrl('Special:Permalink/' + ingredients.firstrevid),
		        			'title': 'پیوند دائمی به نخستین نسخهٔ صفحه'
		        		})
		        		.text(ingredients.date)
	        		)
		    	);
		
		    var $details = $('<div>')
		    	.attr('id', 'npf-details-' + ingredients.revid)
		    	.addClass('npf-flex-row')
		        .append($('<span>')
		        	.attr('title', 'ایجاد کنندهٔ صفحه')
		        	.addClass('npf-row-content-right')
			        .append($('<span>')
			        	.append('ایجاد شده توسط ')
			        	.append($('<a>')
			        		.addClass('npf-creator' + (ingredients.newUser ? ' new' : ''))
				        	.attr('href', mw.util.getUrl('کاربر:' + ingredients.creator))
				        	.text(ingredients.creator)
			        	)
			    	)
		        	.append($(ingredients.userTools))
		    	)
		        .append($('<span>')
		        	.attr({
		        		'id': 'cat-iw-container-' + ingredients.revid,
		        		'title': 'لطفاً صبر کنید…'
		        	})
		        	.addClass('npf-row-content-left')
		        	.text('در حال تجزیهٔ صفحه…')
	        	);
		    	
		    var $comment = $('<div>')
		    	.attr('id', 'npf-comment-' + ingredients.revid)
		    	.addClass('npf-flex-row')
		        .append($('<span>')
		        	.addClass('npf-row-content-right')
		        	.attr('title', 'خلاصهٔ ویرایش در زمان ایجاد صفحه')
		            .append('خلاصهٔ ویرایش: ')
		            .append($('<span>')
		                .addClass('npf-italic')
		                .append($(ingredients.comment))
                    )
		        );
		    
		    $box.append(createRow($header));
		    $box.append(createRow($details));
		    $box.append(createRow($comment));
		    
		    // Append tag container only if we have some tags
		    if (ingredients.tags && ingredients.tags.length > 0) {
		        var $tagElements = $('<span>');
		        for (var t = 0; t < ingredients.tags.length; t++) {
		            $tagElements.append($(ingredients.tags[t]));
		        }
		        var $tags = $('<div>')
		            .attr('id', 'npf-tags-' + ingredients.revid)
		            .addClass('npf-tags-container')
		            .append($('<span>')
		            	.attr('title', 'برچسب‌های نصب شده بر نخستین ویرایش')
		                .append('برچسب‌ها: ')
		                .append($tagElements)
		            );
		        $box.append(createRow($tags));
		    }
		    
		    $('#npf-parent-container').append($box);
		    $('.mw-pager-navigation-bar').eq(1).insertAfter($box);				// Move navigation bar to its initial location
            
		}
		var listItems = $('#mw-content-text > section.mw-pager-body > ul > li'), 
		    boxIngredients = [], // Will be populated by information from list items without any API calls
		    i;
		for (i = 0; i < listItems.length; i++) {
		    var hasTags = $(listItems[i])[0].children[9];						// ...children[8] is always for edit tags
		    boxIngredients[i] = {
		        notPatrolled: !!$(listItems[i]).hasClass('not-patrolled'),
		        title: $(listItems[i])[0].children[1].title,
		        url: $(listItems[i])[0].children[1].href,
		        date: $(listItems[i])[0].children[1].innerText,
		        revid: $($(listItems[i])[0]).attr('data-mw-revid'),				// Latest revision's ID is available as "data-mw-revid" attribute for each list item
		        firstrevid: $(listItems[i])[0].children[1].href.match(/\oldid\=(\d*)/)[1], // First revision's ID
                bytes: ($(listItems[i])[0].children[5].innerText).replace(/\[(.*) بایت\]/, '$1'),
		        creator: $(listItems[i])[0].children[6].innerText,
		        userTools: $(listItems[i])[0].children[7],
		        comment: ($(listItems[i])[0].children[8])
		    };
		    if (hasTags) { // We have some tags
		        boxIngredients[i].tags = [];
		        for (var ei = 0; ei < $(listItems[i])[0].children[9].children.length; ei++) {
		            var $element = $($(listItems[i])[0].children[9].children[ei]);
		            if ($element.hasClass('mw-tag-marker')) {					// Prevent pushing "برچسب‌ها" to array
		            	// Store tags as jquery object so we can add
		            	// them to the box with without modifications
		                boxIngredients[i].tags.push($element);
		            }
		        }
		    }
		    if ($($(listItems[i])[0].children[6]).hasClass('new')) {
		    	boxIngredients[i].newUser = true;
		    }
		}
		$('#mw-content-text section.mw-pager-body > ul').remove();
        $('#mw-content-text section.mw-pager-body').append('<div id="npf-parent-container"></div>');	            // Append main parent container
		for (i = 0; i < boxIngredients.length; i++) {
		    createBox(boxIngredients[i]);										// Create boxes
		    parsePage(boxIngredients[i].revid, boxIngredients[i].firstrevid, boxIngredients[i].notPatrolled);		// Update categories and langlinks after we have the api response
		}
});