Location: PHPKode > projects > PhpProjectMaster > www/inc/form_utils.php
<?php
/* 
 Better Form functions library for PHP
 (c) 2004-2007 by "Oleg Savchuk" <hide@address.com>

 part of phpProjectMaster project
 http://phpprojmaster.sourceforge.net

 The contents of this file are subject to the GNU GENERAL PUBLIC LICENSE
 http://www.gnu.org/copyleft/gpl.html
*/

 require_once "sitetpl.php";

/*
 validate_form
 validate_date
 is_dbrecord_exists
 is_dbrecord_exists2

 ComboDate2Str
 StrDate2SQL
 SQLDate2Str
 SQLDate2Unix
 Unix2SQLDate
 SQLDatetime2Date
 checkStrIsDate
 date_add

 date2htmlInput_raw
 date2htmlInput_combo

 field2chk
 get_combo_select
 get_select_name
 get_combo_select_name
 get_radio_select
 get_combo_select_sql

 int2commas
 str2cut

*/

$form_utils_DATE_FORMAT=0; //0 - DD/MM/YYYY (Europe), 1-MM/DD/YYYY (USA)   use $GLOBALS['form_utils_DATE_FORMAT']
$form_utils_DATE_FORMAT_STR="DD/MM/YYYY";
if ($form_utils_DATE_FORMAT) $form_utils_DATE_FORMAT_STR="MM/DD/YYYY";

$form_utils_TIME_FORMAT=0; //0 - HH:MM (Europe), 1-HH:MM AM/PM (USA)       use $GLOBALS['form_utils_TIME_FORMAT']
$form_utils_TIME_FORMAT_STR="HH:MM";
if ($form_utils_TIME_FORMAT) $form_utils_TIME_FORMAT_STR="HH:MM AM/PM";

$form_utils_AWEEKDAY=array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
$form_utils_AMONTH=array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');



//################# VALIDATE REQUIRED FIELDS
//IFORM form values
//REQFLD form descirption
function validate_form($IFORM, $REQFLD){
 $err_msg='';

 foreach ($REQFLD as $key => $value) {
   if (strlen($IFORM[$key])==0){
      $fname=(is_array($REQFLD[$key]))?$REQFLD[$key][0]:$REQFLD[$key];
      $err_msg=lng("Field")." \"$fname\" ".lng("is Required").".";
      break;
   }
 }

 return $err_msg;
}

//################# VALIDATE DATE
function validate_date($date_str, $field_name){
 global $form_utils_DATE_FORMAT_STR;

 if (!checkStrIsDate($date_str)){
    return lng("Field")." \"$field_name\" ".lng("should be in")." $form_utils_DATE_FORMAT_STR ".lng("format");
 }
}


// *****************************************
// *********** DATE FUNCTIONS
// from date string to array (day, month, year)
function ParseStrToDate($inDate, $date_format=''){

 if (!strlen($date_format)) $date_format=$GLOBALS['form_utils_DATE_FORMAT'];  //set global format if date_format not provided

 preg_match("/^\s*(\d+)\/(\d+)\/(\d+)\s*$/", $inDate, $matches);

 if ($date_format){// MM/DD/YYYY
    return array($matches[2]+0,$matches[1]+0,$matches[3]+0);

 }else{                       // DD/MM/YYYY
    return array($matches[1]+0,$matches[2]+0,$matches[3]+0);
 }

}

//from set of values to date in necessary format
function ParseDateToStr($day, $month, $year, $date_format=''){
 if (!strlen($date_format)) $date_format=$GLOBALS['form_utils_DATE_FORMAT'];  //set global format if date_format not provided

 if (strlen($day)<2) $day="0".$day;
 if (strlen($month)<2) $month="0".$month;

 if ($date_format){// MM/DD/YYYY
    return "$month/$day/$year";

 }else{            // DD/MM/YYYY
    return "$day/$month/$year";
 }
}

// *****************************************
function checkStrIsDate($s,$EmptyOK=false){
  $daysInMonth = array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
  if (!$s && $EmptyOK) return true;
  list($day, $month, $year)=ParseStrToDate($s);
  if (!(($year >= 1900) && ($year <= 2078))) return false;
  if (!(($month >= 1) && ($month <= 12))) return false;
  if (($day<1) or ($day>$daysInMonth[$month-1])) return false;
  $leapyeardays =(($year % 4 == 0) && ( (!($year % 100 == 0)) or ($year % 400 == 0) )) ? 29 : 28;
  if (($month==2) && ($day > $leapyeardays)) return false;
  return true;
}

