<?php 
function SendMailCommon($myName,$myFrom,$myReplyTo,$myTo, $myCCList, $myBCCList, $mySubject,$myMsg, $MailFormat)
{
	global $WU_DATA;

	if(!isset($MailFormat) || ($MailFormat!=0 && $MailFormat!=1))
		$MailFormat = 1;
	 
	if($MailFormat==1)
	{
		$myMsgTop = "<table border='0' cellspacing='0' cellpadding='2' width='95%'>
			<tr><td><font face='verdana' size='2'>";
	
		$myMsgBottom = "</font></td></tr></table>";
	}
	else
	{
		$myMsg = strip_tags($myMsg);
		//$myMsg = str_replace("\n","",$myMsg);
		$myMsg = str_replace("\t","",$myMsg);
		$myMsg = str_replace("&nbsp;","",$myMsg);
		$myMsgTop = "";
		$myMsgBottom = "";
	}
	
	$headers = "From: $myName < $myFrom >\n";
	$headers .= "X-Sender: < $myFrom >\n";
	$headers .= "X-Mailer: PHP\n"; // mailer
	$headers .= "Return-Path: < $myFrom >\n";  // Return path for errors

	if($MailFormat == 1)
		$headers .= "Content-Type: text/html; charset=iso-8859-1\n"; // Mime type

	if(isset($myCCList) && strlen(trim($myCCList)) > 0)
		$headers .= "cc: $myCCList\n"; 

	if(isset($myBCCList) && strlen(trim($myBCCList)) > 0)
		$headers .= "bcc: $myBCCList\n"; 

	if(isset($myReplyTo) && strlen(trim($myReplyTo)) > 0)
		$headers .= "Reply-to: < $myReplyTo >\n"; 

	$receipient = $myTo;
	$subject = $mySubject;
	$message = $myMsgTop.$myMsg.$myMsgBottom;
	
	@mail($receipient,$subject,$message,$headers);
}

function sendMail($fromEmail='',$fromName='',$toEmail='',$toName='', $subject='',$message=''){
	
	if($fromEmail!='' && $toEmail!='' && $subject!='' && $message!=''){
		require_once 'PHPMailer/class.phpmailer.php';

		$mail = new PHPMailer(true); //defaults to using php "mail()"; the true param means it will throw exceptions on errors, which we need to catch

		try {
			  //$mail->AddReplyTo($toEmail, $toName);
			  $mail->AddAddress($toEmail, $toName);
			  $mail->SetFrom($fromEmail, $fromName);
			  $mail->Subject = $subject;
			  $mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically
			  $mail->MsgHTML($message);
			  $mail->Send();
			  return true;
			  
			} catch (phpmailerException $e) {
				return false;
			} catch (Exception $e) {
				return false;
			}
	}

}

function validateEmail($val)
{
	$my=$val;
	$attherate= strpos($my,"@");
	$lastattherate = strrpos($my,"@");
	$dotpos= strrpos($my,".");
	$posspace = strpos($my," ");
	$totallen = strlen($my);
	
	if ($attherate<=0 || $dotpos<=0 || $attherate > $dotpos || ($dotpos-$attherate)<=1 || ($dotpos == $totallen-1) || $posspace > -1 || $attherate!=$lastattherate)
	{
		return false;
	}
	else
		return true;
}

function getImageSizing($image_path){
	list($width, $height, $type, $attr)= getimagesize($image_path); 
	return $width.'X'.$height;
}


