<commit_before>//
// Author: Nuno Aguiar

plugin("ZIP");
ow.loadObj();

var createTmp = false;

//Check if a Jar was repacked
function isRepackJar(aJarFilePath) {
	var res = true;

	var aJar = new ZIP();
	try {
		aJar.loadFile(aJarFilePath);
		var listJar = aJar.list();

		for(let i in listJar) {
			//if(listJar[i].name.match(/jarinjarloader/) && listJar[i].name.match(/eclipse/)) {
			if (listJar[i].name.match(/\/js\.jar/)) {
				res = false;
			}
		}
	} catch(e) { }
	aJar.close();

	return res;
}

function getModulesToExclude() {
	loadUnderscore();
	var plugins = __expr.split(/,/);
	var toExclude = [];

	var vad = io.readFile(getOpenAFJar() + "::versionsAndDeps.json");

	for(let i in plugins) {
		var libsOut = _.flatten($from(vad.plugins).equals("name", plugins[i]).equals("removable", true).select(function(r) { return r.deps; }));
		var libsIn  = _.flatten($from(vad.plugins).not().equals("name", plugins[i]).select(function(r) { return r.deps; }));

		toExclude = toExclude.concat(_.without(libsOut, libsIn));
	}

	toExclude = _.uniq(toExclude);
	for(var i in toExclude) {
		if (isDef(toExclude[i]) && toExclude[i].match(/^lib\//)) {
			toExclude[i] = toExclude[i].replace(/^lib\//, "");
		}
	}

	return toExclude;
}

function isRepacked() {
	return irj;
}

function repackIncludeFile(aZipPath, aFilePath) {
	includeMore[aZipPath] = {
		name: aZipPath,
		outside: true,
		outsideName: aFilePath
	}
}

function repackSetMainClass(aClass) {
	mainClass = aClass;
}

try {
  var curDir    = java.lang.System.getProperty("user.dir") + "";
  var classPath = getOpenAFJar();
  var os        = String(java.lang.System.getProperty("os.name"));
} catch (e) {
  logErr("Couldn't retrieve system properties: " + e.message);
  java.lang.System.exit(0);
}

log("Checking if repacking OpenAF for faster loading is needed...");

var zip    = new ZIP();
var zipNew = new ZIP();
var includeMore = {};
var mainClass = undefined;

var irj = isRepackJar(classPath);

try {
// Set .package.json

packJson = jsonParse(af.fromBytes2String(zip.streamGetFile(getOpenAFJar(), ".package.json")));
packJson.version = getVersion();

var fileDB = getOpenAFPath() + "/" + PACKAGESJSON_DB;

var packages = {};
var zipdb = new ZIP();
try {
	packages = af.fromJson(af.fromBytes2String(zipdb.streamGetFile(fileDB, PACKAGESJSON)));
} catch(e) {
	 if (!(e.message.match(/FileNotFoundException/))) logErr(e.message);
}

if (!isUndefined(packages)) {
	packages["OpenAF"] = packJson;
} else {
	packages = {};
	packages["OpenAF"] = packJson;
}

try {
	zipdb.streamPutFile(fileDB, PACKAGESJSON, af.fromString2Bytes(stringify(packages)));
} catch (e) {
	logErr(e.message);
}

// PreRepack actions
$from(ow.obj.fromObj2Array(getOPackLocalDB(), "path")).notEmpty("scripts.prerepack").select(function(r) {
	if (r.name == "OpenCli" && r.version != af.getVersion()) {
		logWarn("Please update OpenCli to match the version " + af.getVersion());
		if (io.fileExists(r.path + "/.url")) {
			logWarn("by executing 'opack install " + eval( io.readFileYAML(r.path + "/.url").c ) + "'" );
		}
	} else {
		log("Executing prepack actions from oPack '" + r.name + "'");
		try {
			var s = new Function(r.scripts.prerepack);
			s();
		} catch(e) {
			logErr("opack '" + r.name + "': " + e);
		}
	}
});

if (!irj || __expr != "" || Object.keys(includeMore).length > 0) {
	var oldVersionFile = classPath.replace(/openaf.jar/, "openaf.jar.orig");

	if (!irj) {
		log("Backup to " + oldVersionFile);
		io.writeFileBytes(oldVersionFile, io.readFileBytes(classPath));
	}

	var toExclude = [];
	if (__expr != "") toExclude = getModulesToExclude();

	try {
		zip.loadFile(oldVersionFile);
	} catch(e) {
		logErr("For the repack operation, excluding or adding modules the original un-repacked openaf.jar version (openaf.jar.orig) is needed!");
		throw e;
	}

	var list = zip.list(oldVersionFile);
	list = merge(list, includeMore);

	var c = 0;
	for(let i in list) {
		c++;
		var el = list[i];

		lognl("Progress " + Math.round(c * 100 / Object.keys(list).length) + "% (" + c + "/" + Object.keys(list).length + ")\r");

		if (toExclude.indexOf(el.name) >= 0) {
			log("Excluding " + el.name);
			continue;
		}

		if(el.name.match(/\.jar$/)) {
			var zipTemp = new ZIP();

			if (el.name.match(/tools-attach.jar$/) &&
			    Packages.jodd.util.ClassLoaderUtil.findToolsJar() != null) {
				zipTemp.loadFile(String(Packages.jodd.util.ClassLoaderUtil.findToolsJar()));
			} else {
				if (!el.outside)
					zipTemp.load(zip.getFile(el.name));
				else
					zipTemp.loadFile(el.outsideName);
			}

			var listTemp = zipTemp.list();

			for (let ii in listTemp) {
				var elTemp = listTemp[ii];
				if (!(elTemp.name.match(/MANIFEST.MF$/)) && !(elTemp.name.match(/ECLIPSE_.RSA$/))) {
					zipNew.putFile(elTemp.name, zipTemp.getFile(elTemp.name));
				}
			}
			zipTemp.close();
		} else {
			if( el.name.match(/MANIFEST.MF$/) ) {
				var str;

				str = af.fromBytes2String(zip.getFile(el.name));

				var newClass = (isDef(mainClass)) ? mainClass : "openaf.AFCmdOS";
				if ((str.match(/jarinjarloader/) && str.match(/eclipse/) )) {
					str = str.replace(/org\.eclipse\.jdt\.internal\.jarinjarloader\.JarRsrcLoader/, newClass);
				} else {
					str = str.replace(/^Main-Class: .+$/m, "Main-Class: " + newClass);
                }
				zipNew.putFile(el.name, af.fromString2Bytes(str));
			} else {
				if (!(el.name.match(/jarinjarloader/))) {
					if (!el.outside)
						zipNew.putFile(el.name, zip.getFile(el.name));
					else
						zipNew.putFile(el.name, io.readFileBytes(el.outsideName));
				}
			}
		}
	}

	ow.loadObj();
	var ilist = "JarIndex-Version: 1.0\n\n" +
				$from(ow.obj.fromObj2Array(zipNew.list()))
				.notStarts("name", "META-INF/")
				.ends("name", "/")
				.select((r)=>{ return r.name.substr(0, r.name.length -1); })
				.join("\n");
	zipNew.putFile("META-INF/INDEX.LIST", af.fromString2Bytes(ilist));
	log("Writing new repacked openaf.jar...");
	zipNew.generate2File(classPath + ".tmp", {"compressionLevel": 9}, true);
	createTmp = true;
	zip.close();
	zipNew.close();
} else {
	log("OpenAF is repacked.");
}

if (createTmp) {
	io.writeFileBytes(classPath.replace(/\\/g, "/"), io.readFileBytes(classPath.replace(/openaf.jar/, "openaf.jar.tmp")));
	io.rm(classPath.replace(/openaf.jar/, "openaf.jar.tmp"));
}

log("Done repacking OpenAF.jar");
// We need to stop (but no longer needed)
//java.lang.System.exit(0);
} catch(e) { printErr(e); if (isDef(e.javaException)) se.javaException.printStackTrace(); }<commit_msg>repack: try to download jar orig if not available<commit_after>//
// Author: Nuno Aguiar

plugin("ZIP");
ow.loadObj();

var createTmp = false;

//Check if a Jar was repacked
function isRepackJar(aJarFilePath) {
	var res = true;

	var aJar = new ZIP();
	try {
		aJar.loadFile(aJarFilePath);
		var listJar = aJar.list();

		for(let i in listJar) {
			//if(listJar[i].name.match(/jarinjarloader/) && listJar[i].name.match(/eclipse/)) {
			if (listJar[i].name.match(/\/js\.jar/)) {
				res = false;
			}
		}
	} catch(e) { }
	aJar.close();

	return res;
}

function getModulesToExclude() {
	loadUnderscore();
	var plugins = __expr.split(/,/);
	var toExclude = [];

	var vad = io.readFile(getOpenAFJar() + "::versionsAndDeps.json");

	for(let i in plugins) {
		var libsOut = _.flatten($from(vad.plugins).equals("name", plugins[i]).equals("removable", true).select(function(r) { return r.deps; }));
		var libsIn  = _.flatten($from(vad.plugins).not().equals("name", plugins[i]).select(function(r) { return r.deps; }));

		toExclude = toExclude.concat(_.without(libsOut, libsIn));
	}

	toExclude = _.uniq(toExclude);
	for(var i in toExclude) {
		if (isDef(toExclude[i]) && toExclude[i].match(/^lib\//)) {
			toExclude[i] = toExclude[i].replace(/^lib\//, "");
		}
	}

	return toExclude;
}

function isRepacked() {
	return irj;
}

function repackIncludeFile(aZipPath, aFilePath) {
	includeMore[aZipPath] = {
		name: aZipPath,
		outside: true,
		outsideName: aFilePath
	}
}

function repackSetMainClass(aClass) {
	mainClass = aClass;
}

try {
  var curDir    = java.lang.System.getProperty("user.dir") + "";
  var classPath = getOpenAFJar();
  var os        = String(java.lang.System.getProperty("os.name"));
} catch (e) {
  logErr("Couldn't retrieve system properties: " + e.message);
  java.lang.System.exit(0);
}

log("Checking if repacking OpenAF for faster loading is needed...");

var zip    = new ZIP();
var zipNew = new ZIP();
var includeMore = {};
var mainClass = undefined;

var irj = isRepackJar(classPath);

try {
// Set .package.json

packJson = jsonParse(af.fromBytes2String(zip.streamGetFile(getOpenAFJar(), ".package.json")));
packJson.version = getVersion();

var fileDB = getOpenAFPath() + "/" + PACKAGESJSON_DB;

var packages = {};
var zipdb = new ZIP();
try {
	packages = af.fromJson(af.fromBytes2String(zipdb.streamGetFile(fileDB, PACKAGESJSON)));
} catch(e) {
	 if (!(e.message.match(/FileNotFoundException/))) logErr(e.message);
}

if (!isUndefined(packages)) {
	packages["OpenAF"] = packJson;
} else {
	packages = {};
	packages["OpenAF"] = packJson;
}

try {
	zipdb.streamPutFile(fileDB, PACKAGESJSON, af.fromString2Bytes(stringify(packages)));
} catch (e) {
	logErr(e.message);
}

// PreRepack actions
$from(ow.obj.fromObj2Array(getOPackLocalDB(), "path")).notEmpty("scripts.prerepack").select(function(r) {
	if (r.name == "OpenCli" && r.version != af.getVersion()) {
		logWarn("Please update OpenCli to match the version " + af.getVersion());
		if (io.fileExists(r.path + "/.url")) {
			logWarn("by executing 'opack install " + eval( io.readFileYAML(r.path + "/.url").c ) + "'" );
		}
	} else {
		log("Executing prepack actions from oPack '" + r.name + "'");
		try {
			var s = new Function(r.scripts.prerepack);
			s();
		} catch(e) {
			logErr("opack '" + r.name + "': " + e);
		}
	}
});

if (!irj || __expr != "" || Object.keys(includeMore).length > 0) {
	var oldVersionFile = classPath.replace(/openaf.jar/, "openaf.jar.orig");

    if (!noHomeComms) sync(() => {
        if (!io.fileExists(oldVersionFile)) {
            var dist = getDistribution() + "/";
            if (dist == "stable/") dist = "";

            var url = "https://openaf.io/" + dist + "openaf-" + getVersion() + ".jar";
            logWarn("Trying to download from '" + url + "'...");
            $rest().get2File(oldVersionFile, url);

            if (!(io.fileExists(oldVersionFile) && io.fileInfo(oldVersionFile).size > 0)) {
                logErr("Couldn't download '" + url + "'");
            }
        }
    });

	if (!irj) {
		log("Backup to " + oldVersionFile);
		io.writeFileBytes(oldVersionFile, io.readFileBytes(classPath));
	}

	var toExclude = [];
	if (__expr != "") toExclude = getModulesToExclude();

	try {
		zip.loadFile(oldVersionFile);
	} catch(e) {
		logErr("For the repack operation, excluding or adding modules the original un-repacked openaf.jar version (openaf.jar.orig) is needed!");
		throw e;
	}

	var list = zip.list(oldVersionFile);
	list = merge(list, includeMore);

	var c = 0;
	for(let i in list) {
		c++;
		var el = list[i];

		lognl("Progress " + Math.round(c * 100 / Object.keys(list).length) + "% (" + c + "/" + Object.keys(list).length + ")\r");

		if (toExclude.indexOf(el.name) >= 0) {
			log("Excluding " + el.name);
			continue;
		}

		if(el.name.match(/\.jar$/)) {
			var zipTemp = new ZIP();

			if (el.name.match(/tools-attach.jar$/) &&
			    Packages.jodd.util.ClassLoaderUtil.findToolsJar() != null) {
				zipTemp.loadFile(String(Packages.jodd.util.ClassLoaderUtil.findToolsJar()));
			} else {
				if (!el.outside)
					zipTemp.load(zip.getFile(el.name));
				else
					zipTemp.loadFile(el.outsideName);
			}

			var listTemp = zipTemp.list();

			for (let ii in listTemp) {
				var elTemp = listTemp[ii];
				if (!(elTemp.name.match(/MANIFEST.MF$/)) && !(elTemp.name.match(/ECLIPSE_.RSA$/))) {
					zipNew.putFile(elTemp.name, zipTemp.getFile(elTemp.name));
				}
			}
			zipTemp.close();
		} else {
			if( el.name.match(/MANIFEST.MF$/) ) {
				var str;

				str = af.fromBytes2String(zip.getFile(el.name));

				var newClass = (isDef(mainClass)) ? mainClass : "openaf.AFCmdOS";
				if ((str.match(/jarinjarloader/) && str.match(/eclipse/) )) {
					str = str.replace(/org\.eclipse\.jdt\.internal\.jarinjarloader\.JarRsrcLoader/, newClass);
				} else {
					str = str.replace(/^Main-Class: .+$/m, "Main-Class: " + newClass);
                }
				zipNew.putFile(el.name, af.fromString2Bytes(str));
			} else {
				if (!(el.name.match(/jarinjarloader/))) {
					if (!el.outside)
						zipNew.putFile(el.name, zip.getFile(el.name));
					else
						zipNew.putFile(el.name, io.readFileBytes(el.outsideName));
				}
			}
		}
	}

	ow.loadObj();
	var ilist = "JarIndex-Version: 1.0\n\n" +
				$from(ow.obj.fromObj2Array(zipNew.list()))
				.notStarts("name", "META-INF/")
				.ends("name", "/")
				.select((r)=>{ return r.name.substr(0, r.name.length -1); })
				.join("\n");
	zipNew.putFile("META-INF/INDEX.LIST", af.fromString2Bytes(ilist));
	log("Writing new repacked openaf.jar...");
	zipNew.generate2File(classPath + ".tmp", {"compressionLevel": 9}, true);
	createTmp = true;
	zip.close();
	zipNew.close();
} else {
	log("OpenAF is repacked.");
}

if (createTmp) {
	io.writeFileBytes(classPath.replace(/\\/g, "/"), io.readFileBytes(classPath.replace(/openaf.jar/, "openaf.jar.tmp")));
	io.rm(classPath.replace(/openaf.jar/, "openaf.jar.tmp"));
}

log("Done repacking OpenAF.jar");
// We need to stop (but no longer needed)
//java.lang.System.exit(0);
} catch(e) { printErr(e); if (isDef(e.javaException)) se.javaException.printStackTrace(); }<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var width = 1280;
        var height = 720;
        var blockSize = 16;

        document.getElementById("paintbtn").onclick = paint;

        //paint the map
        function paint() {
            c.rect(width/2,height/2,90,90);
            c.stroke();
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var width = 1280;
        var height = 720;
        var blockSize = 16;

        document.getElementById("paintbtn").onclick = paint;

        //paint the map
        function paint() {
            c.rect(width/2,height/2,90,90);
            for(int i = 0; i< 3; i++){
                for(int j = 0; j< 3; j++){
                    c.rect(width/2+i, height/2 + j, 30, 30);
                }
            }
            c.stroke();
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>var CSSCurssors = CSSCurssors || {};

window.onload = function() {
	CSSCurssors.loadCursors();
}

/**
 * Cursor Store
 *
 * Encapsules the different cursor properties in CSS along with browser that support the property
 * in an array of JSON.
 *
 * an entry needs 'name' property to get displayed, other properties are optional if no  value for browser
 * is set the browser will be indicated as not supported.
 */

CSSCurssors.cursors = [
	'{ "name" : "auto", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "default", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "none", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "pointer", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "progress", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "help", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "text", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "cell", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "crosshair", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "alias", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "context-menu", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "vertical-text", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "copy", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "move", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "no-drop", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "not-allowed", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "all-scroll", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "col-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "row-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "nesw-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "nwse-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "n-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "e-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "s-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "w-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "ns-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "ew-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "ne-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "nw-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "sw-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "se-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "wait", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "grab", "chrome" : 1, "firefox" : 1, "safari":0, "opera" : 1, "internet-explorer" : 0, "edge" : 0}',
	'{ "name" : "grabbing", "chrome" : 1, "firefox" : 1, "safari":0, "opera" : 1, "internet-explorer" : 0, "edge" : 0}',
	'{ "name" : "zoom-in", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "zoom-out", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 0, "edge" : 1}'
];

/**
 * Cursor Loader
 *
 * Called on page load, parses the Array, extract data and transfer to createNode to make an entry.
 * returned node is appended to the div.
 */
CSSCurssors.loadCursors = function() {
	var cursorItems = document.getElementById("cursorItems");
	var loadingContainer = document.getElementById("loading-container");
	loadingContainer.parentElement.removeChild(loadingContainer);
	var sizeOfcursorItems = CSSCurssors.cursors.length;
	var end = 0;
	for ( var cursor in CSSCurssors.cursors ) {
		if ( (sizeOfcursorItems-1 ) == cursor) {
			end = 1;
		}
		cursorItems.appendChild(CSSCurssors.createNode(CSSCurssors.cursors[cursor],end));
	}
}

/**
 * Creates New Node
 *
 * Cretes new node for a property and sets the cursor value to it.
 */
CSSCurssors.createNode = function(cursorData, end ) {
	var cursorData =  JSON.parse(cursorData);
	if ( cursorData['name'] ) {
		var newCursorNode = document.createElement("div");
		var browserSupport = ''; 	// Initilize to null
		if ( end == 1 ) {
			newCursorNode.setAttribute("class", "grid column small-4 end");
		} else {
			newCursorNode.setAttribute("class", "grid column small-4");
		}

		if ( cursorData['chrome']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['firefox']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['safari']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['opera']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['internet-explorer']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['edge']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		newCursorNode.innerHTML = '

Cursor : ' + cursorData['name']   + '

' + browserSupport + '
';
		return newCursorNode;

	} else {
		return 0;
	}

}
<commit_msg>Reverted some lines that did not need to be changed<commit_after>var CSSCurssors = CSSCurssors || {};

window.onload = function() {
	CSSCurssors.loadCursors();
}

/**
 * Cursor Store
 *
 * Encapsules the different cursor properties in CSS along with browser that support the property
 * in an array of JSON.
 *
 * an entry needs 'name' property to get displayed, other properties are optional if no  value for browser
 * is set the browser will be indicated as not supported.
 */

CSSCurssors.cursors = [
	'{ "name" : "auto", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "default", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "none", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "pointer", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "progress", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "help", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "text", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "cell", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "crosshair", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "alias", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "context-menu", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "vertical-text", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "copy", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "move", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "no-drop", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "not-allowed", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "all-scroll", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "col-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "row-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 0, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "nesw-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "nwse-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "n-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "e-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "s-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "w-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "ns-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "ew-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "ne-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "nw-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "sw-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "se-resize", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "wait", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 1, "edge" : 1}',
	'{ "name" : "grab", "chrome" : 1, "firefox" : 1, "safari":0, "opera" : 1, "internet-explorer" : 0, "edge" : 0}',
	'{ "name" : "grabbing", "chrome" : 1, "firefox" : 1, "safari":0, "opera" : 1, "internet-explorer" : 0, "edge" : 0}',
	'{ "name" : "zoom-in", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 0, "edge" : 1}',
	'{ "name" : "zoom-out", "chrome" : 1, "firefox" : 1, "safari":1, "opera" : 1, "internet-explorer" : 0, "edge" : 1}'
];

/**
 * Cursor Loader
 *
 * Called on page load, parses the Array, extract data and transfer to createNode to make an entry.
 * returned node is appended to the div.
 */
CSSCurssors.loadCursors = function() {
	var cursorItems = document.getElementById("cursorItems");
	var loadingContainer = document.getElementById("loading-container");
	loadingContainer.parentElement.removeChild(loadingContainer);
	var sizeOfcursorItems = CSSCurssors.cursors.length;
	var end = 0;
	for ( var cursor in CSSCurssors.cursors ) {
		if ( (sizeOfcursorItems-1 ) == cursor) {
			end = 1;
		}
		cursorItems.appendChild(CSSCurssors.createNode(CSSCurssors.cursors[cursor],end));
	}
}

/**
 * Creates New Node
 *
 * Cretes new node for a property and sets the cursor value to it.
 */
CSSCurssors.createNode = function(cursorData, end ) {
	var cursorData =  JSON.parse(cursorData);
	if ( cursorData['name'] ) {
		var newCursorNode = document.createElement("div");
		var browserSupport = ''; 	// Initilize to null
		if ( end == 1 ) {
			newCursorNode.setAttribute("class", "grid column small-4 end");
		} else {
			newCursorNode.setAttribute("class", "grid column small-4");
		}

		if ( cursorData['chrome']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['firefox']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['safari']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['opera']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['internet-explorer']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		if ( cursorData['edge']  )  {
			browserSupport += '

';
		} else {
			browserSupport += '

';
		}

		newCursorNode.innerHTML = '

Cursor : ' + cursorData['name']   + '

' + browserSupport + '
';
		return newCursorNode;

	} else {
		return 0;
	}

}
<|endoftext|>


<commit_before>/*
 * The OnCore Consulting LLC License
 *
 * Copyright 2016 OnCore Consulting LLC, All Rights Reserved.
 *
 * Permission IS NOT GRANTED to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, unless the following conditions are met:
 *
 * Written permission is obtained from
 * OnCore Consulting LLC and the above copyright
 * notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * The ServiceEndPoints object defines all Service End points used
 * by the application.  This file should be altered on deployment
 * by the CM scripts to alter the endpoints based on target environment.
 *
 * @author Royce Owens
 *
 * @returns {ServiceEndPoints}
 */
'use strict';
function ServiceEndPoints()
{

}

ServiceEndPoints.prototype = {

    /**
     * Given a service name, return the fully
     * qualified service URL.
     *
     * @param {type} key a service name
     * @returns {String} a fully qualified URL
     */
    getEndPoint: function (key)
    {
        // ====== CM TOUCH POINT =================
        var calOrdersHost = "http://localhost:8080";
        // =======================================

        if (key === "findNavBarPrivilegesByPartyId")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.party/findNavBarPrivilegesByPartyId";
        } else if (key === "findNavMenuPrivilegesByPartyId")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.party/findNavMenuPrivilegesByPartyId";
        } else if (key === "findAllPrivilegesByPartyId")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.party/findAllPrivilegesByPartyId";
        } else if (key === "findPartyByUserIdAndPassword")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.party/findPartyByUserIdAndPassword";
        } else if (key === "createOrder")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.order1/create";
        } else
        {
            return "UNDEFINED";
        }
    }
};
<commit_msg>Revert "[#139507469] Initial REST service to store orders.  This will need to be updated with the actual JSON structure once available."<commit_after>/*
 * The OnCore Consulting LLC License
 *
 * Copyright 2016 OnCore Consulting LLC, All Rights Reserved.
 *
 * Permission IS NOT GRANTED to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, unless the following conditions are met:
 *
 * Written permission is obtained from
 * OnCore Consulting LLC and the above copyright
 * notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

/**
 * The ServiceEndPoints object defines all Service End points used
 * by the application.  This file should be altered on deployment
 * by the CM scripts to alter the endpoints based on target environment.
 *
 * @author Royce Owens
 *
 * @returns {ServiceEndPoints}
 */
'use strict';
function ServiceEndPoints()
{

}

ServiceEndPoints.prototype = {

    /**
     * Given a service name, return the fully
     * qualified service URL.
     *
     * @param {type} key a service name
     * @returns {String} a fully qualified URL
     */
    getEndPoint: function (key)
    {
        // ====== CM TOUCH POINT =================
        var calOrdersHost = "http://localhost:8080";
        // =======================================

        if (key === "findNavBarPrivilegesByPartyId")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.party/findNavBarPrivilegesByPartyId";
        } else if (key === "findNavMenuPrivilegesByPartyId")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.party/findNavMenuPrivilegesByPartyId";
        } else if (key === "findAllPrivilegesByPartyId")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.party/findAllPrivilegesByPartyId";
        } else if (key === "findPartyByUserIdAndPassword")
        {
            return calOrdersHost + "/CalOrdersRest/webresources/com.oncore.calorders.rest.party/findPartyByUserIdAndPassword";
        } else
        {
            return "UNDEFINED";
        }
    }
};
<|endoftext|>