// *****************************************
// from 3 REQUEST fields _DAY, _MON, _YEAR to date str
function ComboDate2Str($field_name, $hFORM=NULL){
 if (!$hFORM) $hFORM=$_REQUEST;

 list ($day, $month, $year)=array($hFORM[$field_name."_DAY"], $hFORM[$field_name."_MON"], $hFORM[$field_name."_YEAR"]);
 if (!$day or !$month or !$year) return '';

 #validate date
 if (!checkStrIsDate("$day/$month/$year",0)){
    #date can be invalid if day of Month is wrong like 31 Jun or 29 Feb 2001, so just add one month
    if ($day>=31 or $month==2 && $day>=29){
       $day=1;
       $month++;
       if ($month>12){
          $month=1;
          $year++;
       }
    } else{
      return '';
    }
 }

 return ParseDateToStr($day,$month,$year);
}

// *****************************************
// from date string to YYYY-MM-DD
function StrDate2SQL($s){
 if (!strlen($s)) return '';

 list($day, $month, $year)=ParseStrToDate($s);
 if (strlen($day)<2) $day="0".$day;
 if (strlen($month)<2) $month="0".$month;
 return "$year-$month-$day";
}

// *****************************************
// from YYYY-MM-DD to date string
// params: SQL Date, Format (if 1 - better human format), Add HH:MM:SS
function SQLDate2Str($s, $human_format=0, $add_hms=0){
 global $form_utils_AMONTH;

 if (!strlen($s) || $s=='0000-00-00') return '';

 $unixtime=SQLDate2Unix($s);

 $time_format_str='';
 if ($add_hms){
    if ($GLOBALS['form_utils_TIME_FORMAT']){
       $time_format_str=' h:i A';
    }else{
       $time_format_str=' H:i';
    }
 }

 if ($human_format){
    if ($GLOBALS['form_utils_DATE_FORMAT']){ // MM/DD/YYYY
       return date("M d Y".$time_format_str, $unixtime);

    }else{                                   // DD/MM/YYYY
       return date("d M Y".$time_format_str, $unixtime);
    }
 }else{
    if ($GLOBALS['form_utils_DATE_FORMAT']){ // MM/DD/YYYY
       return date("m/d/Y".$time_format_str, $unixtime);

    }else{                                   // DD/MM/YYYY
       return date("d/m/Y".$time_format_str, $unixtime);
    }
 }

}

##### from YYYY-MM-DD to UNIX time (epoch seconds)
function SQLDate2Unix($s){
 preg_match("/^(\d+)-(\d+)-(\d+)/", $s, $matches);
 list($year, $mon, $day)=array($matches[1],$matches[2],$matches[3]);

 //time
 list($hour, $min, $sec)=array(0,0,0);
 if ( preg_match("/(\d+):(\d+):(\d+)$/", $s, $matches) ) {
    list($hour, $min, $sec)=array($matches[1],$matches[2],$matches[3]);
 }

 return @mktime($hour, $min, $sec, $mon, $day, $year);
}

##### from UNIX time (epoch seconds) to YYYY-MM-DD HH:MM:SS
function Unix2SQLDate($unixtime){
  list ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($unixtime);
  $year+=1900;
  $mon+=1;
  return "$year-$mon-$mday $hour:$min:$sec";
}

############### SQL DateTime to just SQL Date
function SQLDatetime2Date($s){
 preg_match("/^(\d+)-(\d+)-(\d+) ?/", $s, $matches);

 return "$matches[1]-$matches[2]-$matches[3]";
}

###################
# $datetime=$_[0]; #unixtime
# $period=$_[1];  #d (default),m,y
# $amount=$_[2];
function date_add($datetime, $period, $amount){
 $result=0;

 list ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime($datetime);

// return mktime($hour, $min, $sec, $mon+1, $mday, $year+1900);

 if ($period=='y'){         #add years
    $result=mktime($hour, $min, $sec, $mon+1, $mday, $year+1900+$amount);
 } elseif ($period=='m'){    #add months
    $result=mktime($hour, $min, $sec, $mon+1+$amount, $mday, $year+1900);
 } else {    #add days
    $result=mktime($hour, $min, $sec, $mon+1, $mday+$amount, $year+1900);
 }

 return $result;
}

