Wednesday, 14 February 2007

PHP: Form with smarty + captcha

Form composition with smarty + captcha


/*
Usage:
$ff=array(
array('text', 'field_name', 'label', array('class'=>'area'), array('postlabel'=>'ddd', 'validate'=>'empty')),
array('separator', 'td_class', 'text here'),
array('options', 'field_name2', 'label', array('options'=>array(1=>2)), array('postlabel'=>'ddd', 'check'=>'empty')),
array('submit', '', '', array('value'=>'Sign up')),
array('hidden', 'hid', '', array('value'=>'blah'))
);
sf_init($ff);

$smarty->assign(array('f2'=>$ff, 'in'=>$_REQUEST));
$sm->register_function('smarty_form', 'smarty_form');
{smarty_form fields=$f2 in=$in table_attr="class=tabt cellpadding=0 cellspacing=0" form_attr="method=post" colspan_class="separator"}

*/

function sf_init(&$ff) {
$ft=array('type', 'name', 'label', 'fp', 'gp'); // make readable array
foreach ($ff as $fd) {
$fdh=array(); foreach ($ft as $i=>$t) {if (isset($fd[$i])) $fdh[$t]=$fd[$i];}
$f2[]=$fdh;
}
$ff=$f2;
}
function iname($f2, $fd) {
foreach ($f2 as $i=>$f) {if ($f['name']==$fd) $fi=$i;}
return (isset($fi) ? $fi : -1);
}
function vfields($f2) {
$fr=array();
foreach ($f2 as $f) {
if (!in_array($f['type'], array('separator', 'submit')) && $f['name']!='captcha') $fr[]=$f['name'];
}
return $fr;
}

function smarty_form($p, &$smarty) {
$hidden=array();
foreach ($p['fields'] as $i=>$_fd) {$fd=&$p['fields'][$i];
// start values
$fd['fp']['name']=$fd['name']; // for form tags
$fd['fp']['type']=$fd['type'];
if (isset($p['in'][$fd['name']])) { // in-value
$par=(in_array($fd['type'], array('options', 'radios', 'checkboxes')) ? 'selected' : 'value');
$fd['fp'][$par]=$p['in'][$fd['name']];
}
// generate fields
if (in_array($fd['type'], array('options', 'radios', 'checkboxes'))) {
require_once(SMARTY_DIR."plugins/function.html_$fd[type].php");
if (isset($p['in'][$fd['name']])) $fd['fp']['selected']=$p['in'][$fd['name']];
$fields_t[$fd['name']]=call_user_func("smarty_function_html_$fd[type]", $fd['fp'], $smarty);
} elseif (!in_array($fd['type'], array('separator', 'hidden'))) {
$fields_t[$fd['name']]=_field_gen($fd['fp'], $fd['type']);
}
// data for table, hidden fields
if ($fd['type']=='hidden') $hidden[]=_field_gen($fd['fp'], $fd['type']);
elseif ($fd['type']=='separator') $data[][]=$fd['label'];
else $data[]=array(
$fd['label'].(isset($fd['gp']['check']) ? ' *' : ''),
$fields_t[$fd['name']].(isset($fd['gp']['plabel']) ? $fd['gp']['plabel'] : '')
);
}

$js=_jstext($p['fields']); // javascript-check
return $js.'<form '.$p['form_attr'].($js ? ' onsubmit="return validate_form(this)"' : '').'>'.
"\n".implode("\n", $hidden)."\n"._tablefm($data, &$p).'</form>';
}
function _tablefm($data, $p) {
$res[]='<table '.$p['table_attr'].'>';
$cols=0; foreach ($data as $line) {$c=count($line); if ($c>$cols) $cols=$c;}
foreach ($data as $line) {
$res[]='<tr>';
if (count($line)==1) $res[]="<td class=\"$p[colspan_class]\" colspan=$cols>$line[0]</td>";
else {foreach ($line as $y=>$v) $res[]="<td>$v</td>";}
$res[]='</tr>';
}
$res[]='</table>';
return implode("\n", $res);
}
function _jstext($fields_h) {
foreach ($fields_h as $fd) {
if (!isset($fd['gp']['check'])) continue;
$rs['name'][]=$fd['name'];
$rs['label'][]=$fd['label'];
$rs['check'][]=$fd['gp']['check'];
}
if (!$rs) return '';
return '
<script>
v_names = new Array("'.implode('", "', $rs['name']).'");
v_checks = new Array("'.implode('", "', $rs['check']).'");
v_labels = new Array("'.implode('", "', $rs['label']).'");

function validate_form(obj) {
errors="";
for (i=0; i<obj.elements.length; i++) {
for (y=0; y<v_names.length; y++) {
if (obj.elements[i].name==v_names[y]) errors+=_validate(v_checks[y], obj.elements[i], v_labels[y]);
}
}
if (errors) {alert(errors); return false;}
else return true;
}
function _validate(type, obj, label) {
res="";
if (type=="email") {
if (obj.value.indexOf(".")>2 && obj.value.indexOf("@") > 0) res="";
else res="E-mail address is not valid\n";
} else if (type=="empty") {
if (obj.value=="" || obj.value==null) res="Field \""+label+"\" is empty\n";
}
return res;
}
</script>
';
}
function _field_gen($params, $type='input') {
if ($type=='textarea') {
foreach ($params as $k=>$v) {if ($k!='value') $pp="$k=\"$v\"";}
return '<textarea '.implode(' ', $pp).'>'.(isset($params['value']) ? $params['value'] : '').'</textarea>';
} else {
foreach ($params as $k=>$v) {$pp[]="$k=\"$v\"";}
return '<input '.implode(' ', $pp).'>';
}
}


