/***
|Name|InlineJavascriptPlugin|
|Source|http://www.TiddlyTools.com/#InlineJavascriptPlugin|
|Documentation|http://www.TiddlyTools.com/#InlineJavascriptPluginInfo|
|Version|1.9.6|
|Author|Eric Shulman|
|License|http://www.TiddlyTools.com/#LegalStatements|
|~CoreVersion|2.1|
|Type|plugin|
|Description|Insert Javascript executable code directly into your tiddler content.|
''Call directly into TW core utility routines, define new functions, calculate values, add dynamically-generated TiddlyWiki-formatted output'' into tiddler content, or perform any other programmatic actions each time the tiddler is rendered.
!!!!!Documentation
>see [[InlineJavascriptPluginInfo]]
!!!!!Revisions
<<<
2010.12.15 1.9.6 allow (but ignore) type="..." syntax
|please see [[InlineJavascriptPluginInfo]] for additional revision details|
2005.11.08 1.0.0 initial release
<<<
!!!!!Code
***/
//{{{
version.extensions.InlineJavascriptPlugin= {major: 1, minor: 9, revision: 6, date: new Date(2010,12,15)};
config.formatters.push( {
name: "inlineJavascript",
match: "\\<script",
lookahead: "\\<script(?: type=\\\"[^\\\"]*\\\")?(?: src=\\\"([^\\\"]*)\\\")?(?: label=\\\"([^\\\"]*)\\\")?(?: title=\\\"([^\\\"]*)\\\")?(?: key=\\\"([^\\\"]*)\\\")?( show)?\\>((?:.|\\n)*?)\\</script\\>",
handler: function(w) {
var lookaheadRegExp = new RegExp(this.lookahead,"mg");
lookaheadRegExp.lastIndex = w.matchStart;
var lookaheadMatch = lookaheadRegExp.exec(w.source)
if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
var src=lookaheadMatch[1];
var label=lookaheadMatch[2];
var tip=lookaheadMatch[3];
var key=lookaheadMatch[4];
var show=lookaheadMatch[5];
var code=lookaheadMatch[6];
if (src) { // external script library
var script = document.createElement("script"); script.src = src;
document.body.appendChild(script); document.body.removeChild(script);
}
if (code) { // inline code
if (show) // display source in tiddler
wikify("{{{\n"+lookaheadMatch[0]+"\n}}}\n",w.output);
if (label) { // create 'onclick' command link
var link=createTiddlyElement(w.output,"a",null,"tiddlyLinkExisting",wikifyPlainText(label));
var fixup=code.replace(/document.write\s*\(/gi,'place.bufferedHTML+=(');
link.code="function _out(place,tiddler){"+fixup+"\n};_out(this,this.tiddler);"
link.tiddler=w.tiddler;
link.onclick=function(){
this.bufferedHTML="";
try{ var r=eval(this.code);
if(this.bufferedHTML.length || (typeof(r)==="string")&&r.length)
var s=this.parentNode.insertBefore(document.createElement("span"),this.nextSibling);
if(this.bufferedHTML.length)
s.innerHTML=this.bufferedHTML;
if((typeof(r)==="string")&&r.length) {
wikify(r,s,null,this.tiddler);
return false;
} else return r!==undefined?r:false;
} catch(e){alert(e.description||e.toString());return false;}
};
link.setAttribute("title",tip||"");
var URIcode='javascript:void(eval(decodeURIComponent(%22(function(){try{';
URIcode+=encodeURIComponent(encodeURIComponent(code.replace(/\n/g,' ')));
URIcode+='}catch(e){alert(e.description||e.toString())}})()%22)))';
link.setAttribute("href",URIcode);
link.style.cursor="pointer";
if (key) link.accessKey=key.substr(0,1); // single character only
}
else { // run script immediately
var fixup=code.replace(/document.write\s*\(/gi,'place.innerHTML+=(');
var c="function _out(place,tiddler){"+fixup+"\n};_out(w.output,w.tiddler);";
try { var out=eval(c); }
catch(e) { out=e.description?e.description:e.toString(); }
if (out && out.length) wikify(out,w.output,w.highlightRegExp,w.tiddler);
}
}
w.nextMatch = lookaheadMatch.index + lookaheadMatch[0].length;
}
}
} )
//}}}
// // Backward-compatibility for TW2.1.x and earlier
//{{{
if (typeof(wikifyPlainText)=="undefined") window.wikifyPlainText=function(text,limit,tiddler) {
if(limit > 0) text = text.substr(0,limit);
var wikifier = new Wikifier(text,formatter,null,tiddler);
return wikifier.wikifyPlain();
}
//}}}
// // GLOBAL FUNCTION: $(...) -- 'shorthand' convenience syntax for document.getElementById()
//{{{
if (typeof($)=='undefined') { function $(id) { return document.getElementById(id.replace(/^#/,'')); } }
//}}}
<html>
<form>
<table>
<tr><td>Average Cherry Tree Lanterns</td><td><input type="text" size="2" maxlength="5" value="2.7" id="tree"></td></tr>
<tr><td>Starting Lanterns</td><td><input type="text" size="5" maxlength="5" value="1200" id="starting"></td></tr>
<tr><td>Needed set pieces (daily special)</td><td><input type="text" size="2" maxlength="2" value="2" id="needed"></td></tr>
<tr><td>Simulations</td><td><input type="text" size="8" maxlength="12" value="100000" id="simulations"></td></tr>
</table>
Select which chests you want to simulate. Large numbers of simulations may be very slow.
<table>
<tr>
<td colspan="2" align="center"><input type="checkbox" id="cb_bronze" >Bronze<br></td>
<td colspan="2" align="center"><input type="checkbox" id="cb_silver" >Silver<br></td>
<td colspan="2" align="center"><input type="checkbox" id="cb_gold" >Gold<br></td>
</tr>
<tr>
<td>Daily Special</td>
<td>7%</td>
<td>Daily Special</td>
<td>13%</td>
<td>Daily Special</td>
<td>25%</td>
</tr>
<tr>
<td>Rogue</td>
<td>10%</td>
<td>One-Up kit</td>
<td>8%</td>
<td>One-story Pagoda</td>
<td>10%</td>
</tr>
<tr>
<td>Champion</td>
<td>10%</td>
<td>Boost Crate</td>
<td>10%</td>
<td>Renovation kit</td>
<td>8%</td>
</tr>
<tr>
<td>Military Drummer</td>
<td>11%</td>
<td>Mass Motivation Kit</td>
<td>13%</td>
<td>Store building</td>
<td>15%</td>
</tr>
<tr>
<td>Color Guard</td>
<td>12%</td>
<td>Watchfire</td>
<td>15%</td>
<td>Medium Medal Package</td>
<td>10%</td>
</tr>
<tr>
<td>5 Forge Points</td>
<td>15%</td>
<td>10 Forge Points</td>
<td>11%</td>
<td>20 Forge Points</td>
<td>10%</td>
</tr>
<tr>
<td>Observatory Blueprint</td>
<td>15%</td>
<td>2 Observatory Blueprints</td>
<td>15%</td>
<td>5 Blueprints</td>
<td>10%</td>
</tr>
<tr>
<td>70 Spring Lanterns</td>
<td>20%</td>
<td>120 Spring Lanterns</td>
<td>15%</td>
<td>200 Spring Lanterns</td>
<td>12%</td>
</tr>
</table>
</form>
</html><script label="Click here to run simulation">
var tree = parseFloat(document.getElementById("tree").value);
var starting = parseInt(document.getElementById("starting").value);
var needed = parseInt(document.getElementById("needed").value);
var simulations = parseInt(document.getElementById("simulations").value);
var cb_bronze = document.getElementById("cb_bronze").checked;
var cb_silver = document.getElementById("cb_silver").checked;
var cb_gold = document.getElementById("cb_gold").checked;
var ta = document.getElementById("ta_result");
ta.value = "Average lanterns per tree: " + tree + "\n";
ta.value += "Starting with " + starting + " Lanterns.\n";
ta.value += "Running " + simulations + " simulations per chest type.\n";
if (cb_bronze != true && cb_silver != true && cb_gold != true) {
ta.value += "No chests selected!\n";
}
var i;
var lanterns;
var roll;
var dailyspecials;
if (cb_bronze) {
var res_bronze = { lanternsleft:0,chests:0, prize1:0,prize2:0,prize3:0,prize4:0,prize5:0,prize6:0,prize7:0,prize8:0,totalfailure:0,treelanterns:0, prizelanterns:0,leftover:0,blossoms:0,needed:0 };
for (i = 0; i < simulations; i += 1) {
dailyspecials = 0;
lanterns = starting;
while (lanterns > 39) {
res_bronze.chests += 1;
lanterns -= 40;
lanterns += tree;
res_bronze.treelanterns += tree;
res_bronze.blossoms += 5;
roll = Math.random();
if (roll <= 0.07) {
res_bronze.prize1 += 1;
dailyspecials += 1;
} else if (roll <= 0.17) {
res_bronze.prize2 += 1;
} else if (roll <= 0.27) {
res_bronze.prize3 += 1;
} else if (roll <= 0.38) {
res_bronze.prize4 += 1;
} else if (roll <= 0.5) {
res_bronze.prize5 += 1;
} else if (roll <= 0.65) {
res_bronze.prize6 += 1;
} else if (roll <= 0.8) {
res_bronze.prize7 += 1;
} else {
res_bronze.prize8 += 1;
lanterns += 70;
res_bronze.prizelanterns += 70;
}
}
res_bronze.leftover += lanterns;
if (dailyspecials === 0) {
res_bronze.totalfailure += 1;
} else if (dailyspecials >= needed) {
res_bronze.needed += 1;
}
}
ta.value += "\nBRONZE RESULTS:\n--------\n";
ta.value += "Average Daily Specials won: " + res_bronze.prize1/simulations + "\n";
ta.value += "Average Rogues won: " + res_bronze.prize2/simulations + "\n";
ta.value += "Average Champions won: " + res_bronze.prize3/simulations + "\n";
ta.value += "Average Military Drummers won: " + res_bronze.prize4/simulations + "\n";
ta.value += "Average Color Guards won: " + res_bronze.prize5/simulations + "\n";
ta.value += "Average 5 Forge Points won: " + res_bronze.prize6/simulations + "\n";
ta.value += "Average Observatory Blueprint won: " + res_bronze.prize7/simulations + "\n";
ta.value += "Average 70 Spring Lanterns won: " + res_bronze.prize8/simulations + "\n--------\n";
ta.value += starting + " Lanterns buys " + Math.floor(starting/40) + " Bronze Chests (not counting Spring Lantern prize)\n";
ta.value += "Average Chests actually opened: " + res_bronze.chests/simulations + "\n";
ta.value += "Successes (got needed set pieces): " + 100*res_bronze.needed/simulations + "%\n";
ta.value += "Total failures (zero daily specials): " + 100*res_bronze.totalfailure/simulations + "%\n";
ta.value += "Average Lanterns gained from trees: " + res_bronze.treelanterns/simulations + "\n";
ta.value += "Average Lanterns gained from chests: " + res_bronze.prizelanterns/simulations + "\n";
ta.value += "Average Total Lanterns gained: " + (res_bronze.prizelanterns+res_bronze.treelanterns)/simulations + "\n";
ta.value += "Average Blossoms gained from chests: " + res_bronze.blossoms/simulations + "\n";
ta.value += "Average leftover lanterns: " + res_bronze.leftover/simulations + "\n";
}
if (cb_silver) {
var res_silver = { lanternsleft:0,chests:0, prize1:0,prize2:0,prize3:0,prize4:0,prize5:0,prize6:0,prize7:0,prize8:0,totalfailure:0,treelanterns:0, prizelanterns:0, leftover:0,blossoms:0,needed:0 };
for (i = 0; i < simulations; i += 1) {
dailyspecials = 0;
lanterns = starting;
while (lanterns > 69) {
res_silver.chests += 1;
lanterns -= 70;
lanterns += tree;
res_silver.treelanterns += tree;
res_silver.blossoms += 10;
roll = Math.random();
if (roll <= 0.13) {
res_silver.prize1 += 1;
dailyspecials += 1;
} else if (roll <= 0.21) {
res_silver.prize2 += 1;
} else if (roll <= 0.31) {
res_silver.prize3 += 1;
} else if (roll <= 0.44) {
res_silver.prize4 += 1;
} else if (roll <= 0.59) {
res_silver.prize5 += 1;
} else if (roll <= 0.70) {
res_silver.prize6 += 1;
} else if (roll <= 0.85) {
res_silver.prize7 += 1;
} else {
res_silver.prize8 += 1;
lanterns += 120;
res_silver.prizelanterns += 120;
}
}
res_silver.leftover += lanterns;
if (dailyspecials === 0) {
res_silver.totalfailure += 1;
} else if (dailyspecials >= needed) {
res_silver.needed += 1;
}
}
ta.value += "\nSILVER RESULTS:\n--------\n";
ta.value += "Average Daily Specials won: " + res_silver.prize1/simulations + "\n";
ta.value += "Average One-Up kits won: " + res_silver.prize2/simulations + "\n";
ta.value += "Average Boost Crates won: " + res_silver.prize3/simulations + "\n";
ta.value += "Average Mass Motivation Kits won: " + res_silver.prize4/simulations + "\n";
ta.value += "Average Watchfires won: " + res_silver.prize5/simulations + "\n";
ta.value += "Average 10 Forge Points won: " + res_silver.prize6/simulations + "\n";
ta.value += "Average 2 Observatory Blueprints won: " + res_silver.prize7/simulations + "\n";
ta.value += "Average 120 Spring Lanterns won: " + res_silver.prize8/simulations + "\n--------\n";
ta.value += starting + " Lanterns buys " + Math.floor(starting/70) + " silver Chests (not counting Spring Lantern prize)\n";
ta.value += "Average Chests actually opened: " + res_silver.chests/simulations + "\n";
ta.value += "Successes (got needed set pieces): " + 100*res_silver.needed/simulations + "%\n";
ta.value += "Total failures (zero daily specials): " + 100*res_silver.totalfailure/simulations + "%\n";
ta.value += "Average Lanterns gained from trees: " + res_silver.treelanterns/simulations + "\n";
ta.value += "Average Lanterns gained from chests: " + res_silver.prizelanterns/simulations + "\n";
ta.value += "Average Total Lanterns gained: " + (res_silver.prizelanterns+res_silver.treelanterns)/simulations + "\n";
ta.value += "Average Blossoms gained from chests: " + res_silver.blossoms/simulations + "\n";
ta.value += "Average leftover lanterns: " + res_silver.leftover/simulations + "\n";
}
if (cb_gold) {
var res_gold = { lanternsleft:0,chests:0, prize1:0,prize2:0,prize3:0,prize4:0,prize5:0,prize6:0,prize7:0,prize8:0,totalfailure:0,treelanterns:0, prizelanterns:0, leftover:0,blossoms:0,needed:0 };
for (i = 0; i < simulations; i += 1) {
dailyspecials = 0;
lanterns = starting;
while (lanterns > 119) {
res_gold.chests += 1;
lanterns -= 120;
lanterns += tree;
res_gold.treelanterns += tree;
res_gold.blossoms += 20;
roll = Math.random();
if (roll <= 0.25) {
res_gold.prize1 += 1;
dailyspecials += 1;
} else if (roll <= 0.35) {
res_gold.prize2 += 1;
} else if (roll <= 0.43) {
res_gold.prize3 += 1;
} else if (roll <= 0.58) {
res_gold.prize4 += 1;
} else if (roll <= 0.68) {
res_gold.prize5 += 1;
} else if (roll <= 0.78) {
res_gold.prize6 += 1;
} else if (roll <= 0.88) {
res_gold.prize7 += 1;
} else {
res_gold.prize8 += 1;
lanterns += 200;
res_gold.prizelanterns += 200;
}
}
res_gold.leftover += lanterns;
if (dailyspecials === 0) {
res_gold.totalfailure += 1;
} else if (dailyspecials >= needed) {
res_gold.needed += 1;
}
}
ta.value += "\nGOLD RESULTS\n--------\n";
ta.value += "Average Daily Specials won: " + res_gold.prize1/simulations + "\n";
ta.value += "Average One-story Pagodas won: " + res_gold.prize2/simulations + "\n";
ta.value += "Average Renovation kits won: " + res_gold.prize3/simulations + "\n";
ta.value += "Average Store buildings won: " + res_gold.prize4/simulations + "\n";
ta.value += "Average Medium Medal Packages won: " + res_gold.prize5/simulations + "\n";
ta.value += "Average 20 Forge Points won: " + res_gold.prize6/simulations + "\n";
ta.value += "Average 5 Blueprints won: " + res_gold.prize7/simulations + "\n";
ta.value += "Average 200 Spring Lanterns won: " + res_gold.prize8/simulations + "\n--------\n";
ta.value += starting + " Lanterns buys " + Math.floor(starting/120) + " gold Chests (not counting Spring Lantern prize)\n";
ta.value += "Average Chests actually opened: " + res_gold.chests/simulations + "\n";
ta.value += "Successes (got needed set pieces): " + 100*res_gold.needed/simulations + "%\n";
ta.value += "Total failures (zero daily specials): " + 100*res_gold.totalfailure/simulations + "%\n";
ta.value += "Average Lanterns gained from trees: " + res_gold.treelanterns/simulations + "\n";
ta.value += "Average Lanterns gained from chests: " + res_gold.prizelanterns/simulations + "\n";
ta.value += "Average Total Lanterns gained: " + (res_gold.prizelanterns+res_gold.treelanterns)/simulations + "\n";
ta.value += "Average Blossoms gained from chests: " + res_gold.blossoms/simulations + "\n";
ta.value += "Average leftover lanterns: " + res_gold.leftover/simulations + "\n";
}
</script>
<html>
<textarea id="ta_result" rows="42" cols="80" spellcheck="false" readonly></textarea>
</html>
^^<script label="Clear">
document.getElementById("ta_result").value="";
</script>^^
/***
|''Name:''|UploadPlugin|
|''Description:''|Save to web a TiddlyWiki|
|''Version:''|4.1.3|
|''Date:''|Feb 24, 2008|
|''Source:''|http://tiddlywiki.bidix.info/#UploadPlugin|
|''Documentation:''|http://tiddlywiki.bidix.info/#UploadPluginDoc|
|''Author:''|BidiX (BidiX (at) bidix (dot) info)|
|''License:''|[[BSD open source license|http://tiddlywiki.bidix.info/#%5B%5BBSD%20open%20source%20license%5D%5D ]]|
|''~CoreVersion:''|2.2.0|
|''Requires:''|PasswordOptionPlugin|
***/
//{{{
version.extensions.UploadPlugin = {
major: 4, minor: 1, revision: 3,
date: new Date("Feb 24, 2008"),
source: 'http://tiddlywiki.bidix.info/#UploadPlugin',
author: 'BidiX (BidiX (at) bidix (dot) info',
coreVersion: '2.2.0'
};
//
// Environment
//
if (!window.bidix) window.bidix = {}; // bidix namespace
bidix.debugMode = false; // true to activate both in Plugin and UploadService
//
// Upload Macro
//
config.macros.upload = {
// default values
defaultBackupDir: '', //no backup
defaultStoreScript: "store.php",
defaultToFilename: "index.html",
defaultUploadDir: ".",
authenticateUser: true // UploadService Authenticate User
};
config.macros.upload.label = {
promptOption: "Save and Upload this TiddlyWiki with UploadOptions",
promptParamMacro: "Save and Upload this TiddlyWiki in %0",
saveLabel: "save to web",
saveToDisk: "save to disk",
uploadLabel: "upload"
};
config.macros.upload.messages = {
noStoreUrl: "No store URL in parmeters or options",
usernameOrPasswordMissing: "Username or password missing"
};
config.macros.upload.handler = function(place,macroName,params) {
if (readOnly)
return;
var label;
if (document.location.toString().substr(0,4) == "http")
label = this.label.saveLabel;
else
label = this.label.uploadLabel;
var prompt;
if (params[0]) {
prompt = this.label.promptParamMacro.toString().format([this.destFile(params[0],
(params[1] ? params[1]:bidix.basename(window.location.toString())), params[3])]);
} else {
prompt = this.label.promptOption;
}
createTiddlyButton(place, label, prompt, function() {config.macros.upload.action(params);}, null, null, this.accessKey);
};
config.macros.upload.action = function(params)
{
// for missing macro parameter set value from options
if (!params) params = {};
var storeUrl = params[0] ? params[0] : config.options.txtUploadStoreUrl;
var toFilename = params[1] ? params[1] : config.options.txtUploadFilename;
var backupDir = params[2] ? params[2] : config.options.txtUploadBackupDir;
var uploadDir = params[3] ? params[3] : config.options.txtUploadDir;
var username = params[4] ? params[4] : config.options.txtUploadUserName;
var password = config.options.pasUploadPassword; // for security reason no password as macro parameter
// for still missing parameter set default value
if ((!storeUrl) && (document.location.toString().substr(0,4) == "http"))
storeUrl = bidix.dirname(document.location.toString())+'/'+config.macros.upload.defaultStoreScript;
if (storeUrl.substr(0,4) != "http")
storeUrl = bidix.dirname(document.location.toString()) +'/'+ storeUrl;
if (!toFilename)
toFilename = bidix.basename(window.location.toString());
if (!toFilename)
toFilename = config.macros.upload.defaultToFilename;
if (!uploadDir)
uploadDir = config.macros.upload.defaultUploadDir;
if (!backupDir)
backupDir = config.macros.upload.defaultBackupDir;
// report error if still missing
if (!storeUrl) {
alert(config.macros.upload.messages.noStoreUrl);
clearMessage();
return false;
}
if (config.macros.upload.authenticateUser && (!username || !password)) {
alert(config.macros.upload.messages.usernameOrPasswordMissing);
clearMessage();
return false;
}
bidix.upload.uploadChanges(false,null,storeUrl, toFilename, uploadDir, backupDir, username, password);
return false;
};
config.macros.upload.destFile = function(storeUrl, toFilename, uploadDir)
{
if (!storeUrl)
return null;
var dest = bidix.dirname(storeUrl);
if (uploadDir && uploadDir != '.')
dest = dest + '/' + uploadDir;
dest = dest + '/' + toFilename;
return dest;
};
//
// uploadOptions Macro
//
config.macros.uploadOptions = {
handler: function(place,macroName,params) {
var wizard = new Wizard();
wizard.createWizard(place,this.wizardTitle);
wizard.addStep(this.step1Title,this.step1Html);
var markList = wizard.getElement("markList");
var listWrapper = document.createElement("div");
markList.parentNode.insertBefore(listWrapper,markList);
wizard.setValue("listWrapper",listWrapper);
this.refreshOptions(listWrapper,false);
var uploadCaption;
if (document.location.toString().substr(0,4) == "http")
uploadCaption = config.macros.upload.label.saveLabel;
else
uploadCaption = config.macros.upload.label.uploadLabel;
wizard.setButtons([
{caption: uploadCaption, tooltip: config.macros.upload.label.promptOption,
onClick: config.macros.upload.action},
{caption: this.cancelButton, tooltip: this.cancelButtonPrompt, onClick: this.onCancel}
]);
},
options: [
"txtUploadUserName",
"pasUploadPassword",
"txtUploadStoreUrl",
"txtUploadDir",
"txtUploadFilename",
"txtUploadBackupDir",
"chkUploadLog",
"txtUploadLogMaxLine"
],
refreshOptions: function(listWrapper) {
var opts = [];
for(i=0; i<this.options.length; i++) {
var opt = {};
opts.push();
opt.option = "";
n = this.options[i];
opt.name = n;
opt.lowlight = !config.optionsDesc[n];
opt.description = opt.lowlight ? this.unknownDescription : config.optionsDesc[n];
opts.push(opt);
}
var listview = ListView.create(listWrapper,opts,this.listViewTemplate);
for(n=0; n<opts.length; n++) {
var type = opts[n].name.substr(0,3);
var h = config.macros.option.types[type];
if (h && h.create) {
h.create(opts[n].colElements['option'],type,opts[n].name,opts[n].name,"no");
}
}
},
onCancel: function(e)
{
backstage.switchTab(null);
return false;
},
wizardTitle: "Upload with options",
step1Title: "These options are saved in cookies in your browser",
step1Html: "<input type='hidden' name='markList'></input><br>",
cancelButton: "Cancel",
cancelButtonPrompt: "Cancel prompt",
listViewTemplate: {
columns: [
{name: 'Description', field: 'description', title: "Description", type: 'WikiText'},
{name: 'Option', field: 'option', title: "Option", type: 'String'},
{name: 'Name', field: 'name', title: "Name", type: 'String'}
],
rowClasses: [
{className: 'lowlight', field: 'lowlight'}
]}
};
//
// upload functions
//
if (!bidix.upload) bidix.upload = {};
if (!bidix.upload.messages) bidix.upload.messages = {
//from saving
invalidFileError: "The original file '%0' does not appear to be a valid TiddlyWiki",
backupSaved: "Backup saved",
backupFailed: "Failed to upload backup file",
rssSaved: "RSS feed uploaded",
rssFailed: "Failed to upload RSS feed file",
emptySaved: "Empty template uploaded",
emptyFailed: "Failed to upload empty template file",
mainSaved: "Main TiddlyWiki file uploaded",
mainFailed: "Failed to upload main TiddlyWiki file. Your changes have not been saved",
//specific upload
loadOriginalHttpPostError: "Can't get original file",
aboutToSaveOnHttpPost: 'About to upload on %0 ...',
storePhpNotFound: "The store script '%0' was not found."
};
bidix.upload.uploadChanges = function(onlyIfDirty,tiddlers,storeUrl,toFilename,uploadDir,backupDir,username,password)
{
var callback = function(status,uploadParams,original,url,xhr) {
if (!status) {
displayMessage(bidix.upload.messages.loadOriginalHttpPostError);
return;
}
if (bidix.debugMode)
alert(original.substr(0,500)+"\n...");
// Locate the storeArea div's
var posDiv = locateStoreArea(original);
if((posDiv[0] == -1) || (posDiv[1] == -1)) {
alert(config.messages.invalidFileError.format([localPath]));
return;
}
bidix.upload.uploadRss(uploadParams,original,posDiv);
};
if(onlyIfDirty && !store.isDirty())
return;
clearMessage();
// save on localdisk ?
if (document.location.toString().substr(0,4) == "file") {
var path = document.location.toString();
var localPath = getLocalPath(path);
saveChanges();
}
// get original
var uploadParams = new Array(storeUrl,toFilename,uploadDir,backupDir,username,password);
var originalPath = document.location.toString();
// If url is a directory : add index.html
if (originalPath.charAt(originalPath.length-1) == "/")
originalPath = originalPath + "index.html";
var dest = config.macros.upload.destFile(storeUrl,toFilename,uploadDir);
var log = new bidix.UploadLog();
log.startUpload(storeUrl, dest, uploadDir, backupDir);
displayMessage(bidix.upload.messages.aboutToSaveOnHttpPost.format([dest]));
if (bidix.debugMode)
alert("about to execute Http - GET on "+originalPath);
var r = doHttp("GET",originalPath,null,null,username,password,callback,uploadParams,null);
if (typeof r == "string")
displayMessage(r);
return r;
};
bidix.upload.uploadRss = function(uploadParams,original,posDiv)
{
var callback = function(status,params,responseText,url,xhr) {
if(status) {
var destfile = responseText.substring(responseText.indexOf("destfile:")+9,responseText.indexOf("\n", responseText.indexOf("destfile:")));
displayMessage(bidix.upload.messages.rssSaved,bidix.dirname(url)+'/'+destfile);
bidix.upload.uploadMain(params[0],params[1],params[2]);
} else {
displayMessage(bidix.upload.messages.rssFailed);
}
};
// do uploadRss
if(config.options.chkGenerateAnRssFeed) {
var rssPath = uploadParams[1].substr(0,uploadParams[1].lastIndexOf(".")) + ".xml";
var rssUploadParams = new Array(uploadParams[0],rssPath,uploadParams[2],'',uploadParams[4],uploadParams[5]);
var rssString = generateRss();
// no UnicodeToUTF8 conversion needed when location is "file" !!!
if (document.location.toString().substr(0,4) != "file")
rssString = convertUnicodeToUTF8(rssString);
bidix.upload.httpUpload(rssUploadParams,rssString,callback,Array(uploadParams,original,posDiv));
} else {
bidix.upload.uploadMain(uploadParams,original,posDiv);
}
};
bidix.upload.uploadMain = function(uploadParams,original,posDiv)
{
var callback = function(status,params,responseText,url,xhr) {
var log = new bidix.UploadLog();
if(status) {
// if backupDir specified
if ((params[3]) && (responseText.indexOf("backupfile:") > -1)) {
var backupfile = responseText.substring(responseText.indexOf("backupfile:")+11,responseText.indexOf("\n", responseText.indexOf("backupfile:")));
displayMessage(bidix.upload.messages.backupSaved,bidix.dirname(url)+'/'+backupfile);
}
var destfile = responseText.substring(responseText.indexOf("destfile:")+9,responseText.indexOf("\n", responseText.indexOf("destfile:")));
displayMessage(bidix.upload.messages.mainSaved,bidix.dirname(url)+'/'+destfile);
store.setDirty(false);
log.endUpload("ok");
} else {
alert(bidix.upload.messages.mainFailed);
displayMessage(bidix.upload.messages.mainFailed);
log.endUpload("failed");
}
};
// do uploadMain
var revised = bidix.upload.updateOriginal(original,posDiv);
bidix.upload.httpUpload(uploadParams,revised,callback,uploadParams);
};
bidix.upload.httpUpload = function(uploadParams,data,callback,params)
{
var localCallback = function(status,params,responseText,url,xhr) {
url = (url.indexOf("nocache=") < 0 ? url : url.substring(0,url.indexOf("nocache=")-1));
if (xhr.status == 404)
alert(bidix.upload.messages.storePhpNotFound.format([url]));
if ((bidix.debugMode) || (responseText.indexOf("Debug mode") >= 0 )) {
alert(responseText);
if (responseText.indexOf("Debug mode") >= 0 )
responseText = responseText.substring(responseText.indexOf("\n\n")+2);
} else if (responseText.charAt(0) != '0')
alert(responseText);
if (responseText.charAt(0) != '0')
status = null;
callback(status,params,responseText,url,xhr);
};
// do httpUpload
var boundary = "---------------------------"+"AaB03x";
var uploadFormName = "UploadPlugin";
// compose headers data
var sheader = "";
sheader += "--" + boundary + "\r\nContent-disposition: form-data; name=\"";
sheader += uploadFormName +"\"\r\n\r\n";
sheader += "backupDir="+uploadParams[3] +
";user=" + uploadParams[4] +
";password=" + uploadParams[5] +
";uploaddir=" + uploadParams[2];
if (bidix.debugMode)
sheader += ";debug=1";
sheader += ";;\r\n";
sheader += "\r\n" + "--" + boundary + "\r\n";
sheader += "Content-disposition: form-data; name=\"userfile\"; filename=\""+uploadParams[1]+"\"\r\n";
sheader += "Content-Type: text/html;charset=UTF-8" + "\r\n";
sheader += "Content-Length: " + data.length + "\r\n\r\n";
// compose trailer data
var strailer = new String();
strailer = "\r\n--" + boundary + "--\r\n";
data = sheader + data + strailer;
if (bidix.debugMode) alert("about to execute Http - POST on "+uploadParams[0]+"\n with \n"+data.substr(0,500)+ " ... ");
var r = doHttp("POST",uploadParams[0],data,"multipart/form-data; ;charset=UTF-8; boundary="+boundary,uploadParams[4],uploadParams[5],localCallback,params,null);
if (typeof r == "string")
displayMessage(r);
return r;
};
// same as Saving's updateOriginal but without convertUnicodeToUTF8 calls
bidix.upload.updateOriginal = function(original, posDiv)
{
if (!posDiv)
posDiv = locateStoreArea(original);
if((posDiv[0] == -1) || (posDiv[1] == -1)) {
alert(config.messages.invalidFileError.format([localPath]));
return;
}
var revised = original.substr(0,posDiv[0] + startSaveArea.length) + "\n" +
store.allTiddlersAsHtml() + "\n" +
original.substr(posDiv[1]);
var newSiteTitle = getPageTitle().htmlEncode();
revised = revised.replaceChunk("<title"+">","</title"+">"," " + newSiteTitle + " ");
revised = updateMarkupBlock(revised,"PRE-HEAD","MarkupPreHead");
revised = updateMarkupBlock(revised,"POST-HEAD","MarkupPostHead");
revised = updateMarkupBlock(revised,"PRE-BODY","MarkupPreBody");
revised = updateMarkupBlock(revised,"POST-SCRIPT","MarkupPostBody");
return revised;
};
//
// UploadLog
//
// config.options.chkUploadLog :
// false : no logging
// true : logging
// config.options.txtUploadLogMaxLine :
// -1 : no limit
// 0 : no Log lines but UploadLog is still in place
// n : the last n lines are only kept
// NaN : no limit (-1)
bidix.UploadLog = function() {
if (!config.options.chkUploadLog)
return; // this.tiddler = null
this.tiddler = store.getTiddler("UploadLog");
if (!this.tiddler) {
this.tiddler = new Tiddler();
this.tiddler.title = "UploadLog";
this.tiddler.text = "| !date | !user | !location | !storeUrl | !uploadDir | !toFilename | !backupdir | !origin |";
this.tiddler.created = new Date();
this.tiddler.modifier = config.options.txtUserName;
this.tiddler.modified = new Date();
store.addTiddler(this.tiddler);
}
return this;
};
bidix.UploadLog.prototype.addText = function(text) {
if (!this.tiddler)
return;
// retrieve maxLine when we need it
var maxLine = parseInt(config.options.txtUploadLogMaxLine,10);
if (isNaN(maxLine))
maxLine = -1;
// add text
if (maxLine != 0)
this.tiddler.text = this.tiddler.text + text;
// Trunck to maxLine
if (maxLine >= 0) {
var textArray = this.tiddler.text.split('\n');
if (textArray.length > maxLine + 1)
textArray.splice(1,textArray.length-1-maxLine);
this.tiddler.text = textArray.join('\n');
}
// update tiddler fields
this.tiddler.modifier = config.options.txtUserName;
this.tiddler.modified = new Date();
store.addTiddler(this.tiddler);
// refresh and notifiy for immediate update
story.refreshTiddler(this.tiddler.title);
store.notify(this.tiddler.title, true);
};
bidix.UploadLog.prototype.startUpload = function(storeUrl, toFilename, uploadDir, backupDir) {
if (!this.tiddler)
return;
var now = new Date();
var text = "\n| ";
var filename = bidix.basename(document.location.toString());
if (!filename) filename = '/';
text += now.formatString("0DD/0MM/YYYY 0hh:0mm:0ss") +" | ";
text += config.options.txtUserName + " | ";
text += "[["+filename+"|"+location + "]] |";
text += " [[" + bidix.basename(storeUrl) + "|" + storeUrl + "]] | ";
text += uploadDir + " | ";
text += "[[" + bidix.basename(toFilename) + " | " +toFilename + "]] | ";
text += backupDir + " |";
this.addText(text);
};
bidix.UploadLog.prototype.endUpload = function(status) {
if (!this.tiddler)
return;
this.addText(" "+status+" |");
};
//
// Utilities
//
bidix.checkPlugin = function(plugin, major, minor, revision) {
var ext = version.extensions[plugin];
if (!
(ext &&
((ext.major > major) ||
((ext.major == major) && (ext.minor > minor)) ||
((ext.major == major) && (ext.minor == minor) && (ext.revision >= revision))))) {
// write error in PluginManager
if (pluginInfo)
pluginInfo.log.push("Requires " + plugin + " " + major + "." + minor + "." + revision);
eval(plugin); // generate an error : "Error: ReferenceError: xxxx is not defined"
}
};
bidix.dirname = function(filePath) {
if (!filePath)
return;
var lastpos;
if ((lastpos = filePath.lastIndexOf("/")) != -1) {
return filePath.substring(0, lastpos);
} else {
return filePath.substring(0, filePath.lastIndexOf("\\"));
}
};
bidix.basename = function(filePath) {
if (!filePath)
return;
var lastpos;
if ((lastpos = filePath.lastIndexOf("#")) != -1)
filePath = filePath.substring(0, lastpos);
if ((lastpos = filePath.lastIndexOf("/")) != -1) {
return filePath.substring(lastpos + 1);
} else
return filePath.substring(filePath.lastIndexOf("\\")+1);
};
bidix.initOption = function(name,value) {
if (!config.options[name])
config.options[name] = value;
};
//
// Initializations
//
// require PasswordOptionPlugin 1.0.1 or better
bidix.checkPlugin("PasswordOptionPlugin", 1, 0, 1);
// styleSheet
setStylesheet('.txtUploadStoreUrl, .txtUploadBackupDir, .txtUploadDir {width: 22em;}',"uploadPluginStyles");
//optionsDesc
merge(config.optionsDesc,{
txtUploadStoreUrl: "Url of the UploadService script (default: store.php)",
txtUploadFilename: "Filename of the uploaded file (default: in index.html)",
txtUploadDir: "Relative Directory where to store the file (default: . (downloadService directory))",
txtUploadBackupDir: "Relative Directory where to backup the file. If empty no backup. (default: ''(empty))",
txtUploadUserName: "Upload Username",
pasUploadPassword: "Upload Password",
chkUploadLog: "do Logging in UploadLog (default: true)",
txtUploadLogMaxLine: "Maximum of lines in UploadLog (default: 10)"
});
// Options Initializations
bidix.initOption('txtUploadStoreUrl','');
bidix.initOption('txtUploadFilename','');
bidix.initOption('txtUploadDir','');
bidix.initOption('txtUploadBackupDir','');
bidix.initOption('txtUploadUserName','');
bidix.initOption('pasUploadPassword','');
bidix.initOption('chkUploadLog',true);
bidix.initOption('txtUploadLogMaxLine','10');
// Backstage
merge(config.tasks,{
uploadOptions: {text: "upload", tooltip: "Change UploadOptions and Upload", content: '<<uploadOptions>>'}
});
config.backstageTasks.push("uploadOptions");
//}}}