function broken_tags($str)
{
preg_match_all("/(<\w+)(?:.){0,}?>/", $str, $v1);
preg_match_all("/<\/\w+>/", $str, $v2);
$open = array_map('strtolower', $v1[1]);
$closed = array_map('strtolower', $v2[0]);
foreach ($open as $tag)
{
$end_tag = preg_replace("/<(.*)/", "</$1>", $tag);
if (!in_array($end_tag, $closed)) return true;
unset($closed[array_search($end_tag, $closed)]);
}
return false;
}
Sabtu, 31 Maret 2012
Element Event Remover (PHP)
function remove_event($sSource, $aDisabledAttributes=false){
if(!is_array($aDisabledAttributes)){
$aDisabledAttributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
}
$sSource = stripcslashes($sSource);
if(empty($aDisabledAttributes)){
return $sSource;
}
$aDisabledAttributes = @implode('|', $aDisabledAttributes);
$sSource = preg_replace('/<(.*?)>/ie', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(".$aDisabledAttributes.")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", $sSource );
//$sSource = preg_replace('/\s(' . $aDisabledAttributes . ').*?([\s\>])/', '\\2', $sSource);
//$sSource = preg_replace('@[a-z]*=""@is', '', $sSource);
return $sSource;
}
if(!is_array($aDisabledAttributes)){
$aDisabledAttributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
}
$sSource = stripcslashes($sSource);
if(empty($aDisabledAttributes)){
return $sSource;
}
$aDisabledAttributes = @implode('|', $aDisabledAttributes);
$sSource = preg_replace('/<(.*?)>/ie', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(".$aDisabledAttributes.")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", $sSource );
//$sSource = preg_replace('/\s(' . $aDisabledAttributes . ').*?([\s\>])/', '\\2', $sSource);
//$sSource = preg_replace('@[a-z]*=""@is', '', $sSource);
return $sSource;
}
UTF8 to Entity Converter (PHP)
function UTF8ToEntities($string){
if (!ereg("[\200-\237]",$string) && !ereg("[\241-\377]",$string))
return $string;
$string = preg_replace("/[\302-\375]([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\340-\375].([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\360-\375]..([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\370-\375]...([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\374-\375]....([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\300-\301]./", "�", $string);
$string = preg_replace("/\364[\220-\277]../","�",$string);
$string = preg_replace("/[\365-\367].../","�",$string);
$string = preg_replace("/[\370-\373]..../","�",$string);
$string = preg_replace("/[\374-\375]...../","�",$string);
$string = preg_replace("/[\376-\377]/","�",$string);
$string = preg_replace("/[\302-\364]{2,}/","�",$string);
$string = preg_replace(
"/([\360-\364])([\200-\277])([\200-\277])([\200-\277])/e",
"'&#'.((ord('\\1')&7)<<18 | (ord('\\2')&63)<<12 |".
" (ord('\\3')&63)<<6 | (ord('\\4')&63)).';'",
$string);
$string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
"'&#'.((ord('\\1')&15)<<12 | (ord('\\2')&63)<<6 | (ord('\\3')&63)).';'",
$string);
$string = preg_replace("/([\300-\337])([\200-\277])/e",
"'&#'.((ord('\\1')&31)<<6 | (ord('\\2')&63)).';'",
$string);
$string = preg_replace("/[\200-\277]/","�",$string);
return $string;
}
if (!ereg("[\200-\237]",$string) && !ereg("[\241-\377]",$string))
return $string;
$string = preg_replace("/[\302-\375]([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\340-\375].([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\360-\375]..([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\370-\375]...([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\374-\375]....([\001-\177])/","�\\1",$string);
$string = preg_replace("/[\300-\301]./", "�", $string);
$string = preg_replace("/\364[\220-\277]../","�",$string);
$string = preg_replace("/[\365-\367].../","�",$string);
$string = preg_replace("/[\370-\373]..../","�",$string);
$string = preg_replace("/[\374-\375]...../","�",$string);
$string = preg_replace("/[\376-\377]/","�",$string);
$string = preg_replace("/[\302-\364]{2,}/","�",$string);
$string = preg_replace(
"/([\360-\364])([\200-\277])([\200-\277])([\200-\277])/e",
"'&#'.((ord('\\1')&7)<<18 | (ord('\\2')&63)<<12 |".
" (ord('\\3')&63)<<6 | (ord('\\4')&63)).';'",
$string);
$string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
"'&#'.((ord('\\1')&15)<<12 | (ord('\\2')&63)<<6 | (ord('\\3')&63)).';'",
$string);
$string = preg_replace("/([\300-\337])([\200-\277])/e",
"'&#'.((ord('\\1')&31)<<6 | (ord('\\2')&63)).';'",
$string);
$string = preg_replace("/[\200-\277]/","�",$string);
return $string;
}
Read and Write Cookie (JavaScript)
// Example:
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.
function writeCookie(name, value, hours)
{
var expire = "";
if(hours != null)
{
expire = new Date((new Date()).getTime() + hours * 3600000);
expire = "; expires=" + expire.toGMTString();
}
document.cookie = name + "=" + escape(value) + expire;
}
// Example:
// alert( readCookie("myCookie") );
function readCookie(name)
{
var cookieValue = "";
var search = name + "=";
if(document.cookie.length > 0)
{
offset = document.cookie.indexOf(search);
if (offset != -1)
{
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
cookieValue = unescape(document.cookie.substring(offset, end))
}
}
return cookieValue;
}
// writeCookie("myCookie", "my name", 24);
// Stores the string "my name" in the cookie "myCookie" which expires after 24 hours.
function writeCookie(name, value, hours)
{
var expire = "";
if(hours != null)
{
expire = new Date((new Date()).getTime() + hours * 3600000);
expire = "; expires=" + expire.toGMTString();
}
document.cookie = name + "=" + escape(value) + expire;
}
// Example:
// alert( readCookie("myCookie") );
function readCookie(name)
{
var cookieValue = "";
var search = name + "=";
if(document.cookie.length > 0)
{
offset = document.cookie.indexOf(search);
if (offset != -1)
{
offset += search.length;
end = document.cookie.indexOf(";", offset);
if (end == -1) end = document.cookie.length;
cookieValue = unescape(document.cookie.substring(offset, end))
}
}
return cookieValue;
}
UTF8 to Entity Converter (JavaScript)
function utf8ToEntity(utf8) {
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,'');}
var utf8_char = utf8;
utf8_char=utf8_char.trim();
var html_entity='';
for(i=0; i<=utf8_char.length; i++){
if(utf8_char.charCodeAt(i)>127){html_entity+='&#'+utf8_char.charCodeAt(i) + ';';}
else{html_entity += utf8_char.charAt(i);}
}
return html_entity;
}
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,'');}
var utf8_char = utf8;
utf8_char=utf8_char.trim();
var html_entity='';
for(i=0; i<=utf8_char.length; i++){
if(utf8_char.charCodeAt(i)>127){html_entity+='&#'+utf8_char.charCodeAt(i) + ';';}
else{html_entity += utf8_char.charAt(i);}
}
return html_entity;
}
HTML Entity Encoder-Decoder (JavaScript)
function htmlEntityEncode(data){
var output=data;
output=replaceStr('"','"',output,true);
output=replaceStr('&','&',output,true);
output=replaceStr('<','<',output,true);
output=replaceStr('>','>',output,true);
return output;
}
function htmlEntityDecode(data){
var output=data;
output=replaceStr('>','>',output,true);
output=replaceStr('<','<',output,true);
output=replaceStr('&','&',output,true);
output=replaceStr('"','"',output,true);
return output;
}
var output=data;
output=replaceStr('"','"',output,true);
output=replaceStr('&','&',output,true);
output=replaceStr('<','<',output,true);
output=replaceStr('>','>',output,true);
return output;
}
function htmlEntityDecode(data){
var output=data;
output=replaceStr('>','>',output,true);
output=replaceStr('<','<',output,true);
output=replaceStr('&','&',output,true);
output=replaceStr('"','"',output,true);
return output;
}
in_array Function (JavaScript)
function in_array(needle,haystack){
var i;
for(i in haystack){
if(needle==haystack[i]){return true;}
}
return false;
}
var i;
for(i in haystack){
if(needle==haystack[i]){return true;}
}
return false;
}
Base64 Encoder-Decoder (JavaScript)
var keyStr64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
function base64Encode(input){
var output="";
var chr1,chr2,chr3="";
var enc1,enc2,enc3,enc4="";
var i=0;
do{
chr1=input.charCodeAt(i++);
chr2=input.charCodeAt(i++);
chr3=input.charCodeAt(i++);
enc1=chr1>>2;
enc2=((chr1& 3)<<4)|(chr2>>4);
enc3=((chr2&15)<<2)|(chr3>>6);
enc4=chr3&63;
if(isNaN(chr2)){enc3=enc4=64;}
else if(isNaN(chr3)){enc4=64;}
output=output+keyStr64.charAt(enc1)+keyStr64.charAt(enc2)+keyStr64.charAt(enc3)+keyStr64.charAt(enc4);
chr1=chr2=chr3="";
enc1=enc2=enc3=enc4="";
} while(i<input.length);
return output;
}
function base64Decode(input){
var output="";
var chr1,chr2,chr3="";
var enc1,enc2,enc3,enc4="";
var i=0;
var base64test=/[^A-Za-z0-9+/=]/g;
if(base64test.exec(input)){
}
input=input.replace(/[^A-Za-z0-9+/=]/g,"");
do{
enc1=keyStr64.indexOf(input.charAt(i++));
enc2=keyStr64.indexOf(input.charAt(i++));
enc3=keyStr64.indexOf(input.charAt(i++));
enc4=keyStr64.indexOf(input.charAt(i++));
chr1=(enc1<< 2)|(enc2>>4);
chr2=((enc2&15)<<4)|(enc3>>2);
chr3=((enc3& 3)<<6)|enc4;
output=output+String.fromCharCode(chr1);
if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}
chr1=chr2=chr3="";
enc1=enc2=enc3=enc4="";
} while (i<input.length);
return output;
}
function base64Encode(input){
var output="";
var chr1,chr2,chr3="";
var enc1,enc2,enc3,enc4="";
var i=0;
do{
chr1=input.charCodeAt(i++);
chr2=input.charCodeAt(i++);
chr3=input.charCodeAt(i++);
enc1=chr1>>2;
enc2=((chr1& 3)<<4)|(chr2>>4);
enc3=((chr2&15)<<2)|(chr3>>6);
enc4=chr3&63;
if(isNaN(chr2)){enc3=enc4=64;}
else if(isNaN(chr3)){enc4=64;}
output=output+keyStr64.charAt(enc1)+keyStr64.charAt(enc2)+keyStr64.charAt(enc3)+keyStr64.charAt(enc4);
chr1=chr2=chr3="";
enc1=enc2=enc3=enc4="";
} while(i<input.length);
return output;
}
function base64Decode(input){
var output="";
var chr1,chr2,chr3="";
var enc1,enc2,enc3,enc4="";
var i=0;
var base64test=/[^A-Za-z0-9+/=]/g;
if(base64test.exec(input)){
}
input=input.replace(/[^A-Za-z0-9+/=]/g,"");
do{
enc1=keyStr64.indexOf(input.charAt(i++));
enc2=keyStr64.indexOf(input.charAt(i++));
enc3=keyStr64.indexOf(input.charAt(i++));
enc4=keyStr64.indexOf(input.charAt(i++));
chr1=(enc1<< 2)|(enc2>>4);
chr2=((enc2&15)<<4)|(enc3>>2);
chr3=((enc3& 3)<<6)|enc4;
output=output+String.fromCharCode(chr1);
if(enc3!=64){output=output+String.fromCharCode(chr2);}
if(enc4!=64){output=output+String.fromCharCode(chr3);}
chr1=chr2=chr3="";
enc1=enc2=enc3=enc4="";
} while (i<input.length);
return output;
}
Get GPS Information form EXIF Data (JavaScript)
function getRealPosition(gpsData)
{
if(gpsData.length<20)
return false;
var xdata = eval(base64Decode(gpsData));
// Latitude
var tmpArr = new Array();
var GPSLatitudeRef = xdata[0]['GPSLatitudeRef'];
var GPSLatitude = xdata[0]['GPSLatitude'];
var GPSLatitudeDegreeStr = xdata[0]['GPSLatitude'][0];
tmpArr = GPSLatitudeDegreeStr.split('/');
var GPSLatitudeDegree = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var GPSLatitudeMinuteStr = xdata[0]['GPSLatitude'][1];
tmpArr = GPSLatitudeMinuteStr.split('/');
var GPSLatitudeMinute = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var GPSLatitudeSecondStr = xdata[0]['GPSLatitude'][2];
tmpArr = GPSLatitudeSecondStr.split('/');
var GPSLatitudeSecond = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
// Longitude
var tmpArr = new Array();
var GPSLongitudeRef = xdata[0]['GPSLongitudeRef'];
var GPSLongitude = xdata[0]['GPSLongitude'];
var GPSLongitudeDegreeStr = xdata[0]['GPSLongitude'][0];
tmpArr = GPSLongitudeDegreeStr.split('/');
var GPSLongitudeDegree = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var GPSLongitudeMinuteStr = xdata[0]['GPSLongitude'][1];
tmpArr = GPSLongitudeMinuteStr.split('/');
var GPSLongitudeMinute = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var GPSLongitudeSecondStr = xdata[0]['GPSLongitude'][2];
tmpArr = GPSLongitudeSecondStr.split('/');
var GPSLongitudeSecond = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
// Altitude
var GPSAltitudeRef = xdata[0]['GPSAltitudeRef'];
var GPSAltitudeStr = xdata[0]['GPSAltitudeRef'];
tmpArr = GPSLongitudeSecondStr.split('/');
var GPSAltitude = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var latitude = dmstoreal(GPSLatitudeDegree, GPSLatitudeMinute, GPSLatitudeSecond);
if(GPSLatitudeRef.indexOf('S')>-1) latitude=latitude*-1;
var longitude = dmstoreal(GPSLongitudeDegree, GPSLongitudeMinute, GPSLongitudeSecond);
if(GPSLongitudeRef.indexOf('W')>-1) longitude=longitude*-1;
var altitude = GPSAltitude;
var gpsPosition = new Array()
gpsPosition['latitude'] = latitude;
gpsPosition['longitude'] = longitude;
gpsPosition['altitude'] = altitude;
return gpsPosition;
}
function dmstoreal(degree, minute, second)
{
return parseFloat(degree+(((minute*60)+(second))/3600));
}
{
if(gpsData.length<20)
return false;
var xdata = eval(base64Decode(gpsData));
// Latitude
var tmpArr = new Array();
var GPSLatitudeRef = xdata[0]['GPSLatitudeRef'];
var GPSLatitude = xdata[0]['GPSLatitude'];
var GPSLatitudeDegreeStr = xdata[0]['GPSLatitude'][0];
tmpArr = GPSLatitudeDegreeStr.split('/');
var GPSLatitudeDegree = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var GPSLatitudeMinuteStr = xdata[0]['GPSLatitude'][1];
tmpArr = GPSLatitudeMinuteStr.split('/');
var GPSLatitudeMinute = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var GPSLatitudeSecondStr = xdata[0]['GPSLatitude'][2];
tmpArr = GPSLatitudeSecondStr.split('/');
var GPSLatitudeSecond = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
// Longitude
var tmpArr = new Array();
var GPSLongitudeRef = xdata[0]['GPSLongitudeRef'];
var GPSLongitude = xdata[0]['GPSLongitude'];
var GPSLongitudeDegreeStr = xdata[0]['GPSLongitude'][0];
tmpArr = GPSLongitudeDegreeStr.split('/');
var GPSLongitudeDegree = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var GPSLongitudeMinuteStr = xdata[0]['GPSLongitude'][1];
tmpArr = GPSLongitudeMinuteStr.split('/');
var GPSLongitudeMinute = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var GPSLongitudeSecondStr = xdata[0]['GPSLongitude'][2];
tmpArr = GPSLongitudeSecondStr.split('/');
var GPSLongitudeSecond = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
// Altitude
var GPSAltitudeRef = xdata[0]['GPSAltitudeRef'];
var GPSAltitudeStr = xdata[0]['GPSAltitudeRef'];
tmpArr = GPSLongitudeSecondStr.split('/');
var GPSAltitude = parseFloat(tmpArr[0])/parseFloat(tmpArr[1]);
var latitude = dmstoreal(GPSLatitudeDegree, GPSLatitudeMinute, GPSLatitudeSecond);
if(GPSLatitudeRef.indexOf('S')>-1) latitude=latitude*-1;
var longitude = dmstoreal(GPSLongitudeDegree, GPSLongitudeMinute, GPSLongitudeSecond);
if(GPSLongitudeRef.indexOf('W')>-1) longitude=longitude*-1;
var altitude = GPSAltitude;
var gpsPosition = new Array()
gpsPosition['latitude'] = latitude;
gpsPosition['longitude'] = longitude;
gpsPosition['altitude'] = altitude;
return gpsPosition;
}
function dmstoreal(degree, minute, second)
{
return parseFloat(degree+(((minute*60)+(second))/3600));
}
LZW Compression (JavaScript)
// LZW-compress a string
function lzw_encode(s)
{
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++)
{
currChar=data[i];
if (dict[phrase + currChar] != null)
{
phrase += currChar;
}
else
{
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++)
{
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s)
{
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++)
{
var currCode = data[i].charCodeAt(0);
if (currCode < 256)
{
phrase = data[i];
}
else
{
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
function lzw_encode(s)
{
var dict = {};
var data = (s + "").split("");
var out = [];
var currChar;
var phrase = data[0];
var code = 256;
for (var i=1; i<data.length; i++)
{
currChar=data[i];
if (dict[phrase + currChar] != null)
{
phrase += currChar;
}
else
{
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
dict[phrase + currChar] = code;
code++;
phrase=currChar;
}
}
out.push(phrase.length > 1 ? dict[phrase] : phrase.charCodeAt(0));
for (var i=0; i<out.length; i++)
{
out[i] = String.fromCharCode(out[i]);
}
return out.join("");
}
// Decompress an LZW-encoded string
function lzw_decode(s)
{
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++)
{
var currCode = data[i].charCodeAt(0);
if (currCode < 256)
{
phrase = data[i];
}
else
{
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
LZW Compression (PHP)
<?php
/**
* @link http://code.google.com/p/php-lzw/
* @author Jakub Vrana, http://php.vrana.cz/
* @copyright 2009 Jakub Vrana
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
/** LZW compression
* @param string data to compress
* @return string binary data
*/
function lzw_compress($string) {
// compression
$dictionary = array_flip(range("\0", "\xFF"));
$word = "";
$codes = array();
for ($i=0; $i <= strlen($string); $i++) {
$x = $string[$i];
if (strlen($x) && isset($dictionary[$word . $x])) {
$word .= $x;
} elseif ($i) {
$codes[] = $dictionary[$word];
$dictionary[$word . $x] = count($dictionary);
$word = $x;
}
}
// convert codes to binary string
$dictionary_count = 256;
$bits = 8; // ceil(log($dictionary_count, 2))
$return = "";
$rest = 0;
$rest_length = 0;
foreach ($codes as $code) {
$rest = ($rest << $bits) + $code;
$rest_length += $bits;
$dictionary_count++;
if ($dictionary_count > (1 << $bits)) {
$bits++;
}
while ($rest_length > 7) {
$rest_length -= 8;
$return .= chr($rest >> $rest_length);
$rest &= (1 << $rest_length) - 1;
}
}
return $return . ($rest_length ? chr($rest << (8 - $rest_length)) : "");
}
/** LZW decompression
* @param string compressed binary data
* @return string original data
*/
function lzw_decompress($binary) {
// convert binary string to codes
$dictionary_count = 256;
$bits = 8; // ceil(log($dictionary_count, 2))
$codes = array();
$rest = 0;
$rest_length = 0;
for ($i=0; $i < strlen($binary); $i++) {
$rest = ($rest << 8) + ord($binary[$i]);
$rest_length += 8;
if ($rest_length >= $bits) {
$rest_length -= $bits;
$codes[] = $rest >> $rest_length;
$rest &= (1 << $rest_length) - 1;
$dictionary_count++;
if ($dictionary_count > (1 << $bits)) {
$bits++;
}
}
}
// decompression
$dictionary = range("\0", "\xFF");
$return = "";
foreach ($codes as $i => $code) {
$element = $dictionary[$code];
if (!isset($element)) {
$element = $word . $word[0];
}
$return .= $element;
if ($i) {
$dictionary[] = $word . $element[0];
}
$word = $element;
}
return $return;
}
?>
/**
* @link http://code.google.com/p/php-lzw/
* @author Jakub Vrana, http://php.vrana.cz/
* @copyright 2009 Jakub Vrana
* @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
*/
/** LZW compression
* @param string data to compress
* @return string binary data
*/
function lzw_compress($string) {
// compression
$dictionary = array_flip(range("\0", "\xFF"));
$word = "";
$codes = array();
for ($i=0; $i <= strlen($string); $i++) {
$x = $string[$i];
if (strlen($x) && isset($dictionary[$word . $x])) {
$word .= $x;
} elseif ($i) {
$codes[] = $dictionary[$word];
$dictionary[$word . $x] = count($dictionary);
$word = $x;
}
}
// convert codes to binary string
$dictionary_count = 256;
$bits = 8; // ceil(log($dictionary_count, 2))
$return = "";
$rest = 0;
$rest_length = 0;
foreach ($codes as $code) {
$rest = ($rest << $bits) + $code;
$rest_length += $bits;
$dictionary_count++;
if ($dictionary_count > (1 << $bits)) {
$bits++;
}
while ($rest_length > 7) {
$rest_length -= 8;
$return .= chr($rest >> $rest_length);
$rest &= (1 << $rest_length) - 1;
}
}
return $return . ($rest_length ? chr($rest << (8 - $rest_length)) : "");
}
/** LZW decompression
* @param string compressed binary data
* @return string original data
*/
function lzw_decompress($binary) {
// convert binary string to codes
$dictionary_count = 256;
$bits = 8; // ceil(log($dictionary_count, 2))
$codes = array();
$rest = 0;
$rest_length = 0;
for ($i=0; $i < strlen($binary); $i++) {
$rest = ($rest << 8) + ord($binary[$i]);
$rest_length += 8;
if ($rest_length >= $bits) {
$rest_length -= $bits;
$codes[] = $rest >> $rest_length;
$rest &= (1 << $rest_length) - 1;
$dictionary_count++;
if ($dictionary_count > (1 << $bits)) {
$bits++;
}
}
}
// decompression
$dictionary = range("\0", "\xFF");
$return = "";
foreach ($codes as $i => $code) {
$element = $dictionary[$code];
if (!isset($element)) {
$element = $word . $word[0];
}
$return .= $element;
if ($i) {
$dictionary[] = $word . $element[0];
}
$word = $element;
}
return $return;
}
?>
Sharing Session Data Using Database (PHP)
File lib-session.php
This function has been used on Planet Biru (http://www.planetbiru.com)
<?php
class KamsSession
{
private $ks_db_connection;
private $ks_session;
var $ks_cfg_usedatabase = false;
var $ks_db_host;
var $ks_db_user;
var $ks_db_password;
var $ks_db_name;
var $ks_db_table = "sessions";
var $ks_cookie_name = "kscookie";
var $ks_cookie_lifetime = 86400;
var $ks_cookie_path = "/";
var $ks_cookie_domain = "";
var $ks_cookie_secure = false;
var $ks_cookie_httponly = false;
var $ks_session_id;
var $ks_session_name = "kssession";
var $ks_session_gc_probability = 50;
var $ks_session_save_handler = "user";
var $ks_session_method = 2;
function __construct()
{
}
function session_set_cookie_params($lifetime=0, $path="/",
$domain="", $secure=false, $httponly=false)
{
$this->ks_cookie_lifetime = $lifetime;
$this->ks_cookie_path = $path;
$this->ks_cookie_domain = $domain;
$this->ks_cookie_secure = $secure;
$this->ks_cookie_httponly = $httponly;
}
function session_set_database_params($host, $database,
$user, $password, $table="sessions")
{
$this->ks_db_host = $host;
$this->ks_db_user = $user;
$this->ks_db_password = $user;
$this->ks_db_name = $password;
$this->ks_db_table = $table;
}
function start()
{
if($this->ks_cfg_usedatabase)
{
$this->ks_session_id = $this->getmycookie($this->ks_cookie_name);
ini_set('session.gc_probability', $this->ks_session_gc_probability);
ini_set('session.save_handler', $this->ks_session_save_handler);
ini_set('session.gc_maxlifetime', $this->ks_cookie_lifetime);
ini_set('session.save_path', $this->ks_cookie_path);
ini_set('session.cookie_domain', $this->ks_cookie_domain);
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc'));
session_id(strrev(md5($this->ks_session_id)));
session_name($this->ks_session_name);
session_start();
$this->setmycookie($this->ks_cookie_name, $this->ks_session_id,
time()+$this->ks_cookie_lifetime, $this->ks_cookie_path,
$this->ks_cookie_domain, $this->ks_cookie_secure,
$this->ks_cookie_httponly);
setcookie($this->ks_session_name, md5(time().mt_rand(1,999999)),
time()+$this->ks_cookie_lifetime, $this->ks_cookie_path,
$this->ks_cookie_domain, $this->ks_cookie_secure,
$this->ks_cookie_httponly);
if($this->ks_session_method == 2)
{
if(is_array($this->ks_session) && count($this->ks_session))
{
foreach($this->ks_session as $key=>$gval)
{
$_SESSION[$key] = $this->ks_session[$key];
}
}
}
}
else
{
session_start();
}
}
function setmycookie($name, $value="", $lifetime=0, $path="/",
$domain="", $secure=false, $httponly=false)
{
$value = str_rot13(strrev($value));
setcookie($name."0", substr($value,24,8),
$lifetime, $path, $domain, $secure, $httponly);
setcookie($name."1", substr($value,0 ,8),
$lifetime, $path, $domain, $secure, $httponly);
setcookie($name."2", substr($value,16,8),
$lifetime, $path, $domain, $secure, $httponly);
setcookie($name."3", substr($value,8 ,8),
$lifetime, $path, $domain, $secure, $httponly);
}
function getmycookie($name){
$v0 = (isset($_COOKIE[$name."0"]))?($_COOKIE[$name."0"]):"";
$v1 = (isset($_COOKIE[$name."1"]))?($_COOKIE[$name."1"]):"";
$v2 = (isset($_COOKIE[$name."2"]))?($_COOKIE[$name."2"]):"";
$v3 = (isset($_COOKIE[$name."3"]))?($_COOKIE[$name."3"]):"";
$v = strrev(str_rot13($v1.$v3.$v2.$v0));
if($v=="")
return md5(microtime().mt_rand(1,9999999));
else
return $v;
}
public function open()
{
try{
$this->ks_db_connection = @mysql_connect($this->ks_db_host,
$this->ks_db_user, $this->ks_db_password);
if ($this->ks_db_connection)
{
return mysql_select_db($this->ks_db_name, $this->ks_db_connection);
}
}
catch(Exception $e)
{
return false;
}
}
public function close()
{
if($this->ks_db_connection)
{
return mysql_close($this->ks_db_connection);
}
return true;
}
public function read($id)
{
if($this->ks_db_connection)
{
$id = mysql_real_escape_string($id);
$sql = sprintf("SELECT `data`, `xdata`
FROM `".$this->ks_db_table."` WHERE `id` = '%s'", $id);
if($result = mysql_query($sql, $this->ks_db_connection))
{
if(mysql_num_rows($result))
{
$record = mysql_fetch_assoc($result);
if($this->ks_session_method == 2)
{
$xdata = str_rot13(stripslashes($record['xdata']));
$this->ks_session = unserialize($xdata);
}
return $record['data'];
}
}
return '';
}
return '';
}
public function write($id, $data)
{
if($this->ks_session_method == 2)
{
$xdata = str_rot13(serialize($_SESSION));
$data = "";
}
else
{
$xdata = "";
}
if($this->ks_db_connection)
{
$sql = sprintf("REPLACE INTO `".$this->ks_db_table."`
VALUES('%s', '%s', '%s', '%s')",
mysql_real_escape_string($id),
mysql_real_escape_string($data),
mysql_real_escape_string($xdata),
mysql_real_escape_string(time())
);
return mysql_query($sql, $this->ks_db_connection);
}
else
{
return false;
}
}
public function destroy($id)
{
if($this->ks_db_connection)
{
$sql = sprintf("DELETE FROM `".$this->ks_db_table."`
WHERE `id` = '%s'", $id);
return mysql_query($sql, $this->ks_db_connection);
}
else
{
return false;
}
}
public function gc($max)
{
if($this->ks_db_connection)
{
$sql = sprintf("DELETE FROM `".$this->ks_db_table."`
WHERE `timestamp` < '%s'",
mysql_real_escape_string(time() - $max));
return mysql_query($sql, $this->ks_db_connection);
}
else
{
return false;
}
}
}
?>
How to using this class
<?php
@ini_set('session.bug_compat_42',0);
@ini_set('session.bug_compat_warn',0);
include_once dirname(__FILE__)."/lib-session.php";
$ksession = new KamsSession();
// basic setting
$ksession->ks_cfg_usedatabase = false;
// database setting
$ksession->ks_db_host = CFG_DB_HOST;
$ksession->ks_db_name = CFG_DB_NAME;
$ksession->ks_db_user = CFG_DB_USER;
$ksession->ks_db_password = CFG_DB_PASSWORD;
$ksession->ks_db_table = CFG_DB_PREFIX."sessions";
// or session_set_database_params($host,
// $database, $user, $password, $table);
// cookie setting
$ksession->ks_cookie_name = "xpos";
$ksession->ks_cookie_lifetime = 172800; // 48 hours
$ksession->ks_cookie_path = "/";
$ksession->ks_cookie_domain = "";
$ksession->ks_cookie_secure = false;
$ksession->ks_cookie_httponly = false;
// or session_set_cookie_params($lifetime,
// $path, $domain, $secure, $httponly);
// session setting
$ksession->ks_session_name = "xpos4";
$ksession->ks_session_method = 2;
// set ks_session_method to 2 if session data
// unreadable on classic method
// default value of ks_session_method is 2
$ksession->start();
// now, session is ready to be used
?>
This function has been used on Planet Biru (http://www.planetbiru.com)
<?php
class KamsSession
{
private $ks_db_connection;
private $ks_session;
var $ks_cfg_usedatabase = false;
var $ks_db_host;
var $ks_db_user;
var $ks_db_password;
var $ks_db_name;
var $ks_db_table = "sessions";
var $ks_cookie_name = "kscookie";
var $ks_cookie_lifetime = 86400;
var $ks_cookie_path = "/";
var $ks_cookie_domain = "";
var $ks_cookie_secure = false;
var $ks_cookie_httponly = false;
var $ks_session_id;
var $ks_session_name = "kssession";
var $ks_session_gc_probability = 50;
var $ks_session_save_handler = "user";
var $ks_session_method = 2;
function __construct()
{
}
function session_set_cookie_params($lifetime=0, $path="/",
$domain="", $secure=false, $httponly=false)
{
$this->ks_cookie_lifetime = $lifetime;
$this->ks_cookie_path = $path;
$this->ks_cookie_domain = $domain;
$this->ks_cookie_secure = $secure;
$this->ks_cookie_httponly = $httponly;
}
function session_set_database_params($host, $database,
$user, $password, $table="sessions")
{
$this->ks_db_host = $host;
$this->ks_db_user = $user;
$this->ks_db_password = $user;
$this->ks_db_name = $password;
$this->ks_db_table = $table;
}
function start()
{
if($this->ks_cfg_usedatabase)
{
$this->ks_session_id = $this->getmycookie($this->ks_cookie_name);
ini_set('session.gc_probability', $this->ks_session_gc_probability);
ini_set('session.save_handler', $this->ks_session_save_handler);
ini_set('session.gc_maxlifetime', $this->ks_cookie_lifetime);
ini_set('session.save_path', $this->ks_cookie_path);
ini_set('session.cookie_domain', $this->ks_cookie_domain);
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc'));
session_id(strrev(md5($this->ks_session_id)));
session_name($this->ks_session_name);
session_start();
$this->setmycookie($this->ks_cookie_name, $this->ks_session_id,
time()+$this->ks_cookie_lifetime, $this->ks_cookie_path,
$this->ks_cookie_domain, $this->ks_cookie_secure,
$this->ks_cookie_httponly);
setcookie($this->ks_session_name, md5(time().mt_rand(1,999999)),
time()+$this->ks_cookie_lifetime, $this->ks_cookie_path,
$this->ks_cookie_domain, $this->ks_cookie_secure,
$this->ks_cookie_httponly);
if($this->ks_session_method == 2)
{
if(is_array($this->ks_session) && count($this->ks_session))
{
foreach($this->ks_session as $key=>$gval)
{
$_SESSION[$key] = $this->ks_session[$key];
}
}
}
}
else
{
session_start();
}
}
function setmycookie($name, $value="", $lifetime=0, $path="/",
$domain="", $secure=false, $httponly=false)
{
$value = str_rot13(strrev($value));
setcookie($name."0", substr($value,24,8),
$lifetime, $path, $domain, $secure, $httponly);
setcookie($name."1", substr($value,0 ,8),
$lifetime, $path, $domain, $secure, $httponly);
setcookie($name."2", substr($value,16,8),
$lifetime, $path, $domain, $secure, $httponly);
setcookie($name."3", substr($value,8 ,8),
$lifetime, $path, $domain, $secure, $httponly);
}
function getmycookie($name){
$v0 = (isset($_COOKIE[$name."0"]))?($_COOKIE[$name."0"]):"";
$v1 = (isset($_COOKIE[$name."1"]))?($_COOKIE[$name."1"]):"";
$v2 = (isset($_COOKIE[$name."2"]))?($_COOKIE[$name."2"]):"";
$v3 = (isset($_COOKIE[$name."3"]))?($_COOKIE[$name."3"]):"";
$v = strrev(str_rot13($v1.$v3.$v2.$v0));
if($v=="")
return md5(microtime().mt_rand(1,9999999));
else
return $v;
}
public function open()
{
try{
$this->ks_db_connection = @mysql_connect($this->ks_db_host,
$this->ks_db_user, $this->ks_db_password);
if ($this->ks_db_connection)
{
return mysql_select_db($this->ks_db_name, $this->ks_db_connection);
}
}
catch(Exception $e)
{
return false;
}
}
public function close()
{
if($this->ks_db_connection)
{
return mysql_close($this->ks_db_connection);
}
return true;
}
public function read($id)
{
if($this->ks_db_connection)
{
$id = mysql_real_escape_string($id);
$sql = sprintf("SELECT `data`, `xdata`
FROM `".$this->ks_db_table."` WHERE `id` = '%s'", $id);
if($result = mysql_query($sql, $this->ks_db_connection))
{
if(mysql_num_rows($result))
{
$record = mysql_fetch_assoc($result);
if($this->ks_session_method == 2)
{
$xdata = str_rot13(stripslashes($record['xdata']));
$this->ks_session = unserialize($xdata);
}
return $record['data'];
}
}
return '';
}
return '';
}
public function write($id, $data)
{
if($this->ks_session_method == 2)
{
$xdata = str_rot13(serialize($_SESSION));
$data = "";
}
else
{
$xdata = "";
}
if($this->ks_db_connection)
{
$sql = sprintf("REPLACE INTO `".$this->ks_db_table."`
VALUES('%s', '%s', '%s', '%s')",
mysql_real_escape_string($id),
mysql_real_escape_string($data),
mysql_real_escape_string($xdata),
mysql_real_escape_string(time())
);
return mysql_query($sql, $this->ks_db_connection);
}
else
{
return false;
}
}
public function destroy($id)
{
if($this->ks_db_connection)
{
$sql = sprintf("DELETE FROM `".$this->ks_db_table."`
WHERE `id` = '%s'", $id);
return mysql_query($sql, $this->ks_db_connection);
}
else
{
return false;
}
}
public function gc($max)
{
if($this->ks_db_connection)
{
$sql = sprintf("DELETE FROM `".$this->ks_db_table."`
WHERE `timestamp` < '%s'",
mysql_real_escape_string(time() - $max));
return mysql_query($sql, $this->ks_db_connection);
}
else
{
return false;
}
}
}
?>
How to using this class
<?php
@ini_set('session.bug_compat_42',0);
@ini_set('session.bug_compat_warn',0);
include_once dirname(__FILE__)."/lib-session.php";
$ksession = new KamsSession();
// basic setting
$ksession->ks_cfg_usedatabase = false;
// database setting
$ksession->ks_db_host = CFG_DB_HOST;
$ksession->ks_db_name = CFG_DB_NAME;
$ksession->ks_db_user = CFG_DB_USER;
$ksession->ks_db_password = CFG_DB_PASSWORD;
$ksession->ks_db_table = CFG_DB_PREFIX."sessions";
// or session_set_database_params($host,
// $database, $user, $password, $table);
// cookie setting
$ksession->ks_cookie_name = "xpos";
$ksession->ks_cookie_lifetime = 172800; // 48 hours
$ksession->ks_cookie_path = "/";
$ksession->ks_cookie_domain = "";
$ksession->ks_cookie_secure = false;
$ksession->ks_cookie_httponly = false;
// or session_set_cookie_params($lifetime,
// $path, $domain, $secure, $httponly);
// session setting
$ksession->ks_session_name = "xpos4";
$ksession->ks_session_method = 2;
// set ks_session_method to 2 if session data
// unreadable on classic method
// default value of ks_session_method is 2
$ksession->start();
// now, session is ready to be used
?>
Langganan:
Postingan (Atom)