/*
Usage:
image.php:
$captcha=array(140, 34, 'britanic.ttf', 25, 0, 0, 0, array(255,255,255), array(0,0,50));
captcha();
form.php:
<form method="POST"><img src="img.php"><input type="text" name="captcha"><input type="submit"></form>
if ($_POST && check_captcha()) echo "ok";

*/

function captcha() {
global $captcha;
list($box_w, $box_h, $font, $font_size, $font_angle, $margin_left, $margin_top, $color_bg, $color_text)=$captcha;
$pass=''; $chm=rand(0,1);
$ch=array(str_split('aeiouy'), str_split('bcdfjhgkmnprstvxz'));
while (strlen($pass)<6) {$pass.=$ch[$chm][array_rand($ch[$chm])]; $chm=($chm ? 0:1);}
session_start();
$_SESSION['captcha'] = $pass;
$image = ImageCreatetruecolor($box_w,$box_h); // create the image resource
$color_bg = ImageColorAllocate($image, $color_bg[0], $color_bg[1], $color_bg[2]); // set colors
$color_text = ImageColorAllocate($image, $color_text[0], $color_text[1], $color_text[2]);
imagefill($image, 0, 0, $color_bg); // set background
imagettftext($image, $font_size, $font_angle, $margin_left, $font_size + $margin_top, $color_text, $font, $pass); // set text
header("Content-Type: image/jpg"); // or image/jpg
imagejpeg($image); // created image
imagedestroy($image);
}
function check_captcha() {
session_start();
if (isset($_SESSION['captcha']) && isset($_REQUEST['captcha']) && $_SESSION['captcha']==$_REQUEST['captcha']) {
unset($_SESSION['captcha']);
return 1;
}
return 0;
}

PHP highlight in Javascript

Javascript


<script>
function h_js(name) {
h_base(name, "js_", "(function|var|null|false|true|try|catch|if|else|new|return|for)", "([\!\(\)=\}\{,.])");
}
function h_php(name) {
h_base(name, "php_", "(function|global|array|echo|if|else|elseif|return|foreach|as|[\!\(\)=\}\{,.])");
}
function h_java(name) {
h_base(name, "java_", "(package|import|public|private|static|final|class|void|null|boolean|int|false|true|try|catch|if|else|new|return|for)");
}
function h_base(name, wpre, bvar, bres) {
obj=document.getElementById(name); if (!obj) return;
bvar=new RegExp(bvar, "ig");
bquote=new RegExp("(\"[^\"]+\"|'[^']+')", "ig");
bcomm=new RegExp("(\/\/ .*)", "ig");
if (bres) bres=new RegExp(bres, "ig");
ta=obj.innerHTML.split(lnbr);
for (i=0; i < ta.length; i++) {
cl=wpre+"res"; if (bres) ta[i]=ta[i].replace(bres, "<font class="+cl+">$1</font>");
cl=wpre+"var"; ta[i]=ta[i].replace(bvar, "<font class="+cl+">$1</font>");
cl=wpre+"quote"; ta[i]=ta[i].replace(bquote, "<font class="+cl+">$1</font>");
cl=wpre+"comment"; ta[i]=ta[i].replace(bcomm, "<font class="+cl+">$1</font>");
}
tj=ta.join("_LN_"); cl=wpre+"comment"; tj=tj.replace(/(\/\*.*?\*\/)/gi, "<font class="+cl+">$1</font>"); ta=tj.split("_LN_");
cl=wpre+"in"; obj.innerHTML="<pre class="+cl+">"+ta.join("\n")+"</pre>";
}
</script>