<commit_before>var app = angular.module( 'interface', ['ngAria', 'ngRoute', 'ngSanitize', 'pascalprecht.translate']);<commit_msg>comment<commit_after>// ----------------------------------------------------------------------------
// create application angular
var app = angular.module( 'interface', [
    'ngAria',
    'ngRoute',
    'ngSanitize',
    'pascalprecht.translate'
]);<|endoftext|>


<commit_before>'use strict';

var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var PgSession = require('connect-pg-simple')(session);
var ConnectRoles = require('connect-roles');
var passportify = require('./utils/passportify');
var _ = require('lodash');
var busboy = require('connect-busboy');
var user;
var methodOverride;
var adminPage;

// *** Custom Middleware ***

// The built-in Connect/Express middleware modified to only allow overrides on POST-requests
methodOverride = function (key) {
  key = key || '_method';
  return function methodOverride(req, res, next) {
    if ((req.originalMethod || req.method).toUpperCase() !== 'POST') {
      next();
      return;
    }

    req.originalMethod = req.originalMethod || req.method;

    if (req.query && key in req.query) {
      req.method = req.query[key].toUpperCase();
      delete req.query[key];
    } else if (req.body && key in req.body) {
      req.method = req.body[key].toUpperCase();
      delete req.body[key];
    } else if (req.headers['x-http-method-override']) {
      req.method = req.headers['x-http-method-override'].toUpperCase();
    }

    next();
  };
};

