<commit_before>/*
 * Copyright (C) 2012 Vanderbilt University, All rights reserved.
 *
 * Author: Miklos Maroti
 */

define([ "util/assert", "core/core", "core/tasync" ], function(ASSERT, Core, TASYNC) {
	"use strict";

	// ----------------- CoreType -----------------

	var CoreType = function(oldcore) {
		// copy all operations
		var core = {};
		for ( var key in oldcore) {
			core[key] = oldcore[key];
		}

		// ----- validity

		function __test(text, cond) {
			if (!cond) {
				throw new Error(text);
			}
		}

		function isValidNode(node) {
			try {
				__test("core", oldcore.isValidNode(node));
				__test("base", typeof node.base === "object");
				return true;
			} catch (error) {
				console.log("Wrong node", error.stack);
				return false;
			}
		}

        function isFalseNode(node) {
            //TODO this hack should be removed, but now it seems just fine :)
            if(typeof oldcore.getPointerPath(node,"base") === "undefined"){
                return true;
            }
            return false;
        }

		core.isValidNode = isValidNode;

		// ----- navigation

		core.getBase = function(node) {
			ASSERT(isValidNode(node));

			// TODO: check if base has moved
			return node.base;
		};

		core.loadRoot = function(hash) {
			return TASYNC.call(__loadRoot2, oldcore.loadRoot(hash));
		};

		function __loadRoot2(node) {
            ASSERT(typeof node.base === "undefined" || node.base === null); //kecso - TODO it should be undefined, but maybe because of the cache it can be null

			node.base = null;
			return node;
		}

        core.loadChild = function(node,relid){
            var child = TASYNC.call(__loadBase,oldcore.loadChild(node,relid));
            var base = core.getBase(node);
            var basechild = null;
            if(base && oldcore.getChildrenRelids(base).indexOf(relid) !== -1){
                basechild = TASYNC.call(__loadBase,oldcore.loadChild(base,relid));
            }
            return TASYNC.call(function(ch,bch,n,r){
                var done = null;
                if(ch === null){
                    if(bch !== null){
                        ch = core.createNode({base:bch,parent:n,relid:r});
                        done = core.persist(core.getRoot(n));
                    }
                }
                return TASYNC.call(function(child){return child;},ch,done);
            },child,basechild,node,relid);
        };

        core.loadByPath = function(node,path){
            ASSERT(isValidNode(node));
            ASSERT(path === "" || path.charAt(0) === "/");
            path = path.split("/");
            return loadDescendantByPath(node, path, 1);
        };
        var loadDescendantByPath = function(node,pathArray,index){
            if (node === null || index === pathArray.length) {
                return node;
            }

            var child = core.loadChild(node, pathArray[index]);
            return TASYNC.call(loadDescendantByPath, child, pathArray, index + 1);
        };

        //TODO the pointer loading is totally based upon the loadByPath...
        core.loadPointer = function(node,name){
            var pointerPath = core.getPointerPath(node,name);
            return TASYNC.call(core.loadByPath,core.getRoot(node),pointerPath);
        };

		function __loadBase(node) {
			ASSERT(node === null || typeof node.base === "undefined" || typeof node.base === "object");

			if (typeof node.base === "undefined") {
                if(!core.isEmpty(node) && isFalseNode(node)){
                    //console.log('!!! ISFALSENODE PLEASE CHECK PROJECT STRUCTURE !!!: ' + core.getPath(node));
                    var root = core.getRoot(node);
                    core.deleteNode(node);
                    return TASYNC.call(function(){return null;},core.persist(root));
                    //return null;
                } else {
                    return TASYNC.call(__loadBase2, node, oldcore.loadPointer(node, "base"));
                }
			} else if(node === null){
                return node; //TODO we have to check if it can be allowed or we have to make the nullpointer otherwise
            } else {
                var oldpath = core.getPath(node.base);
                var newpath = core.getPointerPath(node,"base");
                if(oldpath !== newpath){
                    delete node.base;
                    return __loadBase(node);
                } else {
                    return node;
                }
			}
		}

		function __loadBase2(node, target) {
            if(typeof node.base !== null && typeof node.base === 'object' && (oldcore.getPath(node.base) === oldcore.getPath(target))){
                //TODO somehow the object already loaded properly and we do no know about it!!!
                return node;
            } else {
                ASSERT(typeof node.base === "undefined" || node.base === null); //kecso

                if(target === null){
                    node.base = null;
                    return node;
                } else {
                    return TASYNC.call(function(n,b){n.base = b; return n;},node,__loadBase(target));
                }
            }
		}

        core.getChildrenRelids = function(node){
            var inheritRelIds = node.base === null ? [] : core.getChildrenRelids(core.getBase(node));
            var ownRelIds = oldcore.getChildrenRelids(node);
            for(var i=0;i<inheritRelIds.length;i++){
                if(ownRelIds.indexOf(inheritRelIds[i]) === -1){
                    ownRelIds.push(inheritRelIds[i]);
                }
            }
            return ownRelIds;
        };

        core.loadChildren = function(node) {
            ASSERT(isValidNode(node));
            var relids = core.getChildrenRelids(node);
            relids = relids.sort(); //TODO this should be temporary
            var children = [];
            for(var i = 0; i< relids.length; i++)
                children[i] = core.loadChild(node,relids[i]);
            return TASYNC.call(function(n){
                var newn = [];
                for(var i=0; i<n.length;i++){
                    if(n[i] !== null){
                        newn.push(n[i]);
                    }
                }
                return newn;
            },TASYNC.lift(children));
        };

        //TODO now the collection paths doesn't take any kind of inheritance into account...
        core.loadCollection = function(node, name) {
            var root =  core.getRoot(node);
            var paths = core.getCollectionPaths(node,name);

            var nodes = [];
            for(var i = 0; i < paths.length; i++) {
                nodes[i] = core.loadByPath(root, paths[i]);
            }

            return TASYNC.lift(nodes);
        };

		// ----- creation

		core.createNode = function(parameters) {
			parameters = parameters || {};
			var base = parameters.base || null,
				parent = parameters.parent;

			ASSERT(!parent || isValidNode(parent));
			ASSERT(!base || isValidNode(base));
            ASSERT(!base || core.getPath(base) !== core.getPath(parent));

			var node = oldcore.createNode(parameters);
            node.base = base;
            oldcore.setPointer(node,"base",base);

			return node;
		};

		// ----- properties

		core.getAttributeNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getAttributeNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};
        core.getOwnAttributeNames = function(node){
            return oldcore.getAttributeNames(node);
        };

		core.getRegistryNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getRegistryNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};
        core.getOwnRegistryNames = function(node){
            return oldcore.getRegistryNames(node);
        };

		core.getAttribute = function(node, name) {
			ASSERT(isValidNode(node));
            var value;
			do {
				value = oldcore.getAttribute(node, name);
				node = node.base;
			} while (typeof value === "undefined" && node !== null);

			return value;
		};
        core.getOwnAttribute = function(node,name) {
            return oldcore.getAttribute(node,name);
        };

		core.getRegistry = function(node, name) {
			ASSERT(isValidNode(node));
            var value;
			do {
				value = oldcore.getRegistry(node, name);
				node = node.base;
			} while (typeof value === "undefined" && node !== null);

			return value;
		};
        core.getOwnRegistry = function(node,name) {
            return oldcore.getRegistry(node,name);
        };

		// ----- pointers

		core.getPointerNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getPointerNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};
        core.getOwnPointerNames = function(node){
            ASSERT(isValidNode(node));
            return oldcore.getPointerNames(node);
        };

        core.getPointerPath = function (node, name) {
            ASSERT(isValidNode(node) && typeof name === "string");

            var ownPointerPath = oldcore.getPointerPath(node,name);
            if(ownPointerPath !== undefined){
                return ownPointerPath;
            }
            var source = "",
                target,
                coretree = core.getCoreTree(),
                parentOfBase,
                baseOfParent,
                basePath,
                hasNullTarget = false,
                getProperty = function(node,name){
                    var property;
                    while(property === undefined && node !== null){
                        property = coretree.getProperty(node,name);
                        node = core.getBase(node);
                    }
                    return property;
                },
                getSimpleBasePath = function(node){
                    var path = oldcore.getPointerPath(node,name);
                    if(path === undefined){
                        if(node.base !== null && node.base !== undefined){
                            return getSimpleBasePath(node.base);
                        } else {
                            return undefined;
                        }
                    } else {
                        return path;
                    }
                },
                getParentOfBasePath = function(node){
                    if(node.base){
                        var parent = core.getParent(node.base);
                        if(parent){
                            return core.getPath(parent);
                        } else {
                            return undefined;
                        }
                    } else {
                        return undefined;
                    }
                },
                getBaseOfParentPath = function(node){
                    var parent = core.getParent(node);
                    if(parent){
                        if(parent.base){
                            return core.getPath(parent.base);
                        } else {
                            return undefined;
                        }
                    } else {
                        return undefined;
                    }
                },
                getTargetRelPath = function(node,relSource,name){
                    var ovr = core.getChild(node,'ovr');
                    var source = core.getChild(ovr,relSource);
                    return getProperty(source,name);
                };

            basePath = node.base ? getSimpleBasePath(node.base) : undefined;

            while(node){
                target = getTargetRelPath(node,source,name);
                if( target !== undefined){
                    if(target.indexOf('_nullptr') !== -1){
                        hasNullTarget = true;
                        target = undefined;
                    } else {
                        break;
                    }
                }

                source = "/" + core.getRelid(node) + source;
                if(getParentOfBasePath(node) === getBaseOfParentPath(node)){
                    node = core.getParent(node);
                } else {
                    node = null;
                }
            }

            if (target !== undefined) {
                ASSERT(node);
                target = coretree.joinPaths(oldcore.getPath(node), target);
            }
            return target || basePath || (hasNullTarget ? null : undefined);
        };
        core.getOwnPointerPath = function(node,name){
            oldcore.getPointerPath(node,name);
        };

        core.setBase = function(node,base){
            ASSERT(isValidNode(node) && (base === undefined || base === null || isValidNode(base)));
            ASSERT(!base || core.getPath(core.getParent(node)) !== core.getPath(base));
            ASSERT(!base || core.getPath(node) !== core.getPath(base));
            if(!!base){
                oldcore.setPointer(node, "base", base);
                //TODO maybe this is not the best way, needs to be double checked
                node.base = base;
            } else {
                oldcore.setPointer(node,'base',null);
                node.base = null;
            }
        };

        core.getChild = function(node,relid){
            ASSERT(isValidNode(node) && (typeof node.base === 'undefined' || typeof node.base === 'object'));
            var child = oldcore.getChild(node,relid);
            if(node.base !== null && node.base !== undefined){
                if(child.base === null || child.base === undefined){
                    child.base = core.getChild(node.base,relid);
                }
            } else {
                child.base = null;
            }
            return child;
        };
        core.moveNode = function(node,parent){
            var base = node.base;
            ASSERT(!base || core.getPath(base) !== core.getPath(parent));

            var moved = oldcore.moveNode(node,parent);
            moved.base = base;
            return moved;
        };
        core.copyNode = function(node,parent){
            var base = node.base;
            ASSERT(!base || core.getPath(base) !== core.getPath(parent));

            var newnode = oldcore.copyNode(node,parent);
            newnode.base = base;
            return newnode;
        };

        core.getSingleNodeHash = function(node){
            //TODO this function only needed while the inheritance is not in its final form!!!
            //bb377d14fd57cbe2b0a2ad297a7a303b7a5fccf3
            ASSERT(isValidNode(node));
            function xorHashes (a, b) {
                var outHash = "";
                if(a.length === b.length){
                    for(var i=0;i< a.length;i++){
                        outHash += (parseInt(a.charAt(i),16) ^ parseInt(b.charAt(i),16)).toString(16);
                    }
                }
                return outHash;
            }
            var hash = "0000000000000000000000000000000000000000";
            while( node ){
                hash = xorHashes(hash,oldcore.getSingleNodeHash(node));
                node = core.getBase(node);
            }
            return hash;
        };

        core.getChildrenPaths = function(node){
            var path = core.getPath(node);

            var relids = core.getChildrenRelids(node);
            for ( var i = 0; i < relids.length; ++i) {
                relids[i] = path + "/" + relids[i];
            }

            return relids;
        };
        // -------- kecso

		return core;
	};

	return CoreType;
});
<commit_msg>inheritance bugfix additionally the deletion of an inherited child is now prohibited<commit_after>/*
 * Copyright (C) 2012 Vanderbilt University, All rights reserved.
 *
 * Author: Miklos Maroti
 */

