User:Tomtomn00/GRWS: Difference between revisions
>Tomtomn00 No edit summary |
>Tomtomn00 fix |
||
Line 1: | Line 1: | ||
==''' | ==The '''''current''''' LocalSettings.php looks '''ROUGHLY''' like what is below== | ||
'''PLEASE NOTE THAT THIS IS IN .php - BUT RUBY MAKES IT LOOK BETTER HERE''' | '''PLEASE NOTE THAT THIS IS IN .php - BUT RUBY MAKES IT LOOK BETTER HERE''' | ||
<code ruby> | <code ruby> |
Revision as of 18:55, 7 April 2012
The current LocalSettings.php looks ROUGHLY like what is below
PLEASE NOTE THAT THIS IS IN .php - BUT RUBY MAKES IT LOOK BETTER HERE
<?php
- This file was automatically generated by the MediaWiki 1.18.0
- installer. If you make manual changes, please keep track in case you
- need to recreate them later.
- See includes/DefaultSettings.php for all configurable settings
- and their default values, but don't forget to make changes in _this_
- file, not there.
- Further documentation for configuration settings may be found at:
- http://www.mediawiki.org/wiki/Manual:Configuration_settings
- Protect against web entry
if ( !defined( 'MEDIAWIKI' ) ) {
exit;
}
- Uncomment this to disable output compression
- $wgDisableOutputCompression = true;
$wgSitename = "Roblox Wiki";
$wgMetaNamespace = "Roblox Wiki";
- The URL base path to the directory containing the wiki;
- defaults for all runtime URL paths are based off of this.
- For more information on customizing the URLs please see:
- http://www.mediawiki.org/wiki/Manual:Short_URL
$wgScriptPath = "/wiki"; #I think here it's just index
$wgScriptExtension = ".php";
- The relative URL path to the skins directory
$wgStylePath = "$wgScriptPath/skins";
- The relative URL path to the logo. Make sure you change this from the default,
- or else you'll overwrite your logo when you upgrade!
$wgLogo = "$wgStylePath/common/images/wiki.png";
- UPO means: this is also a user preference option
$wgEnableEmail = true;
$wgEnableUserEmail = true; # UPO
$wgEmergencyContact = ""; ##removed##
$wgPasswordSender = ""; ##removed##
$wgEnotifUserTalk = false; # UPO
$wgEnotifWatchlist = false; # UPO
$wgEmailAuthentication = true;
- Database settings
$wgDBtype = ""; ##What type of Database type is it? - normally MySql
$wgDBserver = ""; ##Whatever the Database server is - often LocalHost
$wgDBname = ""; ##Whatever the Database name is
$wgDBuser = ""; ##Whatever the Database username is
$wgDBpassword = ""; ##Whatever the Database password is
- MySQL specific settings
$wgDBprefix = "";
- MySQL table options to use during installation or update
$wgDBTableOptions = "ENGINE=InnoDB, DEFAULT CHARSET=binary";
- Experimental charset support for MySQL 4.1/5.0.
$wgDBmysql5 = false;
- Shared memory settings
$wgMainCacheType = CACHE_NONE;
$wgMemCachedServers = array();
- To enable image uploads, make sure the 'images' directory
- is writable, then set this to true:
$wgEnableUploads = false;
- $wgUseImageMagick = true;
- $wgImageMagickConvertCommand = "/usr/bin/convert";
- InstantCommons allows wiki to use images from http://commons.wikimedia.org
$wgUseInstantCommons = false;
- If you use ImageMagick (or any other shell command) on a
- Linux server, this will need to be set to the name of an
- available UTF-8 locale
$wgShellLocale = "en_US.utf8";
- If you want to use image uploads under safe mode,
- create the directories images/archive, images/thumb and
- images/temp, and make them all writable. Then uncomment
- this, if it's not already uncommented:
- $wgHashedUploadDirectory = false;
- If you have the appropriate support software installed
- you can enable inline LaTeX equations:
$wgUseTeX = false;
- Set $wgCacheDirectory to a writable directory on the web server
- to make your wiki go slightly faster. The directory should not
- be publically accessible from the web.
- $wgCacheDirectory = "$IP/cache";
- Site language code, should be one of ./languages/Language(.*).php
$wgLanguageCode = "en-gb";
$wgSecretKey = ""; # U NO GET MAI KEY!
- Site upgrade key. Must be set to a string (default provided) to turn on the
- web installer while LocalSettings.php is in place
$wgUpgradeKey = ""; # U NO GET MAI KEY!
- Default skin: you can change the default skin. Use the internal symbolic
- names, ie 'standard', 'nostalgia', 'cologneblue', 'monobook', 'vector':
$wgDefaultSkin = "vector";
- For attaching licensing metadata to pages, and displaying an
- appropriate copyright notice / icon. GNU Free Documentation
- License and Creative Commons licenses are supported so far.
- $wgEnableCreativeCommonsRdf = true;
$wgRightsPage = ""; # Set to the title of a wiki page that describes your license/copyright
$wgRightsUrl = "";
$wgRightsText = "";
$wgRightsIcon = "";
- $wgRightsCode = ""; # Not yet used
- Path to the GNU diff3 utility. Used for conflict resolution.
$wgDiff3 = "";
- The following permissions were set based on your choice in the installer
$wgGroupPermissions['*']['edit'] = false;
- Query string length limit for ResourceLoader. You should only set this if
- your web server has a query string length limit (then set it to that limit),
- or if you have suhosin.get.max_value_length set in php.ini (then set it to
- that value)
$wgResourceLoaderMaxQueryLength = -1;
- End of automatically generated settings.
- Add more configuration options below.
$wgEnableUploads = true; # Enable uploads
$wgFileExtensions[] = 'exe';
$wgFileBlacklist = array_diff( $wgFileBlacklist, array ('exe') ); #Won't let users upload dodgy .exe files.
$wgStrictFileExtensions = false;
$wgFileExtensions = array('png','gif','jpg','jpeg','doc','xls','mpp','pdf','ppt','tiff','bmp','docx', 'xlsx', 'pptx','ps','odt','ods','odp','odg');
$wgGroupPermissions['Reviewer']['user'] = true;
$wgGroupPermissions['Reviewer']['move'] = false;
$wgGroupPermissions['Reviewer']['review'] = true;
$wgGroupPermissions['Reviewer']['validate'] = true;
$wgGroupPermissions['Reviewer']['autoreview'] = true;
$wgGroupPermissions['Reviewer']['unreviewedpages '] = true;
$wgFlaggedRevsStatsAge = false;
$wgFlaggedRevsAutopromote['days'] = 90; # days since registration
$wgFlaggedRevsAutopromote['edits'] = 150; # total edit count
$wgFlaggedRevsAutopromote['excludeDeleted'] = true; # exclude deleted edits from 'edits' count above?
$wgFlaggedRevsAutopromote['spacing'] = 3; # spacing of edit intervals
$wgFlaggedRevsAutopromote['benchmarks'] = 15; # how many edit intervals are needed?
$wgFlaggedRevsAutopromote['recentContentEdits'] = 10; # $wgContentNamespaces edits in recent changes
$wgFlaggedRevsAutopromote['totalContentEdits'] = 30; # $wgContentNamespaces edits
$wgFlaggedRevsAutopromote['uniqueContentPages'] = 10; # $wgContentNamespaces unique pages edited
$wgFlaggedRevsAutopromote['editComments'] = 5; # how many edit comments used?
$wgFlaggedRevsAutopromote['email'] = true; # user must be emailconfirmed?
$wgFlaggedRevsAutopromote['userpageBytes'] = 0; # if userpage is needed, what is the min size?
$wgFlaggedRevsTags = array(
'accuracy' => array( 'levels' => 3, 'quality' => 2, 'pristine' => 4 ),
'depth' => array( 'levels' => 3, 'quality' => 2, 'pristine' => 4 ),
'tone' => array( 'levels' => 3, 'quality' => 1, 'pristine' => 4 ),
);
$wgFlagRestrictions = array(
'accuracy' => array( 'review' => 1 ),
'depth' => array( 'review' => 2 ),
'style' => array( 'review' => 3 ),
);
$wgGroupPermissions['*']['edit'] = false;
$wgGroupPermissions['*']['move'] = false;
$wgGroupPermissions['*']['createtalk'] = false;
$wgGroupPermissions['sysop']['writer'] = true;
$wgGroupPermissions['Bureaucrat']['userrights'] = true;
$wgGroupPermissions['Bureaucrat']['noratelimit'] = true;
$wgGroupPermissions['writer']['edit'] = true;
$wgGroupPermissions['writer']['createtalk'] = true;
$wgGroupPermissions['writer']['move'] = false;
$wgGroupPermissions['writer']['delete'] = false;
$wgGroupPermissions['Editor']['edit'] = true;
$wgGroupPermissions['Editor']['editprotected'] = true;
$wgGroupPermissions['Editor']['protect'] = true;
However, giving us more rights, you could stick this at the end of it.
$wgGroupPermissions['writer']['unblockself'] = false; /* Cannot block anyway */
$wgGroupPermissions['editor']['unblockself'] = true; /* Can block */
$wgGroupPermissions['sysop']['unblockself'] = true;
$wgUseRCPatrol = true; /* Allow patrol right */
$wgGroupPermissions['writer']['patrol'] = true; /* Autopatrolled right, stops reviewing */
$wgGroupPermissions['editor']['patrol'] = true; /* Some users are only editors */
$wgGroupPermissions['sysop']['patrol'] = true;
$wgGroupPermissions['writer']['move'] = false; /* writers write, editors edit */
$wgGroupPermissions['editor']['move'] = true; /* If we're hired, we're trusted? + some users only editor*/
$wgGroupPermissions['sysop']['move'] = true;
/* Lets put in delete! (my suggestion (Tomtomn00)) */
$wgGroupPermissions['writer']['delete'] = false; /* writers write, editors edit */
$wgGroupPermissions['editor']['delete'] = true; /* If we're hired, we're trusted? + some users only editor*/
$wgGroupPermissions['sysop']['delete'] = true;
/* NOTE: Most sysop things will already be enabled */
Gadget
This is just some popup gadget I've got in .js.
// STARTFILE: main.js // ********************************************************************** // ** changes to this file affect many users. ** // ** please discuss on the talk page before editing ** // ********************************************************************** // ** if you do edit this file, be sure that your editor recognizes it ** // ** as utf8, or the weird and wonderful characters in the namespaces ** // ** below will be completely broken. You can check with the show ** // ** changes button before submitting the edit. ** // ** test: مدیا מיוחד Мэдыя ** // **********************************************************************
// Trying to shove as many of these as possible into the pg (popup globals) object
function pg(){}; // dummy to stop errors
window.pg = {
re: {}, // regexps
ns: {}, // namespaces
string: {}, // translatable strings
wiki: {}, // local site info
misc: {}, //
option: {}, // options, see newOption etc
optionDefault: {}, // default option values
flag: {}, // misc flags
cache: {}, // page and image cache
structures: {}, // navlink structures
timer: {}, // all sorts of timers (too damn many)
counter: {}, // .. and all sorts of counters
current: {}, // state info
endoflist: null
};
window.pop = { // wrap various functions in here
init: {},
util: {},
endoflist: null
};
function popupsReady() {
if (!window.pg) { return false; }
if (!pg.flag) { return false; }
if (!pg.flag.finishedLoading) { return false; }
return true;
}
/// Local Variables: /// /// mode:c /// /// End: /// // ENDFILE: main.js // STARTFILE: actions.js function setupTooltips(container, remove, force, popData) { log('setupTooltips, container='+container+', remove='+remove); if (!container) { //<NOLITE> // the main initial call if (getValueOf('popupOnEditSelection') && window.doSelectionPopup && document && document.editform && document.editform.wpTextbox1) { document.editform.wpTextbox1.onmouseup=doSelectionPopup; } //</NOLITE> // article/content is a structure-dependent thing container = defaultPopupsContainer(); }
if (!remove && !force && container.ranSetupTooltipsAlready) { return; } container.ranSetupTooltipsAlready = !remove;
var anchors; anchors=container.getElementsByTagName('A'); setupTooltipsLoop(anchors, 0, 250, 100, remove, popData); }
function defaultPopupsContainer() {
if (getValueOf('popupOnlyArticleLinks')) {
return document.getElementById('mw_content') || document.getElementById('content') || document.getElementById('article') || document;
} return document;
}
function setupTooltipsLoop(anchors,begin,howmany,sleep, remove, popData) { log(simplePrintf('setupTooltipsLoop(%s,%s,%s,%s,%s)', arguments)); var finish=begin+howmany; var loopend = min(finish, anchors.length); var j=loopend - begin; log ('setupTooltips: anchors.length=' + anchors.length + ', begin=' + begin + ', howmany=' + howmany + ', loopend=' + loopend + ', remove=' + remove); var doTooltip= remove ? removeTooltip : addTooltip; // try a faster (?) loop construct if (j > 0) { do { var a=anchors[loopend - j]; if (typeof a=='undefined' || !a || !a.href) { log('got null anchor at index ' + loopend - j); continue; } doTooltip(a, popData); } while (--j); } if (finish < anchors.length) { setTimeout(function() { setupTooltipsLoop(anchors,finish,howmany,sleep,remove,popData);}, sleep); } else { if ( !remove && ! getValueOf('popupTocLinks')) { rmTocTooltips(); } pg.flag.finishedLoading=true; } }
// eliminate popups from the TOC // This also kills any onclick stuff that used to be going on in the toc function rmTocTooltips() { var toc=document.getElementById('toc'); if (toc) { var tocLinks=toc.getElementsByTagName('A'); var tocLen = tocLinks.length; for (j=0; j<tocLen; ++j) { removeTooltip(tocLinks[j], true); } } }
function addTooltip(a, popData) { if ( !isPopupLink(a) ) { return; } a.onmouseover=mouseOverWikiLink; a.onmouseout= mouseOutWikiLink; a.onmousedown = killPopup; a.hasPopup = true; a.popData = popData; }
function removeTooltip(a) { if ( !a.hasPopup ) { return; } a.onmouseover = null; a.onmouseout = null; if (a.originalTitle) { a.title = a.originalTitle; } a.hasPopup=false; }
function removeTitle(a) { a.title=; if (a.originalTitle) { return; } a.originalTitle=a.title; }
function restoreTitle(a) { if ( a.title || !a.originalTitle ) { return; } a.title = a.originalTitle; }
function registerHooks(np) { var popupMaxWidth=getValueOf('popupMaxWidth');
if (typeof popupMaxWidth == 'number') { var setMaxWidth = function () { np.mainDiv.style.maxWidth = popupMaxWidth + 'px'; np.maxWidth = popupMaxWidth;
try {
// hack for IE // see http://www.svendtofte.com/code/max_width_in_ie/ // use setExpression as documented here on msdn: http://tinyurl dot com/dqljn
if (np.mainDiv.style.setExpression) { np.mainDiv.style.setExpression( 'width', 'document.body.clientWidth > ' + popupMaxWidth + ' ? "' +popupMaxWidth + 'px": "auto"'); }
} catch (errors) { errlog( "Running on IE8 are we not?: " + errors ); }
}; np.addHook(setMaxWidth, 'unhide', 'before'); } //<NOLITE> if (window.addPopupShortcuts && window.rmPopupShortcuts) { np.addHook(addPopupShortcuts, 'unhide', 'after'); np.addHook(rmPopupShortcuts, 'hide', 'before'); } //</NOLITE> }
function mouseOverWikiLink(evt) {
if (!window.popupsReady || !window.popupsReady()) { return; }
if (!evt && window.event) {evt=window.event};
return mouseOverWikiLink2(this, evt);
}
function footnoteTarget(a) { var aTitle=Title.fromAnchor(a); // We want ".3A" rather than "%3A" or "?" here, so use the anchor property directly var anch = aTitle.anchor; if ( ! /^(cite_note-|_note-|endnote)/.test(anch) ) { return false; }
var lTitle=Title.fromURL(location.href); if ( lTitle.toString(true) != aTitle.toString(true) ) { return false; }
var el=document.getElementById(anch); while ( el && typeof el.nodeName == 'string') { var nt = el.nodeName.toLowerCase(); if ( nt == 'li' ) { return el; } else if ( nt == 'body' ) { return false; } else if ( el.parentNode ) { el=el.parentNode; } else { return false; } } return false; }
function footnotePreview(x, navpop) {
setPopupHTML('' + x.innerHTML, 'popupPreview', navpop.idNumber,
getValueOf('popupSubpopups') ? function() { setupTooltips(document.getElementById('popupPreview' + navpop.idNumber)); } : null); }
// var modid=0; // if(!window.opera) { window.opera={postError: console.log}; }
function modifierKeyHandler(a) { return function(evt) { // opera.postError('modifierKeyHandler called' + (++modid)); // opera.postError(+evt + modid); // for (var i in evt) { // opera.postError( + modid + ' ' + i + ' ' + evt[i]); // } // opera.postError(+evt.ctrlKey + modid); var mod=getValueOf('popupModifier'); if (!mod) { return true; }
if (!evt && window.event) {evt=window.event}; // opera.postError('And now....'+modid); // opera.postError(+evt+modid); // opera.postError(+evt.ctrlKey+modid);
var modPressed = modifierPressed(evt); var action = getValueOf('popupModifierAction');
// FIXME: probable bug - modifierPressed should be modPressed below? if ( action == 'disable' && modifierPressed ) { return true; } if ( action == 'enable' && !modifierPressed ) { return true; }
mouseOverWikiLink2(a, evt); }; }
function modifierPressed(evt) { var mod=getValueOf('popupModifier'); if (!mod) { return false; }
if (!evt && window.event) {evt=window.event}; // opera.postError('And now....'+modid); // opera.postError(+evt+modid); // opera.postError(+evt.ctrlKey+modid);
return ( evt && mod && evt[mod.toLowerCase() + 'Key'] );
}
function dealWithModifier(a,evt) { if (!getValueOf('popupModifier')) { return false; } var action = getValueOf('popupModifierAction'); if ( action == 'enable' && !modifierPressed(evt) || action == 'disable' && modifierPressed(evt) ) { // if the modifier is needed and not pressed, listen for it until // we mouseout of this link. restoreTitle(a); var addHandler='addEventListener'; var rmHandler='removeEventListener'; var on=; if (!document.addEventListener) { addHandler='attachEvent'; rmHandler='detachEvent'; on='on'; } if (!document[addHandler]) { // forget it return; }
a.modifierKeyHandler=modifierKeyHandler(a);
switch (action) { case 'enable': document[addHandler](on+'keydown', a.modifierKeyHandler, false); a[addHandler](on+'mouseout', function() { document[rmHandler](on+'keydown', a.modifierKeyHandler, false); }, true); break; case 'disable': document[addHandler](on+'keyup', a.modifierKeyHandler, false); }
return true; } return false; }
function mouseOverWikiLink2(a, evt) { if (dealWithModifier(a,evt)) { return; } if ( getValueOf('removeTitles') ) { removeTitle(a); } if ( a==pg.current.link && a.navpopup && a.navpopup.isVisible() ) { return; } pg.current.link=a;
if (getValueOf('simplePopups') && pg.option.popupStructure===null) { // reset *default value* of popupStructure setDefault('popupStructure', 'original'); }
var article=(new Title()).fromAnchor(a); // set global variable (ugh) to hold article (wikipage) pg.current.article = article;
if (!a.navpopup) { // FIXME: this doesn't behave well if you mouse out of a popup // directly into a link with the same href if (pg.current.linksHash[a.href] && false) { a.navpopup = pg.current.linksHash[a.href]; } else { a.navpopup=newNavpopup(a, article); pg.current.linksHash[a.href] = a.navpopup; pg.current.links.push(a); } } if (a.navpopup.pending===null || a.navpopup.pending!==0) { // either fresh popups or those with unfinshed business are redone from scratch simplePopupContent(a, article); } a.navpopup.showSoonIfStable(a.navpopup.delay);
getValueOf('popupInitialWidth');
clearInterval(pg.timer.checkPopupPosition); pg.timer.checkPopupPosition=setInterval(checkPopupPosition, 600);
if(getValueOf('simplePopups')) { if (getValueOf('popupPreviewButton') && !a.simpleNoMore) { var d=document.createElement('div'); d.className='popupPreviewButtonDiv'; var s=document.createElement('span'); d.appendChild(s); s.className='popupPreviewButton'; s['on' + getValueOf('popupPreviewButtonEvent')] = function() { a.simpleNoMore=true; nonsimplePopupContent(a,article); } s.innerHTML=popupString('show preview'); setPopupHTML(d, 'popupPreview', a.navpopup.idNumber); } return; }
if (a.navpopup.pending!==0 ) { nonsimplePopupContent(a, article); } }
// simplePopupContent: the content that is shown even when simplePopups is true function simplePopupContent(a, article) { /* FIXME hack */ a.navpopup.hasPopupMenu=false; a.navpopup.setInnerHTML(popupHTML(a)); fillEmptySpans({navpopup:a.navpopup});
if (getValueOf('popupDraggable')) { var dragHandle = getValueOf('popupDragHandle') || null; if (dragHandle && dragHandle != 'all') { dragHandle += a.navpopup.idNumber; } setTimeout(function(){a.navpopup.makeDraggable(dragHandle);}, 150); }
//<NOLITE>
if (getValueOf('popupRedlinkRemoval') && a.className=='new') {
setPopupHTML('
'+popupRedlinkHTML(article), 'popupRedlink', a.navpopup.idNumber);
}
//</NOLITE>
}
function debugData(navpopup) { if(getValueOf('popupDebugging') && navpopup.idNumber) { setPopupHTML('idNumber='+navpopup.idNumber + ', pending=' + navpopup.pending, 'popupError', navpopup.idNumber); } }
function newNavpopup(a, article) { var navpopup = new Navpopup(); navpopup.fuzz=5; navpopup.delay=getValueOf('popupDelay')*1000; // increment global counter now navpopup.idNumber = ++pg.idNumber; navpopup.parentAnchor = a; navpopup.parentPopup = (a.popData && a.popData.owner); navpopup.article = article; registerHooks(navpopup); return navpopup; }
function nonsimplePopupContent(a, article) {
var diff=null, history=null;
var params=parseParams(a.href);
var oldid=(typeof params.oldid=='undefined' ? null : params.oldid);
//<NOLITE>
if(getValueOf('popupPreviewDiffs') && window.loadDiff) {
diff=params.diff;
}
if(getValueOf('popupPreviewHistory')) {
history=(params.action=='history');
}
//</NOLITE>
a.navpopup.pending=0;
var x;
if (x=footnoteTarget(a)) { footnotePreview(x, a.navpopup); //<NOLITE> } else if ( diff || diff === 0 ) { loadDiff(article, oldid, diff, a.navpopup); } else if ( history ) { loadAPIPreview('history', article, a.navpopup); } else if ( pg.re.contribs.test(a.href) ) { loadAPIPreview('contribs', article, a.navpopup); } else if ( pg.re.backlinks.test(a.href) ) { loadAPIPreview('backlinks', article, a.navpopup);
} else if ( // FIXME should be able to get all preview combinations with options
article.namespaceId()==pg.nsImageId && ( getValueOf('imagePopupsForImages') || ! anchorContainsImage(a) ) ) { loadAPIPreview('imagepagepreview', article, a.navpopup); loadImage(article, a.navpopup); //</NOLITE> } else { if (article.namespaceId() == pg.nsCategoryId && getValueOf('popupCategoryMembers')) { loadAPIPreview('category', article, a.navpopup); } else if ((article.namespaceId() == pg.nsUserId || article.namespaceId() == pg.nsUsertalkId) && getValueOf('popupUserInfo')) { loadAPIPreview('userinfo', article, a.navpopup); } startArticlePreview(article, oldid, a.navpopup); } }
function pendingNavpopTask(navpop) { if (navpop && navpop.pending===null) { navpop.pending=0; } ++navpop.pending; debugData(navpop); }
function completedNavpopTask(navpop) { if (navpop && navpop.pending) { --navpop.pending; } debugData(navpop); }
function startArticlePreview(article, oldid, navpop) { navpop.redir=0; loadPreview(article, oldid, navpop); }
function loadPreview(article, oldid, navpop) { pendingNavpopTask(navpop); if (!navpop.redir) { navpop.originalArticle=article; } if (!navpop.visible && getValueOf('popupLazyDownloads')) { var id=(navpop.redir) ? 'DOWNLOAD_PREVIEW_REDIR_HOOK' : 'DOWNLOAD_PREVIEW_HOOK'; navpop.addHook(function() { getWiki(article, insertPreview, oldid, navpop); return true; }, 'unhide', 'before', id); } else { getWiki(article, insertPreview, oldid, navpop); } }
function loadPreviewFromRedir(redirMatch, navpop) { // redirMatch is a regex match var target = new Title().fromWikiText(redirMatch[2]); // overwrite (or add) anchor from original target // mediawiki does overwrite; eg User:Lupin/foo3#Done if ( navpop.article.anchor ) { target.anchor = navpop.article.anchor; } var trailingRubbish=redirMatch[4]; navpop.redir++; navpop.redirTarget=target; //<NOLITE> if (window.redirLink) { var warnRedir = redirLink(target, navpop.article); setPopupHTML(warnRedir, 'popupWarnRedir', navpop.idNumber); } //</NOLITE> navpop.article=target; fillEmptySpans({redir: true, redirTarget: target, navpopup:navpop}); return loadPreview(target, null, navpop); }
function insertPreview(download) { if (!download.owner) { return; }
var redirMatch = pg.re.redirect.exec(download.data); if (download.owner.redir===0 && redirMatch) { completedNavpopTask(download.owner); loadPreviewFromRedir(redirMatch, download.owner); return; }
if (download.owner.visible || !getValueOf('popupLazyPreviews')) { insertPreviewNow(download); } else { var id=(download.owner.redir) ? 'PREVIEW_REDIR_HOOK' : 'PREVIEW_HOOK'; download.owner.addHook( function(){insertPreviewNow(download); return true;}, 'unhide', 'after', id ); } }
function insertPreviewNow(download) { if (!download.owner) { return; } var wikiText=download.data; var navpop=download.owner; completedNavpopTask(navpop); var art=navpop.redirTarget || navpop.originalArticle;
//<NOLITE> makeFixDabs(wikiText, navpop); if (getValueOf('popupSummaryData') && window.getPageInfo) { var info=getPageInfo(wikiText, download); setPopupTrailer(getPageInfo(wikiText, download), navpop.idNumber); }
var imagePage=; if (art.namespaceId()==pg.nsImageId) { imagePage=art.toString(); } else { imagePage=getValidImageFromWikiText(wikiText); } if(imagePage) { loadImage(Title.fromWikiText(imagePage), navpop); } //</NOLITE>
if (getValueOf('popupPreviews')) { insertArticlePreview(download, art, navpop); }
}
function insertArticlePreview(download, art, navpop) { if (download && typeof download.data == typeof ){ if (art.namespaceId()==pg.nsTemplateId && getValueOf('popupPreviewRawTemplates')) { // FIXME compare/consolidate with diff escaping code for wikitext
var h='' + download.data.entify().split('\\n').join('
\\n') + '';
setPopupHTML(h, 'popupPreview', navpop.idNumber); } else { var p=prepPreviewmaker(download.data, art, navpop); p.showPreview(); } } }
function prepPreviewmaker(data, article, navpop) { // deal with tricksy anchors var d=anchorize(data, article.anchorString()); var urlBase=joinPath([pg.wiki.articlebase, article.urlString()]); var p=new Previewmaker(d, urlBase, navpop); return p; }
// Try to imitate the way mediawiki generates HTML anchors from section titles
function anchorize(d, anch) {
if (!anch) { return d; }
var anchRe=RegExp('(?:=+\\s*' + literalizeRegex(anch).replace(/[_ ]/g, '[_ ]') + '\\s*=+|\\{\\{\\s*'+getValueOf('popupAnchorRegexp')+'\\s*(?:\\|[^|}]*)*?\\s*'+literalizeRegex(anch)+'\\s*(?:\\|[^}]*)?\}\})');
var match=d.match(anchRe);
if(match && match.length > 0 && match[0]) { return d.substring(d.indexOf(match[0])); }
// now try to deal with == foo baz boom == -> #foo_baz_boom var lines=d.split('\n'); for (var i=0; i<lines.length; ++i) { lines[i]=lines[i].replace(RegExp('[[]{2}([^|\\]]*?[|])?(.*?)[\\]]{2}', 'g'), '$2') .replace(/'([^'])/g, '$1').replace(RegExp("([^'])", 'g'), '$1'); if (lines[i].match(anchRe)) { return d.split('\n').slice(i).join('\n').replace(RegExp('^[^=]*'), ); } } return d; }
function killPopup() { if (getValueOf('popupShortcutKeys') && window.rmPopupShortcuts) { rmPopupShortcuts(); } if (!pg) { return; } pg.current.link && pg.current.link.navpopup && pg.current.link.navpopup.banish(); pg.current.link=null; abortAllDownloads(); if (pg.timer.checkPopupPosition !== null) { clearInterval(pg.timer.checkPopupPosition); pg.timer.checkPopupPosition=null; } return true; // preserve default action } // ENDFILE: actions.js // STARTFILE: domdrag.js /**
@fileoverview The {@link Drag} object, which enables objects to be dragged around.
************************************************* dom-drag.js 09.25.2001 www.youngpup.net ************************************************** 10.28.2001 - fixed minor bug where events sometimes fired off the handle, not the root. ************************************************* Pared down, some hooks added by [[User:Lupin]] Copyright Aaron Boodman. Saying stupid things daily since March 2001.
- /
/**
Creates a new Drag object. This is used to make various DOM elements draggable. @constructor
- /
function Drag () {
/**
Condition to determine whether or not to drag. This function should take one parameter, an Event.
To disable this, set it to null
.
@type Function
*/
this.startCondition = null;
/**
Hook to be run when the drag finishes. This is passed the final coordinates of
the dragged object (two integers, x and y). To disables this, set it to null
.
@type Function
*/
this.endHook = null;
}
/**
Gets an event in a cross-browser manner. @param {Event} e @private
- /
Drag.prototype.fixE = function(e) { if (typeof e == 'undefined') { e = window.event; } if (typeof e.layerX == 'undefined') { e.layerX = e.offsetX; } if (typeof e.layerY == 'undefined') { e.layerY = e.offsetY; } return e; }; /**
Initialises the Drag instance by telling it which object you want to be draggable, and what you want to drag it by. @param {DOMElement} o The "handle" by whichoRoot
is dragged. @param {DOMElement} oRoot The object which moves wheno
is dragged, oro
if omitted.
- /
Drag.prototype.init = function(o, oRoot) { var dragObj = this; this.obj = o; o.onmousedown = function(e) { dragObj.start.apply( dragObj, [e]); }; o.dragging = false; o.popups_draggable = true; o.hmode = true; o.vmode = true;
o.root = oRoot && oRoot !== null ? oRoot : o ;
if (isNaN(parseInt(o.root.style.left, 10))) { o.root.style.left = "0px"; } if (isNaN(parseInt(o.root.style.top, 10))) { o.root.style.top = "0px"; }
o.root.onthisStart = function(){}; o.root.onthisEnd = function(){}; o.root.onthis = function(){}; };
/**
Starts the drag. @private @param {Event} e
- /
Drag.prototype.start = function(e) { var o = this.obj; // = this; e = this.fixE(e); if (this.startCondition && !this.startCondition(e)) { return; } var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom, 10); var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right, 10); o.root.onthisStart(x, y);
o.lastMouseX = e.clientX; o.lastMouseY = e.clientY;
var dragObj = this; o.onmousemoveDefault = document.onmousemove; o.dragging = true; document.onmousemove = function(e) { dragObj.drag.apply( dragObj, [e] ); }; document.onmouseup = function(e) { dragObj.end.apply( dragObj, [e] ); }; return false; }; /**
Does the drag. @param {Event} e @private
- /
Drag.prototype.drag = function(e) { e = this.fixE(e); var o = this.obj;
var ey = e.clientY; var ex = e.clientX; var y = parseInt(o.vmode ? o.root.style.top : o.root.style.bottom, 10); var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right, 10 ); var nx, ny;
nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1)); ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));
this.obj.root.style[o.hmode ? "left" : "right"] = nx + "px"; this.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px"; this.obj.lastMouseX = ex; this.obj.lastMouseY = ey;
this.obj.root.onthis(nx, ny); return false; };
/**
Ends the drag. @private
- /
Drag.prototype.end = function() { document.onmousemove=this.obj.onmousemoveDefault; document.onmouseup = null; this.obj.dragging = false; if (this.endHook) { this.endHook( parseInt(this.obj.root.style[this.obj.hmode ? "left" : "right"], 10), parseInt(this.obj.root.style[this.obj.vmode ? "top" : "bottom"], 10)); } }; // ENDFILE: domdrag.js // STARTFILE: structures.js //<NOLITE> pg.structures.original={}; pg.structures.original.popupLayout=function () { return ['popupError', 'popupImage', 'popupTopLinks', 'popupTitle', 'popupData', 'popupOtherLinks', 'popupRedir', ['popupWarnRedir', 'popupRedirTopLinks', 'popupRedirTitle', 'popupRedirData', 'popupRedirOtherLinks'], 'popupMiscTools', ['popupRedlink'], 'popupPrePreviewSep', 'popupPreview', 'popupSecondPreview', 'popupPreviewMore', 'popupPostPreview', 'popupFixDab']; }; pg.structures.original.popupRedirSpans=function () { return ['popupRedir', 'popupWarnRedir', 'popupRedirTopLinks', 'popupRedirTitle', 'popupRedirData', 'popupRedirOtherLinks']; }; pg.structures.original.popupTitle=function (x) { log ('defaultstructure.popupTitle'); if (!getValueOf('popupNavLinks')) { return navlinkStringToHTML('<<mainlink>>',x.article,x.params); } return ; }; pg.structures.original.popupTopLinks=function (x) { log ('defaultstructure.popupTopLinks'); if (getValueOf('popupNavLinks')) { return navLinksHTML(x.article, x.hint, x.params); } return ; }; pg.structures.original.popupImage=function(x) { log ('original.popupImage, x.article='+x.article+', x.navpop.idNumber='+x.navpop.idNumber); return imageHTML(x.article, x.navpop.idNumber); }; pg.structures.original.popupRedirTitle=pg.structures.original.popupTitle; pg.structures.original.popupRedirTopLinks=pg.structures.original.popupTopLinks;
function copyStructure(oldStructure, newStructure) {
pg.structures[newStructure]={};
for (var prop in pg.structures[oldStructure]) {
pg.structures[newStructure][prop]=pg.structures[oldStructure][prop];
}
}
copyStructure('original', 'nostalgia'); pg.structures.nostalgia.popupTopLinks=function(x) { var str=; str += '<<mainlink|shortcut= >>';
// user links
// contribs - log - count - email - block
// count only if applicable; block only if popupAdminLinks
str += 'if(user){
<<contribs|shortcut=c>>';
str+='if(wikimedia){*<<count|shortcut=#>>}';
str+='if(ipuser){}else{*<<email|shortcut=E>>}if(admin){*<<block|shortcut=b>>}}';
// editing links // talkpage -> edit|new - history - un|watch - article|edit // other page -> edit - history - un|watch - talk|edit|new var editstr='<<edit|shortcut=e>>'; var editOldidStr='if(oldid){<<editOld|shortcut=e>>|<<revert|shortcut=v|rv>>|<<edit|cur>>}else{' + editstr + '}' var historystr='<<history|shortcut=h>>'; var watchstr='<<unwatch|unwatchShort>>|<<watch|shortcut=w|watchThingy>>';
str+='
if(talk){' +
editOldidStr+'|<<new|shortcut=+>>' + '*' + historystr+'*'+watchstr + '*' +
'<<article|shortcut=a>>|<<editArticle|edit>>' +
'}else{' + // not a talk page
editOldidStr + '*' + historystr + '*' + watchstr + '*' +
'<<talk|shortcut=t>>|<<editTalk|edit>>|<<newTalk|shortcut=+|new>>'
+ '}';
// misc links
str += '
<<whatLinksHere|shortcut=l>>*<<relatedChanges|shortcut=r>>';
str += 'if(admin){
}else{*}<<move|shortcut=m>>';
// admin links str += 'if(admin){*<<unprotect|unprotectShort>>|<<protect|shortcut=p>>*' + '<<undelete|undeleteShort>>|<<delete|shortcut=d>>}'; return navlinkStringToHTML(str, x.article, x.params); }; pg.structures.nostalgia.popupRedirTopLinks=pg.structures.nostalgia.popupTopLinks;
/** -- fancy -- **/
copyStructure('original', 'fancy');
pg.structures.fancy.popupTitle=function (x) {
return navlinkStringToHTML('<<mainlink>>',x.article,x.params);
};
pg.structures.fancy.popupTopLinks=function(x) {
var hist='<<history|shortcut=h|hist>>|<<lastEdit|shortcut=/|last>>if(mainspace_en){|<<editors|shortcut=E|eds>>}';
var watch='<<unwatch|unwatchShort>>|<<watch|shortcut=w|watchThingy>>';
var move='<<move|shortcut=m|move>>';
return navlinkStringToHTML('if(talk){' +
'<<edit|shortcut=e>>|<<new|shortcut=+|+>>*' + hist + '*' +
'<<article|shortcut=a>>|<<editArticle|edit>>' + '*' + watch + '*' + move +
'}else{<<edit|shortcut=e>>*' + hist +
'*<<talk|shortcut=t|>>|<<editTalk|edit>>|<<newTalk|shortcut=+|new>>' +
'*' + watch + '*' + move+'}
', x.article, x.params);
};
pg.structures.fancy.popupOtherLinks=function(x) {
var admin='<<unprotect|unprotectShort>>|<<protect|shortcut=p>>*<<undelete|undeleteShort>>|<<delete|shortcut=d|del>>';
var user='<<contribs|shortcut=c>>if(wikimedia){|<<count|shortcut=#|#>>}';
user+='if(ipuser){|<<arin>>}else{*<<email|shortcut=E|'+
popupString('email')+'>>}if(admin){*<<block|shortcut=b>>}';
var normal='<<whatLinksHere|shortcut=l|links here>>*<<relatedChanges|shortcut=r|related>>';
return navlinkStringToHTML('
if(user){' + user + '*}if(admin){'+admin+'if(user){
}else{*}}' + normal,
x.article, x.params);
};
pg.structures.fancy.popupRedirTitle=pg.structures.fancy.popupTitle;
pg.structures.fancy.popupRedirTopLinks=pg.structures.fancy.popupTopLinks;
pg.structures.fancy.popupRedirOtherLinks=pg.structures.fancy.popupOtherLinks;
/** -- fancy2 -- **/
// hack for User:MacGyverMagic
copyStructure('fancy', 'fancy2');
pg.structures.fancy2.popupTopLinks=function(x) { // hack out the
at the end and put one at the beginning
return '
'+pg.structures.fancy.popupTopLinks(x).replace(RegExp('
$','i'),);
};
pg.structures.fancy2.popupLayout=function () { // move toplinks to after the title
return ['popupError', 'popupImage', 'popupTitle', 'popupData', 'popupTopLinks', 'popupOtherLinks',
'popupRedir', ['popupWarnRedir', 'popupRedirTopLinks', 'popupRedirTitle', 'popupRedirData', 'popupRedirOtherLinks'],
'popupMiscTools', ['popupRedlink'],
'popupPrePreviewSep', 'popupPreview', 'popupSecondPreview', 'popupPreviewMore', 'popupPostPreview', 'popupFixDab'];
};
/** -- menus -- **/ copyStructure('original', 'menus'); pg.structures.menus.popupLayout=function () { return ['popupError', 'popupImage', 'popupTopLinks', 'popupTitle', 'popupOtherLinks', 'popupRedir', ['popupWarnRedir', 'popupRedirTopLinks', 'popupRedirTitle', 'popupRedirData', 'popupRedirOtherLinks'], 'popupData', 'popupMiscTools', ['popupRedlink'], 'popupPrePreviewSep', 'popupPreview', 'popupSecondPreview', 'popupPreviewMore', 'popupPostPreview', 'popupFixDab']; }; function toggleSticky(uid) { var popDiv=document.getElementById('navpopup_maindiv'+uid); if (!popDiv) { return; } if (!popDiv.navpopup.sticky) { popDiv.navpopup.stick(); } else { popDiv.navpopup.unstick(); popDiv.navpopup.hide(); } } pg.structures.menus.popupTopLinks = function (x, shorter) { // FIXME maybe this stuff should be cached var s=[];
var dropdiv='var endspan=''; var hist='<<history|shortcut=h>>'; if (!shorter) { hist = '<menurow>' + hist + '|<<historyfeed|rss>>if(mainspace_en){|<<editors|shortcut=E>>}</menurow>'; } var lastedit='<<lastEdit|shortcut=/|show last edit>>'; var jsHistory='<<lastContrib|last set of edits>><<sinceMe|changes since mine>>'; var linkshere='<<whatLinksHere|shortcut=l|what links here>>'; var related='<<relatedChanges|shortcut=r|related changes>>'; var search='<menurow><<search|shortcut=s>>if(wikimedia){|<<globalsearch|shortcut=g|global>>}' + '|<<google|shortcut=G|web>></menurow>'; var watch='<menurow><<unwatch|unwatchShort>>|<<watch|shortcut=w|watchThingy>></menurow>'; var protect='<menurow><<unprotect|unprotectShort>>|' + '<<protect|shortcut=p>>|<<protectlog|log>></menurow>'; var del='<menurow><<undelete|undeleteShort>>|<<delete|shortcut=d>>|' + '<<deletelog|log>></menurow>'; var move='<<move|shortcut=m|move page>>'; var nullPurge='<menurow><<nullEdit|shortcut=n|null edit>>|<<purge|shortcut=P>></menurow>'; var viewOptions='<menurow><<view|shortcut=v>>|<<render|shortcut=S>>|<<raw>></menurow>'; var editRow='if(oldid){' + '<menurow><<edit|shortcut=e>>|<<editOld|shortcut=e|this revision>></menurow>' + '<menurow><<revert|shortcut=v>>|<<undo>></menurow>' + '}else{<<edit|shortcut=e>>}'; var markPatrolled='if(rcid){<<markpatrolled|mark patrolled>>}'; var newTopic='if(talk){<<new|shortcut=+|new topic>>}'; var protectDelete='if(admin){' + protect + del + '}';
if (getValueOf('popupActionsMenu')) { s.push( '<<mainlink>>*' + dropdiv + menuTitle('actions')); } else { s.push( dropdiv + '<<mainlink>>'); } s.push( '<menu>') s.push( editRow + markPatrolled + newTopic + hist + lastedit ) if (!shorter) { s.push(jsHistory); } s.push( move + linkshere + related) if (!shorter) { s.push(nullPurge + search); } if (!shorter) { s.push(viewOptions); }
s.push('' + watch + protectDelete); s.push('
' +
'if(talk){<<article|shortcut=a|view article>><<editArticle|edit article>>}' + 'else{<<talk|shortcut=t|talk page>><<editTalk|edit talk>>' + '<<newTalk|shortcut=+|new topic>>}</menu>' + enddiv);
// user menu starts here var email='<<email|shortcut=E|email user>>'; var contribs= 'if(wikimedia){<menurow>}<<contribs|shortcut=c|contributions>>if(wikimedia){</menurow>}' + 'if(admin){<menurow><<deletedContribs>></menurow>}';
s.push('if(user){*' + dropdiv + menuTitle('user'));
s.push('<menu>'); +
s.push('<menurow><<userPage|shortcut=u|user page>>|<<userSpace|space>></menurow>');
s.push('<<userTalk|shortcut=t|user talk>><<editUserTalk|edit user talk>>' +
'<<newUserTalk|shortcut=+|leave comment>>');
if(!shorter) { s.push( 'if(ipuser){<<arin>>}else{' + email + '}') }
else { s.push( 'if(ipuser){}else{' + email + '}') }
' + contribs + '<<userlog|shortcut=L|user log>>');
s.push('if(wikimedia){<<count|shortcut=#|edit counter>>}'); s.push('if(admin){<menurow><<unblock|unblockShort>>|<<block|shortcut=b|block user>></menurow>}'); s.push('<<blocklog|shortcut=B|block log>>' + getValueOf('popupExtraUserMenu')); s.push('</menu>' + enddiv + '}');
// popups menu starts here if (getValueOf('popupSetupMenu') && !x.navpop.hasPopupMenu /* FIXME: hack */) { x.navpop.hasPopupMenu=true; s.push('*' + dropdiv + menuTitle('popupsMenu') + '<menu>'); s.push('<<togglePreviews|toggle previews>>'); s.push('<<purgePopups|reset>>'); s.push('<<disablePopups|disable>>'); s.push('</menu>'+enddiv); } return navlinkStringToHTML(s.join(), x.article, x.params); };
function menuTitle(s) { return '<a href="#" noPopup=1>' + popupString(s) + '</a>'; }
pg.structures.menus.popupRedirTitle=pg.structures.menus.popupTitle; pg.structures.menus.popupRedirTopLinks=pg.structures.menus.popupTopLinks;
copyStructure('menus', 'shortmenus'); pg.structures.shortmenus.popupTopLinks=function(x) { return pg.structures.menus.popupTopLinks(x,true); }; pg.structures.shortmenus.popupRedirTopLinks=pg.structures.shortmenus.popupTopLinks;
copyStructure('shortmenus', 'dabshortmenus'); pg.structures.dabshortmenus.popupLayout=function () { return ['popupError', 'popupImage', 'popupTopLinks', 'popupTitle', 'popupOtherLinks', 'popupRedir', ['popupWarnRedir', 'popupRedirTopLinks', 'popupRedirTitle', 'popupRedirData', 'popupRedirOtherLinks'], 'popupData', 'popupMiscTools', ['popupRedlink'], 'popupFixDab', 'popupPrePreviewSep', 'popupPreview', 'popupSecondPreview', 'popupPreviewMore', 'popupPostPreview']; };
copyStructure('menus', 'dabmenus'); pg.structures.dabmenus.popupLayout=pg.structures.dabshortmenus.popupLayout;
//</NOLITE>
pg.structures.lite={};
pg.structures.lite.popupLayout=function () {
return ['popupTitle', 'popupPreview' ];
};
pg.structures.lite.popupTitle=function (x) {
log (x.article + ': structures.lite.popupTitle');
//return navlinkStringToHTML('<<mainlink>>',x.article,x.params);
}; // ENDFILE: structures.js // STARTFILE: autoedit.js //<NOLITE> function getParamValue(paramName, h) { if (typeof h == 'undefined' ) { h = document.location.href; } var cmdRe=RegExp('[&?]'+paramName+'=([^&]*)'); var m=cmdRe.exec(h); if (m) { try { return decodeURIComponent(m[1]); } catch (someError) {} } return null; }
function substitute(data,cmdBody) { // alert('sub\nfrom: '+cmdBody.from+'\nto: '+cmdBody.to+'\nflags: '+cmdBody.flags); var fromRe=RegExp(cmdBody.from, cmdBody.flags); return data.replace(fromRe, cmdBody.to); }
function execCmds(data, cmdList) { for (var i=0; i<cmdList.length; ++i) { data=cmdList[i].action(data, cmdList[i]); } return data; }
function parseCmd(str) { // returns a list of commands if (!str.length) { return []; } var p=false; switch (str.charAt(0)) { case 's': p=parseSubstitute(str); break; default: return false; } if (p) { return [p].concat(parseCmd(p.remainder)); } return false; }
function unEscape(str, sep) { return str.split('\\\\').join('\\').split('\\'+sep).join(sep).split('\\n').join('\n'); }
function parseSubstitute(str) {
// takes a string like s/a/b/flags;othercmds and parses it
var from,to,flags,tmp;
if (str.length<4) { return false; } var sep=str.charAt(1); str=str.substring(2);
tmp=skipOver(str,sep); if (tmp) { from=tmp.segment; str=tmp.remainder; } else { return false; }
tmp=skipOver(str,sep); if (tmp) { to=tmp.segment; str=tmp.remainder; } else { return false; }
flags=; if (str.length) { tmp=skipOver(str,';') || skipToEnd(str, ';'); if (tmp) {flags=tmp.segment; str=tmp.remainder; } }
return {action: substitute, from: from, to: to, flags: flags, remainder: str};
}
function skipOver(str,sep) { var endSegment=findNext(str,sep); if (endSegment<0) { return false; } var segment=unEscape(str.substring(0,endSegment), sep); return {segment: segment, remainder: str.substring(endSegment+1)}; }
function skipToEnd(str,sep) { return {segment: str, remainder: }; }
function findNext(str, ch) { for (var i=0; i<str.length; ++i) { if (str.charAt(i)=='\\') { i+=2; } if (str.charAt(i)==ch) { return i; } } return -1; }
function setCheckbox(param, box) { var val=getParamValue(param); if (val!==null) { switch (val) { case '1': case 'yes': case 'true': box.checked=true; break; case '0': case 'no': case 'false': box.checked=false; } } }
function autoEdit() { if (!setupPopups.completed) { setupPopups(); } if (!window.wgEnableAPI || !wgEnableAPI ) { return false; } if (getParamValue('autowatchlist') && getParamValue('actoken')===autoClickToken()) modifyWatchlist(getParamValue('title'), getParamValue('action')); if (!document.editform) { return false; } if (window.autoEdit.alreadyRan) { return false; } window.autoEdit.alreadyRan=true; var cmdString=getParamValue('autoedit'); if (cmdString) { try { var editbox=document.editform.wpTextbox1; } catch (dang) { return; } var cmdList=parseCmd(cmdString); var input=editbox.value; var output=execCmds(input, cmdList); editbox.value=output; // wikEd user script compatibility if (typeof(wikEdUseWikEd) != 'undefined') { if (wikEdUseWikEd == true) { WikEdUpdateFrame(); } } } setCheckbox('autominor', document.editform.wpMinoredit); setCheckbox('autowatch', document.editform.wpWatchthis);
var rvid = getParamValue('autorv'); if (rvid) { var url=pg.wiki.apiwikibase + '?action=query&format=json&prop=revisions&revids='+rvid; startDownload(url, null, autoEdit2); } else { autoEdit2(); } }
function autoEdit2(d) { var summary=getParamValue('autosummary'); var summaryprompt=getParamValue('autosummaryprompt'); var summarynotice=; if (d && d.data && getParamValue('autorv')) { var s = getRvSummary(summary, d.data); if (s===false) { summaryprompt=true; summarynotice=popupString('Failed to get revision information, please edit manually.\n\n'); summary = simplePrintf(summary, [getParamValue('autorv'), '(unknown)', '(unknown)']); } else { summary = s; } } if (summaryprompt) { var txt= summarynotice + popupString('Enter a non-empty edit summary or press cancel to abort'); var response=prompt(txt, summary); if (response) { summary=response; } else { return; } } if (summary) { document.editform.wpSummary.value=summary; } // Attempt to avoid possible premature clicking of the save button // (maybe delays in updates to the DOM are to blame?? or a red herring) setTimeout(autoEdit3, 100); }
function autoClickToken() {
return mw.user.sessionId();
}
function autoEdit3() {
if( getParamValue('actoken') != autoClickToken()) return;
var btn=getParamValue('autoclick'); if (btn) { if (document.editform && document.editform[btn]) { var button=document.editform[btn]; var msg=tprintf('The %s button has been automatically clicked. Please wait for the next page to load.', [ button.value ]); bannerMessage(msg); document.title='('+document.title+')'; button.click(); } else { alert(tprintf('Could not find button %s. Please check the settings in your javascript file.', [ btn ])); } } }
function bannerMessage(s) { var headings=document.getElementsByTagName('h1'); if (headings) { var div=document.createElement('div'); div.innerHTML='' + s + ''; headings[0].parentNode.insertBefore(div, headings[0]); } }
function getRvSummary(template, json) { try { var o=getJsObj(json); var edit = anyChild(o.query.pages).revisions[0]; } catch (badness) {return false;} var timestamp = edit.timestamp.split(/[A-Z]/g).join(' ').replace(/^ *| *$/g, ); return simplePrintf(template, [edit.revid, timestamp, edit.user]); }
//</NOLITE> // ENDFILE: autoedit.js // STARTFILE: downloader.js /**
@fileoverview {@link Downloader}, a xmlhttprequest wrapper, and helper functions.
- /
/**
Creates a new Downloader @constructor @class The Downloader class. Create a new instance of this class to download stuff. @param {String} url The url to download. This can be omitted and supplied later.
- /
function Downloader(url) { // Source: http://jibbering.com/2002/4/httprequest.html /** xmlhttprequest object which we're wrapping */ this.http = false;
/*@cc_on @*/ /*@if (@_jscript_version >= 5) // JScript gives us Conditional compilation, // we can cope with old IE versions. // and security blocked creation of the objects. try { this.http = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { this.http = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { // this.http = false; } } @end @*/
if (! this.http && typeof XMLHttpRequest!='undefined') { this.http = new XMLHttpRequest(); }
/**
The url to download
@type String
*/
this.url = url;
/**
A universally unique ID number
@type integer
*/
this.id=null;
/**
Modification date, to be culled from the incoming headers
@type Date
@private
*/
this.lastModified = null;
/**
What to do when the download completes successfully
@type Function
@private
*/
this.callbackFunction = null;
/**
What to do on failure
@type Function
@private
*/
this.onFailure = null;
/**
Flag set on abort
@type boolean
*/
this.aborted = false;
/**
HTTP method. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html for possibilities.
@type String
*/
this.method='GET';
/**
Async flag.
@type boolean
*/
this.async=true;
}
new Downloader();
/** Submits the http request. */
Downloader.prototype.send = function (x) {
if (!this.http) { return null; }
return this.http.send(x);
};
/** Aborts the download, setting the aborted
field to true. */
Downloader.prototype.abort = function () {
if (!this.http) { return null; }
this.aborted=true;
return this.http.abort();
};
/** Returns the downloaded data. */
Downloader.prototype.getData = function () {if (!this.http) { return null; } return this.http.responseText;};
/** Prepares the download. */
Downloader.prototype.setTarget = function () {
if (!this.http) { return null; }
this.http.open(this.method, this.url, this.async);
};
/** Gets the state of the download. */
Downloader.prototype.getReadyState=function () {if (!this.http) { return null; } return this.http.readyState;};
pg.misc.downloadsInProgress = { };
/** Starts the download.
Note that setTarget {@link Downloader#setTarget} must be run first
- /
Downloader.prototype.start=function () { if (!this.http) { return; } pg.misc.downloadsInProgress[this.id] = this; this.http.send(null); };
/** Gets the 'Last-Modified' date from the download headers.
Should be run after the download completes.
Returns null
on failure.
@return {Date}
- /
Downloader.prototype.getLastModifiedDate=function () { if(!this.http) { return null; } var lastmod=null; try { lastmod=this.http.getResponseHeader('Last-Modified'); } catch (err) {} if (lastmod) { return new Date(lastmod); } return null; };
/** Sets the callback function.
@param {Function} f callback function, called as f(this)
on success
- /
Downloader.prototype.setCallback = function (f) { if(!this.http) { return; } this.http.onreadystatechange = f; };
Downloader.prototype.getStatus = function() { if (!this.http) { return null; } return this.http.status; };
////////////////////////////////////////////////// // helper functions
/** Creates a new {@link Downloader} and prepares it for action.
@param {String} url The url to download @param {integer} id The ID of the {@link Downloader} object @param {Function} callback The callback function invoked on success @return {String/Downloader} the {@link Downloader} object created, or 'ohdear' if an unsupported browser
- /
function newDownload(url, id, callback, onfailure) { var d=new Downloader(url); if (!d.http) { return 'ohdear'; } d.id=id; d.setTarget(); if (!onfailure) { onfailure=2; } var f = function () { if (d.getReadyState() == 4) { delete pg.misc.downloadsInProgress[this.id]; try { if ( d.getStatus() == 200 ) { d.data=d.getData(); d.lastModified=d.getLastModifiedDate(); callback(d); } else if (typeof onfailure == typeof 1) { if (onfailure > 0) { // retry newDownload(url, id, callback, onfailure - 1); } } else if (typeof onfailure == 'function') { onfailure(d,url,id,callback); } } catch (somerr) { /* ignore it */ } } }; d.setCallback(f); return d; } /** Simulates a download from cached data.
The supplied data is put into a {@link Downloader} as if it had downloaded it. @param {String} url The url. @param {integer} id The ID. @param {Function} callback The callback, which is invoked immediately ascallback(d)
, whered
is the new {@link Downloader}. @param {String} data The (cached) data. @param {Date} lastModified The (cached) last modified date.
- /
function fakeDownload(url, id, callback, data, lastModified, owner) { var d=newDownload(url,callback); d.owner=owner; d.id=id; d.data=data; d.lastModified=lastModified; return callback(d); }
/**
Starts a download. @param {String} url The url to download @param {integer} id The ID of the {@link Downloader} object @param {Function} callback The callback function invoked on success @return {String/Downloader} the {@link Downloader} object created, or 'ohdear' if an unsupported browser
- /
function startDownload(url, id, callback) { var d=newDownload(url, id, callback); if (typeof d == typeof ) { return d; } d.start(); return d; }
/**
Aborts all downloads which have been started.
- /
function abortAllDownloads() { for ( var x in pg.misc.downloadsInProgress ) { try { pg.misc.downloadsInProgress[x].aborted=true; pg.misc.downloadsInProgress[x].abort(); delete pg.misc.downloadsInProgress[x]; } catch (e) { } } } // ENDFILE: downloader.js // STARTFILE: livepreview.js // TODO: location is often not correct (eg relative links in previews)
/**
* InstaView - a Mediawiki to HTML converter in JavaScript * Version 0.6.1 * Copyright (C) Pedro Fayolle 2005-2006 * http://en.wikipedia.org/wiki/User:Pilaf * Distributed under the BSD license * * Changelog: * * 0.6.1 * - Fixed problem caused by \r characters * - Improved inline formatting parser * * 0.6 * - Changed name to InstaView * - Some major code reorganizations and factored out some common functions * - Handled conversion of relative links (i.e. /foo) * - Fixed misrendering of adjacent definition list items * - Fixed bug in table headings handling * - Changed date format in signatures to reflect Mediawiki's * - Fixed handling of Image:... * - Updated MD5 function (hopefully it will work with UTF-8) * - Fixed bug in handling of links inside images * * To do: * - Better support for <math> * - Full support for * - Parser-based (as opposed to RegExp-based) inline wikicode handling (make it one-pass and bullet-proof) * - Support for templates (through AJAX) * - Support for coloured links (AJAX) */ var Insta = {} function setupLivePreview() { // options Insta.conf = { baseUrl: '', user: {}, wiki: { lang: pg.wiki.lang, interwiki: pg.wiki.interwiki, default_thumb_width: 180 }, paths: { articles: pg.wiki.articlePath + '/', // Only used for Insta previews with images. (not in popups) math: '/math/', images: '//upload.wikimedia.org/wikipedia/en/', // FIXME ( window.getImageUrlStart ? getImageUrlStart(pg.wiki.hostname) : ''), images_fallback: '//upload.wikimedia.org/wikipedia/commons/', magnify_icon: 'skins/common/images/magnify-clip.png' }, locale: { user: mw.config.get('wgFormattedNamespaces')[pg.nsUserId], image: mw.config.get('wgFormattedNamespaces')[pg.nsImageId], category: mw.config.get('wgFormattedNamespaces')[pg.nsCategoryId], // shouldn't be used in popup previews, i think months: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] } } // options with default values or backreferences with (Insta.conf) { user.name = user.name || 'Wikipedian' user.signature = '[['+locale.user+':'+user.name+'|'+user.name+']]' //paths.images = '//upload.wikimedia.org/wikipedia/' + wiki.lang + '/' } // define constants Insta.BLOCK_IMAGE = new RegExp('^\\[\\[(?:File|Image|'+Insta.conf.locale.image+ '):.*?\\|.*?(?:frame|thumbnail|thumb|none|right|left|center)', 'i'); } Insta.dump = function(from, to) { if (typeof from == 'string') from = document.getElementById(from) if (typeof to == 'string') to = document.getElementById(to) to.innerHTML = this.convert(from.value) } Insta.convert = function(wiki) { var ll = (typeof wiki == 'string')? wiki.replace(/\r/g,'').split(/\n/): wiki, // lines of wikicode o='', // output p=0, // para flag $r // result of passing a regexp to $() // some shorthands function remain() { return ll.length } function sh() { return ll.shift() } // shift function ps(s) { o+=s } // push function f() // similar to C's printf, uses ? as placeholders, ?? to escape question marks { var i=1,a=arguments,f=a[0],o='',c,p for (;i<a.length; i++) if ((p=f.indexOf('?'))+1) { // allow character escaping i -= c=f.charAt(p+1)=='?'?1:0 o += f.substring(0,p)+(c?'?':a[i]) f=f.substr(p+1+c) } else break; return o+f } function html_entities(s) { return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">") } function max(a,b) { return (a>b)?a:b } function min(a,b) { return (a<b)?a:b } // return the first non matching character position between two strings function str_imatch(a, b) { for (var i=0, l=min(a.length, b.length); i<l; i++) if (a.charAt(i)!=b.charAt(i)) break return i } // compare current line against a string or regexp // if passed a string it will compare only the first string.length characters // if passed a regexp the result is stored in $r function $(c) { return (typeof c == 'string') ? (ll[0].substr(0,c.length)==c) : ($r = ll[0].match(c)) } function $$(c) { return ll[0]==c } // compare current line against a string function _(p) { return ll[0].charAt(p) } // return char at pos p function endl(s) { ps(s); sh() } function parse_list() { var prev=''; while (remain() && $(/^([*#:;]+)(.*)$/)) { var l_match = $r sh() var ipos = str_imatch(prev, l_match[1]) // close uncontinued lists for (var i=prev.length-1; i >= ipos; i--) { var pi = prev.charAt(i) if (pi=='*') ps('</ul>') else if (pi=='#') ps('</ol>') // close a dl only if the new item is not a dl item (:, ; or empty) else switch (l_match[1].charAt(i)) { case'':case'*':case'#': ps('</dl>') } } // open new lists for (var i=ipos; i<l_match[1].length; i++) { var li = l_match[1].charAt(i) if (li=='*') ps('<ul>') else if (li=='#') ps('<ol>') // open a new dl only if the prev item is not a dl item (:, ; or empty) else switch(prev.charAt(i)) { case'':case'*':case'#': ps('<dl>') } } switch (l_match[1].charAt(l_match[1].length-1)) { case '*': case '#': ps('<li>' + parse_inline_nowiki(l_match[2])); break case ';': ps('<dt>') var dt_match // handle ;dt :dd format if (dt_match = l_match[2].match(/(.*?)(:.*?)$/)) { ps(parse_inline_nowiki(dt_match[1])) ll.unshift(dt_match[2]) } else ps(parse_inline_nowiki(l_match[2])) break case ':': ps('<dd>' + parse_inline_nowiki(l_match[2])) } prev=l_match[1] } // close remaining lists for (var i=prev.length-1; i>=0; i--) ps(f('</?>', (prev.charAt(i)=='*')? 'ul': ((prev.charAt(i)=='#')? 'ol': 'dl'))) } function parse_table() { endl(f('<table?>', $(/^\{\|( .*)$/)? $r[1]: '')) for (;remain();) if ($('|')) switch (_(1)) { case '}': endl('</table>'); return case '-': endl(f('<tr ?>', $(/\|-*(.*)/)[1])); break default: parse_table_data() } else if ($('!')) parse_table_data() else sh() } function parse_table_data() { var td_line, match_i // 1: "|+", '|' or '+' // 2: ?? // 3: attributes ?? // TODO: finish commenting this regexp var td_match = sh().match(/^(\|\+|\||!)((?:([^[|]*?)\|(?!\|))?(.*))$/) if (td_match[1] == '|+') ps('<caption'); else ps('<t' + ((td_match[1]=='|')?'d':'h')) if (typeof td_match[3] != 'undefined') { ps(' ' + td_match[3]) match_i = 4 } else match_i = 2 ps('>') if (td_match[1] != '|+') { // use || or !! as a cell separator depending on context // NOTE: when split() is passed a regexp make sure to use non-capturing brackets td_line = td_match[match_i].split((td_match[1] == '|')? '||': /(?:\|\||!!)/) ps(parse_inline_nowiki(td_line.shift())) while (td_line.length) ll.unshift(td_match[1] + td_line.pop()) } else ps(td_match[match_i]) var tc = 0, td = [] for (;remain(); td.push(sh())) if ($('|')) { if (!tc) break // we're at the outer-most level (no nested tables), skip to td parse else if (_(1)=='}') tc-- } else if (!tc && $('!')) break else if ($('{|')) tc++ if (td.length) ps(Insta.convert(td)) } function parse_pre() { ps('<pre>') do endl(parse_inline_nowiki(ll[0].substring(1)) + "\n"); while (remain() && $(' ')) ps('</pre>') } function parse_block_image() { ps(parse_image(sh())) } function parse_image(str) { //<NOLITE> // get what's in between "[[Image:" and "]]" var tag = str.substring(str.indexOf(':') + 1, str.length - 2); var width; var attr = [], filename, caption = ''; var thumb=0, frame=0, center=0; var align=''; if (tag.match(/\|/)) { // manage nested links var nesting = 0; var last_attr; for (var i = tag.length-1; i > 0; i--) { if (tag.charAt(i) == '|' && !nesting) { last_attr = tag.substr(i+1); tag = tag.substring(0, i); break; } else switch (tag.substr(i-1, 2)) { case ']]': nesting++; i--; break; case '[[': nesting--; i--; } } attr = tag.split(/\s*\|\s*/); attr.push(last_attr); filename = attr.shift(); var w_match; for (;attr.length; attr.shift()) if (w_match = attr[0].match(/^(\d*)(?:[px]*\d*)?px$/)) width = w_match[1] else switch(attr[0]) { case 'thumb': case 'thumbnail': thumb=true; case 'frame': frame=true; break; case 'none': case 'right': case 'left': center=false; align=attr[0]; break; case 'center': center=true; align='none'; break; default: if (attr.length == 1) caption = attr[0]; } } else filename = tag; var o=''; if (frame) { if (align=='') align = 'right'; o += f("<div class='thumb t?'>", align); if (thumb) { if (!width) width = Insta.conf.wiki.default_thumb_width; o += f("<div style='width:?px;'>?", 2+width*1, make_image(filename, caption, width)) + f("<div class='thumbcaption'><div class='magnify' style='float:right'><a href='?' class='internal' title='Enlarge'><img src='?'></a></div>?</div>", Insta.conf.paths.articles + Insta.conf.locale.image + ':' + filename, Insta.conf.paths.magnify_icon, parse_inline_nowiki(caption) ) } else { o += '<div>' + make_image(filename, caption) + f("<div class='thumbcaption'>?</div>", parse_inline_nowiki(caption)) } o += '</div></div>'; } else if (align != '') { o += f("<div class='float?'><span>?</span></div>", align, make_image(filename, caption, width)); } else { return make_image(filename, caption, width); } return center? f("<div class='center'>?</div>", o): o; //</NOLITE> } function parse_inline_nowiki(str) { var start, lastend=0 var substart=0, nestlev=0, open, close, subloop; var html=''; while (-1 != (start = str.indexOf('<nowiki>', substart))) { html += parse_inline_wiki(str.substring(lastend, start)); start += 8; substart = start; subloop = true; do { open = str.indexOf('<nowiki>', substart); close = str.indexOf('', substart);
if (close<=open || open==-1) { if (close==-1) { return html + html_entities(str.substr(start)); } substart = close+9; if (nestlev) { nestlev--; } else { lastend = substart; html += html_entities(str.substring(start, lastend-9)); subloop = false; } } else { substart = open+8; nestlev++; } } while (subloop) }
return html + parse_inline_wiki(str.substr(lastend)); }
function make_image(filename, caption, width) { //<NOLITE> // uppercase first letter in file name filename = filename.charAt(0).toUpperCase() + filename.substr(1); // replace spaces with underscores filename = filename.replace(/ /g, '_');
caption = strip_inline_wiki(caption);
var md5 = hex_md5(filename);
var source = md5.charAt(0) + '/' + md5.substr(0,2) + '/' + filename;
if (width) width = "width='" + width + "px'";
var img = "<img onerror=\""+escapeQuotesHTML("this.onerror=null;this.src='"+pg.jsescape(Insta.conf.paths.images_fallback + source)+"'")+"\" src=\""+escapeQuotesHTML(Insta.conf.paths.images + source)+"\" "+(caption!= ? "alt=\"" + escapeQuotesHTML(caption) + "\"" : )+" "+width+">";
return f("<a class='image' ? href=\"?\">?</a>", (caption!=)? "title=\"" + escapeQuotesHTML(caption) + "\"" : , escapeQuotesHTML(Insta.conf.paths.articles + Insta.conf.locale.image + ':' + filename), img); //</NOLITE> }
function parse_inline_images(str) { //<NOLITE> var start, substart=0, nestlev=0; var loop, close, open, wiki, html;
while (-1 != (start=str.indexOf('[[', substart))) { if(str.substr(start+2).match(RegExp('^(Image|File|' + Insta.conf.locale.image + '):','i'))) { loop=true; substart=start; do { substart+=2; close=str.indexOf(']]',substart); open=str.indexOf('[[',substart); if (close<=open||open==-1) { if (close==-1) return str; substart=close; if (nestlev) { nestlev--; } else { wiki=str.substring(start,close+2); html=parse_image(wiki); str=str.replace(wiki,html); substart=start+html.length; loop=false; } } else { substart=open; nestlev++; } } while (loop)
} else break; }
//</NOLITE> return str; }
// the output of this function doesn't respect the FILO structure of HTML // but since most browsers can handle it I'll save myself the hassle function parse_inline_formatting(str) { var em,st,i,li,o=; while ((i=str.indexOf("",li))+1) { o += str.substring(li,i); li=i+2; if (str.charAt(i+2)=="'") { li++; st=!st; o+=st?'':''; } else { em=!em; o+=em?'':''; } } return o+str.substr(li); }
function parse_inline_wiki(str) { var aux_match;
str = parse_inline_images(str); str = parse_inline_formatting(str);
// math while (aux_match = str.match(/<(?:)math>(.*?)<\/math>/i)) { var math_md5 = hex_md5(aux_match[1]); str = str.replace(aux_match[0], f("<img src='?.png'>", Insta.conf.paths.math+math_md5)); }
// Build a Mediawiki-formatted date string var date = new Date; var minutes = date.getUTCMinutes(); if (minutes < 10) minutes = '0' + minutes; var date = f("?:?, ? ? ? (UTC)", date.getUTCHours(), minutes, date.getUTCDate(), Insta.conf.locale.months[date.getUTCMonth()], date.getUTCFullYear());
// text formatting return str. // signatures replace(/~{5}(?!~)/g, date). replace(/~{4}(?!~)/g, Insta.conf.user.name+' '+date). replace(/~{3}(?!~)/g, Insta.conf.user.name).
// Category:..., Image:..., etc... replace(RegExp('\\[\\[:((?:'+Insta.conf.locale.category+'|Image|File|'+Insta.conf.locale.image+'|'+Insta.conf.wiki.interwiki+'):[^|]*?)\\]\\](\w*)','gi'), "<a href='"+Insta.conf.paths.articles+"$1'>$1$2</a>"). // remove straight category and interwiki tags replace(RegExp('\\[\\[(?:'+Insta.conf.locale.category+'|'+Insta.conf.wiki.interwiki+'):.*?\\]\\]','gi'),).
// Links, Links, etc... replace(RegExp('\\[\\[:((?:'+Insta.conf.locale.category+'|Image|File|'+Insta.conf.locale.image+'|'+Insta.conf.wiki.interwiki+'):.*?)\\|([^\\]]+?)\\]\\](\\w*)','gi'), "<a href='"+Insta.conf.paths.articles+"$1'>$2$3</a>").
// /Relative links replace(/\[\[(\/[^|]*?)\]\]/g, f("<a href='?$1'>$1</a>", Insta.conf.baseUrl)).
// Relative links replace(/\[\[(\/.*?)\|(.+?)\]\]/g, f("<a href='?$1'>$2</a>", Insta.conf.baseUrl)).
// Common links replace(/\[\[([^|]*?)\]\](\w*)/g, f("<a href='?$1'>$1$2</a>", Insta.conf.paths.articles)).
// Links replace(/\[\[(.*?)\|([^\]]+?)\]\](\w*)/g, f("<a href='?$1'>$2$3</a>", Insta.conf.paths.articles)).
// Namespace replace(/\[\[([^\]]*?:)?(.*?)( *\(.*?\))?\|\]\]/g, f("<a href='?$1$2$3'>$2</a>", Insta.conf.paths.articles)).
// External links replace(/\[(https?|news|ftp|mailto|gopher|irc):(\/*)([^\]]*?) (.*?)\]/g, "<a class='external' href='$1:$2$3'>$4</a>"). replace(/\[http:\/\/(.*?)\]/g, "<a class='external' href='http://$1'>[#]</a>"). replace(/\[(news|ftp|mailto|gopher|irc):(\/*)(.*?)\]/g, "<a class='external' href='$1:$2$3'>$1:$2$3</a>"). replace(/(^| )(https?|news|ftp|mailto|gopher|irc):(\/*)([^ $]*[^.,!?;: $])/g, "$1<a class='external' href='$2:$3$4'>$2:$3$4</a>").
replace(,). replace(,); } /*
- /
function strip_inline_wiki(str) { return str .replace(/\[\^\*\|(.*?)\]\]/g,'$1') .replace(/\[\[(.*?)\]\]/g,'$1') .replace(/(.*?)/g,'$1'); }
// begin parsing for (;remain();) if ($(/^(={1,6})(.*)\1(.*)$/)) { p=0 endl(f('<h?>?</h?>?', $r[1].length, parse_inline_nowiki($r[2]), $r[1].length, $r[3]))
} else if ($(/^[*#:;]/)) { p=0 parse_list()
} else if ($(' ')) { p=0 parse_pre()
} else if ($('{|')) { p=0 parse_table()
} else if ($(/^----+$/)) { p=0
endl('')
} else if ($(Insta.BLOCK_IMAGE)) { p=0 parse_block_image()
} else {
// handle paragraphs if ($$()) {
if (p = (remain()>1 && ll[1]==())) endl('
')
} else {
if(!p) {
ps('
')
p=1
}
ps(parse_inline_nowiki(ll[0]) + ' ')
}
sh();
}
return o
};
window.wiki2html=function(txt,baseurl) {
Insta.conf.baseUrl=baseurl;
return Insta.convert(txt);
};
// ENDFILE: livepreview.js
// STARTFILE: pageinfo.js
//<NOLITE>
function popupFilterPageSize(data) {
return formatBytes(data.length);
}
function popupFilterCountLinks(data) {
var num=countLinks(data);
return String(num) + ' ' + ((num!=1)?popupString('wikiLinks'):popupString('wikiLink'));
}
function popupFilterCountImages(data) {
var num=countImages(data);
return String(num) + ' ' + ((num!=1)?popupString('images'):popupString('image'));
}
function popupFilterCountCategories(data) {
var num=countCategories(data);
return String(num) + ' ' + ((num!=1)?popupString('categories'):popupString('category'));
}
function popupFilterLastModified(data,download) {
var lastmod=download.lastModified;
var now=new Date();
var age=now-lastmod;
if (lastmod && getValueOf('popupLastModified')) {
return (tprintf('%s old', [formatAge(age)])).replace(RegExp(' ','g'), ' ');
}
return ;
}
function formatAge(age) {
// coerce into a number
var a=0+age, aa=a;
var seclen = 1000;
var minlen = 60*seclen;
var hourlen = 60*minlen;
var daylen = 24*hourlen;
var weeklen = 7*daylen;
var numweeks = (a-a%weeklen)/weeklen; a = a-numweeks*weeklen; var sweeks = addunit(numweeks, 'week');
var numdays = (a-a%daylen)/daylen; a = a-numdays*daylen; var sdays = addunit(numdays, 'day');
var numhours = (a-a%hourlen)/hourlen; a = a-numhours*hourlen; var shours = addunit(numhours,'hour');
var nummins = (a-a%minlen)/minlen; a = a-nummins*minlen; var smins = addunit(nummins, 'minute');
var numsecs = (a-a%seclen)/seclen; a = a-numsecs*seclen; var ssecs = addunit(numsecs, 'second');
if (aa > 4*weeklen) { return sweeks; }
if (aa > weeklen) { return sweeks + ' ' + sdays; }
if (aa > daylen) { return sdays + ' ' + shours; }
if (aa > 6*hourlen) { return shours; }
if (aa > hourlen) { return shours + ' ' + smins; }
if (aa > 10*minlen) { return smins; }
if (aa > minlen) { return smins + ' ' + ssecs; }
return ssecs;
}
function addunit(num,str) { return + num + ' ' + ((num!=1) ? popupString(str+'s') : popupString(str)) ;}
function runPopupFilters(list, data, download) {
var ret=[];
for (var i=0; i<list.length; ++i) {
if (list[i] && typeof list[i] == 'function') {
var s=list[i](data, download, download.owner.article);
if (s) { ret.push(s); }
}
}
return ret;
}
function getPageInfo(data, download) {
if (!data || data.length === 0) { return popupString('Empty page'); }
var popupFilters=getValueOf('popupFilters') || [];
var extraPopupFilters = getValueOf('extraPopupFilters') || [];
var pageInfoArray = runPopupFilters(popupFilters.concat(extraPopupFilters), data, download);
var pageInfo=pageInfoArray.join(', ');
if (pageInfo !== ) { pageInfo = upcaseFirst(pageInfo); }
return pageInfo;
}
// this could be improved!
function countLinks(wikiText) { return wikiText.split('[[').length - 1; }
// if N = # matches, n = # brackets, then
// String.parenSplit(regex) intersperses the N+1 split elements
// with Nn other elements. So total length is
// L= N+1 + Nn = N(n+1)+1. So N=(L-1)/(n+1).
function countImages(wikiText) {
return (wikiText.parenSplit(pg.re.image).length - 1) / (pg.re.imageBracketCount + 1);
}
function countCategories(wikiText) {
return (wikiText.parenSplit(pg.re.category).length - 1) / (pg.re.categoryBracketCount + 1);
}
function popupFilterStubDetect(data, download, article) {
var counts=stubCount(data, article);
if (counts.real) { return popupString('stub'); }
if (counts.sect) { return popupString('section stub'); }
return ;
}
function popupFilterDisambigDetect(data, download, article) {
if (getValueOf('popupOnlyArticleDabStub') && article.namespace()) { return ; }
return (isDisambig(data, article)) ? popupString('disambig') : ;
}
function formatBytes(num) {
return (num > 949) ? (Math.round(num/100)/10+popupString('kB')) : (num +' ' + popupString('bytes')) ;
}
//</NOLITE>
// ENDFILE: pageinfo.js
// STARTFILE: titles.js
/**
@fileoverview Defines the {@link Title} class, and associated crufty functions.
Title
deals with article titles and their various
forms. {@link Stringwrapper} is the parent class of
Title
, which exists simply to make things a little
neater.
- /
- /
Title
.
@constructor
@class The Title class. Holds article titles and converts them into
various forms. Also deals with anchors, by which we mean the bits
of the article URL after a # character, representing locations
within an article.
@param {String} value The initial value to assign to the
article. This must be the canonical title (see {@link
Title#value}. Omit this in the constructor and use another function
to set the title if this is unavailable.
- /
- /
- /
' + popupString('Click to disambiguate this link to:') + '
';
html+=list.join(', '); return html; }
function makeFixDabs(wikiText, navpop) {
if (getValueOf('popupFixDabs') && isDisambig(wikiText, navpop.article) &&
Title.fromURL(location.href).namespaceId() != pg.nsSpecialId &&
navpop.article.talkPage() ) {
setPopupHTML(makeFixDab(wikiText, navpop), 'popupFixDab', navpop.idNumber);
}
}
function popupRedlinkHTML(article) { return changeLinkTargetLink( { newTarget: null, text: popupString('remove this link').split(' ').join(' '), hint: popupString("remove all links to this page from this article"), clickButton: "wpDiff", oldTarget: article.toString(), summary: simplePrintf(getValueOf('popupRedlinkSummary'), [article.toString()])}); } //</NOLITE> // ENDFILE: dab.js // STARTFILE: htmloutput.js
function appendPopupContent(obj, elementId, popupId, onSuccess) { return setPopupHTML(obj, elementId, popupId, onSuccess, true); }
// this has to use a timer loop as we don't know if the DOM element exists when we want to set the text function setPopupHTML (str, elementId, popupId, onSuccess, append) { if (elementId=='popupPreview') { } if (typeof popupId === 'undefined') { //console.error('popupId is not defined in setPopupHTML, html='+str.substring(0,100)); popupId = pg.idNumber; }
var popupElement=document.getElementById(elementId+popupId); if (popupElement) { if (!append) { popupElement.innerHTML=; } if (isString(str)) { popupElement.innerHTML+=str; } else { popupElement.appendChild(str); } if (onSuccess) { onSuccess(); } setTimeout(checkPopupPosition, 100); return true; } else { // call this function again in a little while... setTimeout(function(){ setPopupHTML(str,elementId,popupId,onSuccess); }, 600); } return null; }
//<NOLITE> function setPopupTrailer(str,id) {return setPopupHTML(str, 'popupData', id);} //</NOLITE>
function fillEmptySpans(args) { return fillEmptySpans2(args); }
// args.navpopup is mandatory // optional: args.redir, args.redirTarget // FIXME: ye gods, this is ugly stuff function fillEmptySpans2(args) { // if redir is present and true then redirTarget is mandatory var redir=true; if (typeof args != 'object' || typeof args.redir == 'undefined' || !args.redir) { redir=false; } var a=args.navpopup.parentAnchor;
var article, hint=null, oldid=null, params={}; if (redir && typeof args.redirTarget == typeof {}) { article=args.redirTarget; //hint=article.hintValue(); } else { article=(new Title()).fromAnchor(a); hint=a.originalTitle || article.hintValue(); params=parseParams(a.href); oldid=(getValueOf('popupHistoricalLinks')) ? params.oldid : null; rcid=params.rcid; } var x={ article:article, hint: hint, oldid: oldid, rcid: rcid, navpop:args.navpopup, params:params };
var structure=pg.structures[getValueOf('popupStructure')]; if (typeof structure != 'object') { setPopupHTML('popupError', 'Unknown structure (this should never happen): '+ pg.option.popupStructure, args.navpopup.idNumber); return; } var spans=flatten(pg.misc.layout); var numspans = spans.length; var redirs=pg.misc.redirSpans;
for (var i=0; i<numspans; ++i) { var f=findThis(redirs, spans[i]); //log('redir='+redir+', f='+f+', spans[i]='+spans[i]); if ( (f!==null && !redir) || (f===null && redir) ) { //log('skipping this set of the loop'); continue; } var structurefn=structure[spans[i]]; var setfn = setPopupHTML; if (getValueOf('popupActiveNavlinks') && (spans[i].indexOf('popupTopLinks')==0 || spans[i].indexOf('popupRedirTopLinks')==0) ) { setfn = setPopupTipsAndHTML; } switch (typeof structurefn) { case 'function': //log('running '+spans[i]+'({article:'+x.article+', hint:'+x.hint+', oldid: '+x.oldid+'})'); setfn(structurefn(x), spans[i], args.navpopup.idNumber); break; case 'string': setfn(structurefn, spans[i], args.navpopup.idNumber); break; default: errlog('unknown thing with label '+spans[i]); break; } } }
// flatten an array function flatten(list, start) { var ret=[]; if (typeof start == 'undefined') { start=0; } for (var i=start; i<list.length; ++i) { if (typeof list[i] == typeof []) { return ret.concat(flatten(list[i])).concat(flatten(list, i+1)); } else { ret.push(list[i]); } } return ret; }
// Generate html for whole popup function popupHTML (a) { getValueOf('popupStructure'); var structure=pg.structures[pg.option.popupStructure]; if (typeof structure != 'object') { //return 'Unknown structure: '+pg.option.popupStructure; // override user choice pg.option.popupStructure=pg.optionDefault.popupStructure; return popupHTML(a); } if (typeof structure.popupLayout != 'function') { return 'Bad layout'; } pg.misc.layout=structure.popupLayout(); if (typeof structure.popupRedirSpans == 'function') { pg.misc.redirSpans=structure.popupRedirSpans(); } else { pg.misc.redirSpans=[]; } return makeEmptySpans(pg.misc.layout, a.navpopup); }
function makeEmptySpans (list, navpop) { var ret=; for (var i=0; i<list.length; ++i) { if (typeof list[i] == typeof ) { ret += emptySpanHTML(list[i], navpop.idNumber, 'div'); } else if (typeof list[i] == typeof [] && list[i].length > 0 ) { ret = ret.parenSplit(RegExp('(</[^>]*?>$)')).join(makeEmptySpans(list[i], navpop)); } else if (typeof list[i] == typeof {} && list[i].nodeType ) { ret += emptySpanHTML(list[i].name, navpop.idNumber, list[i].nodeType); } } return ret; }
function emptySpanHTML(name, id, tag, classname) {
tag = tag || 'span';
if (!classname) { classname = emptySpanHTML.classAliases[name]; }
classname = classname || name;
if (name == getValueOf('popupDragHandle')) { classname += ' popupDragHandle'; }
return simplePrintf('<%s id="%s" class="%s"></%s>', [tag, name + id, classname, tag]);
}
emptySpanHTML.classAliases={ 'popupSecondPreview': 'popupPreview' };
// generate html for popup image // <a id="popupImageLinkn"><img id="popupImagen"> // where n=idNumber function imageHTML(article, idNumber) { return simplePrintf('<a id="popupImageLink$1">' + '<img align="right" valign="top" id="popupImg$1" style="display: none;"></img>' + '</a>', [ idNumber ]); }
function popTipsSoonFn(id, when, popData) { when || ( when=250 ); var popTips=function(){ setupTooltips(document.getElementById(id), false, true, popData); }; return function() { setTimeout( popTips, when, popData ); }; }
function setPopupTipsAndHTML(html, divname, idnumber, popData) { setPopupHTML(html, divname, idnumber, getValueOf('popupSubpopups') ? popTipsSoonFn(divname + idnumber, null, popData) : null); } // ENDFILE: htmloutput.js // STARTFILE: mouseout.js ////////////////////////////////////////////////// // fuzzy checks
function fuzzyCursorOffMenus(x,y, fuzz, parent) { if (!parent) { return null; } var uls=parent.getElementsByTagName('ul'); for (var i=0; i<uls.length; ++i) { if (uls[i].className=='popup_menu') { if (uls[i].offsetWidth > 0) return false; } // else {document.title+='.';} } return true; }
function checkPopupPosition () { // stop the popup running off the right of the screen // FIXME avoid pg.current.link pg.current.link && pg.current.link.navpopup && pg.current.link.navpopup.limitHorizontalPosition(); }
function mouseOutWikiLink () { if (!window.popupsReady || !window.popupsReady()) { return; } //console ('mouseOutWikiLink'); var a=this; if (a.navpopup==null) return; if ( ! a.navpopup.isVisible() ) { a.navpopup.banish(); return; }
restoreTitle(a);
Navpopup.tracker.addHook(posCheckerHook(a.navpopup)); }
function posCheckerHook(navpop) { return function() { if (!navpop.isVisible()) { return true; /* remove this hook */ } if (Navpopup.tracker.dirty) { return false; } var x=Navpopup.tracker.x, y=Navpopup.tracker.y; var mouseOverNavpop = navpop.isWithin(x,y,navpop.fuzz, navpop.mainDiv) || !fuzzyCursorOffMenus(x,y,navpop.fuzz, navpop.mainDiv);
// FIXME it'd be prettier to do this internal to the Navpopup objects var t=getValueOf('popupHideDelay'); if (t) { t = t * 1000; } if (!t) { if(!mouseOverNavpop) { navpop.banish(); return true; /* remove this hook */ } return false; } // we have a hide delay set var d=+(new Date()); if ( !navpop.mouseLeavingTime ) { navpop.mouseLeavingTime = d; return false; } if ( mouseOverNavpop ) { navpop.mouseLeavingTime=null; return false; } if (d - navpop.mouseLeavingTime > t) { navpop.mouseLeavingTime=null; navpop.banish(); return true; /* remove this hook */ } return false; }; }
function runStopPopupTimer(navpop) { // at this point, we should have left the link but remain within the popup // so we call this function again until we leave the popup. if (!navpop.stopPopupTimer) { navpop.stopPopupTimer=setInterval(posCheckerHook(navpop), 500); navpop.addHook(function(){clearInterval(navpop.stopPopupTimer);}, 'hide', 'before'); } } // ENDFILE: mouseout.js // STARTFILE: previewmaker.js /**
@fileoverview Defines the {@link Previewmaker} object, which generates short previews from wiki markup.
- /
/**
Creates a new Previewmaker @constructor @class The Previewmaker class. Use an instance of this to generate short previews from Wikitext. @param {String} wikiText The Wikitext source of the page we wish to preview. @param {String} baseUrl The url we should prepend when creating relative urls. @param {Navpopup} owner The navpop associated to this preview generator
- /
function Previewmaker(wikiText, baseUrl, owner) { /** The wikitext which is manipulated to generate the preview. */ this.originalData=wikiText; this.setData(); this.baseUrl=baseUrl; this.owner=owner; this.maxCharacters=getValueOf('popupMaxPreviewCharacters'); this.maxSentences=getValueOf('popupMaxPreviewSentences'); } Previewmaker.prototype.setData=function() { var maxSize=max(10000, 2*this.maxCharacters); this.data=this.originalData.substring(0,maxSize); }; /** Remove HTML comments
@private
- /
Previewmaker.prototype.killComments = function () { // this also kills one trailing newline, eg diamyo this.data=this.data.replace(RegExp('\\n?', 'g'), ); }; /**
@private
- /
Previewmaker.prototype.killDivs = function () { // say goodbye, divs (can be nested, so use * not *?) this.data=this.data.replace(RegExp('< *div[^>]* *>[\\s\\S]*?< */ *div *>', 'gi'), ); }; /**
@private
- /
Previewmaker.prototype.killGalleries = function () { this.data=this.data.replace(RegExp('< *gallery[^>]* *>[\\s\\S]*?< */ *gallery *>', 'gi'), ); }; /**
@private
- /
Previewmaker.prototype.kill = function(opening, closing, subopening, subclosing, repl) { var oldk=this.data; var k=this.killStuff(this.data, opening, closing, subopening, subclosing, repl); while (k.length < oldk.length) { oldk=k; k=this.killStuff(k, opening, closing, subopening, subclosing, repl); } this.data=k; }; /**
@private
- /
Previewmaker.prototype.killStuff = function (txt, opening, closing, subopening, subclosing, repl) { var op=this.makeRegexp(opening); var cl=this.makeRegexp(closing, '^'); var sb=subopening ? this.makeRegexp(subopening, '^') : null; var sc=subclosing ? this.makeRegexp(subclosing, '^') : cl; if (!op || !cl) { alert('Navigation Popups error: op or cl is null! something is wrong.'); return; } if (!op.test(txt)) { return txt; } var ret=; var opResult = op.exec(txt); ret = txt.substring(0,opResult.index); txt=txt.substring(opResult.index+opResult[0].length); var depth = 1; while (txt.length > 0) { var removal=0; if (depth==1 && cl.test(txt)) { depth--; removal=cl.exec(txt)[0].length; } else if (depth > 1 && sc.test(txt)) { depth--; removal=sc.exec(txt)[0].length; }else if (sb && sb.test(txt)) { depth++; removal=sb.exec(txt)[0].length; } if ( !removal ) { removal = 1; } txt=txt.substring(removal); if (depth==0) { break; } } return ret + (repl || ) + txt; }; /**
@private
- /
Previewmaker.prototype.makeRegexp = function (x, prefix, suffix) { prefix = prefix || ; suffix = suffix || ; var reStr=; var flags=; if (isString(x)) { reStr=prefix + literalizeRegex(x) + suffix; } else if (isRegExp(x)) { var s=x.toString().substring(1); var sp=s.split('/'); flags=sp[sp.length-1]; sp[sp.length-1]=; s=sp.join('/'); s=s.substring(0,s.length-1); reStr= prefix + s + suffix; } else { log ('makeRegexp failed'); }
log ('makeRegexp: got reStr=' + reStr + ', flags=' + flags); return RegExp(reStr, flags); }; /**
@private
- /
Previewmaker.prototype.killBoxTemplates = function () {
// taxobox removal... in fact, there's a saudiprincebox_begin, so let's be more general // also, have float_begin, ... float_end this.kill(RegExp('[{][{][^{}\\s|]*?(float|box)[_ ](begin|start)', 'i'), /[}][}]\s*/, '{{');
// infoboxes etc // from User:Zyxw/popups.js: kill frames too this.kill(RegExp('[{][{][^{}\\s|]*?(infobox|elementbox|frame)[_ ]', 'i'), /[}][}]\s*/, '{{');
}; /**
@private
- /
Previewmaker.prototype.killTemplates = function () { this.kill(, , '{', '}', ' '); }; /**
@private
- /
Previewmaker.prototype.killTables = function () { // tables are bad, too // this can be slow, but it's an inprovement over a browser hang // torture test: Comparison_of_Intel_Central_Processing_Units this.kill('{|', /[|]}\s*/, '{|'); this.kill(/<table.*?>/i, /<\/table.*?>/i, /<table.*?>/i); // remove lines starting with a pipe for the hell of it (?) this.data=this.data.replace(RegExp('^[|].*$', 'mg'), ); }; /**
@private
- /
Previewmaker.prototype.killImages = function () { var forbiddenNamespaceAliases = []; jQuery.each(mw.config.get('wgNamespaceIds'), function(_localizedNamespaceLc, _namespaceId) { if (_namespaceId!=pg.nsImageId && _namespaceId!=pg.nsCategoryId) return; forbiddenNamespaceAliases.push(_localizedNamespaceLc.split(' ').join('[ _]')); //todo: escape regexp fragments! });
// images and categories are a nono this.kill(RegExp('[[][[]\\s*(' + forbiddenNamespaceAliases.join('|') + ')\\s*:', 'i'), /\]\]\s*/, '[', ']'); }; /**
@private
- /
Previewmaker.prototype.killHTML = function () { // kill <ref ...>...</ref> this.kill(/<ref\b[^/>]*?>/i, /<\/ref>/i);
// let's also delete entire lines starting with <. it's worth a try. this.data=this.data.replace(RegExp('(^|\\n) *<.*', 'g'), '\n');
// and those pesky html tags, but not or <blockquote> var splitted=this.data.parenSplit(/(<.*?>)/); var len=splitted.length; for (var i=1; i<len; i=i+2) { switch (splitted[i]) { case '<nowiki>': case '': break; default: if (! /^< *\/? *blockquote\b/i.test(splitted[i])) { splitted[i]=; } } } this.data=splitted.join(); }; /**
@private
- /
Previewmaker.prototype.killChunks = function() { // heuristics alert // chunks of italic text? you crazy, man? var italicChunkRegex=new RegExp ("((^|\\n)\\s*:*\\s*[^']([^']||'[^']){20}(.|\\n[^\\n])*[.!?\\s]*\\n)+", 'g'); // keep stuff separated, though, so stick in \n (fixes Union Jack? this.data=this.data.replace(italicChunkRegex, '\n'); }; /**
@private
- /
Previewmaker.prototype.mopup = function () { // we simply *can't* be doing with horizontal rules right now this.data=this.data.replace(RegExp('^-{4,}','mg'),);
// no indented lines this.data=this.data.replace(RegExp('(^|\\n) *:[^\\n]*','g'), );
// replace , and whatever else there is// this'll probably do this.data=this.data.replace(RegExp('^__[A-Z_]*__ *$', 'gmi'),); }; /**
@private
- /
Previewmaker.prototype.firstBit = function () { // dont't be givin' me no subsequent paragraphs, you hear me? /// first we "normalize" section headings, removing whitespace after, adding before var d=this.data;
if (getValueOf('popupPreviewCutHeadings')) { this.data=this.data.replace(RegExp('\\s*(==+[^=]*==+)\\s*', 'g'), '\n\n$1 '); /// then we want to get rid of paragraph breaks whose text ends badly this.data=this.data.replace(RegExp('([:;]) *\\n{2,}', 'g'), '$1\n');
this.data=this.data.replace(RegExp('^[\\s\\n]*'), ); stuff=(RegExp('^([^\\n]|\\n[^\\n\\s])*')).exec(this.data); if (stuff) { d = stuff[0]; } if (!getValueOf('popupPreviewFirstParOnly')) { d = this.data; }
/// now put \n\n after sections so that bullets and numbered lists work d=d.replace(RegExp('(==+[^=]*==+)\\s*', 'g'), '$1\n\n'); }
// superfluous sentences are RIGHT OUT.
// note: exactly 1 set of parens here needed to make the slice work
d = d.parenSplit(RegExp('([!?.]+["'+"'"+']*\\s)','g'));
// leading space is bad, mmkay?
d[0]=d[0].replace(RegExp('^\\s*'), );
var notSentenceEnds=RegExp('([^.][a-z][.] *[a-z]|etc|sic|Dr|Mr|Mrs|Ms|St|no|op|cit|\\^\\*|\\s[A-Zvclm])$', 'i'); d = this.fixSentenceEnds(d, notSentenceEnds);
this.fullLength=d.join().length; var maxChars=getValueOf('popupMaxPreviewCharacters') + this.extraCharacters; var n=this.maxSentences; var dd=this.firstSentences(d,n);
do { dd=this.firstSentences(d,n); --n; } while ( dd.length > this.maxCharacters && n != 0 );
this.data = dd; }; /**
@private
- /
Previewmaker.prototype.fixSentenceEnds = function(strs, reg) { // take an array of strings, strs // join strs[i] to strs[i+1] & strs[i+2] if strs[i] matches regex reg
var abbrevRe=/\b[a-z][^a-z]*$/i;
for (var i=0; i<strs.length-2; ++i) { if (reg.test(strs[i])) { a=[]; for (var j=0; j<strs.length; ++j) { if (j<i) a[j]=strs[j]; if (j==i) a[i]=strs[i]+strs[i+1]+strs[i+2]; if (j>i+2) a[j-2]=strs[j]; } return this.fixSentenceEnds(a,reg); } // BUGGY STUFF - trying to fix up S. C. Johnson & Son preview if (false && abbrevRe.test(strs[i])) { var j=i, buf=; do { buf=buf+strs[i]+strs[i+1]; i=i+2; } while (i<strs.length-2 && abbrevRe.test(strs[i])); strs[i]=buf+strs[i]; var a=(j?strs.slice(0,j-1):[]).concat(strs.slice(i)); return this.fixSentenceEnds(a,reg); } } return strs; }; /**
@private
- /
Previewmaker.prototype.firstSentences = function(strs, howmany) { var t=strs.slice(0, 2*howmany); return t.join(); }; /**
@private
- /
Previewmaker.prototype.killBadWhitespace = function() { // also cleans up isolated ', eg Suntory Sungoliath this.data=this.data.replace(RegExp('^ *\'+ *$', 'gm'), ); }; /**
Runs the various methods to generate the preview.
The preview is stored in the html</html> field.
@private
- /
Previewmaker.prototype.makePreview = function() {
if (this.owner.article.namespaceId()!=pg.nsTemplateId &&
this.owner.article.namespaceId()!=pg.nsImageId ) {
this.killComments();
this.killDivs();
this.killGalleries();
this.killBoxTemplates();
if (getValueOf('popupPreviewKillTemplates')) {
this.killTemplates();
} else {
this.killMultilineTemplates();
}
this.killTables();
this.killImages();
this.killHTML();
this.killChunks();
this.mopup();
this.firstBit();
this.killBadWhitespace();
}
else
{
this.killHTML();
}
this.html=wiki2html(this.data, this.baseUrl); // needs livepreview
this.fixHTML();
this.stripLongTemplates();
};
/**
@private
- /
Previewmaker.prototype.esWiki2HtmlPart = function(data) {
var reLinks = /(?:\[\[([^|\]]*)(?:\|([^|\]]*))*]]([a-z]*))/gi; //match a wikilink
reLinks.lastIndex = 0; //reset regex
var match;
var result = "";
var postfixIndex = 0;
while ((match = reLinks.exec(data)) != null) //match all wikilinks
{
//FIXME: the way that link is built here isn't perfect. It is clickable, but popups preview won't recognize it in some cases.
result += escapeQuotesHTML(data.substring(postfixIndex, match.index)) +
'<a href="'+Insta.conf.paths.articles+escapeQuotesHTML(match[1])+'">'+escapeQuotesHTML((match[2]?match[2]:match[1])+match[3])+"</a>";
postfixIndex = reLinks.lastIndex;
}
//append the rest
result += escapeQuotesHTML(data.substring(postfixIndex));
return result;
};
Previewmaker.prototype.editSummaryPreview=function() {
var reAes = /\/\* *(.*?) *\*\//g; //match the first section marker
reAes.lastIndex = 0; //reset regex
var match;
match = reAes.exec(this.data);
if (match)
{
//we have a section link. Split it, process it, combine it.
var prefix = this.data.substring(0,match.index-1);
var section = match[1];
var postfix = this.data.substring(reAes.lastIndex);
var start = "";
var end = "";
if (prefix.length>0) start = this.esWiki2HtmlPart(prefix) + " " + start + "- ";
if (postfix.length>0) end = ": " + end + this.esWiki2HtmlPart(postfix);
var t=new Title().fromURL(this.baseUrl);
t.anchorFromUtf(section);
var sectionLink = Insta.conf.paths.articles + escapeQuotesHTML(t.toString(true)) + '#' + escapeQuotesHTML(t.anchor);
return start + '<a href="'+sectionLink+'">→</a> '+escapeQuotesHTML(section) + end;
}
//else there's no section link, htmlify the whole thing.
return this.esWiki2HtmlPart(this.data);
};
//<NOLITE>
/** Test function for debugging preview problems one step at a time.
*/
function previewSteps(txt) {
try {
txt=txt || document.editform.wpTextbox1.value;
} catch (err) {
if (pg.cache.pages.length > 0) {
txt=pg.cache.pages[pg.cache.pages.length-1].data;
} else {
alert('provide text or use an edit page');
}
}
txt=txt.substring(0,10000);
var base=pg.wiki.articlebase + Title.fromURL(document.location.href).urlString();
var p=new Previewmaker(txt, base, pg.current.link.navpopup);
if (this.owner.article.namespaceId() != pg.nsTemplateId) {
p.killComments(); if (!confirm('done killComments(). Continue?\n---\n' + p.data)) { return; }
p.killDivs(); if (!confirm('done killDivs(). Continue?\n---\n' + p.data)) { return; }
p.killGalleries(); if (!confirm('done killGalleries(). Continue?\n---\n' + p.data)) { return; }
p.killBoxTemplates(); if (!confirm('done killBoxTemplates(). Continue?\n---\n' + p.data)) { return; }
if (getValueOf('popupPreviewKillTemplates')) {
p.killTemplates(); if (!confirm('done killTemplates(). Continue?\n---\n' + p.data)) { return; }
} else {
p.killMultilineTemplates(); if (!confirm('done killMultilineTemplates(). Continue?\n---\n' + p.data)) { return; }
}
p.killTables(); if (!confirm('done killTables(). Continue?\n---\n' + p.data)) { return; }
p.killImages(); if (!confirm('done killImages(). Continue?\n---\n' + p.data)) { return; }
p.killHTML(); if (!confirm('done killHTML(). Continue?\n---\n' + p.data)) { return; }
p.killChunks(); if (!confirm('done killChunks(). Continue?\n---\n' + p.data)) { return; }
p.mopup(); if (!confirm('done mopup(). Continue?\n---\n' + p.data)) { return; }
p.firstBit(); if (!confirm('done firstBit(). Continue?\n---\n' + p.data)) { return; }
p.killBadWhitespace(); if (!confirm('done killBadWhitespace(). Continue?\n---\n' + p.data)) { return; }
}
p.html=wiki2html(p.data, base); // needs livepreview
p.fixHTML(); if (!confirm('done fixHTML(). Continue?\n---\n' + p.html)) { return; }
p.stripLongTemplates(); if (!confirm('done stripLongTemplates(). Continue?\n---\n' + p.html)) { return; }
alert('finished preview - end result follows.\n---\n' + p.html);
}
//</NOLITE>
/**
Works around a quoting bug in livepreview.
wiki2html('Foo\'s "bar"')
gives @literal{<a href='Foo's "bar"'>}
which doesn't do very well. We change this into @literal{<a href="Foo's %22bar%22">}
@private
- /
Previewmaker.prototype.fixHTML = function() {
if(!this.html) return;
// all links seem to have potential issues with quotation marks
var splitted=this.html.parenSplit(/href='([^>]*)'/g);
var ret=;
for (var i=0; i<splitted.length; ++i) {
if(i%2==0) { ret += splitted[i]; continue; }
if(i%2==1) { ret += 'href="' + splitted[i].split('"').join('%22') + '"'; }
}
// fix question marks in wiki links
// maybe this'll break some stuff :-(
ret=ret.replace(RegExp('\(<a href="' + pg.wiki.articlePath + '/[^"]*\)[?]\(.*?"\)', 'g'), '$1%3F$2');
// FIXME fix up % too
this.html=ret;
};
/**
Generates the preview and displays it in the current popup.
Does nothing if the generated preview is invalid or consists of whitespace only.
Also activates wikilinks in the preview for subpopups if the popupSubpopups option is true.
- /
Previewmaker.prototype.showPreview = function () {
this.makePreview();
if (typeof this.html != typeof ) return;
if (RegExp('^\\s*$').test(this.html)) return;
setPopupHTML('
', 'popupPrePreviewSep', this.owner.idNumber);
setPopupTipsAndHTML(this.html, 'popupPreview', this.owner.idNumber, { owner: this.owner });
var more = (this.fullLength > this.data.length) ? this.moreLink() : ;
setPopupHTML(more, 'popupPreviewMore', this.owner.idNumber);
};
/**
@private
- /
Previewmaker.prototype.moreLink=function() {
var a=document.createElement('a');
a.className='popupMoreLink';
a.innerHTML=popupString('more...');
var savedThis=this;
a.onclick=function() {
savedThis.maxCharacters+=2000;
savedThis.maxSentences+=20;
savedThis.setData();
savedThis.showPreview();
}
return a;
}
/**
@private
- /
Previewmaker.prototype.stripLongTemplates = function() {
// operates on the HTML!
this.html=this.html.replace(RegExp('^.{0,1000}[{][{][^}]*?(<(p|br)( /)?>\\s*){2,}([^{}]*?[}][}])?', 'gi'), );
this.html=this.html.split('\n').join(' '); // workaround for templates
this.html=this.html.replace(RegExp('[{][{][^}]*<pre>[^}]*[}][}]','gi'), '');
};
/**
@private
*/
Previewmaker.prototype.killMultilineTemplates = function() {
this.kill('{{{', '}}}');
this.kill(RegExp('\\s*[{][{][^{}]*\\n'), '}}', '{{');
};
// ENDFILE: previewmaker.js
// STARTFILE: querypreview.js
function loadAPIPreview(queryType, article, navpop) {
var art=new Title(article).urlString();
var url=pg.wiki.apiwikibase + '?format=json&action=query&';
var htmlGenerator=function(a,d){alert('invalid html generator');};
switch (queryType) {
case 'history':
url += 'meta=userinfo&uiprop=options&titles=' + art + '&prop=revisions&rvlimit=' +
getValueOf('popupHistoryPreviewLimit');
htmlGenerator=APIhistoryPreviewHTML;
break;
case 'category':
url += 'list=categorymembers&cmtitle=' + art;
htmlGenerator=APIcategoryPreviewHTML;
break;
case 'userinfo':
var username = new Title( article ).userName();
var usernameart = encodeURIComponent( username );
if (pg.re.ipUser.test(username)) {
url += 'list=blocks&bkprop=range&bkip=' + usernameart;
} else {
url += 'list=users&usprop=blockinfo|groups|editcount|registration&ususers=' + usernameart + "&meta=globaluserinfo&guiprop=groups|unattached&guiuser="+ usernameart;
}
htmlGenerator=APIuserInfoPreviewHTML;
break;
case 'contribs':
var usernameart = encodeURIComponent( new Title( article ).userName() );
url += 'list=usercontribs&meta=userinfo&uiprop=options&ucuser=' + usernameart +
'&uclimit=' + getValueOf('popupContribsPreviewLimit');
htmlGenerator=APIcontribsPreviewHTML;
break;
case 'imagepagepreview':
var trail='';
if (getValueOf('popupImageLinks')) { trail = '&list=imageusage&iutitle=' + art; }
url += 'titles=' + art + '&prop=revisions|imageinfo&rvprop=content' + trail;
htmlGenerator=APIimagepagePreviewHTML;
break;
case 'backlinks':
url += 'list=backlinks&bltitle=' + art;
htmlGenerator=APIbacklinksPreviewHTML;
break;
}
pendingNavpopTask(navpop);
if( !window.wgEnableAPI || !wgEnableAPI ) {
/* The API is not available */
htmlGenerator=function(a,d){
return 'This function of navigation popups now requires a MediaWiki ' +
'installation with the <a href="http://www.mediawiki.org/wiki/API">API</a> enabled.'; };
}
var callback=function(d){
log( "callback of API functions was hit" );
showAPIPreview(queryType, htmlGenerator(article,d,navpop), navpop.idNumber, navpop, d);
};
if (pg.flag.isIE) {
url = url + '&*'; //to circumvent https://bugzilla.wikimedia.org/show_bug.cgi?id=28840
}
var go = function(){
getPageWithCaching(url, callback, navpop);
return true;
}
if (navpop.visible || !getValueOf('popupLazyDownloads')) { go(); }
else { navpop.addHook(go, 'unhide', 'before', 'DOWNLOAD_'+queryType+'_QUERY_DATA'); }
}
function linkList(list) {
list.sort(function(x,y) { return (x==y ? 0 : (x<y ? -1 : 1)); });
var buf=[];
for (var i=0; i<list.length; ++i) {
buf.push(wikiLink({article: new Title(list[i]),
text: list[i].split(' ').join(' '),
action: 'view'}));
}
return buf.join(', ');
}
function getTimeOffset(tz) {
if( tz ) {
if( tz.indexOf('|') > -1 ) {
// New format
return parseInt(tz.split('|')[1],10);
} else if ( tz.indexOf(':') > -1 ) {
// Old format
return( parseInt(tz,10)*60 + parseInt(tz.split(':')[1],10) );
}
}
return 0;
}
function editPreviewTable(article, h, reallyContribs, timeOffset) {
var html=['<table>'];
var day=null;
var curart=article;
for (var i=0; i<h.length; ++i) {
if (reallyContribs) {
var page=h[i]['title']; curart = new Title(page);
}
var minor=typeof h[i]['minor']=='undefined' ? '' : '<b>m </b>';
var editDate=adjustDate(getDateFromTimestamp(h[i].timestamp), timeOffset);
var thisDay = dayFormat(editDate);
var thisTime = timeFormat(editDate);
if (thisDay==day) { thisDay=''; }
else { day=thisDay; }
if (thisDay) {
html.push( '<tr><td colspan=3><span class="popup_history_date">' +
thisDay+'</span></td></tr>' );
}
html.push('<tr class="popup_history_row_' + ( (i%2) ? 'odd' : 'even') + '">');
html.push('<td>(<a href="' + pg.wiki.titlebase + new Title(curart).urlString() +
'&diff=prev&oldid=' + h[i]['revid'] + '">' + popupString('last') + '</a>)</td>');
html.push('<td>' +
'<a href="' + pg.wiki.titlebase + new Title(curart).urlString() +
'&oldid=' + h[i]['revid'] + '">' + thisTime + '</a></td>');
var col3url='', col3txt='';
if (!reallyContribs) {
var user=h[i]['user'];
if( typeof h[i]['userhidden'] == "undefined" ) {
if( pg.re.ipUser.test(user) ) {
col3url=pg.wiki.titlebase + mw.config.get('wgFormattedNamespaces')[pg.nsSpecialId] + ':Contributions&target=' + new Title(user).urlString();
} else {
col3url=pg.wiki.titlebase + mw.config.get('wgFormattedNamespaces')[pg.nsUserId] + ':' + new Title(user).urlString();
}
col3txt=escapeQuotesHTML(user);
} else {
col3url=getValueOf('popupRevDelUrl');
col3txt=escapeQuotesHTML( popupString('revdel'));
}
} else {
col3url=pg.wiki.titlebase + curart.urlString();
col3txt=escapeQuotesHTML(page);
}
html.push('<td>' + (reallyContribs ? minor : '') +
'<a href="' + col3url + '">' + col3txt + '</a></td>');
var comment='';
var c=h[i].comment || h[i]['*'];
if (c) {
comment=new Previewmaker(c, new Title(curart).toUrl()).editSummaryPreview();
} else if (typeof h[i]['commenthidden'] != "undefined" ) {
comment=popupString('revdel');
}
html.push('<td>' + (!reallyContribs ? minor : '') + comment + '</td>');
html.push('</tr>');
html=[html.join('')];
}
html.push('</table>');
return html.join('');
}
function getDateFromTimestamp(t) {
var s=t.split(/[^0-9]/);
switch(s.length) {
case 0: return null;
case 1: return new Date(s[0]);
case 2: return new Date(s[0], s[1]-1);
case 3: return new Date(s[0], s[1]-1, s[2]);
case 4: return new Date(s[0], s[1]-1, s[2], s[3]);
case 5: return new Date(s[0], s[1]-1, s[2], s[3], s[4]);
case 6: return new Date(s[0], s[1]-1, s[2], s[3], s[4], s[5]);
default: return new Date(s[0], s[1]-1, s[2], s[3], s[4], s[5], s[6]);
}
}
function adjustDate(d, offset) {
// offset is in minutes
var o=offset * 60 * 1000;
return new Date( +d + o);
}
function dayFormat(editDate, utc) {
if (utc) { return map(zeroFill, [editDate.getUTCFullYear(), editDate.getUTCMonth()+1, editDate.getUTCDate()]).join('-'); }
return map(zeroFill, [editDate.getFullYear(), editDate.getMonth()+1, editDate.getDate()]).join('-');
}
function timeFormat(editDate, utc) {
if (utc) { return map(zeroFill, [editDate.getUTCHours(), editDate.getUTCMinutes(), editDate.getUTCSeconds()]).join(':'); }
return map(zeroFill, [editDate.getHours(), editDate.getMinutes(), editDate.getSeconds()]).join(':');
}
function showAPIPreview(queryType, html, id, navpop, download) {
// DJ: done
var target='popupPreview';
switch (queryType) {
case 'imagelinks':
case 'category':
case 'userinfo':
target='popupPostPreview'; break;
}
setPopupTipsAndHTML(html, target, id);
completedNavpopTask(navpop);
}
function APIbacklinksPreviewHTML(article, download, navpop) {
try {
var jsObj=getJsObj(download.data);
var list=jsObj.query.backlinks;
} catch (someError) { return 'backlinksPreviewHTML went wonky'; }
var html=[];
if (!list) { return popupString('No backlinks found'); }
for ( var i=0; i < list.length; i++ ) {
var t=new Title(list[i]['title']);
html.push('<a href="' + pg.wiki.titlebase + t.urlString() + '">' + t + '</a>');
}
html=html.join(', ');
if (jsObj['query-continue'] && jsObj['query-continue'].backlinks && jsObj['query-continue'].backlinks.blcontinue) {
html += popupString(' and more');
}
return html;
}
function APIsharedImagePagePreviewHTML(obj) {
log( "APIsharedImagePagePreviewHTML" );
var popupid = obj['requestid'];
if( obj['query'] && obj['query']['pages'] )
{
var page=anyChild(obj['query']['pages']);
var content=(page && page.revisions ) ? page.revisions[0]['*'] : null;
if( content )
{
/* Not entirely safe, but the best we can do */
var p=new Previewmaker(content, pg.current.link.navpopup.article, pg.current.link.navpopup);
p.makePreview();
setPopupHTML( p.html, "popupSecondPreview", popupid );
}
}
}
function APIimagepagePreviewHTML(article, download, navpop) {
try {
var jsObj=getJsObj(download.data);
var page=anyChild(jsObj.query.pages);
var content=(page && page.revisions ) ? page.revisions[0]['*'] : null;
} catch (someError) {
return 'API imagepage preview failed :(';
}
var ret='';
var alt='';
try{alt=navpop.parentAnchor.childNodes[0].alt;} catch(e){}
if (alt) {
ret = ret + '<hr><b>' + popupString('Alt text:') + '</b> ' + escapeQuotesHTML(alt);
}
if (content) {
var p=prepPreviewmaker(content, article, navpop);
p.makePreview();
if (p.html) { ret += '<hr>' + p.html; }
}
if (content!==null && getValueOf('popupSummaryData')) {
var info=getPageInfo(content, download);
log(info);
setPopupTrailer(info, navpop.idNumber);
}
if (page && page.imagerepository == "shared" ) {
var art=new Title(article);
var encart = encodeURIComponent( "File:" + art.stripNamespace() );
var shared_url = pg.wiki.apicommonsbase + '?format=json&callback=APIsharedImagePagePreviewHTML' +
'&requestid=' + navpop.idNumber +
'&action=query&prop=revisions&rvprop=content&titles=' + encart;
if (pg.flag.isIE) {
shared_url = shared_url + '&*'; //to circumvent https://bugzilla.wikimedia.org/show_bug.cgi?id=28840
}
ret = ret +'<hr>' + popupString( 'Image from Commons') +
': <a href="' + pg.wiki.commonsbase + '?title=' + encart + '">' +
popupString( 'Description page') + '</a>';
importScriptURI( shared_url );
}
showAPIPreview('imagelinks', APIimagelinksPreviewHTML(article,download), navpop.idNumber, download);
return ret;
}
function APIimagelinksPreviewHTML(article, download) {
try {
var jsobj=getJsObj(download.data);
var list=jsobj.query.imageusage;
if (!list) { return popupString('No image links found'); }
} catch(someError) { return 'Image links preview generation failed :('; }
var ret=[];
for (var i=0; i < list.length; i++) {
ret.push(list[i]['title']);
}
if (ret.length === 0) { return popupString('No image links found'); }
return '<h2>' + popupString('File links') + '</h2>' + linkList(ret);
}
function APIcategoryPreviewHTML(article, download) {
try{
var jsobj=getJsObj(download.data);
var list=jsobj.query.categorymembers;
} catch(someError) { return 'Category preview failed :('; }
var ret=[];
for (var p=0; p < list.length; p++) {
ret.push(list[p]['title']);
}
if (ret.length === 0) { return popupString('Empty category'); }
ret = '<h2>' + tprintf('Category members (%s shown)', [ret.length]) + '</h2>' +linkList(ret);
if (jsobj['query-continue'] && jsobj['query-continue'].categorymembers && jsobj['query-continue'].categorymembers.cmcontinue) {
ret += popupString(' and more');
}
return ret;
}
function APIuserInfoPreviewHTML(article, download) {
var ret=[];
try{
var queryobj=getJsObj(download.data).query;
} catch(someError) { return 'Userinfo preview failed :('; }
var user=anyChild(queryobj.users);
if (user) {
var globaluserinfo=queryobj.globaluserinfo;
if (user.invalid == '') {
ret.push( popupString( 'Invalid user') );
} else if (user.missing == '') {
ret.push( popupString( 'Not a registered username') );
}
if( user.blockedby )
ret.push('<b>' + popupString('BLOCKED') + '</b>');
if( globaluserinfo && (globaluserinfo.locked != null || globaluserinfo.hidden != null) ) {
var lockedSulAccountIsAttachedToThis = true;
for( var i=0; globaluserinfo.unattached && i < globaluserinfo.unattached.length; i++) {
if (globaluserinfo.unattached[i].wiki===wgDBname) { lockedSulAccountIsAttachedToThis=false; break; }
}
if (lockedSulAccountIsAttachedToThis) {
if (globaluserinfo.locked != null) ret.push('<b><i>' + popupString('LOCKED') + '</i></b>');
if (globaluserinfo.hidden != null) ret.push('<b><i>' + popupString('HIDDEN') + '</i></b>');
}
}
for( var i=0; (user.groups && i < user.groups.length); i++) {
switch (user.groups[i]) {
case '*':
case 'user':
case 'autoconfirmed':
break;
default:
ret.push( escapeQuotesHTML(user.groups[i]) );
}
}
for( var i=0; (globaluserinfo && globaluserinfo.groups && i < globaluserinfo.groups.length); i++) {
ret.push( '<i>'+escapeQuotesHTML(globaluserinfo.groups[i])+'</i>' );
}
if( user.editcount || user.registration )
ret.push( escapeQuotesHTML((user.editcount?user.editcount:'') + popupString(' edits since: ') + (user.registration?dayFormat(getDateFromTimestamp(user.registration)):'')) );
}
if (queryobj.blocks) {
ret.push( popupString( 'IP user') ); //we only request list=blocks for IPs
for (var i=0; i<queryobj.blocks.length; i++) {
ret.push('<b>' + popupString(queryobj.blocks[i].rangestart===queryobj.blocks[i].rangeend ? 'BLOCKED' : 'RANGEBLOCKED') + '</b>' );
}
}
ret = '<hr>' + ret.join( ', ' );
return ret;
}
function APIcontribsPreviewHTML(article, download, navpop) {
return APIhistoryPreviewHTML(article, download, navpop, true);
}
function APIhistoryPreviewHTML(article, download, navpop, reallyContribs) {
try {
var jsobj=getJsObj(download.data);
var tz=jsobj.query.userinfo.options.timecorrection;
if( reallyContribs )
var edits=jsobj.query.usercontribs;
else
var edits=anyChild(jsobj.query.pages)['revisions'];
} catch (someError) {
return 'History preview failed :-(';
}
var timeOffset = getTimeOffset(tz);
Cookie.create('popTz', timeOffset, 1);
var ret=editPreviewTable(article, edits, reallyContribs, timeOffset);
return ret;
}
//</NOLITE>
// ENDFILE: querypreview.js
// STARTFILE: debug.js
////////////////////////////////////////////////////////////////////
// Debugging functions
////////////////////////////////////////////////////////////////////
function log(){}; // dummy to stop errors
function setupDebugging() {
//<NOLITE>
if (window.popupDebug) { // popupDebug is set from .version
window.log=function(x) { //if(gMsg!='')gMsg += '\n'; gMsg+=time() + ' ' + x; };
window.console.log(x);
}
window.errlog=function(x) {
window.console.error(x);
}
log('Initializing logger');
} else {
//</NOLITE>
window.log = function(x) {};
window.errlog = function(x) {};
//<NOLITE>
}
//</NOLITE>
}
// ENDFILE: debug.js
// STARTFILE: images.js
// load image of type Title.
function loadImage(image, navpop) {
if (typeof image.stripNamespace != 'function') { alert('loadImages bad'); }
// API call to retrieve image info.
if (!getValueOf('popupImages') || !window.wgEnableAPI || !wgEnableAPI) return;
if (!isValidImageName(image)) return false;
var art=image.urlString();
var url=pg.wiki.apiwikibase + '?format=json&action=query';
url += '&prop=imageinfo&iiprop=url|mime&iiurlwidth=' + getValueOf('popupImageSizeLarge');;
url += '&titles=' + art;
if (pg.flag.isIE) {
url = url + '&*'; //to circumvent https://bugzilla.wikimedia.org/show_bug.cgi?id=28840
}
pendingNavpopTask(navpop);
var callback=function(d){
popupsInsertImage(navpop.idNumber, navpop, d);
};
var go = function(){
getPageWithCaching(url, callback, navpop);
return true;
}
if (navpop.visible || !getValueOf('popupLazyDownloads')) { go(); }
else { navpop.addHook(go, 'unhide', 'after', 'DOWNLOAD_IMAGE_QUERY_DATA
</code>
==[[MediaWiki:Print.css]]==
<pre>
/* Do not print:
1: When in mainspace: Article message boxes,
navboxes, sister project boxes, disambig links,
and items marked as metadata.
2: Privacy, about, disclaimer, redirect and section edit links.
3: Show/hide toggles for collapsible items.
4: Items marked as noprint.
5: Also will not print any references if we were to have any.
*/
.ns-0 .ambox,
.ns-0 .navbox,
.ns-0 .vertical-navbox,
.ns-0 .infobox.sisterproject,
.ns-0 .dablink,
.ns-0 .metadata,
#filetoc,
#footer-places,
#mobileview,
.editlink,
a.NavToggle, span.collapseButton, span.mw-collapsible-toggle,
.noprint {
display: none !important;
}
/* Add formatting to make sure that "external references" from templates
like [[Template:Ref]] do not get URL expansion, not even when printed.
The anchor itself has class "external autonumber" and the url expansion
is inserted when printing (see the common printing style sheet at
http://en.wikipedia.org/skins-1.5/common/commonPrint.css) using the
":after" pseudo-element of CSS. Also hide in <cite> elements.
*/
#content cite a.external.text:after,
.nourlexpansion a.external.text:after,
.nourlexpansion a.external.autonumber:after {
display: none !important;
}
/* Uncollapse collapsible tables/divs.
The proper way to do this for tables is to use display:table-row,
but this is not supported by all browsers, so use display:block as fallback.
*/
table.collapsible tr, div.NavPic, div.NavContent {
display: block !important;
}
table.collapsible tr {
display: table-row !important;
}
/* Hiding some items when printing with Simple skin */
.skin-simple div#column-one,
.skin-simple div#f-poweredbyico,
.skin-simple div#f-copyrightico,
.skin-simple .editsection {
display: none;
}
/* On websites with siteSub visible, the margin on the firstHeading is not needed. */
#firstHeading {
margin: 0px;
}
</code>
{{TitledBox/end}}
==[[MediaWiki:Edittools.js]]==
<code javascript>
//If you wish to change this, contact Tomtomn00 on his talk page.
//
//
if (typeof (EditTools_set_focus) == 'undefined')
var EditTools_set_focus = true;
if (typeof (EditTools_set_focus_initially) == 'undefined')
var EditTools_set_focus_initially = EditTools_set_focus;
var EditTools =
{
charinsert : {
'Insert': ' – — ‘+’ “+” ° ″ ′ ≈ ≠ ≤ ≥ ± − × ÷ √ ← → · § Sign_your_posts_on_talk_pages: ~~\~~ Cite_your_sources: <ref>+</ref>',
'Wiki markup': 'Insert: – — ‘+’ “+” ° ″ ′ ≈ ≠ ≤ ≥ ± − × ÷ √ ← → · § ~~\~~ <ref>+</ref> Wiki_markup: {\{+}} {\{\{+}}} | [+] [\[+]] [\[Category:+]] #REDIRECT.[\[+]] <s>+</s> <sup>+</sup> <sub>+</sub> <code>+</code> <pre>+
+
<ref.name="+"/> {\{#tag:ref|+|group="nb"|name=""}} {\{Reflist}} <references/> + {\{DEFAULTSORT:+}} + <span.class="plainlinks">+',
'Symbols': '~ | ¡¿†‡↔↑↓•¶ # ½⅓⅔¼¾⅛⅜⅝⅞∞ ‘+’ “+” ‹+› «+» ⟨+⟩ ¤₳฿₵¢₡₢$₫₯€₠₣ƒ₴₭₤ℳ₥₦№₧₰£៛₨₪৳₮₩¥ ♠♣♥♦ m² m³ ♭♯♮ ©®™ ◌ {\{Unicode|+}}',
'Latin': 'A a Á á À à  â Ä ä Ǎ ǎ Ă ă Ā ā à ã Å å Ą ą Æ æ Ǣ ǣ B b C c Ć ć Ċ ċ Ĉ ĉ Č č Ç ç D d Ď ď Đ đ Ḍ ḍ Ð ð E e É é È è Ė ė Ê ê Ë ë Ě ě Ĕ ĕ Ē ē Ẽ ẽ Ę ę Ẹ ẹ Ɛ ɛ Ə ə F f G g Ġ ġ Ĝ ĝ Ğ ğ Ģ ģ H h Ĥ ĥ Ħ ħ Ḥ ḥ I i İ ı Í í Ì ì Î î Ï ï Ǐ ǐ Ĭ ĭ Ī ī Ĩ ĩ Į į Ị ị J j Ĵ ĵ K k Ķ ķ L l Ĺ ĺ Ŀ ŀ Ľ ľ Ļ ļ Ł ł Ḷ ḷ Ḹ ḹ M m Ṃ ṃ N n Ń ń Ň ň Ñ ñ Ņ ņ Ṇ ṇ Ŋ ŋ O o Ó ó Ò ò Ô ô Ö ö Ǒ ǒ Ŏ ŏ Ō ō Õ õ Ǫ ǫ Ọ ọ Ő ő Ø ø Œ œ Ɔ ɔ P p Q q R r Ŕ ŕ Ř ř Ŗ ŗ Ṛ ṛ Ṝ ṝ S s Ś ś Ŝ ŝ Š š Ş ş Ș ș Ṣ ṣ ß T t Ť ť Ţ ţ Ț ț Ṭ ṭ Þ þ U u Ú ú Ù ù Û û Ü ü Ǔ ǔ Ŭ ŭ Ū ū Ũ ũ Ů ů Ų ų Ụ ụ Ű ű Ǘ ǘ Ǜ ǜ Ǚ ǚ Ǖ ǖ V v W w Ŵ ŵ X x Y y Ý ý Ŷ ŷ Ÿ ÿ Ỹ ỹ Ȳ ȳ Z z Ź ź Ż ż Ž ž ß Ð ð Þ þ Ŋ ŋ Ə ə {\{Unicode|+}}',
'Greek': 'ΆάΈέΉήΊίΌόΎύΏώ ΑαΒβΓγΔδ ΕεΖζΗηΘθ ΙιΚκΛλΜμ ΝνΞξΟοΠπ ΡρΣσςΤτΥυ ΦφΧχΨψΩω ᾼᾳᾴᾺὰᾲᾶᾷἈἀᾈᾀἉἁᾉᾁἌἄᾌᾄἊἂᾊᾂἎἆᾎᾆἍἅᾍᾅἋἃᾋᾃἏἇᾏᾇ ῈὲἘἐἙἑἜἔἚἒἝἕἛἓ ῌῃῄῊὴῂῆῇἨἠᾘᾐἩἡᾙᾑἬἤᾜᾔἪἢᾚᾒἮἦᾞᾖἭἥᾝᾕἫἣᾛᾓἯἧᾟᾗ ῚὶῖἸἰἹἱἼἴἺἲἾἶἽἵἻἳἿἷ ῸὸὈὀὉὁὌὄὊὂὍὅὋὃ ῤῬῥ ῪὺῦὐὙὑὔὒὖὝὕὛὓὟὗ ῼῳῴῺὼῲῶῷὨὠᾨᾠὩὡᾩᾡὬὤᾬᾤὪὢᾪᾢὮὦᾮᾦὭὥᾭᾥὫὣᾫᾣὯὧᾯᾧ {\{Polytonic|+}}',
'Cyrillic': 'АаБбВвГг ҐґЃѓДдЂђ ЕеЁёЄєЖж ЗзЅѕИиІі ЇїЙйЈјКк ЌќЛлЉљМм НнЊњОоПп РрСсТтЋћ УуЎўФфХх ЦцЧчЏџШш ЩщЪъЫыЬь ЭэЮюЯя ӘәӨөҒғҖҗ ҚқҜҝҢңҮү ҰұҲҳҸҹҺһ ҔҕӢӣӮӯҘҙ ҠҡҤҥҪҫӐӑ ӒӓӔӕӖӗӰӱ ӲӳӸӹӀ ҞҟҦҧҨҩҬҭ ҴҵҶҷҼҽҾҿ ӁӂӃӄӇӈӋӌ ӚӛӜӝӞӟӠӡ ӤӥӦӧӪӫӴӵ ́',
'Hebrew': 'אבגדהוזחטיךכלםמןנסעףפץצקרשת ׳ ״ װױײ',
'Arabic': ' Transcription: ʾ ṯ ḥ ḫ ẖ ḏ š ṣ ḍ ṭ ẓ ʿ ġ ẗ ا ﺁ ب ت ث ج ح خ د ذ ر ز س ش ص ض ط ظ ع غ ف ق ك ل م ن ه ة و ي ى ء أ إ ؤ ئ',
'IPA (English)': 'ˈ ˌ ŋ ɡ tʃ dʒ ʃ ʒ θ ð ʔ iː ɪ uː ʊ ʌ ɜr eɪ ɛ æ oʊ ɒ ɔː ɔɪ ɔr ɑː ɑr aɪ aʊ ə ər ɨ ɵ ʉ {\{IPA-en|+}} {\{IPA|/+/}} ⟨+⟩',
'IPA': 'ʈɖɟɡɢʡʔ ɸβθðʃʒɕʑʂʐçʝɣχʁħʕʜʢɦ ɱɳɲŋɴ ʋɹɻɰ ʙⱱʀɾɽ ɬ ɮ ɺ ɭʎʟ ʍɥɧ ʼ ɓɗʄɠʛ ʘǀǃǂǁ ɨʉɯ ɪʏʊ øɘɵɤ ə ɛœɜɞʌɔ æ ɐ ɶɑɒ ʰʱʷʲˠˤˀ ᵊ k̚ ⁿˡ ˈˌːˑ t̪ d̪ s̺ s̻ θ̼ s̬ n̥ ŋ̊ a̤ a̰ β̞ ˕ r̝ ˔ o˞ ɚ ɝ e̘ e̙ u̟ i̠ ɪ̈ e̽ ɔ̹ ɔ̜ n̩ ə̆ ə̯ ə̃ ȷ̃ ɫ z̴ ə̋ ə́ ə̄ ə̀ ə̏ ə̌ ə̂ ə᷄ ə᷅ ə᷇ ə᷆ ə᷈ ə᷉ t͡ʃ d͡ʒ t͜ɬ ‿ ˥ ˦ ˧ ˨ ˩ ꜛ ꜜ | ‖ ↗ ↘ k͈ s͎ {\{IPA|+}}',
'Math and logic': '− × ÷ ⋅ ° ∗ ∘ ± ∓ ≤ ≥ ≠ ≡ ≅ ≜ ≝ ≐ ≃ ≈ ⊕ ⊗ ⇐ ⇔ ⇒ ∞ ← ↔ → ≪ ≫ ∝ √ ∤ ≀ ◅ ▻ ⋉ ⋊ ⋈ ∴ ∵ ↦ ¬ ∧ ∨ ⊻ ∀ ∃ ∈ ∉ ∋ ⊆ ⊈ ⊊ ⊂ ⊄ ⊇ ⊉ ⊋ ⊃ ⊅ ∪ ∩ ∑ ∏ ∐ ′ ∫ ∬ ∭ ∮ ∇ ∂ ∆ ∅ ℂ ℍ ℕ ℙ ℚ ℝ ℤ ℵ ⌊ ⌋ ⌈ ⌉ ⊤ ⊥ ⊢ ⊣ ⊧ □ ∠ ⟨ ⟩ {\{frac|+|}} − <math>+</math> {\{math|+}}'
},
charinsertDivider : "\240",
extraCSS : '\
#editpage-specialchars {\
margin-top: 15px;\
border-width: 1px;\
border-style: solid;\
border-color: #aaaaaa;\
padding: 2px;\
}\
#editpage-specialchars a {\
}\
#editpage-specialchars a:hover {\
}\
',
appendExtraCSS : function ()
{
appendCSS(EditTools.extraCSS);
},
cookieName : 'edittoolscharsubset',
createEditTools : function (placeholder)
{
var box = document.createElement("div");
box.id = "editpage-specialchars";
box.title = 'Click on the character or tag to insert it into the edit window';
//append user-defined sets
if (window.charinsertCustom)
for (id in charinsertCustom)
if (!EditTools.charinsert[id]) EditTools.charinsert[id] = ;
//create drop-down select
var prevSubset = 0, curSubset = 0;
var sel = document.createElement('select'), id;
for (id in EditTools.charinsert)
sel.options[sel.options.length] = new Option(id, id);
sel.selectedIndex = 0;
sel.style.cssFloat = sel.style.styleFloat = 'left';
sel.style.marginRight = '5px';
sel.title = 'Choose character subset';
sel.onchange = sel.onkeyup = selectSubset;
box.appendChild(sel);
//create "recall" switch
if (window.editToolsRecall) {
var recall = document.createElement('span');
recall.appendChild(document.createTextNode('↕')); // ↔
recall.onclick = function () {
sel.selectedIndex = prevSubset;
selectSubset();
}
with (recall.style) { cssFloat = styleFloat = 'left'; marginRight = '5px'; cursor = 'pointer'; }
box.appendChild(recall);
}
// load latest selection from cookies
try {
var cookieRe = new RegExp ("(?:^|;)\\s*" + EditTools.cookieName + "=(\\d+)\\s*(?:;|$)");
var m = cookieRe.exec(document.cookie);
if (m && m.length > 1 && parseInt(m[1]) < sel.options.length)
sel.selectedIndex = parseInt(m[1]);
} catch (err) { /* ignore */ }
placeholder.parentNode.replaceChild(box, placeholder);
selectSubset();
return;
function selectSubset ()
{
//remember previous (for "recall" button)
prevSubset = curSubset;
curSubset = sel.selectedIndex;
//save into cookies for persistence
try {
var expires = new Date ();
expires.setTime( expires.getTime() + 30 * 24 * 60 * 60 * 1000 ); // + 30 days
document.cookie = EditTools.cookieName + "=" + curSubset + ";path=/;expires=" + expires.toUTCString();
} catch (err) { /* ignore */ }
//hide other subsets
var pp = box.getElementsByTagName('p') ;
for (var i=0; i<pp.length; i++)
pp[i].style.display = 'none';
//show/create current subset
var id = sel.options[curSubset].value;
var p = document.getElementById(id);
if (!p){
p = document.createElement('p');
p.id = id;
if (id == 'Arabic' || id == 'Hebrew'){ p.style.fontSize = '120%'; p.dir = 'rtl'; }
var tokens = EditTools.charinsert[id];
if (window.charinsertCustom && charinsertCustom[id]){
if (tokens.length > 0) tokens += ' ';
tokens += charinsertCustom[id];
}
EditTools.createTokens(p, tokens);
box.appendChild(p);
}
p.style.display = 'inline';
}
},
createTokens : function (paragraph, str)
{
var tokens = str.split(' '), token, i, n;
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
n = token.indexOf('+');
if (token == || token == '_')
addText(EditTools.charinsertDivider + ' ');
else if (token == '\n')
paragraph.appendChild(document.createElement('br'));
else if (token == '___')
paragraph.appendChild(document.createElement('hr'));
else if (token.charAt(token.length-1) == ':') // : at the end means just text
addBold(token);
else if (n == 0) // +<tag> -> <tag>+</tag>
addLink(token.substring(1), '</' + token.substring(2), token.substring(1));
else if (n > 0) // <tag>+</tag>
addLink(token.substring(0,n), token.substring(n+1));
else if (token.length > 2 && token.charCodeAt(0) > 127) //a string of insertable characters
for (var j=0; j < token.length; j++) addLink(token.charAt(j), );
else
addLink(token, );
}
return;
function addLink (tagOpen, tagClose, name)
{
var handler;
var dle = tagOpen.indexOf('\x10');
if (dle > 0){
var path = tagOpen.substring(dle+1).split('.');
tagOpen = tagOpen.substring(0,dle);
var handler = window;
for (var i = 0; i < path.length; i++) {
handler = handler[path[i]];
}
} else {
tagOpen = tagOpen.replace(/\./g,' ');
tagClose = tagClose ? tagClose.replace(/_/g,' ') : ;
handler = new Function( "evt", "insertTags('" + tagOpen + "', '" + tagClose + "', ); return killEvt( evt );" );
}
var a = document.createElement('a');
name = name || tagOpen + tagClose;
name = name.replace(/\\n/g,);
a.appendChild(document.createTextNode(name));
a.href = "#";
addHandler( a, 'click', handler );
paragraph.appendChild(a);
addText(' ');
}
function addBold (text)
{
var b = document.createElement('b');
b.appendChild(document.createTextNode(text.replace(/_/g,' ')));
paragraph.appendChild(b);
addText(' ');
}
function addText (txt)
{
paragraph.appendChild(document.createTextNode(txt));
}
},
enableForAllFields : function ()
{
if (typeof (insertTags) != 'function' || window.WikEdInsertTags) return;
// insertTags from the site-wide /skins-1.5/common/edit.js just inserts in the first
// textarea in the document. Evidently, that's not good if we have multiple textareas.
// My first idea was to simply add a hidden textarea as the first one, and redefine
// insertTags such that it copied first the last active textareas contents over to that hidden
// field, set the cursor or selection there, let the standard insertTags do its thing, and
// then copy the hidden field's text, cursor position and selection back to the currently
// active field. Unfortunately, that is just as complex as simply copying the whole code
// from wikibits to here and let it work on the right text field in the first place.
var texts = document.getElementsByTagName ('textarea');
for (var i = 0; i < texts.length; i++) {
addHandler (texts[i], 'focus', EditTools.registerTextField);
}
// While we're at it, also enable it for input fields
texts = document.getElementsByTagName ('input');
for (var i = 0; i < texts.length; i++) {
if (texts[i].type == 'text') addHandler (texts[i], 'focus', EditTools.registerTextField);
}
insertTags = EditTools.insertTags; // Redefine the global insertTags
},
last_active_textfield : null,
registerTextField : function (evt)
{
var e = evt || window.event;
var node = e.target || e.srcElement;
if (!node) return;
EditTools.last_active_textfield = node.id;
return true;
},
getTextArea : function ()
{
var txtarea = null;
if (EditTools.last_active_textfield && EditTools.last_active_textfield != "")
txtarea = document.getElementById (EditTools.last_active_textfield);
if (!txtarea) {
// Fallback option: old behaviour
if (document.editform) {
txtarea = document.editform.wpTextbox1;
} else {
// Some alternate form? Take the first one we can find
txtarea = document.getElementsByTagName ('textarea');
if (txtarea.length > 0) txtarea = txtarea[0]; else txtarea = null;
}
}
return txtarea;
},
insertTags : function (tagOpen, tagClose, sampleText)
{
var txtarea = EditTools.getTextArea ();
if (!txtarea) return;
/* Usability initiative compatibility */
if ( typeof $j != 'undefined' && typeof $j.fn.textSelection != 'undefined' ) {
$j( txtarea ).textSelection(
'encapsulateSelection', { 'pre': tagOpen, 'peri': sampleText, 'post': tagClose }
);
return;
}
var selText, isSample = false;
function checkSelectedText ()
{
if (!selText) {
selText = sampleText; isSample = true;
} else if (selText.charAt (selText.length - 1) == ' ') { // Exclude ending space char
selText = selText.substring (0, selText.length - 1);
tagClose += ' ';
}
}
if (document.selection && document.selection.createRange) { // IE/Opera
// Save window scroll position
var winScroll = 0;
if (document.documentElement && document.documentElement.scrollTop)
winScroll = document.documentElement.scrollTop;
else if (document.body)
winScroll = document.body.scrollTop;
// Get current selection
txtarea.focus();
var range = document.selection.createRange();
selText = range.text;
// Insert tags
checkSelectedText ();
range.text = tagOpen + selText + tagClose;
// Mark sample text as selected
if (isSample && range.moveStart) {
if (window.opera) tagClose = tagClose.replace (/\n/g, "");
range.moveStart( 'character', - tagClose.length - selText.length);
range.moveEnd ('character', - tagClose.length);
}
range.select ();
// Restore window scroll position
if (document.documentElement && document.documentElement.scrollTop)
document.documentElement.scrollTop = winScroll;
else if (document.body)
document.body.scrollTop = winScroll;
} else if (txtarea.selectionStart || txtarea.selectionStart == '0') { // Mozilla
// Save textarea scroll position
var textScroll = txtarea.scrollTop;
// Get current selection
txtarea.focus();
var startPos = txtarea.selectionStart;
var endPos = txtarea.selectionEnd;
selText = txtarea.value.substring (startPos, endPos);
// Insert tags
checkSelectedText ();
txtarea.value = txtarea.value.substring (0, startPos)
+ tagOpen + selText + tagClose
+ txtarea.value.substring (endPos);
// Set new selection
if (isSample) {
txtarea.selectionStart = startPos + tagOpen.length;
txtarea.selectionEnd = startPos + tagOpen.length + selText.length;
} else {
txtarea.selectionStart = startPos + tagOpen.length + selText.length + tagClose.length;
txtarea.selectionEnd = txtarea.selectionStart;
}
// Restore textarea scroll position
txtarea.scrollTop = textScroll;
}
}, // end insertTags
setup : function ()
{
var placeholder = document.getElementById("editpage-specialchars");
if (!placeholder) return; // has this already been run once?
EditTools.appendExtraCSS ();
EditTools.createEditTools (placeholder);
EditTools.enableForAllFields ();
}
}; // end EditTools
// No need to hook this, as the loading of this page is itself hooked.
EditTools.setup();
MediaWiki:Common.js/watchlist.js
/* Load the geonotices. */
addOnloadHook(function() {
importScriptURI( wgScript + '?title=MediaWiki:Geonotice.js&action=raw&ctype=text/javascript&maxage=3600&ver=2');
});
/** Add dismiss buttons to watchlist-message *************************************
*
* Description: Allows multiple dismiss buttons on MediaWiki:Watchlist-details with bump-able cookie IDs.
* Note: HTML is backwards compatible with old version, new version ignores old syntax, except for dismissed IDs.
* Maintainers: Ruud Koot, MZMcBride
*/
function addDismissButton() {
var docobj = document.getElementById('bodyContent') || document.getElementById('content') || document;
var watchItems = getElementsByClassName(docobj, 'div', 'watchlist-message');
if(watchItems.length == 0) watchItems = getElementsByClassName(docobj, 'li', 'watchlist-message');
if(watchItems.length == 0) return
for(var i=0;i<watchItems.length;i++) {
var watchlistCookieID = parseInt(watchItems[i].className.replace(/.*cookie\-ID\_(\d*).*/ig,'$1'));
if(isNaN(watchlistCookieID)) continue
if(document.cookie.indexOf('hidewatchlistmessage-' + watchlistCookieID + '=yes') != -1) {
watchItems[i].style.display = 'none';
continue;
}
var Button = document.createElement('span');
var ButtonLink = document.createElement('a');
var ButtonText = document.createTextNode('dismiss');
ButtonLink.setAttribute('id','dismissButton');
ButtonLink.setAttribute('href','javascript:dismissWatchlistMessage(' + i + ',' + watchlistCookieID + ')');
ButtonLink.setAttribute('title','Hide this message');
ButtonLink.appendChild(ButtonText);
Button.appendChild(document.createTextNode(' ['));
Button.appendChild(ButtonLink);
Button.appendChild(document.createTextNode(']'));
watchItems[i].appendChild(Button);
}
}
function dismissWatchlistMessage(num,cid) {
var docobj = document.getElementById('bodyContent') || document.getElementById('content') || document
var watchItems = getElementsByClassName(docobj, 'div', 'watchlist-message');
if(watchItems.length == 0) watchItems = getElementsByClassName(docobj, 'li', 'watchlist-message');
watchItems[num].style.display = 'none';
var e = new Date();
e.setTime( e.getTime() + (4*7*24*60*60*1000) );
document.cookie = 'hidewatchlistmessage-' + cid + '=yes; expires=' + e.toGMTString() + '; path=/';
}
addOnloadHook(addDismissButton);