Return fields of mapper object as an associative array
+
Returns
array
+
Parameters
+
+
$obj
object
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::copyfrom
+
(
+
+
$key,
+
+
+
+
+
+
$func = NULL
+
+
+
+
)
+
+
+
+
+
+abstract
+
+
+
+
Hydrate mapper object using hive array variable
+
Returns
NULL
+
Parameters
+
+
$key
string
+
$func
callback
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::copyto
+
(
+
+
$key
)
+
+
+
+
+
+abstract
+
+
+
+
Populate hive array variable with mapper fields
+
Returns
NULL
+
Parameters
+
+
$key
string
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::count
+
(
+
+
$filter = NULL,
+
+
+
+
+
+
$ttl = 0
+
+
+
+
)
+
+
+
+
+
+abstract
+
+
+
+
Count records that match criteria
+
Returns
int
+
Parameters
+
+
$filter
array
+
$ttl
int
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::dbtype
+
(
+
)
+
+
+
+
+
+abstract
+
+
+
+
Return database type
+
Returns
string
+
+
+
+
+
+
+
+
+
DB\Cursor::dry
+
(
+
)
+
+
+
+
+
Return TRUE if current cursor position is not mapped to any record
+
Returns
bool
+
+
+
+
+
+
+
+
+
DB\Cursor::erase
+
(
+
)
+
+
+
+
+
Delete current record
+
Returns
int|bool
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::find
+
(
+
+
$filter = NULL,
+
+
+
+
+
array
+
$options = NULL,
+
+
+
+
+
+
$ttl = 0
+
+
+
+
)
+
+
+
+
+
+abstract
+
+
+
+
Return records (array of mapper objects) that match criteria
+
Returns
array
+
Parameters
+
+
$filter
string|array
+
$options
array
+
$ttl
int
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::findone
+
(
+
+
$filter = NULL,
+
+
+
+
+
array
+
$options = NULL,
+
+
+
+
+
+
$ttl = 0
+
+
+
+
)
+
+
+
+
+
Return first record (mapper object) that matches criteria
+
Returns
object|FALSE
+
Parameters
+
+
$filter
string|array
+
$options
array
+
$ttl
int
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::first
+
(
+
)
+
+
+
+
+
Map to first record in cursor
+
Returns
mixed
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::insert
+
(
+
)
+
+
+
+
+
+abstract
+
+
+
+
Insert new record
+
Returns
array
+
+
+
+
+
+
+
+
+
DB\Cursor::last
+
(
+
)
+
+
+
+
+
Map to last record in cursor
+
Returns
mixed
+
+
+
+
+
+
+
+
+
DB\Cursor::load
+
(
+
+
$filter = NULL,
+
+
+
+
+
array
+
$options = NULL,
+
+
+
+
+
+
$ttl = 0
+
+
+
+
)
+
+
+
+
+
Map to first record that matches criteria
+
Returns
array|FALSE
+
Parameters
+
+
$filter
string|array
+
$options
array
+
$ttl
int
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::next
+
(
+
)
+
+
+
+
+
Map next record
+
Returns
mixed
+
+
+
+
+
+
+
+
+
DB\Cursor::onerase
+
(
+
+
$func
)
+
+
+
+
+
Define onerase trigger
+
Returns
callback
+
Parameters
+
+
$func
callback
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::oninsert
+
(
+
+
$func
)
+
+
+
+
+
Define oninsert trigger
+
Returns
callback
+
Parameters
+
+
$func
callback
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::onload
+
(
+
+
$func
)
+
+
+
+
+
Define onload trigger
+
Returns
callback
+
Parameters
+
+
$func
callback
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::onupdate
+
(
+
+
$func
)
+
+
+
+
+
Define onupdate trigger
+
Returns
callback
+
Parameters
+
+
$func
callback
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::paginate
+
(
+
+
$pos = 0,
+
+
+
+
+
+
$size = 10,
+
+
+
+
+
+
$filter = NULL,
+
+
+
+
+
array
+
$options = NULL,
+
+
+
+
+
+
$ttl = 0
+
+
+
+
)
+
+
+
+
+
Return array containing subset of records matching criteria, total number of records in superset, specified limit, number of subsets available, and actual subset position
+
Returns
array
+
Parameters
+
+
$pos
int
+
$size
int
+
$filter
string|array
+
$options
array
+
$ttl
int
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::prev
+
(
+
)
+
+
+
+
+
Map previous record
+
Returns
mixed
+
+
+
+
+
+
+
+
+
DB\Cursor::reset
+
(
+
)
+
+
+
+
+
Reset cursor
+
Returns
NULL
+
+
+
+
+
+
+
+
+
DB\Cursor::save
+
(
+
)
+
+
+
+
+
Save mapped record
+
Returns
mixed
+
+
+
+
+
+
+
+
+
DB\Cursor::skip
+
(
+
+
$ofs = 1
)
+
+
+
+
+
Map to nth record relative to current cursor position
+
Returns
mixed
+
Parameters
+
+
$ofs
int
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
DB\Cursor::update
+
(
+
)
+
+
+
+
+
+abstract
+
+
+
+
Update current record
+
Returns
array
+
+
+
+The documentation for this class was generated from the following file:
+
db/cursor.php
+
+
diff --git a/management-interface/lib/api/classDB_1_1Cursor.png b/management-interface/lib/api/classDB_1_1Cursor.png
new file mode 100644
index 0000000..858faba
Binary files /dev/null and b/management-interface/lib/api/classDB_1_1Cursor.png differ
diff --git a/management-interface/lib/api/classDB_1_1Jig-members.html b/management-interface/lib/api/classDB_1_1Jig-members.html
new file mode 100644
index 0000000..53e9e59
--- /dev/null
+++ b/management-interface/lib/api/classDB_1_1Jig-members.html
@@ -0,0 +1,59 @@
+
+
+
+
+
+
+
+Fat-Free Framework: Member List
+
+
+
+
+
+
+
Return the MIME types stated in the HTTP Accept header as an array; If a list of MIME types is specified, return the best match; or FALSE if none found
+
Returns
array|string|FALSE
+
Parameters
+
+
$list
string|array
+
+
+
+
+
+
+
+
+
+
+
+
Web::engine
+
(
+
+
$arg = 'curl'
)
+
+
+
+
+
Specify the HTTP request engine to use; If not available, fall back to an applicable substitute
+
Returns
string
+
Parameters
+
+
$arg
string
+
+
+
+
+
+
+
+
+
+
+
+
Web::filler
+
(
+
+
$count = 1,
+
+
+
+
+
+
$max = 20,
+
+
+
+
+
+
$std = TRUE
+
+
+
+
)
+
+
+
+
+
Return chunk of text from standard Lorem Ipsum passage
+
Returns
string
+
Parameters
+
+
$count
int
+
$max
int
+
$std
bool
+
+
+
+
+
+
+
+
+
+
+
+
Web::mime
+
(
+
+
$file
)
+
+
+
+
+
Detect MIME type using file extension
+
Returns
string
+
Parameters
+
+
$file
string
+
+
+
+
+
+
+
+
+
+
+
+
Web::minify
+
(
+
+
$files,
+
+
+
+
+
+
$mime = NULL,
+
+
+
+
+
+
$header = TRUE,
+
+
+
+
+
+
$path = ''
+
+
+
+
)
+
+
+
+
+
Strip Javascript/CSS files of extraneous whitespaces and comments; Return combined output as a minified string
A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!
+
Condensed in a single ~50KB file, F3 (as we fondly call it) gives you solid foundation, a mature code base, and a no-nonsense approach to writing Web applications. Under the hood is an easy-to-use Web development tool kit, a high-performance URL routing and cache engine, built-in code highlighting, and support for multilingual applications. It's lightweight, easy-to-use, and fast. Most of all, it doesn't get in your way.
+
Whether you're a novice or an expert PHP programmer, F3 will get you up and running in no time. No unnecessary and painstaking installation procedures. No complex configuration required. No convoluted directory structures. There's no better time to start developing Web applications the easy way than right now!
+
F3 supports both SQL and NoSQL databases off-the-shelf: MySQL, SQLite, MSSQL/Sybase, PostgreSQL, DB2, and MongoDB. It also comes with powerful object-relational mappers for data abstraction and modeling that are just as lightweight as the framework. No configuration needed.
+
Unlike other frameworks, F3 aims to be usable - not usual.
+
The philosophy behind the framework and its approach to software architecture is towards minimalism in structural components, avoiding application complexity and striking a balance between code elegance, application performance and programmer productivity.
+
diff --git a/management-interface/lib/api/jquery.js b/management-interface/lib/api/jquery.js
new file mode 100644
index 0000000..c197801
--- /dev/null
+++ b/management-interface/lib/api/jquery.js
@@ -0,0 +1,31 @@
+/*!
+ * jQuery JavaScript Library v1.7.1
+ * http://jquery.com/
+ *
+ * Copyright 2011, John Resig
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ * http://jquery.org/license
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ * Copyright 2011, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ *
+ * Date: Mon Nov 21 21:11:03 2011 -0500
+ */
+(function(bb,L){var av=bb.document,bu=bb.navigator,bl=bb.location;var b=(function(){var bF=function(b0,b1){return new bF.fn.init(b0,b1,bD)},bU=bb.jQuery,bH=bb.$,bD,bY=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,bM=/\S/,bI=/^\s+/,bE=/\s+$/,bA=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,bN=/^[\],:{}\s]*$/,bW=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,bP=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,bJ=/(?:^|:|,)(?:\s*\[)+/g,by=/(webkit)[ \/]([\w.]+)/,bR=/(opera)(?:.*version)?[ \/]([\w.]+)/,bQ=/(msie) ([\w.]+)/,bS=/(mozilla)(?:.*? rv:([\w.]+))?/,bB=/-([a-z]|[0-9])/ig,bZ=/^-ms-/,bT=function(b0,b1){return(b1+"").toUpperCase()},bX=bu.userAgent,bV,bC,e,bL=Object.prototype.toString,bG=Object.prototype.hasOwnProperty,bz=Array.prototype.push,bK=Array.prototype.slice,bO=String.prototype.trim,bv=Array.prototype.indexOf,bx={};bF.fn=bF.prototype={constructor:bF,init:function(b0,b4,b3){var b2,b5,b1,b6;if(!b0){return this}if(b0.nodeType){this.context=this[0]=b0;this.length=1;return this}if(b0==="body"&&!b4&&av.body){this.context=av;this[0]=av.body;this.selector=b0;this.length=1;return this}if(typeof b0==="string"){if(b0.charAt(0)==="<"&&b0.charAt(b0.length-1)===">"&&b0.length>=3){b2=[null,b0,null]}else{b2=bY.exec(b0)}if(b2&&(b2[1]||!b4)){if(b2[1]){b4=b4 instanceof bF?b4[0]:b4;b6=(b4?b4.ownerDocument||b4:av);b1=bA.exec(b0);if(b1){if(bF.isPlainObject(b4)){b0=[av.createElement(b1[1])];bF.fn.attr.call(b0,b4,true)}else{b0=[b6.createElement(b1[1])]}}else{b1=bF.buildFragment([b2[1]],[b6]);b0=(b1.cacheable?bF.clone(b1.fragment):b1.fragment).childNodes}return bF.merge(this,b0)}else{b5=av.getElementById(b2[2]);if(b5&&b5.parentNode){if(b5.id!==b2[2]){return b3.find(b0)}this.length=1;this[0]=b5}this.context=av;this.selector=b0;return this}}else{if(!b4||b4.jquery){return(b4||b3).find(b0)}else{return this.constructor(b4).find(b0)}}}else{if(bF.isFunction(b0)){return b3.ready(b0)}}if(b0.selector!==L){this.selector=b0.selector;this.context=b0.context}return bF.makeArray(b0,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return bK.call(this,0)},get:function(b0){return b0==null?this.toArray():(b0<0?this[this.length+b0]:this[b0])},pushStack:function(b1,b3,b0){var b2=this.constructor();if(bF.isArray(b1)){bz.apply(b2,b1)}else{bF.merge(b2,b1)}b2.prevObject=this;b2.context=this.context;if(b3==="find"){b2.selector=this.selector+(this.selector?" ":"")+b0}else{if(b3){b2.selector=this.selector+"."+b3+"("+b0+")"}}return b2},each:function(b1,b0){return bF.each(this,b1,b0)},ready:function(b0){bF.bindReady();bC.add(b0);return this},eq:function(b0){b0=+b0;return b0===-1?this.slice(b0):this.slice(b0,b0+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(bK.apply(this,arguments),"slice",bK.call(arguments).join(","))},map:function(b0){return this.pushStack(bF.map(this,function(b2,b1){return b0.call(b2,b1,b2)}))},end:function(){return this.prevObject||this.constructor(null)},push:bz,sort:[].sort,splice:[].splice};bF.fn.init.prototype=bF.fn;bF.extend=bF.fn.extend=function(){var b9,b2,b0,b1,b6,b7,b5=arguments[0]||{},b4=1,b3=arguments.length,b8=false;if(typeof b5==="boolean"){b8=b5;b5=arguments[1]||{};b4=2}if(typeof b5!=="object"&&!bF.isFunction(b5)){b5={}}if(b3===b4){b5=this;--b4}for(;b40){return}bC.fireWith(av,[bF]);if(bF.fn.trigger){bF(av).trigger("ready").off("ready")}}},bindReady:function(){if(bC){return}bC=bF.Callbacks("once memory");if(av.readyState==="complete"){return setTimeout(bF.ready,1)}if(av.addEventListener){av.addEventListener("DOMContentLoaded",e,false);bb.addEventListener("load",bF.ready,false)}else{if(av.attachEvent){av.attachEvent("onreadystatechange",e);bb.attachEvent("onload",bF.ready);var b0=false;try{b0=bb.frameElement==null}catch(b1){}if(av.documentElement.doScroll&&b0){bw()}}}},isFunction:function(b0){return bF.type(b0)==="function"},isArray:Array.isArray||function(b0){return bF.type(b0)==="array"},isWindow:function(b0){return b0&&typeof b0==="object"&&"setInterval" in b0},isNumeric:function(b0){return !isNaN(parseFloat(b0))&&isFinite(b0)},type:function(b0){return b0==null?String(b0):bx[bL.call(b0)]||"object"},isPlainObject:function(b2){if(!b2||bF.type(b2)!=="object"||b2.nodeType||bF.isWindow(b2)){return false}try{if(b2.constructor&&!bG.call(b2,"constructor")&&!bG.call(b2.constructor.prototype,"isPrototypeOf")){return false}}catch(b1){return false}var b0;for(b0 in b2){}return b0===L||bG.call(b2,b0)},isEmptyObject:function(b1){for(var b0 in b1){return false}return true},error:function(b0){throw new Error(b0)},parseJSON:function(b0){if(typeof b0!=="string"||!b0){return null}b0=bF.trim(b0);if(bb.JSON&&bb.JSON.parse){return bb.JSON.parse(b0)}if(bN.test(b0.replace(bW,"@").replace(bP,"]").replace(bJ,""))){return(new Function("return "+b0))()}bF.error("Invalid JSON: "+b0)},parseXML:function(b2){var b0,b1;try{if(bb.DOMParser){b1=new DOMParser();b0=b1.parseFromString(b2,"text/xml")}else{b0=new ActiveXObject("Microsoft.XMLDOM");b0.async="false";b0.loadXML(b2)}}catch(b3){b0=L}if(!b0||!b0.documentElement||b0.getElementsByTagName("parsererror").length){bF.error("Invalid XML: "+b2)}return b0},noop:function(){},globalEval:function(b0){if(b0&&bM.test(b0)){(bb.execScript||function(b1){bb["eval"].call(bb,b1)})(b0)}},camelCase:function(b0){return b0.replace(bZ,"ms-").replace(bB,bT)},nodeName:function(b1,b0){return b1.nodeName&&b1.nodeName.toUpperCase()===b0.toUpperCase()},each:function(b3,b6,b2){var b1,b4=0,b5=b3.length,b0=b5===L||bF.isFunction(b3);if(b2){if(b0){for(b1 in b3){if(b6.apply(b3[b1],b2)===false){break}}}else{for(;b40&&b0[0]&&b0[b1-1])||b1===0||bF.isArray(b0));if(b3){for(;b21?aJ.call(arguments,0):bG;if(!(--bw)){bC.resolveWith(bC,bx)}}}function bz(bF){return function(bG){bB[bF]=arguments.length>1?aJ.call(arguments,0):bG;bC.notifyWith(bE,bB)}}if(e>1){for(;bv
a";bI=bv.getElementsByTagName("*");bF=bv.getElementsByTagName("a")[0];if(!bI||!bI.length||!bF){return{}}bG=av.createElement("select");bx=bG.appendChild(av.createElement("option"));bE=bv.getElementsByTagName("input")[0];bJ={leadingWhitespace:(bv.firstChild.nodeType===3),tbody:!bv.getElementsByTagName("tbody").length,htmlSerialize:!!bv.getElementsByTagName("link").length,style:/top/.test(bF.getAttribute("style")),hrefNormalized:(bF.getAttribute("href")==="/a"),opacity:/^0.55/.test(bF.style.opacity),cssFloat:!!bF.style.cssFloat,checkOn:(bE.value==="on"),optSelected:bx.selected,getSetAttribute:bv.className!=="t",enctype:!!av.createElement("form").enctype,html5Clone:av.createElement("nav").cloneNode(true).outerHTML!=="<:nav>",submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true};bE.checked=true;bJ.noCloneChecked=bE.cloneNode(true).checked;bG.disabled=true;bJ.optDisabled=!bx.disabled;try{delete bv.test}catch(bC){bJ.deleteExpando=false}if(!bv.addEventListener&&bv.attachEvent&&bv.fireEvent){bv.attachEvent("onclick",function(){bJ.noCloneEvent=false});bv.cloneNode(true).fireEvent("onclick")}bE=av.createElement("input");bE.value="t";bE.setAttribute("type","radio");bJ.radioValue=bE.value==="t";bE.setAttribute("checked","checked");bv.appendChild(bE);bD=av.createDocumentFragment();bD.appendChild(bv.lastChild);bJ.checkClone=bD.cloneNode(true).cloneNode(true).lastChild.checked;bJ.appendChecked=bE.checked;bD.removeChild(bE);bD.appendChild(bv);bv.innerHTML="";if(bb.getComputedStyle){bA=av.createElement("div");bA.style.width="0";bA.style.marginRight="0";bv.style.width="2px";bv.appendChild(bA);bJ.reliableMarginRight=(parseInt((bb.getComputedStyle(bA,null)||{marginRight:0}).marginRight,10)||0)===0}if(bv.attachEvent){for(by in {submit:1,change:1,focusin:1}){bB="on"+by;bw=(bB in bv);if(!bw){bv.setAttribute(bB,"return;");bw=(typeof bv[bB]==="function")}bJ[by+"Bubbles"]=bw}}bD.removeChild(bv);bD=bG=bx=bA=bv=bE=null;b(function(){var bM,bU,bV,bT,bN,bO,bL,bS,bR,e,bP,bQ=av.getElementsByTagName("body")[0];if(!bQ){return}bL=1;bS="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";bR="visibility:hidden;border:0;";e="style='"+bS+"border:5px solid #000;padding:0;'";bP="
").append(bD.replace(a6,"")).find(e):bD)}if(bA){bv.each(bA,[bD,bB,bC])}}});return this},serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?b.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||q.test(this.nodeName)||aZ.test(this.type))}).map(function(e,bv){var bw=b(this).val();return bw==null?null:b.isArray(bw)?b.map(bw,function(by,bx){return{name:bv.name,value:by.replace(bs,"\r\n")}}):{name:bv.name,value:bw.replace(bs,"\r\n")}}).get()}});b.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,bv){b.fn[bv]=function(bw){return this.on(bv,bw)}});b.each(["get","post"],function(e,bv){b[bv]=function(bw,by,bz,bx){if(b.isFunction(by)){bx=bx||bz;bz=by;by=L}return b.ajax({type:bv,url:bw,data:by,success:bz,dataType:bx})}});b.extend({getScript:function(e,bv){return b.get(e,L,bv,"script")},getJSON:function(e,bv,bw){return b.get(e,bv,bw,"json")},ajaxSetup:function(bv,e){if(e){am(bv,b.ajaxSettings)}else{e=bv;bv=b.ajaxSettings}am(bv,e);return bv},ajaxSettings:{url:aE,isLocal:aM.test(s[1]),global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":aV},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":bb.String,"text html":true,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{context:true,url:true}},ajaxPrefilter:f(aa),ajaxTransport:f(r),ajax:function(bz,bx){if(typeof bz==="object"){bx=bz;bz=L}bx=bx||{};var bD=b.ajaxSetup({},bx),bS=bD.context||bD,bG=bS!==bD&&(bS.nodeType||bS instanceof b)?b(bS):b.event,bR=b.Deferred(),bN=b.Callbacks("once memory"),bB=bD.statusCode||{},bC,bH={},bO={},bQ,by,bL,bE,bI,bA=0,bw,bK,bJ={readyState:0,setRequestHeader:function(bT,bU){if(!bA){var e=bT.toLowerCase();bT=bO[e]=bO[e]||bT;bH[bT]=bU}return this},getAllResponseHeaders:function(){return bA===2?bQ:null},getResponseHeader:function(bT){var e;if(bA===2){if(!by){by={};while((e=aD.exec(bQ))){by[e[1].toLowerCase()]=e[2]}}e=by[bT.toLowerCase()]}return e===L?null:e},overrideMimeType:function(e){if(!bA){bD.mimeType=e}return this},abort:function(e){e=e||"abort";if(bL){bL.abort(e)}bF(0,e);return this}};function bF(bZ,bU,b0,bW){if(bA===2){return}bA=2;if(bE){clearTimeout(bE)}bL=L;bQ=bW||"";bJ.readyState=bZ>0?4:0;var bT,b4,b3,bX=bU,bY=b0?bj(bD,bJ,b0):L,bV,b2;if(bZ>=200&&bZ<300||bZ===304){if(bD.ifModified){if((bV=bJ.getResponseHeader("Last-Modified"))){b.lastModified[bC]=bV}if((b2=bJ.getResponseHeader("Etag"))){b.etag[bC]=b2}}if(bZ===304){bX="notmodified";bT=true}else{try{b4=G(bD,bY);bX="success";bT=true}catch(b1){bX="parsererror";b3=b1}}}else{b3=bX;if(!bX||bZ){bX="error";if(bZ<0){bZ=0}}}bJ.status=bZ;bJ.statusText=""+(bU||bX);if(bT){bR.resolveWith(bS,[b4,bX,bJ])}else{bR.rejectWith(bS,[bJ,bX,b3])}bJ.statusCode(bB);bB=L;if(bw){bG.trigger("ajax"+(bT?"Success":"Error"),[bJ,bD,bT?b4:b3])}bN.fireWith(bS,[bJ,bX]);if(bw){bG.trigger("ajaxComplete",[bJ,bD]);if(!(--b.active)){b.event.trigger("ajaxStop")}}}bR.promise(bJ);bJ.success=bJ.done;bJ.error=bJ.fail;bJ.complete=bN.add;bJ.statusCode=function(bT){if(bT){var e;if(bA<2){for(e in bT){bB[e]=[bB[e],bT[e]]}}else{e=bT[bJ.status];bJ.then(e,e)}}return this};bD.url=((bz||bD.url)+"").replace(bq,"").replace(c,s[1]+"//");bD.dataTypes=b.trim(bD.dataType||"*").toLowerCase().split(h);if(bD.crossDomain==null){bI=K.exec(bD.url.toLowerCase());bD.crossDomain=!!(bI&&(bI[1]!=s[1]||bI[2]!=s[2]||(bI[3]||(bI[1]==="http:"?80:443))!=(s[3]||(s[1]==="http:"?80:443))))}if(bD.data&&bD.processData&&typeof bD.data!=="string"){bD.data=b.param(bD.data,bD.traditional)}aW(aa,bD,bx,bJ);if(bA===2){return false}bw=bD.global;bD.type=bD.type.toUpperCase();bD.hasContent=!aQ.test(bD.type);if(bw&&b.active++===0){b.event.trigger("ajaxStart")}if(!bD.hasContent){if(bD.data){bD.url+=(M.test(bD.url)?"&":"?")+bD.data;delete bD.data}bC=bD.url;if(bD.cache===false){var bv=b.now(),bP=bD.url.replace(br,"$1_="+bv);bD.url=bP+((bP===bD.url)?(M.test(bD.url)?"&":"?")+"_="+bv:"")}}if(bD.data&&bD.hasContent&&bD.contentType!==false||bx.contentType){bJ.setRequestHeader("Content-Type",bD.contentType)}if(bD.ifModified){bC=bC||bD.url;if(b.lastModified[bC]){bJ.setRequestHeader("If-Modified-Since",b.lastModified[bC])}if(b.etag[bC]){bJ.setRequestHeader("If-None-Match",b.etag[bC])}}bJ.setRequestHeader("Accept",bD.dataTypes[0]&&bD.accepts[bD.dataTypes[0]]?bD.accepts[bD.dataTypes[0]]+(bD.dataTypes[0]!=="*"?", "+aV+"; q=0.01":""):bD.accepts["*"]);for(bK in bD.headers){bJ.setRequestHeader(bK,bD.headers[bK])}if(bD.beforeSend&&(bD.beforeSend.call(bS,bJ,bD)===false||bA===2)){bJ.abort();return false}for(bK in {success:1,error:1,complete:1}){bJ[bK](bD[bK])}bL=aW(r,bD,bx,bJ);if(!bL){bF(-1,"No Transport")}else{bJ.readyState=1;if(bw){bG.trigger("ajaxSend",[bJ,bD])}if(bD.async&&bD.timeout>0){bE=setTimeout(function(){bJ.abort("timeout")},bD.timeout)}try{bA=1;bL.send(bH,bF)}catch(bM){if(bA<2){bF(-1,bM)}else{throw bM}}}return bJ},param:function(e,bw){var bv=[],by=function(bz,bA){bA=b.isFunction(bA)?bA():bA;bv[bv.length]=encodeURIComponent(bz)+"="+encodeURIComponent(bA)};if(bw===L){bw=b.ajaxSettings.traditional}if(b.isArray(e)||(e.jquery&&!b.isPlainObject(e))){b.each(e,function(){by(this.name,this.value)})}else{for(var bx in e){v(bx,e[bx],bw,by)}}return bv.join("&").replace(k,"+")}});function v(bw,by,bv,bx){if(b.isArray(by)){b.each(by,function(bA,bz){if(bv||ap.test(bw)){bx(bw,bz)}else{v(bw+"["+(typeof bz==="object"||b.isArray(bz)?bA:"")+"]",bz,bv,bx)}})}else{if(!bv&&by!=null&&typeof by==="object"){for(var e in by){v(bw+"["+e+"]",by[e],bv,bx)}}else{bx(bw,by)}}}b.extend({active:0,lastModified:{},etag:{}});function bj(bD,bC,bz){var bv=bD.contents,bB=bD.dataTypes,bw=bD.responseFields,by,bA,bx,e;for(bA in bw){if(bA in bz){bC[bw[bA]]=bz[bA]}}while(bB[0]==="*"){bB.shift();if(by===L){by=bD.mimeType||bC.getResponseHeader("content-type")}}if(by){for(bA in bv){if(bv[bA]&&bv[bA].test(by)){bB.unshift(bA);break}}}if(bB[0] in bz){bx=bB[0]}else{for(bA in bz){if(!bB[0]||bD.converters[bA+" "+bB[0]]){bx=bA;break}if(!e){e=bA}}bx=bx||e}if(bx){if(bx!==bB[0]){bB.unshift(bx)}return bz[bx]}}function G(bH,bz){if(bH.dataFilter){bz=bH.dataFilter(bz,bH.dataType)}var bD=bH.dataTypes,bG={},bA,bE,bw=bD.length,bB,bC=bD[0],bx,by,bF,bv,e;for(bA=1;bA=bw.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();bw.animatedProperties[this.prop]=true;for(bA in bw.animatedProperties){if(bw.animatedProperties[bA]!==true){e=false}}if(e){if(bw.overflow!=null&&!b.support.shrinkWrapBlocks){b.each(["","X","Y"],function(bC,bD){bz.style["overflow"+bD]=bw.overflow[bC]})}if(bw.hide){b(bz).hide()}if(bw.hide||bw.show){for(bA in bw.animatedProperties){b.style(bz,bA,bw.orig[bA]);b.removeData(bz,"fxshow"+bA,true);b.removeData(bz,"toggle"+bA,true)}}bv=bw.complete;if(bv){bw.complete=false;bv.call(bz)}}return false}else{if(bw.duration==Infinity){this.now=bx}else{bB=bx-this.startTime;this.state=bB/bw.duration;this.pos=b.easing[bw.animatedProperties[this.prop]](this.state,bB,0,1,bw.duration);this.now=this.start+((this.end-this.start)*this.pos)}this.update()}return true}};b.extend(b.fx,{tick:function(){var bw,bv=b.timers,e=0;for(;e").appendTo(e),bw=bv.css("display");bv.remove();if(bw==="none"||bw===""){if(!a8){a8=av.createElement("iframe");a8.frameBorder=a8.width=a8.height=0}e.appendChild(a8);if(!m||!a8.createElement){m=(a8.contentWindow||a8.contentDocument).document;m.write((av.compatMode==="CSS1Compat"?"":"")+"");m.close()}bv=m.createElement(bx);m.body.appendChild(bv);bw=b.css(bv,"display");e.removeChild(a8)}Q[bx]=bw}return Q[bx]}var V=/^t(?:able|d|h)$/i,ad=/^(?:body|html)$/i;if("getBoundingClientRect" in av.documentElement){b.fn.offset=function(bI){var by=this[0],bB;if(bI){return this.each(function(e){b.offset.setOffset(this,bI,e)})}if(!by||!by.ownerDocument){return null}if(by===by.ownerDocument.body){return b.offset.bodyOffset(by)}try{bB=by.getBoundingClientRect()}catch(bF){}var bH=by.ownerDocument,bw=bH.documentElement;if(!bB||!b.contains(bw,by)){return bB?{top:bB.top,left:bB.left}:{top:0,left:0}}var bC=bH.body,bD=aK(bH),bA=bw.clientTop||bC.clientTop||0,bE=bw.clientLeft||bC.clientLeft||0,bv=bD.pageYOffset||b.support.boxModel&&bw.scrollTop||bC.scrollTop,bz=bD.pageXOffset||b.support.boxModel&&bw.scrollLeft||bC.scrollLeft,bG=bB.top+bv-bA,bx=bB.left+bz-bE;return{top:bG,left:bx}}}else{b.fn.offset=function(bF){var bz=this[0];if(bF){return this.each(function(bG){b.offset.setOffset(this,bF,bG)})}if(!bz||!bz.ownerDocument){return null}if(bz===bz.ownerDocument.body){return b.offset.bodyOffset(bz)}var bC,bw=bz.offsetParent,bv=bz,bE=bz.ownerDocument,bx=bE.documentElement,bA=bE.body,bB=bE.defaultView,e=bB?bB.getComputedStyle(bz,null):bz.currentStyle,bD=bz.offsetTop,by=bz.offsetLeft;while((bz=bz.parentNode)&&bz!==bA&&bz!==bx){if(b.support.fixedPosition&&e.position==="fixed"){break}bC=bB?bB.getComputedStyle(bz,null):bz.currentStyle;bD-=bz.scrollTop;by-=bz.scrollLeft;if(bz===bw){bD+=bz.offsetTop;by+=bz.offsetLeft;if(b.support.doesNotAddBorder&&!(b.support.doesAddBorderForTableAndCells&&V.test(bz.nodeName))){bD+=parseFloat(bC.borderTopWidth)||0;by+=parseFloat(bC.borderLeftWidth)||0}bv=bw;bw=bz.offsetParent}if(b.support.subtractsBorderForOverflowNotVisible&&bC.overflow!=="visible"){bD+=parseFloat(bC.borderTopWidth)||0;by+=parseFloat(bC.borderLeftWidth)||0}e=bC}if(e.position==="relative"||e.position==="static"){bD+=bA.offsetTop;by+=bA.offsetLeft}if(b.support.fixedPosition&&e.position==="fixed"){bD+=Math.max(bx.scrollTop,bA.scrollTop);by+=Math.max(bx.scrollLeft,bA.scrollLeft)}return{top:bD,left:by}}}b.offset={bodyOffset:function(e){var bw=e.offsetTop,bv=e.offsetLeft;if(b.support.doesNotIncludeMarginInBodyOffset){bw+=parseFloat(b.css(e,"marginTop"))||0;bv+=parseFloat(b.css(e,"marginLeft"))||0}return{top:bw,left:bv}},setOffset:function(bx,bG,bA){var bB=b.css(bx,"position");if(bB==="static"){bx.style.position="relative"}var bz=b(bx),bv=bz.offset(),e=b.css(bx,"top"),bE=b.css(bx,"left"),bF=(bB==="absolute"||bB==="fixed")&&b.inArray("auto",[e,bE])>-1,bD={},bC={},bw,by;if(bF){bC=bz.position();bw=bC.top;by=bC.left}else{bw=parseFloat(e)||0;by=parseFloat(bE)||0}if(b.isFunction(bG)){bG=bG.call(bx,bA,bv)}if(bG.top!=null){bD.top=(bG.top-bv.top)+bw}if(bG.left!=null){bD.left=(bG.left-bv.left)+by}if("using" in bG){bG.using.call(bx,bD)}else{bz.css(bD)}}};b.fn.extend({position:function(){if(!this[0]){return null}var bw=this[0],bv=this.offsetParent(),bx=this.offset(),e=ad.test(bv[0].nodeName)?{top:0,left:0}:bv.offset();bx.top-=parseFloat(b.css(bw,"marginTop"))||0;bx.left-=parseFloat(b.css(bw,"marginLeft"))||0;e.top+=parseFloat(b.css(bv[0],"borderTopWidth"))||0;e.left+=parseFloat(b.css(bv[0],"borderLeftWidth"))||0;return{top:bx.top-e.top,left:bx.left-e.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||av.body;while(e&&(!ad.test(e.nodeName)&&b.css(e,"position")==="static")){e=e.offsetParent}return e})}});b.each(["Left","Top"],function(bv,e){var bw="scroll"+e;b.fn[bw]=function(bz){var bx,by;if(bz===L){bx=this[0];if(!bx){return null}by=aK(bx);return by?("pageXOffset" in by)?by[bv?"pageYOffset":"pageXOffset"]:b.support.boxModel&&by.document.documentElement[bw]||by.document.body[bw]:bx[bw]}return this.each(function(){by=aK(this);if(by){by.scrollTo(!bv?bz:b(by).scrollLeft(),bv?bz:b(by).scrollTop())}else{this[bw]=bz}})}});function aK(e){return b.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}b.each(["Height","Width"],function(bv,e){var bw=e.toLowerCase();b.fn["inner"+e]=function(){var bx=this[0];return bx?bx.style?parseFloat(b.css(bx,bw,"padding")):this[bw]():null};b.fn["outer"+e]=function(by){var bx=this[0];return bx?bx.style?parseFloat(b.css(bx,bw,by?"margin":"border")):this[bw]():null};b.fn[bw]=function(bz){var bA=this[0];if(!bA){return bz==null?null:this}if(b.isFunction(bz)){return this.each(function(bE){var bD=b(this);bD[bw](bz.call(this,bE,bD[bw]()))})}if(b.isWindow(bA)){var bB=bA.document.documentElement["client"+e],bx=bA.document.body;return bA.document.compatMode==="CSS1Compat"&&bB||bx&&bx["client"+e]||bB}else{if(bA.nodeType===9){return Math.max(bA.documentElement["client"+e],bA.body["scroll"+e],bA.documentElement["scroll"+e],bA.body["offset"+e],bA.documentElement["offset"+e])}else{if(bz===L){var bC=b.css(bA,bw),by=parseFloat(bC);return b.isNumeric(by)?by:bC}else{return this.css(bw,typeof bz==="string"?bz:bz+"px")}}}}});bb.jQuery=bb.$=b;if(typeof define==="function"&&define.amd&&define.amd.jQuery){define("jquery",[],function(){return b
+})}})(window);
diff --git a/management-interface/lib/api/nav_f.png b/management-interface/lib/api/nav_f.png
new file mode 100644
index 0000000..5ceae87
Binary files /dev/null and b/management-interface/lib/api/nav_f.png differ
diff --git a/management-interface/lib/api/nav_g.png b/management-interface/lib/api/nav_g.png
new file mode 100644
index 0000000..2093a23
Binary files /dev/null and b/management-interface/lib/api/nav_g.png differ
diff --git a/management-interface/lib/api/nav_h.png b/management-interface/lib/api/nav_h.png
new file mode 100644
index 0000000..e619809
Binary files /dev/null and b/management-interface/lib/api/nav_h.png differ
diff --git a/management-interface/lib/api/open.png b/management-interface/lib/api/open.png
new file mode 100644
index 0000000..7e740cc
Binary files /dev/null and b/management-interface/lib/api/open.png differ
diff --git a/management-interface/lib/api/sync_off.png b/management-interface/lib/api/sync_off.png
new file mode 100644
index 0000000..b856624
Binary files /dev/null and b/management-interface/lib/api/sync_off.png differ
diff --git a/management-interface/lib/api/sync_on.png b/management-interface/lib/api/sync_on.png
new file mode 100644
index 0000000..e5044af
Binary files /dev/null and b/management-interface/lib/api/sync_on.png differ
diff --git a/management-interface/lib/api/tab_a.png b/management-interface/lib/api/tab_a.png
new file mode 100644
index 0000000..170a784
Binary files /dev/null and b/management-interface/lib/api/tab_a.png differ
diff --git a/management-interface/lib/api/tab_b.png b/management-interface/lib/api/tab_b.png
new file mode 100644
index 0000000..7774499
Binary files /dev/null and b/management-interface/lib/api/tab_b.png differ
diff --git a/management-interface/lib/api/tab_h.png b/management-interface/lib/api/tab_h.png
new file mode 100644
index 0000000..e1dddef
Binary files /dev/null and b/management-interface/lib/api/tab_h.png differ
diff --git a/management-interface/lib/api/tab_s.png b/management-interface/lib/api/tab_s.png
new file mode 100644
index 0000000..3dc07b0
Binary files /dev/null and b/management-interface/lib/api/tab_s.png differ
diff --git a/management-interface/lib/api/tabs.css b/management-interface/lib/api/tabs.css
new file mode 100644
index 0000000..71145bb
--- /dev/null
+++ b/management-interface/lib/api/tabs.css
@@ -0,0 +1,60 @@
+.tabs, .tabs2, .tabs3 {
+ background-image: url('tab_b.png');
+ width: 100%;
+ z-index: 101;
+ font-size: 13px;
+ font-family: 'Lucida Grande',Geneva,Helvetica,Arial,sans-serif;
+}
+
+.tabs2 {
+ font-size: 10px;
+}
+.tabs3 {
+ font-size: 9px;
+}
+
+.tablist {
+ margin: 0;
+ padding: 0;
+ display: table;
+}
+
+.tablist li {
+ float: left;
+ display: table-cell;
+ background-image: url('tab_b.png');
+ line-height: 36px;
+ list-style: none;
+}
+
+.tablist a {
+ display: block;
+ padding: 0 20px;
+ font-weight: bold;
+ background-image:url('tab_s.png');
+ background-repeat:no-repeat;
+ background-position:right;
+ color: #434343;
+ text-shadow: 0px 1px 1px rgba(255, 255, 255, 0.9);
+ text-decoration: none;
+ outline: none;
+}
+
+.tabs3 .tablist a {
+ padding: 0 10px;
+}
+
+.tablist a:hover {
+ background-image: url('tab_h.png');
+ background-repeat:repeat-x;
+ color: #fff;
+ text-shadow: 0px 1px 1px rgba(0, 0, 0, 1.0);
+ text-decoration: none;
+}
+
+.tablist li.current a {
+ background-image: url('tab_a.png');
+ background-repeat:repeat-x;
+ color: #fff;
+ text-shadow: 0px 1px 1px rgba(0, 0, 0, 1.0);
+}
diff --git a/management-interface/lib/audit.php b/management-interface/lib/audit.php
new file mode 100644
index 0000000..32a64a9
--- /dev/null
+++ b/management-interface/lib/audit.php
@@ -0,0 +1,177 @@
+get('AGENT');
+ return (bool)preg_match('/('.self::UA_Desktop.')/i',$agent) &&
+ !$this->ismobile();
+ }
+
+ /**
+ * Return TRUE if user agent is a mobile device
+ * @return bool
+ **/
+ function ismobile() {
+ $agent=Base::instance()->get('AGENT');
+ return (bool)preg_match('/('.self::UA_Mobile.')/i',$agent);
+ }
+
+ /**
+ * Return TRUE if user agent is a Web bot
+ * @return bool
+ **/
+ function isbot() {
+ $agent=Base::instance()->get('AGENT');
+ return (bool)preg_match('/('.self::UA_Bot.')/i',$agent);
+ }
+
+ /**
+ * Return TRUE if specified ID has a valid (Luhn) Mod-10 check digit
+ * @return bool
+ * @param $id string
+ **/
+ function mod10($id) {
+ if (!ctype_digit($id))
+ return FALSE;
+ $id=strrev($id);
+ $sum=0;
+ for ($i=0,$l=strlen($id);$i<$l;$i++)
+ $sum+=$id[$i]+$i%2*(($id[$i]>4)*-4+$id[$i]%5);
+ return !($sum%10);
+ }
+
+ /**
+ * Return credit card type if number is valid
+ * @return string|FALSE
+ * @param $id string
+ **/
+ function card($id) {
+ $id=preg_replace('/[^\d]/','',$id);
+ if ($this->mod10($id)) {
+ if (preg_match('/^3[47][0-9]{13}$/',$id))
+ return 'American Express';
+ if (preg_match('/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/',$id))
+ return 'Diners Club';
+ if (preg_match('/^6(?:011|5[0-9][0-9])[0-9]{12}$/',$id))
+ return 'Discover';
+ if (preg_match('/^(?:2131|1800|35\d{3})\d{11}$/',$id))
+ return 'JCB';
+ if (preg_match('/^5[1-5][0-9]{14}$/',$id))
+ return 'MasterCard';
+ if (preg_match('/^4[0-9]{12}(?:[0-9]{3})?$/',$id))
+ return 'Visa';
+ }
+ return FALSE;
+ }
+
+ /**
+ * Return entropy estimate of a password (NIST 800-63)
+ * @return int|float
+ * @param $str string
+ **/
+ function entropy($str) {
+ $len=strlen($str);
+ return 4*min($len,1)+($len>1?(2*(min($len,8)-1)):0)+
+ ($len>8?(1.5*(min($len,20)-8)):0)+($len>20?($len-20):0)+
+ 6*(bool)(preg_match(
+ '/[A-Z].*?[0-9[:punct:]]|[0-9[:punct:]].*?[A-Z]/',$str));
+ }
+
+}
diff --git a/management-interface/lib/auth.php b/management-interface/lib/auth.php
new file mode 100644
index 0000000..78a068c
--- /dev/null
+++ b/management-interface/lib/auth.php
@@ -0,0 +1,233 @@
+mapper,'load'),
+ array(
+ array_merge(
+ array(
+ '@'.$this->args['id'].'==? AND '.
+ '@'.$this->args['pw'].'==?'.
+ (isset($this->args['realm'])?
+ (' AND @'.$this->args['realm'].'==?'):''),
+ $id,$pw
+ ),
+ (isset($this->args['realm'])?array($realm):array())
+ )
+ )
+ );
+ }
+
+ /**
+ * MongoDB storage handler
+ * @return bool
+ * @param $id string
+ * @param $pw string
+ * @param $realm string
+ **/
+ protected function _mongo($id,$pw,$realm) {
+ return (bool)
+ $this->mapper->load(
+ array(
+ $this->args['id']=>$id,
+ $this->args['pw']=>$pw
+ )+
+ (isset($this->args['realm'])?
+ array($this->args['realm']=>$realm):array())
+ );
+ }
+
+ /**
+ * SQL storage handler
+ * @return bool
+ * @param $id string
+ * @param $pw string
+ * @param $realm string
+ **/
+ protected function _sql($id,$pw,$realm) {
+ return (bool)
+ call_user_func_array(
+ array($this->mapper,'load'),
+ array(
+ array_merge(
+ array(
+ $this->args['id'].'=? AND '.
+ $this->args['pw'].'=?'.
+ (isset($this->args['realm'])?
+ (' AND '.$this->args['realm'].'=?'):''),
+ $id,$pw
+ ),
+ (isset($this->args['realm'])?array($realm):array())
+ )
+ )
+ );
+ }
+
+ /**
+ * LDAP storage handler
+ * @return bool
+ * @param $id string
+ * @param $pw string
+ **/
+ protected function _ldap($id,$pw) {
+ $dc=@ldap_connect($this->args['dc']);
+ if ($dc &&
+ ldap_set_option($dc,LDAP_OPT_PROTOCOL_VERSION,3) &&
+ ldap_set_option($dc,LDAP_OPT_REFERRALS,0) &&
+ ldap_bind($dc,$this->args['rdn'],$this->args['pw']) &&
+ ($result=ldap_search($dc,$this->args['base_dn'],
+ 'uid='.$id)) &&
+ ldap_count_entries($dc,$result) &&
+ ($info=ldap_get_entries($dc,$result)) &&
+ @ldap_bind($dc,$info[0]['dn'],$pw) &&
+ @ldap_close($dc)) {
+ return $info[0]['uid'][0]==$id;
+ }
+ user_error(self::E_LDAP);
+ }
+
+ /**
+ * SMTP storage handler
+ * @return bool
+ * @param $id string
+ * @param $pw string
+ **/
+ protected function _smtp($id,$pw) {
+ $socket=@fsockopen(
+ (strtolower($this->args['scheme'])=='ssl'?
+ 'ssl://':'').$this->args['host'],
+ $this->args['port']);
+ $dialog=function($cmd=NULL) use($socket) {
+ if (!is_null($cmd))
+ fputs($socket,$cmd."\r\n");
+ $reply='';
+ while (!feof($socket) &&
+ ($info=stream_get_meta_data($socket)) &&
+ !$info['timed_out'] && $str=fgets($socket,4096)) {
+ $reply.=$str;
+ if (preg_match('/(?:^|\n)\d{3} .+\r\n/s',
+ $reply))
+ break;
+ }
+ return $reply;
+ };
+ if ($socket) {
+ stream_set_blocking($socket,TRUE);
+ $dialog();
+ $fw=Base::instance();
+ $dialog('EHLO '.$fw->get('HOST'));
+ if (strtolower($this->args['scheme'])=='tls') {
+ $dialog('STARTTLS');
+ stream_socket_enable_crypto(
+ $socket,TRUE,STREAM_CRYPTO_METHOD_TLS_CLIENT);
+ $dialog('EHLO '.$fw->get('HOST'));
+ }
+ // Authenticate
+ $dialog('AUTH LOGIN');
+ $dialog(base64_encode($id));
+ $reply=$dialog(base64_encode($pw));
+ $dialog('QUIT');
+ fclose($socket);
+ return (bool)preg_match('/^235 /',$reply);
+ }
+ user_error(self::E_SMTP);
+ }
+
+ /**
+ * Login auth mechanism
+ * @return bool
+ * @param $id string
+ * @param $pw string
+ * @param $realm string
+ **/
+ function login($id,$pw,$realm=NULL) {
+ return $this->{'_'.$this->storage}($id,$pw,$realm);
+ }
+
+ /**
+ * HTTP basic auth mechanism
+ * @return bool
+ * @param $func callback
+ **/
+ function basic($func=NULL) {
+ $fw=Base::instance();
+ $realm=$fw->get('REALM');
+ $hdr=NULL;
+ if (isset($_SERVER['HTTP_AUTHORIZATION']))
+ $hdr=$_SERVER['HTTP_AUTHORIZATION'];
+ elseif (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION']))
+ $hdr=$_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
+ if (!empty($hdr))
+ list($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW'])=
+ explode(':',base64_decode(substr($hdr,6)));
+ if (isset($_SERVER['PHP_AUTH_USER'],$_SERVER['PHP_AUTH_PW']) &&
+ $this->login(
+ $_SERVER['PHP_AUTH_USER'],
+ $func?
+ $fw->call($func,$_SERVER['PHP_AUTH_PW']):
+ $_SERVER['PHP_AUTH_PW'],
+ $realm
+ ))
+ return TRUE;
+ if (PHP_SAPI!='cli')
+ header('WWW-Authenticate: Basic realm="'.$realm.'"');
+ $fw->status(401);
+ return FALSE;
+ }
+
+ /**
+ * Instantiate class
+ * @return object
+ * @param $storage string|object
+ * @param $args array
+ **/
+ function __construct($storage,array $args=NULL) {
+ if (is_object($storage) && is_a($storage,'DB\Cursor')) {
+ $this->storage=$storage->dbtype();
+ $this->mapper=$storage;
+ unset($ref);
+ }
+ else
+ $this->storage=$storage;
+ $this->args=$args;
+ }
+
+}
diff --git a/management-interface/lib/basket.php b/management-interface/lib/basket.php
new file mode 100644
index 0000000..3db2b5d
--- /dev/null
+++ b/management-interface/lib/basket.php
@@ -0,0 +1,229 @@
+item);
+ }
+
+ /**
+ * Assign value to field
+ * @return scalar|FALSE
+ * @param $key string
+ * @param $val scalar
+ **/
+ function set($key,$val) {
+ return ($key=='_id')?FALSE:($this->item[$key]=$val);
+ }
+
+ /**
+ * Retrieve value of field
+ * @return scalar|FALSE
+ * @param $key string
+ **/
+ function get($key) {
+ if ($key=='_id')
+ return $this->id;
+ if (array_key_exists($key,$this->item))
+ return $this->item[$key];
+ user_error(sprintf(self::E_Field,$key));
+ return FALSE;
+ }
+
+ /**
+ * Delete field
+ * @return NULL
+ * @param $key string
+ **/
+ function clear($key) {
+ unset($this->item[$key]);
+ }
+
+ /**
+ * Return items that match key/value pair;
+ * If no key/value pair specified, return all items
+ * @return array|FALSE
+ * @param $key string
+ * @param $val mixed
+ **/
+ function find($key=NULL,$val=NULL) {
+ if (isset($_SESSION[$this->key])) {
+ $out=array();
+ foreach ($_SESSION[$this->key] as $id=>$item)
+ if (!isset($key) ||
+ array_key_exists($key,$item) && $item[$key]==$val) {
+ $obj=clone($this);
+ $obj->id=$id;
+ $obj->item=$item;
+ $out[]=$obj;
+ }
+ return $out;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Return first item that matches key/value pair
+ * @return object|FALSE
+ * @param $key string
+ * @param $val mixed
+ **/
+ function findone($key,$val) {
+ return ($data=$this->find($key,$val))?$data[0]:FALSE;
+ }
+
+ /**
+ * Map current item to matching key/value pair
+ * @return array
+ * @param $key string
+ * @param $val mixed
+ **/
+ function load($key,$val) {
+ if ($found=$this->find($key,$val)) {
+ $this->id=$found[0]->id;
+ return $this->item=$found[0]->item;
+ }
+ $this->reset();
+ return array();
+ }
+
+ /**
+ * Return TRUE if current item is empty/undefined
+ * @return bool
+ **/
+ function dry() {
+ return !$this->item;
+ }
+
+ /**
+ * Return number of items in basket
+ * @return int
+ **/
+ function count() {
+ return isset($_SESSION[$this->key])?count($_SESSION[$this->key]):0;
+ }
+
+ /**
+ * Save current item
+ * @return array
+ **/
+ function save() {
+ if (!$this->id)
+ $this->id=uniqid(NULL,TRUE);
+ $_SESSION[$this->key][$this->id]=$this->item;
+ return $this->item;
+ }
+
+ /**
+ * Erase item matching key/value pair
+ * @return bool
+ * @param $key string
+ * @param $val mixed
+ **/
+ function erase($key,$val) {
+ $found=$this->find($key,$val);
+ if ($found && $id=$found[0]->id) {
+ unset($_SESSION[$this->key][$id]);
+ if ($id==$this->id)
+ $this->reset();
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Reset cursor
+ * @return NULL
+ **/
+ function reset() {
+ $this->id=NULL;
+ $this->item=array();
+ }
+
+ /**
+ * Empty basket
+ * @return NULL
+ **/
+ function drop() {
+ unset($_SESSION[$this->key]);
+ }
+
+ /**
+ * Hydrate item using hive array variable
+ * @return NULL
+ * @param $key string
+ **/
+ function copyfrom($key) {
+ foreach (\Base::instance()->get($key) as $key=>$val)
+ $this->item[$key]=$val;
+ }
+
+ /**
+ * Populate hive array variable with item contents
+ * @return NULL
+ * @param $key string
+ **/
+ function copyto($key) {
+ $var=&\Base::instance()->ref($key);
+ foreach ($this->item as $key=>$field)
+ $var[$key]=$field;
+ }
+
+ /**
+ * Check out basket contents
+ * @return array
+ **/
+ function checkout() {
+ if (isset($_SESSION[$this->key])) {
+ $out=$_SESSION[$this->key];
+ unset($_SESSION[$this->key]);
+ return $out;
+ }
+ return array();
+ }
+
+ /**
+ * Instantiate class
+ * @return void
+ * @param $key string
+ **/
+ function __construct($key='basket') {
+ $this->key=$key;
+ @session_start();
+ Base::instance()->sync('SESSION');
+ $this->reset();
+ }
+
+}
diff --git a/management-interface/lib/bcrypt.php b/management-interface/lib/bcrypt.php
new file mode 100644
index 0000000..311c1e3
--- /dev/null
+++ b/management-interface/lib/bcrypt.php
@@ -0,0 +1,89 @@
+31)
+ user_error(self::E_CostArg);
+ $len=22;
+ if ($salt) {
+ if (!preg_match('/^[[:alnum:]\.\/]{'.$len.',}$/',$salt))
+ user_error(self::E_SaltArg);
+ }
+ else {
+ $raw=16;
+ $iv='';
+ if (extension_loaded('mcrypt'))
+ $iv=mcrypt_create_iv($raw,MCRYPT_DEV_URANDOM);
+ if (!$iv && extension_loaded('openssl'))
+ $iv=openssl_random_pseudo_bytes($raw);
+ if (!$iv)
+ for ($i=0;$i<$raw;$i++)
+ $iv.=chr(mt_rand(0,255));
+ $salt=str_replace('+','.',base64_encode($iv));
+ }
+ $salt=substr($salt,0,$len);
+ $hash=crypt($pw,sprintf('$2y$%02d$',$cost).$salt);
+ return strlen($hash)>13?$hash:FALSE;
+ }
+
+ /**
+ * Check if password is still strong enough
+ * @return bool
+ * @param $hash string
+ * @param $cost int
+ **/
+ function needs_rehash($hash,$cost=self::COST) {
+ list($pwcost)=sscanf($hash,"$2y$%d$");
+ return $pwcost<$cost;
+ }
+
+ /**
+ * Verify password against hash using timing attack resistant approach
+ * @return bool
+ * @param $pw string
+ * @param $hash string
+ **/
+ function verify($pw,$hash) {
+ $val=crypt($pw,$hash);
+ $len=strlen($val);
+ if ($len!=strlen($hash) || $len<14)
+ return FALSE;
+ $out=0;
+ for ($i=0;$i<$len;$i++)
+ $out|=(ord($val[$i])^ord($hash[$i]));
+ return $out===0;
+ }
+
+}
diff --git a/management-interface/lib/changelog.txt b/management-interface/lib/changelog.txt
new file mode 100644
index 0000000..7ae905b
--- /dev/null
+++ b/management-interface/lib/changelog.txt
@@ -0,0 +1,416 @@
+CHANGELOG
+
+3.2.2 (19 March 2014)
+* NEW: Locales set automatically (Feature request #522)
+* NEW: Mapper dbtype()
+* NEW: before- and after- triggers for all mappers
+* NEW: Decode HTML5 entities if PHP>5.3 detected (Feature request #552)
+* NEW: Send credentials only if AUTH is present in the SMTP extension
+ response (Feature request #545)
+* NEW: BITMASK variable to allow ENT_COMPAT override
+* NEW: Redis support for caching
+* Enable SMTP feature detection
+* Enable extended ICU custom date format (Feature request #555)
+* Enable custom time ICU format
+* Add option to turn off session table creation (Feature request #557)
+* Enhanced template token rendering and custom filters (Feature request
+ #550)
+* Avert multiple loads in DB-managed sessions (Feature request #558)
+* Add EXEC to associative fetch
+* Bug fix: Building template tokens breaks on inline OR condition (Issue
+ #573)
+* Bug fix: SMTP->send does not use the $log parameter (Issue #571)
+* Bug fix: Allow setting sqlsrv primary keys on insert (Issue #570)
+* Bug fix: Generated query for obtaining table schema in sqlsrv incorrect
+ (Bug #565)
+* Bug fix: SQL mapper flag set even when value has not changed (Bug #562)
+* Bug fix: Add XFRAME config option (Feature request #546)
+* Bug fix: Incorrect parsing of comments (Issue #541)
+* Bug fix: Multiple Set-Cookie headers (Issue #533)
+* Bug fix: Mapper is dry after save()
+* Bug fix: Prevent infinite loop when error handler is triggered
+ (Issue #361)
+* Bug fix: Mapper tweaks not passing primary keys as arguments
+* Bug fix: Zero indexes in dot-notated arrays fail to compile
+* Bug fix: Prevent GROUP clause double-escaping
+* Bug fix: Regression of zlib compression bug
+* Bug fix: Method copyto() does not include ad hoc fields
+* Check existence of OpenID mode (Issue #529)
+* Generate a 404 when a tokenized class doesn't exist
+* Fix SQLite quotes (Issue #521)
+* Bug fix: BASE is incorrect on Windows
+
+3.2.1 (7 January 2014)
+* NEW: EMOJI variable, UTF->translate(), UTF->emojify(), and UTF->strrev()
+* Allow empty strings in config()
+* Add support for turning off php://input buffering via RAW
+ (FALSE by default)
+* Add Cursor->load() and Cursor->find() TTL support
+* Support Web->receive() large file downloads via PUT
+* ONERROR safety check
+* Fix session CSRF cookie detection
+* Framework object now passed to route handler contructors
+* Allow override of DIACRITICS
+* Various code optimizations
+* Support log disabling (Issue #483)
+* Implicit mapper load() on authentication
+* Declare abstract methods for Cursor derivatives
+* Support single-quoted HTML/XML attributes (Feature request #503)
+* Relax property visibility of mappers and derivatives
+* Deprecated: {{~ ~}} instructions and {{* *}} comments; Use {~ ~} and
+ {* *} instead
+* Minor fix: Audit->ipv4() return value
+* Bug fix: Backslashes in BASE not converted on Windows
+* Bug fix: UTF->substr() with negative offset and specified length
+* Bug fix: Replace named URL tokens on render()
+* Bug fix: BASE is not empty when run from document root
+* Bug fix: stringify() recursion
+
+3.2.0 (18 December 2013)
+* NEW: Automatic CSRF protection (with IP and User-Agent checks) for
+ sessions mapped to SQL-, Jig-, Mongo- and Cache-based backends
+* NEW: Named routes
+* NEW: PATH variable; returns the URL relative to BASE
+* NEW: Image->captcha() color parameters
+* NEW: Ability to access MongoCuror thru the cursor() method
+* NEW: Mapper->fields() method returns array of field names
+* NEW: Mapper onload(), oninsert(), onupdate(), and onerase() event
+ listeners/triggers
+* NEW: Preview class (a lightweight template engine)
+* NEW: rel() method derives path from URL relative to BASE; useful for
+ rerouting
+* NEW: PREFIX variable for prepending a string to a dictionary term;
+ Enable support for prefixed dictionary arrays and .ini files (Feature
+ request #440)
+* NEW: Google static map plugin
+* NEW: devoid() method
+* Introduce clean(); similar to scrub(), except that arg is passed by
+ value
+* Use $ttl for cookie expiration (Issue #457)
+* Fix needs_rehash() cost comparison
+* Add pass-by-reference argument to exists() so if method returns TRUE,
+ a subsequent get() is unnecessary
+* Improve MySQL support
+* Move esc(), raw(), and dupe() to View class where they more
+ appropriately belong
+* Allow user-defined fields in SQL mapper constructor (Feature request
+ #450)
+* Re-implement the pre-3.0 template resolve() feature
+* Remove redundant instances of session_commit()
+* Add support for input filtering in Mapper->copyfrom()
+* Prevent intrusive behavior of Mapper->copyfrom()
+* Support multiple SQL primary keys
+* Support custom tag attributes/inline tokens defined at runtime
+ (Feature request #438)
+* Broader support for HTTP basic auth
+* Prohibit Jig _id clear()
+* Add support for detailed stringify() output
+* Add base directory to UI path as fallback
+* Support Test->expect() chaining
+* Support __tostring() in stringify()
+* Trigger error on invalid CAPTCHA length (Issue #458)
+* Bug fix: exists() pass-by-reference argument returns incorrect value
+* Bug fix: DB Exec does not return affected row if query contains a
+ sub-SELECT (Issue #437)
+* Improve seed generator and add code for detecting of acceptable
+ limits in Image->captcha() (Feature request #460)
+* Add decimal format ICU extension
+* Bug fix: 404-reported URI contains HTTP query
+* Bug fix: Data type detection in DB->schema()
+* Bug fix: TZ initialization
+* Bug fix: paginate() passes incorrect argument to count()
+* Bug fix: Incorrect query when reloading after insert()
+* Bug fix: SQL preg_match error in pdo_type matching (Issue #447)
+* Bug fix: Missing merge() function (Issue #444)
+* Bug fix: BASE misdefined in command line mode
+* Bug fix: Stringifying hive may run infinite (Issue #436)
+* Bug fix: Incomplete stringify() when DEBUG<3 (Issue #432)
+* Bug fix: Redirection of basic auth (Issue #430)
+* Bug fix: Filter only PHP code (including short tags) in templates
+* Bug fix: Markdown paragraph parser does not convert PHP code blocks
+ properly
+* Bug fix: identicon() colors on same keys are randomized
+* Bug fix: quotekey() fails on aliased keys
+* Bug fix: Missing _id in Jig->find() return value
+* Bug fix: LANGUAGE/LOCALES handling
+* Bug fix: Loose comparison in stringify()
+
+3.1.2 (5 November 2013)
+* Abandon .chm help format; Package API documentation in plain HTML;
+ (Launch lib/api/index.html in your browser)
+* Deprecate BAIL in favor of HALT (default: TRUE)
+* Revert to 3.1.0 autoload behavior; Add support for lowercase folder
+ names
+* Allow Spring-style HTTP method overrides
+* Add support for SQL Server-based sessions
+* Capture full X-Forwarded-For header
+* Add protection against malicious scripts; Extra check if file was really
+ uploaded
+* Pass-thru page limit in return value of Cursor->paginate()
+* Optimize code: Implement single-pass escaping
+* Short circuit Jig->find() if source file is empty
+* Bug fix: PHP globals passed by reference in hive() result (Issue #424)
+* Bug fix: ZIP mime type incorrect behavior
+* Bug fix: Jig->erase() filter malfunction
+* Bug fix: Mongo->select() group
+* Bug fix: Unknown bcrypt constant
+
+3.1.1 (13 October 2013)
+* NEW: Support OpenID attribute exchange
+* NEW: BAIL variable enables/disables continuance of execution on non-fatal
+ errors
+* Deprecate BAIL in favor of HALT (default: FALSE)
+* Add support for Oracle
+* Mark cached queries in log (Feature Request #405)
+* Implement Bcrypt->needs_reshash()
+* Add entropy to SQL cache hash; Add uuid() method to DB backends
+* Find real document root; Simplify debug paths
+* Permit OpenID required fields to be declared as comma-separated string or
+ array
+* Pass modified filename as argument to user-defined function in
+ Web->receive()
+* Quote keys in optional SQL clauses (Issue #408)
+* Allow UNLOAD to override fatal error detection (Issue #404)
+* Mutex operator precedence error (Issue #406)
+* Bug fix: exists() malfunction (Issue #401)
+* Bug fix: Jig mapper triggers error when loading from CACHE (Issue #403)
+* Bug fix: Array index check
+* Bug fix: OpenID verified() return value
+* Bug fix: Basket->find() should return a set of results (Issue #407);
+ Also implemented findone() for consistency with mappers
+* Bug fix: PostgreSQL last insert ID (Issue #410)
+* Bug fix: $port component URL overwritten by _socket()
+* Bug fix: Calculation of elapsed time
+
+3.1.0 (20 August 2013)
+* NEW: Web->filler() returns a chunk of text from the standard
+ Lorem Ipsum passage
+* Change in behavior: Drop support for JSON serialization
+* SQL->exec() now returns value of RETURNING clause
+* Add support for $ttl argument in count() (Issue #393)
+* Allow UI to be overridden by custom $path
+* Return result of PDO primitives: begintransaction(), rollback(), and
+ commit()
+* Full support for PHP 5.5
+* Flush buffers only when DEBUG=0
+* Support class->method, class::method, and lambda functions as
+ Web->basic() arguments
+* Commit session on Basket->save()
+* Optional enlargement in Image->resize()
+* Support authentication on hosts running PHP-CGI
+* Change visibility level of Cache properties
+* Prevent ONERROR recursion
+* Work around Apache pre-2.4 VirtualDocumentRoot bug
+* Prioritize cURL in HTTP engine detection
+* Bug fix: Minify tricky JS
+* Bug fix: desktop() detection
+* Bug fix: Double-slash on TEMP-relative path
+* Bug fix: Cursor mapping of first() and last() records
+* Bug fix: Premature end of Web->receive() on multiple files
+* Bug fix: German umlaute to its corresponding grammatically-correct
+ equivalent
+
+3.0.9 (12 June 2013)
+* NEW: Web->whois()
+* NEW: Template tags
+* Improve CACHE consistency
+* Case-insensitive MIME type detection
+* Support pre-PHP 5.3.4 in Prefab->instance()
+* Refactor isdesktop() and ismobile(); Add isbot()
+* Add support for Markdown strike-through
+* Work around ODBC's lack of quote() support
+* Remove useless Prefab destructor
+* Support multiple cache instances
+* Bug fix: Underscores in OpenId keys mangled
+* Refactor format()
+* Numerous tweaks
+* Bug fix: MongoId object not preserved
+* Bug fix: Double-quotes included in lexicon() string (Issue #341)
+* Bug fix: UTF-8 formatting mangled on Windows (Issue #342)
+* Bug fix: Cache->load() error when CACHE is FALSE (Issue #344)
+* Bug fix: send() ternary expression
+* Bug fix: Country code constants
+
+3.0.8 (17 May 2013)
+* NEW: Bcrypt lightweight hashing library\
+* Return total number of records in superset in Cursor->paginate()
+* ONERROR short-circuit (Enhancement #334)
+* Apply quotes/backticks on DB identifiers
+* Allow enabling/disabling of SQL log
+* Normalize glob() behavior (Issue #330)
+* Bug fix: mbstring 2-byte text truncation (Issue #325)
+* Bug fix: Unsupported operand types (Issue #324)
+
+3.0.7 (2 May 2013)
+* NEW: route() now allows an array of routing patterns as first argument;
+ support array as first argument of map()
+* NEW: entropy() for calculating password strength (NIST 800-63)
+* NEW: AGENT variable containing auto-detected HTTP user agent string
+* NEW: ismobile() and isdesktop() methods
+* NEW: Prefab class and descendants now accept constructor arguments
+* Change in behavior: Cache->exists() now returns timestamp and TTL of
+ cache entry or FALSE if not found (Feature request #315)
+* Preserve timestamp and TTL when updating cache entry (Feature request
+ #316)
+* Improved currency formatting with C99 compliance
+* Suppress unnecessary program halt at startup caused by misconfigured
+ server
+* Add support for dashes in custom attribute names in templates
+* Bug fix: Routing precedene (Issue #313)
+* Bug fix: Remove Jig _id element from document property
+* Bug fix: Web->rss() error when not enough items in the feed (Issue #299)
+* Bug fix: Web engine fallback (Issue #300)
+* Bug fix: and formatting
+* Bug fix: Text rendering of text with trailing punctuation (Issue #303)
+* Bug fix: Incorrect regex in SMTP
+
+3.0.6 (31 Mar 2013)
+* NEW: Image->crop()
+* Modify documentation blocks for PHPDoc interoperability
+* Allow user to control whether Base->rerouet() uses a permanent or
+ temporary redirect
+* Allow JAR elements to be set individually
+* Refactor DB\SQL\Mapper->insert() to cope with autoincrement fields
+* Trigger error when captcha() font is missing
+* Remove unnecessary markdown regex recursion
+* Check for scalars instead of DB\SQL strings
+* Implement more comprehensive diacritics table
+* Add option for disabling 401 errors when basic auth() fails
+* Add markdown syntax highlighting for Apache configuration
+* Markdown->render() deprecated to remove dependency on UI variable;
+ Feature replaced by Markdown->convert() to enable translation from
+ markdown string to HTML
+* Optimize factory() code of all data mappers
+* Apply backticks on MySQL table names
+* Bug fix: Routing failure when directory path contains a tilde (Issue #291)
+* Bug fix: Incorrect markdown parsing of strong/em sequences and inline HTML
+* Bug fix: Cached page not echoed (Issue #278)
+* Bug fix: Object properties not escaped when rendering
+* Bug fix: OpenID error response ignored
+* Bug fix: memcache_get_extended_stats() timeout
+* Bug fix: Base->set() doesn't pass TTL to Cache->set()
+* Bug fix: Base->scrub() ignores pass-thru * argument (Issue #274)
+
+3.0.5 (16 Feb 2013)
+* NEW: Markdown class with PHP, HTML, and .ini syntax highlighting support
+* NEW: Options for caching of select() and find() results
+* NEW: Web->acceptable()
+* Add send() argument for forcing downloads
+* Provide read() option for applying Unix LF as standard line ending
+* Bypass lexicon() call if LANGUAGE is undefined
+* Load fallback language dictionary if LANGUAGE is undefined
+* map() now checks existence of class/methods for non-tokenized URLs
+* Improve error reporting of non-existent Template methods
+* Address output buffer issues on some servers
+* Bug fix: Setting DEBUG to 0 won't suppress the stack trace when the
+ content type is application/json (Issue #257)
+* Bug fix: Image dump/render additional arguments shifted
+* Bug fix: ob_clean() causes buffer issues with zlib compression
+* Bug fix: minify() fails when commenting CSS @ rules (Issue #251)
+* Bug fix: Handling of commas inside quoted strings
+* Bug fix: Glitch in stringify() handling of closures
+* Bug fix: dry() in mappers returns TRUE despite being hydrated by
+ factory() (Issue #265)
+* Bug fix: expect() not handling flags correctly
+* Bug fix: weather() fails when server is unreachable
+
+3.0.4 (29 Jan 2013)
+* NEW: Support for ICU/CLDR pluralization
+* NEW: User-defined FALLBACK language
+* NEW: minify() now recognizes CSS @import directives
+* NEW: UTF->bom() returns byte order mark for UTF-8 encoding
+* Expose SQL\Mapper->schema()
+* Change in behavior: Send error response as JSON string if AJAX request is
+ detected
+* Deprecated: afind*() methods
+* Discard output buffer in favor of debug output
+* Make _id available to Jig queries
+* Magic class now implements ArrayAccess
+* Abort execution on startup errors
+* Suppress stack trace on DEBUG level 0
+* Allow single = as equality operator in Jig query expressions
+* Abort OpenID discovery if Web->request() fails
+* Mimic PHP *RECURSION* in stringify()
+* Modify Jig parser to allow wildcard-search using preg_match()
+* Abort execution after error() execution
+* Concatenate cached/uncached minify() iterations; Prevent spillover
+ caching of previous minify() result
+* Work around obscure PHP session id regeneration bug
+* Revise algorithm for Jig filter involving undefined fields (Issue #230)
+* Use checkdnsrr() instead of gethostbyname() in DNSBL check
+* Auto-adjust pagination to cursor boundaries
+* Add Romanian diacritics
+* Bug fix: Root namespace reference and sorting with undefined Jig fields
+* Bug fix: Greedy receive() regex
+* Bug fix: Default LANGUAGE always 'en'
+* Bug fix: minify() hammers cache backend
+* Bug fix: Previous values of primary keys not saved during factory()
+ instantiation
+* Bug fix: Jig find() fails when search key is not present in all records
+* Bug fix: Jig SORT_DESC (Issue #233)
+* Bug fix: Error reporting (Issue #225)
+* Bug fix: language() return value
+
+3.0.3 (29 Dec 2013)
+* NEW: [ajax] and [sync] routing pattern modifiers
+* NEW: Basket class (session-based pseudo-mapper, shopping cart, etc.)
+* NEW: Test->message() method
+* NEW: DB profiling via DB->log()
+* NEW: Matrix->calendar()
+* NEW: Audit->card() and Audit->mod10() for credit card verification
+* NEW: Geo->weather()
+* NEW: Base->relay() accepts comma-separated callbacks; but unlike
+ Base->chain(), result of previous callback becomes argument of the next
+* Numerous performance tweaks
+* Interoperability with new MongoClient class
+* Web->request() now recognizes gzip and deflate encoding
+* Differences in behavior of Web->request() engines rectified
+* mutex() now uses an ID as argument (instead of filename to make it clear
+ that specified file is not the target being locked, but a primitive
+ cross-platform semaphore)
+* DB\SQL\Mapper field _id now returned even in the absence of any
+ auto-increment field
+* Magic class spinned off as a separate file
+* ISO 3166-1 alpha-2 table updated
+* Apache redirect emulation for PHP 5.4 CLI server mode
+* Framework instance now passed as argument to any user-defined shutdown
+ function
+* Cache engine now used as storage for Web->minify() output
+* Flag added for enabling/disabling Image class filter history
+* Bug fix: Trailing routing token consumes HTTP query
+* Bug fix: LANGUAGE spills over to LOCALES setting
+* Bug fix: Inconsistent dry() return value
+* Bug fix: URL-decoding
+
+3.0.2 (23 Dec 2013)
+* NEW: Syntax-highlighted stack traces via Base->highlight(); boolean
+ HIGHLIGHT global variable can be used to enable/disable this feature
+* NEW: Template engine tag
+* NEW: Image->captcha()
+* NEW: DNSBL-based spammer detection (ported from 2.x)
+* NEW: paginate(), first(), and last() methods for data mappers
+* NEW: X-HTTP-Method-Override header now recognized
+* NEW: Base->chain() method for executing callbacks in succession
+* NEW: HOST global variable; derived from either $_SERVER['SERVER_NAME'] or
+ gethostname()
+* NEW: REALM global variable representing full canonical URI
+* NEW: Auth plug-in
+* NEW: Pingback plug-in (implements both Pingback 1.0 protocol client and
+ server)
+* NEW: DEBUG verbosity can now reach up to level 3; Base->stringify() drills
+ down to object properties at this setting
+* NEW: HTTP PATCH method added to recognized HTTP ReST methods
+* Web->slug() now trims trailing dashes
+* Web->request() now allows relative local URLs as argument
+* Use of PARAMS in route handlers now unnecessary; framework now passes two
+ arguments to route handlers: the framework object instance and an array
+ containing the captured values of tokens in route patterns
+* Standardized timeout settings among Web->request() backends
+* Session IDs regenerated for additional security
+* Automatic HTTP 404 responses by Base->call() now restricted to route
+ handlers
+* Empty comments in ini-style files now parsed properly
+* Use file_get_contents() in methods that don't involve high concurrency
+
+3.0.1 (14 Dec 2013)
+* Major rewrite of much of the framework's core features
diff --git a/management-interface/lib/code.css b/management-interface/lib/code.css
new file mode 100644
index 0000000..618703f
--- /dev/null
+++ b/management-interface/lib/code.css
@@ -0,0 +1 @@
+code{word-wrap:break-word;color:black}.comment,.doc_comment,.ml_comment{color:dimgray;font-style:italic}.variable{color:blueviolet}.const,.constant_encapsed_string,.class_c,.dir,.file,.func_c,.halt_compiler,.line,.method_c,.lnumber,.dnumber{color:crimson}.string,.and_equal,.boolean_and,.boolean_or,.concat_equal,.dec,.div_equal,.inc,.is_equal,.is_greater_or_equal,.is_identical,.is_not_equal,.is_not_identical,.is_smaller_or_equal,.logical_and,.logical_or,.logical_xor,.minus_equal,.mod_equal,.mul_equal,.ns_c,.ns_separator,.or_equal,.plus_equal,.sl,.sl_equal,.sr,.sr_equal,.xor_equal,.start_heredoc,.end_heredoc,.object_operator,.paamayim_nekudotayim{color:black}.abstract,.array,.array_cast,.as,.break,.case,.catch,.class,.clone,.continue,.declare,.default,.do,.echo,.else,.elseif,.empty.enddeclare,.endfor,.endforach,.endif,.endswitch,.endwhile,.eval,.exit,.extends,.final,.for,.foreach,.function,.global,.goto,.if,.implements,.include,.include_once,.instanceof,.interface,.isset,.list,.namespace,.new,.print,.private,.public,.protected,.require,.require_once,.return,.static,.switch,.throw,.try,.unset,.use,.var,.while{color:royalblue}.open_tag,.open_tag_with_echo,.close_tag{color:orange}.ini_section{color:black}.ini_key{color:royalblue}.ini_value{color:crimson}.xml_tag{color:dodgerblue}.xml_attr{color:blueviolet}.xml_data{color:red}.section{color:black}.directive{color:blue}.data{color:dimgray}
diff --git a/management-interface/lib/db/cursor.php b/management-interface/lib/db/cursor.php
new file mode 100644
index 0000000..354c683
--- /dev/null
+++ b/management-interface/lib/db/cursor.php
@@ -0,0 +1,313 @@
+query[$this->ptr]);
+ }
+
+ /**
+ * Return first record (mapper object) that matches criteria
+ * @return object|FALSE
+ * @param $filter string|array
+ * @param $options array
+ * @param $ttl int
+ **/
+ function findone($filter=NULL,array $options=NULL,$ttl=0) {
+ return ($data=$this->find($filter,$options,$ttl))?$data[0]:FALSE;
+ }
+
+ /**
+ * Return array containing subset of records matching criteria,
+ * total number of records in superset, specified limit, number of
+ * subsets available, and actual subset position
+ * @return array
+ * @param $pos int
+ * @param $size int
+ * @param $filter string|array
+ * @param $options array
+ * @param $ttl int
+ **/
+ function paginate(
+ $pos=0,$size=10,$filter=NULL,array $options=NULL,$ttl=0) {
+ $total=$this->count($filter,$ttl);
+ $count=ceil($total/$size);
+ $pos=max(0,min($pos,$count-1));
+ return array(
+ 'subset'=>$this->find($filter,
+ array_merge(
+ $options?:array(),
+ array('limit'=>$size,'offset'=>$pos*$size)
+ ),
+ $ttl
+ ),
+ 'total'=>$total,
+ 'limit'=>$size,
+ 'count'=>$count,
+ 'pos'=>$pos<$count?$pos:0
+ );
+ }
+
+ /**
+ * Map to first record that matches criteria
+ * @return array|FALSE
+ * @param $filter string|array
+ * @param $options array
+ * @param $ttl int
+ **/
+ function load($filter=NULL,array $options=NULL,$ttl=0) {
+ return ($this->query=$this->find($filter,$options,$ttl)) &&
+ $this->skip(0)?$this->query[$this->ptr=0]:FALSE;
+ }
+
+ /**
+ * Map to first record in cursor
+ * @return mixed
+ **/
+ function first() {
+ return $this->skip(-$this->ptr);
+ }
+
+ /**
+ * Map to last record in cursor
+ * @return mixed
+ **/
+ function last() {
+ return $this->skip(($ofs=count($this->query)-$this->ptr)?$ofs-1:0);
+ }
+
+ /**
+ * Map to nth record relative to current cursor position
+ * @return mixed
+ * @param $ofs int
+ **/
+ function skip($ofs=1) {
+ $this->ptr+=$ofs;
+ return $this->ptr>-1 && $this->ptrquery)?
+ $this->query[$this->ptr]:FALSE;
+ }
+
+ /**
+ * Map next record
+ * @return mixed
+ **/
+ function next() {
+ return $this->skip();
+ }
+
+ /**
+ * Map previous record
+ * @return mixed
+ **/
+ function prev() {
+ return $this->skip(-1);
+ }
+
+ /**
+ * Save mapped record
+ * @return mixed
+ **/
+ function save() {
+ return $this->query?$this->update():$this->insert();
+ }
+
+ /**
+ * Delete current record
+ * @return int|bool
+ **/
+ function erase() {
+ $this->query=array_slice($this->query,0,$this->ptr,TRUE)+
+ array_slice($this->query,$this->ptr,NULL,TRUE);
+ $this->ptr=0;
+ }
+
+ /**
+ * Define onload trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function onload($func) {
+ return $this->trigger['load']=$func;
+ }
+
+ /**
+ * Define beforeinsert trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function beforeinsert($func) {
+ return $this->trigger['beforeinsert']=$func;
+ }
+
+ /**
+ * Define afterinsert trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function afterinsert($func) {
+ return $this->trigger['afterinsert']=$func;
+ }
+
+ /**
+ * Define oninsert trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function oninsert($func) {
+ return $this->afterinsert($func);
+ }
+
+ /**
+ * Define beforeupdate trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function beforeupdate($func) {
+ return $this->trigger['beforeupdate']=$func;
+ }
+
+ /**
+ * Define afterupdate trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function afterupdate($func) {
+ return $this->trigger['afterupdate']=$func;
+ }
+
+ /**
+ * Define onupdate trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function onupdate($func) {
+ return $this->afterupdate($func);
+ }
+
+ /**
+ * Define beforeerase trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function beforeerase($func) {
+ return $this->trigger['beforeerase']=$func;
+ }
+
+ /**
+ * Define aftererase trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function aftererase($func) {
+ return $this->trigger['aftererase']=$func;
+ }
+
+ /**
+ * Define onerase trigger
+ * @return callback
+ * @param $func callback
+ **/
+ function onerase($func) {
+ return $this->aftererase($func);
+ }
+
+ /**
+ * Reset cursor
+ * @return NULL
+ **/
+ function reset() {
+ $this->query=array();
+ $this->ptr=0;
+ }
+
+}
diff --git a/management-interface/lib/db/jig.php b/management-interface/lib/db/jig.php
new file mode 100644
index 0000000..16f2255
--- /dev/null
+++ b/management-interface/lib/db/jig.php
@@ -0,0 +1,133 @@
+dir.$file))
+ return array();
+ $raw=$fw->read($dst);
+ switch ($this->format) {
+ case self::FORMAT_JSON:
+ $data=json_decode($raw,TRUE);
+ break;
+ case self::FORMAT_Serialized:
+ $data=$fw->unserialize($raw);
+ break;
+ }
+ return $data;
+ }
+
+ /**
+ * Write data to file
+ * @return int
+ * @param $file string
+ * @param $data array
+ **/
+ function write($file,array $data=NULL) {
+ $fw=\Base::instance();
+ switch ($this->format) {
+ case self::FORMAT_JSON:
+ $out=json_encode($data,@constant('JSON_PRETTY_PRINT'));
+ break;
+ case self::FORMAT_Serialized:
+ $out=$fw->serialize($data);
+ break;
+ }
+ return $fw->write($this->dir.$file,$out);
+ }
+
+ /**
+ * Return directory
+ * @return string
+ **/
+ function dir() {
+ return $this->dir;
+ }
+
+ /**
+ * Return UUID
+ * @return string
+ **/
+ function uuid() {
+ return $this->uuid;
+ }
+
+ /**
+ * Return SQL profiler results
+ * @return string
+ **/
+ function log() {
+ return $this->log;
+ }
+
+ /**
+ * Jot down log entry
+ * @return NULL
+ * @param $frame string
+ **/
+ function jot($frame) {
+ if ($frame)
+ $this->log.=date('r').' '.$frame.PHP_EOL;
+ }
+
+ /**
+ * Clean storage
+ * @return NULL
+ **/
+ function drop() {
+ if ($glob=@glob($this->dir.'/*',GLOB_NOSORT))
+ foreach ($glob as $file)
+ @unlink($file);
+ }
+
+ /**
+ * Instantiate class
+ * @param $dir string
+ * @param $format int
+ **/
+ function __construct($dir,$format=self::FORMAT_JSON) {
+ if (!is_dir($dir))
+ mkdir($dir,\Base::MODE,TRUE);
+ $this->uuid=\Base::instance()->hash($this->dir=$dir);
+ $this->format=$format;
+ }
+
+}
diff --git a/management-interface/lib/db/jig/mapper.php b/management-interface/lib/db/jig/mapper.php
new file mode 100644
index 0000000..3ac3d21
--- /dev/null
+++ b/management-interface/lib/db/jig/mapper.php
@@ -0,0 +1,459 @@
+document);
+ }
+
+ /**
+ * Assign value to field
+ * @return scalar|FALSE
+ * @param $key string
+ * @param $val scalar
+ **/
+ function set($key,$val) {
+ return ($key=='_id')?FALSE:($this->document[$key]=$val);
+ }
+
+ /**
+ * Retrieve value of field
+ * @return scalar|FALSE
+ * @param $key string
+ **/
+ function get($key) {
+ if ($key=='_id')
+ return $this->id;
+ if (array_key_exists($key,$this->document))
+ return $this->document[$key];
+ user_error(sprintf(self::E_Field,$key));
+ return FALSE;
+ }
+
+ /**
+ * Delete field
+ * @return NULL
+ * @param $key string
+ **/
+ function clear($key) {
+ if ($key!='_id')
+ unset($this->document[$key]);
+ }
+
+ /**
+ * Convert array to mapper object
+ * @return object
+ * @param $id string
+ * @param $row array
+ **/
+ protected function factory($id,$row) {
+ $mapper=clone($this);
+ $mapper->reset();
+ $mapper->id=$id;
+ foreach ($row as $field=>$val)
+ $mapper->document[$field]=$val;
+ $mapper->query=array(clone($mapper));
+ if (isset($mapper->trigger['load']))
+ \Base::instance()->call($mapper->trigger['load'],$mapper);
+ return $mapper;
+ }
+
+ /**
+ * Return fields of mapper object as an associative array
+ * @return array
+ * @param $obj object
+ **/
+ function cast($obj=NULL) {
+ if (!$obj)
+ $obj=$this;
+ return $obj->document+array('_id'=>$this->id);
+ }
+
+ /**
+ * Convert tokens in string expression to variable names
+ * @return string
+ * @param $str string
+ **/
+ function token($str) {
+ $self=$this;
+ $str=preg_replace_callback(
+ '/(?stringify(substr($expr[1],1)):
+ (preg_match('/^\w+/',
+ $mix=$self->token($expr[2]))?
+ $fw->stringify($mix):
+ $mix)).
+ ']';
+ },
+ $token[1]
+ );
+ },
+ $str
+ );
+ return trim($str);
+ }
+
+ /**
+ * Return records that match criteria
+ * @return array|FALSE
+ * @param $filter array
+ * @param $options array
+ * @param $ttl int
+ * @param $log bool
+ **/
+ function find($filter=NULL,array $options=NULL,$ttl=0,$log=TRUE) {
+ if (!$options)
+ $options=array();
+ $options+=array(
+ 'order'=>NULL,
+ 'limit'=>0,
+ 'offset'=>0
+ );
+ $fw=\Base::instance();
+ $cache=\Cache::instance();
+ $db=$this->db;
+ $now=microtime(TRUE);
+ $data=array();
+ if (!$fw->get('CACHE') || !$ttl || !($cached=$cache->exists(
+ $hash=$fw->hash($this->db->dir().
+ $fw->stringify(array($filter,$options))).'.jig',$data)) ||
+ $cached[0]+$ttlread($this->file);
+ if (is_null($data))
+ return FALSE;
+ foreach ($data as $id=>&$doc) {
+ $doc['_id']=$id;
+ unset($doc);
+ }
+ if ($filter) {
+ if (!is_array($filter))
+ return FALSE;
+ // Normalize equality operator
+ $expr=preg_replace('/(?<=[^<>!=])=(?!=)/','==',$filter[0]);
+ // Prepare query arguments
+ $args=isset($filter[1]) && is_array($filter[1])?
+ $filter[1]:
+ array_slice($filter,1,NULL,TRUE);
+ $args=is_array($args)?$args:array(1=>$args);
+ $keys=$vals=array();
+ $tokens=array_slice(
+ token_get_all('token($expr)),1);
+ $data=array_filter($data,
+ function($_row) use($fw,$args,$tokens) {
+ $_expr='';
+ $ctr=0;
+ $named=FALSE;
+ foreach ($tokens as $token) {
+ if (is_string($token))
+ if ($token=='?') {
+ // Positional
+ $ctr++;
+ $key=$ctr;
+ }
+ else {
+ if ($token==':')
+ $named=TRUE;
+ else
+ $_expr.=$token;
+ continue;
+ }
+ elseif ($named &&
+ token_name($token[0])=='T_STRING') {
+ $key=':'.$token[1];
+ $named=FALSE;
+ }
+ else {
+ $_expr.=$token[1];
+ continue;
+ }
+ $_expr.=$fw->stringify(
+ is_string($args[$key])?
+ addcslashes($args[$key],'\''):
+ $args[$key]);
+ }
+ // Avoid conflict with user code
+ unset($fw,$tokens,$args,$ctr,$token,$key,$named);
+ extract($_row);
+ // Evaluate pseudo-SQL expression
+ return eval('return '.$_expr.';');
+ }
+ );
+ }
+ if (isset($options['order'])) {
+ $cols=$fw->split($options['order']);
+ uasort(
+ $data,
+ function($val1,$val2) use($cols) {
+ foreach ($cols as $col) {
+ $parts=explode(' ',$col,2);
+ $order=empty($parts[1])?
+ SORT_ASC:
+ constant($parts[1]);
+ $col=$parts[0];
+ if (!array_key_exists($col,$val1))
+ $val1[$col]=NULL;
+ if (!array_key_exists($col,$val2))
+ $val2[$col]=NULL;
+ list($v1,$v2)=array($val1[$col],$val2[$col]);
+ if ($out=strnatcmp($v1,$v2)*
+ (($order==SORT_ASC)*2-1))
+ return $out;
+ }
+ return 0;
+ }
+ );
+ }
+ $data=array_slice($data,
+ $options['offset'],$options['limit']?:NULL,TRUE);
+ if ($fw->get('CACHE') && $ttl)
+ // Save to cache backend
+ $cache->set($hash,$data,$ttl);
+ }
+ $out=array();
+ foreach ($data as $id=>&$doc) {
+ unset($doc['_id']);
+ $out[]=$this->factory($id,$doc);
+ unset($doc);
+ }
+ if ($log && isset($args)) {
+ if ($filter)
+ foreach ($args as $key=>$val) {
+ $vals[]=$fw->stringify(is_array($val)?$val[0]:$val);
+ $keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
+ }
+ $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
+ $this->file.' [find] '.
+ ($filter?preg_replace($keys,$vals,$filter[0],1):''));
+ }
+ return $out;
+ }
+
+ /**
+ * Count records that match criteria
+ * @return int
+ * @param $filter array
+ * @param $ttl int
+ **/
+ function count($filter=NULL,$ttl=0) {
+ $now=microtime(TRUE);
+ $out=count($this->find($filter,NULL,$ttl,FALSE));
+ $this->db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
+ $this->file.' [count] '.($filter?json_encode($filter):''));
+ return $out;
+ }
+
+ /**
+ * Return record at specified offset using criteria of previous
+ * load() call and make it active
+ * @return array
+ * @param $ofs int
+ **/
+ function skip($ofs=1) {
+ $this->document=($out=parent::skip($ofs))?$out->document:array();
+ $this->id=$out?$out->id:NULL;
+ if ($this->document && isset($this->trigger['load']))
+ \Base::instance()->call($this->trigger['load'],$this);
+ return $out;
+ }
+
+ /**
+ * Insert new record
+ * @return array
+ **/
+ function insert() {
+ if ($this->id)
+ return $this->update();
+ $db=$this->db;
+ $now=microtime(TRUE);
+ while (($id=uniqid(NULL,TRUE)) &&
+ ($data=$db->read($this->file)) && isset($data[$id]) &&
+ !connection_aborted())
+ usleep(mt_rand(0,100));
+ $this->id=$id;
+ $data[$id]=$this->document;
+ $pkey=array('_id'=>$this->id);
+ if (isset($this->trigger['beforeinsert']))
+ \Base::instance()->call($this->trigger['beforeinsert'],
+ array($this,$pkey));
+ $db->write($this->file,$data);
+ $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
+ $this->file.' [insert] '.json_encode($this->document));
+ if (isset($this->trigger['afterinsert']))
+ \Base::instance()->call($this->trigger['afterinsert'],
+ array($this,$pkey));
+ $this->load(array('@_id=?',$this->id));
+ return $this->document;
+ }
+
+ /**
+ * Update current record
+ * @return array
+ **/
+ function update() {
+ $db=$this->db;
+ $now=microtime(TRUE);
+ $data=$db->read($this->file);
+ $data[$this->id]=$this->document;
+ if (isset($this->trigger['beforeupdate']))
+ \Base::instance()->call($this->trigger['beforeupdate'],
+ array($this,array('_id'=>$this->id)));
+ $db->write($this->file,$data);
+ $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
+ $this->file.' [update] '.json_encode($this->document));
+ if (isset($this->trigger['afterupdate']))
+ \Base::instance()->call($this->trigger['afterupdate'],
+ array($this,array('_id'=>$this->id)));
+ return $this->document;
+ }
+
+ /**
+ * Delete current record
+ * @return bool
+ * @param $filter array
+ **/
+ function erase($filter=NULL) {
+ $db=$this->db;
+ $now=microtime(TRUE);
+ $data=$db->read($this->file);
+ if ($filter) {
+ foreach ($this->find($filter,NULL,FALSE) as $mapper)
+ if (!$mapper->erase())
+ return FALSE;
+ return TRUE;
+ }
+ elseif (isset($this->id)) {
+ $pkey=array('_id'=>$this->id);
+ unset($data[$this->id]);
+ parent::erase();
+ $this->skip(0);
+ }
+ else
+ return FALSE;
+ if (isset($this->trigger['beforeerase']))
+ \Base::instance()->call($this->trigger['beforeerase'],
+ array($this,$pkey));
+ $db->write($this->file,$data);
+ if ($filter) {
+ $args=isset($filter[1]) && is_array($filter[1])?
+ $filter[1]:
+ array_slice($filter,1,NULL,TRUE);
+ $args=is_array($args)?$args:array(1=>$args);
+ foreach ($args as $key=>$val) {
+ $vals[]=\Base::instance()->
+ stringify(is_array($val)?$val[0]:$val);
+ $keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
+ }
+ }
+ $db->jot('('.sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
+ $this->file.' [erase] '.
+ ($filter?preg_replace($keys,$vals,$filter[0],1):''));
+ if (isset($this->trigger['aftererase']))
+ \Base::instance()->call($this->trigger['aftererase'],
+ array($this,$pkey));
+ return TRUE;
+ }
+
+ /**
+ * Reset cursor
+ * @return NULL
+ **/
+ function reset() {
+ $this->id=NULL;
+ $this->document=array();
+ parent::reset();
+ }
+
+ /**
+ * Hydrate mapper object using hive array variable
+ * @return NULL
+ * @param $key string
+ * @param $func callback
+ **/
+ function copyfrom($key,$func=NULL) {
+ $var=\Base::instance()->get($key);
+ if ($func)
+ $var=$func($var);
+ foreach ($var as $key=>$val)
+ $this->document[$key]=$val;
+ }
+
+ /**
+ * Populate hive array variable with mapper fields
+ * @return NULL
+ * @param $key string
+ **/
+ function copyto($key) {
+ $var=&\Base::instance()->ref($key);
+ foreach ($this->document as $key=>$field)
+ $var[$key]=$field;
+ }
+
+ /**
+ * Return field names
+ * @return array
+ **/
+ function fields() {
+ return array_keys($this->document);
+ }
+
+ /**
+ * Instantiate class
+ * @return void
+ * @param $db object
+ * @param $file string
+ **/
+ function __construct(\DB\Jig $db,$file) {
+ $this->db=$db;
+ $this->file=$file;
+ $this->reset();
+ }
+
+}
diff --git a/management-interface/lib/db/jig/session.php b/management-interface/lib/db/jig/session.php
new file mode 100644
index 0000000..705cbce
--- /dev/null
+++ b/management-interface/lib/db/jig/session.php
@@ -0,0 +1,168 @@
+sid)
+ $this->load(array('@session_id=?',$this->sid=$id));
+ return $this->dry()?FALSE:$this->get('data');
+ }
+
+ /**
+ * Write session data
+ * @return TRUE
+ * @param $id string
+ * @param $data string
+ **/
+ function write($id,$data) {
+ $fw=\Base::instance();
+ $sent=headers_sent();
+ $headers=$fw->get('HEADERS');
+ if ($id!=$this->sid)
+ $this->load(array('@session_id=?',$this->sid=$id));
+ $csrf=$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash(mt_rand());
+ $this->set('session_id',$id);
+ $this->set('data',$data);
+ $this->set('csrf',$sent?$this->csrf():$csrf);
+ $this->set('ip',$fw->get('IP'));
+ $this->set('agent',
+ isset($headers['User-Agent'])?$headers['User-Agent']:'');
+ $this->set('stamp',time());
+ $this->save();
+ return TRUE;
+ }
+
+ /**
+ * Destroy session
+ * @return TRUE
+ * @param $id string
+ **/
+ function destroy($id) {
+ $this->erase(array('@session_id=?',$id));
+ setcookie(session_name(),'',strtotime('-1 year'));
+ unset($_COOKIE[session_name()]);
+ header_remove('Set-Cookie');
+ return TRUE;
+ }
+
+ /**
+ * Garbage collector
+ * @return TRUE
+ * @param $max int
+ **/
+ function cleanup($max) {
+ $this->erase(array('@stamp+?',$max,time()));
+ return TRUE;
+ }
+
+ /**
+ * Return anti-CSRF token
+ * @return string|FALSE
+ **/
+ function csrf() {
+ return $this->dry()?FALSE:$this->get('csrf');
+ }
+
+ /**
+ * Return IP address
+ * @return string|FALSE
+ **/
+ function ip() {
+ return $this->dry()?FALSE:$this->get('ip');
+ }
+
+ /**
+ * Return Unix timestamp
+ * @return string|FALSE
+ **/
+ function stamp() {
+ return $this->dry()?FALSE:$this->get('stamp');
+ }
+
+ /**
+ * Return HTTP user agent
+ * @return string|FALSE
+ **/
+ function agent() {
+ return $this->dry()?FALSE:$this->get('agent');
+ }
+
+ /**
+ * Instantiate class
+ * @param $db object
+ * @param $table string
+ **/
+ function __construct(\DB\Jig $db,$table='sessions') {
+ parent::__construct($db,'sessions');
+ session_set_save_handler(
+ array($this,'open'),
+ array($this,'close'),
+ array($this,'read'),
+ array($this,'write'),
+ array($this,'destroy'),
+ array($this,'cleanup')
+ );
+ register_shutdown_function('session_commit');
+ @session_start();
+ $fw=\Base::instance();
+ $headers=$fw->get('HEADERS');
+ if (($ip=$this->ip()) && $ip!=$fw->get('IP') ||
+ ($agent=$this->agent()) &&
+ (!isset($headers['User-Agent']) ||
+ $agent!=$headers['User-Agent'])) {
+ session_destroy();
+ $fw->error(403);
+ }
+ $csrf=$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash(mt_rand());
+ if ($this->load(array('@session_id=?',$this->sid=session_id()))) {
+ $this->set('csrf',$csrf);
+ $this->save();
+ }
+ }
+
+}
diff --git a/management-interface/lib/db/mongo.php b/management-interface/lib/db/mongo.php
new file mode 100644
index 0000000..833f160
--- /dev/null
+++ b/management-interface/lib/db/mongo.php
@@ -0,0 +1,92 @@
+dsn;
+ }
+
+ /**
+ * Return UUID
+ * @return string
+ **/
+ function uuid() {
+ return $this->uuid;
+ }
+
+ /**
+ * Return MongoDB profiler results
+ * @return string
+ **/
+ function log() {
+ $cursor=$this->selectcollection('system.profile')->find();
+ foreach (iterator_to_array($cursor) as $frame)
+ if (!preg_match('/\.system\..+$/',$frame['ns']))
+ $this->log.=date('r',$frame['ts']->sec).' ('.
+ sprintf('%.1f',$frame['millis']).'ms) '.
+ $frame['ns'].' ['.$frame['op'].'] '.
+ (empty($frame['query'])?
+ '':json_encode($frame['query'])).
+ (empty($frame['command'])?
+ '':json_encode($frame['command'])).
+ PHP_EOL;
+ return $this->log;
+ }
+
+ /**
+ * Intercept native call to re-enable profiler
+ * @return int
+ **/
+ function drop() {
+ $out=parent::drop();
+ $this->setprofilinglevel(2);
+ return $out;
+ }
+
+ /**
+ * Instantiate class
+ * @param $dsn string
+ * @param $dbname string
+ * @param $options array
+ **/
+ function __construct($dsn,$dbname,array $options=NULL) {
+ $this->uuid=\Base::instance()->hash($this->dsn=$dsn);
+ $class=class_exists('\MongoClient')?'\MongoClient':'\Mongo';
+ parent::__construct(new $class($dsn,$options?:array()),$dbname);
+ $this->setprofilinglevel(2);
+ }
+
+}
diff --git a/management-interface/lib/db/mongo/mapper.php b/management-interface/lib/db/mongo/mapper.php
new file mode 100644
index 0000000..bcb7f6e
--- /dev/null
+++ b/management-interface/lib/db/mongo/mapper.php
@@ -0,0 +1,346 @@
+document);
+ }
+
+ /**
+ * Assign value to field
+ * @return scalar|FALSE
+ * @param $key string
+ * @param $val scalar
+ **/
+ function set($key,$val) {
+ return $this->document[$key]=$val;
+ }
+
+ /**
+ * Retrieve value of field
+ * @return scalar|FALSE
+ * @param $key string
+ **/
+ function get($key) {
+ if ($this->exists($key))
+ return $this->document[$key];
+ user_error(sprintf(self::E_Field,$key));
+ return FALSE;
+ }
+
+ /**
+ * Delete field
+ * @return NULL
+ * @param $key string
+ **/
+ function clear($key) {
+ unset($this->document[$key]);
+ }
+
+ /**
+ * Convert array to mapper object
+ * @return object
+ * @param $row array
+ **/
+ protected function factory($row) {
+ $mapper=clone($this);
+ $mapper->reset();
+ foreach ($row as $key=>$val)
+ $mapper->document[$key]=$val;
+ $mapper->query=array(clone($mapper));
+ if (isset($mapper->trigger['load']))
+ \Base::instance()->call($mapper->trigger['load'],$mapper);
+ return $mapper;
+ }
+
+ /**
+ * Return fields of mapper object as an associative array
+ * @return array
+ * @param $obj object
+ **/
+ function cast($obj=NULL) {
+ if (!$obj)
+ $obj=$this;
+ return $obj->document;
+ }
+
+ /**
+ * Build query and execute
+ * @return array
+ * @param $fields string
+ * @param $filter array
+ * @param $options array
+ * @param $ttl int
+ **/
+ function select($fields=NULL,$filter=NULL,array $options=NULL,$ttl=0) {
+ if (!$options)
+ $options=array();
+ $options+=array(
+ 'group'=>NULL,
+ 'order'=>NULL,
+ 'limit'=>0,
+ 'offset'=>0
+ );
+ $fw=\Base::instance();
+ $cache=\Cache::instance();
+ if (!($cached=$cache->exists($hash=$fw->hash($this->db->dsn().
+ $fw->stringify(array($fields,$filter,$options))).'.mongo',
+ $result)) || !$ttl || $cached[0]+$ttlcollection->group(
+ $options['group']['keys'],
+ $options['group']['initial'],
+ $options['group']['reduce'],
+ array(
+ 'condition'=>$filter,
+ 'finalize'=>$options['group']['finalize']
+ )
+ );
+ $tmp=$this->db->selectcollection(
+ $fw->get('HOST').'.'.$fw->get('BASE').'.'.
+ uniqid(NULL,TRUE).'.tmp'
+ );
+ $tmp->batchinsert($grp['retval'],array('safe'=>TRUE));
+ $filter=array();
+ $collection=$tmp;
+ }
+ else {
+ $filter=$filter?:array();
+ $collection=$this->collection;
+ }
+ $this->cursor=$collection->find($filter,$fields?:array());
+ if ($options['order'])
+ $this->cursor=$this->cursor->sort($options['order']);
+ if ($options['limit'])
+ $this->cursor=$this->cursor->limit($options['limit']);
+ if ($options['offset'])
+ $this->cursor=$this->cursor->skip($options['offset']);
+ $result=array();
+ while ($this->cursor->hasnext())
+ $result[]=$this->cursor->getnext();
+ if ($options['group'])
+ $tmp->drop();
+ if ($fw->get('CACHE') && $ttl)
+ // Save to cache backend
+ $cache->set($hash,$result,$ttl);
+ }
+ $out=array();
+ foreach ($result as $doc)
+ $out[]=$this->factory($doc);
+ return $out;
+ }
+
+ /**
+ * Return records that match criteria
+ * @return array
+ * @param $filter array
+ * @param $options array
+ * @param $ttl int
+ **/
+ function find($filter=NULL,array $options=NULL,$ttl=0) {
+ if (!$options)
+ $options=array();
+ $options+=array(
+ 'group'=>NULL,
+ 'order'=>NULL,
+ 'limit'=>0,
+ 'offset'=>0
+ );
+ return $this->select(NULL,$filter,$options,$ttl);
+ }
+
+ /**
+ * Count records that match criteria
+ * @return int
+ * @param $filter array
+ * @param $ttl int
+ **/
+ function count($filter=NULL,$ttl=0) {
+ $fw=\Base::instance();
+ $cache=\Cache::instance();
+ if (!($cached=$cache->exists($hash=$fw->hash($fw->stringify(
+ array($filter))).'.mongo',$result)) || !$ttl ||
+ $cached[0]+$ttlcollection->count($filter);
+ if ($fw->get('CACHE') && $ttl)
+ // Save to cache backend
+ $cache->set($hash,$result,$ttl);
+ }
+ return $result;
+ }
+
+ /**
+ * Return record at specified offset using criteria of previous
+ * load() call and make it active
+ * @return array
+ * @param $ofs int
+ **/
+ function skip($ofs=1) {
+ $this->document=($out=parent::skip($ofs))?$out->document:array();
+ if ($this->document && isset($this->trigger['load']))
+ \Base::instance()->call($this->trigger['load'],$this);
+ return $out;
+ }
+
+ /**
+ * Insert new record
+ * @return array
+ **/
+ function insert() {
+ if (isset($this->document['_id']))
+ return $this->update();
+ if (isset($this->trigger['beforeinsert']))
+ \Base::instance()->call($this->trigger['beforeinsert'],
+ array($this,$pkey));
+ $this->collection->insert($this->document);
+ $pkey=array('_id'=>$this->document['_id']);
+ if (isset($this->trigger['afterinsert']))
+ \Base::instance()->call($this->trigger['afterinsert'],
+ array($this,$pkey));
+ $this->load(array('_id'=>$this->document['_id']));
+ return $this->document;
+ }
+
+ /**
+ * Update current record
+ * @return array
+ **/
+ function update() {
+ if (isset($this->trigger['beforeupdate']))
+ \Base::instance()->call($this->trigger['beforeupdate'],
+ array($this,$pkey));
+ $this->collection->update(
+ $pkey=array('_id'=>$this->document['_id']),
+ $this->document,
+ array('upsert'=>TRUE)
+ );
+ if (isset($this->trigger['afterupdate']))
+ \Base::instance()->call($this->trigger['afterupdate'],
+ array($this,$pkey));
+ return $this->document;
+ }
+
+ /**
+ * Delete current record
+ * @return bool
+ * @param $filter array
+ **/
+ function erase($filter=NULL) {
+ if ($filter)
+ return $this->collection->remove($filter);
+ $pkey=array('_id'=>$this->document['_id']);
+ if (isset($this->trigger['beforeerase']))
+ \Base::instance()->call($this->trigger['beforeerase'],
+ array($this,$pkey));
+ $result=$this->collection->
+ remove(array('_id'=>$this->document['_id']));
+ parent::erase();
+ $this->skip(0);
+ if (isset($this->trigger['aftererase']))
+ \Base::instance()->call($this->trigger['aftererase'],
+ array($this,$pkey));
+ return $result;
+ }
+
+ /**
+ * Reset cursor
+ * @return NULL
+ **/
+ function reset() {
+ $this->document=array();
+ parent::reset();
+ }
+
+ /**
+ * Hydrate mapper object using hive array variable
+ * @return NULL
+ * @param $key string
+ * @param $func callback
+ **/
+ function copyfrom($key,$func=NULL) {
+ $var=\Base::instance()->get($key);
+ if ($func)
+ $var=$func($var);
+ foreach ($var as $key=>$val)
+ $this->document[$key]=$val;
+ }
+
+ /**
+ * Populate hive array variable with mapper fields
+ * @return NULL
+ * @param $key string
+ **/
+ function copyto($key) {
+ $var=&\Base::instance()->ref($key);
+ foreach ($this->document as $key=>$field)
+ $var[$key]=$field;
+ }
+
+ /**
+ * Return field names
+ * @return array
+ **/
+ function fields() {
+ return array_keys($this->document);
+ }
+
+ /**
+ * Return the cursor from last query
+ * @return object|NULL
+ **/
+ function cursor() {
+ return $this->cursor;
+ }
+
+ /**
+ * Instantiate class
+ * @return void
+ * @param $db object
+ * @param $collection string
+ **/
+ function __construct(\DB\Mongo $db,$collection) {
+ $this->db=$db;
+ $this->collection=$db->{$collection};
+ $this->reset();
+ }
+
+}
diff --git a/management-interface/lib/db/mongo/session.php b/management-interface/lib/db/mongo/session.php
new file mode 100644
index 0000000..e3c6665
--- /dev/null
+++ b/management-interface/lib/db/mongo/session.php
@@ -0,0 +1,174 @@
+sid)
+ $this->load(array('session_id'=>$this->sid=$id));
+ return $this->dry()?FALSE:$this->get('data');
+ }
+
+ /**
+ * Write session data
+ * @return TRUE
+ * @param $id string
+ * @param $data string
+ **/
+ function write($id,$data) {
+ $fw=\Base::instance();
+ $sent=headers_sent();
+ $headers=$fw->get('HEADERS');
+ if ($id!=$this->sid)
+ $this->load(array('session_id'=>$this->sid=$id));
+ $csrf=$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash(mt_rand());
+ $this->set('session_id',$id);
+ $this->set('data',$data);
+ $this->set('csrf',$sent?$this->csrf():$csrf);
+ $this->set('ip',$fw->get('IP'));
+ $this->set('agent',
+ isset($headers['User-Agent'])?$headers['User-Agent']:'');
+ $this->set('stamp',time());
+ $this->save();
+ if (!$sent) {
+ if (isset($_COOKIE['_']))
+ setcookie('_','',strtotime('-1 year'));
+ call_user_func_array('setcookie',
+ array('_',$csrf)+$fw->get('JAR'));
+ }
+ return TRUE;
+ }
+
+ /**
+ * Destroy session
+ * @return TRUE
+ * @param $id string
+ **/
+ function destroy($id) {
+ $this->erase(array('session_id'=>$id));
+ setcookie(session_name(),'',strtotime('-1 year'));
+ unset($_COOKIE[session_name()]);
+ header_remove('Set-Cookie');
+ return TRUE;
+ }
+
+ /**
+ * Garbage collector
+ * @return TRUE
+ * @param $max int
+ **/
+ function cleanup($max) {
+ $this->erase(array('$where'=>'this.stamp+'.$max.'<'.time()));
+ return TRUE;
+ }
+
+ /**
+ * Return anti-CSRF token
+ * @return string|FALSE
+ **/
+ function csrf() {
+ return $this->dry()?FALSE:$this->get('csrf');
+ }
+
+ /**
+ * Return IP address
+ * @return string|FALSE
+ **/
+ function ip() {
+ return $this->dry()?FALSE:$this->get('ip');
+ }
+
+ /**
+ * Return Unix timestamp
+ * @return string|FALSE
+ **/
+ function stamp() {
+ return $this->dry()?FALSE:$this->get('stamp');
+ }
+
+ /**
+ * Return HTTP user agent
+ * @return string|FALSE
+ **/
+ function agent() {
+ return $this->dry()?FALSE:$this->get('agent');
+ }
+
+ /**
+ * Instantiate class
+ * @param $db object
+ * @param $table string
+ **/
+ function __construct(\DB\Mongo $db,$table='sessions') {
+ parent::__construct($db,$table);
+ session_set_save_handler(
+ array($this,'open'),
+ array($this,'close'),
+ array($this,'read'),
+ array($this,'write'),
+ array($this,'destroy'),
+ array($this,'cleanup')
+ );
+ register_shutdown_function('session_commit');
+ @session_start();
+ $fw=\Base::instance();
+ $headers=$fw->get('HEADERS');
+ if (($ip=$this->ip()) && $ip!=$fw->get('IP') ||
+ ($agent=$this->agent()) &&
+ (!isset($headers['User-Agent']) ||
+ $agent!=$headers['User-Agent'])) {
+ session_destroy();
+ $fw->error(403);
+ }
+ $csrf=$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash(mt_rand());
+ if ($this->load(array('session_id'=>$this->sid=session_id()))) {
+ $this->set('csrf',$csrf);
+ $this->save();
+ }
+ }
+
+}
diff --git a/management-interface/lib/db/sql.php b/management-interface/lib/db/sql.php
new file mode 100644
index 0000000..88e34dc
--- /dev/null
+++ b/management-interface/lib/db/sql.php
@@ -0,0 +1,403 @@
+trans=TRUE;
+ return $out;
+ }
+
+ /**
+ * Rollback SQL transaction
+ * @return bool
+ **/
+ function rollback() {
+ $out=parent::rollback();
+ $this->trans=FALSE;
+ return $out;
+ }
+
+ /**
+ * Commit SQL transaction
+ * @return bool
+ **/
+ function commit() {
+ $out=parent::commit();
+ $this->trans=FALSE;
+ return $out;
+ }
+
+ /**
+ * Map data type of argument to a PDO constant
+ * @return int
+ * @param $val scalar
+ **/
+ function type($val) {
+ switch (gettype($val)) {
+ case 'NULL':
+ return \PDO::PARAM_NULL;
+ case 'boolean':
+ return \PDO::PARAM_BOOL;
+ case 'integer':
+ return \PDO::PARAM_INT;
+ default:
+ return \PDO::PARAM_STR;
+ }
+ }
+
+ /**
+ * Cast value to PHP type
+ * @return scalar
+ * @param $type string
+ * @param $val scalar
+ **/
+ function value($type,$val) {
+ switch ($type) {
+ case \PDO::PARAM_NULL:
+ return (unset)$val;
+ case \PDO::PARAM_INT:
+ return (int)$val;
+ case \PDO::PARAM_BOOL:
+ return (bool)$val;
+ case \PDO::PARAM_STR:
+ return (string)$val;
+ }
+ }
+
+ /**
+ * Execute SQL statement(s)
+ * @return array|int|FALSE
+ * @param $cmds string|array
+ * @param $args string|array
+ * @param $ttl int
+ * @param $log bool
+ **/
+ function exec($cmds,$args=NULL,$ttl=0,$log=TRUE) {
+ $auto=FALSE;
+ if (is_null($args))
+ $args=array();
+ elseif (is_scalar($args))
+ $args=array(1=>$args);
+ if (is_array($cmds)) {
+ if (count($args)<($count=count($cmds)))
+ // Apply arguments to SQL commands
+ $args=array_fill(0,$count,$args);
+ if (!$this->trans) {
+ $this->begin();
+ $auto=TRUE;
+ }
+ }
+ else {
+ $cmds=array($cmds);
+ $args=array($args);
+ }
+ $fw=\Base::instance();
+ $cache=\Cache::instance();
+ $result=FALSE;
+ foreach (array_combine($cmds,$args) as $cmd=>$arg) {
+ if (!preg_replace('/(^\s+|[\s;]+$)/','',$cmd))
+ continue;
+ $now=microtime(TRUE);
+ $keys=$vals=array();
+ if ($fw->get('CACHE') && $ttl && ($cached=$cache->exists(
+ $hash=$fw->hash($this->dsn.$cmd.
+ $fw->stringify($arg)).'.sql',$result)) &&
+ $cached[0]+$ttl>microtime(TRUE)) {
+ foreach ($arg as $key=>$val) {
+ $vals[]=$fw->stringify(is_array($val)?$val[0]:$val);
+ $keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
+ }
+ }
+ elseif (is_object($query=$this->prepare($cmd))) {
+ foreach ($arg as $key=>$val) {
+ if (is_array($val)) {
+ // User-specified data type
+ $query->bindvalue($key,$val[0],$val[1]);
+ $vals[]=$fw->stringify($this->value($val[1],$val[0]));
+ }
+ else {
+ // Convert to PDO data type
+ $query->bindvalue($key,$val,
+ $type=$this->type($val));
+ $vals[]=$fw->stringify($this->value($type,$val));
+ }
+ $keys[]='/'.(is_numeric($key)?'\?':preg_quote($key)).'/';
+ }
+ $query->execute();
+ $error=$query->errorinfo();
+ if ($error[0]!=\PDO::ERR_NONE) {
+ // Statement-level error occurred
+ if ($this->trans)
+ $this->rollback();
+ user_error('PDOStatement: '.$error[2]);
+ }
+ if (preg_match('/^\s*'.
+ '(?:CALL|EXPLAIN|SELECT|PRAGMA|SHOW|RETURNING|EXEC)\b/is',
+ $cmd)) {
+ $result=$query->fetchall(\PDO::FETCH_ASSOC);
+ // Work around SQLite quote bug
+ if (preg_match('/sqlite2?/',$this->engine))
+ foreach ($result as $pos=>$rec) {
+ unset($result[$pos]);
+ $result[$pos]=array();
+ foreach ($rec as $key=>$val)
+ $result[$pos][trim($key,'\'"[]`')]=$val;
+ }
+ $this->rows=count($result);
+ if ($fw->get('CACHE') && $ttl)
+ // Save to cache backend
+ $cache->set($hash,$result,$ttl);
+ }
+ else
+ $this->rows=$result=$query->rowcount();
+ $query->closecursor();
+ unset($query);
+ }
+ else {
+ $error=$this->errorinfo();
+ if ($error[0]!=\PDO::ERR_NONE) {
+ // PDO-level error occurred
+ if ($this->trans)
+ $this->rollback();
+ user_error('PDO: '.$error[2]);
+ }
+ }
+ if ($log)
+ $this->log.=date('r').' ('.
+ sprintf('%.1f',1e3*(microtime(TRUE)-$now)).'ms) '.
+ (empty($cached)?'':'[CACHED] ').
+ preg_replace($keys,$vals,$cmd,1).PHP_EOL;
+ }
+ if ($this->trans && $auto)
+ $this->commit();
+ return $result;
+ }
+
+ /**
+ * Return number of rows affected by last query
+ * @return int
+ **/
+ function count() {
+ return $this->rows;
+ }
+
+ /**
+ * Return SQL profiler results
+ * @return string
+ **/
+ function log() {
+ return $this->log;
+ }
+
+ /**
+ * Retrieve schema of SQL table
+ * @return array|FALSE
+ * @param $table string
+ * @param $fields array|string
+ * @param $ttl int
+ **/
+ function schema($table,$fields=NULL,$ttl=0) {
+ // Supported engines
+ $cmd=array(
+ 'sqlite2?'=>array(
+ 'PRAGMA table_info("'.$table.'");',
+ 'name','type','dflt_value','notnull',0,'pk',TRUE),
+ 'mysql'=>array(
+ 'SHOW columns FROM `'.$this->dbname.'`.`'.$table.'`;',
+ 'Field','Type','Default','Null','YES','Key','PRI'),
+ 'mssql|sqlsrv|sybase|dblib|pgsql|odbc'=>array(
+ 'SELECT '.
+ 'c.column_name AS field,'.
+ 'c.data_type AS type,'.
+ 'c.column_default AS defval,'.
+ 'c.is_nullable AS nullable,'.
+ 't.constraint_type AS pkey '.
+ 'FROM information_schema.columns AS c '.
+ 'LEFT OUTER JOIN '.
+ 'information_schema.key_column_usage AS k '.
+ 'ON '.
+ 'c.table_name=k.table_name AND '.
+ 'c.column_name=k.column_name AND '.
+ 'c.table_schema=k.table_schema '.
+ ($this->dbname?
+ ('AND c.table_catalog=k.table_catalog '):'').
+ 'LEFT OUTER JOIN '.
+ 'information_schema.table_constraints AS t ON '.
+ 'k.table_name=t.table_name AND '.
+ 'k.constraint_name=t.constraint_name '.
+ 'k.table_schema=t.table_schema '.
+ ($this->dbname?
+ ('AND k.table_catalog=t.table_catalog '):'').
+ 'WHERE '.
+ 'c.table_name='.$this->quote($table).' '.
+ ($this->dbname?
+ ('AND c.table_catalog='.
+ $this->quote($this->dbname)):'').
+ ';',
+ 'field','type','defval','nullable','YES','pkey','PRIMARY KEY'),
+ 'oci'=>array(
+ 'SELECT c.column_name AS field, '.
+ 'c.data_type AS type, '.
+ 'c.data_default AS defval, '.
+ 'c.nullable AS nullable, '.
+ '(SELECT t.constraint_type '.
+ 'FROM all_cons_columns acc '.
+ 'LEFT OUTER JOIN all_constraints t '.
+ 'ON acc.constraint_name=t.constraint_name '.
+ 'WHERE acc.table_name='.$this->quote($table).' '.
+ 'AND acc.column_name=c.column_name '.
+ 'AND constraint_type='.$this->quote('P').') AS pkey '.
+ 'FROM all_tab_cols c '.
+ 'WHERE c.table_name='.$this->quote($table),
+ 'FIELD','TYPE','DEFVAL','NULLABLE','Y','PKEY','P')
+ );
+ if (is_string($fields))
+ $fields=\Base::instance()->split($fields);
+ foreach ($cmd as $key=>$val)
+ if (preg_match('/'.$key.'/',$this->engine)) {
+ // Improve InnoDB performance on MySQL with
+ // SET GLOBAL innodb_stats_on_metadata=0;
+ // This requires SUPER privilege!
+ $rows=array();
+ foreach ($this->exec($val[0],NULL,$ttl) as $row) {
+ if (!$fields || in_array($row[$val[1]],$fields))
+ $rows[$row[$val[1]]]=array(
+ 'type'=>$row[$val[2]],
+ 'pdo_type'=>
+ preg_match('/int\b|int(?=eger)|bool/i',
+ $row[$val[2]],$parts)?
+ constant('\PDO::PARAM_'.
+ strtoupper($parts[0])):
+ \PDO::PARAM_STR,
+ 'default'=>$row[$val[3]],
+ 'nullable'=>$row[$val[4]]==$val[5],
+ 'pkey'=>$row[$val[6]]==$val[7]
+ );
+ }
+ return $rows;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Quote string
+ * @return string
+ * @param $val mixed
+ * @param $type int
+ **/
+ function quote($val,$type=\PDO::PARAM_STR) {
+ return $this->engine=='odbc'?
+ (is_string($val)?
+ \Base::instance()->stringify(str_replace('\'','\'\'',$val)):
+ $val):
+ parent::quote($val,$type);
+ }
+
+ /**
+ * Return UUID
+ * @return string
+ **/
+ function uuid() {
+ return $this->uuid;
+ }
+
+ /**
+ * Return database engine
+ * @return string
+ **/
+ function driver() {
+ return $this->engine;
+ }
+
+ /**
+ * Return server version
+ * @return string
+ **/
+ function version() {
+ return parent::getattribute(parent::ATTR_SERVER_VERSION);
+ }
+
+ /**
+ * Return database name
+ * @return string
+ **/
+ function name() {
+ return $this->dbname;
+ }
+
+ /**
+ * Return quoted identifier name
+ * @return string
+ * @param $key
+ **/
+ function quotekey($key) {
+ if ($this->engine=='mysql')
+ $key="`".implode('`.`',explode('.',$key))."`";
+ elseif (preg_match('/sybase|dblib/',$this->engine))
+ $key="'".implode("'.'",explode('.',$key))."'";
+ elseif (preg_match('/sqlite2?|pgsql|oci/',$this->engine))
+ $key='"'.implode('"."',explode('.',$key)).'"';
+ elseif (preg_match('/mssql|sqlsrv|odbc/',$this->engine))
+ $key="[".implode('].[',explode('.',$key))."]";
+ return $key;
+ }
+
+ /**
+ * Instantiate class
+ * @param $dsn string
+ * @param $user string
+ * @param $pw string
+ * @param $options array
+ **/
+ function __construct($dsn,$user=NULL,$pw=NULL,array $options=NULL) {
+ $fw=\Base::instance();
+ $this->uuid=$fw->hash($this->dsn=$dsn);
+ if (preg_match('/^.+?(?:dbname|database)=(.+?)(?=;|$)/i',$dsn,$parts))
+ $this->dbname=$parts[1];
+ if (!$options)
+ $options=array();
+ if (isset($parts[0]) && strstr($parts[0],':',TRUE)=='mysql')
+ $options+=array(\PDO::MYSQL_ATTR_INIT_COMMAND=>'SET NAMES '.
+ strtolower(str_replace('-','',$fw->get('ENCODING'))).';');
+ parent::__construct($dsn,$user,$pw,$options);
+ $this->engine=parent::getattribute(parent::ATTR_DRIVER_NAME);
+ }
+
+}
diff --git a/management-interface/lib/db/sql/mapper.php b/management-interface/lib/db/sql/mapper.php
new file mode 100644
index 0000000..6af4675
--- /dev/null
+++ b/management-interface/lib/db/sql/mapper.php
@@ -0,0 +1,552 @@
+fields+$this->adhoc);
+ }
+
+ /**
+ * Assign value to field
+ * @return scalar
+ * @param $key string
+ * @param $val scalar
+ **/
+ function set($key,$val) {
+ if (array_key_exists($key,$this->fields)) {
+ $val=is_null($val) && $this->fields[$key]['nullable']?
+ NULL:$this->db->value($this->fields[$key]['pdo_type'],$val);
+ if ($this->fields[$key]['value']!==$val ||
+ $this->fields[$key]['default']!==$val && is_null($val))
+ $this->fields[$key]['changed']=TRUE;
+ return $this->fields[$key]['value']=$val;
+ }
+ // Parenthesize expression in case it's a subquery
+ $this->adhoc[$key]=array('expr'=>'('.$val.')','value'=>NULL);
+ return $val;
+ }
+
+ /**
+ * Retrieve value of field
+ * @return scalar
+ * @param $key string
+ **/
+ function get($key) {
+ if ($key=='_id')
+ return $this->_id;
+ elseif (array_key_exists($key,$this->fields))
+ return $this->fields[$key]['value'];
+ elseif (array_key_exists($key,$this->adhoc))
+ return $this->adhoc[$key]['value'];
+ user_error(sprintf(self::E_Field,$key));
+ }
+
+ /**
+ * Clear value of field
+ * @return NULL
+ * @param $key string
+ **/
+ function clear($key) {
+ if (array_key_exists($key,$this->adhoc))
+ unset($this->adhoc[$key]);
+ }
+
+ /**
+ * Get PHP type equivalent of PDO constant
+ * @return string
+ * @param $pdo string
+ **/
+ function type($pdo) {
+ switch ($pdo) {
+ case \PDO::PARAM_NULL:
+ return 'unset';
+ case \PDO::PARAM_INT:
+ return 'int';
+ case \PDO::PARAM_BOOL:
+ return 'bool';
+ case \PDO::PARAM_STR:
+ return 'string';
+ }
+ }
+
+ /**
+ * Convert array to mapper object
+ * @return object
+ * @param $row array
+ **/
+ protected function factory($row) {
+ $mapper=clone($this);
+ $mapper->reset();
+ foreach ($row as $key=>$val) {
+ if (array_key_exists($key,$this->fields))
+ $var='fields';
+ elseif (array_key_exists($key,$this->adhoc))
+ $var='adhoc';
+ else
+ continue;
+ $mapper->{$var}[$key]['value']=$val;
+ if ($var=='fields' && $mapper->{$var}[$key]['pkey'])
+ $mapper->{$var}[$key]['previous']=$val;
+ }
+ $mapper->query=array(clone($mapper));
+ if (isset($mapper->trigger['load']))
+ \Base::instance()->call($mapper->trigger['load'],$mapper);
+ return $mapper;
+ }
+
+ /**
+ * Return fields of mapper object as an associative array
+ * @return array
+ * @param $obj object
+ **/
+ function cast($obj=NULL) {
+ if (!$obj)
+ $obj=$this;
+ return array_map(
+ function($row) {
+ return $row['value'];
+ },
+ $obj->fields+$obj->adhoc
+ );
+ }
+
+ /**
+ * Build query string and execute
+ * @return array
+ * @param $fields string
+ * @param $filter string|array
+ * @param $options array
+ * @param $ttl int
+ **/
+ function select($fields,$filter=NULL,array $options=NULL,$ttl=0) {
+ if (!$options)
+ $options=array();
+ $options+=array(
+ 'group'=>NULL,
+ 'order'=>NULL,
+ 'limit'=>0,
+ 'offset'=>0
+ );
+ $sql='SELECT '.$fields.' FROM '.$this->table;
+ $args=array();
+ if ($filter) {
+ if (is_array($filter)) {
+ $args=isset($filter[1]) && is_array($filter[1])?
+ $filter[1]:
+ array_slice($filter,1,NULL,TRUE);
+ $args=is_array($args)?$args:array(1=>$args);
+ list($filter)=$filter;
+ }
+ $sql.=' WHERE '.$filter;
+ }
+ $db=$this->db;
+ if ($options['group'])
+ $sql.=' GROUP BY '.implode(',',array_map(
+ function($str) use($db) {
+ return preg_match('/^(\w+)(?:\h+HAVING|\h*(?:,|$))/i',
+ $str,$parts)?
+ ($db->quotekey($parts[1]).
+ (isset($parts[2])?(' '.$parts[2]):'')):$str;
+ },
+ explode(',',$options['group'])));
+ if ($options['order']) {
+ $sql.=' ORDER BY '.implode(',',array_map(
+ function($str) use($db) {
+ return preg_match('/^(\w+)(?:\h+(ASC|DESC))?\h*(?:,|$)/i',
+ $str,$parts)?
+ ($db->quotekey($parts[1]).
+ (isset($parts[2])?(' '.$parts[2]):'')):$str;
+ },
+ explode(',',$options['order'])));
+ }
+ if ($options['limit'])
+ $sql.=' LIMIT '.(int)$options['limit'];
+ if ($options['offset'])
+ $sql.=' OFFSET '.(int)$options['offset'];
+ $result=$this->db->exec($sql,$args,$ttl);
+ $out=array();
+ foreach ($result as &$row) {
+ foreach ($row as $field=>&$val) {
+ if (array_key_exists($field,$this->fields)) {
+ if (!is_null($val) || !$this->fields[$field]['nullable'])
+ $val=$this->db->value(
+ $this->fields[$field]['pdo_type'],$val);
+ }
+ elseif (array_key_exists($field,$this->adhoc))
+ $this->adhoc[$field]['value']=$val;
+ unset($val);
+ }
+ $out[]=$this->factory($row);
+ unset($row);
+ }
+ return $out;
+ }
+
+ /**
+ * Return records that match criteria
+ * @return array
+ * @param $filter string|array
+ * @param $options array
+ * @param $ttl int
+ **/
+ function find($filter=NULL,array $options=NULL,$ttl=0) {
+ if (!$options)
+ $options=array();
+ $options+=array(
+ 'group'=>NULL,
+ 'order'=>NULL,
+ 'limit'=>0,
+ 'offset'=>0
+ );
+ $adhoc='';
+ foreach ($this->adhoc as $key=>$field)
+ $adhoc.=','.$field['expr'].' AS '.$this->db->quotekey($key);
+ return $this->select(implode(',',
+ array_map(array($this->db,'quotekey'),array_keys($this->fields))).
+ $adhoc,$filter,$options,$ttl);
+ }
+
+ /**
+ * Count records that match criteria
+ * @return int
+ * @param $filter string|array
+ * @param $ttl int
+ **/
+ function count($filter=NULL,$ttl=0) {
+ $sql='SELECT COUNT(*) AS '.
+ $this->db->quotekey('rows').' FROM '.$this->table;
+ $args=array();
+ if ($filter) {
+ if (is_array($filter)) {
+ $args=isset($filter[1]) && is_array($filter[1])?
+ $filter[1]:
+ array_slice($filter,1,NULL,TRUE);
+ $args=is_array($args)?$args:array(1=>$args);
+ list($filter)=$filter;
+ }
+ $sql.=' WHERE '.$filter;
+ }
+ $result=$this->db->exec($sql,$args,$ttl);
+ return $result[0]['rows'];
+ }
+
+ /**
+ * Return record at specified offset using same criteria as
+ * previous load() call and make it active
+ * @return array
+ * @param $ofs int
+ **/
+ function skip($ofs=1) {
+ $out=parent::skip($ofs);
+ $dry=$this->dry();
+ foreach ($this->fields as $key=>&$field) {
+ $field['value']=$dry?NULL:$out->fields[$key]['value'];
+ $field['changed']=FALSE;
+ if ($field['pkey'])
+ $field['previous']=$dry?NULL:$out->fields[$key]['value'];
+ unset($field);
+ }
+ foreach ($this->adhoc as $key=>&$field) {
+ $field['value']=$dry?NULL:$out->adhoc[$key]['value'];
+ unset($field);
+ }
+ if (isset($this->trigger['load']))
+ \Base::instance()->call($this->trigger['load'],$this);
+ return $out;
+ }
+
+ /**
+ * Insert new record
+ * @return object
+ **/
+ function insert() {
+ $args=array();
+ $ctr=0;
+ $fields='';
+ $values='';
+ $filter='';
+ $pkeys=array();
+ $nkeys=array();
+ $ckeys=array();
+ $inc=NULL;
+ foreach ($this->fields as $key=>$field)
+ if ($field['pkey'])
+ $pkeys[$key]=$field['previous'];
+ if (isset($this->trigger['beforeinsert']))
+ \Base::instance()->call($this->trigger['beforeinsert'],
+ array($this,$pkeys));
+ foreach ($this->fields as $key=>&$field) {
+ if ($field['pkey']) {
+ $field['previous']=$field['value'];
+ if (!$inc && $field['pdo_type']==\PDO::PARAM_INT &&
+ empty($field['value']) && !$field['nullable'])
+ $inc=$key;
+ $filter.=($filter?' AND ':'').$this->db->quotekey($key).'=?';
+ $nkeys[$ctr+1]=array($field['value'],$field['pdo_type']);
+ }
+ if ($field['changed'] && $key!=$inc) {
+ $fields.=($ctr?',':'').$this->db->quotekey($key);
+ $values.=($ctr?',':'').'?';
+ $args[$ctr+1]=array($field['value'],$field['pdo_type']);
+ $ctr++;
+ $ckeys[]=$key;
+ }
+ $field['changed']=FALSE;
+ unset($field);
+ }
+ if ($fields) {
+ $this->db->exec(
+ (preg_match('/mssql|dblib|sqlsrv/',$this->engine) &&
+ array_intersect(array_keys($pkeys),$ckeys)?
+ 'SET IDENTITY_INSERT '.$this->table.' ON;':'').
+ 'INSERT INTO '.$this->table.' ('.$fields.') '.
+ 'VALUES ('.$values.')',$args
+ );
+ $seq=NULL;
+ if ($this->engine=='pgsql') {
+ $names=array_keys($pkeys);
+ $seq=$this->source.'_'.end($names).'_seq';
+ }
+ if ($this->engine!='oci')
+ $this->_id=$this->db->lastinsertid($seq);
+ // Reload to obtain default and auto-increment field values
+ $this->load($inc?
+ array($inc.'=?',$this->db->value(
+ $this->fields[$inc]['pdo_type'],$this->_id)):
+ array($filter,$nkeys));
+ if (isset($this->trigger['afterinsert']))
+ \Base::instance()->call($this->trigger['afterinsert'],
+ array($this,$pkeys));
+ }
+ return $this;
+ }
+
+ /**
+ * Update current record
+ * @return object
+ **/
+ function update() {
+ $args=array();
+ $ctr=0;
+ $pairs='';
+ $filter='';
+ $pkeys=array();
+ foreach ($this->fields as $key=>$field)
+ if ($field['pkey'])
+ $pkeys[$key]=$field['previous'];
+ if (isset($this->trigger['beforeupdate']))
+ \Base::instance()->call($this->trigger['beforeupdate'],
+ array($this,$pkeys));
+ foreach ($this->fields as $key=>$field)
+ if ($field['changed']) {
+ $pairs.=($pairs?',':'').$this->db->quotekey($key).'=?';
+ $args[$ctr+1]=array($field['value'],$field['pdo_type']);
+ $ctr++;
+ }
+ foreach ($this->fields as $key=>$field)
+ if ($field['pkey']) {
+ $filter.=($filter?' AND ':'').$this->db->quotekey($key).'=?';
+ $args[$ctr+1]=array($field['previous'],$field['pdo_type']);
+ $ctr++;
+ }
+ if ($pairs) {
+ $sql='UPDATE '.$this->table.' SET '.$pairs;
+ if ($filter)
+ $sql.=' WHERE '.$filter;
+ $this->db->exec($sql,$args);
+ if (isset($this->trigger['afterupdate']))
+ \Base::instance()->call($this->trigger['afterupdate'],
+ array($this,$pkeys));
+ }
+ return $this;
+ }
+
+ /**
+ * Delete current record
+ * @return int
+ * @param $filter string|array
+ **/
+ function erase($filter=NULL) {
+ if ($filter) {
+ $args=array();
+ if (is_array($filter)) {
+ $args=isset($filter[1]) && is_array($filter[1])?
+ $filter[1]:
+ array_slice($filter,1,NULL,TRUE);
+ $args=is_array($args)?$args:array(1=>$args);
+ list($filter)=$filter;
+ }
+ return $this->db->
+ exec('DELETE FROM '.$this->table.' WHERE '.$filter.';',$args);
+ }
+ $args=array();
+ $ctr=0;
+ $filter='';
+ $pkeys=array();
+ foreach ($this->fields as $key=>&$field) {
+ if ($field['pkey']) {
+ $filter.=($filter?' AND ':'').$this->db->quotekey($key).'=?';
+ $args[$ctr+1]=array($field['previous'],$field['pdo_type']);
+ $pkeys[$key]=$field['previous'];
+ $ctr++;
+ }
+ $field['value']=NULL;
+ $field['changed']=(bool)$field['default'];
+ if ($field['pkey'])
+ $field['previous']=NULL;
+ unset($field);
+ }
+ foreach ($this->adhoc as &$field) {
+ $field['value']=NULL;
+ unset($field);
+ }
+ parent::erase();
+ $this->skip(0);
+ if (isset($this->trigger['beforeerase']))
+ \Base::instance()->call($this->trigger['beforeerase'],
+ array($this,$pkeys));
+ $out=$this->db->
+ exec('DELETE FROM '.$this->table.' WHERE '.$filter.';',$args);
+ if (isset($this->trigger['aftererase']))
+ \Base::instance()->call($this->trigger['aftererase'],
+ array($this,$pkeys));
+ return $out;
+ }
+
+ /**
+ * Reset cursor
+ * @return NULL
+ **/
+ function reset() {
+ foreach ($this->fields as &$field) {
+ $field['value']=NULL;
+ $field['changed']=FALSE;
+ if ($field['pkey'])
+ $field['previous']=NULL;
+ unset($field);
+ }
+ foreach ($this->adhoc as &$field) {
+ $field['value']=NULL;
+ unset($field);
+ }
+ parent::reset();
+ }
+
+ /**
+ * Hydrate mapper object using hive array variable
+ * @return NULL
+ * @param $key string
+ * @param $func callback
+ **/
+ function copyfrom($key,$func=NULL) {
+ $var=\Base::instance()->get($key);
+ if ($func)
+ $var=$func($var);
+ foreach ($var as $key=>$val)
+ if (in_array($key,array_keys($this->fields))) {
+ $field=&$this->fields[$key];
+ if ($field['value']!==$val) {
+ $field['value']=$val;
+ $field['changed']=TRUE;
+ }
+ unset($field);
+ }
+ }
+
+ /**
+ * Populate hive array variable with mapper fields
+ * @return NULL
+ * @param $key string
+ **/
+ function copyto($key) {
+ $var=&\Base::instance()->ref($key);
+ foreach ($this->fields+$this->adhoc as $key=>$field)
+ $var[$key]=$field['value'];
+ }
+
+ /**
+ * Return schema
+ * @return array
+ **/
+ function schema() {
+ return $this->fields;
+ }
+
+ /**
+ * Return field names
+ * @return array
+ * @param $adhoc bool
+ **/
+ function fields($adhoc=TRUE) {
+ return array_keys($this->fields+($adhoc?$this->adhoc:array()));
+ }
+
+ /**
+ * Instantiate class
+ * @param $db object
+ * @param $table string
+ * @param $fields array|string
+ * @param $ttl int
+ **/
+ function __construct(\DB\SQL $db,$table,$fields=NULL,$ttl=60) {
+ $this->db=$db;
+ $this->engine=$db->driver();
+ if ($this->engine=='oci')
+ $table=strtoupper($table);
+ $this->source=$table;
+ $this->table=$this->db->quotekey($table);
+ $this->fields=$db->schema($table,$fields,$ttl);
+ $this->reset();
+ }
+
+}
diff --git a/management-interface/lib/db/sql/session.php b/management-interface/lib/db/sql/session.php
new file mode 100644
index 0000000..48050ec
--- /dev/null
+++ b/management-interface/lib/db/sql/session.php
@@ -0,0 +1,187 @@
+sid)
+ $this->load(array('session_id=?',$this->sid=$id));
+ return $this->dry()?FALSE:$this->get('data');
+ }
+
+ /**
+ * Write session data
+ * @return TRUE
+ * @param $id string
+ * @param $data string
+ **/
+ function write($id,$data) {
+ $fw=\Base::instance();
+ $sent=headers_sent();
+ $headers=$fw->get('HEADERS');
+ if ($id!=$this->sid)
+ $this->load(array('session_id=?',$this->sid=$id));
+ $csrf=$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash(mt_rand());
+ $this->set('session_id',$id);
+ $this->set('data',$data);
+ $this->set('csrf',$sent?$this->csrf():$csrf);
+ $this->set('ip',$fw->get('IP'));
+ $this->set('agent',
+ isset($headers['User-Agent'])?$headers['User-Agent']:'');
+ $this->set('stamp',time());
+ $this->save();
+ return TRUE;
+ }
+
+ /**
+ * Destroy session
+ * @return TRUE
+ * @param $id string
+ **/
+ function destroy($id) {
+ $this->erase(array('session_id=?',$id));
+ setcookie(session_name(),'',strtotime('-1 year'));
+ unset($_COOKIE[session_name()]);
+ header_remove('Set-Cookie');
+ return TRUE;
+ }
+
+ /**
+ * Garbage collector
+ * @return TRUE
+ * @param $max int
+ **/
+ function cleanup($max) {
+ $this->erase(array('stamp+?',$max,time()));
+ return TRUE;
+ }
+
+ /**
+ * Return anti-CSRF token
+ * @return string|FALSE
+ **/
+ function csrf() {
+ return $this->dry()?FALSE:$this->get('csrf');
+ }
+
+ /**
+ * Return IP address
+ * @return string|FALSE
+ **/
+ function ip() {
+ return $this->dry()?FALSE:$this->get('ip');
+ }
+
+ /**
+ * Return Unix timestamp
+ * @return string|FALSE
+ **/
+ function stamp() {
+ return $this->dry()?FALSE:$this->get('stamp');
+ }
+
+ /**
+ * Return HTTP user agent
+ * @return string|FALSE
+ **/
+ function agent() {
+ return $this->dry()?FALSE:$this->get('agent');
+ }
+
+ /**
+ * Instantiate class
+ * @param $db object
+ * @param $table string
+ * @param $force bool
+ **/
+ function __construct(\DB\SQL $db,$table='sessions',$force=TRUE) {
+ if ($force)
+ $db->exec(
+ (preg_match('/mssql|sqlsrv|sybase/',$db->driver())?
+ ('IF NOT EXISTS (SELECT * FROM sysobjects WHERE '.
+ 'name='.$db->quote($table).' AND xtype=\'U\') '.
+ 'CREATE TABLE dbo.'):
+ ('CREATE TABLE IF NOT EXISTS '.
+ (($name=$db->name())?($name.'.'):''))).
+ $table.' ('.
+ 'session_id VARCHAR(40),'.
+ 'data TEXT,'.
+ 'csrf TEXT,'.
+ 'ip VARCHAR(40),'.
+ 'agent VARCHAR(255),'.
+ 'stamp INTEGER,'.
+ 'PRIMARY KEY(session_id)'.
+ ');'
+ );
+ parent::__construct($db,$table);
+ session_set_save_handler(
+ array($this,'open'),
+ array($this,'close'),
+ array($this,'read'),
+ array($this,'write'),
+ array($this,'destroy'),
+ array($this,'cleanup')
+ );
+ register_shutdown_function('session_commit');
+ @session_start();
+ $fw=\Base::instance();
+ $headers=$fw->get('HEADERS');
+ if (($ip=$this->ip()) && $ip!=$fw->get('IP') ||
+ ($agent=$this->agent()) &&
+ (!isset($headers['User-Agent']) ||
+ $agent!=$headers['User-Agent'])) {
+ session_destroy();
+ $fw->error(403);
+ }
+ $csrf=$fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash(mt_rand());
+ if ($this->load(array('session_id=?',$this->sid=session_id()))) {
+ $this->set('csrf',$csrf);
+ $this->save();
+ }
+ }
+
+}
diff --git a/management-interface/lib/f3.php b/management-interface/lib/f3.php
new file mode 100644
index 0000000..4788d58
--- /dev/null
+++ b/management-interface/lib/f3.php
@@ -0,0 +1,35 @@
+6)
+ user_error(sprintf(self::E_Color,'0x'.$hex));
+ $color=str_split($hex,$len/3);
+ foreach ($color as &$hue) {
+ $hue=hexdec(str_repeat($hue,6/$len));
+ unset($hue);
+ }
+ return $color;
+ }
+
+ /**
+ * Invert image
+ * @return object
+ **/
+ function invert() {
+ imagefilter($this->data,IMG_FILTER_NEGATE);
+ return $this->save();
+ }
+
+ /**
+ * Adjust brightness (range:-255 to 255)
+ * @return object
+ * @param $level int
+ **/
+ function brightness($level) {
+ imagefilter($this->data,IMG_FILTER_BRIGHTNESS,$level);
+ return $this->save();
+ }
+
+ /**
+ * Adjust contrast (range:-100 to 100)
+ * @return object
+ * @param $level int
+ **/
+ function contrast($level) {
+ imagefilter($this->data,IMG_FILTER_CONTRAST,$level);
+ return $this->save();
+ }
+
+ /**
+ * Convert to grayscale
+ * @return object
+ **/
+ function grayscale() {
+ imagefilter($this->data,IMG_FILTER_GRAYSCALE);
+ return $this->save();
+ }
+
+ /**
+ * Adjust smoothness
+ * @return object
+ * @param $level int
+ **/
+ function smooth($level) {
+ imagefilter($this->data,IMG_FILTER_SMOOTH,$level);
+ return $this->save();
+ }
+
+ /**
+ * Emboss the image
+ * @return object
+ **/
+ function emboss() {
+ imagefilter($this->data,IMG_FILTER_EMBOSS);
+ return $this->save();
+ }
+
+ /**
+ * Apply sepia effect
+ * @return object
+ **/
+ function sepia() {
+ imagefilter($this->data,IMG_FILTER_GRAYSCALE);
+ imagefilter($this->data,IMG_FILTER_COLORIZE,90,60,45);
+ return $this->save();
+ }
+
+ /**
+ * Pixelate the image
+ * @return object
+ * @param $size int
+ **/
+ function pixelate($size) {
+ imagefilter($this->data,IMG_FILTER_PIXELATE,$size,TRUE);
+ return $this->save();
+ }
+
+ /**
+ * Blur the image using Gaussian filter
+ * @return object
+ * @param $selective bool
+ **/
+ function blur($selective=FALSE) {
+ imagefilter($this->data,
+ $selective?IMG_FILTER_SELECTIVE_BLUR:IMG_FILTER_GAUSSIAN_BLUR);
+ return $this->save();
+ }
+
+ /**
+ * Apply sketch effect
+ * @return object
+ **/
+ function sketch() {
+ imagefilter($this->data,IMG_FILTER_MEAN_REMOVAL);
+ return $this->save();
+ }
+
+ /**
+ * Flip on horizontal axis
+ * @return object
+ **/
+ function hflip() {
+ $tmp=imagecreatetruecolor(
+ $width=$this->width(),$height=$this->height());
+ imagesavealpha($tmp,TRUE);
+ imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
+ imagecopyresampled($tmp,$this->data,
+ 0,0,$width-1,0,$width,$height,-$width,$height);
+ imagedestroy($this->data);
+ $this->data=$tmp;
+ return $this->save();
+ }
+
+ /**
+ * Flip on vertical axis
+ * @return object
+ **/
+ function vflip() {
+ $tmp=imagecreatetruecolor(
+ $width=$this->width(),$height=$this->height());
+ imagesavealpha($tmp,TRUE);
+ imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
+ imagecopyresampled($tmp,$this->data,
+ 0,0,0,$height-1,$width,$height,$width,-$height);
+ imagedestroy($this->data);
+ $this->data=$tmp;
+ return $this->save();
+ }
+
+ /**
+ * Crop the image
+ * @return object
+ * @param $x1 int
+ * @param $y1 int
+ * @param $x2 int
+ * @param $y2 int
+ **/
+ function crop($x1,$y1,$x2,$y2) {
+ $tmp=imagecreatetruecolor($width=$x2-$x1+1,$height=$y2-$y1+1);
+ imagesavealpha($tmp,TRUE);
+ imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
+ imagecopyresampled($tmp,$this->data,
+ 0,0,$x1,$y1,$width,$height,$width,$height);
+ imagedestroy($this->data);
+ $this->data=$tmp;
+ return $this->save();
+ }
+
+ /**
+ * Resize image (Maintain aspect ratio); Crop relative to center
+ * if flag is enabled; Enlargement allowed if flag is enabled
+ * @return object
+ * @param $width int
+ * @param $height int
+ * @param $crop bool
+ * @param $enlarge bool
+ **/
+ function resize($width,$height,$crop=TRUE,$enlarge=TRUE) {
+ // Adjust dimensions; retain aspect ratio
+ $ratio=($origw=imagesx($this->data))/($origh=imagesy($this->data));
+ if (!$crop)
+ if ($width/$ratio<=$height)
+ $height=$width/$ratio;
+ else
+ $width=$height*$ratio;
+ if (!$enlarge) {
+ $width=min($origw,$width);
+ $height=min($origh,$height);
+ }
+ // Create blank image
+ $tmp=imagecreatetruecolor($width,$height);
+ imagesavealpha($tmp,TRUE);
+ imagefill($tmp,0,0,IMG_COLOR_TRANSPARENT);
+ // Resize
+ if ($crop) {
+ if ($width/$ratio<=$height) {
+ $cropw=$origh*$width/$height;
+ imagecopyresampled($tmp,$this->data,
+ 0,0,($origw-$cropw)/2,0,$width,$height,$cropw,$origh);
+ }
+ else {
+ $croph=$origw*$height/$width;
+ imagecopyresampled($tmp,$this->data,
+ 0,0,0,($origh-$croph)/2,$width,$height,$origw,$croph);
+ }
+ }
+ else
+ imagecopyresampled($tmp,$this->data,
+ 0,0,0,0,$width,$height,$origw,$origh);
+ imagedestroy($this->data);
+ $this->data=$tmp;
+ return $this->save();
+ }
+
+ /**
+ * Rotate image
+ * @return object
+ * @param $angle int
+ **/
+ function rotate($angle) {
+ $this->data=imagerotate($this->data,$angle,
+ imagecolorallocatealpha($this->data,0,0,0,127));
+ imagesavealpha($this->data,TRUE);
+ return $this->save();
+ }
+
+ /**
+ * Apply an image overlay
+ * @return object
+ * @param $img object
+ * @param $align int
+ **/
+ function overlay(Image $img,$align=NULL) {
+ if (is_null($align))
+ $align=self::POS_Right|self::POS_Bottom;
+ $ovr=imagecreatefromstring($img->dump());
+ imagesavealpha($ovr,TRUE);
+ $imgw=$this->width();
+ $imgh=$this->height();
+ $ovrw=imagesx($ovr);
+ $ovrh=imagesy($ovr);
+ if ($align & self::POS_Left)
+ $posx=0;
+ if ($align & self::POS_Center)
+ $posx=($imgw-$ovrw)/2;
+ if ($align & self::POS_Right)
+ $posx=$imgw-$ovrw;
+ if ($align & self::POS_Top)
+ $posy=0;
+ if ($align & self::POS_Middle)
+ $posy=($imgh-$ovrh)/2;
+ if ($align & self::POS_Bottom)
+ $posy=$imgh-$ovrh;
+ if (empty($posx))
+ $posx=0;
+ if (empty($posy))
+ $posy=0;
+ imagecopy($this->data,$ovr,$posx,$posy,0,0,$ovrw,$ovrh);
+ return $this->save();
+ }
+
+ /**
+ * Generate identicon
+ * @return object
+ * @param $str string
+ * @param $size int
+ * @param $blocks int
+ **/
+ function identicon($str,$size=64,$blocks=4) {
+ $sprites=array(
+ array(.5,1,1,0,1,1),
+ array(.5,0,1,0,.5,1,0,1),
+ array(.5,0,1,0,1,1,.5,1,1,.5),
+ array(0,.5,.5,0,1,.5,.5,1,.5,.5),
+ array(0,.5,1,0,1,1,0,1,1,.5),
+ array(1,0,1,1,.5,1,1,.5,.5,.5),
+ array(0,0,1,0,1,.5,0,0,.5,1,0,1),
+ array(0,0,.5,0,1,.5,.5,1,0,1,.5,.5),
+ array(.5,0,.5,.5,1,.5,1,1,.5,1,.5,.5,0,.5),
+ array(0,0,1,0,.5,.5,1,.5,.5,1,.5,.5,0,1),
+ array(0,.5,.5,1,1,.5,.5,0,1,0,1,1,0,1),
+ array(.5,0,1,0,1,1,.5,1,1,.75,.5,.5,1,.25),
+ array(0,.5,.5,0,.5,.5,1,0,1,.5,.5,1,.5,.5,0,1),
+ array(0,0,1,0,1,1,0,1,1,.5,.5,.25,.5,.75,0,.5,.5,.25),
+ array(0,.5,.5,.5,.5,0,1,0,.5,.5,1,.5,.5,1,.5,.5,0,1),
+ array(0,0,1,0,.5,.5,.5,0,0,.5,1,.5,.5,1,.5,.5,0,1)
+ );
+ $hash=sha1($str);
+ $this->data=imagecreatetruecolor($size,$size);
+ list($r,$g,$b)=$this->rgb(hexdec(substr($hash,-3)));
+ $fg=imagecolorallocate($this->data,$r,$g,$b);
+ imagefill($this->data,0,0,IMG_COLOR_TRANSPARENT);
+ $ctr=count($sprites);
+ $dim=$blocks*floor($size/$blocks)*2/$blocks;
+ for ($j=0,$y=ceil($blocks/2);$j<$y;$j++)
+ for ($i=$j,$x=$blocks-1-$j;$i<$x;$i++) {
+ $sprite=imagecreatetruecolor($dim,$dim);
+ imagefill($sprite,0,0,IMG_COLOR_TRANSPARENT);
+ if ($block=$sprites[
+ hexdec($hash[($j*$blocks+$i)*2])%$ctr]) {
+ for ($k=0,$pts=count($block);$k<$pts;$k++)
+ $block[$k]*=$dim;
+ imagefilledpolygon($sprite,$block,$pts/2,$fg);
+ }
+ $sprite=imagerotate($sprite,
+ 90*(hexdec($hash[($j*$blocks+$i)*2+1])%4),
+ imagecolorallocatealpha($sprite,0,0,0,127));
+ for ($k=0;$k<4;$k++) {
+ imagecopyresampled($this->data,$sprite,
+ $i*$dim/2,$j*$dim/2,0,0,$dim/2,$dim/2,$dim,$dim);
+ $this->data=imagerotate($this->data,90,
+ imagecolorallocatealpha($this->data,0,0,0,127));
+ }
+ imagedestroy($sprite);
+ }
+ imagesavealpha($this->data,TRUE);
+ return $this->save();
+ }
+
+ /**
+ * Generate CAPTCHA image
+ * @return object|FALSE
+ * @param $font string
+ * @param $size int
+ * @param $len int
+ * @param $key string
+ * @param $path string
+ * @param $fg int
+ * @param $bg int
+ **/
+ function captcha($font,$size=24,$len=5,
+ $key=NULL,$path='',$fg=0xFFFFFF,$bg=0x000000) {
+ if ((!$ssl=extension_loaded('openssl')) && ($len<4 || $len>13)) {
+ user_error(sprintf(self::E_Length,$len));
+ return FALSE;
+ }
+ $fw=Base::instance();
+ foreach ($fw->split($path?:$fw->get('UI').';./') as $dir)
+ if (is_file($path=$dir.$font)) {
+ $seed=strtoupper(substr(
+ $ssl?bin2hex(openssl_random_pseudo_bytes($len)):uniqid(),
+ -$len));
+ $block=$size*3;
+ $tmp=array();
+ for ($i=0,$width=0,$height=0;$i<$len;$i++) {
+ // Process at 2x magnification
+ $box=imagettfbbox($size*2,0,$path,$seed[$i]);
+ $w=$box[2]-$box[0];
+ $h=$box[1]-$box[5];
+ $char=imagecreatetruecolor($block,$block);
+ imagefill($char,0,0,$bg);
+ imagettftext($char,$size*2,0,
+ ($block-$w)/2,$block-($block-$h)/2,
+ $fg,$path,$seed[$i]);
+ $char=imagerotate($char,mt_rand(-30,30),
+ imagecolorallocatealpha($char,0,0,0,127));
+ // Reduce to normal size
+ $tmp[$i]=imagecreatetruecolor(
+ ($w=imagesx($char))/2,($h=imagesy($char))/2);
+ imagefill($tmp[$i],0,0,IMG_COLOR_TRANSPARENT);
+ imagecopyresampled($tmp[$i],$char,0,0,0,0,$w/2,$h/2,$w,$h);
+ imagedestroy($char);
+ $width+=$i+1<$len?$block/2:$w/2;
+ $height=max($height,$h/2);
+ }
+ $this->data=imagecreatetruecolor($width,$height);
+ imagefill($this->data,0,0,IMG_COLOR_TRANSPARENT);
+ for ($i=0;$i<$len;$i++) {
+ imagecopy($this->data,$tmp[$i],
+ $i*$block/2,($height-imagesy($tmp[$i]))/2,0,0,
+ imagesx($tmp[$i]),imagesy($tmp[$i]));
+ imagedestroy($tmp[$i]);
+ }
+ imagesavealpha($this->data,TRUE);
+ if ($key)
+ $fw->set($key,$seed);
+ return $this->save();
+ }
+ user_error(self::E_Font);
+ return FALSE;
+ }
+
+ /**
+ * Return image width
+ * @return int
+ **/
+ function width() {
+ return imagesx($this->data);
+ }
+
+ /**
+ * Return image height
+ * @return int
+ **/
+ function height() {
+ return imagesy($this->data);
+ }
+
+ /**
+ * Send image to HTTP client
+ * @return NULL
+ **/
+ function render() {
+ $args=func_get_args();
+ $format=$args?array_shift($args):'png';
+ if (PHP_SAPI!='cli') {
+ header('Content-Type: image/'.$format);
+ header('X-Powered-By: '.Base::instance()->get('PACKAGE'));
+ }
+ call_user_func_array('image'.$format,
+ array_merge(array($this->data),$args));
+ }
+
+ /**
+ * Return image as a string
+ * @return string
+ **/
+ function dump() {
+ $args=func_get_args();
+ $format=$args?array_shift($args):'png';
+ ob_start();
+ call_user_func_array('image'.$format,
+ array_merge(array($this->data),$args));
+ return ob_get_clean();
+ }
+
+ /**
+ * Save current state
+ * @return object
+ **/
+ function save() {
+ $fw=Base::instance();
+ if ($this->flag) {
+ if (!is_dir($dir=$fw->get('TEMP')))
+ mkdir($dir,Base::MODE,TRUE);
+ $this->count++;
+ $fw->write($dir.'/'.
+ $fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash($this->file).'-'.$this->count.'.png',
+ $this->dump());
+ }
+ return $this;
+ }
+
+ /**
+ * Revert to specified state
+ * @return object
+ * @param $state int
+ **/
+ function restore($state=1) {
+ $fw=Base::instance();
+ if ($this->flag && is_file($file=($path=$fw->get('TEMP').
+ $fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash($this->file).'-').$state.'.png')) {
+ if (is_resource($this->data))
+ imagedestroy($this->data);
+ $this->data=imagecreatefromstring($fw->read($file));
+ imagesavealpha($this->data,TRUE);
+ foreach (glob($path.'*.png',GLOB_NOSORT) as $match)
+ if (preg_match('/-(\d+)\.png/',$match,$parts) &&
+ $parts[1]>$state)
+ @unlink($match);
+ $this->count=$state;
+ }
+ return $this;
+ }
+
+ /**
+ * Undo most recently applied filter
+ * @return object
+ **/
+ function undo() {
+ if ($this->flag) {
+ if ($this->count)
+ $this->count--;
+ return $this->restore($this->count);
+ }
+ return $this;
+ }
+
+ /**
+ * Load string
+ * @return object
+ * @param $str string
+ **/
+ function load($str) {
+ $this->data=imagecreatefromstring($str);
+ imagesavealpha($this->data,TRUE);
+ $this->save();
+ return $this;
+ }
+
+ /**
+ * Instantiate image
+ * @param $file string
+ * @param $flag bool
+ * @param $path string
+ **/
+ function __construct($file=NULL,$flag=FALSE,$path='') {
+ $this->flag=$flag;
+ if ($file) {
+ $fw=Base::instance();
+ // Create image from file
+ $this->file=$file;
+ foreach ($fw->split($path?:$fw->get('UI').';./') as $dir)
+ if (is_file($dir.$file))
+ return $this->load($fw->read($dir.$file));
+ }
+ }
+
+ /**
+ * Wrap-up
+ * @return NULL
+ **/
+ function __destruct() {
+ if (is_resource($this->data)) {
+ imagedestroy($this->data);
+ $fw=Base::instance();
+ $path=$fw->get('TEMP').
+ $fw->hash($fw->get('ROOT').$fw->get('BASE')).'.'.
+ $fw->hash($this->file);
+ if ($glob=@glob($path.'*.png',GLOB_NOSORT))
+ foreach ($glob as $match)
+ if (preg_match('/-(\d+)\.png/',$match))
+ @unlink($match);
+ }
+ }
+
+}
diff --git a/management-interface/lib/license.txt b/management-interface/lib/license.txt
new file mode 100644
index 0000000..3c7236c
--- /dev/null
+++ b/management-interface/lib/license.txt
@@ -0,0 +1,621 @@
+GNU GENERAL PUBLIC LICENSE
+Version 3, 29 June 2007
+
+Copyright (C) 2007 Free Software Foundation, Inc.
+Everyone is permitted to copy and distribute verbatim copies
+of this license document, but changing it is not allowed.
+
+Preamble
+
+The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+The precise terms and conditions for copying, distribution and
+modification follow.
+
+TERMS AND CONDITIONS
+
+0. Definitions.
+
+"This License" refers to version 3 of the GNU General Public License.
+
+"Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+"The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+1. Source Code.
+
+The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+The Corresponding Source for a work in source code form is that
+same work.
+
+2. Basic Permissions.
+
+All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+4. Conveying Verbatim Copies.
+
+You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+5. Conveying Modified Source Versions.
+
+You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+a) The work must carry prominent notices stating that you modified
+it, and giving a relevant date.
+
+b) The work must carry prominent notices stating that it is
+released under this License and any conditions added under section
+7. This requirement modifies the requirement in section 4 to
+"keep intact all notices".
+
+c) You must license the entire work, as a whole, under this
+License to anyone who comes into possession of a copy. This
+License will therefore apply, along with any applicable section 7
+additional terms, to the whole of the work, and all its parts,
+regardless of how they are packaged. This License gives no
+permission to license the work in any other way, but it does not
+invalidate such permission if you have separately received it.
+
+d) If the work has interactive user interfaces, each must display
+Appropriate Legal Notices; however, if the Program has interactive
+interfaces that do not display Appropriate Legal Notices, your
+work need not make them do so.
+
+A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+6. Conveying Non-Source Forms.
+
+You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+a) Convey the object code in, or embodied in, a physical product
+(including a physical distribution medium), accompanied by the
+Corresponding Source fixed on a durable physical medium
+customarily used for software interchange.
+
+b) Convey the object code in, or embodied in, a physical product
+(including a physical distribution medium), accompanied by a
+written offer, valid for at least three years and valid for as
+long as you offer spare parts or customer support for that product
+model, to give anyone who possesses the object code either (1) a
+copy of the Corresponding Source for all the software in the
+product that is covered by this License, on a durable physical
+medium customarily used for software interchange, for a price no
+more than your reasonable cost of physically performing this
+conveying of source, or (2) access to copy the
+Corresponding Source from a network server at no charge.
+
+c) Convey individual copies of the object code with a copy of the
+written offer to provide the Corresponding Source. This
+alternative is allowed only occasionally and noncommercially, and
+only if you received the object code with such an offer, in accord
+with subsection 6b.
+
+d) Convey the object code by offering access from a designated
+place (gratis or for a charge), and offer equivalent access to the
+Corresponding Source in the same way through the same place at no
+further charge. You need not require recipients to copy the
+Corresponding Source along with the object code. If the place to
+copy the object code is a network server, the Corresponding Source
+may be on a different server (operated by you or a third party)
+that supports equivalent copying facilities, provided you maintain
+clear directions next to the object code saying where to find the
+Corresponding Source. Regardless of what server hosts the
+Corresponding Source, you remain obligated to ensure that it is
+available for as long as needed to satisfy these requirements.
+
+e) Convey the object code using peer-to-peer transmission, provided
+you inform other peers where the object code and Corresponding
+Source of the work are being offered to the general public at no
+charge under subsection 6d.
+
+A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+"Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+7. Additional Terms.
+
+"Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+a) Disclaiming warranty or limiting liability differently from the
+terms of sections 15 and 16 of this License; or
+
+b) Requiring preservation of specified reasonable legal notices or
+author attributions in that material or in the Appropriate Legal
+Notices displayed by works containing it; or
+
+c) Prohibiting misrepresentation of the origin of that material, or
+requiring that modified versions of such material be marked in
+reasonable ways as different from the original version; or
+
+d) Limiting the use for publicity purposes of names of licensors or
+authors of the material; or
+
+e) Declining to grant rights under trademark law for use of some
+trade names, trademarks, or service marks; or
+
+f) Requiring indemnification of licensors and authors of that
+material by anyone who conveys the material (or modified versions of
+it) with contractual assumptions of liability to the recipient, for
+any liability that these contractual assumptions directly impose on
+those licensors and authors.
+
+All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+8. Termination.
+
+You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+9. Acceptance Not Required for Having Copies.
+
+You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+10. Automatic Licensing of Downstream Recipients.
+
+Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+11. Patents.
+
+A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+12. No Surrender of Others' Freedom.
+
+If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+13. Use with the GNU Affero General Public License.
+
+Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+14. Revised Versions of this License.
+
+The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+15. Disclaimer of Warranty.
+
+THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+16. Limitation of Liability.
+
+IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+17. Interpretation of Sections 15 and 16.
+
+If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+END OF TERMS AND CONDITIONS
diff --git a/management-interface/lib/log.php b/management-interface/lib/log.php
new file mode 100644
index 0000000..7ec78c0
--- /dev/null
+++ b/management-interface/lib/log.php
@@ -0,0 +1,60 @@
+write(
+ $this->file,
+ date($format).
+ (isset($_SERVER['REMOTE_ADDR'])?
+ (' ['.$_SERVER['REMOTE_ADDR'].']'):'').' '.
+ trim($text).PHP_EOL,
+ TRUE
+ );
+ }
+
+ /**
+ * Erase log
+ * @return NULL
+ **/
+ function erase() {
+ @unlink($this->file);
+ }
+
+ /**
+ * Instantiate class
+ * @param $file string
+ **/
+ function __construct($file) {
+ $fw=Base::instance();
+ if (!is_dir($dir=$fw->get('LOGS')))
+ mkdir($dir,Base::MODE,TRUE);
+ $this->file=$dir.$file;
+ }
+
+}
diff --git a/management-interface/lib/magic.php b/management-interface/lib/magic.php
new file mode 100644
index 0000000..d17d180
--- /dev/null
+++ b/management-interface/lib/magic.php
@@ -0,0 +1,140 @@
+isprivate();
+ unset($ref);
+ return $out;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Convenience method for checking property value
+ * @return mixed
+ * @param $key string
+ **/
+ function offsetexists($key) {
+ return $this->visible($key)?isset($this->$key):$this->exists($key);
+ }
+
+ /**
+ * Alias for offsetexists()
+ * @return mixed
+ * @param $key string
+ **/
+ function __isset($key) {
+ return $this->offsetexists($key);
+ }
+
+ /**
+ * Convenience method for assigning property value
+ * @return mixed
+ * @param $key string
+ * @param $val scalar
+ **/
+ function offsetset($key,$val) {
+ return $this->visible($key)?($this->key=$val):$this->set($key,$val);
+ }
+
+ /**
+ * Alias for offsetset()
+ * @return mixed
+ * @param $key string
+ * @param $val scalar
+ **/
+ function __set($key,$val) {
+ return $this->offsetset($key,$val);
+ }
+
+ /**
+ * Convenience method for retrieving property value
+ * @return mixed
+ * @param $key string
+ **/
+ function offsetget($key) {
+ return $this->visible($key)?$this->$key:$this->get($key);
+ }
+
+ /**
+ * Alias for offsetget()
+ * @return mixed
+ * @param $key string
+ **/
+ function __get($key) {
+ return $this->offsetget($key);
+ }
+
+ /**
+ * Convenience method for checking property value
+ * @return NULL
+ * @param $key string
+ **/
+ function offsetunset($key) {
+ if ($this->visible($key))
+ unset($this->$key);
+ else
+ $this->clear($key);
+ }
+
+ /**
+ * Alias for offsetunset()
+ * @return NULL
+ * @param $key string
+ **/
+ function __unset($key) {
+ $this->offsetunset($key);
+ }
+
+}
diff --git a/management-interface/lib/markdown.php b/management-interface/lib/markdown.php
new file mode 100644
index 0000000..bc6cfd4
--- /dev/null
+++ b/management-interface/lib/markdown.php
@@ -0,0 +1,570 @@
+\h?(.*?(?:\n+|$))/','\1',$str);
+ return strlen($str)?
+ ('