define([ "util/assert", "core/core", "core/tasync" ], function(ASSERT, Core, TASYNC) {
	"use strict";

	// ----------------- CoreType -----------------

	var CoreType = function(oldcore) {
		// copy all operations
		var core = {};
		for ( var key in oldcore) {
			core[key] = oldcore[key];
		}

		// ----- validity

		function __test(text, cond) {
			if (!cond) {
				throw new Error(text);
			}
		}

		function isValidNode(node) {
			try {
				__test("core", oldcore.isValidNode(node));
				__test("base", typeof node.base === "object");
				return true;
			} catch (error) {
				console.log("Wrong node", error.stack);
				return false;
			}
		}

        function isFalseNode(node) {
            //TODO this hack should be removed, but now it seems just fine :)
            if(typeof oldcore.getPointerPath(node,"base") === "undefined"){
                return true;
            }
            return false;
        }

		core.isValidNode = isValidNode;

		// ----- navigation

		core.getBase = function(node) {
			ASSERT(isValidNode(node));

			// TODO: check if base has moved
			return node.base;
		};

		core.loadRoot = function(hash) {
			return TASYNC.call(__loadRoot2, oldcore.loadRoot(hash));
		};

		function __loadRoot2(node) {
            ASSERT(typeof node.base === "undefined" || node.base === null); //kecso - TODO it should be undefined, but maybe because of the cache it can be null

			node.base = null;
			return node;
		}

        core.loadChild = function(node,relid){
            var child = TASYNC.call(__loadBase,oldcore.loadChild(node,relid));
            var base = core.getBase(node);
            var basechild = null;
            if(base && oldcore.getChildrenRelids(base).indexOf(relid) !== -1){
                basechild = TASYNC.call(__loadBase,oldcore.loadChild(base,relid));
            }
            return TASYNC.call(function(ch,bch,n,r){
                var done = null;
                if(ch === null){
                    if(bch !== null){
                        ch = core.createNode({base:bch,parent:n,relid:r});
                        done = core.persist(core.getRoot(n));
                    }
                }
                return TASYNC.call(function(child){return child;},ch,done);
            },child,basechild,node,relid);
        };

        core.loadByPath = function(node,path){
            ASSERT(isValidNode(node));
            ASSERT(path === "" || path.charAt(0) === "/");
            path = path.split("/");
            return loadDescendantByPath(node, path, 1);
        };
        var loadDescendantByPath = function(node,pathArray,index){
            if (node === null || index === pathArray.length) {
                return node;
            }

            var child = core.loadChild(node, pathArray[index]);
            return TASYNC.call(loadDescendantByPath, child, pathArray, index + 1);
        };

        //TODO the pointer loading is totally based upon the loadByPath...
        core.loadPointer = function(node,name){
            var pointerPath = core.getPointerPath(node,name);
            return TASYNC.call(core.loadByPath,core.getRoot(node),pointerPath);
        };

		function __loadBase(node) {
			ASSERT(node === null || typeof node.base === "undefined" || typeof node.base === "object");

			if (typeof node.base === "undefined") {
                if(core.isEmpty(node)){
                    //empty nodes do not have a base
                    return null;
                } else if(/*!core.isEmpty(node) && */isFalseNode(node)){
                    //console.log('!!! ISFALSENODE PLEASE CHECK PROJECT STRUCTURE !!!: ' + core.getPath(node));
                    var root = core.getRoot(node);
                    oldcore.deleteNode(node); //when we want to delete here we really want to delete it!!! :)
                    return TASYNC.call(function(){return null;},core.persist(root));
                    //return null;
                } else {
                    //console.log('kecso - not FALSE node but without loaded BASE' + core.getPath(node));
                    return TASYNC.call(__loadBase2, node, oldcore.loadPointer(node, "base"));
                }
			} else if(node === null){
                return node; //TODO we have to check if it can be allowed or we have to make the nullpointer otherwise
            } else {
                //console.log('kecso - not FALSE node with loaded BASE' + core.getPath(node));
                var oldpath = core.getPath(node.base);
                var newpath = core.getPointerPath(node,"base");
                if(oldpath !== newpath){
                    delete node.base;
                    return __loadBase(node);
                } else {
                    return node;
                }
			}
		}

		function __loadBase2(node, target) {
            if(typeof node.base !== null && typeof node.base === 'object' && (oldcore.getPath(node.base) === oldcore.getPath(target))){
                //TODO somehow the object already loaded properly and we do no know about it!!!
                return node;
            } else {
                ASSERT(typeof node.base === "undefined" || node.base === null); //kecso

                if(target === null){
                    node.base = null;
                    return node;
                } else {
                    return TASYNC.call(function(n,b){n.base = b; return n;},node,__loadBase(target));
                }
            }
		}

        core.getChildrenRelids = function(node){
            var inheritRelIds = node.base === null ? [] : core.getChildrenRelids(core.getBase(node));
            var ownRelIds = oldcore.getChildrenRelids(node);
            for(var i=0;i<inheritRelIds.length;i++){
                if(ownRelIds.indexOf(inheritRelIds[i]) === -1){
                    ownRelIds.push(inheritRelIds[i]);
                }
            }
            return ownRelIds;
        };

        core.loadChildren = function(node) {
            ASSERT(isValidNode(node));
            var relids = core.getChildrenRelids(node);
            relids = relids.sort(); //TODO this should be temporary
            var children = [];
            for(var i = 0; i< relids.length; i++)
                children[i] = core.loadChild(node,relids[i]);
            return TASYNC.call(function(n){
                var newn = [];
                for(var i=0; i<n.length;i++){
                    if(n[i] !== null){
                        newn.push(n[i]);
                    }
                }
                return newn;
            },TASYNC.lift(children));
        };

        //TODO now the collection paths doesn't take any kind of inheritance into account...
        core.loadCollection = function(node, name) {
            var root =  core.getRoot(node);
            var paths = core.getCollectionPaths(node,name);

            var nodes = [];
            for(var i = 0; i < paths.length; i++) {
                nodes[i] = core.loadByPath(root, paths[i]);
            }

            return TASYNC.lift(nodes);
        };

		// ----- creation

		core.createNode = function(parameters) {
			parameters = parameters || {};
			var base = parameters.base || null,
				parent = parameters.parent;

			ASSERT(!parent || isValidNode(parent));
			ASSERT(!base || isValidNode(base));
            ASSERT(!base || core.getPath(base) !== core.getPath(parent));

			var node = oldcore.createNode(parameters);
            node.base = base;
            oldcore.setPointer(node,"base",base);

			return node;
		};

		// ----- properties

		core.getAttributeNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getAttributeNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};
        core.getOwnAttributeNames = function(node){
            return oldcore.getAttributeNames(node);
        };

		core.getRegistryNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getRegistryNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};
        core.getOwnRegistryNames = function(node){
            return oldcore.getRegistryNames(node);
        };

		core.getAttribute = function(node, name) {
			ASSERT(isValidNode(node));
            var value;
			do {
				value = oldcore.getAttribute(node, name);
				node = node.base;
			} while (typeof value === "undefined" && node !== null);

			return value;
		};
        core.getOwnAttribute = function(node,name) {
            return oldcore.getAttribute(node,name);
        };

		core.getRegistry = function(node, name) {
			ASSERT(isValidNode(node));
            var value;
			do {
				value = oldcore.getRegistry(node, name);
				node = node.base;
			} while (typeof value === "undefined" && node !== null);

			return value;
		};
        core.getOwnRegistry = function(node,name) {
            return oldcore.getRegistry(node,name);
        };

		// ----- pointers

		core.getPointerNames = function(node) {
			ASSERT(isValidNode(node));

			var merged = {};
			do {
				var names = oldcore.getPointerNames(node);
				for ( var i = 0; i < names.length; ++i) {
					if (!(names[i] in merged)) {
						merged[names[i]] = true;
					}
				}

				node = node.base;
			} while (node);

			return Object.keys(merged);
		};
        core.getOwnPointerNames = function(node){
            ASSERT(isValidNode(node));
            return oldcore.getPointerNames(node);
        };

        core.getPointerPath = function (node, name) {
            ASSERT(isValidNode(node) && typeof name === "string");

            var ownPointerPath = oldcore.getPointerPath(node,name);
            if(ownPointerPath !== undefined){
                return ownPointerPath;
            }
            var source = "",
                target,
                coretree = core.getCoreTree(),
                parentOfBase,
                baseOfParent,
                basePath,
                hasNullTarget = false,
                getProperty = function(node,name){
                    var property;
                    while(property === undefined && node !== null){
                        property = coretree.getProperty(node,name);
                        node = core.getBase(node);
                    }
                    return property;
                },
                getSimpleBasePath = function(node){
                    var path = oldcore.getPointerPath(node,name);
                    if(path === undefined){
                        if(node.base !== null && node.base !== undefined){
                            return getSimpleBasePath(node.base);
                        } else {
                            return undefined;
                        }
                    } else {
                        return path;
                    }
                },
                getParentOfBasePath = function(node){
                    if(node.base){
                        var parent = core.getParent(node.base);
                        if(parent){
                            return core.getPath(parent);
                        } else {
                            return undefined;
                        }
                    } else {
                        return undefined;
                    }
                },
                getBaseOfParentPath = function(node){
                    var parent = core.getParent(node);
                    if(parent){
                        if(parent.base){
                            return core.getPath(parent.base);
                        } else {
                            return undefined;
                        }
                    } else {
                        return undefined;
                    }
                },
                getTargetRelPath = function(node,relSource,name){
                    var ovr = core.getChild(node,'ovr');
                    var source = core.getChild(ovr,relSource);
                    return getProperty(source,name);
                };

            basePath = node.base ? getSimpleBasePath(node.base) : undefined;

            while(node){
                target = getTargetRelPath(node,source,name);
                if( target !== undefined){
                    if(target.indexOf('_nullptr') !== -1){
                        hasNullTarget = true;
                        target = undefined;
                    } else {
                        break;
                    }
                }

                source = "/" + core.getRelid(node) + source;
                if(getParentOfBasePath(node) === getBaseOfParentPath(node)){
                    node = core.getParent(node);
                } else {
                    node = null;
                }
            }

            if (target !== undefined) {
                ASSERT(node);
                target = coretree.joinPaths(oldcore.getPath(node), target);
            }
            return target || basePath || (hasNullTarget ? null : undefined);
        };
        core.getOwnPointerPath = function(node,name){
            oldcore.getPointerPath(node,name);
        };

        core.setBase = function(node,base){
            ASSERT(isValidNode(node) && (base === undefined || base === null || isValidNode(base)));
            ASSERT(!base || core.getPath(core.getParent(node)) !== core.getPath(base));
            ASSERT(!base || core.getPath(node) !== core.getPath(base));
            if(!!base){
                oldcore.setPointer(node, "base", base);
                //TODO maybe this is not the best way, needs to be double checked
                node.base = base;
            } else {
                oldcore.setPointer(node,'base',null);
                node.base = null;
            }
        };

        core.getChild = function(node,relid){
            ASSERT(isValidNode(node) && (typeof node.base === 'undefined' || typeof node.base === 'object'));
            var child = oldcore.getChild(node,relid);
            if(node.base !== null && node.base !== undefined){
                if(child.base === null || child.base === undefined){
                    child.base = core.getChild(node.base,relid);
                }
            } else {
                child.base = null;
            }
            return child;
        };
        core.moveNode = function(node,parent){
            var base = node.base;
            ASSERT(!base || core.getPath(base) !== core.getPath(parent));

            var moved = oldcore.moveNode(node,parent);
            moved.base = base;
            return moved;
        };
        core.copyNode = function(node,parent){
            var base = node.base;
            ASSERT(!base || core.getPath(base) !== core.getPath(parent));

            var newnode = oldcore.copyNode(node,parent);
            newnode.base = base;
            return newnode;
        };

        core.getSingleNodeHash = function(node){
            //TODO this function only needed while the inheritance is not in its final form!!!
            //bb377d14fd57cbe2b0a2ad297a7a303b7a5fccf3
            ASSERT(isValidNode(node));
            function xorHashes (a, b) {
                var outHash = "";
                if(a.length === b.length){
                    for(var i=0;i< a.length;i++){
                        outHash += (parseInt(a.charAt(i),16) ^ parseInt(b.charAt(i),16)).toString(16);
                    }
                }
                return outHash;
            }
            var hash = "0000000000000000000000000000000000000000";
            while( node ){
                hash = xorHashes(hash,oldcore.getSingleNodeHash(node));
                node = core.getBase(node);
            }
            return hash;
        };

        core.getChildrenPaths = function(node){
            var path = core.getPath(node);

            var relids = core.getChildrenRelids(node);
            for ( var i = 0; i < relids.length; ++i) {
                relids[i] = path + "/" + relids[i];
            }

            return relids;
        };

        core.deleteNode = function(node){
            //currently we only check if the node is inherited from its parents children
            var pathOne = core.getPath(core.getBase(core.getParent(node))),
                pathTwo = core.getPath(core.getParent(core.getBase(node)));
            if(pathOne !== pathTwo){
                oldcore.deleteNode(node);
            } else {
                console.log('kecso - do not delete this node');
            }
        };
        // -------- kecso

		return core;
	};

	return CoreType;
});
<|endoftext|>