// *** User Role Definitions ***

user = new ConnectRoles({
  userProperty: 'passportUser',
  failureHandler: function (req, res, action) {
    if (!req.isAuthenticated()) {
      res.redirect('/admin/login');
    } else {
      res.status(403);
      res.send('Access Denied - You don\'t have permission to: ' + action);
    }
  },
});

user.use(function (req) {
  if (!req.isAuthenticated()) {
    return false;
  }
});
user.use('edit content', function (req) {
  if (req.passportUser.role === 'editor') {
    return true;
  }
});
user.use(function (req) {
  if (req.passportUser.role === 'admin') {
    return true;
  }
});

adminPage = function (page) {
  var contentTypes = page.contentTypes;
  var assembleMainPage;
  var app;
  var config = page.config;
  var sessionStore = new PgSession({ conString: config.db });
  var knex = page.knex;

  page.on('close', function () {
    sessionStore.close();
  });

  // *** Express setup ***

  app = express();

  page.adminApp = app;

  app.use(cookieParser());
  app.use(busboy());
  app.use(session({
    store: sessionStore,
    secret: config.cookieSecret,
    cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
    resave: false,
    saveUninitialized: false,
  }));
  app.use(methodOverride());
  app.use(user.middleware());

  page.passportify = passportify(page);

  // *** Routes ***

  assembleMainPage = function (req, res, next, formOverride) {
    formOverride = formOverride || {};

    var queries;

    queries = _.map(contentTypes, function (contentType) {
      return req.userCan(contentType.getRequiredPermission()) ? contentType.getFormTemplateData() : Promise.resolve();
    });

    queries.unshift(knex('vars').first('value').where('key', 'dictionary'));

    Promise.all(queries).then(function (formData) {
      var templateChildren = {};
      var dictionary = page._fillDictionary(formData.shift()).dictionary;
      var element;

      _.each(contentTypes, function (contentType, contentTypeName) {
        var data = formData.shift();
        var formGroup = contentType.getFormGroup();
        var template;
        var formTemplate;
        var listTemplate;

        if (!req.userCan(contentType.getRequiredPermission())) {
          return;
        }

        //TODO: Move some of this logic into node-tema preprocessor / processor methods?

        formTemplate = contentType.getFormTemplate();

        if (formTemplate) {
          formTemplate = _.extend({
            form : formOverride[data.formName] || data.form,
            formData : data,
            dictionaryData : dictionary,
          }, formTemplate);
        }

        if (data.list !== undefined && contentType.getFormListTemplate()) {
          listTemplate = _.extend({ list : data.list }, contentType.getFormListTemplate());
        }

        // Do we need to wrap the parts together?
        if (formTemplate && listTemplate) {
          template = _.extend({ children : [] }, contentType.getFormWrapper(data));
          template.children.push(_.extend({
            noAdminPartWrap : true,
            canAdd : true,
          }, formTemplate));
          template.children.push(listTemplate);
        } else {
          template = listTemplate || formTemplate;
        }

        // Should we group it together with other forms?
        if (formGroup) {
          if (!templateChildren[formGroup.name]) {
            templateChildren[formGroup.name] = _.extend({
              templateWrappers : ['admin-section'],
              children : [],
            }, formGroup.attributes || {});
          }
          templateChildren[formGroup.name].children.push(_.extend({
            noAdminPartWrap : formGroup.noAdminPartWrap,
          }, template));
        } else {
          templateChildren[contentTypeName] = template;
        }
      });

      //TODO: Deal with ordering of form in the same way here as in "routes.js"
      templateChildren = _.values(templateChildren);

      if (templateChildren.length === 1) {
        element = templateChildren[0];
        if (element.template === 'admin-form') {
          element.formData.name = undefined;
        }
      }

      res.app.get('theme engine').recursiveRenderer({
        templateWrappers : ['admin-index', 'page', 'layout'],
        dictionaryData : dictionary,
        variables : {
          jsConfig : {
            //TODO: Move into the blocks content type
            blockTypes : _.difference(config.blockTypes, config.flickr.key ? [] : ['Flickr', 'Story']),
            flickrKey : config.flickr.key,
          },
        },
        children : templateChildren,
      }, function (err, result) {
        if (err) {
          next(err);
        } else {
          res.send(result);
        }
      });
    }).then(undefined, next);
  };

  app.get('/', user.can('edit content'), function (req, res, next) {
    assembleMainPage(req, res, next);
  });
  app.get('/login', function (req, res, next) {
    if (!req.isAuthenticated()) { return next(); }
    res.redirect('/admin');
  }, function (req, res, next) {
    res.app.get('theme engine').recursiveRenderer({
      templateWrappers : ['layout'],
      children : [{
        template : 'admin-login',
        authServices : page.passportify.services,
      }],
    }, function (err, result) {
      if (err) {
        next(err);
      } else {
        res.send(result);
      }
    });
  });
  app.get('/logout', function (req, res) {
    req.logout();
    res.redirect('/admin');
  });

  _.each(contentTypes, function (contentType) {
    contentType.setAdminPageAssemble(assembleMainPage).addToAdmin(app);
  });

  return app;
};

