# MediaWiki:Gadget-quickLinker.js

From faraghaib
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

- Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
- Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
- Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.

    /*
    from :https://he.wikipedia.org/wiki/מדיה_ויקי:Gadget-quickLinker.js
    This is script for quickly adding links to article from related articles. It is especially useful for orphan articles (invoked automatically), stub articles (invoked automatically) and new articles which usually have less links compared to long existing articles.
    */
    if ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) $(function(){

    var titleNoBrackets = /(.+?)( \(|$)/.exec(mw.config.get('wgTitle'));
    if (titleNoBrackets) titleNoBrackets = titleNoBrackets[1];
    else return;
    switch (mw.config.get('wgUserLanguage') )
    {
    	case 'fa':
    		mw.messages.set({
    			'qlinker-edit' : 'ویرایش سریع',
    			'qlinker-cancel' : 'لغو',
    			'linkify-summary': '[[ویکی‌پدیا:ابزار پیوندساز|ابزار پیوندساز]]: افزودن پیوند [[$1]] به متن',
    			'linkify-summary-seeAlso': '[[ویکی‌پدیا:ابزار پیوندساز|ابزار پیوندساز]]: افزودن پیوند [[$1]] به زیربخش جستارهای وابسته ',
    			'qlinker-save-success': '$1 با موفقیت ذخیره شد!',
    			'qlinker-save-continue': 'ذخیره',
    			'qlinker-skip': 'رها کردن صفحه',
    			'qlinker-invoke': 'افزودن سریع پیوند ',
    			'qlinker-sidelink': 'افزودن پیوند',
    			'qlinker-no-results': 'نتیجه‌ای یافت نشد',
    			'qlinker-confirm-masslink': 'این صفحه پیوندهای زیادی دارد آیا مطمئنید؟',
    			'qlinker-orphanpage': 'این مقاله بن‌بست یا یتیم است و در هیچ مقالهٔ دیگری به آن پیوند وجود ندارد.',
    			'qlinker-add-see-also': 'عنوان این صفحه در هیچ متنی ذکر نشده است، لطفاً مقاله‌ای را نام ببرید تا پیوند این صفحه را به زیربخش جستارهای وابسته‌اش بیافزایم',
    			'qlinker-seeAlso':'جستارهای وابسته',
    			'qlinker-preText':'مقاله‌مقصد',
    			'qlinker-disambig-temp-reg':'ابهام|نام کوچک'
    		});
    	break;
    	default:
    		mw.messages.set({
    			'qlinker-edit' : 'Quick edit',
    			'qlinker-cancel' : 'Cancel',
    			'linkify-summary': 'Adding link to [[$1]]',
    			'qlinker-save-success': '$1 has been saved successfully!',
    			'qlinker-save-continue': 'Save',
    			'qlinker-skip': 'Skip page',
    			'qlinker-invoke': 'Quickly add links',
    			'qlinker-sidelink': 'Add links',
    			'qlinker-no-results': 'No results found',
    			'qlinker-confirm-masslink': 'This page already has many links. Are you sure?'
    		});
    	break;
    }
    var patterns = {
    		tagNames: /<\/?[a-zA-Z\d]*/g,
    		color: /#(?:[abcdef0-9]{8}|[abcdef0-9]{6}|[abcdef0-9]{3})/gi,
    		fileNames: /(?:پرونده|File|تصویر|Image)\:.*?(?=\||\]|\n|$)/gi, // don't capture | after
    		fileParameter: /\|\s*(file|image|تصویر|پرونده)\s*\=\s*.*/gi,
    		nowikiTag:/<nowiki>.+?<\/nowiki>/g,
    		preTag:/<pre.*?>.*?<\/pre>/g,
    		insideHtmlComment: /<\!\-\-[\s\S]*?\-\->/g,
    		linksOnEnglishContext: /[a-z][\:\,\. ]*\[\[[\da-z\-\, ]*/gi,
    		mathTag: /<math.*?>[\s\S]*?<\/math>/g,
    		refname: /\<ref name\=.*?\>/g,
    		sourceTag: /(?:<source.*?>[\s\S]*?<\/source>|<syntaxhighlight.*?>[\s\S]*?<\/syntaxhighlight>|<code.*?>[\s\S]*?<\/code>|<timeline.*?>[\s\S]*?<\/timeline>)/g,
    		url: /\/\/.*?(?=[\s\n\|\}\]<]|$)/gi,	 // بدون https?: هم ممکن است
    		subsection: /\={1,}(?:[^\=\n\r]+)\={1,}/gi,
    		blackListTemp: /\{\{(?:جعبه اطلاعات دهستان ایران|جعبه روستای ایران|جعبه اطلاعات روستای ایران)(?:[^\}]+)\}\}/gi,
    		templateVar:/\|[^\n\|\=]+\=/gi
    }

    function createQuickEditorDialog(searchRes, safeMode){
    	function QuickEditorDialog( config ) {
    	  this.contextRgx = new RegExp('(.*[^\\[])(' + mw.util.escapeRegExp(titleNoBrackets) +')((?![^\\[\\{]*[\\]\\}]).*)', 'i');
    	  this.contextRgxLink = new RegExp('(.*\\[\\[)([^\\]]+?)\\|(' + mw.util.escapeRegExp(titleNoBrackets) +')(\\]\\].*)', 'i');
    	  this.pageI = -1;
    	  this.searchData = null;
    	  this.curPage = null;
    	  this.safeMode = safeMode;
    	  this.skipsCounter = 0;
    	  this.starttimestamp = null;
    	  this.timestamp = null;
    	  QuickEditorDialog.super.call( this, config );
    	}
    	OO.inheritClass( QuickEditorDialog, OO.ui.ProcessDialog );

    	// Specify a name for .addWindows()
    	QuickEditorDialog.static.name = 'QuickEditorDialog';
    	// Specify a title statically (or, alternatively, with data passed to the opening() method).
    	QuickEditorDialog.static.title = mw.msg('qlinker-edit');

    	QuickEditorDialog.static.actions = [
    	  { action: 'saveContinue', label: mw.msg('qlinker-save-continue'), flags: [ 'other', 'constructive' ] },
    	  { action: 'skipOne', label: mw.msg('qlinker-skip'), flags: [ 'other', 'progressive' ] },
    	  { label: mw.msg('qlinker-cancel'), flags: 'safe' }
    	];

    	// Customize the initialize() function: This is where to add content to the dialog body and set up event handlers.
    	QuickEditorDialog.prototype.initialize = function () {
    	  // Call the parent method
    	  QuickEditorDialog.super.prototype.initialize.call( this );
    	  // Create and append a layout and some content.
    	  this.content = new OO.ui.PanelLayout( { padded: true, expanded: true } );
    	  this.$body.append( this.content.$element );
    	};

    	QuickEditorDialog.prototype.getBodyHeight = function () {
    	  return 400;
    	};

    	QuickEditorDialog.prototype.getSetupProcess = function ( data ) {
    	  data = data || {};
    	  return QuickEditorDialog.super.prototype.getSetupProcess.call( this, data )
    	  .next( function () {
    		// Set up contents based on data
    		this.searchData = data.searchData.query;
    		this.starttimestamp = data.searchData.curtimestamp;
    		this.nextPage();
    	  }, this );
    	};

    	// Use the getActionProcess() method to specify a process to handle the
    	// actions (for the 'save' action, in this example).
    	QuickEditorDialog.prototype.getActionProcess = function ( action ) {
    	  var dialog = this;
    	  switch ( action ) {
    		case 'skipOne':
    			return new OO.ui.Process( function () {
    			  dialog.skipsCounter++;
    			  dialog.nextPage();
    			}, this );
    		case 'saveContinue':
    			return new OO.ui.Process( function () {
    			  dialog.savePage();
    			}, this );
    	  }

    	  // Fallback to parent handler.
    	  return QuickEditorDialog.super.prototype.getActionProcess.call( this, action );
    	};

    	QuickEditorDialog.prototype.savePage = function ( ) {
    		if (this.curPage)
    		{
    			var api = new mw.Api(), pagename = this.curPage;
    			api.post({
    				action: 'edit',
    				title: this.curPage,
    				summary: mw.msg('linkify-summary', mw.config.get('wgTitle')),
    				minor: '',
    				token: mw.user.tokens.get('csrfToken'),
    				text: this.text
    			}).done(function(d) {
    				if (d && d.edit && d.edit.result == 'Success')	mw.notify(mw.msg('qlinker-save-success', pagename));
    			});
    		}
    		var self = this;
    		if(this.safeMode) setTimeout(function(){ self.nextPage(); }, 5000/(self.skipsCounter+1));
    		else self.nextPage();
    	};

    	QuickEditorDialog.prototype.nextPage = function ( ) {
    		var m, mt, contextPre, contextPost, contextInner, contextInnerOld, newContext;
    		this.pageI++;
    		if (this.searchData.pageids.length <= this.pageI)
    		{
    			if(this.curPage === null) {
    				this.content.$element.html('<h1><a target="_blank" href="/wiki/Special:Search/'+encodeURI('"' + titleNoBrackets +'" -linksto:"'+mw.config.get('wgPageName') + '"')+'">'+mw.msg('qlinker-no-results')+'</a></h1>');
    				this.actions.setAbilities( {
    					saveContinue: false, skipOne: false
    				} );
    			} else {
    				this.close();
    			}
    			return;
    		}
    		var page = this.searchData.pages[this.searchData.pageids[this.pageI]],
    			pagecontent = page.revisions[0]['*'];
    			var pagecontentForRegex=pagecontent
    		var disambRgx=new RegExp('\{\{ *('+mw.msg('qlinker-disambig-temp-reg')+')', 'i');
    		if (disambRgx.exec(pagecontent)){self.nextPage();}
    		// test content
    		for (i in patterns) {
    			pagecontentForRegex=pagecontentForRegex.replace(patterns[i],'')
    		}
    		if (mt=this.contextRgx.exec(pagecontentForRegex)) {
    			m = this.contextRgx.exec(pagecontent)
    			if (m[0]==mt[0] ){
    			//if (m== mt){
    				contextPost = m[3];
    				contextInner = (m[2] == mw.config.get('wgTitle')) ? '[['+mw.config.get('wgTitle')+']]' : '[['+mw.config.get('wgTitle')+'|' + m[2] + ']]';
    				contextInnerOld = '';
    			}else{
    				m = null;
    			}
    		}
    		else if (mt=this.contextRgxLink.exec(pagecontentForRegex)) {
    			m = this.contextRgxLink.exec(pagecontent)
    			if (m[0]==mt[0] ){
    				if(m[2].endsWith(')'))
    				{
    					m = null; // other existing meaning
    				}
    				else
    				{
    					contextPost = m[3] == mw.config.get('wgTitle')? m[4] : '|' + m[3] + m[4];
    					contextInner = mw.config.get('wgTitle');
    					contextInnerOld = '<s>' + m[2] + (m[3] == mw.config.get('wgTitle')? '|' : '') + '</s>';
    				}
    			}else{
    				m = null;
    			}
    		}else{
    			m = null;
    		}

    		if ((page.title!=mw.config.get('wgTitle')) && m) {
    				var context = m[0];
    				contextPre = m[1];
    				newContext = contextPre+contextInner+contextPost;
    				this.content.$element.html('<h1><a href="/wiki/'+encodeURI(page.title)+'" target="_blank">'+page.title+'</a></h1><p>'+contextPre+contextInnerOld+'<b>'+contextInner+'</b>'+contextPost+'</p>');
    				this.curPage = page.title;
    				this.text = pagecontent.replace(context, newContext)
    				this.timestamp = page.revisions[0].timestamp;
    		}
    		else {
    			this.nextPage();
    		}
    	}

    	// Make the window.
    	var qlinkerEditor = new QuickEditorDialog( {
    	  size: 'medium'
    	} );

    	// Create and append a window manager, which will open and close the window.
    	var windowManager = new OO.ui.WindowManager();
    	$( 'body' ).append( windowManager.$element );

    	// Add the window to the window manager using the addWindows() method.
    	windowManager.addWindows( [ qlinkerEditor ] );

    	// Open the window!
    	windowManager.openWindow( qlinkerEditor,  { searchData: searchRes } );
    }

    function createAddLinksButton(){
    	var addLinksWizard = $(mw.util.addPortletLink(
    					'p-tb',
    					'#',
    					mw.msg('qlinker-sidelink'),
    					't-quicklinker',
    					mw.msg('qlinker-invoke'),
    					null,
    					'#t-whatlinkshere'
    	));

    	addLinksWizard.click(function(e){
    		protectedSearchQuery();
    		e.preventDefault();
    	});
    	return addLinksWizard;
    }

    function createAddLinksButtonSeeAlso(){
    	var addLinksWizard = $(mw.util.addPortletLink(
    					'p-tb',
    					'#',
    					mw.msg('qlinker-sidelink'),
    					't-quicklinker',
    					mw.msg('qlinker-invoke'),
    					null,
    					'#t-whatlinkshere'
    	));

    	addLinksWizard.click(function(e){
    		protectedSearchQuery();
    		e.preventDefault();
    	});
    	return addLinksWizard;
    }

    function AddSeeAlso(PsgeToAddSeeAlso,LinkedName)
    {
    	if (PsgeToAddSeeAlso)
    	{
    		//get text
    		// should page content by page title
    		(new mw.Api()).get({
    			format: 'json',
    			action: 'query',
    			titles: PsgeToAddSeeAlso,
    			prop: 'revisions',
    			rvprop: 'content',
    		}).then(function(data) {
    			var page = data.query.pages[Object.keys(data.query.pages)[0]];
    			var pagecontent = page.revisions[0]['*'];
    			// Cleaning the content
    			pagecontent=pagecontent.replace(/\= \=/gi,'==')
    			pagecontent=pagecontent.replace(/\=([^\= \n\r]+) *\=/gi,'= $1 =')
    			pagecontent=pagecontent.replace(/\={4,}/gi,'==')
    			// adding link to the content
    			var newPagecontent=pagecontent.replace('== ' + mw.msg('qlinker-seeAlso') + ' ==','== ' + mw.msg('qlinker-seeAlso') + ' ==\n* [[' + LinkedName + ']]\n')
    			if (newPagecontent==pagecontent) return false
    			//save new text
    			var api = new mw.Api();
    			api.post({
    				action: 'edit',
    				title: PsgeToAddSeeAlso,
    				summary: mw.msg('linkify-summary-seeAlso', mw.config.get('wgTitle')),
    				minor: '',
    				token: mw.user.tokens.get('csrfToken'),
    				text: newPagecontent
    			}).done(function(d) {
    				if (d && d.edit && d.edit.result == 'Success')	mw.notify(mw.msg('qlinker-save-success', PsgeToAddSeeAlso));
    				return true
    			});
    		});
    	}else{
    		 mw.notify(mw.msg('qlinker-no-results'));
    		 return false
    	}

    };

    function protectedSearchQuery()
    {
    	var api = new mw.Api();
    	api.get( {
    		action: 'query',
    		prop: 'linkshere',
    		lhlimit: 500,
    		titles: mw.config.get('wgPageName'),
    		indexpageids: 1
    	}).done(function(d) {
    		var isValid = true, safeMode = false;
    		if(d.query && d.query.pages && d.query.pages[d.query.pageids[0]] && d.query.pages[d.query.pageids[0]].linkshere && d.query.pages[d.query.pageids[0]].linkshere.length > 100)
    		{
    			/*isValid = confirm(mw.msg('qlinker-confirm-masslink'));
    			safeMode = true;*/
    			return;
    		}
    		if (!isValid) return;
    		searchLinksApi().done(function(q){
    			if (q.error) mw.notify(q.error.info);
    			if (!q.query || !q.query.pageids || q.query.pageids.length<=1) {
    				var PsgeToAddSeeAlso = prompt(mw.msg('qlinker-add-see-also'), mw.msg('qlinker-preText'));
    				if (PsgeToAddSeeAlso != null) {
    					var Result= AddSeeAlso(PsgeToAddSeeAlso, mw.config.get('wgPageName'))
    				}
    				return Result;
    			}
    			mw.loader.using('oojs-ui-windows', function() {	createQuickEditorDialog(q, safeMode) } );
    		});
    	})
    }
    function searchLinksApi() {
    	var api = new mw.Api();
    	return api.get( {
    		action: 'query',
    		generator: 'search',
    		gsrnamespace: 0,
    		gsrsearch: 'insource:"' + mw.util.escapeRegExp(titleNoBrackets) +'" -linksto:'+mw.config.get('wgPageName'),
    		gsrlimit: 50,
    		prop: 'revisions',
    		rvprop: 'content|timestamp',
    		indexpageids: 1,
    		curtimestamp: 1
    	});
    }
    if ($('.dmbox').length==0) {// Don't show the tool at Disambiguation pages because it is useless
    	if ($('.orphanpage, .stub').length>0) {
    		if ($('.orphanpage').length>0) mw.msg('qlinker-orphanpage')
    		searchLinksApi().done(function(d){
    			if (d.query && d.query.pageids && d.query.pageids.length>1) {
    				createAddLinksButton().css('font-weight', 'bold')
    			} else{
    				if (d.query && d.query.pageids){
    					createAddLinksButtonSeeAlso().css('font-weight', 'bold')
    				}
    			}
    		});
    	}
    	else {
    		createAddLinksButton();
    	}
    }
    });

Retrieved from "https://en.faraghaib.ir/w/index.php?title=MediaWiki:Gadget-quickLinker.js&oldid=349"