<commit_before>'use strict';

const Confidence = require('confidence');
const Dotenv = require('dotenv');

Dotenv.config({ silent: true });

const criteria = {
    env: process.env.NODE_ENV
};

const config = {
    $meta: 'This file configures the plot device.',
    projectName: 'Frame',
    port: {
        web: {
            $filter: 'env',
            test: 9090,
            production: process.env.PORT,
            $default: 9000
        }
    },
    authAttempts: {
        forIp: 50,
        forIpAndUser: 7
    },
    hapiMongoModels: {
        mongodb: {
            connection: {
                uri: {
                    $filter: 'env',
                    production: process.env.MONGODB_URI,
                    $default: process.env.MONGODB_URI || 'mongodb://localhost:27017/'
                },
                db: {
                    $filter: 'env',
                    production: process.env.MONGODB_DB_NAME,
                    test: 'frame-test',
                    $default: 'frame'
                }
            }
        },
        autoIndex: true
    },
    nodemailer: {
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        auth: {
            user: 'jedireza@gmail.com',
            pass: process.env.SMTP_PASSWORD
        }
    },
    system: {
        fromAddress: {
            name: 'Frame',
            address: 'jedireza@gmail.com'
        },
        toAddress: {
            name: 'Frame',
            address: 'jedireza@gmail.com'
        }
    }
};

const store = new Confidence.Store(config);

exports.get = function (key) {

    return store.get(key, criteria);
};

exports.meta = function (key) {

    return store.meta(key, criteria);
};
<commit_msg>not sure why auto indexing is failing on heroku<commit_after>'use strict';

const Confidence = require('confidence');
const Dotenv = require('dotenv');

Dotenv.config({ silent: true });

const criteria = {
    env: process.env.NODE_ENV
};

const config = {
    $meta: 'This file configures the plot device.',
    projectName: 'Frame',
    port: {
        web: {
            $filter: 'env',
            test: 9090,
            production: process.env.PORT,
            $default: 9000
        }
    },
    authAttempts: {
        forIp: 50,
        forIpAndUser: 7
    },
    hapiMongoModels: {
        mongodb: {
            connection: {
                uri: {
                    $filter: 'env',
                    production: process.env.MONGODB_URI,
                    $default: process.env.MONGODB_URI || 'mongodb://localhost:27017/'
                },
                db: {
                    $filter: 'env',
                    production: process.env.MONGODB_DB_NAME,
                    test: 'frame-test',
                    $default: 'frame'
                }
            }
        },
        autoIndex: false
    },
    nodemailer: {
        host: 'smtp.gmail.com',
        port: 465,
        secure: true,
        auth: {
            user: 'jedireza@gmail.com',
            pass: process.env.SMTP_PASSWORD
        }
    },
    system: {
        fromAddress: {
            name: 'Frame',
            address: 'jedireza@gmail.com'
        },
        toAddress: {
            name: 'Frame',
            address: 'jedireza@gmail.com'
        }
    }
};

const store = new Confidence.Store(config);

exports.get = function (key) {

    return store.get(key, criteria);
};

exports.meta = function (key) {

    return store.meta(key, criteria);
};
<|endoftext|>


<commit_before>

if (typeof (Omeka) == 'undefined') {
    Omeka = new Object();
}

if (!Omeka.Timeline) {
    Omeka.Timeline = new Array();
}

if (!Omeka.Timeline.behavior) {
    Omeka.Timeline.behavior = function(id) {
    }
}

if (!Omeka.Timeline.history) {
    Omeka.Timeline.history = new Array();
}

Omeka.Timeline.createTimeline = function(config) {
	// we must override this method to provide for our Javascript behaviors on
	// events
	Timeline.DefaultEventSource.prototype._resolveRelativeURL = function(url, base) {
		if (url == null || url == '') {
			return url;
		} else if (url.indexOf('://') > 0 || url.indexOf('javascript:') == 0) {
			return url;
		} else if (url.substr(0, 1) == '/') {
			return base.substr(0, base.indexOf('/', base.indexOf('://') + 3))
					+ url;
		} else {
			return base + url;
		}
	};
	if (!config.eventSource) {
		config.eventSource = new Timeline.DefaultEventSource();
	}
	if (!config.bandInfos) {
		config.bandInfos = [
				Timeline.createBandInfo( {
					width : "70%",
					eventSource : config.eventSource,
					intervalUnit : Timeline.DateTime.MONTH,
					intervalPixels : 100
				}),
				Timeline.createBandInfo( {
					width : "30%",
					intervalUnit : Timeline.DateTime.YEAR,
					intervalPixels : 200,
					eventSource : config.secondSource ? config.secondSource
							: new Timeline.DefaultEventSource(),
					overview : true
				}) ];
		config.bandInfos[1].syncWith = 0;
		config.bandInfos[1].highlight = true;
	}
	Omeka.Timeline[Omeka.Timeline.length] = Timeline.create(config.timelinediv,
			config.bandInfos);
	config.eventSource.loadJSON( {
		"events" : config.events
	}, document.location.href);
	Omeka.Timeline[Omeka.Timeline.length - 1].setCenter = function(s) {
		this._bands.each(function(i) {
			i.setCenterVisibleDate(SimileAjax.DateTime
					.parseGregorianDateTime(s))
		});
	}
	console.log("Emitting Omeka.Timeline.timelinecreated");
	jq_neatlineexhibit('body').trigger("Omeka.Timeline.timelinecreated",[config.timelinediv]);

}

var resizeTimerID = null;

Omeka.Timeline.onResize = function() {
	if (resizeTimerID == null) {
		resizeTimerID = window.setTimeout(function() {
			resizeTimerID = null;
			Omeka.Timeline.timeline.layout();
		}, 500);
	}
}<commit_msg><commit_after>

if (typeof (Omeka) == 'undefined') {
    Omeka = new Object();
}

if (!Omeka.Timeline) {
    Omeka.Timeline = new Array();
}

if (!Omeka.Timeline.behavior) {
    Omeka.Timeline.behavior = function(id) {
    }
}

if (!Omeka.Timeline.history) {
    Omeka.Timeline.history = new Array();
}

Omeka.Timeline.createTimeline = function(config) {
	// we must override this method to provide for our Javascript behaviors on
	// events
	Timeline.DefaultEventSource.prototype._resolveRelativeURL = function(url, base) {
		if (url == null || url == '') {
			return url;
		} else if (url.indexOf('://') > 0 || url.indexOf('javascript:') == 0) {
			return url;
		} else if (url.substr(0, 1) == '/') {
			return base.substr(0, base.indexOf('/', base.indexOf('://') + 3))
					+ url;
		} else {
			return base + url;
		}
	};
	if (!config.eventSource) {
		config.eventSource = new Timeline.DefaultEventSource();
	}
	if (!config.bandInfos) {
		config.bandInfos = [
				Timeline.createBandInfo( {
					width : "70%",
					eventSource : config.eventSource,
					intervalUnit : Timeline.DateTime.MONTH,
					intervalPixels : 100
				}),
				Timeline.createBandInfo( {
					width : "30%",
					intervalUnit : Timeline.DateTime.YEAR,
					intervalPixels : 200,
					eventSource : config.secondSource ? config.secondSource
							: new Timeline.DefaultEventSource(),
					overview : true
				}) ];
		config.bandInfos[1].syncWith = 0;
		config.bandInfos[1].highlight = true;
	}
	Omeka.Timeline[Omeka.Timeline.length] = Timeline.create(config.timelinediv,
			config.bandInfos);
	config.eventSource.loadJSON( {
		"events" : config.events
	}, document.location.href);
	Omeka.Timeline[Omeka.Timeline.length - 1].setCenter = function(s) {
		this._bands.each(function(i) {
			i.setCenterVisibleDate(SimileAjax.DateTime
					.parseGregorianDateTime(s))
		});
	}
	console.log("Emitting timelinecreated");
	jq_neatlineexhibit('body').trigger("timelinecreated",[config.timelinediv]);

}

var resizeTimerID = null;

Omeka.Timeline.onResize = function() {
	if (resizeTimerID == null) {
		resizeTimerID = window.setTimeout(function() {
			resizeTimerID = null;
			Omeka.Timeline.timeline.layout();
		}, 500);
	}
}<|endoftext|>


<commit_before>/* jslint node: true */
'use strict';

//	ENiGMA½
const conf			= require('./config.js');

//	deps
const sqlite3		= require('sqlite3');
const sqlite3Trans	= require('sqlite3-trans');
const paths			= require('path');
const async			= require('async');
const _				= require('lodash');
const assert		= require('assert');
const moment		= require('moment');

//	database handles
const dbs = {};

exports.getTransactionDatabase		= getTransactionDatabase;
exports.getModDatabasePath			= getModDatabasePath;
exports.getISOTimestampString		= getISOTimestampString;
exports.sanatizeString				= sanatizeString;
exports.initializeDatabases			= initializeDatabases;

exports.dbs							= dbs;

function getTransactionDatabase(db) {
	return sqlite3Trans.wrap(db);
}

function getDatabasePath(name) {
	return paths.join(conf.config.paths.db, `${name}.sqlite3`);
}

function getModDatabasePath(moduleInfo, suffix) {
	//
	//	Mods that use a database are stored in Config.paths.modsDb (e.g. enigma-bbs/db/mods)
	//	We expect that moduleInfo defines packageName which will be the base of the modules
	//	filename. An optional suffix may be supplied as well.
	//
	const HOST_RE = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/;

	assert(_.isObject(moduleInfo));
	assert(_.isString(moduleInfo.packageName), 'moduleInfo must define "packageName"!');

	let full = moduleInfo.packageName;
	if(suffix) {
		full += `.${suffix}`;
	}

	assert(
		(full.split('.').length > 1 && HOST_RE.test(full)),
		'packageName must follow Reverse Domain Name Notation - https://en.wikipedia.org/wiki/Reverse_domain_name_notation');

	return paths.join(conf.config.paths.modsDb, `${full}.sqlite3`);
}

function getISOTimestampString(ts) {
	ts = ts || moment();
	return ts.format('YYYY-MM-DDTHH:mm:ss.SSSZ');
}