//************* current weekend = Sunday(0)
function date2weekend($time){

 $arr=getdate($time);
 $wday=$arr['wday'];  //0-Sunday: 6-Saturday
 $diff=7-$wday;
 if ($diff>=7) $diff=0;
 $result=strtotime("+$diff day", $time);

 return $result;
}


//************* from HH:MM[:SS] to dayseconds (from day begin, max 86400)
function time2sec($str){
 $result=0;
 $arr=explode(':',$str);
 
 if ( is_array($arr) ) {
    $result=$arr[0]*3600+$arr[1]*60+$arr[2];
 }

 return $result;
}

//************* from dayseconds to HH:MM
// $is_sec if set - also add seconds -> HH:MM:SS
function sec2time($sec, $is_sec=0){
 $result='';

 $b=floor($sec/3600);
// $result=toXX($b);
 $result=$b;
 $sec=$sec-$b*3600;
 $b=floor($sec/60);
 $result=$result.':'.toXX($b);
 if ($is_sec) {
    $sec=$sec-$b*60;
    $result=$result.':'.toXX($sec);
 }

 return $result;
}










//################### return >0 if record with the same db field exists
//Additional list of WHERE conditions can be specified
function is_dbrecord_exists2($table_name, $field_name, $field_value, $more_where=''){
 $sql="select count(*) from $table_name where $field_name=".db_quote($field_value);
 if ($more_where){
    $sql.=$more_where;
 }
// logger($sql);
//rw($sql);
 $sth=db_query($sql);
 $row=mysql_fetch_row($sth);

 return $row[0]+0;
}



#*********************************************************************
#Function: date2htmlInput_raw
#Purpose : create HTML for date input (not depend on dictionary)
#Params  : field name, field value, Form name
#Returns : HTML string
#Comment : -
#*********************************************************************
function date2htmlInput_raw($fname,$fvalue,$FormName='DataF'){
 global $root_url;

 if ( preg_match("/^\d+-\d+-\d+ ?/", $fvalue) ){ #if field contain date in SQL format - convert it to str
    $fvalue=SQLDate2Str($fvalue);
 }

 return "<input type=text name='$fname' value=\"$fvalue\" size=10 maxlength=10 onKeyPress='chkDigits(4)' class='text' onChange='input_changed()'>".
        "<A HREF=# onClick='PopUpCalendar(\"$FormName\",\"$fname\");'><IMG SRC='$root_url/img/calendar.gif' BORDER=0 alt='Popup Calendar'></A>";
}

#*********************************************************************
#Function: date2htmlInput_jq
#Purpose : create HTML for date input (jQuery.calendar version)
#Params  : field name, field value, Form name
#Returns : HTML string
#Comment : -
#*********************************************************************
function date2htmlInput_jq($fname,$fvalue,$FormName='DataF'){
 global $root_url;

 if ( preg_match("/^\d+-\d+-\d+ ?/", $fvalue) ){ #if field contain date in SQL format - convert it to str
    $fvalue=SQLDate2Str($fvalue);
 }

 return "<input type='text' name='$fname' value=\"$fvalue\" size='10' maxlength='10' onKeyPress='chkDigits(4)' class='text' onChange='input_changed()'>".
        "<a href='#' onclick=\"popUpCal.showFor($('input[@name=\\'$fname\\']')[0]);return false;\"><img src='$root_url/img/calendar.gif' border='0' alt='Popup Calendar' /></A>";
}

#*********************************************************************
#Function: date2htmlInput_combo
#Purpose : create HTML for date input (drop down view)
#Params  : field name, field value
#Returns : HTML string, field names created by adding _DAY,_MON,_YEAR to $fname
#Comment : -
#*********************************************************************
function date2htmlInput_combo($fname,$fvalue, $events=''){
 global $form_utils_AMONTH;

# logger("$fname => $fvalue");
 if ( preg_match("/^\d+-\d+-\d+ ?/", $fvalue) ){ #if field contain date in SQL format - convert it to str
    $fvalue=SQLDate2Str($fvalue);
 }

 list ($day, $month, $year)= ( $fvalue?ParseStrToDate($fvalue):array('','','') );
 $day=preg_replace("/^0+/", "", $day);
 $month=preg_replace("/^0+/", "", $month);
 $result='';

 #day
 $result.="<select name='item[${fname}_MON]' class='forms' $events>".get_combo_select_arr(array_merge(array(''),range(1,12)), array_merge(array(''),$form_utils_AMONTH), $month)."</select>";
 $result.="<select name='item[${fname}_DAY]' class='forms' $events>".get_combo_select_arr(array_merge(array(''),range(1,31)), array_merge(array(''),range(1,31)), $day)."</select>";
 $result.="<select name='item[${fname}_YEAR]' class='forms' $events>".get_combo_select_arr(array_merge(array(''),range(date("Y")-100, date("Y"))), array_merge(array(''),range(date("Y")-100, date("Y"))), $year)."</select>";

 return $result;
}