module.exports = adminPage;
<commit_msg>chore(debug): heroku debug<commit_after>'use strict';

var express = require('express');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var PgSession = require('connect-pg-simple')(session);
var ConnectRoles = require('connect-roles');
var passportify = require('./utils/passportify');
var _ = require('lodash');
var busboy = require('connect-busboy');
var user;
var methodOverride;
var adminPage;

// *** Custom Middleware ***

// The built-in Connect/Express middleware modified to only allow overrides on POST-requests
methodOverride = function (key) {
  key = key || '_method';
  return function methodOverride(req, res, next) {
    if ((req.originalMethod || req.method).toUpperCase() !== 'POST') {
      next();
      return;
    }

    req.originalMethod = req.originalMethod || req.method;

    if (req.query && key in req.query) {
      req.method = req.query[key].toUpperCase();
      delete req.query[key];
    } else if (req.body && key in req.body) {
      req.method = req.body[key].toUpperCase();
      delete req.body[key];
    } else if (req.headers['x-http-method-override']) {
      req.method = req.headers['x-http-method-override'].toUpperCase();
    }

    next();
  };
};

// *** User Role Definitions ***

user = new ConnectRoles({
  userProperty: 'passportUser',
  failureHandler: function (req, res, action) {
    if (!req.isAuthenticated()) {
      res.redirect('/admin/login');
    } else {
      res.status(403);
      res.send('Access Denied - You don\'t have permission to: ' + action);
    }
  },
});