function sanatizeString(s) {
	return s.replace(/[\0\x08\x09\x1a\n\r"'\\%]/g, c => {	//	eslint-disable-line no-control-regex
		switch (c) {
			case '\0'	: return '\\0';
			case '\x08'	: return '\\b';
			case '\x09'	: return '\\t';
			case '\x1a'	: return '\\z';
			case '\n'	: return '\\n';
			case '\r'	: return '\\r';

			case '"' :
			case '\'' :
			case '\\' :
			case '%' :
				return `\\${c}`;
		}
	});
}

function initializeDatabases(cb) {
	async.eachSeries( [ 'system', 'user', 'message', 'file' ], (dbName, next) => {
		dbs[dbName] = sqlite3Trans.wrap(new sqlite3.Database(getDatabasePath(dbName), err => {
			if(err) {
				return cb(err);
			}

			dbs[dbName].serialize( () => {
				DB_INIT_TABLE[dbName]( () => {
					return next(null);
				});
			});
		}));
	}, err => {
		return cb(err);
	});
}

function enableForeignKeys(db) {
	db.run('PRAGMA foreign_keys = ON;');
}

const DB_INIT_TABLE = {
	system : (cb) => {
		enableForeignKeys(dbs.system);

		//	Various stat/event logging - see stat_log.js
		dbs.system.run(
			`CREATE TABLE IF NOT EXISTS system_stat (
				stat_name		VARCHAR PRIMARY KEY NOT NULL,
				stat_value		VARCHAR NOT NULL
			);`
		);

		dbs.system.run(
			`CREATE TABLE IF NOT EXISTS system_event_log (
				id				INTEGER PRIMARY KEY,
				timestamp		DATETIME NOT NULL,
				log_name		VARCHAR NOT NULL,
				log_value		VARCHAR NOT NULL,

				UNIQUE(timestamp, log_name)
			);`
		);

		dbs.system.run(
			`CREATE TABLE IF NOT EXISTS user_event_log (
				id				INTEGER PRIMARY KEY,
				timestamp		DATETIME NOT NULL,
				user_id			INTEGER NOT NULL,
				log_name		VARCHAR NOT NULL,
				log_value		VARCHAR NOT NULL,

				UNIQUE(timestamp, user_id, log_name)
			);`
		);

		return cb(null);
	},

	user : (cb) => {
		enableForeignKeys(dbs.user);

		dbs.user.run(
			`CREATE TABLE IF NOT EXISTS user (
				id			INTEGER PRIMARY KEY,
				user_name	VARCHAR NOT NULL,
				UNIQUE(user_name)
			);`
		);

		//	:TODO: create FK on delete/etc.

		dbs.user.run(
			`CREATE TABLE IF NOT EXISTS user_property (
				user_id		INTEGER NOT NULL,
				prop_name	VARCHAR NOT NULL,
				prop_value	VARCHAR,
				UNIQUE(user_id, prop_name),
				FOREIGN KEY(user_id) REFERENCES user(id) ON DELETE CASCADE
			);`
		);

		dbs.user.run(
			`CREATE TABLE IF NOT EXISTS user_group_member (
				group_name	VARCHAR NOT NULL,
				user_id		INTEGER NOT NULL,
				UNIQUE(group_name, user_id)
			);`
		);

		dbs.user.run(
			`CREATE TABLE IF NOT EXISTS user_login_history (
				user_id		INTEGER NOT NULL,
				user_name	VARCHAR NOT NULL,
				timestamp	DATETIME NOT NULL
			);`
		);

		return cb(null);
	},

	message : (cb) => {
		enableForeignKeys(dbs.message);

		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS message (
				message_id				INTEGER PRIMARY KEY,
				area_tag				VARCHAR NOT NULL,
				message_uuid			VARCHAR(36) NOT NULL,
				reply_to_message_id		INTEGER,
				to_user_name			VARCHAR NOT NULL,
				from_user_name			VARCHAR NOT NULL,
				subject, /* FTS @ message_fts */
				message, /* FTS @ message_fts */
				modified_timestamp		DATETIME NOT NULL,
				view_count				INTEGER NOT NULL DEFAULT 0,
				UNIQUE(message_uuid)
			);`
		);

		dbs.message.run(
			`CREATE INDEX IF NOT EXISTS message_by_area_tag_index
			ON message (area_tag);`
		);

		dbs.message.run(
			`CREATE VIRTUAL TABLE IF NOT EXISTS message_fts USING fts4 (
				content="message",
				subject,
				message
			);`
		);

		dbs.message.run(
			`CREATE TRIGGER IF NOT EXISTS message_before_update BEFORE UPDATE ON message BEGIN
				DELETE FROM message_fts WHERE docid=old.rowid;
			END;`
		);

		dbs.message.run(
			`CREATE TRIGGER IF NOT EXISTS message_before_delete BEFORE DELETE ON message BEGIN
				DELETE FROM message_fts WHERE docid=old.rowid;
			END;`
		);

		dbs.message.run(
			`CREATE TRIGGER IF NOT EXISTS message_after_update AFTER UPDATE ON message BEGIN
				INSERT INTO message_fts(docid, subject, message) VALUES(new.rowid, new.subject, new.message);
			END;`
		);

		dbs.message.run(
			`CREATE TRIGGER IF NOT EXISTS message_after_insert AFTER INSERT ON message BEGIN
				INSERT INTO message_fts(docid, subject, message) VALUES(new.rowid, new.subject, new.message);
			END;`
		);

		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS message_meta (
				message_id		INTEGER NOT NULL,
				meta_category	INTEGER NOT NULL,
				meta_name		VARCHAR NOT NULL,
				meta_value		VARCHAR NOT NULL,
				UNIQUE(message_id, meta_category, meta_name, meta_value),
				FOREIGN KEY(message_id) REFERENCES message(message_id) ON DELETE CASCADE
			);`
		);

		//	:TODO: need SQL to ensure cleaned up if delete from message?
		/*
		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS hash_tag (
				hash_tag_id		INTEGER PRIMARY KEY,
				hash_tag_name	VARCHAR NOT NULL,
				UNIQUE(hash_tag_name)
			);`
		);

		//	:TODO: need SQL to ensure cleaned up if delete from message?
		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS message_hash_tag (
				hash_tag_id	INTEGER NOT NULL,
				message_id	INTEGER NOT NULL,
			);`
		);
		*/

		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS user_message_area_last_read (
				user_id		INTEGER NOT NULL,
				area_tag	VARCHAR NOT NULL,
				message_id	INTEGER NOT NULL,
				UNIQUE(user_id, area_tag)
			);`
		);

		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS message_area_last_scan (
				scan_toss		VARCHAR NOT NULL,
				area_tag		VARCHAR NOT NULL,
				message_id		INTEGER NOT NULL,
				UNIQUE(scan_toss, area_tag)
			);`
		);

		return cb(null);
	},

	file : (cb) => {
		enableForeignKeys(dbs.file);

		dbs.file.run(
			//	:TODO: should any of this be unique -- file_sha256 unless dupes are allowed on the system
			`CREATE TABLE IF NOT EXISTS file (
				file_id				INTEGER PRIMARY KEY,
				area_tag			VARCHAR NOT NULL,
				file_sha256			VARCHAR NOT NULL,
				file_name,			/* FTS @ file_fts */
				storage_tag			VARCHAR NOT NULL,
				desc,				/* FTS @ file_fts */
				desc_long,			/* FTS @ file_fts */
				upload_timestamp	DATETIME NOT NULL
			);`
		);

		dbs.file.run(
			`CREATE INDEX IF NOT EXISTS file_by_area_tag_index
			ON file (area_tag);`
		);

		dbs.file.run(
			`CREATE INDEX IF NOT EXISTS file_by_sha256_index
			ON file (file_sha256);`
		);

		dbs.file.run(
			`CREATE VIRTUAL TABLE IF NOT EXISTS file_fts USING fts4 (
				content="file",
				file_name,
				desc,
				desc_long
			);`
		);

		dbs.file.run(
			`CREATE TRIGGER IF NOT EXISTS file_before_update BEFORE UPDATE ON file BEGIN
				DELETE FROM file_fts WHERE docid=old.rowid;
			END;`
		);

		dbs.file.run(
			`CREATE TRIGGER IF NOT EXISTS file_before_delete BEFORE DELETE ON file BEGIN
				DELETE FROM file_fts WHERE docid=old.rowid;
			END;`
		);

		dbs.file.run(
			`CREATE TRIGGER IF NOT EXISTS file_after_update AFTER UPDATE ON file BEGIN
				INSERT INTO file_fts(docid, file_name, desc, desc_long) VALUES(new.rowid, new.file_name, new.desc, new.desc_long);
			END;`
		);

		dbs.file.run(
			`CREATE TRIGGER IF NOT EXISTS file_after_insert AFTER INSERT ON file BEGIN
				INSERT INTO file_fts(docid, file_name, desc, desc_long) VALUES(new.rowid, new.file_name, new.desc, new.desc_long);
			END;`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_meta (
				file_id			INTEGER NOT NULL,
				meta_name		VARCHAR NOT NULL,
				meta_value		VARCHAR NOT NULL,
				UNIQUE(file_id, meta_name, meta_value),
				FOREIGN KEY(file_id) REFERENCES file(file_id) ON DELETE CASCADE
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS hash_tag (
				hash_tag_id		INTEGER PRIMARY KEY,
				hash_tag		VARCHAR NOT NULL,

				UNIQUE(hash_tag)
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_hash_tag (
				hash_tag_id		INTEGER NOT NULL,
				file_id			INTEGER NOT NULL,

				UNIQUE(hash_tag_id, file_id)
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_user_rating (
				file_id			INTEGER NOT NULL,
				user_id			INTEGER NOT NULL,
				rating			INTEGER NOT NULL,

				UNIQUE(file_id, user_id)
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_web_serve (
				hash_id				VARCHAR NOT NULL PRIMARY KEY,
				expire_timestamp	DATETIME NOT NULL
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_web_serve_batch (
				hash_id		VARCHAR NOT NULL,
				file_id		INTEGER NOT NULL,

				UNIQUE(hash_id, file_id)
			);`
		);

		return cb(null);
	}
};<commit_msg>Fix bug with quote escaping in DB sanatizeString()<commit_after>/* jslint node: true */
'use strict';

//	ENiGMA½
const conf			= require('./config.js');

//	deps
const sqlite3		= require('sqlite3');
const sqlite3Trans	= require('sqlite3-trans');
const paths			= require('path');
const async			= require('async');
const _				= require('lodash');
const assert		= require('assert');
const moment		= require('moment');

//	database handles
const dbs = {};

exports.getTransactionDatabase		= getTransactionDatabase;
exports.getModDatabasePath			= getModDatabasePath;
exports.getISOTimestampString		= getISOTimestampString;
exports.sanatizeString				= sanatizeString;
exports.initializeDatabases			= initializeDatabases;

exports.dbs							= dbs;

function getTransactionDatabase(db) {
	return sqlite3Trans.wrap(db);
}

function getDatabasePath(name) {
	return paths.join(conf.config.paths.db, `${name}.sqlite3`);
}

function getModDatabasePath(moduleInfo, suffix) {
	//
	//	Mods that use a database are stored in Config.paths.modsDb (e.g. enigma-bbs/db/mods)
	//	We expect that moduleInfo defines packageName which will be the base of the modules
	//	filename. An optional suffix may be supplied as well.
	//
	const HOST_RE = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9])$/;

	assert(_.isObject(moduleInfo));
	assert(_.isString(moduleInfo.packageName), 'moduleInfo must define "packageName"!');

	let full = moduleInfo.packageName;
	if(suffix) {
		full += `.${suffix}`;
	}

	assert(
		(full.split('.').length > 1 && HOST_RE.test(full)),
		'packageName must follow Reverse Domain Name Notation - https://en.wikipedia.org/wiki/Reverse_domain_name_notation');

	return paths.join(conf.config.paths.modsDb, `${full}.sqlite3`);
}

function getISOTimestampString(ts) {
	ts = ts || moment();
	return ts.format('YYYY-MM-DDTHH:mm:ss.SSSZ');
}

function sanatizeString(s) {
	return s.replace(/[\0\x08\x09\x1a\n\r"'\\%]/g, c => {	//	eslint-disable-line no-control-regex
		switch (c) {
			case '\0'	: return '\\0';
			case '\x08'	: return '\\b';
			case '\x09'	: return '\\t';
			case '\x1a'	: return '\\z';
			case '\n'	: return '\\n';
			case '\r'	: return '\\r';

			case '"' :
			case '\'' :
				return `${c}${c}`;

			case '\\' :
			case '%' :
				return `\\${c}`;
		}
	});
}

function initializeDatabases(cb) {
	async.eachSeries( [ 'system', 'user', 'message', 'file' ], (dbName, next) => {
		dbs[dbName] = sqlite3Trans.wrap(new sqlite3.Database(getDatabasePath(dbName), err => {
			if(err) {
				return cb(err);
			}

			dbs[dbName].serialize( () => {
				DB_INIT_TABLE[dbName]( () => {
					return next(null);
				});
			});
		}));
	}, err => {
		return cb(err);
	});
}

function enableForeignKeys(db) {
	db.run('PRAGMA foreign_keys = ON;');
}

const DB_INIT_TABLE = {
	system : (cb) => {
		enableForeignKeys(dbs.system);

		//	Various stat/event logging - see stat_log.js
		dbs.system.run(
			`CREATE TABLE IF NOT EXISTS system_stat (
				stat_name		VARCHAR PRIMARY KEY NOT NULL,
				stat_value		VARCHAR NOT NULL
			);`
		);

		dbs.system.run(
			`CREATE TABLE IF NOT EXISTS system_event_log (
				id				INTEGER PRIMARY KEY,
				timestamp		DATETIME NOT NULL,
				log_name		VARCHAR NOT NULL,
				log_value		VARCHAR NOT NULL,

				UNIQUE(timestamp, log_name)
			);`
		);

		dbs.system.run(
			`CREATE TABLE IF NOT EXISTS user_event_log (
				id				INTEGER PRIMARY KEY,
				timestamp		DATETIME NOT NULL,
				user_id			INTEGER NOT NULL,
				log_name		VARCHAR NOT NULL,
				log_value		VARCHAR NOT NULL,

				UNIQUE(timestamp, user_id, log_name)
			);`
		);

		return cb(null);
	},

	user : (cb) => {
		enableForeignKeys(dbs.user);

		dbs.user.run(
			`CREATE TABLE IF NOT EXISTS user (
				id			INTEGER PRIMARY KEY,
				user_name	VARCHAR NOT NULL,
				UNIQUE(user_name)
			);`
		);

		//	:TODO: create FK on delete/etc.

		dbs.user.run(
			`CREATE TABLE IF NOT EXISTS user_property (
				user_id		INTEGER NOT NULL,
				prop_name	VARCHAR NOT NULL,
				prop_value	VARCHAR,
				UNIQUE(user_id, prop_name),
				FOREIGN KEY(user_id) REFERENCES user(id) ON DELETE CASCADE
			);`
		);

		dbs.user.run(
			`CREATE TABLE IF NOT EXISTS user_group_member (
				group_name	VARCHAR NOT NULL,
				user_id		INTEGER NOT NULL,
				UNIQUE(group_name, user_id)
			);`
		);

		dbs.user.run(
			`CREATE TABLE IF NOT EXISTS user_login_history (
				user_id		INTEGER NOT NULL,
				user_name	VARCHAR NOT NULL,
				timestamp	DATETIME NOT NULL
			);`
		);

		return cb(null);
	},

	message : (cb) => {
		enableForeignKeys(dbs.message);

		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS message (
				message_id				INTEGER PRIMARY KEY,
				area_tag				VARCHAR NOT NULL,
				message_uuid			VARCHAR(36) NOT NULL,
				reply_to_message_id		INTEGER,
				to_user_name			VARCHAR NOT NULL,
				from_user_name			VARCHAR NOT NULL,
				subject, /* FTS @ message_fts */
				message, /* FTS @ message_fts */
				modified_timestamp		DATETIME NOT NULL,
				view_count				INTEGER NOT NULL DEFAULT 0,
				UNIQUE(message_uuid)
			);`
		);

		dbs.message.run(
			`CREATE INDEX IF NOT EXISTS message_by_area_tag_index
			ON message (area_tag);`
		);

		dbs.message.run(
			`CREATE VIRTUAL TABLE IF NOT EXISTS message_fts USING fts4 (
				content="message",
				subject,
				message
			);`
		);

		dbs.message.run(
			`CREATE TRIGGER IF NOT EXISTS message_before_update BEFORE UPDATE ON message BEGIN
				DELETE FROM message_fts WHERE docid=old.rowid;
			END;`
		);

		dbs.message.run(
			`CREATE TRIGGER IF NOT EXISTS message_before_delete BEFORE DELETE ON message BEGIN
				DELETE FROM message_fts WHERE docid=old.rowid;
			END;`
		);

		dbs.message.run(
			`CREATE TRIGGER IF NOT EXISTS message_after_update AFTER UPDATE ON message BEGIN
				INSERT INTO message_fts(docid, subject, message) VALUES(new.rowid, new.subject, new.message);
			END;`
		);

		dbs.message.run(
			`CREATE TRIGGER IF NOT EXISTS message_after_insert AFTER INSERT ON message BEGIN
				INSERT INTO message_fts(docid, subject, message) VALUES(new.rowid, new.subject, new.message);
			END;`
		);

		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS message_meta (
				message_id		INTEGER NOT NULL,
				meta_category	INTEGER NOT NULL,
				meta_name		VARCHAR NOT NULL,
				meta_value		VARCHAR NOT NULL,
				UNIQUE(message_id, meta_category, meta_name, meta_value),
				FOREIGN KEY(message_id) REFERENCES message(message_id) ON DELETE CASCADE
			);`
		);

		//	:TODO: need SQL to ensure cleaned up if delete from message?
		/*
		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS hash_tag (
				hash_tag_id		INTEGER PRIMARY KEY,
				hash_tag_name	VARCHAR NOT NULL,
				UNIQUE(hash_tag_name)
			);`
		);

		//	:TODO: need SQL to ensure cleaned up if delete from message?
		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS message_hash_tag (
				hash_tag_id	INTEGER NOT NULL,
				message_id	INTEGER NOT NULL,
			);`
		);
		*/

		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS user_message_area_last_read (
				user_id		INTEGER NOT NULL,
				area_tag	VARCHAR NOT NULL,
				message_id	INTEGER NOT NULL,
				UNIQUE(user_id, area_tag)
			);`
		);

		dbs.message.run(
			`CREATE TABLE IF NOT EXISTS message_area_last_scan (
				scan_toss		VARCHAR NOT NULL,
				area_tag		VARCHAR NOT NULL,
				message_id		INTEGER NOT NULL,
				UNIQUE(scan_toss, area_tag)
			);`
		);

		return cb(null);
	},

	file : (cb) => {
		enableForeignKeys(dbs.file);

		dbs.file.run(
			//	:TODO: should any of this be unique -- file_sha256 unless dupes are allowed on the system
			`CREATE TABLE IF NOT EXISTS file (
				file_id				INTEGER PRIMARY KEY,
				area_tag			VARCHAR NOT NULL,
				file_sha256			VARCHAR NOT NULL,
				file_name,			/* FTS @ file_fts */
				storage_tag			VARCHAR NOT NULL,
				desc,				/* FTS @ file_fts */
				desc_long,			/* FTS @ file_fts */
				upload_timestamp	DATETIME NOT NULL
			);`
		);

		dbs.file.run(
			`CREATE INDEX IF NOT EXISTS file_by_area_tag_index
			ON file (area_tag);`
		);

		dbs.file.run(
			`CREATE INDEX IF NOT EXISTS file_by_sha256_index
			ON file (file_sha256);`
		);

		dbs.file.run(
			`CREATE VIRTUAL TABLE IF NOT EXISTS file_fts USING fts4 (
				content="file",
				file_name,
				desc,
				desc_long
			);`
		);

		dbs.file.run(
			`CREATE TRIGGER IF NOT EXISTS file_before_update BEFORE UPDATE ON file BEGIN
				DELETE FROM file_fts WHERE docid=old.rowid;
			END;`
		);

		dbs.file.run(
			`CREATE TRIGGER IF NOT EXISTS file_before_delete BEFORE DELETE ON file BEGIN
				DELETE FROM file_fts WHERE docid=old.rowid;
			END;`
		);

		dbs.file.run(
			`CREATE TRIGGER IF NOT EXISTS file_after_update AFTER UPDATE ON file BEGIN
				INSERT INTO file_fts(docid, file_name, desc, desc_long) VALUES(new.rowid, new.file_name, new.desc, new.desc_long);
			END;`
		);

		dbs.file.run(
			`CREATE TRIGGER IF NOT EXISTS file_after_insert AFTER INSERT ON file BEGIN
				INSERT INTO file_fts(docid, file_name, desc, desc_long) VALUES(new.rowid, new.file_name, new.desc, new.desc_long);
			END;`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_meta (
				file_id			INTEGER NOT NULL,
				meta_name		VARCHAR NOT NULL,
				meta_value		VARCHAR NOT NULL,
				UNIQUE(file_id, meta_name, meta_value),
				FOREIGN KEY(file_id) REFERENCES file(file_id) ON DELETE CASCADE
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS hash_tag (
				hash_tag_id		INTEGER PRIMARY KEY,
				hash_tag		VARCHAR NOT NULL,

				UNIQUE(hash_tag)
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_hash_tag (
				hash_tag_id		INTEGER NOT NULL,
				file_id			INTEGER NOT NULL,

				UNIQUE(hash_tag_id, file_id)
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_user_rating (
				file_id			INTEGER NOT NULL,
				user_id			INTEGER NOT NULL,
				rating			INTEGER NOT NULL,

				UNIQUE(file_id, user_id)
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_web_serve (
				hash_id				VARCHAR NOT NULL PRIMARY KEY,
				expire_timestamp	DATETIME NOT NULL
			);`
		);

		dbs.file.run(
			`CREATE TABLE IF NOT EXISTS file_web_serve_batch (
				hash_id		VARCHAR NOT NULL,
				file_id		INTEGER NOT NULL,

				UNIQUE(hash_id, file_id)
			);`
		);

		return cb(null);
	}
};<|endoftext|>


<commit_before>//============================================//
//            SERVER CONFIGURATION            //
//============================================//
if( typeof( window ) === 'undefined' ) {     // if there isn't a window, then this is severside, so do serverside config
//============================================//
//IP ADDRESS                                  //
  var SERVER_IP =                             //
  process.env.DELBID_NODEJS_IP                // toggle on for local testing
//process.env.OPENSHIFT_NODEJS_IP             // toggle on for openshift deploy
//============================================//
//PORT NUMBER                                 //
  var SERVER_PORT =                           //
  process.env.DELBID_NODEJS_PORT              // toggle on for local testing
//process.env.OPENSHIFT_NODEJS_PORT           // toggle on for openshift deploy
//============================================//
//SECRET FOR SESSION DATA                     //
  var COOKIE_SECRET =                         //
  process.env.DELBID_COOKIE_SECRET            // toggle on for local testing
//process.env.OPENSHIFT_COOKIE_SECRET         // toggle on for openshift deploy
//============================================//
//MONGODB CONNECTION INFO                     //
  var MONGO_USER =                            //
  process.env.DELBID_MONGO_DB_USERNAME        // toggle on for local testing
//process.env.OPENSHIFT_MONGODB_DB_USERNAME   // toggle on for openshift deploy
//============================================//
  var MONGO_PASS =                            //
  process.env.DELBID_MONGO_DB_PASS            // toggle on for local testing
//process.env.OPENSHIFT_MONGODB_DB_PASSWORD   // toggle on for openshift deploy
//============================================//
  var MONGO_IP =                              //
  process.env.DELBID_MONGO_DB_IP              // toggle on for local testing
//process.env.OPENSHIFT_MONGODB_DB_IP         // toggle on for openshift deploy
//============================================//
  var MONGO_PORT =                            //
  process.env.DELBID_MONGO_DB_PORT            // toggle on for local testing
//process.env.OPENSHIFT_MONGODB_DB_PORT       // toggle on for openshift deploy
//============================================//
  var MONGO_DB_NAME =                         //
  process.env.DELBID_MONGO_DB_NAME            // toggle on for local testing
//process.env.OPENSHIFT_MONGO_DB_NAME         // toggle on for openshift deploy
//============================================//
}                                             //
//============================================//

//============================================//
//            CLIENT CONFIGURATION            //
//============================================//
//IP ADDRESS                                  //
  var CLIENT_IP =                             //
  'localhost'                                 // toggle on for local testing
//'delegate.bid'                              // toggle on for openshift deploy (swap in your own domain)
//============================================//
//PORT NUMBER                                 //
  var CLIENT_PORT =                           //
  8080                                        // toggle on for local testing
//8000                                        // neccessary for openshift, as websockets is restricted to this port
//============================================//

//serverside exports
if( typeof( window ) === 'undefined' ) {
	module.exports.CLIENT_IP     = CLIENT_IP;
	module.exports.CLIENT_PORT   = CLIENT_PORT;
	module.exports.CLIENT_HOST   = CLIENT_IP + ':' + CLIENT_PORT;
	module.exports.SERVER_IP     = SERVER_IP;
	module.exports.SERVER_PORT   = SERVER_PORT;
	module.exports.SERVER_HOST   = SERVER_IP + ':' + SERVER_PORT;
	module.exports.COOKIE_SECRET = COOKIE_SECRET;
	module.exports.MONGO_USER    = MONGO_USER;
	module.exports.MONGO_PASS    = MONGO_PASS;
	module.exports.MONGO_IP      = MONGO_IP;
	module.exports.MONGO_PORT    = MONGO_PORT;
	module.exports.MONGO_DB_NAME = MONGO_DB_NAME;
}
<commit_msg>switched to deploy mode<commit_after>//============================================//
//            SERVER CONFIGURATION            //
//============================================//
if( typeof( window ) === 'undefined' ) {     // if there isn't a window, then this is severside, so do serverside config
//============================================//
//IP ADDRESS                                  //
  var SERVER_IP =                             //
//process.env.DELBID_NODEJS_IP                // toggle on for local testing
  process.env.OPENSHIFT_NODEJS_IP             // toggle on for openshift deploy
//============================================//
//PORT NUMBER                                 //
  var SERVER_PORT =                           //
//process.env.DELBID_NODEJS_PORT              // toggle on for local testing
  process.env.OPENSHIFT_NODEJS_PORT           // toggle on for openshift deploy
//============================================//
//SECRET FOR SESSION DATA                     //
  var COOKIE_SECRET =                         //
//process.env.DELBID_COOKIE_SECRET            // toggle on for local testing
  process.env.OPENSHIFT_COOKIE_SECRET         // toggle on for openshift deploy
//============================================//
//MONGODB CONNECTION INFO                     //
  var MONGO_USER =                            //
//process.env.DELBID_MONGO_DB_USERNAME        // toggle on for local testing
  process.env.OPENSHIFT_MONGODB_DB_USERNAME   // toggle on for openshift deploy
//============================================//
  var MONGO_PASS =                            //
//process.env.DELBID_MONGO_DB_PASS            // toggle on for local testing
  process.env.OPENSHIFT_MONGODB_DB_PASSWORD   // toggle on for openshift deploy
//============================================//
  var MONGO_IP =                              //
//process.env.DELBID_MONGO_DB_IP              // toggle on for local testing
  process.env.OPENSHIFT_MONGODB_DB_HOST       // toggle on for openshift deploy
//============================================//
  var MONGO_PORT =                            //
//process.env.DELBID_MONGO_DB_PORT            // toggle on for local testing
  process.env.OPENSHIFT_MONGODB_DB_PORT       // toggle on for openshift deploy
//============================================//
  var MONGO_DB_NAME =                         //
//process.env.DELBID_MONGO_DB_NAME            // toggle on for local testing
  process.env.OPENSHIFT_MONGO_DB_NAME         // toggle on for openshift deploy
//============================================//
}                                             //
//============================================//

//============================================//
//            CLIENT CONFIGURATION            //
//============================================//
//IP ADDRESS                                  //
  var CLIENT_IP =                             //
//'localhost'                                 // toggle on for local testing
  'delegate.bid'                              // toggle on for openshift deploy (swap in your own domain)
//============================================//
//PORT NUMBER                                 //
  var CLIENT_PORT =                           //
//8080                                        // toggle on for local testing
  8000                                        // neccessary for openshift, as websockets is restricted to this port
//============================================//

//serverside exports
if( typeof( window ) === 'undefined' ) {
	module.exports.CLIENT_IP     = CLIENT_IP;
	module.exports.CLIENT_PORT   = CLIENT_PORT;
	module.exports.CLIENT_HOST   = CLIENT_IP + ':' + CLIENT_PORT;
	module.exports.SERVER_IP     = SERVER_IP;
	module.exports.SERVER_PORT   = SERVER_PORT;
	module.exports.SERVER_HOST   = SERVER_IP + ':' + SERVER_PORT;
	module.exports.COOKIE_SECRET = COOKIE_SECRET;
	module.exports.MONGO_USER    = MONGO_USER;
	module.exports.MONGO_PASS    = MONGO_PASS;
	module.exports.MONGO_IP      = MONGO_IP;
	module.exports.MONGO_PORT    = MONGO_PORT;
	module.exports.MONGO_DB_NAME = MONGO_DB_NAME;
}
<|endoftext|>


<commit_before>var activeCueIds = [];
var nScrubs = -1; //number of times scrubed. Could put in a function to reset after x number scrubs, and then instead load new subs in same genre.

$( document ).ready(function() {
  //for when DOM is ready..

  //initialise with subs:
  scrubTrack(nScrubs + 1);

	var iframe_active = $(".activevideo:first").data("zid");
	if (iframe_active == null || iframe_active <= 0) $('#ajax-loader-video').toggle();

	$('#'+iframe_active).load(function(){
		$('#ajax-loader-video').toggle();
  });

	document.getElementById('video').addEventListener('loadedmetadata', function() {
		this.currentTime = 3;
	}, false);

	//Enable swiping...
	$(".swipescrub").swipe( {
		//Generic swipe handler for all directions
    swipe: function(event, direction, distance, duration, fingerCount, fingerData) {

      if (direction == null) return false;

      if (direction == 'up') {
        console.log("scrub up " + nScrubs);
        scrubTrack(nScrubs);

      }

      if (direction == 'down') console.log("down"); //return false;

      if (direction == 'right') console.log("right"); //return false;

      if (direction == 'left') console.log("left"); //return false;
      //if (direction == 'left') rotatelement(".info-panels",180); //return false;
    },
   //Default is 75px
   threshold:15
	});

});

function scrubTrack(offsetIndex){

  var track = video.addTextTrack("captions", "comedy", "en");

  track.mode = "showing";

  //arrays for upcoming cues
  var starttime = [], endtime = [] , text = [] ;

  $selector = $("#comedy li").eq(offsetIndex);

  //making a buffer of 60 seconds from the list-items in the api, storing them in the starttime, endtime and text arrays.
  $selector.each(function(i){
  	starttime[i] = $selector.eq(i).find(".start").text();
  	endtime[i]   = $selector.eq(i).find(".end").text();
  	text[i]      = $selector.eq(i).find(".text").text();
	});

  //console.log(starttime.length, starttime);
  //console.log($selector);

	for (var i = 0; i < starttime.length; i++) {
	  console.log(i, starttime[i], endtime[i], text[i]);
	  //newCue = new VTTCue(starttime[i], endtime[i], text[i]);
	  track.addCue(new VTTCue(starttime[i], endtime[i], text[i]));
    //storing cue ID's in the activeCueIds array - to be used for deletion
	  //activeCueIds[i] = newCue.id;
	}

	/*track.addCue(new VTTCue(0, 12, "Loaded Cues"));
	track.addCue(new VTTCue(18.7, 21.5, "This blade has a dark past."));
	track.addCue(new VTTCue(22.8, 26.8, "It has shed much innocent blood."));
	track.addCue(new VTTCue(29, 32.45, "You're a fool for traveling alone, so completely unprepared."));
	track.addCue(new VTTCue(32.75, 35.8, "You're lucky your blood's still flowing."));
	track.addCue(new VTTCue(36.25, 37.3, "Thank you."));
	track.addCue(new VTTCue(38.5, 40, "So..."));
	track.addCue(new VTTCue(40.4, 44.8, "What brings you to the land of the gatekeepers?"));
	track.addCue(new VTTCue(46, 48.5, "I'm searching for someone."));
	track.addCue(new VTTCue(49, 53.2, "Someone very dear? A kindred spirit?"));
	track.addCue(new VTTCue(54.4, 56, "A dragon."));
	track.addCue(new VTTCue(58.85, 61.75, "A dangerous quest for a lone hunter."));
	track.addCue(new VTTCue(62.95, 65.87, "I've been alone for as long as I can remember."));
	track.addCue(new VTTCue(118.25, 119.5, "We're almost done. Shhh..."));	*/
	//return offsetIndex;
	offsetIndex++;
}

/*laravel specifics? don't know where these came from */

function pinClone() {
	balancelement(".info-panels");
	var ZIDkey_val = $("#info:first").data("todo");
	//$('#ajax-loader-pindu').toggle();
	$('.active').slideToggle();
	var nextactivetodo = $('.active').nextAll('.col-lg-4:first');
	$( ".active" ).remove();
	nextactivetodo.slideToggle().addClass( "active" );

    //Get value and make sure it is not null
	if (ZIDkey_val.length == 0)  window.location.reload();
		$.ajax({
      url: "pages/functions/votes_addupvote.php",
      type: "post",
      dataType:"json",
      data: { ZID_key : ZIDkey_val },
      statusCode: {
          404: function() {
            alert("Big problem! Page not found");
          }
        },
      success: function(data){
    		if (data.bool_flag) {
      		return;
    		} else {
      		console.log(data.message + '  ' + data.dbconn);
      		return;
      		//$('#ajax-loader-pindu').toggle();
      		// window.location.reload();
    		}
      },
      error:function(data){
        console.log(' Function error  ');
        $('#ajax-loader-pindu').toggle();
        //window.location.reload();
      }
    });
  return;
}

function pinRemove() {
	balancelement(".info-panels");
	var ZIDkey_val = $("#info:first").data("todo");
	//$('#ajax-loader-pindu').toggle();
	$('.active').slideToggle();
	var nextactivetodo = $('.active').nextAll('.col-lg-4:first');
	$( ".active" ).remove();
	nextactivetodo.slideToggle().addClass( "active" );

  //Get value and make sure it is not null
	if (ZIDkey_val.length == 0)  window.location.reload();

	$.ajax({
    url: "pages/functions/votes_adddownvote.php",
    type: "post",
    dataType:"json",
		data: { ZID_key : ZIDkey_val },
    statusCode: {
      404: function() {
        alert("Big problem! Page not found");
      }
    },
    success: function(data){
			if (data.bool_flag) {
			return;
			} else {
  			console.log(data.message + '  ' + data.dbconn);
  			return;
  			//$('#ajax-loader-pindu').toggle();
  			// window.location.reload();
			}
    },
    error:function(data){
  		console.log(' Function error  ');
  		$('#ajax-loader-pindu').toggle();
  		//window.location.reload();
    }
  });

return;

}

function visitorSubmit() {
	$('#ajax-loader-visitorSubmit').toggle();
	var ZIDkey_val = $("#visitorTask").val();
	if (ZIDkey_val.length == 0)  window.location.reload();

			$.ajax({
	            url: "pages/functions/tasks_visitors_add.php",
	            type: "post",
	            dataType:"json",
				data: { body_tasks : ZIDkey_val },
	            statusCode: {
	                404: function() {
	                  alert("Big problem! Page not found");
	                }
	              },
	            success: function(data){
					if (data.bool_flag) {
						window.location.assign("./login.html");
						return;
					} else {
						$('#ajax-loader-pindu').toggle();
						console.log(data.message + '  ' + data.dbconn);
						alert(data.message + '  ' + data.dbconn);
						window.location.reload();
						return;
					}
	            },
	            error:function(data){
					console.log(' Function error  ');
					$('#ajax-loader-pindu').toggle();
					//window.location.reload();
	            }
	        });

}

function pinLater() {
	$('#ajax-loader-pindu').toggle();
	//$('#ajax-loader-later').toggle();
	window.location.reload();
}
<commit_msg>Update scrubr.js<commit_after>var activeCueIds = [];
var nScrubs = -1; //number of times scrubed. Could put in a function to reset after x number scrubs, and then instead load new subs in same genre.

$( document ).ready(function() {
  //for when DOM is ready..

  //initialise with subs:
  scrubTrack(nScrubs + 1);

	var iframe_active = $(".activevideo:first").data("zid");
	if (iframe_active == null || iframe_active <= 0) $('#ajax-loader-video').toggle();

	$('#'+iframe_active).load(function(){
		$('#ajax-loader-video').toggle();
  });

	document.getElementById('video').addEventListener('loadedmetadata', function() {
		this.currentTime = 3;
	}, false);

	//Enable swiping...
	$(".swipescrub").swipe( {
		//Generic swipe handler for all directions
    swipe: function(event, direction, distance, duration, fingerCount, fingerData) {

      if (direction == null) {return false;}

      if (direction == 'up') {
        console.log("scrub up " + nScrubs);
        scrubTrack(nScrubs);
      }

      if (direction == 'down') {console.log("down");} //return false;

      if (direction == 'right') console.log("right"); //return false;

      if (direction == 'left') {console.log("left");} //return false;
      //if (direction == 'left') rotatelement(".info-panels",180); //return false;
    },
   //Default is 75px
   threshold:15
	});

});

function scrubTrack(offsetIndex){

  var track = video.addTextTrack("captions", "comedy", "en");

  track.mode = "showing";

  //arrays for upcoming cues
  var starttime = [], endtime = [] , text = [] ;

  $selector = $("#comedy li").eq(offsetIndex);

  //making a buffer of 60 seconds from the list-items in the api, storing them in the starttime, endtime and text arrays.
  $selector.each(function(i){
  	starttime[i] = $selector.eq(i).find(".start").text();
  	endtime[i]   = $selector.eq(i).find(".end").text();
  	text[i]      = $selector.eq(i).find(".text").text();
	});

  //console.log(starttime.length, starttime);
  //console.log($selector);

	for (var i = 0; i < starttime.length; i++) {
	  console.log(i, starttime[i], endtime[i], text[i]);
	  //newCue = new VTTCue(starttime[i], endtime[i], text[i]);
	  track.addCue(new VTTCue(starttime[i], endtime[i], text[i]));
    //storing cue ID's in the activeCueIds array - to be used for deletion
	  //activeCueIds[i] = newCue.id;
	}

	/*track.addCue(new VTTCue(0, 12, "Loaded Cues"));
	track.addCue(new VTTCue(18.7, 21.5, "This blade has a dark past."));
	track.addCue(new VTTCue(22.8, 26.8, "It has shed much innocent blood."));
	track.addCue(new VTTCue(29, 32.45, "You're a fool for traveling alone, so completely unprepared."));
	track.addCue(new VTTCue(32.75, 35.8, "You're lucky your blood's still flowing."));
	track.addCue(new VTTCue(36.25, 37.3, "Thank you."));
	track.addCue(new VTTCue(38.5, 40, "So..."));
	track.addCue(new VTTCue(40.4, 44.8, "What brings you to the land of the gatekeepers?"));
	track.addCue(new VTTCue(46, 48.5, "I'm searching for someone."));
	track.addCue(new VTTCue(49, 53.2, "Someone very dear? A kindred spirit?"));
	track.addCue(new VTTCue(54.4, 56, "A dragon."));
	track.addCue(new VTTCue(58.85, 61.75, "A dangerous quest for a lone hunter."));
	track.addCue(new VTTCue(62.95, 65.87, "I've been alone for as long as I can remember."));
	track.addCue(new VTTCue(118.25, 119.5, "We're almost done. Shhh..."));	*/
	//return offsetIndex;
	offsetIndex++;
}

/*laravel specifics? don't know where these came from */

function pinClone() {
	balancelement(".info-panels");
	var ZIDkey_val = $("#info:first").data("todo");
	//$('#ajax-loader-pindu').toggle();
	$('.active').slideToggle();
	var nextactivetodo = $('.active').nextAll('.col-lg-4:first');
	$( ".active" ).remove();
	nextactivetodo.slideToggle().addClass( "active" );

    //Get value and make sure it is not null
	if (ZIDkey_val.length == 0)  window.location.reload();
		$.ajax({
      url: "pages/functions/votes_addupvote.php",
      type: "post",
      dataType:"json",
      data: { ZID_key : ZIDkey_val },
      statusCode: {
          404: function() {
            alert("Big problem! Page not found");
          }
        },
      success: function(data){
    		if (data.bool_flag) {
      		return;
    		} else {
      		console.log(data.message + '  ' + data.dbconn);
      		return;
      		//$('#ajax-loader-pindu').toggle();
      		// window.location.reload();
    		}
      },
      error:function(data){
        console.log(' Function error  ');
        $('#ajax-loader-pindu').toggle();
        //window.location.reload();
      }
    });
  return;
}

function pinRemove() {
	balancelement(".info-panels");
	var ZIDkey_val = $("#info:first").data("todo");
	//$('#ajax-loader-pindu').toggle();
	$('.active').slideToggle();
	var nextactivetodo = $('.active').nextAll('.col-lg-4:first');
	$( ".active" ).remove();
	nextactivetodo.slideToggle().addClass( "active" );

  //Get value and make sure it is not null
	if (ZIDkey_val.length == 0)  window.location.reload();

	$.ajax({
    url: "pages/functions/votes_adddownvote.php",
    type: "post",
    dataType:"json",
		data: { ZID_key : ZIDkey_val },
    statusCode: {
      404: function() {
        alert("Big problem! Page not found");
      }
    },
    success: function(data){
			if (data.bool_flag) {
			return;
			} else {
  			console.log(data.message + '  ' + data.dbconn);
  			return;
  			//$('#ajax-loader-pindu').toggle();
  			// window.location.reload();
			}
    },
    error:function(data){
  		console.log(' Function error  ');
  		$('#ajax-loader-pindu').toggle();
  		//window.location.reload();
    }
  });

return;

}

function visitorSubmit() {
	$('#ajax-loader-visitorSubmit').toggle();
	var ZIDkey_val = $("#visitorTask").val();
	if (ZIDkey_val.length == 0)  window.location.reload();

			$.ajax({
	            url: "pages/functions/tasks_visitors_add.php",
	            type: "post",
	            dataType:"json",
				data: { body_tasks : ZIDkey_val },
	            statusCode: {
	                404: function() {
	                  alert("Big problem! Page not found");
	                }
	              },
	            success: function(data){
					if (data.bool_flag) {
						window.location.assign("./login.html");
						return;
					} else {
						$('#ajax-loader-pindu').toggle();
						console.log(data.message + '  ' + data.dbconn);
						alert(data.message + '  ' + data.dbconn);
						window.location.reload();
						return;
					}
	            },
	            error:function(data){
					console.log(' Function error  ');
					$('#ajax-loader-pindu').toggle();
					//window.location.reload();
	            }
	        });

}

function pinLater() {
	$('#ajax-loader-pindu').toggle();
	//$('#ajax-loader-later').toggle();
	window.location.reload();
}
<|endoftext|>


<commit_before>const path = require('path');

module.exports = {
  "aws_access_key_id":"",
  "aws_secret_access_key":"",
  "aws_s3_bucket":"",
  "capture_dir": path.join(__dirname,'capture'),
  "capture_frequency":60, // in seconds
  "capture_width":1280,   // 1280 or 3280
  "capture_height":1024   // 1024 or 2464,
};
<commit_msg>Removing key and secret attributes from config<commit_after>const path = require('path');

module.exports = {
  "aws_s3_bucket":"809f8c7e-cc23-484a-a3b0-e028084e4e4e",
  "capture_dir": path.join(__dirname,'capture'),
  "capture_frequency":60, // in seconds
  "capture_width":1280,   // 1280 or 3280
  "capture_height":1024   // 1024 or 2464,
};
<|endoftext|>


<commit_before>module.exports = {
    chunkSize: 32,
    horizontalDistance: 2,
    verticalDistance: 2,
    horizontalRemoveDistance: 3,
    verticalRemoveDistance: 3,
    chunkCache: {},

    initialPosition: [16.5, 25.5, 16.5],
    chunkFolder: './chunks/test/',
    server: 'ws://ws.tenten.us',

    textures: [
        {
            value: 1,
            name: 'ground',
            sides: [
                14,
                23, 23, 23, 23,
                3
            ]
        },
        {
            value: 2,
            name: 'brick',
            src: 'http://g.tenten.us/textures/brick.png'
        },
        {
            value: 3,
            name: 'dirt',
            src: 'http://g.tenten.us/textures/dirt.png'
        },
        {
            value: 4,
            name: 'obsidian',
            src: 'http://g.tenten.us/textures/obsidian.png'
        },
        {
            value: 5,
            name: 'whitewool',
            src: 'http://g.tenten.us/textures/whitewool.png'
        },
        {
            value: 6,
            name: 'water',
            src: 'http://g.tenten.us/textures/water.png'
        },
        {
            value: 7,
            name: 'lava',
            src: 'http://g.tenten.us/textures/lava.png'
        },
        {
            value: 8,
            name: 'crate',
            src: 'http://g.tenten.us/textures/crate.png'
        },
        {
            value: 9,
            name: 'brick2',
            src: 'http://g.tenten.us/textures/brick2.png'
        },
        {
            value: 10,
            name: 'brick3',
            src: 'http://g.tenten.us/textures/brick3.png'
        },
        {
            value: 11,
            name: 'cobblestone',
            src: 'http://g.tenten.us/textures/cobblestone.png'
        },
        {
            value: 12,
            name: 'cobblestone2',
            src: 'http://g.tenten.us/textures/cobblestone2.png'
        },
        {
            value: 13,
            name: 'granite',
            src: 'http://g.tenten.us/textures/granite.png'
        },
        {
            value: 14,
            name: 'grass',
            src: 'http://g.tenten.us/textures/grass.png'
        },
        {
            value: 15,
            name: 'grassy cobblestone',
            src: 'http://g.tenten.us/textures/grassy_cobblestone.png'
        },
        {
            value: 16,
            name: 'ice',
            src: 'http://g.tenten.us/textures/ice.png'
        },
        {
            value: 17,
            name: 'long grass',
            src: 'http://g.tenten.us/textures/long_grass.png'
        },
        {
            value: 18,
            name: 'sandstone',
            src: 'http://g.tenten.us/textures/sandstone.png'
        },
        {
            value: 19,
            name: 'slate',
            src: 'http://g.tenten.us/textures/slate.png'
        },
        {
            value: 20,
            name: 'snow2',
            src: 'http://g.tenten.us/textures/sparkly_snow.png'
        },
        {
            value: 21,
            name: 'straw',
            src: 'http://g.tenten.us/textures/straw.png'
        },
        {
            value: 22,
            name: 'wood',
            src: 'http://g.tenten.us/textures/woodsiding.png'
        },
        {
            value: 23,
            name: 'grass+dirt',
            src: 'http://g.tenten.us/textures/grass_dirt.png'
        }
    ]
}<commit_msg>remove config.js<commit_after><|endoftext|>


<commit_before>module.exports = {
    serviceName: "buildImages",
    servicePort: 4100,
    extKeyRequired: false,

    "FILES": __dirname + "/FILES/",
    "deployer": __dirname + "/deployer/",
    "workingDir": "/opt/tmp/",
    "localSrcDir": "/opt/soajs/node_modules/",

    "imagePrefix": {
        "core": "soajsorg/"
    },

    "dockerTemnplates": {
        "nginx": {
            "from": 'FROM soajsorg/basenginx',
            "maintainer": 'MAINTAINER SOAJS Team <team@soajs.org>',
            "body": [
                'RUN mkdir -p /opt/soajs/FILES/profiles && mkdir -p /opt/soajs/deployer && mkdir -p /etc/nginx/ssl',
                'ADD ./deployer /opt/soajs/deployer/',
                'ENV NODE_ENV=production',
                'RUN cd /opt/soajs/deployer/ && npm install',
                'EXPOSE #SERVICEPORT#',
                'CMD ["/bin/bash"]']
        },
        "soajs": {
            "from": 'FROM soajsorg/baseservice',
            "maintainer": 'MAINTAINER SOAJS Team <team@soajs.org>',
            "body": [
                'RUN mkdir -p /opt/soajs/node_modules && mkdir -p /opt/soajs/FILES/profiles && mkdir -p /opt/soajs/deployer',
                'ADD ./deployer /opt/soajs/deployer/',
                'ADD ./FILES /opt/soajs/FILES/',
                'ENV NODE_ENV=production',
                'RUN cd /opt/soajs/deployer/ && npm install',
                'RUN cd /opt/soajs/FILES/soajs && npm install',
                'CMD ["/bin/bash"]']
        },
        "logstash": {
		    "from": 'FROM docker.elastic.co/logstash/logstash:5.3.0',
		    "maintainer": 'MAINTAINER SOAJS Team <team@soajs.org>',
		    "body": [
                'USER root',
                'RUN apt-get update && \\',
                    'apt-get install --fix-missing -y git curl && \\',
                    'curl -sL https://deb.nodesource.com/setup_6.x | bash && \\',
                    'apt-get install --fix-missing -y nodejs',
                'RUN mkdir -p /opt/soajs/deployer',
                'ADD ./deployer /opt/soajs/deployer',
                'RUN cd /opt/soajs/deployer/ && npm install',
			    'CMD ["/bin/bash"]']
	    },
        "filebeat": {
            "from": "FROM ubuntu:16.04",
            "maintainer": "MAINTAINER SOAJS Team <team@soajs.org>",
            "body": [
                'RUN apt-get update && apt-get install -y curl',
                'RUN cd /opt/ && \\',
                    'curl -o filebeat.deb https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-5.3.0-amd64.deb && \\',
                    'dpkg -i filebeat.deb && \\',
                    'rm filebeat.deb',
                'ADD ./FILES/filebeat/filebeat.yml /etc/filebeat/filebeat.yml',
                'CMD ["/bin/bash"]'
            ]
        },
        "metricbeat": {
            "from": "FROM frolvlad/alpine-glibc",
            "maintainer": "MAINTAINER SOAJS Team <team@soajs.org>",
            "body": [
                'ENV METRICBEAT_VERSION=5.3.0',
                'RUN apk add --no-cache ca-certificates curl nodejs nodejs-npm git && mkdir -p /opt/soajs/deployer/',
                'RUN curl -L -O https://artifacts.elastic.co/downloads/beats/metricbeat/metricbeat-${METRICBEAT_VERSION}-linux-x86_64.tar.gz && \\',
                    'tar -xvvf metricbeat-${METRICBEAT_VERSION}-linux-x86_64.tar.gz && \\',
                    'mv metricbeat-${METRICBEAT_VERSION}-linux-x86_64/ /metricbeat && \\',
                    'mv /metricbeat/metricbeat.yml /metricbeat/metricbeat.example.yml && \\',
                    'mv /metricbeat/metricbeat /bin/metricbeat && \\',
                    'chmod +x /bin/metricbeat && \\',
                    'mkdir -p /metricbeat/config /metricbeat/data && \\',
                    'rm metricbeat-${METRICBEAT_VERSION}-linux-x86_64.tar.gz',
                'ADD ./deployer /opt/soajs/deployer/',
                'RUN cd /opt/soajs/deployer/ && npm install',
                'CMD ["/bin/sh"]'
            ]
        },
        "kibana": {
            "from": "FROM kibana:5.3.0",
            "maintainer": "MAINTAINER SOAJS Team <team@soajs.org>",
            "body": [
                'RUN apt-get update && \\',
                    'apt-get install --fix-missing -y git curl && \\',
                    'curl -sL https://deb.nodesource.com/setup_6.x | bash && \\',
                    'apt-get install --fix-missing -y nodejs && \\',
                    'npm install --global bower',
                'WORKDIR /usr/share/kibana/plugins',
                'RUN git clone https://github.com/nreese/kibana-time-plugin.git && \\',
                    'cd /usr/share/kibana/plugins/kibana-time-plugin && \\',
                    'bower install --allow-root',
                'ADD ./FILES/kibana/package.json /usr/share/kibana/plugins/kibana-time-plugin/package.json',
                'RUN mkdir -p /opt/soajs/deployer && mkdir -p /usr/share/kibana/config',
                'ADD ./deployer /opt/soajs/deployer',
                'RUN cd /opt/soajs/deployer && npm install',
                'CMD ["/bin/bash"]'
            ]
        },
        "java": {
            "from": "FROM tomcat:8.0-jre8-alpine",
            "maintainer": "MAINTAINER SOAJS Team <team@soajs.org>",
            "body": [
                'RUN apk add --no-cache curl nodejs nodejs-npm git && mkdir -p /opt/soajs/deployer/',
                'ADD ./deployer /opt/soajs/deployer',
                'RUN cd /opt/soajs/deployer && npm install',
                'CMD ["/bin/sh"]'
            ]
        }
    },

    "errors": {
        "402": "No Uploaded files where detected.",
        "403": "Invalid file uploaded! make sure you zip your service before you upload it."
    },
    "schema": {
    }
};
<commit_msg>Reverted logstash, metricbeat, and kibana images<commit_after>module.exports = {
    serviceName: "buildImages",
    servicePort: 4100,
    extKeyRequired: false,

    "FILES": __dirname + "/FILES/",
    "deployer": __dirname + "/deployer/",
    "workingDir": "/opt/tmp/",
    "localSrcDir": "/opt/soajs/node_modules/",

    "imagePrefix": {
        "core": "soajsorg/"
    },

    "dockerTemnplates": {
        "nginx": {
            "from": 'FROM soajsorg/basenginx',
            "maintainer": 'MAINTAINER SOAJS Team <team@soajs.org>',
            "body": [
                'RUN mkdir -p /opt/soajs/FILES/profiles && mkdir -p /opt/soajs/deployer && mkdir -p /etc/nginx/ssl',
                'ADD ./deployer /opt/soajs/deployer/',
                'ENV NODE_ENV=production',
                'RUN cd /opt/soajs/deployer/ && npm install',
                'EXPOSE #SERVICEPORT#',
                'CMD ["/bin/bash"]']
        },
        "soajs": {
            "from": 'FROM soajsorg/baseservice',
            "maintainer": 'MAINTAINER SOAJS Team <team@soajs.org>',
            "body": [
                'RUN mkdir -p /opt/soajs/node_modules && mkdir -p /opt/soajs/FILES/profiles && mkdir -p /opt/soajs/deployer',
                'ADD ./deployer /opt/soajs/deployer/',
                'ADD ./FILES /opt/soajs/FILES/',
                'ENV NODE_ENV=production',
                'RUN cd /opt/soajs/deployer/ && npm install',
                'RUN cd /opt/soajs/FILES/soajs && npm install',
                'CMD ["/bin/bash"]']
        },
        "logstash": {
		    "from": 'FROM docker.elastic.co/logstash/logstash:5.3.0',
		    "maintainer": 'MAINTAINER SOAJS Team <team@soajs.org>',
		    "body": [
			    'Add ./FILES/logstash/logstash.yml /usr/share/logstash/config/logstash.yml',
			    'Add ./FILES/logstash/logstash.conf /usr/share/logstash/config/logstash.conf',
			    'CMD ["/bin/bash"]']
	    },
        "filebeat": {
            "from": "FROM ubuntu:16.04",
            "maintainer": "MAINTAINER SOAJS Team <team@soajs.org>",
            "body": [
                'RUN apt-get update && apt-get install -y curl',
                'RUN cd /opt/ && \\',
                    'curl -o filebeat.deb https://artifacts.elastic.co/downloads/beats/filebeat/filebeat-5.3.0-amd64.deb && \\',
                    'dpkg -i filebeat.deb && \\',
                    'rm filebeat.deb',
                'ADD ./FILES/filebeat/filebeat.yml /etc/filebeat/filebeat.yml',
                'CMD ["/bin/bash"]'
            ]
        },
        "metricbeat": {
            "from": "FROM frolvlad/alpine-glibc",
            "maintainer": "MAINTAINER SOAJS Team <team@soajs.org>",
            "body": [
                'ENV METRICBEAT_VERSION=5.3.0',
                'RUN apk add --no-cache ca-certificates curl',
                'RUN curl -L -O https://artifacts.elastic.co/downloads/beats/metricbeat/metricbeat-${METRICBEAT_VERSION}-linux-x86_64.tar.gz && \\',
                    'tar -xvvf metricbeat-${METRICBEAT_VERSION}-linux-x86_64.tar.gz && \\',
                    'mv metricbeat-${METRICBEAT_VERSION}-linux-x86_64/ /metricbeat && \\',
                    'mv /metricbeat/metricbeat.yml /metricbeat/metricbeat.example.yml && \\',
                    'mv /metricbeat/metricbeat /bin/metricbeat && \\',
                    'chmod +x /bin/metricbeat && \\',
                    'mkdir -p /metricbeat/config /metricbeat/data && \\',
                    'rm metricbeat-${METRICBEAT_VERSION}-linux-x86_64.tar.gz',
                'WORKDIR /metricbeat',
                'ADD ./FILES/metricbeat/metricbeat.yml /metricbeat/metricbeat.yml',
                'ADD ./FILES/metricbeat/start.sh /metricbeat/start.sh',
                'ENTRYPOINT /metricbeat/start.sh'
            ]
        },
        "kibana": {
           "from": "FROM kibana:5.3.0",
           "maintainer": "MAINTAINER SOAJS Team <team@soajs.org>",
           "body": [
               'RUN apt-get update && \\',
                   'apt-get install --fix-missing -y git curl && \\',
                   'curl -sL https://deb.nodesource.com/setup_6.x | bash && \\',
                   'apt-get install --fix-missing -y nodejs && \\',
                   'npm install --global bower',
               'WORKDIR /usr/share/kibana/plugins',
               'RUN git clone https://github.com/nreese/kibana-time-plugin.git && \\',
                   'cd /usr/share/kibana/plugins/kibana-time-plugin && \\',
                   'bower install --allow-root',
               'ADD ./FILES/kibana/package.json /usr/share/kibana/plugins/kibana-time-plugin/package.json'
           ]
       },
        "java": {
            "from": "FROM tomcat:8.0-jre8-alpine",
            "maintainer": "MAINTAINER SOAJS Team <team@soajs.org>",
            "body": [
                'RUN apk add --no-cache curl nodejs nodejs-npm git && mkdir -p /opt/soajs/deployer/',
                'ADD ./deployer /opt/soajs/deployer',
                'RUN cd /opt/soajs/deployer && npm install',
                'CMD ["/bin/sh"]'
            ]
        }
    },

    "errors": {
        "402": "No Uploaded files where detected.",
        "403": "Invalid file uploaded! make sure you zip your service before you upload it."
    },
    "schema": {
    }
};
<|endoftext|>