#*********************************************************************
#Function: time2htmlInput_combo
#Purpose : create HTML for time input (drop down view)
#Params  : field name, field value
#Returns : HTML string, field names created by adding _HH,_MM,_A to $fname
#Comment : AM/PM format only for now
#*********************************************************************
function time2htmlInput_combo($fname,$fvalue, $events=''){

 $time = SQLDate2Str($fvalue);
 preg_match("/^(\d+):(\d+) (\w+) ?/", $time, $match);
 $hour = $match[1];
 $minute = $match[2];
 $a = $match[3];
 
 $result.="<select name='${fname}_HH' $events>".get_combo_select_arr(array_merge(array(''),range(1,12)), array_merge(array(''),range(1,12)), $hour)."</select>";
 $result.="<select name='${fname}_MM' $events>".get_combo_select_arr(array_merge(array(''),get_minute_range()), array_merge(array(''),get_minute_range()), $minute)."</select>";
 $result.="<select name='${fname}_A' $events>".get_combo_select_arr(array_merge(array(''),array('am','pm')), array_merge(array(''),array('am','pm')), $a)."</select>";

 return $result;
}

function get_minute_range(){
    $min = array();
    for ($i=0; $i<60; $i++){
        if ($i<10){
            $i = "0".$i;
        }
        $min[]=$i;
    }
    return $min;
}


/*#*********************************************************************
#Function: get_combo_select
#Purpose : create HTML for select based on file data
#Params  : file, selected value, flag for do not include <select> tag
#Returns : HTML string
#Comment : SQL should return 2 fields: 0 - option value, 1 - option desc
#*********************************************************************
*/
function get_combo_select($infile, $sel_value, $no_select_tag=0){

 $lines='';

// if (file_exists($infile)) 
 $lines=preg_split("/[\r\n]+/",file_get_contents($infile));

 list ($name,$code)=preg_split("/\|/",$lines[0]);
 $selected=0;
 $result;
 if (!$no_select_tag) $result="<select name=\"$name\" $code>";
 for($i=1;$i<count($lines);$i++){
    list ($value,$desc)=preg_split("/\|/",$lines[$i]);
    if (!$value && !$desc) continue;

    if ($value==$sel_value){
       $result.="<option value=\"$value\" selected>$desc\n";
    }
    else{
       $result.="<option value=\"$value\">$desc";
    }
 }
 if (!$no_select_tag) $result.="</select>";
 return $result;
}


# alias for get_select_name
function get_select_name($infile, $sel_value){
 return get_combo_select_name($infile, $sel_value);
}

/*#*********************************************************************
#Function: get_combo_select_name
#Purpose : return only value's name for select based on file data
#Params  : file, selected value
#Returns : string
#Comment : 
#*********************************************************************
*/
function get_combo_select_name($infile, $sel_value){

 $lines=preg_split("/[\r\n]+/",file_get_contents($infile));

# list ($name,$code)=preg_split("/\|/",$lines[0]); #deprecated - first line is name for the field
 $selected=0;
 $result;

 for($i=0;$i<count($lines);$i++){
    list ($value,$desc)=preg_split("/\|/",$lines[$i]);
    if (!$value && !$desc) continue;

    if ($value==$sel_value){
       $result=$desc;
       break;
    }
 }

 return $result;
}