user.use(function (req) {
  if (!req.isAuthenticated()) {
    return false;
  }
});
user.use('edit content', function (req) {
  if (req.passportUser.role === 'editor') {
    return true;
  }
});
user.use(function (req) {
  if (req.passportUser.role === 'admin') {
    return true;
  }
});

adminPage = function (page) {
  var contentTypes = page.contentTypes;
  var assembleMainPage;
  var app;
  var config = page.config;
  console.log('DB string:', config.db);
  var sessionStore = new PgSession({ conString: config.db });
  var knex = page.knex;

  page.on('close', function () {
    sessionStore.close();
  });

  // *** Express setup ***

  app = express();

  page.adminApp = app;

  app.use(cookieParser());
  app.use(busboy());
  app.use(session({
    store: sessionStore,
    secret: config.cookieSecret,
    cookie: { maxAge: 30 * 24 * 60 * 60 * 1000 }, // 30 days
    resave: false,
    saveUninitialized: false,
  }));
  app.use(methodOverride());
  app.use(user.middleware());

  page.passportify = passportify(page);

  // *** Routes ***

  assembleMainPage = function (req, res, next, formOverride) {
    formOverride = formOverride || {};

    var queries;

    queries = _.map(contentTypes, function (contentType) {
      return req.userCan(contentType.getRequiredPermission()) ? contentType.getFormTemplateData() : Promise.resolve();
    });

    queries.unshift(knex('vars').first('value').where('key', 'dictionary'));

    Promise.all(queries).then(function (formData) {
      var templateChildren = {};
      var dictionary = page._fillDictionary(formData.shift()).dictionary;
      var element;

      _.each(contentTypes, function (contentType, contentTypeName) {
        var data = formData.shift();
        var formGroup = contentType.getFormGroup();
        var template;
        var formTemplate;
        var listTemplate;

        if (!req.userCan(contentType.getRequiredPermission())) {
          return;
        }

        //TODO: Move some of this logic into node-tema preprocessor / processor methods?

        formTemplate = contentType.getFormTemplate();

        if (formTemplate) {
          formTemplate = _.extend({
            form : formOverride[data.formName] || data.form,
            formData : data,
            dictionaryData : dictionary,
          }, formTemplate);
        }

        if (data.list !== undefined && contentType.getFormListTemplate()) {
          listTemplate = _.extend({ list : data.list }, contentType.getFormListTemplate());
        }

        // Do we need to wrap the parts together?
        if (formTemplate && listTemplate) {
          template = _.extend({ children : [] }, contentType.getFormWrapper(data));
          template.children.push(_.extend({
            noAdminPartWrap : true,
            canAdd : true,
          }, formTemplate));
          template.children.push(listTemplate);
        } else {
          template = listTemplate || formTemplate;
        }

        // Should we group it together with other forms?
        if (formGroup) {
          if (!templateChildren[formGroup.name]) {
            templateChildren[formGroup.name] = _.extend({
              templateWrappers : ['admin-section'],
              children : [],
            }, formGroup.attributes || {});
          }
          templateChildren[formGroup.name].children.push(_.extend({
            noAdminPartWrap : formGroup.noAdminPartWrap,
          }, template));
        } else {
          templateChildren[contentTypeName] = template;
        }
      });

      //TODO: Deal with ordering of form in the same way here as in "routes.js"
      templateChildren = _.values(templateChildren);

      if (templateChildren.length === 1) {
        element = templateChildren[0];
        if (element.template === 'admin-form') {
          element.formData.name = undefined;
        }
      }

      res.app.get('theme engine').recursiveRenderer({
        templateWrappers : ['admin-index', 'page', 'layout'],
        dictionaryData : dictionary,
        variables : {
          jsConfig : {
            //TODO: Move into the blocks content type
            blockTypes : _.difference(config.blockTypes, config.flickr.key ? [] : ['Flickr', 'Story']),
            flickrKey : config.flickr.key,
          },
        },
        children : templateChildren,
      }, function (err, result) {
        if (err) {
          next(err);
        } else {
          res.send(result);
        }
      });
    }).then(undefined, next);
  };

  app.get('/', user.can('edit content'), function (req, res, next) {
    assembleMainPage(req, res, next);
  });
  app.get('/login', function (req, res, next) {
    if (!req.isAuthenticated()) { return next(); }
    res.redirect('/admin');
  }, function (req, res, next) {
    res.app.get('theme engine').recursiveRenderer({
      templateWrappers : ['layout'],
      children : [{
        template : 'admin-login',
        authServices : page.passportify.services,
      }],
    }, function (err, result) {
      if (err) {
        next(err);
      } else {
        res.send(result);
      }
    });
  });
  app.get('/logout', function (req, res) {
    req.logout();
    res.redirect('/admin');
  });

  _.each(contentTypes, function (contentType) {
    contentType.setAdminPageAssemble(assembleMainPage).addToAdmin(app);
  });

  return app;
};

