validator_array = array();
$this->show_all_errors_together=true;
$this->error_hash = array();
$this->custom_validators=array();
}
function SetFileUploader(&$uploader)
{
$this->file_uploader = &$uploader;
$uploads = $this->file_uploader->getUploadFields();
foreach($this->validator_array as $val_obj)
{
if(false !== array_search($val_obj->variable_name,$uploads))
{
$command = '';
$command_value = '';
$this->parse_validator_string($val_obj->validator_string,
$command,$command_value);
$this->file_uploader->setFieldValidations($val_obj->variable_name,
$command,$command_value,$val_obj->error_string);
}
}
}
function SetDatabase(&$db)
{
$this->database = &$db;
}
function AddCustomValidator(&$customv)
{
array_push_ref($this->custom_validators,$customv);
}
function addValidation($variable,$validator,$error,$condition="")
{
$validator_obj = new ValidatorObj();
$validator_obj->variable_name = $variable;
$validator_obj->validator_string = $validator;
$validator_obj->error_string = $error;
$validator_obj->condition = $condition;
array_push($this->validator_array,$validator_obj);
}
function Process(&$continue)
{
$bResult = true;
if(!$this->common_objs->security_monitor->Validate($this->formvars))
{
$this->error_handler->ShowError("Form Security Check: Access Denied",/*show form*/false);
$continue = false;
return false;
}
if(false == $this->ValidateForm($this->formvars))
{
$bResult = false;
}
if(count($this->custom_validators) > 0)
{
foreach( $this->custom_validators as $custom_val)
{
if(false == $custom_val->DoValidate($this->formvars,$this->error_hash))
{
$bResult = false;
}
}
}
if(false === $this->ext_module->DoValidate($this->formvars,$this->error_hash))
{
$bResult = false;
}
if(!$bResult)
{
$continue=false;
$this->error_handler->ShowInputError($this->error_hash,$this->formname);
return false;
}
else
{
$continue=true;
return true;
}
}
function ValidateCurrentPage($form_variables)
{
if(!$this->common_objs->formpage_renderer->IsPageNumSet())
{
return true;
}
$cur_page_num =
$this->common_objs->formpage_renderer->GetCurrentPageNum();
$bResult = $this->ValidatePage($cur_page_num,$form_variables);
if(false === $this->ext_module->DoValidatePage($this->formvars,$this->error_hash,$cur_page_num))
{
$bResult = false;
}
if(!$bResult)
{
$this->logger->LogInfo("Page Validations $cur_page_num: Errors ".var_export($this->error_hash,TRUE));
$this->error_handler->ShowInputError($this->error_hash,$this->formname);
}
else
{
$this->logger->LogInfo("Page Validations $cur_page_num: succeeded");
}
return $bResult;
}
function IsThisElementInCurrentPage($varname)
{
$cur_page_num =
$this->common_objs->formpage_renderer->GetCurrentPageNum();
$elmnt_page =
$this->config->element_info->GetPageNum($varname);
return ($cur_page_num == $elmnt_page) ? true:false;
}
function ValidateForm($form_variables)
{
$bret = true;
$vcount = count($this->validator_array);
$this->logger->LogInfo("Validating form data: number of validations: $vcount" );
foreach($this->validator_array as $val_obj)
{
$page_num =
$this->config->element_info->GetPageNum($val_obj->variable_name);
//See if the page is shown
if(!$this->common_objs->formpage_renderer->TestPageCondition($page_num,$form_variables))
{
continue;
}
if(!$this->ValidateOneObject($val_obj,$form_variables))
{
$bret = false;
if(false == $this->show_all_errors_together)
{
break;
}
}
}
return $bret;
}
function ValidateOneObject($val_obj,&$form_variables)
{
$error_string="";
$bret = $this->ValidateObject($val_obj,$form_variables,$error_string);
if(!$bret)
{
$this->error_hash[$val_obj->variable_name] = $error_string;
}
return $bret;
}
function ValidatePage($page_num,$form_variables)
{
$bret = true;
$vcount = count($this->validator_array);
foreach($this->validator_array as $val_obj)
{
$elmnt_page =
$this->config->element_info->GetPageNum($val_obj->variable_name);
if($elmnt_page != $page_num)
{
continue;
}
if(!$this->ValidateOneObject($val_obj,$form_variables))
{
$this->logger->LogInfo("Validating variable ".$val_obj->variable_name." returns false" );
$bret = false;
if(false == $this->show_all_errors_together)
{
break;
}
}
}
return $bret;
}
function getErrors()
{
return $this->errors;
}
function parse_validator_string($validator_string,&$command,&$command_value)
{
$splitted = explode("=",$validator_string);
$command = $splitted[0];
$command_value = '';
if(isset($splitted[1]) && strlen($splitted[1])>0)
{
$command_value = $splitted[1];
}
}
function ValidateObject($validatorobj,$formvariables,&$error_string)
{
$bret = true;
//validation condition
if(isset($validatorobj->condition) &&
strlen($validatorobj->condition)>0)
{
if(false == $this->ValidateCondition(
$validatorobj->condition,$formvariables))
{
return true;
}
}
/*$splitted = explode("=",$validatorobj->validator_string);
$command = $splitted[0];
$command_value = '';
if(isset($splitted[1]) && strlen($splitted[1])>0)
{
$command_value = $splitted[1];
}*/
$command = '';
$command_value = '';
$this->parse_validator_string($validatorobj->validator_string,$command,$command_value);
$default_error_message="";
$input_value ="";
if(isset($formvariables[$validatorobj->variable_name]))
{
$input_value = $formvariables[$validatorobj->variable_name];
}
$extra_info="";
$bret = $this->ValidateCommand($command,$command_value,$input_value,
$default_error_message,
$validatorobj->variable_name,
$extra_info,
$formvariables);
if(false == $bret)
{
if(isset($validatorobj->error_string) &&
strlen($validatorobj->error_string)>0)
{
$error_string = $validatorobj->error_string;
}
else
{
$error_string = $default_error_message;
}
if(strlen($extra_info)>0)
{
$error_string .= "\n".$extra_info;
}
}//if
return $bret;
}
function ValidateCondition($condn,$formvariables)
{
return sfm_validate_multi_conditions($condn,$formvariables);
}
function validate_req($input_value, &$default_error_message,$variable_name)
{
$bret = true;
if(!isset($input_value))
{
$bret=false;
}
else
{
$input_value = trim($input_value);
if(strlen($input_value) <=0)
{
$bret=false;
}
$type = $this->config->element_info->GetType($variable_name);
if("datepicker" == $type)
{
$date_obj = new FM_DateObj($this->formvars,$this->config,$this->logger);
if(!$date_obj->GetDateFieldInStdForm($variable_name))
{
$bret=false;
}
}
}
if(!$bret)
{
$default_error_message = sprintf("Please enter the value for %s",$variable_name);
}
return $bret;
}
function validate_maxlen($input_value,$max_len,$variable_name,&$extra_info,&$default_error_message)
{
$bret = true;
if(isset($input_value) )
{
$input_length = strlen($input_value);
if($input_length > $max_len)
{
$bret=false;
$default_error_message = sprintf("Maximum length exceeded for %s.",$variable_name);
}
}
return $bret;
}
function validate_minlen($input_value,$min_len,$variable_name,&$extra_info,&$default_error_message)
{
$bret = true;
if(isset($input_value) )
{
$input_length = strlen($input_value);
if($input_length < $min_len)
{
$bret=false;
//$extra_info = sprintf(E_VAL_MINLEN_EXTRA_INFO,$min_len,$input_length);
$default_error_message = sprintf("Please enter input with length more than %d for %s",$min_len,$variable_name);
}
}
return $bret;
}
function test_datatype($input_value,$reg_exp)
{
if(preg_match($reg_exp,$input_value))
{
return true;
}
return false;
}
/**
Source: http://www.linuxjournal.com/article/9585?page=0,3
*/
function validate_email($email)
{
$isValid = true;
$atIndex = strrpos($email, "@");
if (is_bool($atIndex) && !$atIndex)
{
$isValid = false;
}
else
{
$domain = substr($email, $atIndex+1);
$local = substr($email, 0, $atIndex);
$localLen = strlen($local);
$domainLen = strlen($domain);
if ($localLen < 1 || $localLen > 64)
{
// local part length exceeded
$isValid = false;
}
else if ($domainLen < 1 || $domainLen > 255)
{
// domain part length exceeded
$isValid = false;
}
else if ($local[0] == '.' || $local[$localLen-1] == '.')
{
// local part starts or ends with '.'
$isValid = false;
}
else if (preg_match('/\\.\\./', $local))
{
// local part has two consecutive dots
$isValid = false;
}
else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
{
// character not valid in domain part
$isValid = false;
}
else if (preg_match('/\\.\\./', $domain))
{
// domain part has two consecutive dots
$isValid = false;
}
else if(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
str_replace("\\\\","",$local)))
{
// character not valid in local part unless
// local part is quoted
if (!preg_match('/^"(\\\\"|[^"])+"$/',
str_replace("\\\\","",$local)))
{
$isValid = false;
}
}
}
return $isValid;
}
//function validate_email($email)
//{
// return preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email);
//return preg_match('/^((([a-z]|\d|[!#\$%&\'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&\'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i',$email);
//}
function make_number($input_value)
{
return str_replace(",","",$input_value);
}
function validate_for_numeric_input($input_value,&$validation_success,&$extra_info)
{
$more_validations=true;
$validation_success = true;
if(strlen($input_value)>0)
{
if(false == is_numeric($input_value))
{
$extra_info = "Numeric value required.";
$validation_success = false;
$more_validations=false;
}
}
else
{
$more_validations=false;
}
return $more_validations;
}
function validate_lessthan($command_value,$input_value,
$variable_name,&$default_error_message,&$extra_info )
{
$bret = true;
$input_value = $this->make_number($input_value);
if(false == $this->validate_for_numeric_input($input_value,
$bret,$extra_info))
{
return $bret;
}
if($bret)
{
$lessthan = doubleval($command_value);
$float_inputval = doubleval($input_value);
if($float_inputval >= $lessthan)
{
$default_error_message = sprintf("Enter a value less than %f for %s",
$lessthan,
$variable_name);
$bret = false;
}//if
}
return $bret ;
}
function validate_greaterthan($command_value,$input_value,$variable_name,&$default_error_message,&$extra_info )
{
$bret = true;
$input_value = $this->make_number($input_value);
if(false == $this->validate_for_numeric_input($input_value,$bret,$extra_info))
{
return $bret;
}
if($bret)
{
$greaterthan = doubleval($command_value);
$float_inputval = doubleval($input_value);
if($float_inputval <= $greaterthan)
{
$default_error_message = sprintf("Enter a value greater than %f for %s",
$greaterthan,
$variable_name);
$bret = false;
}//if
}
return $bret ;
}
function validate_select($input_value,$command_value,&$default_error_message,$variable_name)
{
$bret=false;
if(is_array($input_value))
{
foreach($input_value as $value)
{
if($value == $command_value)
{
$bret=true;
break;
}
}
}
else
{
if($command_value == $input_value)
{
$bret=true;
}
}
if(false == $bret)
{
$default_error_message = sprintf("You should select option %s for %s",
$command_value,$variable_name);
}
return $bret;
}
function validate_dontselect($input_value,$command_value,&$default_error_message,$variable_name)
{
$bret=true;
if(is_array($input_value))
{
foreach($input_value as $value)
{
if($value == $command_value)
{
$bret=false;
$default_error_message = sprintf("Wrong option selected for %s",$variable_name);
break;
}
}
}
else
{
if($command_value == $input_value)
{
$bret=false;
$default_error_message = sprintf("Wrong option selected for %s",$variable_name);
}
}
return $bret;
}
function ValidateComparison($input_value,$formvariables,
$command_value,&$extra_info,&$default_error_message,$variable_name,$command)
{
$bret = true;
if(isset($input_value) &&
isset($formvariables[$command_value]))
{
$input_value = $this->make_number($input_value);
$valueOther = $this->make_number($formvariables[$command_value]);
if(true == $this->validate_for_numeric_input($input_value,$bret,$extra_info) &&
true == $this->validate_for_numeric_input($valueOther,$bret,$extra_info))
{
$valueThis = doubleval($input_value);
$valueOther = doubleval($valueOther);
switch($command)
{
case "ltelmnt":
{
if($valueThis >= $valueOther)
{
$bret = false;
$default_error_message = sprintf("Value of %s should be less than that of %s",$variable_name,$command_value);
}
break;
}
case "leelmnt":
{
if($valueThis > $valueOther)
{
$bret = false;
$default_error_message = sprintf("Value of %s should be less than or equal to that of %s",$variable_name,$command_value);
}
break;
}
case "gtelmnt":
{
if($valueThis <= $valueOther)
{
$bret = false;
$default_error_message = sprintf("Value of %s should be greater that of %s",$variable_name,$command_value);
}
break;
}
case "geelmnt":
{
if($valueThis < $valueOther)
{
$bret = false;
$default_error_message = sprintf("Value of %s should be greater or equal to that of %s",$variable_name,$command_value);
}
break;
}
}//switch
}
}
return $bret;
}
function ValidateCommand($command,$command_value,$input_value,&$default_error_message,$variable_name,&$extra_info,$formvariables)
{
$bret=true;
switch($command)
{
case 'required':
{
$bret = $this->validate_req($input_value, $default_error_message,$variable_name);
break;
}
case 'maxlen':
{
$max_len = intval($command_value);
$bret = $this->validate_maxlen($input_value,$max_len,$variable_name,
$extra_info,$default_error_message);
break;
}
case 'minlen':
{
$min_len = intval($command_value);
$bret = $this->validate_minlen($input_value,$min_len,$variable_name,
$extra_info,$default_error_message);
break;
}
case 'alnum':
{
$bret= $this->test_datatype($input_value,"/^[A-Za-z0-9]*$/");
if(false == $bret)
{
$default_error_message = sprintf("Please provide an alpha-numeric input for %s",$variable_name);
}
break;
}
case 'alnum_s':
{
$bret= $this->test_datatype($input_value,"/^[A-Za-z0-9\s]*$/");
if(false == $bret)
{
$default_error_message = sprintf("Please provide an alpha-numeric input for %s",$variable_name);
}
break;
}
case 'num':
case 'numeric':
{
if(isset($input_value) && strlen($input_value)>0)
{
if(!preg_match("/^[\-\+]?[\d\,]*\.?[\d]*$/",$input_value))
{
$bret=false;
$default_error_message = sprintf("Please provide numeric input for %s",$variable_name);
}
}
break;
}
case 'alpha':
{
$bret= $this->test_datatype($input_value,"/^[A-Za-z]*$/");
if(false == $bret)
{
$default_error_message = sprintf("Please provide alphabetic input for %s",$variable_name);
}
break;
}
case 'alpha_s':
{
$bret= $this->test_datatype($input_value,"/^[A-Za-z\s]*$/");
if(false == $bret)
{
$default_error_message = sprintf("Please provide alphabetic input for %s",$variable_name);
}
break;
}
case 'email':
{
if(isset($input_value) && strlen($input_value)>0)
{
$bret= $this->validate_email($input_value);
if(false == $bret)
{
$default_error_message = "Please provide a valida email address";
}
}
break;
}
case "lt":
case "lessthan":
{
$bret = $this->validate_lessthan($command_value,
$input_value,
$variable_name,
$default_error_message,
$extra_info );
break;
}
case "gt":
case "greaterthan":
{
$bret = $this->validate_greaterthan($command_value,
$input_value,
$variable_name,
$default_error_message,
$extra_info );
break;
}
case "regexp":
{
if(isset($input_value) && strlen($input_value)>0)
{
if(!preg_match("$command_value",$input_value))
{
$bret=false;
$default_error_message = sprintf("Please provide a valid input for %s",$variable_name);
}
}
break;
}
case "dontselect":
case "dontselectchk":
case "dontselectradio":
{
$bret = $this->validate_dontselect($input_value,
$command_value,
$default_error_message,
$variable_name);
break;
}//case
case "shouldselchk":
case "selectradio":
{
$bret = $this->validate_select($input_value,
$command_value,
$default_error_message,
$variable_name);
break;
}//case
case "selmin":
{
$min_count = intval($command_value);
$bret = false;
if(is_array($input_value))
{
$bret = (count($input_value) >= $min_count )?true:false;
}
else
{
if(isset($input_value) && !empty($input_value) && $min_count == 1)
{
$bret = true;
}
}
if(!$bret)
{
$default_error_message = sprintf("Please select minimum %d options for %s",
$min_count,$variable_name);
}
break;
}//case
case "selmax":
{
$max_count = intval($command_value);
if(isset($input_value))
{
$bret = (count($input_value) > $max_count )?false:true;
}
break;
}//case
case "selone":
{
if(false == isset($input_value)||
strlen($input_value)<=0)
{
$bret= false;
$default_error_message = sprintf("Please select an option for %s",$variable_name);
}
break;
}
case "eqelmnt":
{
if(isset($formvariables[$command_value]) &&
strcmp($input_value,$formvariables[$command_value])==0 )
{
$bret=true;
}
else
{
$bret= false;
$default_error_message = sprintf("Value of %s should be same as that of %s",$variable_name,$command_value);
}
break;
}
case "ltelmnt":
case "leelmnt":
case "gtelmnt":
case "geelmnt":
{
$bret= $this->ValidateComparison($input_value,$formvariables,
$command_value,$extra_info,$default_error_message,
$variable_name,
$command);
break;
}
case "neelmnt":
{
if(!empty($input_value))
{
if(strcmp($input_value,$formvariables[$command_value]) !=0 )
{
$bret=true;
}
else
{
$bret= false;
$default_error_message = sprintf("Value of %s should not be same as that of %s",$variable_name,$command_value);
}
}
break;
}
case "req_file":
case "max_filesize":
case "file_extn":
{
$bret= $this->ValidateFileUpload($variable_name,
$command,
$command_value,
$default_error_message);
break;
}
case "after_date":
{
$bret = $this->ValidateDate($command_value,$variable_name,false,$formvariables);
}
break;
case "before_date":
{
$bret = $this->ValidateDate($command_value,$variable_name,true,$formvariables);
}
break;
case "unique":
{
//$input_value, $default_error_message,$variable_name
if($this->database)
{
$bret = $this->database->IsFieldUnique($variable_name,$input_value);
if(!$bret)
{
$default_error_message = "This value is already submitted";
}
}
}
break;
}//switch
return $bret;
}//validdate command
function ValidateDate($command_value,$variable_name,$before,$formvariables)
{
$bret = true;
$date_obj = new FM_DateObj($formvariables,$this->config,$this->logger);
$date_other = $date_obj->GetOtherDate($command_value);
$date_this = $date_obj->GetDateFieldInStdForm($variable_name);
if(empty($formvariables[$variable_name]))
{
$bret=true;
}
else
if(!$date_other || !$date_this)
{
$this->logger->LogError("Invalid date received. ".$formvariables[$variable_name]);
$bret=false;
}
else
{
$bret = $before ? strcmp($date_this,$date_other) < 0: strcmp($date_this,$date_other)>0;
}
if(!$bret)
{
$this->logger->LogError("$variable_name: Date validation failed");
}
return $bret;
}
function ValidateFileUpload($variable_name,$command,$command_value,&$default_error_message)
{
$bret=true;
if($command != 'req_file' && !$this->IsThisElementInCurrentPage($variable_name))
{
return true;
}
$bret = $this->file_uploader->ValidateFileUpload($variable_name,$command,
$command_value,$default_error_message,/*form_submitted*/true);
return $bret;
}//function
}//FM_FormValidator
////////ConfirmPage/////////////////
class FM_ConfirmPage extends FM_Module
{
var $formdata_replacement_variable;
var $confirm_submit_variable_name;
var $templ_page;
var $uploader;
var $confirm_edit_button_code;
var $extra_code;
var $extra_code_place;
function FM_ConfirmPage($templ="")
{
$this->formdata_replacement_variable = "fwizformdata";
$this->confirm_submit_variable_name = 'sfm_confirm';
$this->confirm_edit_variable_name = 'sfm_confirm_edit';
$this->templ_page=$templ;
$this->confirm_button_replacement_variable="_sfm_confirm_button_";
$this->edit_button_replacement_variable="_sfm_edit_button_";
$this->print_button_replacement_variable="_sfm_print_button_";
$this->confirm_button_label = "Confirmed";
$this->confirm_edit_button_label = 'Edit';
$this->confirm_edit_button_code = '';
$this->confirm_button_code='';
$this->edit_button_code='';
$this->print_button_code='';
$this->extra_code='';
$this->extra_code_place='';
}
function SetConfirmButtonLabel($label)
{
$this->confirm_button_label = $label;
}
function SetFileUploader(&$upldr)
{
$this->uploader = &$upldr;
}
function Process(&$continue)
{
if($this->NeedShowFormDataEditPage())
{
$continue = false;
return $this->ShowEditPage();
}
elseif($this->NeedShowFormDataConfirmPage())
{
$continue = false;
return $this->ShowConfirmPage();
}
return true;
}
function NeedShowFormDataEditPage()
{
return $this->globaldata->IsButtonClicked($this->confirm_edit_variable_name)?true:false;
}
function NeedShowFormDataConfirmPage()
{
return $this->globaldata->IsButtonClicked($this->confirm_submit_variable_name)?false:true;
}
function IsFinalSubmission()
{
return $this->globaldata->IsButtonClicked($this->confirm_submit_variable_name)?true:false;
}
/*function IsButtonPressed($button_name)
{
if(isset($this->formvars[$button_name])||
isset($this->formvars[$button_name."_x"])||
isset($this->formvars[$button_name."_y"]))
{
return true;
}
return false;
}*/
function ShowEditPage()
{
$this->common_objs->formpage_renderer->DisplayFormPage(0);
return true;
}
function ShowConfirmPage()
{
if(!$this->CreateFormDataMap($datamap))
{
return false;
}
return $this->ShowFormDataConfirmPage($datamap);
}
function CreateFormDataMap(&$ret_map)
{
if(isset($this->formvars[$this->formdata_replacement_variable]))
{
$this->error_handler->HandleConfigError(
_("The variable %s is reserved as an internal variable. This variable can't be used as a form variable"),
$this->formdata_replacement_variable);
return false;
}
$this->common_objs->formvar_mx->AddToHtmlVars($this->formdata_replacement_variable);
$ret_map = $this->common_objs->formvar_mx->CreateFieldMatrix();
$session_var_name = $this->globaldata->SaveFormDataToSession();
if(isset($this->uploader))
{
$this->uploader->CreateUploadFilesVar($session_var_name);
}
$ret_map[$this->formdata_replacement_variable] =
$this->GetButtonCode($session_var_name);
$ret_map[$this->confirm_button_replacement_variable] =
$this->GetConfirmButtonCode($session_var_name);
$ret_map[$this->edit_button_replacement_variable] =
$this->GetEditButtonCode($session_var_name);
$ret_map[$this->print_button_replacement_variable] =
$this->GetPrintButtonCode($session_var_name);
return true;
}
function CreateSubmitButton($name,$label)
{
return " ";
}
function MakeCompleteFormCode($button_code,$session_var_name)
{
$action = $this->globaldata->get_php_self();
$str_ret = "
";
return $str_ret;
}
function GetButtonCode($session_var_name)
{
return $this->MakeCompleteFormCode($this->confirm_edit_button_code,$session_var_name);
}
function GetConfirmButtonCode($session_var_name)
{
return $this->MakeCompleteFormCode($this->confirm_button_code,$session_var_name);
}
function GetEditButtonCode($session_var_name)
{
return $this->MakeCompleteFormCode($this->edit_button_code ,$session_var_name);
}
function GetPrintButtonCode($session_var_name)
{
return $this->print_button_code;
}
function SetButtonCode($confirm_code,$edit_code,$print_code="")
{
$this->confirm_edit_button_code = "$confirm_code $edit_code";
$this->confirm_button_code = $confirm_code;
$this->edit_button_code = $edit_code;
$this->print_button_code = $print_code;
}
function SetExtraCode($extra_code)
{
$this->extra_code = $extra_code;
}
function ShowFormDataConfirmPage(&$datamap)
{
if(strlen($this->templ_page)<=0)
{
return false;
}
if(false == $this->ext_module->BeforeConfirmPageDisplay($datamap))
{
$this->logger->LogError("BeforeConfirmPageDisplay returns false!");
return false;
}
$merger = new FM_PageMerger();
$ret = true;
if(false == $merger->Merge($this->templ_page,$datamap))
{
$this->logger->LogError("ConfirmPage: merge failed");
$ret = false;
}
$out_str = $merger->getMessageBody();
if(!empty($this->extra_code))
{
$out_str = str_replace($this->extra_code_place,$this->extra_code,$out_str);
}
header("pragma: no-cache");
header("cache-control: no-cache");
header("Content-Type: text/html");
echo $out_str;
return $ret;
}
}
/**
* PEAR, the PHP Extension and Application Repository
*
* PEAR class and PEAR_Error class
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category pear
* @package PEAR
* @author Sterling Hughes
* @author Stig Bakken
* @author Tomas V.V.Cox
* @author Greg Beaver
* @copyright 1997-2008 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id$
* @link http://pear.php.net/package/PEAR
* @since File available since Release 0.1
*/
/**#@+
* ERROR constants
*/
define('PEAR_ERROR_RETURN', 1);
define('PEAR_ERROR_PRINT', 2);
define('PEAR_ERROR_TRIGGER', 4);
define('PEAR_ERROR_DIE', 8);
define('PEAR_ERROR_CALLBACK', 16);
/**
* WARNING: obsolete
* @deprecated
*/
define('PEAR_ERROR_EXCEPTION', 32);
/**#@-*/
define('PEAR_ZE2', (function_exists('version_compare') &&
version_compare(zend_version(), "2-dev", "ge")));
if (substr(PHP_OS, 0, 3) == 'WIN') {
define('OS_WINDOWS', true);
define('OS_UNIX', false);
define('PEAR_OS', 'Windows');
} else {
define('OS_WINDOWS', false);
define('OS_UNIX', true);
define('PEAR_OS', 'Unix'); // blatant assumption
}
// instant backwards compatibility
if (!defined('PATH_SEPARATOR')) {
if (OS_WINDOWS) {
define('PATH_SEPARATOR', ';');
} else {
define('PATH_SEPARATOR', ':');
}
}
$GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN;
$GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE;
$GLOBALS['_PEAR_destructor_object_list'] = array();
$GLOBALS['_PEAR_shutdown_funcs'] = array();
$GLOBALS['_PEAR_error_handler_stack'] = array();
@ini_set('track_errors', true);
/**
* Base class for other PEAR classes. Provides rudimentary
* emulation of destructors.
*
* If you want a destructor in your class, inherit PEAR and make a
* destructor method called _yourclassname (same name as the
* constructor, but with a "_" prefix). Also, in your constructor you
* have to call the PEAR constructor: $this->PEAR();.
* The destructor method will be called without parameters. Note that
* at in some SAPI implementations (such as Apache), any output during
* the request shutdown (in which destructors are called) seems to be
* discarded. If you need to get any debug information from your
* destructor, use error_log(), syslog() or something similar.
*
* IMPORTANT! To use the emulated destructors you need to create the
* objects by reference: $obj =& new PEAR_child;
*
* @category pear
* @package PEAR
* @author Stig Bakken
* @author Tomas V.V. Cox
* @author Greg Beaver
* @copyright 1997-2006 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: 1.7.2
* @link http://pear.php.net/package/PEAR
* @see PEAR_Error
* @since Class available since PHP 4.0.2
* @link http://pear.php.net/manual/en/core.pear.php#core.pear.pear
*/
class PEAR
{
// {{{ properties
/**
* Whether to enable internal debug messages.
*
* @var bool
* @access private
*/
var $_debug = false;
/**
* Default error mode for this object.
*
* @var int
* @access private
*/
var $_default_error_mode = null;
/**
* Default error options used for this object when error mode
* is PEAR_ERROR_TRIGGER.
*
* @var int
* @access private
*/
var $_default_error_options = null;
/**
* Default error handler (callback) for this object, if error mode is
* PEAR_ERROR_CALLBACK.
*
* @var string
* @access private
*/
var $_default_error_handler = '';
/**
* Which class to use for error objects.
*
* @var string
* @access private
*/
var $_error_class = 'PEAR_Error';
/**
* An array of expected errors.
*
* @var array
* @access private
*/
var $_expected_errors = array();
// }}}
// {{{ constructor
/**
* Constructor. Registers this object in
* $_PEAR_destructor_object_list for destructor emulation if a
* destructor object exists.
*
* @param string $error_class (optional) which class to use for
* error objects, defaults to PEAR_Error.
* @access public
* @return void
*/
function PEAR($error_class = null)
{
$classname = strtolower(get_class($this));
if ($this->_debug) {
print "PEAR constructor called, class=$classname\n";
}
if ($error_class !== null) {
$this->_error_class = $error_class;
}
while ($classname && strcasecmp($classname, "pear")) {
$destructor = "_$classname";
if (method_exists($this, $destructor)) {
global $_PEAR_destructor_object_list;
$_PEAR_destructor_object_list[] = &$this;
if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
register_shutdown_function("_PEAR_call_destructors");
$GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
}
break;
} else {
$classname = get_parent_class($classname);
}
}
}
// }}}
// {{{ destructor
/**
* Destructor (the emulated type of...). Does nothing right now,
* but is included for forward compatibility, so subclass
* destructors should always call it.
*
* See the note in the class desciption about output from
* destructors.
*
* @access public
* @return void
*/
function _PEAR() {
if ($this->_debug) {
printf("PEAR destructor called, class=%s\n", strtolower(get_class($this)));
}
}
// }}}
// {{{ getStaticProperty()
/**
* If you have a class that's mostly/entirely static, and you need static
* properties, you can use this method to simulate them. Eg. in your method(s)
* do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar');
* You MUST use a reference, or they will not persist!
*
* @access public
* @param string $class The calling classname, to prevent clashes
* @param string $var The variable to retrieve.
* @return mixed A reference to the variable. If not set it will be
* auto initialised to NULL.
*/
function &getStaticProperty($class, $var)
{
static $properties;
if (!isset($properties[$class])) {
$properties[$class] = array();
}
if (!array_key_exists($var, $properties[$class])) {
$properties[$class][$var] = null;
}
return $properties[$class][$var];
}
// }}}
// {{{ registerShutdownFunc()
/**
* Use this function to register a shutdown method for static
* classes.
*
* @access public
* @param mixed $func The function name (or array of class/method) to call
* @param mixed $args The arguments to pass to the function
* @return void
*/
function registerShutdownFunc($func, $args = array())
{
// if we are called statically, there is a potential
// that no shutdown func is registered. Bug #6445
if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
register_shutdown_function("_PEAR_call_destructors");
$GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true;
}
$GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args);
}
// }}}
// {{{ isError()
/**
* Tell whether a value is a PEAR error.
*
* @param mixed $data the value to test
* @param int $code if $data is an error object, return true
* only if $code is a string and
* $obj->getMessage() == $code or
* $code is an integer and $obj->getCode() == $code
* @access public
* @return bool true if parameter is an error
*/
function isError($data, $code = null)
{
if (is_a($data, 'PEAR_Error')) {
if (is_null($code)) {
return true;
} elseif (is_string($code)) {
return $data->getMessage() == $code;
} else {
return $data->getCode() == $code;
}
}
return false;
}
// }}}
// {{{ setErrorHandling()
/**
* Sets how errors generated by this object should be handled.
* Can be invoked both in objects and statically. If called
* statically, setErrorHandling sets the default behaviour for all
* PEAR objects. If called in an object, setErrorHandling sets
* the default behaviour for that object.
*
* @param int $mode
* One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
* PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
* PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION.
*
* @param mixed $options
* When $mode is PEAR_ERROR_TRIGGER, this is the error level (one
* of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
*
* When $mode is PEAR_ERROR_CALLBACK, this parameter is expected
* to be the callback function or method. A callback
* function is a string with the name of the function, a
* callback method is an array of two elements: the element
* at index 0 is the object, and the element at index 1 is
* the name of the method to call in the object.
*
* When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is
* a printf format string used when printing the error
* message.
*
* @access public
* @return void
* @see PEAR_ERROR_RETURN
* @see PEAR_ERROR_PRINT
* @see PEAR_ERROR_TRIGGER
* @see PEAR_ERROR_DIE
* @see PEAR_ERROR_CALLBACK
* @see PEAR_ERROR_EXCEPTION
*
* @since PHP 4.0.5
*/
function setErrorHandling($mode = null, $options = null)
{
if (isset($this) && is_a($this, 'PEAR')) {
$setmode = &$this->_default_error_mode;
$setoptions = &$this->_default_error_options;
} else {
$setmode = &$GLOBALS['_PEAR_default_error_mode'];
$setoptions = &$GLOBALS['_PEAR_default_error_options'];
}
switch ($mode) {
case PEAR_ERROR_EXCEPTION:
case PEAR_ERROR_RETURN:
case PEAR_ERROR_PRINT:
case PEAR_ERROR_TRIGGER:
case PEAR_ERROR_DIE:
case null:
$setmode = $mode;
$setoptions = $options;
break;
case PEAR_ERROR_CALLBACK:
$setmode = $mode;
// class/object method callback
if (is_callable($options)) {
$setoptions = $options;
} else {
trigger_error("invalid error callback", E_USER_WARNING);
}
break;
default:
trigger_error("invalid error mode", E_USER_WARNING);
break;
}
}
// }}}
// {{{ expectError()
/**
* This method is used to tell which errors you expect to get.
* Expected errors are always returned with error mode
* PEAR_ERROR_RETURN. Expected error codes are stored in a stack,
* and this method pushes a new element onto it. The list of
* expected errors are in effect until they are popped off the
* stack with the popExpect() method.
*
* Note that this method can not be called statically
*
* @param mixed $code a single error code or an array of error codes to expect
*
* @return int the new depth of the "expected errors" stack
* @access public
*/
function expectError($code = '*')
{
if (is_array($code)) {
array_push($this->_expected_errors, $code);
} else {
array_push($this->_expected_errors, array($code));
}
return sizeof($this->_expected_errors);
}
// }}}
// {{{ popExpect()
/**
* This method pops one element off the expected error codes
* stack.
*
* @return array the list of error codes that were popped
*/
function popExpect()
{
return array_pop($this->_expected_errors);
}
// }}}
// {{{ _checkDelExpect()
/**
* This method checks unsets an error code if available
*
* @param mixed error code
* @return bool true if the error code was unset, false otherwise
* @access private
* @since PHP 4.3.0
*/
function _checkDelExpect($error_code)
{
$deleted = false;
foreach ($this->_expected_errors AS $key => $error_array) {
if (in_array($error_code, $error_array)) {
unset($this->_expected_errors[$key][array_search($error_code, $error_array)]);
$deleted = true;
}
// clean up empty arrays
if (0 == count($this->_expected_errors[$key])) {
unset($this->_expected_errors[$key]);
}
}
return $deleted;
}
// }}}
// {{{ delExpect()
/**
* This method deletes all occurences of the specified element from
* the expected error codes stack.
*
* @param mixed $error_code error code that should be deleted
* @return mixed list of error codes that were deleted or error
* @access public
* @since PHP 4.3.0
*/
function delExpect($error_code)
{
$deleted = false;
if ((is_array($error_code) && (0 != count($error_code)))) {
// $error_code is a non-empty array here;
// we walk through it trying to unset all
// values
foreach($error_code as $key => $error) {
if ($this->_checkDelExpect($error)) {
$deleted = true;
} else {
$deleted = false;
}
}
return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
} elseif (!empty($error_code)) {
// $error_code comes alone, trying to unset it
if ($this->_checkDelExpect($error_code)) {
return true;
} else {
return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME
}
} else {
// $error_code is empty
return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME
}
}
// }}}
// {{{ raiseError()
/**
* This method is a wrapper that returns an instance of the
* configured error class with this object's default error
* handling applied. If the $mode and $options parameters are not
* specified, the object's defaults are used.
*
* @param mixed $message a text error message or a PEAR error object
*
* @param int $code a numeric error code (it is up to your class
* to define these if you want to use codes)
*
* @param int $mode One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT,
* PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE,
* PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION.
*
* @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter
* specifies the PHP-internal error level (one of
* E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR).
* If $mode is PEAR_ERROR_CALLBACK, this
* parameter specifies the callback function or
* method. In other error modes this parameter
* is ignored.
*
* @param string $userinfo If you need to pass along for example debug
* information, this parameter is meant for that.
*
* @param string $error_class The returned error object will be
* instantiated from this class, if specified.
*
* @param bool $skipmsg If true, raiseError will only pass error codes,
* the error message parameter will be dropped.
*
* @access public
* @return object a PEAR error object
* @see PEAR::setErrorHandling
* @since PHP 4.0.5
*/
function &raiseError($message = null,
$code = null,
$mode = null,
$options = null,
$userinfo = null,
$error_class = null,
$skipmsg = false)
{
// The error is yet a PEAR error object
if (is_object($message)) {
$code = $message->getCode();
$userinfo = $message->getUserInfo();
$error_class = $message->getType();
$message->error_message_prefix = '';
$message = $message->getMessage();
}
if (isset($this) && isset($this->_expected_errors) && sizeof($this->_expected_errors) > 0 && sizeof($exp = end($this->_expected_errors))) {
if ($exp[0] == "*" ||
(is_int(reset($exp)) && in_array($code, $exp)) ||
(is_string(reset($exp)) && in_array($message, $exp))) {
$mode = PEAR_ERROR_RETURN;
}
}
// No mode given, try global ones
if ($mode === null) {
// Class error handler
if (isset($this) && isset($this->_default_error_mode)) {
$mode = $this->_default_error_mode;
$options = $this->_default_error_options;
// Global error handler
} elseif (isset($GLOBALS['_PEAR_default_error_mode'])) {
$mode = $GLOBALS['_PEAR_default_error_mode'];
$options = $GLOBALS['_PEAR_default_error_options'];
}
}
if ($error_class !== null) {
$ec = $error_class;
} elseif (isset($this) && isset($this->_error_class)) {
$ec = $this->_error_class;
} else {
$ec = 'PEAR_Error';
}
if (intval(PHP_VERSION) < 5) {
// little non-eval hack to fix bug #12147
/*PJ: include 'PEAR/FixPHP5PEARWarnings.php';*/
return $a;
}
if ($skipmsg) {
$a = new $ec($code, $mode, $options, $userinfo);
} else {
$a = new $ec($message, $code, $mode, $options, $userinfo);
}
return $a;
}
// }}}
// {{{ throwError()
/**
* Simpler form of raiseError with fewer options. In most cases
* message, code and userinfo are enough.
*
* @param string $message
*
*/
function &throwError($message = null,
$code = null,
$userinfo = null)
{
if (isset($this) && is_a($this, 'PEAR')) {
$a = &$this->raiseError($message, $code, null, null, $userinfo);
return $a;
} else {
$a = &PEAR::raiseError($message, $code, null, null, $userinfo);
return $a;
}
}
// }}}
function staticPushErrorHandling($mode, $options = null)
{
$stack = &$GLOBALS['_PEAR_error_handler_stack'];
$def_mode = &$GLOBALS['_PEAR_default_error_mode'];
$def_options = &$GLOBALS['_PEAR_default_error_options'];
$stack[] = array($def_mode, $def_options);
switch ($mode) {
case PEAR_ERROR_EXCEPTION:
case PEAR_ERROR_RETURN:
case PEAR_ERROR_PRINT:
case PEAR_ERROR_TRIGGER:
case PEAR_ERROR_DIE:
case null:
$def_mode = $mode;
$def_options = $options;
break;
case PEAR_ERROR_CALLBACK:
$def_mode = $mode;
// class/object method callback
if (is_callable($options)) {
$def_options = $options;
} else {
trigger_error("invalid error callback", E_USER_WARNING);
}
break;
default:
trigger_error("invalid error mode", E_USER_WARNING);
break;
}
$stack[] = array($mode, $options);
return true;
}
function staticPopErrorHandling()
{
$stack = &$GLOBALS['_PEAR_error_handler_stack'];
$setmode = &$GLOBALS['_PEAR_default_error_mode'];
$setoptions = &$GLOBALS['_PEAR_default_error_options'];
array_pop($stack);
list($mode, $options) = $stack[sizeof($stack) - 1];
array_pop($stack);
switch ($mode) {
case PEAR_ERROR_EXCEPTION:
case PEAR_ERROR_RETURN:
case PEAR_ERROR_PRINT:
case PEAR_ERROR_TRIGGER:
case PEAR_ERROR_DIE:
case null:
$setmode = $mode;
$setoptions = $options;
break;
case PEAR_ERROR_CALLBACK:
$setmode = $mode;
// class/object method callback
if (is_callable($options)) {
$setoptions = $options;
} else {
trigger_error("invalid error callback", E_USER_WARNING);
}
break;
default:
trigger_error("invalid error mode", E_USER_WARNING);
break;
}
return true;
}
// {{{ pushErrorHandling()
/**
* Push a new error handler on top of the error handler options stack. With this
* you can easily override the actual error handler for some code and restore
* it later with popErrorHandling.
*
* @param mixed $mode (same as setErrorHandling)
* @param mixed $options (same as setErrorHandling)
*
* @return bool Always true
*
* @see PEAR::setErrorHandling
*/
function pushErrorHandling($mode, $options = null)
{
$stack = &$GLOBALS['_PEAR_error_handler_stack'];
if (isset($this) && is_a($this, 'PEAR')) {
$def_mode = &$this->_default_error_mode;
$def_options = &$this->_default_error_options;
} else {
$def_mode = &$GLOBALS['_PEAR_default_error_mode'];
$def_options = &$GLOBALS['_PEAR_default_error_options'];
}
$stack[] = array($def_mode, $def_options);
if (isset($this) && is_a($this, 'PEAR')) {
$this->setErrorHandling($mode, $options);
} else {
PEAR::setErrorHandling($mode, $options);
}
$stack[] = array($mode, $options);
return true;
}
// }}}
// {{{ popErrorHandling()
/**
* Pop the last error handler used
*
* @return bool Always true
*
* @see PEAR::pushErrorHandling
*/
function popErrorHandling()
{
$stack = &$GLOBALS['_PEAR_error_handler_stack'];
array_pop($stack);
list($mode, $options) = $stack[sizeof($stack) - 1];
array_pop($stack);
if (isset($this) && is_a($this, 'PEAR')) {
$this->setErrorHandling($mode, $options);
} else {
PEAR::setErrorHandling($mode, $options);
}
return true;
}
// }}}
// {{{ loadExtension()
/**
* OS independant PHP extension load. Remember to take care
* on the correct extension name for case sensitive OSes.
*
* @param string $ext The extension name
* @return bool Success or not on the dl() call
*/
function loadExtension($ext)
{
if (!extension_loaded($ext)) {
// if either returns true dl() will produce a FATAL error, stop that
if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) {
return false;
}
if (OS_WINDOWS) {
$suffix = '.dll';
} elseif (PHP_OS == 'HP-UX') {
$suffix = '.sl';
} elseif (PHP_OS == 'AIX') {
$suffix = '.a';
} elseif (PHP_OS == 'OSX') {
$suffix = '.bundle';
} else {
$suffix = '.so';
}
return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix);
}
return true;
}
// }}}
}
// {{{ _PEAR_call_destructors()
function _PEAR_call_destructors()
{
global $_PEAR_destructor_object_list;
if (is_array($_PEAR_destructor_object_list) &&
sizeof($_PEAR_destructor_object_list))
{
reset($_PEAR_destructor_object_list);
if (PEAR::getStaticProperty('PEAR', 'destructlifo')) {
$_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list);
}
while (list($k, $objref) = each($_PEAR_destructor_object_list)) {
$classname = get_class($objref);
while ($classname) {
$destructor = "_$classname";
if (method_exists($objref, $destructor)) {
$objref->$destructor();
break;
} else {
$classname = get_parent_class($classname);
}
}
}
// Empty the object list to ensure that destructors are
// not called more than once.
$_PEAR_destructor_object_list = array();
}
// Now call the shutdown functions
if (is_array($GLOBALS['_PEAR_shutdown_funcs']) AND !empty($GLOBALS['_PEAR_shutdown_funcs'])) {
foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) {
call_user_func_array($value[0], $value[1]);
}
}
}
// }}}
/**
* Standard PEAR error class for PHP 4
*
* This class is supserseded by {@link PEAR_Exception} in PHP 5
*
* @category pear
* @package PEAR
* @author Stig Bakken
* @author Tomas V.V. Cox
* @author Gregory Beaver
* @copyright 1997-2006 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: 1.7.2
* @link http://pear.php.net/manual/en/core.pear.pear-error.php
* @see PEAR::raiseError(), PEAR::throwError()
* @since Class available since PHP 4.0.2
*/
class PEAR_Error
{
// {{{ properties
var $error_message_prefix = '';
var $mode = PEAR_ERROR_RETURN;
var $level = E_USER_NOTICE;
var $code = -1;
var $message = '';
var $userinfo = '';
var $backtrace = null;
// }}}
// {{{ constructor
/**
* PEAR_Error constructor
*
* @param string $message message
*
* @param int $code (optional) error code
*
* @param int $mode (optional) error mode, one of: PEAR_ERROR_RETURN,
* PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER,
* PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION
*
* @param mixed $options (optional) error level, _OR_ in the case of
* PEAR_ERROR_CALLBACK, the callback function or object/method
* tuple.
*
* @param string $userinfo (optional) additional user/debug info
*
* @access public
*
*/
function PEAR_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
if ($mode === null) {
$mode = PEAR_ERROR_RETURN;
}
$this->message = $message;
$this->code = $code;
$this->mode = $mode;
$this->userinfo = $userinfo;
if (!PEAR::getStaticProperty('PEAR_Error', 'skiptrace')) {
$this->backtrace = debug_backtrace();
if (isset($this->backtrace[0]) && isset($this->backtrace[0]['object'])) {
unset($this->backtrace[0]['object']);
}
}
if ($mode & PEAR_ERROR_CALLBACK) {
$this->level = E_USER_NOTICE;
$this->callback = $options;
} else {
if ($options === null) {
$options = E_USER_NOTICE;
}
$this->level = $options;
$this->callback = null;
}
if ($this->mode & PEAR_ERROR_PRINT) {
if (is_null($options) || is_int($options)) {
$format = "%s";
} else {
$format = $options;
}
printf($format, $this->getMessage());
}
if ($this->mode & PEAR_ERROR_TRIGGER) {
trigger_error($this->getMessage(), $this->level);
}
if ($this->mode & PEAR_ERROR_DIE) {
$msg = $this->getMessage();
if (is_null($options) || is_int($options)) {
$format = "%s";
if (substr($msg, -1) != "\n") {
$msg .= "\n";
}
} else {
$format = $options;
}
die(sprintf($format, $msg));
}
if ($this->mode & PEAR_ERROR_CALLBACK) {
if (is_callable($this->callback)) {
call_user_func($this->callback, $this);
}
}
if ($this->mode & PEAR_ERROR_EXCEPTION) {
trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_Exception for exceptions", E_USER_WARNING);
eval('$e = new Exception($this->message, $this->code);throw($e);');
}
}
// }}}
// {{{ getMode()
/**
* Get the error mode from an error object.
*
* @return int error mode
* @access public
*/
function getMode() {
return $this->mode;
}
// }}}
// {{{ getCallback()
/**
* Get the callback function/method from an error object.
*
* @return mixed callback function or object/method array
* @access public
*/
function getCallback() {
return $this->callback;
}
// }}}
// {{{ getMessage()
/**
* Get the error message from an error object.
*
* @return string full error message
* @access public
*/
function getMessage()
{
return ($this->error_message_prefix . $this->message);
}
// }}}
// {{{ getCode()
/**
* Get error code from an error object
*
* @return int error code
* @access public
*/
function getCode()
{
return $this->code;
}
// }}}
// {{{ getType()
/**
* Get the name of this error/exception.
*
* @return string error/exception name (type)
* @access public
*/
function getType()
{
return get_class($this);
}
// }}}
// {{{ getUserInfo()
/**
* Get additional user-supplied information.
*
* @return string user-supplied information
* @access public
*/
function getUserInfo()
{
return $this->userinfo;
}
// }}}
// {{{ getDebugInfo()
/**
* Get additional debug information supplied by the application.
*
* @return string debug information
* @access public
*/
function getDebugInfo()
{
return $this->getUserInfo();
}
// }}}
// {{{ getBacktrace()
/**
* Get the call backtrace from where the error was generated.
* Supported with PHP 4.3.0 or newer.
*
* @param int $frame (optional) what frame to fetch
* @return array Backtrace, or NULL if not available.
* @access public
*/
function getBacktrace($frame = null)
{
if (defined('PEAR_IGNORE_BACKTRACE')) {
return null;
}
if ($frame === null) {
return $this->backtrace;
}
return $this->backtrace[$frame];
}
// }}}
// {{{ addUserInfo()
function addUserInfo($info)
{
if (empty($this->userinfo)) {
$this->userinfo = $info;
} else {
$this->userinfo .= " ** $info";
}
}
// }}}
// {{{ toString()
function __toString()
{
return $this->getMessage();
}
// }}}
// {{{ toString()
/**
* Make a string representation of this object.
*
* @return string a string with an object summary
* @access public
*/
function toString() {
$modes = array();
$levels = array(E_USER_NOTICE => 'notice',
E_USER_WARNING => 'warning',
E_USER_ERROR => 'error');
if ($this->mode & PEAR_ERROR_CALLBACK) {
if (is_array($this->callback)) {
$callback = (is_object($this->callback[0]) ?
strtolower(get_class($this->callback[0])) :
$this->callback[0]) . '::' .
$this->callback[1];
} else {
$callback = $this->callback;
}
return sprintf('[%s: message="%s" code=%d mode=callback '.
'callback=%s prefix="%s" info="%s"]',
strtolower(get_class($this)), $this->message, $this->code,
$callback, $this->error_message_prefix,
$this->userinfo);
}
if ($this->mode & PEAR_ERROR_PRINT) {
$modes[] = 'print';
}
if ($this->mode & PEAR_ERROR_TRIGGER) {
$modes[] = 'trigger';
}
if ($this->mode & PEAR_ERROR_DIE) {
$modes[] = 'die';
}
if ($this->mode & PEAR_ERROR_RETURN) {
$modes[] = 'return';
}
return sprintf('[%s: message="%s" code=%d mode=%s level=%s '.
'prefix="%s" info="%s"]',
strtolower(get_class($this)), $this->message, $this->code,
implode("|", $modes), $levels[$this->level],
$this->error_message_prefix,
$this->userinfo);
}
// }}}
}
/*
* Local Variables:
* mode: php
* tab-width: 4
* c-basic-offset: 4
* End:
*/
/**
* PEAR's Mail:: interface.
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2002-2007, Richard Heyes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* o The names of the authors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category Mail
* @package Mail
* @author Chuck Hagenbuch
* @copyright 1997-2010 Chuck Hagenbuch
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id$
* @link http://pear.php.net/package/Mail/
*/
/*PJ: require_once 'PEAR.php';*/
/**
* PEAR's Mail:: interface. Defines the interface for implementing
* mailers under the PEAR hierarchy, and provides supporting functions
* useful in multiple mailer backends.
*
* @access public
* @version $Revision: 1.3 $
* @package Mail
*/
class Mail
{
/**
* Line terminator used for separating header lines.
* @var string
*/
var $sep = "\r\n";
/**
* Provides an interface for generating Mail:: objects of various
* types
*
* @param string $driver The kind of Mail:: object to instantiate.
* @param array $params The parameters to pass to the Mail:: object.
* @return object Mail a instance of the driver class or if fails a PEAR Error
* @access public
*/
function &factory($driver, $params = array())
{
$driver = strtolower($driver);
/*PJ: @include_once 'Mail' . $driver . '.php';*/
$class = 'Mail_' . $driver;
if (class_exists($class)) {
$mailer = new $class($params);
return $mailer;
} else {
return PEAR::raiseError('Unable to find class for driver ' . $driver);
}
}
/**
* Implements Mail::send() function using php's built-in mail()
* command.
*
* @param mixed $recipients Either a comma-seperated list of recipients
* (RFC822 compliant), or an array of recipients,
* each RFC822 valid. This may contain recipients not
* specified in the headers, for Bcc:, resending
* messages, etc.
*
* @param array $headers The array of headers to send with the mail, in an
* associative array, where the array key is the
* header name (ie, 'Subject'), and the array value
* is the header value (ie, 'test'). The header
* produced from those values would be 'Subject:
* test'.
*
* @param string $body The full text of the message body, including any
* Mime parts, etc.
*
* @return mixed Returns true on success, or a PEAR_Error
* containing a descriptive error message on
* failure.
*
* @access public
* @deprecated use Mail_mail::send instead
*/
function send($recipients, $headers, $body)
{
if (!is_array($headers)) {
return PEAR::raiseError('$headers must be an array');
}
$result = $this->_sanitizeHeaders($headers);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
// if we're passed an array of recipients, implode it.
if (is_array($recipients)) {
$recipients = implode(', ', $recipients);
}
// get the Subject out of the headers array so that we can
// pass it as a seperate argument to mail().
$subject = '';
if (isset($headers['Subject'])) {
$subject = $headers['Subject'];
unset($headers['Subject']);
}
// flatten the headers out.
list(, $text_headers) = Mail::prepareHeaders($headers);
return mail($recipients, $subject, $body, $text_headers);
}
/**
* Sanitize an array of mail headers by removing any additional header
* strings present in a legitimate header's value. The goal of this
* filter is to prevent mail injection attacks.
*
* @param array $headers The associative array of headers to sanitize.
*
* @access private
*/
function _sanitizeHeaders(&$headers)
{
foreach ($headers as $key => $value) {
$headers[$key] =
preg_replace('=((||0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i',
null, $value);
}
}
/**
* Take an array of mail headers and return a string containing
* text usable in sending a message.
*
* @param array $headers The array of headers to prepare, in an associative
* array, where the array key is the header name (ie,
* 'Subject'), and the array value is the header
* value (ie, 'test'). The header produced from those
* values would be 'Subject: test'.
*
* @return mixed Returns false if it encounters a bad address,
* otherwise returns an array containing two
* elements: Any From: address found in the headers,
* and the plain text version of the headers.
* @access private
*/
function prepareHeaders($headers)
{
$lines = array();
$from = null;
foreach ($headers as $key => $value) {
if (strcasecmp($key, 'From') === 0) {
/*PJ: include_once 'Mail/RFC822.php';*/
$parser = new Mail_RFC822();
$addresses = $parser->parseAddressList($value, 'localhost', false);
if (is_a($addresses, 'PEAR_Error')) {
return $addresses;
}
$from = $addresses[0]->mailbox . '@' . $addresses[0]->host;
// Reject envelope From: addresses with spaces.
if (strstr($from, ' ')) {
return false;
}
$lines[] = $key . ': ' . $value;
} elseif (strcasecmp($key, 'Received') === 0) {
$received = array();
if (is_array($value)) {
foreach ($value as $line) {
$received[] = $key . ': ' . $line;
}
}
else {
$received[] = $key . ': ' . $value;
}
// Put Received: headers at the top. Spam detectors often
// flag messages with Received: headers after the Subject:
// as spam.
$lines = array_merge($received, $lines);
} else {
// If $value is an array (i.e., a list of addresses), convert
// it to a comma-delimited string of its elements (addresses).
if (is_array($value)) {
$value = implode(', ', $value);
}
$lines[] = $key . ': ' . $value;
}
}
return array($from, join($this->sep, $lines));
}
/**
* Take a set of recipients and parse them, returning an array of
* bare addresses (forward paths) that can be passed to sendmail
* or an smtp server with the rcpt to: command.
*
* @param mixed Either a comma-seperated list of recipients
* (RFC822 compliant), or an array of recipients,
* each RFC822 valid.
*
* @return mixed An array of forward paths (bare addresses) or a PEAR_Error
* object if the address list could not be parsed.
* @access private
*/
function parseRecipients($recipients)
{
/*PJ: include_once 'Mail/RFC822.php';*/
// if we're passed an array, assume addresses are valid and
// implode them before parsing.
if (is_array($recipients)) {
$recipients = implode(', ', $recipients);
}
// Parse recipients, leaving out all personal info. This is
// for smtp recipients, etc. All relevant personal information
// should already be in the headers.
$addresses = Mail_RFC822::parseAddressList($recipients, 'localhost', false);
// If parseAddressList() returned a PEAR_Error object, just return it.
if (is_a($addresses, 'PEAR_Error')) {
return $addresses;
}
$recipients = array();
if (is_array($addresses)) {
foreach ($addresses as $ob) {
$recipients[] = $ob->mailbox . '@' . $ob->host;
}
}
return $recipients;
}
}
/**
* RFC 822 Email address list validation Utility
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2001-2010, Richard Heyes
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* o The names of the authors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category Mail
* @package Mail
* @author Richard Heyes
* @author Chuck Hagenbuch (A comment), ted@example.com (Ted Bloggs), Barney;';
* $structure = Mail_RFC822::parseAddressList($address_string, 'example.com', true)
* print_r($structure);
*
* @author Richard Heyes
* @author Chuck Hagenbuch
* @version $Revision: 1.2 $
* @license BSD
* @package Mail
*/
class Mail_RFC822 {
/**
* The address being parsed by the RFC822 object.
* @var string $address
*/
var $address = '';
/**
* The default domain to use for unqualified addresses.
* @var string $default_domain
*/
var $default_domain = 'localhost';
/**
* Should we return a nested array showing groups, or flatten everything?
* @var boolean $nestGroups
*/
var $nestGroups = true;
/**
* Whether or not to validate atoms for non-ascii characters.
* @var boolean $validate
*/
var $validate = true;
/**
* The array of raw addresses built up as we parse.
* @var array $addresses
*/
var $addresses = array();
/**
* The final array of parsed address information that we build up.
* @var array $structure
*/
var $structure = array();
/**
* The current error message, if any.
* @var string $error
*/
var $error = null;
/**
* An internal counter/pointer.
* @var integer $index
*/
var $index = null;
/**
* The number of groups that have been found in the address list.
* @var integer $num_groups
* @access public
*/
var $num_groups = 0;
/**
* A variable so that we can tell whether or not we're inside a
* Mail_RFC822 object.
* @var boolean $mailRFC822
*/
var $mailRFC822 = true;
/**
* A limit after which processing stops
* @var int $limit
*/
var $limit = null;
/**
* Sets up the object. The address must either be set here or when
* calling parseAddressList(). One or the other.
*
* @access public
* @param string $address The address(es) to validate.
* @param string $default_domain Default domain/host etc. If not supplied, will be set to localhost.
* @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
* @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
*
* @return object Mail_RFC822 A new Mail_RFC822 object.
*/
function Mail_RFC822($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
{
if (isset($address)) $this->address = $address;
if (isset($default_domain)) $this->default_domain = $default_domain;
if (isset($nest_groups)) $this->nestGroups = $nest_groups;
if (isset($validate)) $this->validate = $validate;
if (isset($limit)) $this->limit = $limit;
}
/**
* Starts the whole process. The address must either be set here
* or when creating the object. One or the other.
*
* @access public
* @param string $address The address(es) to validate.
* @param string $default_domain Default domain/host etc.
* @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
* @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
*
* @return array A structured array of addresses.
*/
function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
{
if (!isset($this) || !isset($this->mailRFC822)) {
$obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
return $obj->parseAddressList();
}
if (isset($address)) $this->address = $address;
if (isset($default_domain)) $this->default_domain = $default_domain;
if (isset($nest_groups)) $this->nestGroups = $nest_groups;
if (isset($validate)) $this->validate = $validate;
if (isset($limit)) $this->limit = $limit;
$this->structure = array();
$this->addresses = array();
$this->error = null;
$this->index = null;
// Unfold any long lines in $this->address.
$this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
$this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
while ($this->address = $this->_splitAddresses($this->address));
if ($this->address === false || isset($this->error)) {
/*PJ: require_once 'PEAR.php';*/
return PEAR::raiseError($this->error);
}
// Validate each address individually. If we encounter an invalid
// address, stop iterating and return an error immediately.
foreach ($this->addresses as $address) {
$valid = $this->_validateAddress($address);
if ($valid === false || isset($this->error)) {
/*PJ: require_once 'PEAR.php';*/
return PEAR::raiseError($this->error);
}
if (!$this->nestGroups) {
$this->structure = array_merge($this->structure, $valid);
} else {
$this->structure[] = $valid;
}
}
return $this->structure;
}
/**
* Splits an address into separate addresses.
*
* @access private
* @param string $address The addresses to split.
* @return boolean Success or failure.
*/
function _splitAddresses($address)
{
if (!empty($this->limit) && count($this->addresses) == $this->limit) {
return '';
}
if ($this->_isGroup($address) && !isset($this->error)) {
$split_char = ';';
$is_group = true;
} elseif (!isset($this->error)) {
$split_char = ',';
$is_group = false;
} elseif (isset($this->error)) {
return false;
}
// Split the string based on the above ten or so lines.
$parts = explode($split_char, $address);
$string = $this->_splitCheck($parts, $split_char);
// If a group...
if ($is_group) {
// If $string does not contain a colon outside of
// brackets/quotes etc then something's fubar.
// First check there's a colon at all:
if (strpos($string, ':') === false) {
$this->error = 'Invalid address: ' . $string;
return false;
}
// Now check it's outside of brackets/quotes:
if (!$this->_splitCheck(explode(':', $string), ':')) {
return false;
}
// We must have a group at this point, so increase the counter:
$this->num_groups++;
}
// $string now contains the first full address/group.
// Add to the addresses array.
$this->addresses[] = array(
'address' => trim($string),
'group' => $is_group
);
// Remove the now stored address from the initial line, the +1
// is to account for the explode character.
$address = trim(substr($address, strlen($string) + 1));
// If the next char is a comma and this was a group, then
// there are more addresses, otherwise, if there are any more
// chars, then there is another address.
if ($is_group && substr($address, 0, 1) == ','){
$address = trim(substr($address, 1));
return $address;
} elseif (strlen($address) > 0) {
return $address;
} else {
return '';
}
// If you got here then something's off
return false;
}
/**
* Checks for a group at the start of the string.
*
* @access private
* @param string $address The address to check.
* @return boolean Whether or not there is a group at the start of the string.
*/
function _isGroup($address)
{
// First comma not in quotes, angles or escaped:
$parts = explode(',', $address);
$string = $this->_splitCheck($parts, ',');
// Now we have the first address, we can reliably check for a
// group by searching for a colon that's not escaped or in
// quotes or angle brackets.
if (count($parts = explode(':', $string)) > 1) {
$string2 = $this->_splitCheck($parts, ':');
return ($string2 !== $string);
} else {
return false;
}
}
/**
* A common function that will check an exploded string.
*
* @access private
* @param array $parts The exloded string.
* @param string $char The char that was exploded on.
* @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
*/
function _splitCheck($parts, $char)
{
$string = $parts[0];
for ($i = 0; $i < count($parts); $i++) {
if ($this->_hasUnclosedQuotes($string)
|| $this->_hasUnclosedBrackets($string, '<>')
|| $this->_hasUnclosedBrackets($string, '[]')
|| $this->_hasUnclosedBrackets($string, '()')
|| substr($string, -1) == '\\') {
if (isset($parts[$i + 1])) {
$string = $string . $char . $parts[$i + 1];
} else {
$this->error = 'Invalid address spec. Unclosed bracket or quotes';
return false;
}
} else {
$this->index = $i;
break;
}
}
return $string;
}
/**
* Checks if a string has unclosed quotes or not.
*
* @access private
* @param string $string The string to check.
* @return boolean True if there are unclosed quotes inside the string,
* false otherwise.
*/
function _hasUnclosedQuotes($string)
{
$string = trim($string);
$iMax = strlen($string);
$in_quote = false;
$i = $slashes = 0;
for (; $i < $iMax; ++$i) {
switch ($string[$i]) {
case '\\':
++$slashes;
break;
case '"':
if ($slashes % 2 == 0) {
$in_quote = !$in_quote;
}
// Fall through to default action below.
default:
$slashes = 0;
break;
}
}
return $in_quote;
}
/**
* Checks if a string has an unclosed brackets or not. IMPORTANT:
* This function handles both angle brackets and square brackets;
*
* @access private
* @param string $string The string to check.
* @param string $chars The characters to check for.
* @return boolean True if there are unclosed brackets inside the string, false otherwise.
*/
function _hasUnclosedBrackets($string, $chars)
{
$num_angle_start = substr_count($string, $chars[0]);
$num_angle_end = substr_count($string, $chars[1]);
$this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
$this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
if ($num_angle_start < $num_angle_end) {
$this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
return false;
} else {
return ($num_angle_start > $num_angle_end);
}
}
/**
* Sub function that is used only by hasUnclosedBrackets().
*
* @access private
* @param string $string The string to check.
* @param integer &$num The number of occurences.
* @param string $char The character to count.
* @return integer The number of occurences of $char in $string, adjusted for backslashes.
*/
function _hasUnclosedBracketsSub($string, &$num, $char)
{
$parts = explode($char, $string);
for ($i = 0; $i < count($parts); $i++){
if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
$num--;
if (isset($parts[$i + 1]))
$parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
}
return $num;
}
/**
* Function to begin checking the address.
*
* @access private
* @param string $address The address to validate.
* @return mixed False on failure, or a structured array of address information on success.
*/
function _validateAddress($address)
{
$is_group = false;
$addresses = array();
if ($address['group']) {
$is_group = true;
// Get the group part of the name
$parts = explode(':', $address['address']);
$groupname = $this->_splitCheck($parts, ':');
$structure = array();
// And validate the group part of the name.
if (!$this->_validatePhrase($groupname)){
$this->error = 'Group name did not validate.';
return false;
} else {
// Don't include groups if we are not nesting
// them. This avoids returning invalid addresses.
if ($this->nestGroups) {
$structure = new stdClass;
$structure->groupname = $groupname;
}
}
$address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
}
// If a group then split on comma and put into an array.
// Otherwise, Just put the whole address in an array.
if ($is_group) {
while (strlen($address['address']) > 0) {
$parts = explode(',', $address['address']);
$addresses[] = $this->_splitCheck($parts, ',');
$address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
}
} else {
$addresses[] = $address['address'];
}
// Check that $addresses is set, if address like this:
// Groupname:;
// Then errors were appearing.
if (!count($addresses)){
$this->error = 'Empty group.';
return false;
}
// Trim the whitespace from all of the address strings.
array_map('trim', $addresses);
// Validate each mailbox.
// Format could be one of: name
// geezer@domain.com
// geezer
// ... or any other format valid by RFC 822.
for ($i = 0; $i < count($addresses); $i++) {
if (!$this->validateMailbox($addresses[$i])) {
if (empty($this->error)) {
$this->error = 'Validation failed for: ' . $addresses[$i];
}
return false;
}
}
// Nested format
if ($this->nestGroups) {
if ($is_group) {
$structure->addresses = $addresses;
} else {
$structure = $addresses[0];
}
// Flat format
} else {
if ($is_group) {
$structure = array_merge($structure, $addresses);
} else {
$structure = $addresses;
}
}
return $structure;
}
/**
* Function to validate a phrase.
*
* @access private
* @param string $phrase The phrase to check.
* @return boolean Success or failure.
*/
function _validatePhrase($phrase)
{
// Splits on one or more Tab or space.
$parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
$phrase_parts = array();
while (count($parts) > 0){
$phrase_parts[] = $this->_splitCheck($parts, ' ');
for ($i = 0; $i < $this->index + 1; $i++)
array_shift($parts);
}
foreach ($phrase_parts as $part) {
// If quoted string:
if (substr($part, 0, 1) == '"') {
if (!$this->_validateQuotedString($part)) {
return false;
}
continue;
}
// Otherwise it's an atom:
if (!$this->_validateAtom($part)) return false;
}
return true;
}
/**
* Function to validate an atom which from rfc822 is:
* atom = 1*
*
* If validation ($this->validate) has been turned off, then
* validateAtom() doesn't actually check anything. This is so that you
* can split a list of addresses up before encoding personal names
* (umlauts, etc.), for example.
*
* @access private
* @param string $atom The string to check.
* @return boolean Success or failure.
*/
function _validateAtom($atom)
{
if (!$this->validate) {
// Validation has been turned off; assume the atom is okay.
return true;
}
// Check for any char from ASCII 0 - ASCII 127
if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
return false;
}
// Check for specials:
if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
return false;
}
// Check for control characters (ASCII 0-31):
if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
return false;
}
return true;
}
/**
* Function to validate quoted string, which is:
* quoted-string = <"> *(qtext/quoted-pair) <">
*
* @access private
* @param string $qstring The string to check
* @return boolean Success or failure.
*/
function _validateQuotedString($qstring)
{
// Leading and trailing "
$qstring = substr($qstring, 1, -1);
// Perform check, removing quoted characters first.
return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
}
/**
* Function to validate a mailbox, which is:
* mailbox = addr-spec ; simple address
* / phrase route-addr ; name and route-addr
*
* @access public
* @param string &$mailbox The string to check.
* @return boolean Success or failure.
*/
function validateMailbox(&$mailbox)
{
// A couple of defaults.
$phrase = '';
$comment = '';
$comments = array();
// Catch any RFC822 comments and store them separately.
$_mailbox = $mailbox;
while (strlen(trim($_mailbox)) > 0) {
$parts = explode('(', $_mailbox);
$before_comment = $this->_splitCheck($parts, '(');
if ($before_comment != $_mailbox) {
// First char should be a (.
$comment = substr(str_replace($before_comment, '', $_mailbox), 1);
$parts = explode(')', $comment);
$comment = $this->_splitCheck($parts, ')');
$comments[] = $comment;
// +2 is for the brackets
$_mailbox = substr($_mailbox, strpos($_mailbox, '('.$comment)+strlen($comment)+2);
} else {
break;
}
}
foreach ($comments as $comment) {
$mailbox = str_replace("($comment)", '', $mailbox);
}
$mailbox = trim($mailbox);
// Check for name + route-addr
if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
$parts = explode('<', $mailbox);
$name = $this->_splitCheck($parts, '<');
$phrase = trim($name);
$route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
return false;
}
// Only got addr-spec
} else {
// First snip angle brackets if present.
if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
$addr_spec = substr($mailbox, 1, -1);
} else {
$addr_spec = $mailbox;
}
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
}
// Construct the object that will be returned.
$mbox = new stdClass();
// Add the phrase (even if empty) and comments
$mbox->personal = $phrase;
$mbox->comment = isset($comments) ? $comments : array();
if (isset($route_addr)) {
$mbox->mailbox = $route_addr['local_part'];
$mbox->host = $route_addr['domain'];
$route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
} else {
$mbox->mailbox = $addr_spec['local_part'];
$mbox->host = $addr_spec['domain'];
}
$mailbox = $mbox;
return true;
}
/**
* This function validates a route-addr which is:
* route-addr = "<" [route] addr-spec ">"
*
* Angle brackets have already been removed at the point of
* getting to this function.
*
* @access private
* @param string $route_addr The string to check.
* @return mixed False on failure, or an array containing validated address/route information on success.
*/
function _validateRouteAddr($route_addr)
{
// Check for colon.
if (strpos($route_addr, ':') !== false) {
$parts = explode(':', $route_addr);
$route = $this->_splitCheck($parts, ':');
} else {
$route = $route_addr;
}
// If $route is same as $route_addr then the colon was in
// quotes or brackets or, of course, non existent.
if ($route === $route_addr){
unset($route);
$addr_spec = $route_addr;
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
} else {
// Validate route part.
if (($route = $this->_validateRoute($route)) === false) {
return false;
}
$addr_spec = substr($route_addr, strlen($route . ':'));
// Validate addr-spec part.
if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
return false;
}
}
if (isset($route)) {
$return['adl'] = $route;
} else {
$return['adl'] = '';
}
$return = array_merge($return, $addr_spec);
return $return;
}
/**
* Function to validate a route, which is:
* route = 1#("@" domain) ":"
*
* @access private
* @param string $route The string to check.
* @return mixed False on failure, or the validated $route on success.
*/
function _validateRoute($route)
{
// Split on comma.
$domains = explode(',', trim($route));
foreach ($domains as $domain) {
$domain = str_replace('@', '', trim($domain));
if (!$this->_validateDomain($domain)) return false;
}
return $route;
}
/**
* Function to validate a domain, though this is not quite what
* you expect of a strict internet domain.
*
* domain = sub-domain *("." sub-domain)
*
* @access private
* @param string $domain The string to check.
* @return mixed False on failure, or the validated domain on success.
*/
function _validateDomain($domain)
{
// Note the different use of $subdomains and $sub_domains
$subdomains = explode('.', $domain);
while (count($subdomains) > 0) {
$sub_domains[] = $this->_splitCheck($subdomains, '.');
for ($i = 0; $i < $this->index + 1; $i++)
array_shift($subdomains);
}
foreach ($sub_domains as $sub_domain) {
if (!$this->_validateSubdomain(trim($sub_domain)))
return false;
}
// Managed to get here, so return input.
return $domain;
}
/**
* Function to validate a subdomain:
* subdomain = domain-ref / domain-literal
*
* @access private
* @param string $subdomain The string to check.
* @return boolean Success or failure.
*/
function _validateSubdomain($subdomain)
{
if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
if (!$this->_validateDliteral($arr[1])) return false;
} else {
if (!$this->_validateAtom($subdomain)) return false;
}
// Got here, so return successful.
return true;
}
/**
* Function to validate a domain literal:
* domain-literal = "[" *(dtext / quoted-pair) "]"
*
* @access private
* @param string $dliteral The string to check.
* @return boolean Success or failure.
*/
function _validateDliteral($dliteral)
{
return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
}
/**
* Function to validate an addr-spec.
*
* addr-spec = local-part "@" domain
*
* @access private
* @param string $addr_spec The string to check.
* @return mixed False on failure, or the validated addr-spec on success.
*/
function _validateAddrSpec($addr_spec)
{
$addr_spec = trim($addr_spec);
// Split on @ sign if there is one.
if (strpos($addr_spec, '@') !== false) {
$parts = explode('@', $addr_spec);
$local_part = $this->_splitCheck($parts, '@');
$domain = substr($addr_spec, strlen($local_part . '@'));
// No @ sign so assume the default domain.
} else {
$local_part = $addr_spec;
$domain = $this->default_domain;
}
if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
if (($domain = $this->_validateDomain($domain)) === false) return false;
// Got here so return successful.
return array('local_part' => $local_part, 'domain' => $domain);
}
/**
* Function to validate the local part of an address:
* local-part = word *("." word)
*
* @access private
* @param string $local_part
* @return mixed False on failure, or the validated local part on success.
*/
function _validateLocalPart($local_part)
{
$parts = explode('.', $local_part);
$words = array();
// Split the local_part into words.
while (count($parts) > 0){
$words[] = $this->_splitCheck($parts, '.');
for ($i = 0; $i < $this->index + 1; $i++) {
array_shift($parts);
}
}
// Validate each word.
foreach ($words as $word) {
// If this word contains an unquoted space, it is invalid. (6.2.4)
if (strpos($word, ' ') && $word[0] !== '"')
{
return false;
}
if ($this->_validatePhrase(trim($word)) === false) return false;
}
// Managed to get here, so return the input.
return $local_part;
}
/**
* Returns an approximate count of how many addresses are in the
* given string. This is APPROXIMATE as it only splits based on a
* comma which has no preceding backslash. Could be useful as
* large amounts of addresses will end up producing *large*
* structures when used with parseAddressList().
*
* @param string $data Addresses to count
* @return int Approximate count
*/
function approximateCount($data)
{
return count(preg_split('/(?@. This can be sufficient for most
* people. Optional stricter mode can be utilised which restricts
* mailbox characters allowed to alphanumeric, full stop, hyphen
* and underscore.
*
* @param string $data Address to check
* @param boolean $strict Optional stricter mode
* @return mixed False if it fails, an indexed array
* username/domain if it matches
*/
function isValidInetAddress($data, $strict = false)
{
$regex = $strict ? '/^([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i' : '/^([*+!.$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})$/i';
if (preg_match($regex, trim($data), $matches)) {
return array($matches[1], $matches[2]);
} else {
return false;
}
}
}
/**
* The Mail_Mime class is used to create MIME E-mail messages
*
* The Mail_Mime class provides an OO interface to create MIME
* enabled email messages. This way you can create emails that
* contain plain-text bodies, HTML bodies, attachments, inline
* images and specific headers.
*
* Compatible with PHP versions 4 and 5
*
* LICENSE: This LICENSE is in the BSD license style.
* Copyright (c) 2002-2003, Richard Heyes
* Copyright (c) 2003-2006, PEAR
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the authors, nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* @category Mail
* @package Mail_Mime
* @author Richard Heyes
* @author Tomas V.V. Cox
* @author Cipriano Groenendal
* @author Sean Coates
* @author Aleksander Machniak
* @copyright 2003-2006 PEAR
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version CVS: $Id$
* @link http://pear.php.net/package/Mail_mime
*
* This class is based on HTML Mime Mail class from
* Richard Heyes which was based also
* in the mime_mail.class by Tobias Ratschiller
* and Sascha Schumann
*/
/**
* require PEAR
*
* This package depends on PEAR to raise errors.
*/
/*PJ: require_once 'PEAR.php';*/
/**
* require Mail_mimePart
*
* Mail_mimePart contains the code required to
* create all the different parts a mail can
* consist of.
*/
/*PJ: require_once 'Mail/mimePart.php';*/
/**
* The Mail_Mime class provides an OO interface to create MIME
* enabled email messages. This way you can create emails that
* contain plain-text bodies, HTML bodies, attachments, inline
* images and specific headers.
*
* @category Mail
* @package Mail_Mime
* @author Richard Heyes
* @author Tomas V.V. Cox
* @author Cipriano Groenendal
* @author Sean Coates
* @copyright 2003-2006 PEAR
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: @package_version@
* @link http://pear.php.net/package/Mail_mime
*/
class Mail_mime
{
/**
* Contains the plain text part of the email
*
* @var string
* @access private
*/
var $_txtbody;
/**
* Contains the html part of the email
*
* @var string
* @access private
*/
var $_htmlbody;
/**
* list of the attached images
*
* @var array
* @access private
*/
var $_html_images = array();
/**
* list of the attachements
*
* @var array
* @access private
*/
var $_parts = array();
/**
* Headers for the mail
*
* @var array
* @access private
*/
var $_headers = array();
/**
* Build parameters
*
* @var array
* @access private
*/
var $_build_params = array(
// What encoding to use for the headers
// Options: quoted-printable or base64
'head_encoding' => 'quoted-printable',
// What encoding to use for plain text
// Options: 7bit, 8bit, base64, or quoted-printable
'text_encoding' => 'quoted-printable',
// What encoding to use for html
// Options: 7bit, 8bit, base64, or quoted-printable
'html_encoding' => 'quoted-printable',
// The character set to use for html
'html_charset' => 'ISO-8859-1',
// The character set to use for text
'text_charset' => 'ISO-8859-1',
// The character set to use for headers
'head_charset' => 'ISO-8859-1',
// End-of-line sequence
'eol' => "\r\n",
// Delay attachment files IO until building the message
'delay_file_io' => false
);
/**
* Constructor function
*
* @param mixed $params Build parameters that change the way the email
* is built. Should be an associative array.
* See $_build_params.
*
* @return void
* @access public
*/
function Mail_mime($params = array())
{
// Backward-compatible EOL setting
if (is_string($params)) {
$this->_build_params['eol'] = $params;
} else if (defined('MAIL_MIME_CRLF') && !isset($params['eol'])) {
$this->_build_params['eol'] = MAIL_MIME_CRLF;
}
// Update build parameters
if (!empty($params) && is_array($params)) {
while (list($key, $value) = each($params)) {
$this->_build_params[$key] = $value;
}
}
}
/**
* Set build parameter value
*
* @param string $name Parameter name
* @param string $value Parameter value
*
* @return void
* @access public
* @since 1.6.0
*/
function setParam($name, $value)
{
$this->_build_params[$name] = $value;
}
/**
* Get build parameter value
*
* @param string $name Parameter name
*
* @return mixed Parameter value
* @access public
* @since 1.6.0
*/
function getParam($name)
{
return isset($this->_build_params[$name]) ? $this->_build_params[$name] : null;
}
/**
* Accessor function to set the body text. Body text is used if
* it's not an html mail being sent or else is used to fill the
* text/plain part that emails clients who don't support
* html should show.
*
* @param string $data Either a string or
* the file name with the contents
* @param bool $isfile If true the first param should be treated
* as a file name, else as a string (default)
* @param bool $append If true the text or file is appended to
* the existing body, else the old body is
* overwritten
*
* @return mixed True on success or PEAR_Error object
* @access public
*/
function setTXTBody($data, $isfile = false, $append = false)
{
if (!$isfile) {
if (!$append) {
$this->_txtbody = $data;
} else {
$this->_txtbody .= $data;
}
} else {
$cont = $this->_file2str($data);
if (PEAR::isError($cont)) {
return $cont;
}
if (!$append) {
$this->_txtbody = $cont;
} else {
$this->_txtbody .= $cont;
}
}
return true;
}
/**
* Get message text body
*
* @return string Text body
* @access public
* @since 1.6.0
*/
function getTXTBody()
{
return $this->_txtbody;
}
/**
* Adds a html part to the mail.
*
* @param string $data Either a string or the file name with the
* contents
* @param bool $isfile A flag that determines whether $data is a
* filename, or a string(false, default)
*
* @return bool True on success
* @access public
*/
function setHTMLBody($data, $isfile = false)
{
if (!$isfile) {
$this->_htmlbody = $data;
} else {
$cont = $this->_file2str($data);
if (PEAR::isError($cont)) {
return $cont;
}
$this->_htmlbody = $cont;
}
return true;
}
/**
* Get message HTML body
*
* @return string HTML body
* @access public
* @since 1.6.0
*/
function getHTMLBody()
{
return $this->_htmlbody;
}
/**
* Adds an image to the list of embedded images.
*
* @param string $file The image file name OR image data itself
* @param string $c_type The content type
* @param string $name The filename of the image.
* Only used if $file is the image data.
* @param bool $isfile Whether $file is a filename or not.
* Defaults to true
* @param string $content_id Desired Content-ID of MIME part
* Defaults to generated unique ID
*
* @return bool True on success
* @access public
*/
function addHTMLImage($file,
$c_type='application/octet-stream',
$name = '',
$isfile = true,
$content_id = null
) {
$bodyfile = null;
if ($isfile) {
// Don't load file into memory
if ($this->_build_params['delay_file_io']) {
$filedata = null;
$bodyfile = $file;
} else {
if (PEAR::isError($filedata = $this->_file2str($file))) {
return $filedata;
}
}
$filename = ($name ? $name : $file);
} else {
$filedata = $file;
$filename = $name;
}
if (!$content_id) {
$content_id = md5(uniqid(time()));
}
$this->_html_images[] = array(
'body' => $filedata,
'body_file' => $bodyfile,
'name' => $filename,
'c_type' => $c_type,
'cid' => $content_id
);
return true;
}
/**
* Adds a file to the list of attachments.
*
* @param string $file The file name of the file to attach
* OR the file contents itself
* @param string $c_type The content type
* @param string $name The filename of the attachment
* Only use if $file is the contents
* @param bool $isfile Whether $file is a filename or not
* Defaults to true
* @param string $encoding The type of encoding to use.
* Defaults to base64.
* Possible values: 7bit, 8bit, base64,
* or quoted-printable.
* @param string $disposition The content-disposition of this file
* Defaults to attachment.
* Possible values: attachment, inline.
* @param string $charset The character set used in the filename
* of this attachment.
* @param string $language The language of the attachment
* @param string $location The RFC 2557.4 location of the attachment
* @param string $n_encoding Encoding for attachment name (Content-Type)
* By default filenames are encoded using RFC2231 method
* Here you can set RFC2047 encoding (quoted-printable
* or base64) instead
* @param string $f_encoding Encoding for attachment filename (Content-Disposition)
* See $n_encoding description
* @param string $description Content-Description header
*
* @return mixed True on success or PEAR_Error object
* @access public
*/
function addAttachment($file,
$c_type = 'application/octet-stream',
$name = '',
$isfile = true,
$encoding = 'base64',
$disposition = 'attachment',
$charset = '',
$language = '',
$location = '',
$n_encoding = null,
$f_encoding = null,
$description = ''
) {
$bodyfile = null;
if ($isfile) {
// Don't load file into memory
if ($this->_build_params['delay_file_io']) {
$filedata = null;
$bodyfile = $file;
} else {
if (PEAR::isError($filedata = $this->_file2str($file))) {
return $filedata;
}
}
// Force the name the user supplied, otherwise use $file
$filename = ($name ? $name : $file);
} else {
$filedata = $file;
$filename = $name;
}
if (!strlen($filename)) {
$msg = "The supplied filename for the attachment can't be empty";
$err = PEAR::raiseError($msg);
return $err;
}
$filename = $this->_basename($filename);
$this->_parts[] = array(
'body' => $filedata,
'body_file' => $bodyfile,
'name' => $filename,
'c_type' => $c_type,
'encoding' => $encoding,
'charset' => $charset,
'language' => $language,
'location' => $location,
'disposition' => $disposition,
'description' => $description,
'name_encoding' => $n_encoding,
'filename_encoding' => $f_encoding
);
return true;
}
/**
* Get the contents of the given file name as string
*
* @param string $file_name Path of file to process
*
* @return string Contents of $file_name
* @access private
*/
function &_file2str($file_name)
{
// Check state of file and raise an error properly
if (!file_exists($file_name)) {
$err = PEAR::raiseError('File not found: ' . $file_name);
return $err;
}
if (!is_file($file_name)) {
$err = PEAR::raiseError('Not a regular file: ' . $file_name);
return $err;
}
if (!is_readable($file_name)) {
$err = PEAR::raiseError('File is not readable: ' . $file_name);
return $err;
}
// Temporarily reset magic_quotes_runtime and read file contents
if ($magic_quote_setting = get_magic_quotes_runtime()) {
@ini_set('magic_quotes_runtime', 0);
}
$cont = file_get_contents($file_name);
if ($magic_quote_setting) {
@ini_set('magic_quotes_runtime', $magic_quote_setting);
}
return $cont;
}
/**
* Adds a text subpart to the mimePart object and
* returns it during the build process.
*
* @param mixed &$obj The object to add the part to, or
* null if a new object is to be created.
* @param string $text The text to add.
*
* @return object The text mimePart object
* @access private
*/
function &_addTextPart(&$obj, $text)
{
$params['content_type'] = 'text/plain';
$params['encoding'] = $this->_build_params['text_encoding'];
$params['charset'] = $this->_build_params['text_charset'];
$params['eol'] = $this->_build_params['eol'];
if (is_object($obj)) {
$ret = $obj->addSubpart($text, $params);
return $ret;
} else {
$ret = new Mail_mimePart($text, $params);
return $ret;
}
}
/**
* Adds a html subpart to the mimePart object and
* returns it during the build process.
*
* @param mixed &$obj The object to add the part to, or
* null if a new object is to be created.
*
* @return object The html mimePart object
* @access private
*/
function &_addHtmlPart(&$obj)
{
$params['content_type'] = 'text/html';
$params['encoding'] = $this->_build_params['html_encoding'];
$params['charset'] = $this->_build_params['html_charset'];
$params['eol'] = $this->_build_params['eol'];
if (is_object($obj)) {
$ret = $obj->addSubpart($this->_htmlbody, $params);
return $ret;
} else {
$ret = new Mail_mimePart($this->_htmlbody, $params);
return $ret;
}
}
/**
* Creates a new mimePart object, using multipart/mixed as
* the initial content-type and returns it during the
* build process.
*
* @return object The multipart/mixed mimePart object
* @access private
*/
function &_addMixedPart()
{
$params = array();
$params['content_type'] = 'multipart/mixed';
$params['eol'] = $this->_build_params['eol'];
// Create empty multipart/mixed Mail_mimePart object to return
$ret = new Mail_mimePart('', $params);
return $ret;
}
/**
* Adds a multipart/alternative part to a mimePart
* object (or creates one), and returns it during
* the build process.
*
* @param mixed &$obj The object to add the part to, or
* null if a new object is to be created.
*
* @return object The multipart/mixed mimePart object
* @access private
*/
function &_addAlternativePart(&$obj)
{
$params['content_type'] = 'multipart/alternative';
$params['eol'] = $this->_build_params['eol'];
if (is_object($obj)) {
return $obj->addSubpart('', $params);
} else {
$ret = new Mail_mimePart('', $params);
return $ret;
}
}
/**
* Adds a multipart/related part to a mimePart
* object (or creates one), and returns it during
* the build process.
*
* @param mixed &$obj The object to add the part to, or
* null if a new object is to be created
*
* @return object The multipart/mixed mimePart object
* @access private
*/
function &_addRelatedPart(&$obj)
{
$params['content_type'] = 'multipart/related';
$params['eol'] = $this->_build_params['eol'];
if (is_object($obj)) {
return $obj->addSubpart('', $params);
} else {
$ret = new Mail_mimePart('', $params);
return $ret;
}
}
/**
* Adds an html image subpart to a mimePart object
* and returns it during the build process.
*
* @param object &$obj The mimePart to add the image to
* @param array $value The image information
*
* @return object The image mimePart object
* @access private
*/
function &_addHtmlImagePart(&$obj, $value)
{
$params['content_type'] = $value['c_type'];
$params['encoding'] = 'base64';
$params['disposition'] = 'inline';
$params['dfilename'] = $value['name'];
$params['cid'] = $value['cid'];
$params['body_file'] = $value['body_file'];
$params['eol'] = $this->_build_params['eol'];
if (!empty($value['name_encoding'])) {
$params['name_encoding'] = $value['name_encoding'];
}
if (!empty($value['filename_encoding'])) {
$params['filename_encoding'] = $value['filename_encoding'];
}
$ret = $obj->addSubpart($value['body'], $params);
return $ret;
}
/**
* Adds an attachment subpart to a mimePart object
* and returns it during the build process.
*
* @param object &$obj The mimePart to add the image to
* @param array $value The attachment information
*
* @return object The image mimePart object
* @access private
*/
function &_addAttachmentPart(&$obj, $value)
{
$params['eol'] = $this->_build_params['eol'];
$params['dfilename'] = $value['name'];
$params['encoding'] = $value['encoding'];
$params['content_type'] = $value['c_type'];
$params['body_file'] = $value['body_file'];
$params['disposition'] = isset($value['disposition']) ?
$value['disposition'] : 'attachment';
if ($value['charset']) {
$params['charset'] = $value['charset'];
}
if ($value['language']) {
$params['language'] = $value['language'];
}
if ($value['location']) {
$params['location'] = $value['location'];
}
if (!empty($value['name_encoding'])) {
$params['name_encoding'] = $value['name_encoding'];
}
if (!empty($value['filename_encoding'])) {
$params['filename_encoding'] = $value['filename_encoding'];
}
if (!empty($value['description'])) {
$params['description'] = $value['description'];
}
$ret = $obj->addSubpart($value['body'], $params);
return $ret;
}
/**
* Returns the complete e-mail, ready to send using an alternative
* mail delivery method. Note that only the mailpart that is made
* with Mail_Mime is created. This means that,
* YOU WILL HAVE NO TO: HEADERS UNLESS YOU SET IT YOURSELF
* using the $headers parameter!
*
* @param string $separation The separation between these two parts.
* @param array $params The Build parameters passed to the
* &get() function. See &get for more info.
* @param array $headers The extra headers that should be passed
* to the &headers() function.
* See that function for more info.
* @param bool $overwrite Overwrite the existing headers with new.
*
* @return mixed The complete e-mail or PEAR error object
* @access public
*/
function getMessage($separation = null, $params = null, $headers = null,
$overwrite = false
) {
if ($separation === null) {
$separation = $this->_build_params['eol'];
}
$body = $this->get($params);
if (PEAR::isError($body)) {
return $body;
}
$head = $this->txtHeaders($headers, $overwrite);
$mail = $head . $separation . $body;
return $mail;
}
/**
* Returns the complete e-mail body, ready to send using an alternative
* mail delivery method.
*
* @param array $params The Build parameters passed to the
* &get() function. See &get for more info.
*
* @return mixed The e-mail body or PEAR error object
* @access public
* @since 1.6.0
*/
function getMessageBody($params = null)
{
return $this->get($params, null, true);
}
/**
* Writes (appends) the complete e-mail into file.
*
* @param string $filename Output file location
* @param array $params The Build parameters passed to the
* &get() function. See &get for more info.
* @param array $headers The extra headers that should be passed
* to the &headers() function.
* See that function for more info.
* @param bool $overwrite Overwrite the existing headers with new.
*
* @return mixed True or PEAR error object
* @access public
* @since 1.6.0
*/
function saveMessage($filename, $params = null, $headers = null, $overwrite = false)
{
// Check state of file and raise an error properly
if (file_exists($filename) && !is_writable($filename)) {
$err = PEAR::raiseError('File is not writable: ' . $filename);
return $err;
}
// Temporarily reset magic_quotes_runtime and read file contents
if ($magic_quote_setting = get_magic_quotes_runtime()) {
@ini_set('magic_quotes_runtime', 0);
}
if (!($fh = fopen($filename, 'ab'))) {
$err = PEAR::raiseError('Unable to open file: ' . $filename);
return $err;
}
// Write message headers into file (skipping Content-* headers)
$head = $this->txtHeaders($headers, $overwrite, true);
if (fwrite($fh, $head) === false) {
$err = PEAR::raiseError('Error writing to file: ' . $filename);
return $err;
}
fclose($fh);
if ($magic_quote_setting) {
@ini_set('magic_quotes_runtime', $magic_quote_setting);
}
// Write the rest of the message into file
$res = $this->get($params, $filename);
return $res ? $res : true;
}
/**
* Writes (appends) the complete e-mail body into file.
*
* @param string $filename Output file location
* @param array $params The Build parameters passed to the
* &get() function. See &get for more info.
*
* @return mixed True or PEAR error object
* @access public
* @since 1.6.0
*/
function saveMessageBody($filename, $params = null)
{
// Check state of file and raise an error properly
if (file_exists($filename) && !is_writable($filename)) {
$err = PEAR::raiseError('File is not writable: ' . $filename);
return $err;
}
// Temporarily reset magic_quotes_runtime and read file contents
if ($magic_quote_setting = get_magic_quotes_runtime()) {
@ini_set('magic_quotes_runtime', 0);
}
if (!($fh = fopen($filename, 'ab'))) {
$err = PEAR::raiseError('Unable to open file: ' . $filename);
return $err;
}
// Write the rest of the message into file
$res = $this->get($params, $filename, true);
return $res ? $res : true;
}
/**
* Builds the multipart message from the list ($this->_parts) and
* returns the mime content.
*
* @param array $params Build parameters that change the way the email
* is built. Should be associative. See $_build_params.
* @param resource $filename Output file where to save the message instead of
* returning it
* @param boolean $skip_head True if you want to return/save only the message
* without headers
*
* @return mixed The MIME message content string, null or PEAR error object
* @access public
*/
function &get($params = null, $filename = null, $skip_head = false)
{
if (isset($params)) {
while (list($key, $value) = each($params)) {
$this->_build_params[$key] = $value;
}
}
if (isset($this->_headers['From'])) {
// Bug #11381: Illegal characters in domain ID
if (preg_match("|(@[0-9a-zA-Z\-\.]+)|", $this->_headers['From'], $matches)) {
$domainID = $matches[1];
} else {
$domainID = "@localhost";
}
foreach ($this->_html_images as $i => $img) {
$this->_html_images[$i]['cid']
= $this->_html_images[$i]['cid'] . $domainID;
}
}
if (count($this->_html_images) && isset($this->_htmlbody)) {
foreach ($this->_html_images as $key => $value) {
$regex = array();
$regex[] = '#(\s)((?i)src|background|href(?-i))\s*=\s*(["\']?)' .
preg_quote($value['name'], '#') . '\3#';
$regex[] = '#(?i)url(?-i)\(\s*(["\']?)' .
preg_quote($value['name'], '#') . '\1\s*\)#';
$rep = array();
$rep[] = '\1\2=\3cid:' . $value['cid'] .'\3';
$rep[] = 'url(\1cid:' . $value['cid'] . '\1)';
$this->_htmlbody = preg_replace($regex, $rep, $this->_htmlbody);
$this->_html_images[$key]['name']
= $this->_basename($this->_html_images[$key]['name']);
}
}
$this->_checkParams();
$null = null;
$attachments = count($this->_parts) ? true : false;
$html_images = count($this->_html_images) ? true : false;
$html = strlen($this->_htmlbody) ? true : false;
$text = (!$html && strlen($this->_txtbody)) ? true : false;
switch (true) {
case $text && !$attachments:
$message =& $this->_addTextPart($null, $this->_txtbody);
break;
case !$text && !$html && $attachments:
$message =& $this->_addMixedPart();
for ($i = 0; $i < count($this->_parts); $i++) {
$this->_addAttachmentPart($message, $this->_parts[$i]);
}
break;
case $text && $attachments:
$message =& $this->_addMixedPart();
$this->_addTextPart($message, $this->_txtbody);
for ($i = 0; $i < count($this->_parts); $i++) {
$this->_addAttachmentPart($message, $this->_parts[$i]);
}
break;
case $html && !$attachments && !$html_images:
if (isset($this->_txtbody)) {
$message =& $this->_addAlternativePart($null);
$this->_addTextPart($message, $this->_txtbody);
$this->_addHtmlPart($message);
} else {
$message =& $this->_addHtmlPart($null);
}
break;
case $html && !$attachments && $html_images:
// * Content-Type: multipart/alternative;
// * text
// * Content-Type: multipart/related;
// * html
// * image...
if (isset($this->_txtbody)) {
$message =& $this->_addAlternativePart($null);
$this->_addTextPart($message, $this->_txtbody);
$ht =& $this->_addRelatedPart($message);
$this->_addHtmlPart($ht);
for ($i = 0; $i < count($this->_html_images); $i++) {
$this->_addHtmlImagePart($ht, $this->_html_images[$i]);
}
} else {
// * Content-Type: multipart/related;
// * html
// * image...
$message =& $this->_addRelatedPart($null);
$this->_addHtmlPart($message);
for ($i = 0; $i < count($this->_html_images); $i++) {
$this->_addHtmlImagePart($message, $this->_html_images[$i]);
}
}
/*
// #13444, #9725: the code below was a non-RFC compliant hack
// * Content-Type: multipart/related;
// * Content-Type: multipart/alternative;
// * text
// * html
// * image...
$message =& $this->_addRelatedPart($null);
if (isset($this->_txtbody)) {
$alt =& $this->_addAlternativePart($message);
$this->_addTextPart($alt, $this->_txtbody);
$this->_addHtmlPart($alt);
} else {
$this->_addHtmlPart($message);
}
for ($i = 0; $i < count($this->_html_images); $i++) {
$this->_addHtmlImagePart($message, $this->_html_images[$i]);
}
*/
break;
case $html && $attachments && !$html_images:
$message =& $this->_addMixedPart();
if (isset($this->_txtbody)) {
$alt =& $this->_addAlternativePart($message);
$this->_addTextPart($alt, $this->_txtbody);
$this->_addHtmlPart($alt);
} else {
$this->_addHtmlPart($message);
}
for ($i = 0; $i < count($this->_parts); $i++) {
$this->_addAttachmentPart($message, $this->_parts[$i]);
}
break;
case $html && $attachments && $html_images:
$message =& $this->_addMixedPart();
if (isset($this->_txtbody)) {
$alt =& $this->_addAlternativePart($message);
$this->_addTextPart($alt, $this->_txtbody);
$rel =& $this->_addRelatedPart($alt);
} else {
$rel =& $this->_addRelatedPart($message);
}
$this->_addHtmlPart($rel);
for ($i = 0; $i < count($this->_html_images); $i++) {
$this->_addHtmlImagePart($rel, $this->_html_images[$i]);
}
for ($i = 0; $i < count($this->_parts); $i++) {
$this->_addAttachmentPart($message, $this->_parts[$i]);
}
break;
}
if (!isset($message)) {
$ret = null;
return $ret;
}
// Use saved boundary
if (!empty($this->_build_params['boundary'])) {
$boundary = $this->_build_params['boundary'];
} else {
$boundary = null;
}
// Write output to file
if ($filename) {
// Append mimePart message headers and body into file
$headers = $message->encodeToFile($filename, $boundary, $skip_head);
if (PEAR::isError($headers)) {
return $headers;
}
$this->_headers = array_merge($this->_headers, $headers);
$ret = null;
return $ret;
} else {
$output = $message->encode($boundary, $skip_head);
if (PEAR::isError($output)) {
return $output;
}
$this->_headers = array_merge($this->_headers, $output['headers']);
$body = $output['body'];
return $body;
}
}
/**
* Returns an array with the headers needed to prepend to the email
* (MIME-Version and Content-Type). Format of argument is:
* $array['header-name'] = 'header-value';
*
* @param array $xtra_headers Assoc array with any extra headers (optional)
* @param bool $overwrite Overwrite already existing headers.
* @param bool $skip_content Don't return content headers: Content-Type,
* Content-Disposition and Content-Transfer-Encoding
*
* @return array Assoc array with the mime headers
* @access public
*/
function &headers($xtra_headers = null, $overwrite = false, $skip_content = false)
{
// Add mime version header
$headers['MIME-Version'] = '1.0';
// Content-Type and Content-Transfer-Encoding headers should already
// be present if get() was called, but we'll re-set them to make sure
// we got them when called before get() or something in the message
// has been changed after get() [#14780]
if (!$skip_content) {
$headers += $this->_contentHeaders();
}
if (!empty($xtra_headers)) {
$headers = array_merge($headers, $xtra_headers);
}
if ($overwrite) {
$this->_headers = array_merge($this->_headers, $headers);
} else {
$this->_headers = array_merge($headers, $this->_headers);
}
$headers = $this->_headers;
if ($skip_content) {
unset($headers['Content-Type']);
unset($headers['Content-Transfer-Encoding']);
unset($headers['Content-Disposition']);
}
$encodedHeaders = $this->_encodeHeaders($headers);
return $encodedHeaders;
}
/**
* Get the text version of the headers
* (usefull if you want to use the PHP mail() function)
*
* @param array $xtra_headers Assoc array with any extra headers (optional)
* @param bool $overwrite Overwrite the existing headers with new.
* @param bool $skip_content Don't return content headers: Content-Type,
* Content-Disposition and Content-Transfer-Encoding
*
* @return string Plain text headers
* @access public
*/
function txtHeaders($xtra_headers = null, $overwrite = false, $skip_content = false)
{
$headers = $this->headers($xtra_headers, $overwrite, $skip_content);
// Place Received: headers at the beginning of the message
// Spam detectors often flag messages with it after the Subject: as spam
if (isset($headers['Received'])) {
$received = $headers['Received'];
unset($headers['Received']);
$headers = array('Received' => $received) + $headers;
}
$ret = '';
$eol = $this->_build_params['eol'];
foreach ($headers as $key => $val) {
if (is_array($val)) {
foreach ($val as $value) {
$ret .= "$key: $value" . $eol;
}
} else {
$ret .= "$key: $val" . $eol;
}
}
return $ret;
}
/**
* Sets the Subject header
*
* @param string $subject String to set the subject to.
*
* @return void
* @access public
*/
function setSubject($subject)
{
$this->_headers['Subject'] = $subject;
}
/**
* Set an email to the From (the sender) header
*
* @param string $email The email address to use
*
* @return void
* @access public
*/
function setFrom($email)
{
$this->_headers['From'] = $email;
}
/**
* Add an email to the Cc (carbon copy) header
* (multiple calls to this method are allowed)
*
* @param string $email The email direction to add
*
* @return void
* @access public
*/
function addCc($email)
{
if (isset($this->_headers['Cc'])) {
$this->_headers['Cc'] .= ", $email";
} else {
$this->_headers['Cc'] = $email;
}
}
/**
* Add an email to the Bcc (blank carbon copy) header
* (multiple calls to this method are allowed)
*
* @param string $email The email direction to add
*
* @return void
* @access public
*/
function addBcc($email)
{
if (isset($this->_headers['Bcc'])) {
$this->_headers['Bcc'] .= ", $email";
} else {
$this->_headers['Bcc'] = $email;
}
}
/**
* Since the PHP send function requires you to specify
* recipients (To: header) separately from the other
* headers, the To: header is not properly encoded.
* To fix this, you can use this public method to
* encode your recipients before sending to the send
* function
*
* @param string $recipients A comma-delimited list of recipients
*
* @return string Encoded data
* @access public
*/
function encodeRecipients($recipients)
{
$input = array("To" => $recipients);
$retval = $this->_encodeHeaders($input);
return $retval["To"] ;
}
/**
* Encodes headers as per RFC2047
*
* @param array $input The header data to encode
* @param array $params Extra build parameters
*
* @return array Encoded data
* @access private
*/
function _encodeHeaders($input, $params = array())
{
$build_params = $this->_build_params;
while (list($key, $value) = each($params)) {
$build_params[$key] = $value;
}
foreach ($input as $hdr_name => $hdr_value) {
if (is_array($hdr_value)) {
foreach ($hdr_value as $idx => $value) {
$input[$hdr_name][$idx] = $this->encodeHeader(
$hdr_name, $value,
$build_params['head_charset'], $build_params['head_encoding']
);
}
} else {
$input[$hdr_name] = $this->encodeHeader(
$hdr_name, $hdr_value,
$build_params['head_charset'], $build_params['head_encoding']
);
}
}
return $input;
}
/**
* Encodes a header as per RFC2047
*
* @param string $name The header name
* @param string $value The header data to encode
* @param string $charset Character set name
* @param string $encoding Encoding name (base64 or quoted-printable)
*
* @return string Encoded header data (without a name)
* @access public
* @since 1.5.3
*/
function encodeHeader($name, $value, $charset, $encoding)
{
return Mail_mimePart::encodeHeader(
$name, $value, $charset, $encoding, $this->_build_params['eol']
);
}
/**
* Get file's basename (locale independent)
*
* @param string $filename Filename
*
* @return string Basename
* @access private
*/
function _basename($filename)
{
// basename() is not unicode safe and locale dependent
if (stristr(PHP_OS, 'win') || stristr(PHP_OS, 'netware')) {
return preg_replace('/^.*[\\\\\\/]/', '', $filename);
} else {
return preg_replace('/^.*[\/]/', '', $filename);
}
}
/**
* Get Content-Type and Content-Transfer-Encoding headers of the message
*
* @return array Headers array
* @access private
*/
function _contentHeaders()
{
$attachments = count($this->_parts) ? true : false;
$html_images = count($this->_html_images) ? true : false;
$html = strlen($this->_htmlbody) ? true : false;
$text = (!$html && strlen($this->_txtbody)) ? true : false;
$headers = array();
// See get()
switch (true) {
case $text && !$attachments:
$headers['Content-Type'] = 'text/plain';
break;
case !$text && !$html && $attachments:
case $text && $attachments:
case $html && $attachments && !$html_images:
case $html && $attachments && $html_images:
$headers['Content-Type'] = 'multipart/mixed';
break;
case $html && !$attachments && !$html_images && isset($this->_txtbody):
case $html && !$attachments && $html_images && isset($this->_txtbody):
$headers['Content-Type'] = 'multipart/alternative';
break;
case $html && !$attachments && !$html_images && !isset($this->_txtbody):
$headers['Content-Type'] = 'text/html';
break;
case $html && !$attachments && $html_images && !isset($this->_txtbody):
$headers['Content-Type'] = 'multipart/related';
break;
default:
return $headers;
}
$this->_checkParams();
$eol = !empty($this->_build_params['eol'])
? $this->_build_params['eol'] : "\r\n";
if ($headers['Content-Type'] == 'text/plain') {
// single-part message: add charset and encoding
$headers['Content-Type']
.= ";$eol charset=" . $this->_build_params['text_charset'];
$headers['Content-Transfer-Encoding']
= $this->_build_params['text_encoding'];
} else if ($headers['Content-Type'] == 'text/html') {
// single-part message: add charset and encoding
$headers['Content-Type']
.= ";$eol charset=" . $this->_build_params['html_charset'];
$headers['Content-Transfer-Encoding']
= $this->_build_params['html_encoding'];
} else {
// multipart message: add charset and boundary
if (!empty($this->_build_params['boundary'])) {
$boundary = $this->_build_params['boundary'];
} else if (!empty($this->_headers['Content-Type'])
&& preg_match('/boundary="([^"]+)"/', $this->_headers['Content-Type'], $m)
) {
$boundary = $m[1];
} else {
$boundary = '=_' . md5(rand() . microtime());
}
$this->_build_params['boundary'] = $boundary;
$headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
}
return $headers;
}
/**
* Validate and set build parameters
*
* @return void
* @access private
*/
function _checkParams()
{
$encodings = array('7bit', '8bit', 'base64', 'quoted-printable');
$this->_build_params['text_encoding']
= strtolower($this->_build_params['text_encoding']);
$this->_build_params['html_encoding']
= strtolower($this->_build_params['html_encoding']);
if (!in_array($this->_build_params['text_encoding'], $encodings)) {
$this->_build_params['text_encoding'] = '7bit';
}
if (!in_array($this->_build_params['html_encoding'], $encodings)) {
$this->_build_params['html_encoding'] = '7bit';
}
// text body
if ($this->_build_params['text_encoding'] == '7bit'
&& !preg_match('/ascii/i', $this->_build_params['text_charset'])
&& preg_match('/[^\x00-\x7F]/', $this->_txtbody)
) {
$this->_build_params['text_encoding'] = 'quoted-printable';
}
// html body
if ($this->_build_params['html_encoding'] == '7bit'
&& !preg_match('/ascii/i', $this->_build_params['html_charset'])
&& preg_match('/[^\x00-\x7F]/', $this->_htmlbody)
) {
$this->_build_params['html_encoding'] = 'quoted-printable';
}
}
} // End of class
/**
* The Mail_mimePart class is used to create MIME E-mail messages
*
* This class enables you to manipulate and build a mime email
* from the ground up. The Mail_Mime class is a userfriendly api
* to this class for people who aren't interested in the internals
* of mime mail.
* This class however allows full control over the email.
*
* Compatible with PHP versions 4 and 5
*
* LICENSE: This LICENSE is in the BSD license style.
* Copyright (c) 2002-2003, Richard Heyes
* Copyright (c) 2003-2006, PEAR
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* - Neither the name of the authors, nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* @category Mail
* @package Mail_Mime
* @author Richard Heyes
* @author Cipriano Groenendal
* @author Sean Coates
* @author Aleksander Machniak
* @copyright 2003-2006 PEAR
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version CVS: $Id$
* @link http://pear.php.net/package/Mail_mime
*/
/**
* The Mail_mimePart class is used to create MIME E-mail messages
*
* This class enables you to manipulate and build a mime email
* from the ground up. The Mail_Mime class is a userfriendly api
* to this class for people who aren't interested in the internals
* of mime mail.
* This class however allows full control over the email.
*
* @category Mail
* @package Mail_Mime
* @author Richard Heyes
* @author Cipriano Groenendal
* @author Sean Coates
* @author Aleksander Machniak
* @copyright 2003-2006 PEAR
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version Release: @package_version@
* @link http://pear.php.net/package/Mail_mime
*/
class Mail_mimePart
{
/**
* The encoding type of this part
*
* @var string
* @access private
*/
var $_encoding;
/**
* An array of subparts
*
* @var array
* @access private
*/
var $_subparts;
/**
* The output of this part after being built
*
* @var string
* @access private
*/
var $_encoded;
/**
* Headers for this part
*
* @var array
* @access private
*/
var $_headers;
/**
* The body of this part (not encoded)
*
* @var string
* @access private
*/
var $_body;
/**
* The location of file with body of this part (not encoded)
*
* @var string
* @access private
*/
var $_body_file;
/**
* The end-of-line sequence
*
* @var string
* @access private
*/
var $_eol = "\r\n";
/**
* Constructor.
*
* Sets up the object.
*
* @param string $body The body of the mime part if any.
* @param array $params An associative array of optional parameters:
* content_type - The content type for this part eg multipart/mixed
* encoding - The encoding to use, 7bit, 8bit,
* base64, or quoted-printable
* cid - Content ID to apply
* disposition - Content disposition, inline or attachment
* dfilename - Filename parameter for content disposition
* description - Content description
* charset - Character set to use
* name_encoding - Encoding for attachment name (Content-Type)
* By default filenames are encoded using RFC2231
* Here you can set RFC2047 encoding (quoted-printable
* or base64) instead
* filename_encoding - Encoding for attachment filename (Content-Disposition)
* See 'name_encoding'
* eol - End of line sequence. Default: "\r\n"
* body_file - Location of file with part's body (instead of $body)
*
* @access public
*/
function Mail_mimePart($body = '', $params = array())
{
if (!empty($params['eol'])) {
$this->_eol = $params['eol'];
} else if (defined('MAIL_MIMEPART_CRLF')) { // backward-copat.
$this->_eol = MAIL_MIMEPART_CRLF;
}
$c_type = array();
$c_disp = array();
foreach ($params as $key => $value) {
switch ($key) {
case 'content_type':
$c_type['type'] = $value;
break;
case 'encoding':
$this->_encoding = $value;
$headers['Content-Transfer-Encoding'] = $value;
break;
case 'cid':
$headers['Content-ID'] = '<' . $value . '>';
break;
case 'disposition':
$c_disp['disp'] = $value;
break;
case 'dfilename':
$c_disp['filename'] = $value;
$c_type['name'] = $value;
break;
case 'description':
$headers['Content-Description'] = $value;
break;
case 'charset':
$c_type['charset'] = $value;
$c_disp['charset'] = $value;
break;
case 'language':
$c_type['language'] = $value;
$c_disp['language'] = $value;
break;
case 'location':
$headers['Content-Location'] = $value;
break;
case 'body_file':
$this->_body_file = $value;
break;
}
}
// Content-Type
if (isset($c_type['type'])) {
$headers['Content-Type'] = $c_type['type'];
if (isset($c_type['name'])) {
$headers['Content-Type'] .= ';' . $this->_eol;
$headers['Content-Type'] .= $this->_buildHeaderParam(
'name', $c_type['name'],
isset($c_type['charset']) ? $c_type['charset'] : 'US-ASCII',
isset($c_type['language']) ? $c_type['language'] : null,
isset($params['name_encoding']) ? $params['name_encoding'] : null
);
}
if (isset($c_type['charset'])) {
$headers['Content-Type']
.= ';' . $this->_eol . " charset={$c_type['charset']}";
}
}
// Content-Disposition
if (isset($c_disp['disp'])) {
$headers['Content-Disposition'] = $c_disp['disp'];
if (isset($c_disp['filename'])) {
$headers['Content-Disposition'] .= ';' . $this->_eol;
$headers['Content-Disposition'] .= $this->_buildHeaderParam(
'filename', $c_disp['filename'],
isset($c_disp['charset']) ? $c_disp['charset'] : 'US-ASCII',
isset($c_disp['language']) ? $c_disp['language'] : null,
isset($params['filename_encoding']) ? $params['filename_encoding'] : null
);
}
}
if (!empty($headers['Content-Description'])) {
$headers['Content-Description'] = $this->encodeHeader(
'Content-Description', $headers['Content-Description'],
isset($c_type['charset']) ? $c_type['charset'] : 'US-ASCII',
isset($params['name_encoding']) ? $params['name_encoding'] : 'quoted-printable',
$this->_eol
);
}
// Default content-type
if (!isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'text/plain';
}
// Default encoding
if (!isset($this->_encoding)) {
$this->_encoding = '7bit';
}
// Assign stuff to member variables
$this->_encoded = array();
$this->_headers = $headers;
$this->_body = $body;
}
/**
* Encodes and returns the email. Also stores
* it in the encoded member variable
*
* @param string $boundary Pre-defined boundary string
*
* @return An associative array containing two elements,
* body and headers. The headers element is itself
* an indexed array. On error returns PEAR error object.
* @access public
*/
function encode($boundary=null)
{
$encoded =& $this->_encoded;
if (count($this->_subparts)) {
$boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime());
$eol = $this->_eol;
$this->_headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
$encoded['body'] = '';
for ($i = 0; $i < count($this->_subparts); $i++) {
$encoded['body'] .= '--' . $boundary . $eol;
$tmp = $this->_subparts[$i]->encode();
if (PEAR::isError($tmp)) {
return $tmp;
}
foreach ($tmp['headers'] as $key => $value) {
$encoded['body'] .= $key . ': ' . $value . $eol;
}
$encoded['body'] .= $eol . $tmp['body'] . $eol;
}
$encoded['body'] .= '--' . $boundary . '--' . $eol;
} else if ($this->_body) {
$encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding);
} else if ($this->_body_file) {
// Temporarily reset magic_quotes_runtime for file reads and writes
if ($magic_quote_setting = get_magic_quotes_runtime()) {
@ini_set('magic_quotes_runtime', 0);
}
$body = $this->_getEncodedDataFromFile($this->_body_file, $this->_encoding);
if ($magic_quote_setting) {
@ini_set('magic_quotes_runtime', $magic_quote_setting);
}
if (PEAR::isError($body)) {
return $body;
}
$encoded['body'] = $body;
} else {
$encoded['body'] = '';
}
// Add headers to $encoded
$encoded['headers'] =& $this->_headers;
return $encoded;
}
/**
* Encodes and saves the email into file. File must exist.
* Data will be appended to the file.
*
* @param string $filename Output file location
* @param string $boundary Pre-defined boundary string
* @param boolean $skip_head True if you don't want to save headers
*
* @return array An associative array containing message headers
* or PEAR error object
* @access public
* @since 1.6.0
*/
function encodeToFile($filename, $boundary=null, $skip_head=false)
{
if (file_exists($filename) && !is_writable($filename)) {
$err = PEAR::raiseError('File is not writeable: ' . $filename);
return $err;
}
if (!($fh = fopen($filename, 'ab'))) {
$err = PEAR::raiseError('Unable to open file: ' . $filename);
return $err;
}
// Temporarily reset magic_quotes_runtime for file reads and writes
if ($magic_quote_setting = get_magic_quotes_runtime()) {
@ini_set('magic_quotes_runtime', 0);
}
$res = $this->_encodePartToFile($fh, $boundary, $skip_head);
fclose($fh);
if ($magic_quote_setting) {
@ini_set('magic_quotes_runtime', $magic_quote_setting);
}
return PEAR::isError($res) ? $res : $this->_headers;
}
/**
* Encodes given email part into file
*
* @param string $fh Output file handle
* @param string $boundary Pre-defined boundary string
* @param boolean $skip_head True if you don't want to save headers
*
* @return array True on sucess or PEAR error object
* @access private
*/
function _encodePartToFile($fh, $boundary=null, $skip_head=false)
{
$eol = $this->_eol;
if (count($this->_subparts)) {
$boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime());
$this->_headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
}
if (!$skip_head) {
foreach ($this->_headers as $key => $value) {
fwrite($fh, $key . ': ' . $value . $eol);
}
$f_eol = $eol;
} else {
$f_eol = '';
}
if (count($this->_subparts)) {
for ($i = 0; $i < count($this->_subparts); $i++) {
fwrite($fh, $f_eol . '--' . $boundary . $eol);
$res = $this->_subparts[$i]->_encodePartToFile($fh);
if (PEAR::isError($res)) {
return $res;
}
$f_eol = $eol;
}
fwrite($fh, $eol . '--' . $boundary . '--' . $eol);
} else if ($this->_body) {
fwrite($fh, $f_eol . $this->_getEncodedData($this->_body, $this->_encoding));
} else if ($this->_body_file) {
fwrite($fh, $f_eol);
$res = $this->_getEncodedDataFromFile(
$this->_body_file, $this->_encoding, $fh
);
if (PEAR::isError($res)) {
return $res;
}
}
return true;
}
/**
* Adds a subpart to current mime part and returns
* a reference to it
*
* @param string $body The body of the subpart, if any.
* @param array $params The parameters for the subpart, same
* as the $params argument for constructor.
*
* @return Mail_mimePart A reference to the part you just added. It is
* crucial if using multipart/* in your subparts that
* you use =& in your script when calling this function,
* otherwise you will not be able to add further subparts.
* @access public
*/
function &addSubpart($body, $params)
{
$this->_subparts[] = new Mail_mimePart($body, $params);
return $this->_subparts[count($this->_subparts) - 1];
}
/**
* Returns encoded data based upon encoding passed to it
*
* @param string $data The data to encode.
* @param string $encoding The encoding type to use, 7bit, base64,
* or quoted-printable.
*
* @return string
* @access private
*/
function _getEncodedData($data, $encoding)
{
switch ($encoding) {
case 'quoted-printable':
return $this->_quotedPrintableEncode($data);
break;
case 'base64':
return rtrim(chunk_split(base64_encode($data), 76, $this->_eol));
break;
case '8bit':
case '7bit':
default:
return $data;
}
}
/**
* Returns encoded data based upon encoding passed to it
*
* @param string $filename Data file location
* @param string $encoding The encoding type to use, 7bit, base64,
* or quoted-printable.
* @param resource $fh Output file handle. If set, data will be
* stored into it instead of returning it
*
* @return string Encoded data or PEAR error object
* @access private
*/
function _getEncodedDataFromFile($filename, $encoding, $fh=null)
{
if (!is_readable($filename)) {
$err = PEAR::raiseError('Unable to read file: ' . $filename);
return $err;
}
if (!($fd = fopen($filename, 'rb'))) {
$err = PEAR::raiseError('Could not open file: ' . $filename);
return $err;
}
$data = '';
switch ($encoding) {
case 'quoted-printable':
while (!feof($fd)) {
$buffer = $this->_quotedPrintableEncode(fgets($fd));
if ($fh) {
fwrite($fh, $buffer);
} else {
$data .= $buffer;
}
}
break;
case 'base64':
while (!feof($fd)) {
// Should read in a multiple of 57 bytes so that
// the output is 76 bytes per line. Don't use big chunks
// because base64 encoding is memory expensive
$buffer = fread($fd, 57 * 9198); // ca. 0.5 MB
$buffer = base64_encode($buffer);
$buffer = chunk_split($buffer, 76, $this->_eol);
if (feof($fd)) {
$buffer = rtrim($buffer);
}
if ($fh) {
fwrite($fh, $buffer);
} else {
$data .= $buffer;
}
}
break;
case '8bit':
case '7bit':
default:
while (!feof($fd)) {
$buffer = fread($fd, 1048576); // 1 MB
if ($fh) {
fwrite($fh, $buffer);
} else {
$data .= $buffer;
}
}
}
fclose($fd);
if (!$fh) {
return $data;
}
}
/**
* Encodes data to quoted-printable standard.
*
* @param string $input The data to encode
* @param int $line_max Optional max line length. Should
* not be more than 76 chars
*
* @return string Encoded data
*
* @access private
*/
function _quotedPrintableEncode($input , $line_max = 76)
{
$eol = $this->_eol;
/*
// imap_8bit() is extremely fast, but doesn't handle properly some characters
if (function_exists('imap_8bit') && $line_max == 76) {
$input = preg_replace('/\r?\n/', "\r\n", $input);
$input = imap_8bit($input);
if ($eol != "\r\n") {
$input = str_replace("\r\n", $eol, $input);
}
return $input;
}
*/
$lines = preg_split("/\r?\n/", $input);
$escape = '=';
$output = '';
while (list($idx, $line) = each($lines)) {
$newline = '';
$i = 0;
while (isset($line[$i])) {
$char = $line[$i];
$dec = ord($char);
$i++;
if (($dec == 32) && (!isset($line[$i]))) {
// convert space at eol only
$char = '=20';
} elseif ($dec == 9 && isset($line[$i])) {
; // Do nothing if a TAB is not on eol
} elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) {
$char = $escape . sprintf('%02X', $dec);
} elseif (($dec == 46) && (($newline == '')
|| ((strlen($newline) + strlen("=2E")) >= $line_max))
) {
// Bug #9722: convert full-stop at bol,
// some Windows servers need this, won't break anything (cipri)
// Bug #11731: full-stop at bol also needs to be encoded
// if this line would push us over the line_max limit.
$char = '=2E';
}
// Note, when changing this line, also change the ($dec == 46)
// check line, as it mimics this line due to Bug #11731
// EOL is not counted
if ((strlen($newline) + strlen($char)) >= $line_max) {
// soft line break; " =\r\n" is okay
$output .= $newline . $escape . $eol;
$newline = '';
}
$newline .= $char;
} // end of for
$output .= $newline . $eol;
unset($lines[$idx]);
}
// Don't want last crlf
$output = substr($output, 0, -1 * strlen($eol));
return $output;
}
/**
* Encodes the paramater of a header.
*
* @param string $name The name of the header-parameter
* @param string $value The value of the paramter
* @param string $charset The characterset of $value
* @param string $language The language used in $value
* @param string $encoding Parameter encoding. If not set, parameter value
* is encoded according to RFC2231
* @param int $maxLength The maximum length of a line. Defauls to 75
*
* @return string
*
* @access private
*/
function _buildHeaderParam($name, $value, $charset=null, $language=null,
$encoding=null, $maxLength=75
) {
// RFC 2045:
// value needs encoding if contains non-ASCII chars or is longer than 78 chars
if (!preg_match('#[^\x20-\x7E]#', $value)) {
$token_regexp = '#([^\x21,\x23-\x27,\x2A,\x2B,\x2D'
. ',\x2E,\x30-\x39,\x41-\x5A,\x5E-\x7E])#';
if (!preg_match($token_regexp, $value)) {
// token
if (strlen($name) + strlen($value) + 3 <= $maxLength) {
return " {$name}={$value}";
}
} else {
// quoted-string
$quoted = addcslashes($value, '\\"');
if (strlen($name) + strlen($quoted) + 5 <= $maxLength) {
return " {$name}=\"{$quoted}\"";
}
}
}
// RFC2047: use quoted-printable/base64 encoding
if ($encoding == 'quoted-printable' || $encoding == 'base64') {
return $this->_buildRFC2047Param($name, $value, $charset, $encoding);
}
// RFC2231:
$encValue = preg_replace_callback(
'/([^\x21,\x23,\x24,\x26,\x2B,\x2D,\x2E,\x30-\x39,\x41-\x5A,\x5E-\x7E])/',
array($this, '_encodeReplaceCallback'), $value
);
$value = "$charset'$language'$encValue";
$header = " {$name}*={$value}";
if (strlen($header) <= $maxLength) {
return $header;
}
$preLength = strlen(" {$name}*0*=");
$maxLength = max(16, $maxLength - $preLength - 3);
$maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|";
$headers = array();
$headCount = 0;
while ($value) {
$matches = array();
$found = preg_match($maxLengthReg, $value, $matches);
if ($found) {
$headers[] = " {$name}*{$headCount}*={$matches[0]}";
$value = substr($value, strlen($matches[0]));
} else {
$headers[] = " {$name}*{$headCount}*={$value}";
$value = '';
}
$headCount++;
}
$headers = implode(';' . $this->_eol, $headers);
return $headers;
}
/**
* Encodes header parameter as per RFC2047 if needed
*
* @param string $name The parameter name
* @param string $value The parameter value
* @param string $charset The parameter charset
* @param string $encoding Encoding type (quoted-printable or base64)
* @param int $maxLength Encoded parameter max length. Default: 76
*
* @return string Parameter line
* @access private
*/
function _buildRFC2047Param($name, $value, $charset,
$encoding='quoted-printable', $maxLength=76
) {
// WARNING: RFC 2047 says: "An 'encoded-word' MUST NOT be used in
// parameter of a MIME Content-Type or Content-Disposition field",
// but... it's supported by many clients/servers
$quoted = '';
if ($encoding == 'base64') {
$value = base64_encode($value);
$prefix = '=?' . $charset . '?B?';
$suffix = '?=';
// 2 x SPACE, 2 x '"', '=', ';'
$add_len = strlen($prefix . $suffix) + strlen($name) + 6;
$len = $add_len + strlen($value);
while ($len > $maxLength) {
// We can cut base64-encoded string every 4 characters
$real_len = floor(($maxLength - $add_len) / 4) * 4;
$_quote = substr($value, 0, $real_len);
$value = substr($value, $real_len);
$quoted .= $prefix . $_quote . $suffix . $this->_eol . ' ';
$add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';'
$len = strlen($value) + $add_len;
}
$quoted .= $prefix . $value . $suffix;
} else {
// quoted-printable
$value = $this->encodeQP($value);
$prefix = '=?' . $charset . '?Q?';
$suffix = '?=';
// 2 x SPACE, 2 x '"', '=', ';'
$add_len = strlen($prefix . $suffix) + strlen($name) + 6;
$len = $add_len + strlen($value);
while ($len > $maxLength) {
$length = $maxLength - $add_len;
// don't break any encoded letters
if (preg_match("/^(.{0,$length}[^\=][^\=])/", $value, $matches)) {
$_quote = $matches[1];
}
$quoted .= $prefix . $_quote . $suffix . $this->_eol . ' ';
$value = substr($value, strlen($_quote));
$add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';'
$len = strlen($value) + $add_len;
}
$quoted .= $prefix . $value . $suffix;
}
return " {$name}=\"{$quoted}\"";
}
/**
* Encodes a header as per RFC2047
*
* @param string $name The header name
* @param string $value The header data to encode
* @param string $charset Character set name
* @param string $encoding Encoding name (base64 or quoted-printable)
* @param string $eol End-of-line sequence. Default: "\r\n"
*
* @return string Encoded header data (without a name)
* @access public
* @since 1.6.1
*/
function encodeHeader($name, $value, $charset='ISO-8859-1',
$encoding='quoted-printable', $eol="\r\n"
) {
// Structured headers
$comma_headers = array(
'from', 'to', 'cc', 'bcc', 'sender', 'reply-to',
'resent-from', 'resent-to', 'resent-cc', 'resent-bcc',
'resent-sender', 'resent-reply-to',
'return-receipt-to', 'disposition-notification-to',
);
$other_headers = array(
'references', 'in-reply-to', 'message-id', 'resent-message-id',
);
$name = strtolower($name);
if (in_array($name, $comma_headers)) {
$separator = ',';
} else if (in_array($name, $other_headers)) {
$separator = ' ';
}
if (!$charset) {
$charset = 'ISO-8859-1';
}
// Structured header (make sure addr-spec inside is not encoded)
if (!empty($separator)) {
$parts = Mail_mimePart::_explodeQuotedString($separator, $value);
$value = '';
foreach ($parts as $part) {
$part = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $part);
$part = trim($part);
if (!$part) {
continue;
}
if ($value) {
$value .= $separator==',' ? $separator.' ' : ' ';
} else {
$value = $name . ': ';
}
// let's find phrase (name) and/or addr-spec
if (preg_match('/^<\S+@\S+>$/', $part)) {
$value .= $part;
} else if (preg_match('/^\S+@\S+$/', $part)) {
// address without brackets and without name
$value .= $part;
} else if (preg_match('/<*\S+@\S+>*$/', $part, $matches)) {
// address with name (handle name)
$address = $matches[0];
$word = str_replace($address, '', $part);
$word = trim($word);
// check if phrase requires quoting
if ($word) {
// non-ASCII: require encoding
if (preg_match('#([\x80-\xFF]){1}#', $word)) {
if ($word[0] == '"' && $word[strlen($word)-1] == '"') {
// de-quote quoted-string, encoding changes
// string to atom
$search = array("\\\"", "\\\\");
$replace = array("\"", "\\");
$word = str_replace($search, $replace, $word);
$word = substr($word, 1, -1);
}
// find length of last line
if (($pos = strrpos($value, $eol)) !== false) {
$last_len = strlen($value) - $pos;
} else {
$last_len = strlen($value);
}
$word = Mail_mimePart::encodeHeaderValue(
$word, $charset, $encoding, $last_len, $eol
);
} else if (($word[0] != '"' || $word[strlen($word)-1] != '"')
&& preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $word)
) {
// ASCII: quote string if needed
$word = '"'.addcslashes($word, '\\"').'"';
}
}
$value .= $word.' '.$address;
} else {
// addr-spec not found, don't encode (?)
$value .= $part;
}
// RFC2822 recommends 78 characters limit, use 76 from RFC2047
$value = wordwrap($value, 76, $eol . ' ');
}
// remove header name prefix (there could be EOL too)
$value = preg_replace(
'/^'.$name.':('.preg_quote($eol, '/').')* /', '', $value
);
} else {
// Unstructured header
// non-ASCII: require encoding
if (preg_match('#([\x80-\xFF]){1}#', $value)) {
if ($value[0] == '"' && $value[strlen($value)-1] == '"') {
// de-quote quoted-string, encoding changes
// string to atom
$search = array("\\\"", "\\\\");
$replace = array("\"", "\\");
$value = str_replace($search, $replace, $value);
$value = substr($value, 1, -1);
}
$value = Mail_mimePart::encodeHeaderValue(
$value, $charset, $encoding, strlen($name) + 2, $eol
);
} else if (strlen($name.': '.$value) > 78) {
// ASCII: check if header line isn't too long and use folding
$value = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $value);
$tmp = wordwrap($name.': '.$value, 78, $eol . ' ');
$value = preg_replace('/^'.$name.':\s*/', '', $tmp);
// hard limit 998 (RFC2822)
$value = wordwrap($value, 998, $eol . ' ', true);
}
}
return $value;
}
/**
* Explode quoted string
*
* @param string $delimiter Delimiter expression string for preg_match()
* @param string $string Input string
*
* @return array String tokens array
* @access private
*/
function _explodeQuotedString($delimiter, $string)
{
$result = array();
$strlen = strlen($string);
for ($q=$p=$i=0; $i < $strlen; $i++) {
if ($string[$i] == "\""
&& (empty($string[$i-1]) || $string[$i-1] != "\\")
) {
$q = $q ? false : true;
} else if (!$q && preg_match("/$delimiter/", $string[$i])) {
$result[] = substr($string, $p, $i - $p);
$p = $i + 1;
}
}
$result[] = substr($string, $p);
return $result;
}
/**
* Encodes a header value as per RFC2047
*
* @param string $value The header data to encode
* @param string $charset Character set name
* @param string $encoding Encoding name (base64 or quoted-printable)
* @param int $prefix_len Prefix length. Default: 0
* @param string $eol End-of-line sequence. Default: "\r\n"
*
* @return string Encoded header data
* @access public
* @since 1.6.1
*/
function encodeHeaderValue($value, $charset, $encoding, $prefix_len=0, $eol="\r\n")
{
if ($encoding == 'base64') {
// Base64 encode the entire string
$value = base64_encode($value);
// Generate the header using the specified params and dynamicly
// determine the maximum length of such strings.
// 75 is the value specified in the RFC.
$prefix = '=?' . $charset . '?B?';
$suffix = '?=';
$maxLength = 75 - strlen($prefix . $suffix) - 2;
$maxLength1stLine = $maxLength - $prefix_len;
// We can cut base4 every 4 characters, so the real max
// we can get must be rounded down.
$maxLength = $maxLength - ($maxLength % 4);
$maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4);
$cutpoint = $maxLength1stLine;
$value_out = $value;
$output = '';
while ($value_out) {
// Split translated string at every $maxLength
$part = substr($value_out, 0, $cutpoint);
$value_out = substr($value_out, $cutpoint);
$cutpoint = $maxLength;
// RFC 2047 specifies that any split header should
// be seperated by a CRLF SPACE.
if ($output) {
$output .= $eol . ' ';
}
$output .= $prefix . $part . $suffix;
}
$value = $output;
} else {
// quoted-printable encoding has been selected
$value = Mail_mimePart::encodeQP($value);
// Generate the header using the specified params and dynamicly
// determine the maximum length of such strings.
// 75 is the value specified in the RFC.
$prefix = '=?' . $charset . '?Q?';
$suffix = '?=';
$maxLength = 75 - strlen($prefix . $suffix) - 3;
$maxLength1stLine = $maxLength - $prefix_len;
$maxLength = $maxLength - 1;
// This regexp will break QP-encoded text at every $maxLength
// but will not break any encoded letters.
$reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|";
$reg2nd = "|(.{0,$maxLength}[^\=][^\=])|";
$value_out = $value;
$realMax = $maxLength1stLine + strlen($prefix . $suffix);
if (strlen($value_out) >= $realMax) {
// Begin with the regexp for the first line.
$reg = $reg1st;
$output = '';
while ($value_out) {
// Split translated string at every $maxLength
// But make sure not to break any translated chars.
$found = preg_match($reg, $value_out, $matches);
// After this first line, we need to use a different
// regexp for the first line.
$reg = $reg2nd;
// Save the found part and encapsulate it in the
// prefix & suffix. Then remove the part from the
// $value_out variable.
if ($found) {
$part = $matches[0];
$len = strlen($matches[0]);
$value_out = substr($value_out, $len);
} else {
$part = $value_out;
$value_out = "";
}
// RFC 2047 specifies that any split header should
// be seperated by a CRLF SPACE
if ($output) {
$output .= $eol . ' ';
}
$output .= $prefix . $part . $suffix;
}
$value_out = $output;
} else {
$value_out = $prefix . $value_out . $suffix;
}
$value = $value_out;
}
return $value;
}
/**
* Encodes the given string using quoted-printable
*
* @param string $str String to encode
*
* @return string Encoded string
* @access public
* @since 1.6.0
*/
function encodeQP($str)
{
// Replace all special characters used by the encoder
$search = array('=', '_', '?', ' ');
$replace = array('=3D', '=5F', '=3F', '_');
$str = str_replace($search, $replace, $str);
// Replace all extended characters (\x80-xFF) with their
// ASCII values.
return preg_replace_callback(
'/([\x80-\xFF])/', array('Mail_mimePart', '_qpReplaceCallback'), $str
);
}
/**
* Callback function to replace extended characters (\x80-xFF) with their
* ASCII values (RFC2047: quoted-printable)
*
* @param array $matches Preg_replace's matches array
*
* @return string Encoded character string
* @access private
*/
function _qpReplaceCallback($matches)
{
return sprintf('=%02X', ord($matches[1]));
}
/**
* Callback function to replace extended characters (\x80-xFF) with their
* ASCII values (RFC2231)
*
* @param array $matches Preg_replace's matches array
*
* @return string Encoded character string
* @access private
*/
function _encodeReplaceCallback($matches)
{
return sprintf('%%%02X', ord($matches[1]));
}
} // End of class
/**
* internal PHP-mail() implementation of the PEAR Mail:: interface.
*
* PHP versions 4 and 5
*
* LICENSE:
*
* Copyright (c) 2010 Chuck Hagenbuch
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* o The names of the authors may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @category Mail
* @package Mail
* @author Chuck Hagenbuch
* @copyright 2010 Chuck Hagenbuch
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Id$
* @link http://pear.php.net/package/Mail/
*/
/**
* internal PHP-mail() implementation of the PEAR Mail:: interface.
* @package Mail
* @version $Revision: 1.2 $
*/
class Mail_mail extends Mail {
/**
* Any arguments to pass to the mail() function.
* @var string
*/
var $_params = '';
/**
* Constructor.
*
* Instantiates a new Mail_mail:: object based on the parameters
* passed in.
*
* @param array $params Extra arguments for the mail() function.
*/
function Mail_mail($params = null)
{
// The other mail implementations accept parameters as arrays.
// In the interest of being consistent, explode an array into
// a string of parameter arguments.
if (is_array($params)) {
$this->_params = join(' ', $params);
} else {
$this->_params = $params;
}
/* Because the mail() function may pass headers as command
* line arguments, we can't guarantee the use of the standard
* "\r\n" separator. Instead, we use the system's native line
* separator. */
if (defined('PHP_EOL')) {
$this->sep = PHP_EOL;
} else {
$this->sep = (strpos(PHP_OS, 'WIN') === false) ? "\n" : "\r\n";
}
}
/**
* Implements Mail_mail::send() function using php's built-in mail()
* command.
*
* @param mixed $recipients Either a comma-seperated list of recipients
* (RFC822 compliant), or an array of recipients,
* each RFC822 valid. This may contain recipients not
* specified in the headers, for Bcc:, resending
* messages, etc.
*
* @param array $headers The array of headers to send with the mail, in an
* associative array, where the array key is the
* header name (ie, 'Subject'), and the array value
* is the header value (ie, 'test'). The header
* produced from those values would be 'Subject:
* test'.
*
* @param string $body The full text of the message body, including any
* Mime parts, etc.
*
* @return mixed Returns true on success, or a PEAR_Error
* containing a descriptive error message on
* failure.
*
* @access public
*/
function send($recipients, $headers, $body)
{
if (!is_array($headers)) {
return PEAR::raiseError('$headers must be an array');
}
$result = $this->_sanitizeHeaders($headers);
if (is_a($result, 'PEAR_Error')) {
return $result;
}
// If we're passed an array of recipients, implode it.
if (is_array($recipients)) {
$recipients = implode(', ', $recipients);
}
// Get the Subject out of the headers array so that we can
// pass it as a seperate argument to mail().
$subject = '';
if (isset($headers['Subject'])) {
$subject = $headers['Subject'];
unset($headers['Subject']);
}
// Also remove the To: header. The mail() function will add its own
// To: header based on the contents of $recipients.
unset($headers['To']);
// Flatten the headers out.
$headerElements = $this->prepareHeaders($headers);
if (is_a($headerElements, 'PEAR_Error')) {
return $headerElements;
}
list(, $text_headers) = $headerElements;
// We only use mail()'s optional fifth parameter if the additional
// parameters have been provided and we're not running in safe mode.
if (empty($this->_params) || ini_get('safe_mode')) {
$result = mail($recipients, $subject, $body, $text_headers);
} else {
$result = mail($recipients, $subject, $body, $text_headers,
$this->_params);
}
// If the mail() function returned failure, we need to create a
// PEAR_Error object and return it instead of the boolean result.
if ($result === false) {
$result = PEAR::raiseError('mail() returned failure');
}
return $result;
}
}
////////Mailer/////////////////////
class FM_Mailer
{
var $config;
var $logger;
var $attachments;
var $error_handler;
function FM_Mailer(&$config,&$logger,&$error_handler)
{
$this->config = &$config;
$this->logger = &$logger;
$this->error_handler = &$error_handler;
$this->attachments=array();
}
function SendTextMail($from,$to,$subject,$mailbody)
{
$this->SendMail($from,$to,$subject,$mailbody,false);
}
function SendHtmlMail($from,$to,$subject,$mailbody)
{
$this->SendMail($from,$to,$subject,$mailbody,true);
}
function HandleConfigError($error)
{
$this->error_handler->HandleConfigError($error);
}
function SendMail($from,$to,$subject,$mailbody,$htmlformat)
{
$real_from='';
$reply_to='';
if(true == $this->config->variable_from)
{
$real_from = $from;
}
else
{
$real_from = $this->config->from_addr;
$reply_to = $from;
}
$hdrs = array(
'From' => $real_from,
'Sender' => $real_from,
'Subject' => $subject,
'To' => $to
);
if($this->config->v4_email_headers)
{
$hdrs['Date'] = $this->RFCDate();
$hdrs['Return-Path'] = $real_from;
$uniq_id = md5(uniqid(time()));
$servername = empty($_SERVER['SERVER_NAME'])?'localhost.localdomain':$_SERVER['SERVER_NAME'];
$hdrs['Message-ID'] = sprintf("<%s@%s>", $uniq_id,$servername);
@ini_set('sendmail_from', $real_from);
}
if(!empty($reply_to))
{
$hdrs['Reply-To'] = $reply_to;
}
$this->DefinePHPEOL();
$mime = new Mail_mime(PHP_EOL);
$mailbody = str_replace("\r","",$mailbody);
$mailbody = str_replace("\n",PHP_EOL,$mailbody);
if(true == $htmlformat)
{
$mime->setHTMLBody($mailbody);
}
else
{
$mime->setTxtBody($mailbody);
}
foreach($this->attachments as $file)
{
$mime->addAttachment($file['filepath'],$file['mime_type']);
}
$body = $mime->get(array(
'head_encoding'=>'base64',
'html_encoding'=>'8bit',
'html_charset'=>'UTF-8',
'text_charset'=>'UTF-8',
'head_charset'=>'UTF-8',
'text_encoding'=>'8bit'
));
if(!$this->CheckHeaders($hdrs))
{
$this->HandleConfigError("Email to:$to subject:$subject aborted since it failed header validation");
return false;
}
$headers = $mime->headers($hdrs);
$params = array();
//Email addresses of the form Name
if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN'))
{
$match = array();
if(preg_match("/(.*?)<(.*?)>/",$to,$match))
{
$to = $match[2];
$to = trim($to);
}
}
$method = 'mail';
if($this->config->use_smtp)
{
$method = 'smtp';
$params = array('host'=> $this->config->smtp_host );
if(!empty($this->config->smtp_uname))
{
$params['auth']=true;
$params['timeout'] = 10;
$params['username'] = $this->config->smtp_uname;
$params['password'] = sfm_crypt_decrypt($this->config->smtp_pwd,
$this->config->encr_key);
}
$params['port'] = $this->config->smtp_port;
}
$mail_object = &Mail::factory($method,$params);
if(!$mail_object)
{
$this->HandleConfigError("Couldn't make mail object");
return false;
}
$result = $mail_object->send($to, $headers, $body);
if (PEAR::isError($result))
{
$this->HandleConfigError("email error: ".$result->getMessage());
return false;
}
return true;
}
function RFCDate()
{
$tz = date('Z');
$tzs = ($tz < 0) ? '-' : '+';
$tz = abs($tz);
$tz = (int)($tz/3600)*100 + ($tz%3600)/60;
$result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
return $result;
}
function CheckHeaders(&$headers)
{
foreach ($headers as $key => $value)
{
$value = trim($value);
$headers[$key] = $value;
if($this->IsInjected($value))
{
$this->logger->LogError("Suspicious email header: $key -> $value. Aborting email attempt");
return false;
}
}
return true;
}
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
function AttachFile($filepath,$type)
{
$this->attachments[]=array('filepath'=>$filepath,'mime_type'=>$type);
}
function DefinePHPEOL()
{
if (!defined('PHP_EOL'))
{
switch (strtoupper(substr(PHP_OS, 0, 3)))
{
// Windows
case 'WIN':
define('PHP_EOL', "\r\n");
break;
// Mac
case 'DAR':
define('PHP_EOL', "\r");
break;
// Unix
default:
define('PHP_EOL', "\n");
}
}
}
}
////////ComposedMailSender/////////////
class FM_ComposedMailSender extends FM_Module
{
var $config;
var $formvars;
var $message_subject;
var $message_body;
var $mailer;
function FM_ComposedMailSender()
{
$this->mailer = NULL;
}
function InitMailer()
{
$this->mailer = new FM_Mailer($this->config,$this->logger,$this->error_handler);
}
function ComposeMessage($subj_templ,$mail_templ)
{
$ret = false;
$this->message_subject = $subj_templ;
$templ_page = $mail_templ;
if(strlen($templ_page)>0)
{
$composer = new FM_PageMerger();
$tmpdatamap =
$this->common_objs->formvar_mx->CreateFieldMatrix($this->config->email_format_html);
$ret = true;
if(false == $composer->Merge($templ_page,$tmpdatamap))
{
$ret = false;
$this->logger->LogError("MailComposer: merge failed");
}
$this->message_body = $composer->getMessageBody();
$subj_merge = new FM_PageMerger();
$subj_merge->Merge($this->message_subject,$this->formvars);
$this->message_subject = $subj_merge->getMessageBody();
}
return $ret;
}//ComposeMessage
function SendMail($from,$to)
{
if(NULL == $this->mailer)
{
$this->logger->LogError("mail composer: not initialized");
return false;
}
if(false== $this->config->email_format_html)
{
$this->mailer->SendTextMail($from,$to,
$this->message_subject,
$this->message_body);
}
else
{
$this->mailer->SendHtmlMail($from,$to,
$this->message_subject,
$this->message_body);
}
}
}//
////////FormDataSender/////////////
class FM_FormDataSender extends FM_ComposedMailSender
{
var $mail_subject;
var $mail_template;
var $dest_list;
var $mail_from;
var $file_upload;
var $attach_files;
function FM_FormDataSender($subj="",$templ="",$from="")
{
$this->mail_subject=$subj;
$this->mail_template=$templ;
$this->dest_list=array();
$this->mail_from=$from;
$this->file_upload=NULL;
$this->attach_files = true;
}
function SetFileUploader(&$fileUploader)
{
$this->file_upload = &$fileUploader;
}
function AddToAddr($toaddr,$condn='')
{
array_push($this->dest_list,array('to'=>$toaddr,'condn'=>$condn));
}
function SetAttachFiles($attach_files)
{
$this->attach_files = $attach_files;
}
function SendFormData()
{
$this->InitMailer();
$this->ComposeMessage($this->mail_subject,
$this->mail_template);
if($this->attach_files && NULL != $this->file_upload )
{
$this->file_upload->AttachFiles($this->mailer);
}
$from_merge = new FM_PageMerger();
$from_merge->Merge($this->mail_from,$this->formvars);
$this->mail_from = $from_merge->getMessageBody();
foreach($this->dest_list as $dest_obj)
{
$to_address = $dest_obj['to'];
$condn = $dest_obj['condn'];
if(!empty($condn) && false === sfm_validate_condition($condn,$this->formvars))
{
$this->logger->LogInfo("Condition failed. Skipping email- to:$to_address condn:$condn");
continue;
}
if(!$this->ext_module->BeforeSendingFormSubmissionEMail($to_address,
$this->message_subject,$this->message_body))
{
$this->logger->LogInfo("Extension module prevented sending email to: $to_address");
continue;
}
$this->logger->LogInfo("sending form data to: $to_address");
$this->SendMail($this->mail_from,
$to_address);
}
}
function ValidateInstallation(&$app_command_obj)
{
if(!$app_command_obj->IsEmailTested())
{
return $app_command_obj->TestSMTPEmail();
}
return true;
}
function Process(&$continue)
{
if(strlen($this->mail_template)<=0||
count($this->dest_list)<=0)
{
return false;
}
$continue = true;
$this->SendFormData();
return true;
}
}
////////AutoResponseSender/////////////
class FM_AutoResponseSender extends FM_ComposedMailSender
{
var $subject;
var $template;
var $namevar;
var $emailvar;
function FM_AutoResponseSender($subj="",$templ="")
{
$this->subject = $subj;
$this->template= $templ;
$this->namevar= "";
$this->emailvar= "";
}
function SetToVariables($name_var,$email_var)
{
$this->namevar= $name_var;
$this->emailvar= $email_var;
}
function SendAutoResponse()
{
$name_val =
$this->formvars[$this->namevar];
$email_val =
$this->formvars[$this->emailvar];
$email_val = trim($email_val);
if(empty($email_val))
{
$this->logger->LogError("Email value is empty. Didn't send auto-response");
return;
}
$this->InitMailer();
$this->ComposeMessage($this->subject,$this->template);
$name_val = trim($name_val);
$to_var ='';
if(!empty($name_val))
{
$to_var = "$name_val<$email_val>";
}
else
{
$to_var = $email_val;
}
if(!$this->ext_module->BeforeSendingAutoResponse($to_var,
$this->message_subject,$this->message_body))
{
$this->logger->LogInfo("The extension module stopped the auto-response to: $to_var");
return;
}
$this->logger->LogInfo("sending auto response to: $to_var");
$this->SendMail($this->config->from_addr,$to_var);
}
function Process(&$continue)
{
if(strlen($this->template)<=0||
strlen($this->emailvar)<=0)
{
$this->logger->LogError("auto response: template or emailvar is empty!");
return false;
}
$continue = true;
$this->SendAutoResponse();
return true;
}
function ValidateInstallation(&$app_command_obj)
{
if(!$app_command_obj->IsEmailTested())
{
return $app_command_obj->TestSMTPEmail();
}
return true;
}
}
class FM_FormDataCSVMaker extends FM_Module
{
var $formdata_file;
var $csv_file_maxsize;//in KBs
var $csv_file_variables;
var $csv_seperator;
var $csv_filename;
var $file_uploader;
function FM_FormDataCSVMaker($maxsize=1024,$filepath="")
{
$this->formdata_file=$filepath;
$this->csv_file_maxsize=$maxsize;
$this->csv_file_variables=array();
$this->csv_seperator=",";
$this->csv_filename="";
$this->file_uploader=NULL;
}
function SetFileUploader(&$file_uploader)
{
$this->file_uploader = &$file_uploader;
}
function AddCSVVariable($varname)
{
if(is_array($varname))
{
foreach($varname as $v)
{
array_push($this->csv_file_variables,$v);
}
}
else
{
array_push($this->csv_file_variables,$varname);
}
}
function Process(&$continue)
{
$continue=true;
$tmppath="";
if(!$this->GetCreateDataFilePath($tmppath))
{
$this->logger->LogError("csv maker: failed getting file name");
return false;
}
if(NULL != $this->file_uploader)
{
$this->file_uploader->SaveUploadedFile();
}
$bret = $this->SaveData();
if(false == $bret)
{
$continue = false;
}
return $bret;
}
function AfterVariablessInitialized()
{
if(!empty($_GET['sfm_adminpage']) &&
'csv' == $_GET['sfm_adminpage'])
{
$attachments = false;
if(!empty($_POST['attachments']))
{
if($_POST['attachments'] == 'yes')
{
$attachments = true;
}
}
$this->get_csv_download($attachments);
return false;
}
return true;
}
function DoAppCommand($cmd,$val,&$app_command_obj)
{
$ret=false;
switch($cmd)
{
case 'data_file_list':
{
$this->get_data_file_list($app_command_obj->response_sender);
$ret=true;
break;
}
case 'get_file':
{
if(strlen($val)<=0)
{
$app_command_obj->addError("Name of the file to be downloaded is not mentioned");
}
else
{
$this->get_file($val,$app_command_obj->response_sender);
}
$ret=true;
break;
}
case 'rem_file':
{
$ret = $this->rem_file($val,$app_command_obj);
break;
}
}//switch
return $ret;
}
function GetCreateDataFilePath(&$filepath)
{
if(strlen($this->formdata_file) <= 0)
{
if(!$this->CreateFormDataFileName())
{
return false;
}
}
$filepath = $this->formdata_file;
return true;
}
function SliceFileForDownload(&$filename)
{
$fname = $this->formdata_file;
if(!file_exists($fname))
{
return true;
}
return $this->SliceOutCSVFile($filename);
}
function CreateFormDataFileName()
{
$ret = false;
if(strlen($this->config->form_file_folder) > 0)
{
if(strlen($this->csv_filename)>0)
{
$this->formdata_file = sfm_make_path($this->config->form_file_folder,
$this->csv_filename);
}
else
{
$form_id_part = substr($this->config->get_form_id(),0,8);
if(strlen($form_id_part)<=0) return false;
$filename = $this->formname.'-'.$form_id_part.'-csv.php';
$this->formdata_file = sfm_make_path($this->config->form_file_folder,
$filename);
}
$ret = true;
}
else
{
$this->logger->LogError("csv maker: form_file_folder is not configured");
$this->formdata_file="";
$ret = false;
}
return $ret;
}
function GetSliceOutFileName()
{
$filename = $this->formdata_file;
$today = date("Y-m-d");
$filename_start = strrpos($filename,"/");
if ($filename_start === false ||
is_string ($pos) && !$pos)
{
$filename_start = 0;
}
$ptpos = strpos($filename,".",$filename_start);
if ($ptpos === false ||
is_string ($ptpos) && !$ptpos)
{
$ptpos = strlen($filename);
}
$new_filename = substr($filename,0,$ptpos).'~'.$today.substr($filename,$ptpos);
$suff=0;
while(file_exists($new_filename))
{
$suff++;
$new_filename = substr($filename,0,$ptpos).'~'.$today."-$suff".substr($filename,$ptpos);
}
return $new_filename;
}
function HandleFileOversizing()
{
$fname = $this->formdata_file;
if(!file_exists($fname))
{
return true;
}
$maxsize = $this->csv_file_maxsize * 1024;
$cursize = filesize($fname);
if($cursize >= $maxsize)
{
$this->logger->LogInfo("csv maker: handling file oversize.".
" cur.size=$cursize max size=$maxsize");
$tmpname="";
return $this->SliceOutCSVFile($tmpname);
}
return true;
}
function SliceOutCSVFile(&$newfilename)
{
$newfilename = $this->GetSliceOutFileName();
$this->logger->LogInfo("csv maker: new slice file name $newfilename");
if(!rename($this->formdata_file,$newfilename))
{
$this->error_handler->HandleConfigError("Failed renaming file: ".
" $this->formdata_file. New name: $newfilename");
return false;
}
return $this->CreateCSVFile();
}
function GetFileSignature()
{
return "--Simfatic Forms CSV File--";
}
function CreateCSVFile()
{
$fname = $this->formdata_file;
$file_maker = new SecureFileMaker($this->GetFileSignature());
$ret = $file_maker->CreateFile($fname,$this->getCSVHeader());
if(!$ret)
{
$this->error_handler->HandleConfigError("Failed creating csv file: $fname");
}
return $ret;
}
function getCSVHeader()
{
$header_line = "";
foreach($this->csv_file_variables as $var_name)
{
$header_line .= $var_name;
$header_line .= $this->csv_seperator;
}
$header_line = rtrim($header_line,$this->csv_seperator);
$header_line .= $this->config->slashn;
return $header_line;
}
function DoesHeaderMatch()
{
$file_maker = new SecureFileMaker($this->GetFileSignature());
$fp = fopen($this->formdata_file,"r");
if(!$fp)
{
return false;
}
$header = $file_maker->ReadNextLine($fp);
fclose($fp);
$newheader = $this->getCSVHeader();
$header = trim($header);
$newheader = trim($newheader);
$ret=false;
if(strcasecmp($header,$newheader)==0)
{
$ret =true;
}
return $ret;
}
function EnsureHeaderConsistency()
{
$ret = false;
$this->logger->LogInfo("csv maker: csv header changed; slicing the file");
$tmpname="";
$ret =$this->SliceOutCSVFile($tmpname);
return $ret;
}
function PreProcess()
{
$ret = true;
if(!file_exists($this->formdata_file))
{
$ret =$this->CreateCSVFile();
}
else
if(false == $this->DoesHeaderMatch())
{
$ret =$this->EnsureHeaderConsistency();
}
else
{
$ret =$this->HandleFileOversizing();
}
return $ret;
}
function GetCSVFieldValue($var_name)
{
return $this->common_objs->formvar_mx->GetFieldValueAsString($var_name,/*$use_disp_var*/true);
}
function SaveData()
{
if(strlen($this->formdata_file)<=0)
{
$this->logger->LogError("csv maker: formdata_file is not configured");
return false;
}
if(false == $this->PreProcess())
{
return false;
}
$data_line = $this->GetCSVDataLine();
$this->logger->LogInfo("csv maker: writing to csv file $this->formdata_file");
$file_maker = new SecureFileMaker($this->GetFileSignature());
$ret = $file_maker->AppendLine($this->formdata_file,$data_line);
if(!$ret)
{
$this->error_handler->HandleConfigError("Failed writing to csv file: $this->formdata_file");
}
return $ret;
}
function GetCSVDataLine()
{
$data_line = "";
foreach($this->csv_file_variables as $var_name)
{
$value = $this->GetCSVFieldValue($var_name);
$value = sfm_csv_escape($value);
$data_line .= $value;
$data_line .= $this->csv_seperator;
}
$data_line = rtrim($data_line,$this->csv_seperator);
$data_line .= $this->config->slashn;
return $data_line;
}
function rem_file($val,&$app_command_obj)
{
$parts = explode('/',$val);
$filename=$parts[0];
$is_attachment='n';
if(isset($parts[1]))
{
$is_attachment=$parts[1];
}
if($is_attachment == 'n')
{
$base_folder = $this->getFormDataFolder();
$app_command_obj->rem_file($filename,$base_folder);
return true;
}
return false;
}
function get_csv_download($attachments)
{
$response = new FM_Response($this->config,$this->logger);
$this->get_data_file_list($response);
if($response->isError())
{
$this->logger->LogError("get_csv_download: get_data_file_list returned error ");
echo $response->getError();
return;
}
$resp_string = $response->getResponseStr();
$arr_files = explode("\n",$resp_string);
if(empty($arr_files))
{
$error = "no submissions yet!";
$this->logger->LogError("get_csv_download: $error");
echo $error;
return;
}
header('Content-type: application/x-tar');
$downloadname = $this->formname.'-'.date("Y-m-d").'.tar.gz';
header('Content-disposition: attachment;filename='.$downloadname);
foreach($arr_files as $filename)
{
$filename = trim($filename);
if(empty($filename)){continue;}
$file_response = new FM_Response($this->config,$this->logger);
$this->get_file("$filename/n",$file_response);
$lines = explode("\n",$file_response->getResponseStr());
array_pop($lines);
array_shift($lines);
$file = join("\n", $lines);
$orig_filename = sfm_filename_no_ext($filename).'.csv';
$file = "\xEF\xBB\xBF".$file;//utf-8 BOM for MS Excel
echo sfm_targz($orig_filename,$file);
}
if(true == $attachments && NULL != $this->file_uploader)
{
$this->file_uploader->AttachFilesToDownload();
}
}
function get_data_file_list(&$response_sender)
{
$formid = $this->config->get_form_id();
$len = strlen($formid) ;
$response="";
$handle = opendir($this->getFormDataFolder());
if (!$handle)
{
$err = sprintf(_("Failed getting file list from directory: %s"),$this->config->form_file_folder);
$response_sender->addError($err);
$this->logger->LogError($err);
return false;
}
$csv_file_path="";
$this->GetCreateDataFilePath($csv_file_path);
$csv_file_name = sfm_filename_no_ext($csv_file_path);
if(empty($csv_file_name))
{
$this->logger->LogError("Error: csv_file_name is empty!");
return false;
}
$csv_file_name = str_replace("-","\\-",$csv_file_name);
while(false !== ($file = readdir($handle)) )
{
if(preg_match("/$csv_file_name(.*?)\.php/i",$file))
{
$response .="$file\n";
}
}
$response_sender->SetResponse($response);
return false;
}
function SliceDataFile(&$filename)
{
$csv_path="";
$this->GetCreateDataFilePath($csv_path);
$csv_filename = basename($csv_path);
$csv_filename = trim($csv_filename);
$this->logger->LogInfo("FM_FormDataCSVMaker: SliceDataFile filename:$filename csv_filename:$csv_filename");
if(strcasecmp($csv_filename,$filename)==0)
{
$newfilepath="";
if($this->SliceFileForDownload($newfilepath))
{
$this->logger->LogInfo("FM_FormDataCSVMaker: SliceDataFile new filename:$filename");
$filename = basename($newfilepath);
}
}
}
function get_file($val,&$response)
{
$parts = explode('/',$val);
$filename=$parts[0];
$truncate=$parts[1];
$filename = trim($filename);
if(strcasecmp($truncate,"y")==0)
{
$this->SliceDataFile($filename);
}
$response->SetNeedToRemoveHeader();
return $this->read_data_file($filename,$response);
}
function read_data_file($filename,&$response)
{
$filepath = sfm_make_path($this->getFormDataFolder(),
$filename);
return $response->load_file_contents($filepath);
}
} //FM_FormDataCSVMaker
class SecureFileMaker
{
var $signature_line;
var $file_pos;
function SecureFileMaker($signature)
{
$this->signature_line = $signature;
}
function CreateFile($filepath, $first_line)
{
$fp = fopen($filepath,"w");
if(!$fp)
{
return false;
}
$header = $this->get_header()."\n";
$first_line = trim($first_line);
$header .= $first_line."\n";
if(!fwrite($fp,$header))
{
return false;
}
$footer = $this->get_footer();
if(!fwrite($fp,$footer))
{
return false;
}
fclose($fp);
return true;
}
function get_header()
{
return "signature_line";
}
function get_footer()
{
return "$this->signature_line */ ?>";
}
function gets_backward($fp)
{
$ret_str="";
$t="";
while ($t != "\n")
{
if(0 != fseek($fp, $this->file_pos, SEEK_END))
{
rewind($fp);
break;
}
$t = fgetc($fp);
$ret_str = $t.$ret_str;
$this->file_pos --;
}
return $ret_str;
}
function AppendLine($file_path,$insert_line)
{
$fp = fopen($file_path,"r+");
if(!$fp)
{
return false;
}
$all_lines="";
$this->file_pos = -1;
fseek($fp,$this->file_pos,SEEK_END);
while(1)
{
$pos = ftell($fp);
if($pos <= 0)
{
break;
}
$line = $this->gets_backward($fp);
$cmpline = trim($line);
$all_lines .= $line;
if(strcmp($cmpline,$this->get_footer())==0)
{
break;
}
}
$all_lines = trim($all_lines);
$insert_line = trim($insert_line);
$all_lines = "$insert_line\n$all_lines";
if(!fwrite($fp,$all_lines))
{
return false;
}
fclose($fp);
return true;
}
function ReadNextLine($fp)
{
while(!feof($fp))
{
$line = fgets($fp);
$line = trim($line);
if(strcmp($line,$this->get_header())!=0 &&
strcmp($line,$this->get_footer())!=0)
{
return $line;
}
}
return "";
}
}
//http://www.clker.com/blog/2008/03/27/creating-a-tar-gz-on-the-fly-using-php/
// Computes the unsigned Checksum of a file�s header
// to try to ensure valid file
// PRIVATE ACCESS FUNCTION
function _sfm_computeUnsignedChecksum($bytestring)
{
for($i=0; $i<512; $i++)
$unsigned_chksum += ord($bytestring[$i]);
for($i=0; $i<8; $i++)
$unsigned_chksum -= ord($bytestring[148 + $i]);
$unsigned_chksum += ord(" ") * 8;
return $unsigned_chksum;
}
// Generates a TAR file from the processed data
// PRIVATE ACCESS FUNCTION
function _sfm_tarSection($Name, $Data, $information=NULL)
{
// Generate the TAR header for this file
$header .= str_pad($Name,100,chr(0));
$header .= str_pad("777",7,"0",STR_PAD_LEFT) . chr(0);
$header .= str_pad(decoct($information["user_id"]),7,"0",STR_PAD_LEFT) . chr(0);
$header .= str_pad(decoct($information["group_id"]),7,"0",STR_PAD_LEFT) . chr(0);
$header .= str_pad(decoct(strlen($Data)),11,"0",STR_PAD_LEFT) . chr(0);
$header .= str_pad(decoct(time(0)),11,"0",STR_PAD_LEFT) . chr(0);
$header .= str_repeat(" ",8);
$header .= "0";
$header .= str_repeat(chr(0),100);
$header .= str_pad("ustar",6,chr(32));
$header .= chr(32) . chr(0);
$header .= str_pad($information["user_name"],32,chr(0));
$header .= str_pad($information["group_name"],32,chr(0));
$header .= str_repeat(chr(0),8);
$header .= str_repeat(chr(0),8);
$header .= str_repeat(chr(0),155);
$header .= str_repeat(chr(0),12);
// Compute header checksum
$checksum = str_pad(decoct(_sfm_computeUnsignedChecksum($header)),6,"0",STR_PAD_LEFT);
for($i=0; $i<6; $i++) {
$header[(148 + $i)] = substr($checksum,$i,1);
}
$header[154] = chr(0);
$header[155] = chr(32);
// Pad file contents to byte count divisible by 512
$file_contents = str_pad($Data,(ceil(strlen($Data) / 512) * 512),chr(0));
// Add new tar formatted data to tar file contents
$tar_file = $header . $file_contents;
return $tar_file;
}
function sfm_targz($Name, $Data)
{
return gzencode(_sfm_tarSection($Name,$Data),9);
}
class FM_ThankYouPage extends FM_Module
{
var $page_templ;
var $redir_url;
function FM_ThankYouPage($page_templ="")
{
$this->page_templ=$page_templ;
$this->redir_url="";
}
function Process()
{
$ret = true;
if(false === $this->ext_module->FormSubmitted($this->formvars))
{
$this->logger->LogInfo("Extension Module returns false for FormSubmitted() notification");
$ret = false;
}
else
{
$ret = $this->ShowThankYouPage();
}
if($ret)
{
$this->globaldata->SetFormProcessed(true);
}
return $ret;
}
function ShowThankYouPage($params='')
{
$ret = false;
if(strlen($this->page_templ)>0)
{
$this->logger->LogInfo("Displaying thank you page");
$ret = $this->ShowPage();
}
else
if(strlen($this->redir_url)>0)
{
$this->logger->LogInfo("Redirecting to thank you URL");
$ret = $this->Redirect($this->redir_url,$params);
}
return $ret;
}
function SetRedirURL($url)
{
$this->redir_url=$url;
}
function ShowPage()
{
header("Content-Type: text/html");
echo $this->ComposeContent($this->page_templ);
return true;
}
function ComposeContent($content,$urlencode=false)
{
$merge = new FM_PageMerger();
$html_conv = $urlencode?false:true;
$tmpdatamap = $this->common_objs->formvar_mx->CreateFieldMatrix($html_conv);
if($urlencode)
{
foreach($tmpdatamap as $name => $value)
{
$tmpdatamap[$name] = urlencode($value);
}
}
$this->ext_module->BeforeThankYouPageDisplay($tmpdatamap);
if(false == $merge->Merge($content,$tmpdatamap))
{
$this->logger->LogError("ThankYouPage: merge failed");
return '';
}
return $merge->getMessageBody();
}
function Redirect($url,$params)
{
$has_variables = (FALSE === strpos($url,'?'))?false:true;
if($has_variables)
{
$url = $this->ComposeContent($url,/*urlencode*/true);
if(!empty($params))
{
$url .= '&'.$params;
}
}
else if(!empty($params))
{
$url .= '?'.$params;
$has_variables=true;
}
$from_iframe = isset($this->globaldata->session['sfm_from_iframe']) ?
intval($this->globaldata->session['sfm_from_iframe']):0;
if( $has_variables || $from_iframe )
{
$url = htmlentities($url,ENT_QUOTES,"UTF-8");
//The code below is put in so that it works with iframe-embedded forms also
//$script = "window.open(\"$url\",\"_top\");";
//$noscript = "Submitted the form successfully. Click here to redirect";
$page = <<Redirect