/*#*********************************************************************
#Function: get_combo_select_sql
#Purpose : create HTML for select based on SQL data
#Params  : sql, selected value
#Returns : HTML string
#Comment : SQL should return 2 fields: 0 - option value, 1 - option desc
#*********************************************************************
*/
function get_combo_select_sql($sql, $sel_value){

 $sth=db_query($sql);

 $selected=0;
 $result='';
 while( list($value,$desc)=mysql_fetch_row($sth)){
    if (!$value && !$desc){continue;}
    if ($value==$sel_value){
       $result.="<option value=\"$value\" selected>$desc\n";
    }
    else{
       $result.="<option value=\"$value\">$desc\n";
    }
 }
 return $result;
}

##########################
# get combo select HTML from Array of names and Values
# without <select tag>
function get_combo_select_arr($haValues, $haNames, $sel_value){

 $selected=0;
 $result;
 for($i=0;$i<count($haValues);$i++){
    list ($value,$desc)=array($haValues[$i], $haNames[$i]);

    if ($value==$sel_value){
       $result.="<option value=\"$value\" selected>$desc\n";
    }
    else{
       $result.="<option value=\"$value\">$desc\n";
    }
 }
 return $result;
}

//****************************
function get_radio_select($tpl, $sel_value, $name=''){

 $lines=preg_split("/[\r\n]/", file_get_contents($tpl) );

 if (!$name) list ($name,$delim)=preg_split("/\|/",$lines[0]);

 $selected=0;
 $result="";
 for($i=1;$i<=count($lines);$i++){
    list ($value,$desc)=preg_split("/\|/",$lines[$i]);
    if (!$value && !$desc) continue;
    $desc=preg_replace("/<ROOT_URL>/i", $root_url, $desc);

    if ($value==$sel_value){
       $result.="<input type=radio name=\"$name\" id=\"$name$i\" value=\"$value\" checked><label for=\"$name$i\">$desc</label>$delim\n";
    }
    else{
       $result.="<input type=radio name=\"$name\" id=\"$name$i\" value=\"$value\"><label for=\"$name$i\">$desc</label>$delim\n";
    }
 }
 return $result;
}



###########################
# 50817795 => 50,817,795
function int2commas($int, $group_digits=3, $separator=','){
 $int.='';
 $result='';

 $i;
 for($i=strlen($int)-$group_digits;$i>=0;$i-=$group_digits){
    $result=substr($int,$i,$group_digits).($result?$separator:'').$result;
 }
 if ($i>-$group_digits) $result=substr($int,0,$i+$group_digits).($result?$separator:'').$result;

 return $result;
}

############## cut str if it's len > limit
function str2cut($str, $limit){

 if ( function_exists('mb_strlen') ){
    if (mb_strlen($str)>$limit){
       $str=mb_substr($str,0,$limit)."...";
    }
 }else{
    if (strlen($str)>$limit){
       $str=substr($str,0,$limit)."...";
    }
 }

 return $str;
}

###### 0 -> 00, 9 -> 09, 10 -> 10
function toXX($int){
 if ($int<10){
    return '0'.$int;
 }else{
    return $int;
 }
}


//************ use before save html template from HTMLAREA to DB
function htmlarea2tpl($tpl){
 global $root_url;

 $tpl= preg_replace("/&lt;~([^&]+)&gt;/i", "<~$1>", $tpl);
 if ($root_url){
    $tpl= preg_replace("/".preg_quote($root_url,"/")."/i", "<~ROOT_URL>", $tpl);
 }

 return $tpl;
}

//************ use before save html template from HTMLAREA to DB
function tpl2htmlarea($tpl){
 global $root_url;

 $tpl= preg_replace("/<~ROOT_URL>/i", $root_url, $tpl);
 $tpl= preg_replace("/&/i", "&amp;", $tpl);

 return $tpl;
}


function int2YN($r){
 if ($r==1 or $r=='y' or $r=='Y'){
    return lng("Y");
 }
 else{
    return lng("N");
 }
}




// ****************** get first line from email - will be subject, return list(subj, body)
function email2subj_body($email){
 return preg_split("/\n/", $email, 2);
}



function get_replyed_text($intext, $MAX_LINE_CHARS=50){
 $intext.="\n";
 
 $intext=preg_replace("/<br>/i","\n",$intext);
 preg_match_all("/(.{1,$MAX_LINE_CHARS})\s/", $intext, $matches);
 $tarr=$matches[1];

 $intext='';
 for($i=0;$i<count($tarr);$i++){
   $intext.="> $tarr[$i]\n";
 }

 return $intext."\n";
}