module.exports = adminPage;
<|endoftext|>


<commit_before>var util = require('util');
var async = require('async');
var keypair = require('ssh-keypair');

var github = require('./github');

exports.create = function (toolbelt, repository, callback) {
  if (!repository.kind) {
    toolbelt.error("Repository kind must be specified.", repository);

    return callback(null);
  }

  var buildMaker = buildMakers[repository.kind];
  if (!buildMaker) {
    toolbelt.error("Unrecognized build kind: %s", repository.kind);

    return callback(null);
  }

  buildMaker(toolbelt, repository, function (err) {
    if (err) {
      toolbelt.error("Repository not created: %s", err.message, repository);
    }

    callback(null);
  });
};

var createGitHubBuild = function (toolbelt, repository, callback) {
  var Project = toolbelt.models.Project;
  var User = toolbelt.models.User;

  if (!repository.project) {
    toolbelt.error("Repository project must be specified.", repository);

    return callback(null);
  }

  var githubAccount = toolbelt.githubAccount();
  var projectName = repository.project.toLowerCase().replace(/ /g, '-');

  var githubProject = null;
  var striderProject = null;
  var privateKey = null;
  var publicKey = null;

  var checkForExistingProject = function (callback) {
    Project.findOne({ name: projectName }, function (err, p) {
      if (err) {
        toolbelt.error("Unable to check for existing project %s", projectName);

        return callback(err);
      }

      if (p) {
        // This project already exists.
        toolbelt.debug("The project %s already exists.", projectName);

        return callback(null, true);
      }

      callback(null, false);
    });
  };

  var fetchRepositoryData = function (callback) {
    github.getRepository(toolbelt, repository.project, function (err, p) {
      if (err) {
        if (err.notFound) {
          toolbelt.error(
            "Unable to see GitHub repository %s as user %s.",
            repository.project, githubAccount.config.login);
          toolbelt.error(
            "Have you granted %s access rights to that repository?",
            githubAccount.config.login);
        } else {
          toolbelt.error("Unable to fetch GitHub project %s", repository.project);
        }

        return callback(err);
      }

      githubProject = p;
      callback(null);
    });
  };

  var generateKeyPair = function (callback) {
    keypair(repository.name + '-' + toolbelt.user.email, function (err, priv, pub) {
      if (err) return callback(err);

      privateKey = priv;
      publicKey = pub;
      callback(null);
    });
  };

  var createStriderProject = function (callback) {
    var providerConfig = {
      id: 'github',
      account: githubAccount.id,
      repo_id: githubProject.id,
      config: {
        auth: { type: 'https' },
        repo: githubProject.repo,
        owner: githubProject.owner.login,
        url: githubProject.clone_url
      }
    };

    var projectAttrs = {
      name: projectName,
      display_name: githubProject.name,
      display_url: githubProject.display_url,
      public: false,
      prefetch_config: false,
      creator: toolbelt.user._id,
      provider: providerConfig,
      branches: [
        {
          name: 'master',
          active: true,
          mirror_master: false,
          deploy_on_green: true,
          pubkey: publicKey,
          privkey: privateKey,
          plugins: [],
          runner: { id: 'simple-runner', config: { pty: false } }
        },
        {
          name: '*',
          mirror_master: true
        }
      ]
    };

    toolbelt.githubProviderPlugin.setupRepo(githubAccount.config, providerConfig, projectAttrs, function (err, config) {
      if (err) {
        toolbelt.error("Unable to initialize project with GitHub provider", err);
        return callback(err);
      }

      projectAttrs.provider.config = config;

      Project.create(projectAttrs, function (err, project) {
        if (err) {
          toolbelt.error("Unable to create Strider project %s", projectName, err);
          return callback(err);
        }

        callback(null);
      });
    });
  };

  var grantUsersAccess = function (callback) {
    User.update({ _id: toolbelt.user._id }, {
      $push: {
        projects: {
          name: projectName,
          display_name: githubProject.name,
          access_level: 2
        }
      }
    }, function (err, count) {
      if (err) {
        toolbelt.error("Failed to give %s admin access to the project %s.", toolbelt.user.email, projectName, err);
      }

      if (count < 1) {
        toolbelt.error("User %s not found to grant admin access to project %s.", toolbelt.user.email, projectName);
      }

      callback(null);
    });
  };

  checkForExistingProject(function (err, exists) {
    if (err || exists) callback(null);
    if (exists) return callback(null);

    async.series([
      fetchRepositoryData,
      generateKeyPair,
      createStriderProject,
      grantUsersAccess
    ], function (err) {
      if (err) {
        toolbelt.error("Failed to create build for project %s: %s", projectName, err.message);
      }

      callback(null);
    });
  });
};

