require_once dirname(__FILE__)."/class.database.php" ;
require_once dirname(__FILE__)."/parsecsv.lib.php" ;
if ( isset($_SESSION["userid"]) )
{
define("USER_ID",$_SESSION["userid"]);
}
if ( !class_exists("Encryption") )
{
require_once dirname(__FILE__)."/encryption.php" ;
$encryption = new Encryption;
}
if ( !class_exists("chip_password_generator") )
{
include dirname(__FILE__)."/password.generator.php";
$args = array(
'length' => 8,
'alpha_upper_include' => TRUE,
'alpha_lower_include' => FALSE,
'number_include' => TRUE,
'symbol_include' => FALSE,
);
$generator = new chip_password_generator( $args );
}
class PARENT_CLASS {
var $status;
var $message_alert;
var $recent_sql;
function getRecent_sql()
{
return $this -> recent_sql;
}
function get_insert_id()
{
global $db;
return $db -> insert_id;
}
/* GET TOTAL FOR CERTAIN TABLE */
function getTotal($table_name,$criteria = "")
{
global $db;
$sQl = "select count(*) as jml from ".$table_name ;
if ( !empty($criteria) )
$sQl .= " ".$criteria;
$result = $db -> query($sQl);
return $result[0]["jml"];
}
function free_query($query)
{ global $db;
$result = $db -> query($query);
if ( $result )
{
return $result;
}
else
{
$this -> message_alert = $db -> error_message."
Query:".$query;
return false;
}
}
function total_perfield($table_name , $index_field, $criteria = "" )
{
global $db;
$sQl = "select ".$index_field." , count(*) as jml from ".$table_name ;
if ( !empty($criteria) )
$sQl .= " ".$criteria;
$sQl = $sQl." group by ".$index_field;
$result = $db -> query($sQl);
return $result ;
}
// FUNCTION FOR GENERATE ROWS ON CERTAIN TABLE
function view_data($table_name,$criteria = "",$order = "", $custom_fields ="" )
{
global $db;
$sql = "select * from ".$table_name;
if ( $custom_fields != "" )
{
$sql = "select ". $custom_fields." from ".$table_name;
}
$this -> recent_sql = $sql;
if ( !empty($criteria) )
$sql = $sql." ".$criteria;
if ( !empty($order) )
$sql = $sql." ".$order;
$result = $db -> query($sql);
if ( $result )
{
$this -> status = "view data success";
$this -> message_alert = "view data success";
}
else
{
$this -> status = "view data failed";
$this -> message_alert = "There was an error while trying gathering all datas";
}
return $result;
}
// FUNCTION FOR GENERATE ROWS ON CERTAIN TABLE
function insert_data($table_name , $arr_field , $unique_field = "" )
{
global $db;
$total_fields = count($arr_field);
if ( $total_fields < 1 ) {
$this -> status = "add failed";
$this -> message_alert = "Fields Null, Edit Can not be proceed";
return false;
}
$i = 1;
/** SPECIAL ACTION FOR UNIQUE FIELD */
if ( $unique_field != "" )
{
$sQl = "select * from ".$table_name." where ".$unique_field." = '".$arr_field[$unique_field]."' ";
$result = $db -> query($sQl) ;
if ( $result )
{
$this -> message_alert = $unique_field." with value '".$arr_field[$unique_field]."' already exists!";
return false;
}
}
// Generate POST Field
$fields = "";
$values = "";
foreach( $arr_field as $key => $value )
{ $i++;
if ($key != "submit" && $key != "password2" )
{
$fields .= $key.", " ;
$values .= "'".$value."'".", " ;
}
}
$fields = substr($fields,0, strlen($fields) - 2 );
$values = substr($values,0, strlen($values) - 2 );
$sQl = "insert into ".$table_name."(".$fields .")";
$sQl .= " values(".$values.")";
$result = $db -> query($sQl) ;
if ( $result )
{
$this -> status = "insert data success";
$this -> message_alert = "New data has been added successfully!";
}
else
{
$this -> status = "insert data failed";
$this -> message_alert = $db -> error_message."
Query:". $sQl ;
}
return $result;
}
function delete_data($table_name, $id )
{
global $db;
$r = $db -> query("delete from ".$table_name." where id = '$id' ");
if ( $r )
{
$this -> status = "delete success";
$this -> message_alert = "Data has been deleted successfully!";
}
else
{
$this -> status = "delete failed";
$this -> message_alert = "Database saving error, Deleting data can not be proceed";
}
return $r;
}
function edit_data($table_name,$arr_field, $id, $id_key="",$additional_condition="")
{
global $db;
$tot = count($arr_field);
if ( $tot < 1 ) {
$this -> status = "edit_failed";
$this -> message_alert = "Fields Null, Edit Can not be proceed array field empty!";
return false;
exit();
}
$i = 1;
// Generate POST Field
$fields = "";
$values = "";
foreach( $arr_field as $key => $value )
{ $i++;
if ($key != "submit" && $key != "password2" )
{
$fields .= $key."='".$value."'".", " ;
}
}
$fields = substr($fields,0, strlen($fields) - 2 );
$sQl = "update ".$table_name." set ".$fields ." where id = '$id' ";
if ( $id_key != "" )
$sQl = "update ".$table_name." set ".$fields ." where ".$id_key ." = '$id' ";
if ( !empty($additional_condition) )
{
$sQl .= " and ".$additional_condition;
}
$result = $db -> query($sQl) ;
if ( $result )
{
$this -> status = "edit success";
$this -> message_alert = "Data has been updated successfully!";
}
else
{
$this -> status = "edit failed";
$this -> message_alert = $db -> error_message;
}
return $result;
}
/**** SELECT BOX GENERATOR */
function selectview($table,$rowvalue,$rowlabel,$name,$selected="" )
{
global $db;
$q = "select $rowvalue, $rowlabel from $table order by $rowlabel asc ";
$r = $db -> query($q);
if ( $r )
{
$select = "";
$select .= "";
return $select;
}
else
{
return "";
}
}
/******************** FILE MANIPULATION *****/
/* GENERATE CONTENT FROM ANY EXISTING FILE */
function generate_content($filename)
{
if ( file_exists($filename ) )
{
$contains = "";
$file = fopen($filename, "r");
while(!feof($file))
{
$new_content = fgets($file);
$contains .= $new_content;
}
fclose($file);
$this -> message_alert = "File ".$filename." successfully loaded";
return $contains;
}
else
{
$this -> message_alert = "File ".$filename." Is Not Exists";
return false;
}
}
/* SAVE NEW CONTENT INTO FILE */
function save_content($filename,$fill_content="" )
{
if ( file_exists($filename ) )
{
$file = fopen($filename, "w+");
if ( $file )
{
ftruncate($file, 4);
fwrite($file,stripslashes($fill_content));
fclose($file);
$this -> message_alert = "File updated successfully!";
return true;
}
else
{
$this -> message_alert = "Saving Content Process Failed";
return false;
}
}
else
{
$this -> message_alert = "File ".$filename." Is Not Exists";
return false;
}
}/*End-Function*/
/* MAILING BOF */
// Generate Header for email
function email_header($from="")
{
$host = str_replace("www.","",$_SERVER['HTTP_HOST']);
if ( $from == "" )
{ // Default from email address is no-reply
$headers = "From: no-reply@".$_SERVER['HTTP_HOST']."\r\n";
$headers .= "Return-path:";
$from = "no-reply@".$host;
}
else
{
$headers = "From: ".$from."\r\n";
$headers .= "Return-path:<".$from.">";
}
$headers .= "\r\nMessage-ID:<".date("Ymdh").".message5q64iv3zhw8gc4kc@webmail.".$host.">\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8";
ini_set("sendmail_from", $from);
return $headers;
}
function send_email($content,$subject , $to, $from="" )
{
$headers = $this -> email_header($from);
$send = mail($to,$subject,$content,$headers );
return $send;
}
/* MAILING EOF */
function generate_pdf_file($content,$outputfile,$outputdir="", $stream=0,$download=0,$orientation="landscape",$paper="a4")
{
include "dompdf/dompdf_config.inc.php";
$html = ''.$content.
'';;
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->set_paper($paper, $orientation);
$dompdf->render();
if ( $stream ) // 1 if pdf will not write to phisic file
{
$dompdf->stream($outputfile, array('Attachment' => $download ) );
}
else // write to phisic file
{
if ( file_exists($outputdir.$outputfile) )
unlink($outputdir.$outputfile);
$pdfoutput = $dompdf->output();
$fp = fopen($outputdir.$outputfile, "a");
fwrite($fp, $pdfoutput);
fclose($fp);
}
return true;
}
function export_csv($fields="", $table_name,$criteria="", $output_file, $structure=0)
{
$csv = new parseCSV();
$result = $this -> view_data($table_name,$criteria,"",$fields ) ;
$fields = trim($fields);
$fields_arr = explode(",",$fields);
if ( $structure == 1 )
{
$result = array();
}
ini_set("max_execution_time", 600);
$csv->output($output_file,$result , $fields_arr );
}
function import_csv($table_name, $input_file)
{
$csv = new parseCSV();
# Parse '_books.csv' using automatic delimiter detection...
$csv->auto($input_file);
$this -> free_query("delete from ".$table_name);
$main_sql = "insert into ".$table_name;
$fields = implode(",",$csv->titles );
$fields_involved = $fields;
$fields .= ",fields_involved,userid"; // add custom column that will record involved column
$main_sql .= "(".$fields.") values";
foreach ($csv->data as $key => $row)
{
$datas = implode("','",$row );
// VALUES
$datas .= "','".$fields_involved."','".USER_ID;
$datas = "('".$datas."')";
$query = $main_sql.$datas;
$r = $this -> free_query($query);
}
return "success" ;
}
// IMPORT HANDLE
function proceed_import($table_csv,$table_main )
{
$q = "select fields_involved from ".$table_csv." where userid = '".$_SESSION["userid"]."'";
$r = $this -> free_query($q );
$fields = $r[0]["fields_involved"];
// remove id from list because it will fill automate in insert mode
$fields2 = str_replace(" id,","",$fields );
$fields_arr = $fields2 ;
// convert fields string to array
$fields_arr = explode(",",$fields_arr );
// gathering all import data for current user
$r = $this -> free_query("select ".$fields2." from ".$table_csv." where userid = ".$_SESSION["userid"]." ");
$msg_error = "
";
$m=0; // for row number
$total_data = count($r);
$failed = 0; // for count failed process number
for ( $i=0; $i < count($r); $i++)
{
$m ++;
$set = "";
$args = array();
for ( $j=0; $j < count($fields_arr); $j++)
{
$key = trim($fields_arr[$j]) ;
$args[$key] = $r[$i][$key];
}
// if id = 0 then insert, else update
$id = $args["id"];
unset($args["id"]);
if ( $id == 0 )
{
$c = $this -> insert_new($args);
if ( $c == false )
{
$failed ++;
$msg_error .= "
note for row #$m : ".$this -> message_alert ;
}
}
else
{
$c = $this -> update_info($args,$id);
if ( $c == false )
{
$failed ++;
$msg_error .= "
note for row #$m : ".$this -> message_alert ;
}
}
}
$success = $total_data - $failed;
$this -> message_alert = "Total data : $total_data, successfully processed : $success, failed processed : $failed".$msg_error ;
if ( $failed > 0 )
return false;
else
return true;
} // end of function
// usage sync_phone("test","phone,fax,mobile");
// fix invalid phone format to valid format
function sync_phones($table_name,$arr_target)
{
$fields_arr = explode(",",$arr_target);
for ( $i =0; $i < count($fields_arr); $i++)
{
$item1 = " SUBSTR(TRIM(".$fields_arr[$i]."),1,3) ";
$item2 = " SUBSTR(TRIM(".$fields_arr[$i]."),5,3) ";
$item3 = " SUBSTR(TRIM(".$fields_arr[$i]."),9,4) ";
$item_f1 = $fields_arr[$i]."1";
$item_f2 = $fields_arr[$i]."2";
$item_f3 = $fields_arr[$i]."3";
$q = "update ".$table_name." set ".$fields_arr[$i]." = REPLACE(".$fields_arr[$i].",'(','') ";
$this -> free_query($q);
$q = "update ".$table_name." set ".$fields_arr[$i]." = REPLACE(".$fields_arr[$i].",')','') ";
$this -> free_query($q);
$q = "update ".$table_name." set ".$fields_arr[$i]." = REPLACE(".$fields_arr[$i].",' ','-') ";
$this -> free_query($q);
$q = "update ".$table_name." set ".$item_f1." = ".$item1.",".$item_f2." = ".$item2.",".$item_f3." = ".$item3;
$this -> free_query($q);
}
return true;
}
function get_email_template()
{
$r = $this -> view_data("email_template");
return $r[0];
}
function update_email_template($arr_field)
{
$r = $this -> edit_data("email_template",$arr_field,"0");
return $r;
}
function check_if_user_exists($value,$key = "username",$type_login="")
{
if ( $key == "associted_with" && $type_login == retailer_id )
{
// retailer has different action in modificate associated_with field.
$r = $this -> view_data("login_user"," where ".$key." like '%,".$value."%' or ".$key." like '%".$value.",%' and type_login = '".$type_login."' ");
}
else
{
$r = $this -> view_data("login_user"," where ".$key." = '".$value."' ");
if ( $type_login != "" )
{
$r = $this -> view_data("login_user"," where ".$key." = '".$value."' and type_login = '".$type_login."'");
}
}
if ( count($r) > 0 )
return $r;
else
return false;
}
function generate_text() // useful for password or random text
{
global $generator ;
$password = $generator -> get_password();
return $password;
}
/* ENCRYPTION */
function encrypt($string)
{
global $encryption ;
return $encryption -> encrypt($string);
}
function decrypt($string)
{
global $encryption ;
return $encryption -> decrypt($string);
}
/* fields exist validation
check whether any value in certain field exists or not */
function is_field_exits($field_name, $table_name, $value)
{
$r = $this -> view_data( $table_name," where ".$field_name." = '".$value."'");
if ( count($r) > 0 )
return true;
else
return false;
}
function replace_params($arr_args,$content)
{
$new_content = $content;
foreach( $arr_args as $key => $val )
{
$new_content = str_replace($key ,$val,$new_content);
}
return $new_content;
}
// data pending processing
function approve_pending($id,$user=false)
{
if ( $user == false ) // if approve user
{
$r = $this -> view_pending(" where id = ".$id);
$r = $r[0];
switch($r["type_pending"])
{
case "insert" :
$fields = $this -> get_approval_field();
$fields = str_replace(" id,","",$fields );
$q = "insert into ".$this -> table_main."($fields) select ".$fields." from ".$this -> table_pending." where id = ".$id;
$x = $this -> free_query($q);
if ( $x == false )
{
return false;
}
$new_id = $this -> get_insert_id();
// update user info
$q = "update login_user set associted_with = $new_id, pending = 0 where associted_with = ".$id;
$y = $this -> free_query($q);
$x = $this -> delete_data($this -> table_pending,$id);
if ( $this -> table_main == "store" )
{
$this -> free_query(" update store_category set store_id = ".$new_id." where store_id = ".$id);
}
return true;
break;
case "edit" :
$fields_involved = $r["fields_involved"];
$fields_involved = explode(",",$fields_involved);
$q = "update ".$this -> table_main." set ";
foreach ( $fields_involved as $key => $value)
{
$value = trim($value);
$q .= $value." = '".$r[$value]."',";
}
$q .= ".";
$q = str_replace(",.","",$q);
$q .= " where id = ".$id;
$y = $this -> free_query($q);
// update user info
$q = "update login_user set pending = 0 where associted_with = ".$id;
$y = $this -> free_query($q);
$x = $this -> delete_data($this -> table_pending,$id);
return x;
break;
case "delete" :
$x = $this -> remove_data($id);
$y = $this -> delete_data($this -> table_pending,$id);
$z = $this -> remove_user($id);
return true;
break;
} // end switch
}
else // user pending approval
{
$q = "update login_user set pending = 0 where id = ".$id;
return $this -> free_query($q);
}
}
function denied_pending($id,$user=false)
{
if ( $user == false ) // if not denied pending user
{
$r = $this -> view_pending(" where id = ".$id);
$r = $r[0];
if ( $r["type_pending"] == "edit" )
{
// delete pending user info
//$q = "delete from login_user where pending = 1 and associted_with = ".$id;
//$y = $this -> free_query($q);
}
return $this -> delete_data($this -> table_pending,$id);
}
else // if denied pending user
{
$q = "delete login_user where id = ".$id;
return $this -> free_query($q);
}
}
function generate_new_name($table_name,$field_name,$value)
{
for ( $i =0; $i < 100; $i++)
{
$idx = "-".$i;
if ( $i == 0 )
$idx = "";
$new_value = $value.$idx;
$q = " select * from ".$table_name." where ".$field_name." = '".$new_value."' ";
$r = $this -> free_query($q);
if ( $r == false )
{
return $new_value;
}
}
}
############ SEARCHING FACILITY #############
function custom_search($term,$limit="",$idx="")
{
$r = $this -> view_info("where id = '".$term);
// first search by id
if ( $r )
return $r;
//step 2 - search by field
$field = $this -> get_search_field();
$field = explode(",",$field);
$where = "";
foreach($field as $key => $value )
{
$where .= "$value like '%$term%' Or ";
}
$where .= ".";
$where = str_replace("Or .","",$where);
$s = $this -> view_info("where ".$where,$limit);
if ( !empty($idx) )
{
$s = $this -> view_info("where ( ".$where." ) and id in ($idx) ",$limit);
}
return $s;
}
function custom_search2($term ) // for pagination ( no limit define )
{
$r = $this -> view_info("where id = '".$term);
// first search by id
if ( $r )
return $r;
//step 2 - search by field
$field = $this -> get_search_field();
$field = explode(",",$field);
$where = "";
foreach($field as $key => $value )
{
$where .= "$value like '%$term%' Or ";
}
$where .= ".";
$where = str_replace("Or .","",$where);
$s = $this -> free_query("select * from ".$this -> table_main." where ".$where );
if ( !empty($idx) )
{
$s = $this -> free_query("select * from ".$this -> table_main." where ".$where." and id in ($idx) ",$limit );
}
return $s;
}
function get_user_perid()
{
$r = $this -> view_data("login_user");
$users = array();
// loop category per index
for ( $i=0; $i< count($r); $i++)
{
$id = $r[$i]["id"];
$users[$id] = $r[$i]["username"];
}
return $users;
}
function remove_file($file_name)
{
if ( file_exists($file_name) )
unlink($file_name);
return true;
}
}
?>