/* backup the db OR just a table */
function backup_tables($tables = '*',$path=''){
	
	//get all of the tables
	if($tables == '*')
	{
		$tables = array();
		$result = mysql_query('SHOW TABLES');
		while($row = mysql_fetch_row($result))
		{
			$tables[] = $row[0];
		}
	}
	else
	{
		$tables = is_array($tables) ? $tables : explode(',',$tables);
	}
	
	//cycle through
	foreach($tables as $table)
	{
		$result = mysql_query('SELECT * FROM '.$table);
		$num_fields = mysql_num_fields($result);
		
		$return.= 'DROP TABLE '.$table.';';
		$row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
		$return.= "\n\n".$row2[1].";\n\n";
		
		for ($i = 0; $i < $num_fields; $i++) 
		{
			while($row = mysql_fetch_row($result))
			{
				$return.= 'INSERT INTO '.$table.' VALUES(';
				for($j=0; $j<$num_fields; $j++) 
				{
					$row[$j] = addslashes($row[$j]);
					$row[$j] = ereg_replace("\n","\\n",$row[$j]);
					if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
					if ($j<($num_fields-1)) { $return.= ','; }
				}
				$return.= ");\n";
			}
		}
		$return.="\n\n\n";
	}
	
	//save file
	if($path!=''){
		$handle = fopen($path,'w+');
	}else{
		$handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
	}
	
	fwrite($handle,$return);
	fclose($handle);
	return  true;
	
}


function exportTableToCSV($table,$filename = 'export.csv',$exclude_filed=array(),$condition=''){
	    $csv_terminated = "\n";
	    $csv_separator = ",";
	    $csv_enclosed = '"';
	    $csv_escaped = "\\";
	    $sql_query = "select * from $table";
		if($condition != ''){
			$sql_query.= ' WHERE '.$condition;
		}
	
	    // Gets the data from the database
	    $result = mysql_query($sql_query);
	    $fields_cnt = mysql_num_fields($result);
	 
	    $schema_insert = '';
	 
	    for ($i = 0; $i < $fields_cnt; $i++)
	    {
	    	if(!in_array($i,$exclude_filed)){
	    	
		        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
		            stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
		        $schema_insert .= $l;
		        $schema_insert .= $csv_separator;
	    	}    
	    } // end for
	 
	    $out = trim(substr($schema_insert, 0, -1));
	    $out .= $csv_terminated;
	 
	    // Format the data
	    while ($row = mysql_fetch_array($result))
	    {
	        $schema_insert = '';
	        for ($j = 0; $j < $fields_cnt; $j++)
	        {
	        
   		    	if(!in_array($j,$exclude_filed)){
	
		            if ($row[$j] == '0' || $row[$j] != '')
		            {
		 
		                if ($csv_enclosed == '')
		                {
		                    $schema_insert .= $row[$j];
		                } else
		                {
		                    $schema_insert .= $csv_enclosed .
		                    str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
		                }
		            } else
		            {
		                $schema_insert .= '';
		            }
	  	            if ($j < $fields_cnt - 1)
		            {
		                $schema_insert .= $csv_separator;
		            }
		        }
	 
	        } // end for
	 
	        $out .= $schema_insert;
	        $out .= $csv_terminated;
	    } // end while
	 
	    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
	    header("Content-Length: " . strlen($out));
	    // Output to browser with appropriate mime type, you choose <img src="http://thetechnofreak.com/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley">
	    //header("Content-type: text/x-csv");
	    //header("Content-type: text/csv");
	    header("Content-type: application/csv");
	    header("Content-Disposition: attachment; filename=$filename");
	    echo $out;
	    exit;
	 
	}
	
	function covertObjectToArray($objData){
		$returnArr = array();
		
		if($objData && count($objData) > 0 ){
			foreach ($objData as $obd){
				$returnArr[] = $obd;
			}
		}
		return $returnArr;
	}
	

	function getExtension($str) {
	$i = strrpos($str,".");
	if (!$i) { return ""; }
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	return $ext;
}


function generateOrderID(){

	$characters = array("A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z","1","2","3","4","5","6","7","8","9");

	$keys = array();
	$random_chars = '';
	
	while(count($keys) < 7) {
	    $x = mt_rand(0, count($characters)-1);
	    if(!in_array($x, $keys)) {
	       $keys[] = $x;
	    }
	}	

	foreach($keys as $key){
	   $random_chars .= $characters[$key];
	}

return  $random_chars;
}
function validateUsername($val)
{
	
	if(preg_match('/^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/', $username))
		return false;
	else
		return true;
}

function daysDifference($endDate, $beginDate)
{
	$diff = abs(strtotime($endDate) - strtotime($beginDate));	
	$years = floor($diff / (365*60*60*24));
	$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
	$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
	
	return $years;
}
?>