var buildMakers = {
  github: createGitHubBuild
};
<commit_msg>Plugin functions are in .webapp<commit_after>var util = require('util');
var async = require('async');
var keypair = require('ssh-keypair');

var github = require('./github');

exports.create = function (toolbelt, repository, callback) {
  if (!repository.kind) {
    toolbelt.error("Repository kind must be specified.", repository);

    return callback(null);
  }

  var buildMaker = buildMakers[repository.kind];
  if (!buildMaker) {
    toolbelt.error("Unrecognized build kind: %s", repository.kind);

    return callback(null);
  }

  buildMaker(toolbelt, repository, function (err) {
    if (err) {
      toolbelt.error("Repository not created: %s", err.message, repository);
    }

    callback(null);
  });
};

var createGitHubBuild = function (toolbelt, repository, callback) {
  var Project = toolbelt.models.Project;
  var User = toolbelt.models.User;

  if (!repository.project) {
    toolbelt.error("Repository project must be specified.", repository);

    return callback(null);
  }

  var githubAccount = toolbelt.githubAccount();
  var projectName = repository.project.toLowerCase().replace(/ /g, '-');

  var githubProject = null;
  var striderProject = null;
  var privateKey = null;
  var publicKey = null;

  var checkForExistingProject = function (callback) {
    Project.findOne({ name: projectName }, function (err, p) {
      if (err) {
        toolbelt.error("Unable to check for existing project %s", projectName);

        return callback(err);
      }

      if (p) {
        // This project already exists.
        toolbelt.debug("The project %s already exists.", projectName);

        return callback(null, true);
      }

      callback(null, false);
    });
  };

  var fetchRepositoryData = function (callback) {
    github.getRepository(toolbelt, repository.project, function (err, p) {
      if (err) {
        if (err.notFound) {
          toolbelt.error(
            "Unable to see GitHub repository %s as user %s.",
            repository.project, githubAccount.config.login);
          toolbelt.error(
            "Have you granted %s access rights to that repository?",
            githubAccount.config.login);
        } else {
          toolbelt.error("Unable to fetch GitHub project %s", repository.project);
        }

        return callback(err);
      }

      githubProject = p;
      callback(null);
    });
  };

  var generateKeyPair = function (callback) {
    keypair(repository.name + '-' + toolbelt.user.email, function (err, priv, pub) {
      if (err) return callback(err);

      privateKey = priv;
      publicKey = pub;
      callback(null);
    });
  };

  var createStriderProject = function (callback) {
    var providerConfig = {
      id: 'github',
      account: githubAccount.id,
      repo_id: githubProject.id,
      config: {
        auth: { type: 'https' },
        repo: githubProject.repo,
        owner: githubProject.owner.login,
        url: githubProject.clone_url
      }
    };

    var projectAttrs = {
      name: projectName,
      display_name: githubProject.name,
      display_url: githubProject.display_url,
      public: false,
      prefetch_config: false,
      creator: toolbelt.user._id,
      provider: providerConfig,
      branches: [
        {
          name: 'master',
          active: true,
          mirror_master: false,
          deploy_on_green: true,
          pubkey: publicKey,
          privkey: privateKey,
          plugins: [],
          runner: { id: 'simple-runner', config: { pty: false } }
        },
        {
          name: '*',
          mirror_master: true
        }
      ]
    };

    toolbelt.githubProviderPlugin.webapp.setupRepo(githubAccount.config, providerConfig, projectAttrs, function (err, config) {
      if (err) {
        toolbelt.error("Unable to initialize project with GitHub provider", err);
        return callback(err);
      }

      projectAttrs.provider.config = config;

      Project.create(projectAttrs, function (err, project) {
        if (err) {
          toolbelt.error("Unable to create Strider project %s", projectName, err);
          return callback(err);
        }

        callback(null);
      });
    });
  };

  var grantUsersAccess = function (callback) {
    User.update({ _id: toolbelt.user._id }, {
      $push: {
        projects: {
          name: projectName,
          display_name: githubProject.name,
          access_level: 2
        }
      }
    }, function (err, count) {
      if (err) {
        toolbelt.error("Failed to give %s admin access to the project %s.", toolbelt.user.email, projectName, err);
      }

      if (count < 1) {
        toolbelt.error("User %s not found to grant admin access to project %s.", toolbelt.user.email, projectName);
      }

      callback(null);
    });
  };

  checkForExistingProject(function (err, exists) {
    if (err || exists) callback(null);
    if (exists) return callback(null);

    async.series([
      fetchRepositoryData,
      generateKeyPair,
      createStriderProject,
      grantUsersAccess
    ], function (err) {
      if (err) {
        toolbelt.error("Failed to create build for project %s: %s", projectName, err.message);
      }

      callback(null);
    });
  });
};

var buildMakers = {
  github: createGitHubBuild
};
<|endoftext|>


<commit_before>var _ = require('lodash');
var chalk = require('chalk');
var fs = require('fs-extra');
var events = require('events');
var mutil = require('miaow-util');
var path = require('path');
var util = require('util');

function Cache(options) {
  this.options = options;
  this.modules = {};

  try {
    fs.emptyDirSync(options.output);
  } catch (e) {
    mutil.log(chalk.red.bold('清空输出目录失败,可能是内部有已修改但未保存的文件.'));
    throw e;
  }

  // 缓存目录
  this.directory = options.cache;
  if (this.directory) {
    fs.ensureDirSync(this.directory);
    this.cachedModules = fs.readJSONSync(path.join(this.directory, 'miaow.cache.json'), {throws: false}) || {};
  } else {
    this.cachedModules = {};
  }

  this.usedModules = {};

  // 取消事件监听的个数限制
  this.setMaxListeners(0);

  return this;
}

Cache.getInstance = function (options) {
  return new Cache(options);
};

util.inherits(Cache, events.EventEmitter);

Cache.prototype.add = function (module) {
  this.modules[module.srcPath] = module;

  // 监听修改事件
  var cache = this;
  module.on('change', function (token) {
    cache.emit('change', module.srcPath, token);
  });

  // 监听删除事件
  module.once('remove', this.remove.bind(this, module.srcPath));
};

Cache.prototype.get = function (srcPath) {
  return this.modules[srcPath];
};

Cache.prototype.remove = function (srcPath) {
  delete this.modules[srcPath];
};

/**
 * 获取已经缓存的内容
 *
 * @param {String} srcPath 源路径
 * @param {String} plugin 插件标识
 * @param {String} hash 用于判断是否需要使用缓存内容
 */