change code to push it to blog


function out_html($fname) {
$tt=htmlentities(file_get_contents($fname));
$tt=str_replace("\t", " ", $tt);
echo $tt;
}
function js_esc($fname) {
$txt=file_get_contents('1.txt');
$txt=preg_replace('/\r?\n/', '', $txt);
$txt=str_replace('\\', '\\\\', $txt);
$txt=str_replace('"', '\\"', $txt);
echo "<script>document.write(escape(\"$txt\"));</script>";
}

Wednesday, 7 February 2007

PHP: MySQL interface


/*
Mysql functions. Usage:

$isloc=1; $db=array('loc'=>array('localhost', 'root', '', 'db1'), 'srv'=>array());
mconn();
msel("INSER2T INTO stats (^i) VALUES (^v)", array('dt'=>'2006-12-25', 'hh'=>'5'));
msel("UPDATE stats SET ^u WHERE ".mesc('id=%s', "log'in"), array('dt'=>'2006-12-25', 'hh'=>'5'));
msel("SELECT FROM stats WHERE login=%s", array("log'in"), 'hash');
mdis();

mesc('id=%s', "log'in");
mesc('id=%s OR id=%s', array("log'in", "p'wd"));
mesc('id IN (%a)', array("log'in", "p'wd"));
*/

function mconn($link='') {
global $isloc, $db;
$t=$link.($isloc ? 'loc' : 'srv');
$db['_l'][$link]=mysql_connect($db[$t][0], $db[$t][1], $db[$t][2]);
mysql_select_db($db[$t][3], $db['_l'][$link]);
}
function mdis($link='') {
global $db;
mysql_close($db['_l'][$link]);
}
function msel($qu, $fv=array(), $st='', $link='', $sq='') {
global $db;
if (strpos($qu, 'SELECT')!==false) {
$qu=mesc($qu, $fv);
if ($sq) echo $qu."<br>\n";
$res=mysql_query($qu, $db['_l'][$link]);
if ($res===false) {echo '<b>'.$qu.mysql_error()."</b><br>\n"; return;}
$mfa=($st=='scal' ? MYSQL_NUM : MYSQL_ASSOC);
$lines=array(); while ($row=mysql_fetch_array($res, $mfa)) $lines[]=$row;
if ($st=='scal') return ($lines ? $lines[0][0] : '');
else if ($st=='hash') return ($lines ? $lines[0] : array());
else return $lines;
return $lines;
}
if (strpos($qu, 'INSERT')!==false) {
$fds=array(); $vas=array();
foreach ($fv as $f=>$v) {$fds[]=$f; $vas[]="'".mysql_escape_string($v)."'";}
$qu=str_replace('^i', implode(', ', $fds), $qu);
$qu=str_replace('^v', implode(', ', $vas), $qu);
} else if (strpos($qu, 'UPDATE')!==false) {
$vas=array();
foreach ($fv as $f=>$v) {$vas[]=$f.'='."'".mysql_escape_string($v)."'";}
$qu=str_replace('^u', implode(', ', $vas), $qu);
}
if ($sq) echo $qu."<br>\n";
$res=mysql_query($qu, $db['_l'][$link]);
if ($res===false) {echo '<b>'.mysql_error()."</b><br>\n"; return;}
}
function mesc($qu, $fv) {
if (strpos($qu, '%s')!==false) {
if (!is_array($fv)) return str_replace('%s', "'".mysql_escape_string($fv)."'", $qu);
else {foreach ($fv as $v) $qu=preg_replace('/%s/', "'".mysql_escape_string($v)."'", $qu, 1);}
} else if (strpos($qu, '%a')!==false) {
foreach ($fv as $i=>$v) $fv[$i]="'".mysql_escape_string($v)."'";
$str=implode(', ', $fv); if (!$str) $str=0;
return str_replace('%a', $str, $qu);
} else return $qu;
}