//****************** return req/session option from
function get_page_option($var_name, $opt_name, $is_str=0){
 if (isset($_REQUEST[$var_name])){
    if (!$is_str) $_REQUEST[$var_name]+=0;
    $_SESSION[$opt_name]=$_REQUEST[$var_name];
 }

 if (!$is_str) $_SESSION[$opt_name]+=0;
 $var=$_SESSION[$opt_name];

 return $var;
}

//******************
function get_max_sort_order($table){
 return db_value("select max(sort_order) from $table where status<>127");
}

//******************
// change sort_order in table (actually exchange sort_order of 2 rows
//
// dir=-1 - #move up ( 9->0)
// dir=1 #move down ( 0->9)
function sort_order_move($table, $key_field, $item_id, $dir=0){
 $item_id+=0;

 $cmp_sign='';
 $sort_order='';
 if ($dir>0){      #move down ( 0->9)
    $cmp_sign='>';
    $sort_order='';

 }elseif($dir<0){  #move up ( 9->0)
    $cmp_sign='<';
    $sort_order='desc';

 }else{
    return;
 }

 $row1=db_row("select $key_field, sort_order from $table where $key_field=$item_id");

 #exchange sort_order with another Item
 $row2=db_row("select $key_field, sort_order 
      from $table
      where sort_order $cmp_sign ".dbq($row1['sort_order'])." 
      order by sort_order $sort_order
      LIMIT 1" );

 if ($row2[$key_field]>0){
    #record found - do exchange
    db_query("update $table set sort_order=".dbq($row2['sort_order'])." where $key_field=$item_id" ); #our rec
    db_query("update $table set sort_order=".dbq($row1['sort_order'])." where $key_field=".$row2[$key_field] ); #exch rec

 }else{
    #record not found - so we are at the top/bottom
    #no need to move
 }

 return $row2['sort_order']+0;
}

//********************
function perc2graph($perc){
 $BAR_WIDTH=100;

 $perc=$perc/100*$BAR_WIDTH;

 $ps=array(
    'title' => ceil($perc*100)/100,
    'width' => ceil($perc),
 );
 return parse_page('/common', 'progbar.html', $ps, 'v');
}

//********************
// in sql columns should be:
// 0 - id
// 1 - parent_id
// 2 - iname
// order by should be by parent_id
function get_combo_tree_sql($sql, $sel_value){
 $hCHILD=array(); #key - parent_id, value - pos in rows array

 $rows=db_array2($sql);
 for($i=0; $i<count($rows); $i++){
   $row=$rows[$i];

   $hCHILD[ $row[1] ][]=$i;
 }

 $haValues=array();
 $haNames=array();

 buid_arr_tree(0, $rows, $hCHILD, $haValues, $haNames, 0);

 return get_combo_select_arr($haValues, $haNames, $sel_value);
}

//RECURSIVE!!!
function buid_arr_tree($parent_id, &$rows, &$hCHILD, &$haValues, &$haNames, $level=0){
 if ( $level>20 || !is_array($hCHILD[$parent_id]) ) return; #protection from infinite loop

 foreach($hCHILD[$parent_id] as $i){
#    rw($i.'='.$rows[ $i ][2]);
    $id=$rows[$i][0];
    $haValues[]=$id;
    $haNames[]=str_repeat(' --- ',$level).$rows[ $i ][2];
    buid_arr_tree($id, $rows, $hCHILD, $haValues, $haNames, $level+1);
 }

}

// Convert PHP scalar, array or hash to JS scalar/array/hash. 
function php2js($a) 
{ 
    if (is_null($a)) return 'null'; 
    if ($a === false) return 'false'; 
    if ($a === true) return 'true'; 
    if (is_scalar($a)) { 
        $a = addslashes($a); 
        $a = str_replace("\n", '\n', $a); 
        $a = str_replace("\r", '\r', $a); 
        return "'$a'"; 
    } 
    $isList = true; 
    for ($i=0, reset($a); $i<count($a); $i++, next($a)) 
        if (key($a) !== $i) { $isList = false; break; } 
    $result = array(); 
    if ($isList) { 
        foreach ($a as $v) $result[] = php2js($v); 
        return '[ ' . join(',', $result) . ' ]'; 
    } else { 
        foreach ($a as $k=>$v) $result[] = php2js($k) . ': ' . php2js($v); 
        return '{ ' . join(',', $result) . ' }'; 
    } 
} 

?>
Return current item: PhpProjectMaster