Cache.prototype.getCache = function (srcPath, plugin, hash) {
  var files = this.cachedModules[srcPath];

  if (files) {
    var file = _.find(files, {plugin: plugin, hash: hash});

    if (file) {
      var contents;
      try {
        contents = fs.readFileSync(path.resolve(this.directory, file.file));
        this.usedModules[srcPath] = this.usedModules[srcPath] || [];
        this.usedModules[srcPath].push(file);
      } catch(err) {}

      return contents;
    }
  }
};

Cache.prototype.addCache = function (srcPath, plugin, hash, contents) {
  if (!this.directory) {
    return;
  }

  var file = new Date().getTime().toString();

  try{
    fs.writeFileSync(path.resolve(this.directory, file), contents);
    this.usedModules[srcPath] = this.usedModules[srcPath] || [];
    this.usedModules[srcPath].push({
      plugin: plugin,
      hash: hash,
      file: file
    });
  } catch(err) {
    mutil.log('写入缓存目录失败');
  }
};

/**
 * 序列化缓存信息
 */
Cache.prototype.serialize = function () {
  var modules = {};

  _.forEach(this.modules, function (module, srcPath) {
    modules[srcPath] = _.pick(
      module,
      ['srcPath', 'destPath', 'destPathWithHash', 'dependList', 'packList', 'hash', 'url']
    );
  });

  // 写入编译结果
  fs.writeJSONSync(
    path.join(this.options.output, 'miaow.log.json'),
    {
      modules: modules
    });

  // 处理缓存文件
  if (!this.directory) {
    return;
  }
  // 清除没有使用到的文件
  var usedFiles = [];
  _.each(this.usedModules, function (module) {
    usedFiles = usedFiles.concat(_.map(module, 'file'));
  });

  var allFiles = fs.readdirSync(this.directory);
  var directory = this.directory;
  _.difference(allFiles, usedFiles).forEach(function (file) {
    fs.removeSync(path.join(directory, file));
  });

  // 写入记录
  fs.writeJSONSync(path.join(this.directory, 'miaow.cache.json'), this.usedModules);
};

module.exports = Cache;
<commit_msg>删除cache模块<commit_after><|endoftext|>


<commit_before>var LRU = require('lru-cache');

exports.install = module.exports.install = function(mongoose, options) {
	var cache = LRU(options);

	var log = options.debug ? console.log : function() {};

	var orig = {
		execFind: mongoose.Query.prototype.execFind,
		exec: mongoose.Query.prototype.exec
	};

	mongoose.Query.prototype.cache = function() {
		this.__cached = true;
		return this;
	}

	var exec = function(caller, args) {
		if(!this.__cached) {
			return orig[caller].apply(this, args);
		}
		var key = genKey(this);
		var obj = cache.get(key);
		if(obj) {
			log('cache hit: ', key);
			for(var i = 0; i < args.length; i++) {
				if(typeof args[i] === 'function') {
					args[i](null, obj);
					break;
				}
			}
			return this;
		}

		for(var i = 0; i < args.length; i++) {
			if(typeof args[i] !== 'function')
				continue;
			args[i] = (function(err, obj) {
				if(!err) {
					log('save to cache: ', key);
					cache.set(key, obj);
				}
				this.apply(this, arguments);
			}).bind(args[i]);
		}
		return orig[caller].apply(this, args);
	}

	function genKey(query) {
		var q = {};
		for(var k in query) {
			q[k] = query[k];
		}
		q.model = q.model.modelName;
		return JSON.stringify(q);
	}

	mongoose.Query.prototype.execFind = function(arg1, arg2) { return exec.call(this, 'execFind', arguments) };
	mongoose.Query.prototype.exec = function(arg1, arg2) { return exec.call(this, 'exec', arguments) };
	return mongoose;
}
<commit_msg>fix #2<commit_after>var LRU = require('lru-cache');

exports.install = module.exports.install = function(mongoose, options) {
	var cache = LRU(options);

	var log = options.debug ? console.log : function() {};

	var orig = {
		execFind: mongoose.Query.prototype.execFind,
		exec: mongoose.Query.prototype.exec
	};

	mongoose.Query.prototype.cache = function() {
		this.__cached = true;
		return this;
	}

	var exec = function(caller, args) {
		if(!this.__cached) {
			return orig[caller].apply(this, args);
		}
		var key = genKey(this);
		var obj = cache.get(key);
		if(obj) {
			log('cache hit: ', key);
			for(var i = 0; i < args.length; i++) {
				if(typeof args[i] === 'function') {
					args[i](null, obj);
					break;
				}
			}
			return this;
		}

		for(var i = 0; i < args.length; i++) {
			if(typeof args[i] !== 'function')
				continue;
			args[i] = (function(err, obj) {
				if(!err) {
					log('save to cache: ', key);
					cache.set(key, obj);
				}
				this.apply(this, arguments);
			}).bind(args[i]);
		}
		return orig[caller].apply(this, args);
	}

	function genKey(query) {
		return JSON.stringify(query._conditions);
	}

	mongoose.Query.prototype.execFind = function(arg1, arg2) { return exec.call(this, 'execFind', arguments) };
	mongoose.Query.prototype.exec = function(arg1, arg2) { return exec.call(this, 'exec', arguments) };
	return mongoose;
}
<|endoftext|>


<commit_before>var path = require("path");
var stackTrace = require("stack-trace");

module.exports = {
    _debug: false,
    set (flag) {
        this._debug = flag;
    },
    isDebugMode () {
        return this._debug;
    },
    log (msg) {
        if (this._debug) {
            var stack = stackTrace.get()[1];
            var file = path.basename(stack.getFileName());
            var method = stack.getFunctionName();
            console.log("\x1b[1m\x1b[34m[" + file + ":" + method + "]: \x1b[0m" + msg);
        }
    },
    error (msg) {
        var stack = stackTrace.get()[1];
        var file = path.basename(stack.getFileName());
        var method = stack.getFunctionName();
        console.error("\x1b[1m\x1b[91m[Error: " + file + ":" + method + "]: \x1b[0m" + msg);
    }
}
<commit_msg>Add debug info<commit_after>var path = require("path");
var stackTrace = require("stack-trace");

module.exports = {
    _debug: false,
    set (flag) {
        this._debug = flag;
    },
    isDebugMode () {
        return this._debug;
    },
    log (msg) {
        if (this._debug) {
            var stack = stackTrace.get()[1];
            var file = path.basename(stack.getFileName());
            var method = stack.getFunctionName();
            console.log("\x1b[1m\x1b[34m[" + file + ":" + method + "]: \x1b[0m" + msg);
        }
    },
    error (msg) {
        var stack = stackTrace.get()[1];
        var file = path.basename(stack.getFileName());
        var method = stack.getFunctionName();
        console.error("\x1b[1m\x1b[91m[Error: " + file + ":" + method + "]: \x1b[0m" + msg);
    },
    info (msg) {
        var stack = stackTrace.get()[1];
        var file = path.basename(stack.getFileName());
        var method = stack.getFunctionName();
        console.error("\x1b[1m\x1b[36m[Info: " + file + ":" + method + "]: \x1b[0m" + msg);
    }
}
<|endoftext|>