Tuesday, 6 February 2007

PHP: XML to Array and backwards

Here the XML with PHP solution: XML->Array and Array->XML.
Work with it as with usual array.

Format XML->Array
_c - children
_v - value
_a - attributes

This is 1.1 :)

Example #1 (1.xml):


<ddd>
<onemore dd="55">
<tt>333</tt>
<tt ss="s1">555</tt>
<tt>777</tt>
</onemore>
<two>sdf rr</two>
</ddd>



The code:

$xml=xml2ary(file_get_contents('1.xml'));
print_r($xml);


Here is the Array result:

Array
(
[ddd] => Array (
[_c] => Array (
[onemore] => Array (
[_a] => Array (
[dd] => 55
)
[_c] => Array (
[tt] => Array (
[0] => Array (
[_v] => 333
)
[1] => Array (
[_a] => Array (
[ss] => s1
)
[_v] => 555
)
[2] => Array (
[_v] => 777
)
)
)
)
[two] => Array (
[_v] => sdf rr
)
)
)
)


Example #2: (1.xml as described before)

$xml=xml2ary(file_get_contents('1.xml'));
$xml['ddd']['_c']['twomore']=$xml['ddd']['_c']['onemore'];
$xml['ddd']['_c']['twomore']['_c']['tt'][0]['_v']='hello';
echo ary2xml($xml);


Will output result:

<ddd>
<onemore dd="55">
<tt>hello</tt>
<tt ss="s1">555</tt>
<tt>777</tt>
</onemore>
<two>sdf rr</two>
<twomore dd="55">
<tt>hello</tt>
<tt ss="s1">555</tt>
<tt>777</tt>
</twomore>
</ddd>



THE Sources: :)

/*
Working with XML. Usage:
$xml=xml2ary(file_get_contents('1.xml'));
$link=&$xml['ddd']['_c'];
$link['twomore']=$link['onemore'];
// ins2ary(); // dot not insert a link, and arrays with links inside!
echo ary2xml($xml);
*/

// XML to Array
function xml2ary(&$string) {
$parser = xml_parser_create();
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parse_into_struct($parser, $string, $vals, $index);
xml_parser_free($parser);

$mnary=array();
$ary=&$mnary;
foreach ($vals as $r) {
$t=$r['tag'];
if ($r['type']=='open') {
if (isset($ary[$t])) {
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
$cv['_c']=array();
$cv['_c']['_p']=&$ary;
$ary=&$cv['_c'];

} elseif ($r['type']=='complete') {
if (isset($ary[$t])) { // same as open
if (isset($ary[$t][0])) $ary[$t][]=array(); else $ary[$t]=array($ary[$t], array());
$cv=&$ary[$t][count($ary[$t])-1];
} else $cv=&$ary[$t];
if (isset($r['attributes'])) {foreach ($r['attributes'] as $k=>$v) $cv['_a'][$k]=$v;}
$cv['_v']=(isset($r['value']) ? $r['value'] : '');

} elseif ($r['type']=='close') {
$ary=&$ary['_p'];
}
}

_del_p($mnary);
return $mnary;
}

// _Internal: Remove recursion in result array
function _del_p(&$ary) {
foreach ($ary as $k=>$v) {
if ($k==='_p') unset($ary[$k]);
elseif (is_array($ary[$k])) _del_p($ary[$k]);
}
}

// Array to XML
function ary2xml($cary, $d=0, $forcetag='') {
$res=array();
foreach ($cary as $tag=>$r) {
if (isset($r[0])) {
$res[]=ary2xml($r, $d, $tag);
} else {
if ($forcetag) $tag=$forcetag;
$sp=str_repeat("\t", $d);
$res[]="$sp<$tag";
if (isset($r['_a'])) {foreach ($r['_a'] as $at=>$av) $res[]=" $at=\"$av\"";}
$res[]=">".((isset($r['_c'])) ? "\n" : '');
if (isset($r['_c'])) $res[]=ary2xml($r['_c'], $d+1);
elseif (isset($r['_v'])) $res[]=$r['_v'];
$res[]=(isset($r['_c']) ? $sp : '')."</$tag>\n";
}

}
return implode('', $res);
}

// Insert element into array
function ins2ary(&$ary, $element, $pos) {
$ar1=array_slice($ary, 0, $pos); $ar1[]=$element;
$ary=array_merge($ar1, array_slice($ary, $pos));
}