User:AmandaNP/PermissionOTRS.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | Documentation for this user script can be added at User:AmandaNP/PermissionOTRS. |
/** PermissionOTRS.js
// Adds OTRS permission template via the API. Other templates such as {OTRS pending} will be removed.
* @revision 21:40, 11 October 2016 (UTC)
* @license: under the terms of the MIT license
* @authors:
* Maintainer: [[User:Rillke]]
* Created by Bryan Tong Minh
* Amended by [[:de:User:DerHexer]], [[User:Guandalug]], DieBuche, [[User:Steinsplitter]]
* Partially rewritten by Perhelion
* Customized by DeltaQuad
* @required modules: mediawiki.util, jquery.ui, mediawiki.api
// <nowiki>
**/
/*global mediaWiki, jQuery*/
/*jshint curly:false, scripturl:true, forin:false*/
(function ( $, mw ) {
'use strict';
var user = mw.config.get('wgUserName'),
uGrp = mw.config.get('wgUserGroups'),
page = mw.config.get('wgPageName'),
sLink = '([[User:DeltaQuad/PermissionOTRS.js|Script]]) [[m:OTRS|OTRS]] ',
ticket = null,
edittoken = null,
content = null,
timestamp = null,
editform = ( /^(edit|submit)$/.test( mw.config.get('wgAction') ) ) ? $("#wpTextbox1") : null;
if ( mw.config.get('wgNamespaceNumber') !== 6 ||
$.inArray( 'autoconfirmed', uGrp ) === -1 ||
!user ) return;
function _prompt(text, OTRS) {
var OTRSfield = $('#field-otrs'); // there is already a ticket
if ( OTRSfield.length ) // try pre-fill the ticket
ticket = OTRSfield.attr('title').replace(/[^\n]+(\d{16})$/, '$1');
else if ( editform && /\{\{otrs[ _]received\|id=(\d{16})+[^\}\n]*\}\}/i.test( editform.val() ) )
ticket = RegExp.$1;
var type = 'errorbox',
title = (OTRS && OTRS.name)? OTRS.name : 'OTRS',
$ticket = $('<input>').attr({
'value' : ticket,
'type' : 'text',
'id' : 'OTRSdialog',
'maxlength' : 23, // for possible pre-phrase "Ticket#"
'size' : 17,
'class' : 'numbersOnly'
});
if (!text) {
title = 'INVALID ID';
text = 'You must enter a valid 16-digit ticket number.';
} else if (text === 'FAIL') {
title = text;
text = 'No suitable place found to insert template! Please add the template by hand.';
$ticket = '';
} else type = '';
text = $('<label>').attr({
'for' : 'OTRSdialog',
'class' : type
}).text(text);
$('<div>').append([text, $ticket]).dialog({
width : 400,
dialogClass : "wikiEditor-toolbar-dialog",
resizable : false,
modal : true,
title : title,
close : function () {
$(this).dialog("destroy");
$(this).remove();
},
buttons : [{
text : "OK",
click : function () {
ticket = ($ticket) ? $.trim($ticket.val()).replace(/^(Ticket)?#/, '') : ''; // cleanup input
$(this).dialog("close");
if (ticket) { // Check ticket validity
if (/^\d{16}$/.test(ticket))
return _getPage(OTRS);
_prompt('', OTRS);
}
}
}
]
});
}
function _addPermission(template, summary) {
var text = _cleanUp(content),
text_before = text,
regP = /( )*\|\s*[Pp]ermission( )*\=\s*([^\n]*\n)/,
regA = /( )*\|\s*[Aa]uthor( )*\=\s*[^\n]*\n/g; // fallback position, if no permission parameter
if (!regP.test(text)) {
if (!regA.test(text))
return _prompt('FAIL');
var l = regA.lastIndex,
s1 = RegExp.$1 || "", // leading whitespaces as indent?
s2 = (RegExp.$2)? " " : "", // whitespace on parameter?
sr = text.substr(l).search(/^\s*(\||\}\})/m); // try to got at template end
if (sr >= 0) {
sr += l; // insert to the end of information template
text = text.substr(0, sr) + s1 + "|permission" + s2 + "=" + s2 + template + "\n" + text.substr(sr);
} else
return _prompt('FAIL');
} else {
if ( text.indexOf( template ) > 0 )
return mw.notify( 'Same ticket already added…', { title: 'OTRS fail…', type: 'warn' } );
text = text.replace( regP, "$1|permission$2=$2" + template + "\n$3" );
}
if ( text_before === text )
return _prompt('FAIL');
content = text;
_savePage( sLink + summary );
}
var PermissionOTRS = function PermissionOTRS() {
_addPermission('{{PermissionOTRS|id=' + ticket + "|user=" + user + "}}",
'permission confirmed');
};
var OTRSreceived = function OTRSreceived() {
_addPermission('{{OTRS received|id=' + ticket +
'|year={{subst:' +
'#time:Y}}|month={{subst:' +
'#time:F}}|day={{subst:' +
'#time:j}}|user=' + user + '}}',
'insufficent for permission verification');
};
var OTRSprocess = function OTRSprocess() {
_addPermission('{{OTRS received|id=' + ticket +
'|notprocessed=1|year={{subst:' +
'#time:Y}}|month={{subst:' +
'#time:F}}|day={{subst:' +
'#time:j}}|user=' + user + '}}',
'email is being processed');
};
function _cleanUp(text) {
// ToDo: here could be loaded another cleanup module!?
text = text
.replace(/\=\= ?Summary ?\=\=/, '=={{int:filedesc}}==')
.replace(/\=\= ?Licensing ?\=\=/, '=={{int:license-header}}==')
.replace(/\{\{OTRS[ _\-](pending|received)[^\}\n]*\}\}\s?/ig, '')
.replace(/\{\{[Nn]o[ _](OTRS[ _])?permission[^\}\n]*\}\}\s*/g, '\n')
.replace(/\{\{[Dd]elete[^\}\n]*\}\}\s?/g, '')
.replace(/\{\{[Dd]i\-no permission[^\}\n]*\}\}\s*/g,'')
.replace(/^\|\s*([A-Z][^=\n{}\|?!.]+\s*\=)/gm,
function (m, p){ return '|' + p.toLowerCase(); } // lowercase parameter name default
);
return $.trim(text);
}
function _apiFail( code, r ) {
if ( code === "http" ) {
console.log( "HTTP error: " + r.textStatus );
} else if ( code === "ok-but-empty" ) {
console.log( "Got an empty response from the server" );
} else {
console.log( "API error: " + code );
}
mw.notify( 'There was an error processing your request.\n\t\t\t API-error-code:' +
code + '\n\n\t\t\t\tPlease try again.',
{ title: 'Error!', autoHide: 0, type: 'error' } );
}
function _getPage(OTRS) {
if (!editform) {
mw.notify( '…request to tag with "' + OTRS.name + '"\n with Ticket#: ' + ticket,
{ title: 'Processing…' } );
new mw.Api().get({
prop : "info|revisions",
intoken : "edit",
rvprop : "content|timestamp",
titles : page
}).done( function (r) {
mw.notify( 'Got page contents…', { title: 'Processing…' } );
var pages = r.query.pages;
for (var id in pages) {
if (pages.hasOwnProperty(id)) {
pages = pages[id];
edittoken = pages.edittoken;
content = pages.revisions[0]['*'];
timestamp = pages.revisions[0].timestamp;
return OTRS();
}
}
}).fail( function ( code, r ){ _apiFail( code, r ); } );
} else {
content = editform.val();
return OTRS();
}
}
function doneMsg() {
return mw.notify( 'OTRS ticket successfully inserted.',
{ title: 'Done!' } );
}
function _savePage(summary) {
if (!editform) {
new mw.Api().post({
action : 'edit',
summary : summary,
watchlist : 'preferences',
title : page,
token : edittoken,
text : content,
notminor : 1
}).done( function () {
doneMsg().done( function () {
location.reload();
} );
}).fail( function ( code, r ){ _apiFail( code, r ); } );
} else {
$('#wpMinoredit').prop( 'checked', 0 );
editform.val( content );
$('#wpSummary').val( function ( i, v ) {
return $.trim( v.replace( summary, "" ) + " " + summary );
} );
doneMsg();
}
}
function dialogOTRS( e, OTRS ) {
e.preventDefault();
function chkuGrp( b ){
if ( !b )
return mw.notify( 'You are not authorized for this function!',
{ title: 'OTRS fail!', type: 'warn' } );
_prompt( 'Ticket ID (16 digit number):', OTRS );
}
if ( $.inArray( 'otrs-member', mw.config.get('wgGlobalGroups') ) >= 0 || $.inArray( 'sysop', uGrp ) >= 0 )
chkuGrp( 1 );
else // run only for non-admins and no global OTRS-membership found?
new mw.Api().get( {
meta : "globaluserinfo",
guiuser : user,
guiprop : "groups",
} ).done( function (r) {
chkuGrp( ( $.inArray( 'otrs-member', r.query.globaluserinfo.groups ) >= 0 ) );
} ).fail( function ( code, r ){ _apiFail( code, r ); } );
}
var bReceive, bConfirm; // booleans; addPortletLinks only if needed
$('#mw-hidden-catlinks li').children('a').each(function () {
if ( this.text && !( bReceive && bConfirm ) ) { // check cats
if ( /^Items with (?:ticket )?OTRS permission confirmed/.test( this.text ) )
bConfirm = bReceive = 1;
else if ( /^OTRS received/.test( this.text ) )
bReceive = 1;
}
});
mw.loader.using([ 'mediawiki.util', 'jquery.ui', 'mediawiki.api' ], function () {
if (!bConfirm) {
$( mw.util.addPortletLink('p-tb', '#', 'OTRS - Confirmed') )
.click( function ( e ) { dialogOTRS( e, PermissionOTRS ); } );
if (!bReceive)
$( mw.util.addPortletLink('p-tb', '#', 'OTRS - Insufficent') )
.click( function ( e ) { dialogOTRS( e, OTRSreceived ); } );
$( mw.util.addPortletLink('p-tb', '#', 'OTRS - Not processed') )
.click( function ( e ) { dialogOTRS( e, OTRSprocess ); } );
}
});
}( jQuery, mediaWiki ));
// EOF </nowiki>