Click here for troubleshooting information."); define("E_CONF_ERROR_LOGGED","The error is logged."); define("E_CONF_ERROR_NOT_LOGGED","Could not log the error"); define("E_CONF_ERROR_FILE_RENAME_FAILED","Failed renaming file %s new name %s"); define("E_CONF_ERROR_MAKE_FORMDATA_FOLDER","Failed making form data folder %s"); define("E_CONF_ERROR_FORM_DATA_FOLDER_EMPTY","The name of the form data folder provided is empty!"); define("E_CONF_ERROR_WRITE_FORMDATA_FOLDER","Error creating file in the form data folder: %s"); define("E_CONF_FORM_DATA_VAR_NOT_ALLOWED","The variable %s is reserved as an internal variable. ". "This variable can't be used as a form variable"); define("E_CONF_ERROR_FORMPAGE_MERGE","Failed merging form page"); define("E_CONF_FORM_NOT_INSTALLED_TITLE","The form is not installed yet."); define("E_CONF_FORM_NOT_INSTALLED","The form is not installed yet. ". " If you uploaded the form manually, copy paste ". " the URL of the form to the Form URL box and press the ". " 'Install Form' button. It is required to Install the ". " form before you can use the form. "); define("E_CONF_FORM_KEY_NOT_SET","Form key is not set"); define("E_CONF_FORM_ID_NOT_SET","Form ID is not set"); define("E_CONF_FORM_ID_NOT_MATCH","Form ID Does not match"); define("E_CONF_FILE_NAME_NOTSET","Name of the file to be downloaded is not mentioned"); define("E_CONF_FAIL_OPEN_FILE","Failed opening file %s"); define("E_ERR_NO_FILE_UPLOAD","No file uploads present for this form"); define("E_ERR_FAIL_OPEN_UPLD_FOLDER","Failed getting list of files from upload folder(%s)"); define("E_ERR_NO_FILE_UPLOAD_OBJ_SET","File upload object is not set."); define("E_ERR_FAIL_READING_SCRIPT","Form Installer: failed reading the script."); define("E_ERR_FAIL_FIND_MARKERS","Form Installer: could not find the markers"); define("E_ERR_FAIL_GET_FILE_LIST","Failed getting file list from directory: %s"); define("E_ERR_FAIL_WRITING_TO_SCRIPT","Failed opening the script: %s for writing. ". "Please update the access permissions of the file (chmod to 777).". " You can revert the permissions back after installing the script."); define("E_VAL_REQ_FILE_INPUT","A file need to be uploaded for %s"); define("E_VAL_FILESIZE_EXCEEDED","%s: The file has exceeded the size limit %d"); define("E_VAL_EXTN_NOTALLOWED","%s: Only the following types of file extensions are allowed: %s"); define("E_VAL_SHOULD_SEL_CHECK_FAILED","You should select option %s for %s"); define("E_CONFIG_FILE_EXISTS","There exists a file with name %s. ". "Simfatic Forms needs to save configuration information in this file.". " Remove/rename the file %s and try again."); define("E_CONF_NO_FORM_FOLDER","Config Error: No Form data folder is set; but tried to access form data folder"); define("ERROR_EMAIL_BODY","Error occured in form %s.\n\n%s\n\nLog:\n%s"); define("ERROR_EMAIL_SUBJ","Error occured in form %s."); define("CONST_PHP_TAG_START","<"."?"."PHP"); define("CONST_PHP_TAG_END","?".">"); //////GlobalData////////// class FM_GlobalData { var $get_vars; var $post_vars; var $server_vars; var $files; function FM_GlobalData() { $this->get_vars =NULL; $this->post_vars =NULL; $this->server_vars =NULL; $this->files=NULL; } function GetGlobalVars() { global $HTTP_GET_VARS, $HTTP_POST_VARS, $HTTP_SERVER_VARS,$HTTP_POST_FILES; $parser_version = phpversion(); if ($parser_version <= "4.1.0") { $this->get_vars = $HTTP_GET_VARS; $this->post_vars = $HTTP_POST_VARS; $this->server_vars= $HTTP_SERVER_VARS; $this->files = $HTTP_POST_FILES; } if ($parser_version >= "4.1.0") { $this->get_vars = $_GET; $this->post_vars = $_POST; $this->server_vars= $_SERVER; $this->files = $_FILES; } } function get_post_vars() { return $this->post_vars; } function get_get_vars() { return $this->get_vars; } } /////Config///// class FM_Config { var $msg_log_enabled; var $form_submit_variable; var $form_page_code; var $error_display_variable; var $display_error_in_formpage; var $error_page_code; var $email_format_html; var $slashn; var $form_file_folder; var $installed; var $logfile_size; var $encr_key; var $form_id; var $sys_debug_mode; var $error_mail_to; var $debug_mode; function FM_Config() { $this->form_file_folder=""; $this->installed = false; $this->msg_log_enabled = true; $this->form_submit_variable ="sfm_form_submitted"; $this->form_page_code="

Error! code 104

%sfm_error_display_loc%"; $this->error_display_variable="sfm_error_display_loc"; $this->self_script_variable = "sfm_self_script"; $this->confirm_file_list_var = "sfm_file_uploads"; $this->config_update_var = "sfm_conf_update"; $this->config_update_val = "sfm_conf_update_val"; $this->config_form_id_var = "sfm_form_id"; $this->visitor_ip_var = "_sfm_visitor_ip_"; $this->submission_time_var ="_sfm_form_submision_time_"; $this->display_error_in_formpage=true; $this->error_page_code ="

Error!

%sfm_error_display_loc%"; $this->email_format_html=false; $this->slashn = "\r\n"; $this->logfile_size=5120;//In KBs $this->encr_key=""; $this->form_id=""; $this->error_mail_to=""; $this->sys_debug_mode = false; $this->debug_mode = false; } function set_encrkey($key) { $this->encr_key=$key; } function set_form_id($form_id) { $this->form_id = $form_id; } function set_error_email($email) { $this->error_mail_to = $email; } function get_form_id() { return $this->form_id; } function setFormPage($formpage) { $this->form_page_code = $formpage; } function setDebugMode($enable) { $this->debug_mode = $enable; } function getFormConfigIncludeFileName($script_path,$form_name) { $dir_name = dirname($script_path); $conf_file = $dir_name."/".$form_name."_conf_inc.php"; return $conf_file; } function getConfigIncludeSign() { return "//{__Simfatic Forms Config File__}"; } } /////Logger///// class FM_Logger { var $config; var $globaldata; var $log_file_path; var $formname; var $log_filename; var $whole_log; var $is_enabled; function FM_Logger(&$globaldata,&$config,$formname) { $this->config = &$config; $this->globaldata = &$globaldata; $this->formname = $formname; $this->log_filename=""; $this->whole_log=""; $this->is_enabled = false; } function EnableLogging($enable) { $this->is_enabled = $enable; } function CreateFileName() { $ret=false; $filename =""; if(strlen($this->log_filename)> 0) { $filename = $this->log_filename; } else if(strlen($this->config->get_form_id())>0) { $filename = $this->config->get_form_id().".log"; } else { $filename="sf_formproc.log"; } if(strlen($this->config->form_file_folder)>0) { $this->log_file_path = sfm_make_path($this->config->form_file_folder, $filename); $ret=true; } else { $this->log_file_path =""; $ret=false; } return $ret; } function LogString($string,$type) { $bret = false; $t_log = "\n"; $t_log .= $this->globaldata->server_vars['REMOTE_ADDR']."|"; $t_log .= date("Y-m-d h:i:s A|"); $t_log .= "$type| "; $string = str_replace("\n","\\n",$string); $t_log .= $string; if($this->is_enabled) { $bret = $this->writeToFile($t_log); } $this->whole_log .= $t_log; return $bret; } function print_log() { echo $this->whole_log; } function get_log() { return $this->whole_log; } function get_log_file_path() { if(strlen($this->log_file_path)<=0) { if(!$this->CreateFileName()) { return ""; } } return $this->log_file_path; } function writeToFile($t_log) { $this->get_log_file_path(); if(strlen($this->log_file_path)<=0){ return false;} $fp =0; $create_file=false; if(file_exists($this->log_file_path)) { $maxsize= $this->config->logfile_size * 1024; if(filesize($this->log_file_path) >= $maxsize) { $create_file = true; } } else { $create_file = true; } if(true == $create_file) { $fp = @fopen($this->log_file_path,"w"); } else { $fp = @fopen($this->log_file_path,"a+"); } if(!$fp){return false;} if(!fwrite($fp,$t_log)) { fclose($fp); return false; } fclose($fp); return true; } function LogError($string) { return $this->LogString($string,"error"); } function LogInfo($string) { if(false == $this->config->msg_log_enabled) { return true; } return $this->LogString($string,"info"); } } ////ErrorHandler/////////// class FM_ErrorHandler { var $logger; var $config; var $globaldata; var $formname; var $sys_error; var $disable_syserror_handling; function FM_ErrorHandler(&$logger,&$config,&$globaldata,$formname) { $this->logger = &$logger; $this->config = &$config; $this->globaldata = &$globaldata; $this->formname = $formname; $this->sys_error=""; $this->disable_syserror_handling=false; } function InstallConfigErrorCatch() { set_error_handler(array(&$this, 'sys_error_handler')); } function EnableSysErrorHandling() { $this->disable_syserror_handling = false; } function DisableSysErrorHandling() { $this->disable_syserror_handling = true; } function GetLastSysError() { return $this->sys_error; } function IsSysError() { if(strlen($this->sys_error)>0){return true;} else { return false;} } function GetSysError() { return $this->sys_error; } function sys_error_handler($errno, $errstr, $errfile, $errline) { if($errno == E_USER_NOTICE || $errno == E_NOTICE || (defined('E_STRICT') && $errno == E_STRICT) ) { return; } $this->sys_error = "Error ($errno): $errstr\n file:$errfile\nline: $errline \n\n"; if($this->disable_syserror_handling == true) { return; } $this->HandleConfigError($this->sys_error); exit; } function ShowError($error_code) { $this->DisplayError($error_code); } function ShowErrorEx($error_code,$error_extra_info) { $error_extra_info = trim($error_extra_info); $this->DisplayError($error_code."\n".$error_extra_info); } function ShowInputError($error_hash,$form_name) { $this->DisplayError("",$error_hash,$form_name); } function NeedSeperateErrorPage($error_hash) { if(null == $error_hash) { if(false === strpos($this->config->form_page_code, $this->config->error_display_variable)) { return true; } } return false; } function DisplayError($str_error,$error_hash=null,$form_name="") { $str_error = trim($str_error); $this->logger->LogError($str_error); $str_error = nl2br($str_error); $error_page=""; if(true == $this->config->display_error_in_formpage && isset($this->config->form_page_code) && strlen($this->config->form_page_code) > 0 ) { if($this->NeedSeperateErrorPage($error_hash)) { $error_page = $this->config->error_page_code; } else { $error_page = $this->config->form_page_code; } } else { $error_page = $this->config->error_page_code; } $self_script = $this->globaldata->server_vars['PHP_SELF']; $var_map = array( $this->config->error_display_variable => $str_error, $this->config->self_script_variable => $self_script ); if(null != $error_hash) { foreach($error_hash as $inpname => $inp_err) { $err_var = $form_name."_".$inpname."_errorloc"; $var_map[$err_var] = $inp_err; } } $merge = new FM_PageMerger(); if(false == $merge->Merge($error_page,$var_map)) { return false; } $strdisp = $merge->getMessageBody(); echo $strdisp; } function EmailError($error_code) { $this->logger->LogInfo("Sending Error Email To: ".$this->config->error_mail_to); $mailbody = sprintf(ERROR_EMAIL_BODY,$this->formname,$error_code,$this->logger->get_log()); $subj = sprintf(ERROR_EMAIL_SUBJ,$this->formname); @mail($this->config->error_mail_to, $subj, $mailbody, "From: $this->formname"); } function HandleConfigError($error_code,$extrainfo="") { $disp_error = "

"; $disp_error .= E_CONF_ERROR_INTERNAL; $logged = $this->logger->LogError($error_code); if($this->config->debug_mode) { $disp_error .= "
".$error_code."
".E_CONF_ERROR_TS_LINK; } else { if($logged) { $disp_error .= E_CONF_ERROR_LOGGED; } else { $disp_error .= E_CONF_ERROR_NOT_LOGGED; } $disp_error .= "
".E_CONF_ERROR_DEBUG_MODE_INFO."
".E_CONF_ERROR_TS_LINK; } $disp_error .= "

"; if(strlen($this->config->error_mail_to)>0) { $this->EmailError($error_code); } $this->DisplayError($disp_error); } } ////FormMail//////////////// class FormMail { var $globaldata; var $formvars; var $form_name; var $logger; var $config; var $error_handler; var $modules; function FormMail($formname) { $this->form_name = $formname; $this->globaldata = new FM_GlobalData(); $this->config = new FM_Config(); $this->logger = new FM_Logger($this->globaldata,$this->config,$formname); $this->error_handler = new FM_ErrorHandler($this->logger,$this->config,$this->globaldata,$formname); $this->error_handler->InstallConfigErrorCatch(); $this->modules=array(); } function GetConfigInclude() { $this->globaldata->GetGlobalVars(); if(strlen($this->form_name)<=0 ) { return ""; } $conf_file = $this->config->getFormConfigIncludeFileName( $this->globaldata->server_vars['SCRIPT_FILENAME'],$this->form_name); if(!file_exists($conf_file)) { return ""; } $conf_content = file_get_contents($conf_file); if(strlen($conf_content)<=0) { return ""; } $strsign = $this->config->getConfigIncludeSign(); if(!sfm_checkConfigFileSign($conf_content,$strsign)) { return ""; } return $conf_file; } function setEmailFormatHTML($ishtml) { $this->config->email_format_html = $ishtml; } function setFormFileFolder($folder) { $this->config->form_file_folder = $folder; } function setIsInstalled($installed) { $this->config->installed = $installed; } function setFormPage($formpage) { $this->config->setFormPage($formpage); } function setFormID($id) { $this->config->set_form_id($id); } function setFormKey($key) { $this->config->set_encrkey($key); } function EnableLogging($enable) { $this->logger->EnableLogging($enable); } function SetErrorEmail($email) { $this->config->set_error_email($email); } function SetDebugMode($enable) { $this->config->setDebugMode($enable); } function GetVars() { $this->globaldata->GetGlobalVars(); if(strcmp($this->globaldata->server_vars['REQUEST_METHOD'],'POST')==0) { $this->formvars = $this->globaldata->get_post_vars(); } else { $this->formvars = $this->globaldata->get_get_vars(); } magicQuotesRemove($this->formvars); $this->formvars[$this->config->visitor_ip_var] = $this->globaldata->server_vars['REMOTE_ADDR']; $this->formvars[$this->config->submission_time_var] = date("Y-F-d h:i:s A"); if(!isset($this->form_name) || strlen($this->form_name)==0) { $this->error_handler->HandleConfigError(E_CONF_FORM_NAME_NOT_SET,""); return false; } return true; } function addModule(&$module) { array_push_ref($this->modules,$module); } function getmicrotime() { list($usec, $sec) = explode(" ",microtime()); return ((float)$usec + (float)$sec); } function ProcessForm() { $timestart = $this->getmicrotime(); if(false == $this->GetVars()) { $this->logger->LogInfo("GetVars() Failed"); return false; } $this->logger->LogInfo("Processing modules"); $N = count($this->modules); for($i=0;$i<$N;$i++) { $mod = &$this->modules[$i]; $mod->Init($this->config,$this->formvars, $this->logger,$this->globaldata, $this->error_handler,$this->form_name); } for($i=0;$i<$N;$i++) { $mod = &$this->modules[$i]; $continue = true; $mod->Process($continue); if(!$continue){break;} } for($i=0;$i<$N;$i++) { $mod = &$this->modules[$i]; $mod->Destroy(); } $timetaken = $this->getmicrotime()-$timestart; $this->logger->LogInfo("Completed form processing timetaken:$timetaken"); return true; } function showVars() { foreach($this->formvars as $name => $value) { echo "$name $value
"; } } } class FM_Module { var $config; var $formvars; var $logger; var $globaldata; var $error_handler; var $formname; function FM_Module() { } function Init(&$config,$formvars,&$logger,&$globaldata,&$error_handler,$formname) { $this->config = &$config; $this->formvars = &$formvars; $this->logger = &$logger; $this->globaldata =&$globaldata; $this->error_handler = &$error_handler; $this->formname = $formname; } function Process(&$continue) { return true; } function Destroy() { } function getFormDataFolder() { if(strlen($this->config->form_file_folder)<=0) { $this->error_handler->HandleConfigError(E_CONF_NO_FORM_FOLDER); exit; } return $this->config->form_file_folder; } } class FM_FormPageRenderer extends FM_Module { function FM_FormPageRenderer() { } function Process(&$continue) { if($this->NeedDisplayFormPage()) { $this->logger->LogInfo("Displaying form page"); $this->DisplayFormPage(); $continue=false; } else { $continue=true; } } function NeedDisplayFormPage() { if(false == isset($this->formvars[$this->config->form_submit_variable])) { return true; } return false; } function DisplayFormPage() { $merge = new FM_PageMerger(); $self_script = $this->globaldata->server_vars['PHP_SELF']; $var_map = array( $this->config->error_display_variable => "", $this->config->self_script_variable => $self_script ); if(false == $merge->Merge($this->config->form_page_code,$var_map)) { $this->error_handler->HandleConfigError(E_CONF_ERROR_FORMPAGE_MERGE); return false; } $strdisp = $merge->getMessageBody(); echo $strdisp; } } class FM_RefFileDispatcher extends FM_Module { var $ref_files; var $ref_file_variable; function FM_RefFileDispatcher() { $this->ref_files = array(); $this->ref_file_variable="sfm_get_ref_file"; } function AddRefferedFile($filename,$code) { $this->ref_files[$filename] = $code; } function Process(&$continue) { if($this->NeedReturnRefFile()) { $continue=false; $this->ReturnRefferedFile(); } else { $continue=true; } } function ReturnRefferedFile() { $filename = $this->formvars[$this->ref_file_variable]; if(!$this->IsRefferedFilePresent($filename)) { $this->logger->LogInfo("File dispatcher: File not found: $filename "); header("HTTP/1.0 404 Not Found"); } else { $this->logger->LogInfo("dispatching file: $filename "); echo $this->getRefferedFile($filename); } } function IsRefferedFilePresent($filename) { if(isset($this->ref_files[$filename])) { return true; } else { return false; } } function NeedReturnRefFile() { if(isset($this->formvars[$this->ref_file_variable])) { return true; } return false; } function getRefferedFile($filename) { return $this->ref_files[$filename]; } } 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(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); } return $ret; } function SetRedirURL($url) { $this->redir_url=$url; } function ShowPage() { $content = $this->page_templ; $merge = new FM_PageMerger(); $tmpdatamap = $this->formvars; convert_html_entities_in_formdata("",$tmpdatamap); $page = "

Error!

"; $ret = true; if(false == $merge->Merge($content,$tmpdatamap)) { $this->logger->LogError("ThankYouPage: merge failed"); $ret = false; } $page = $merge->getMessageBody(); header("Content-Type: text/html"); echo $page; return $ret; } function Redirect($url) { header("Location: $url"); exit; } }//config class FM_FileUploadHandler extends FM_Module { var $loaded_files; var $dont_delete_files; function FM_FileUploadHandler() { $this->loaded_files = array(); $this->upload_fields = array(); $this->dont_delete_files=false; } function DontDeleteFiles($dont_delete) { $this->dont_delete_files = $dont_delete; } function SetFileUploadFields($fields) { foreach($fields as $f) { array_push($this->upload_fields,$f); } } function CopyFile_Prevent_Overwrite($sourcefile,$destfile) { if(file_exists($destfile)) { $i=1; $path_parts = pathinfo($destfile); $barename = basename($path_parts["basename"],".".$path_parts["extension"]); do { $destfile = $path_parts["dirname"]."/". $barename."$i.".$path_parts["extension"]; $i++; } while(file_exists($destfile)); } if(!copy($sourcefile,$destfile)) { $this->logger->LogError("CopyFile_Prevent_Overwrite file copy failed. ". "source: $sourcefile dest:$destfile"); } return $destfile; } function get_tmpuploadfolder() { return sfm_make_path($this->getFormDataFolder(),"t_uploads_".$this->formname); } function get_uploadfiles_folder() { return sfm_make_path($this->getFormDataFolder(),"uploads_".$this->formname); } function Process(&$continue) { if(isset($this->formvars[$this->config->confirm_file_list_var])) { $this->LoadFromInputVar(); } else { $this->LoadUploadedFiles(); } $continue=true; } function LoadUploadedFiles() { $upld_folder = $this->get_tmpuploadfolder(); $this->logger->LogInfo("File Upload handler: loading uploaded files to folder $upld_folder"); if(!file_exists($upld_folder) && !mkdir($upld_folder)) { $this->logger->LogError("File Upload handler: failed creating folder: $upld_folder"); return false; } foreach($this->upload_fields as $filefield) { $tmp_filepath = $this->globaldata->files[$filefield]['tmp_name']; if(is_uploaded_file($tmp_filepath)) { $filename = $this->globaldata->files[$filefield]['name']; $upld_path = $upld_folder."/".$filename; $upld_path = $this->CopyFile_Prevent_Overwrite($tmp_filepath, $upld_path); $this->logger->LogInfo("File Upload handler: loaded file from $tmp_filepath to $upld_path."); $mimetype = $this->globaldata->files[$filefield]["type"]; $this->loaded_files[] = array("input_name"=>$filefield, "loaded_file"=>$upld_path, "mime_type"=>$mimetype); }//if }//foreach return true; } function IsFieldFileUpload($fieldname) { foreach($this->loaded_files as $fileobj) { if($fileobj['input_name'] == $fieldname) { return true; } } return false; } function GetUploadedFileName($fieldname) { foreach($this->loaded_files as $fileobj) { if($fileobj['input_name'] == $fieldname && isset($fileobj['saved_file'])) { $this->logger->LogError("File Upload handler: GetUploadedFileName".$fileobj['saved_file']); return basename($fileobj['saved_file']); } } return ''; } function SaveUploadedFile() { $upload_folder = $this->get_uploadfiles_folder(); $this->logger->LogInfo("File Upload handler: saving ". "uploaded files to folder: $upload_folder"); if(!file_exists($upload_folder) && !mkdir($upload_folder)) { $this->logger->LogError("File Upload handler: ". "failed creating folder: $upload_folder"); return false; } $nFiles = count($this->loaded_files); for($f=0;$f<$nFiles;$f++) { $save_path = $upload_folder."/". basename($this->loaded_files[$f]['loaded_file']); $this->logger->LogInfo("File Upload handler: ". "saving uploaded file: $save_path"); $this->loaded_files[$f]['saved_file'] = $this->CopyFile_Prevent_Overwrite($this->loaded_files[$f]['loaded_file'], $save_path); $this->logger->LogError("File Upload handler: saved path".$this->loaded_files[$f]['saved_file']); } return true; } function LoadFromInputVar() { $varname = $this->config->confirm_file_list_var; if(!isset($this->formvars[$varname])) { $this->logger->LogError("File Upload handler: confirm_file_list_var is not set for LoadFromInputVar()"); return false; } $upld_val = $this->formvars[$varname]; $upld_folder = $this->get_tmpuploadfolder(); $fileinfos = explode('/',$upld_val); foreach($fileinfos as $fobj) { $fobjinfo = explode('|',$fobj); $inputname = isset($fobjinfo[0])?$fobjinfo[0]:""; $file_name = isset($fobjinfo[1])?$fobjinfo[1]:""; $mime_type = isset($fobjinfo[2])?$fobjinfo[2]:""; if(strlen($inputname)<= 0 || strlen($file_name)<= 0 || strlen($mime_type)<= 0) { $this->logger->LogError("File Upload handler: wrong confirm_file_list_var vaue: $upld_val"); return false; } $inputname = urldecode($inputname); $file_name = urldecode($file_name); $mime_type = urldecode($mime_type); $this->logger->LogInfo("File Upload handler: re-created uploaded file list: $file_name"); $file_path = $upld_folder."/".$file_name; $this->loaded_files[] = array("input_name"=>$inputname, "loaded_file"=>$file_path, "mime_type"=>$mimetype); } } function CreateUploadFilesVar() { $val_uploaded=""; foreach($this->loaded_files as $fileobj) { $filename = basename($fileobj['loaded_file']); $val_uploaded .= urlencode($fileobj['input_name'])."|"; $val_uploaded .= urlencode($filename)."|"; $val_uploaded .= urlencode($fileobj['mime_type']); $val_uploaded .= "/"; } $val_uploaded = rtrim($val_uploaded,"/"); $this->logger->LogInfo("File Upload handler: created upload files var: $val_uploaded"); return CreateHiddenInput($this->config->confirm_file_list_var,$val_uploaded); } function DeleteLoadedFiles() { foreach($this->loaded_files as $fileobj) { unlink($fileobj['loaded_file']); } } function AttachFiles(&$mailer) { foreach($this->loaded_files as $fileobj) { $mailer->AttachFile($fileobj['loaded_file'],$fileobj['mime_type']); }//foreach } function Destroy() { if(!$this->dont_delete_files) { $this->DeleteLoadedFiles(); } } } 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 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 { $fid = $this->config->get_form_id(); if(strlen($fid)<=0) return false; $this->formdata_file = sfm_make_path($this->config->form_file_folder, $fid.".csv"); } $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 CreateCSVFile() { $fname = $this->formdata_file; $fp = fopen($fname,"w"); if(!$fp) { $this->error_handler->HandleConfigError("Failed creating csv file: $fname"); return false; } $header = $this->getCSVHeader(); $ret =false; if(fwrite($fp,$header)) { $this->logger->LogInfo("csv maker: created csv file"); $ret = true; } else { $this->logger->LogInfo("csv maker: failed creating csv file"); } fclose($fp); 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() { $fp = fopen($this->formdata_file,"r"); if(!$fp) { return false; } $header = fgets($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) { $ret_val =""; if(NULL != $this->file_uploader && $this->file_uploader->IsFieldFileUpload($var_name)) { $ret_val = $this->file_uploader->GetUploadedFileName($var_name); } else { $value = $this->formvars[$var_name]; if(is_array($value)) { $val_str=""; foreach($value as $v) { $val_str .= "$v "; } $ret_val = $val_str; } else { $ret_val = $value; } } return $ret_val; } 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 = ""; foreach($this->csv_file_variables as $var_name) { $value = $this->GetCSVFieldValue($var_name); if(preg_match("/[\s\n\,\r]/i",$value)) { $value = str_replace("\"","\"\"",$value); $value = "\"$value\""; } $data_line .= $value; $data_line .= $this->csv_seperator; } $data_line = rtrim($data_line,$this->csv_seperator); $data_line .= $this->config->slashn; $this->logger->LogInfo("csv maker: writing to csv file $this->formdata_file"); $fp = fopen($this->formdata_file,"a+"); if(!$fp) { $fname = $this->formdata_file; $this->error_handler->HandleConfigError(E_CONF_COULD_NOT_OPEN_OUTPUT_DATA_FILE, " filename: $fname"); return false; } if(fwrite($fp,$data_line)) { $this->logger->LogInfo("csv maker: Updated CSV file"); $ret = true; } else { $this->logger->LogError("csv maker: Error updating CSV file"); $ret = false; } fclose($fp); return $ret; } } ////////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); } 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->formvars; if(true == $this->config->email_format_html) { convert_html_entities_in_formdata("",$tmpdatamap); } $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->logger->LogInfo("mail composer: sending text mail"); $this->mailer->SendTextMail($from,$to, $this->message_subject, $this->message_body); } else { $this->logger->LogInfo("mail composer: sending HTML mail"); $this->mailer->SendHtmlMail($from,$to, $this->message_subject, $this->message_body); } } }// ////////AutoResponseSender///////////// class FM_AutoResponseSender extends FM_ComposedMailSender { var $subject; var $template; var $namevar; var $emailvar; var $from; function FM_AutoResponseSender($subj="",$templ="",$from="") { $this->subject = $subj; $this->template= $templ; $this->namevar= ""; $this->emailvar= ""; $this->from = $from; } function SetToVariables($name_var,$email_var) { $this->namevar= $name_var; $this->emailvar= $email_var; } function SendAutoResponse() { $this->InitMailer(); $this->ComposeMessage($this->subject,$this->template); $name_val = $this->formvars[$this->namevar]; $email_val = $this->formvars[$this->emailvar]; $to_var = "$name_val<$email_val>"; $this->logger->LogInfo("sending auto response to: $to_var"); $this->SendMail($this->from,$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; } } ////////FormDataSender///////////// class FM_FormDataSender extends FM_ComposedMailSender { var $mail_subject; var $mail_template; var $dest_list; var $mail_from; var $file_upload; 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; } function SetFileUploader(&$fileUploader) { $this->file_upload = &$fileUploader; } function AddToAddr($toaddr) { array_push($this->dest_list,$toaddr); } function SendFormData() { $this->InitMailer(); $this->ComposeMessage($this->mail_subject, $this->mail_template); if(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 $to_address) { $this->logger->LogInfo("sending form data to: $to_address"); $this->SendMail($this->mail_from, $to_address); } } function Process(&$continue) { if(strlen($this->mail_template)<=0|| count($this->dest_list)<=0) { return false; } $continue = true; $this->SendFormData(); return true; } } ////////Mailer///////////////////// class FM_Mailer { var $config; var $attachments; function FM_Mailer(&$config) { $this->config = &$config; $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 SendMail($from,$to,$subject,$mailbody,$htmlformat) { $hdrs = array( 'From' => $from, 'Sender' => $from, 'Subject' => $subject, 'To' => $to ); $crlf = "\n"; $mime = new Mail_mime($crlf); if(true == $htmlformat) { $mime->setHTMLBody($mailbody); $mime->setTxtBody(strip_tags($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' )); $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); } } $mail_object = &Mail::factory('mail',$params); if($mail_object) { $mail_object->send($to, $headers, $body); } } function sanitizeHeaders(&$headers) { foreach ($headers as $key => $value) { $headers[$key] = preg_replace('=((||0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $value); } } function AttachFile($filepath,$type) { $this->attachments[]=array('filepath'=>$filepath,'mime_type'=>$type); } } ////////ConfirmPage///////////////// class FM_ConfirmPage extends FM_Module { var $formdata_replacement_variable; var $confirm_submit_variable_name; var $templ_page; var $uploader; function FM_ConfirmPage($templ="") { $this->formdata_replacement_variable = "fwizformdata"; $this->confirm_submit_variable_name = "sfm_confirm"; $this->templ_page=$templ; $this->confirm_button_label = "Confirmed"; } function SetConfirmButtonLabel($label) { $this->confirm_button_label = $label; } function SetFileUploader(&$upldr) { $this->uploader = &$upldr; } function Process(&$continue) { if(strlen($this->templ_page)<=0 || false ==$this->NeedShowFormDataConfirmPage()) { $continue=true; return true; } $continue = false; return $this->ShowConfirmPage(); } function NeedShowFormDataConfirmPage() { if(isset($this->formvars[$this->confirm_submit_variable_name])) { return false; } else { return true; } } function ShowConfirmPage() { $this->logger->LogInfo("showing confirmation page"); 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( E_CONF_FORM_DATA_VAR_NOT_ALLOWED, $this->formdata_replacement_variable); return false; } $action = $this->globaldata->server_vars['PHP_SELF']; $ret_map = array_pad($this->formvars,count($this->formvars),0); $str_form_data_map = "
"; foreach($this->formvars as $name => $value) { if(strcasecmp($name,"submit") !=0 && strcasecmp($name,$this->config->visitor_ip_var) !=0 && strcasecmp($name,$this->config->submission_time_var) != 0 ) { if(is_array($value)) { foreach($value as $objval) { $str_form_data_map .= CreateHiddenInput("$name"."[]",$objval); } } else { $str_form_data_map .= CreateHiddenInput($name,$value); } }//if } if(isset($this->uploader)) { $str_form_data_map .= $this->uploader->CreateUploadFilesVar(); $this->uploader->DontDeleteFiles(true); } $str_form_data_map .= " "; $str_form_data_map .= "
"; $ret_map[$this->formdata_replacement_variable] = $str_form_data_map; return true; } function ShowFormDataConfirmPage(&$datamap) { if(strlen($this->templ_page)<=0) { return false; } convert_html_entities_in_formdata($this->formdata_replacement_variable, $datamap); $merger = new FM_PageMerger(); $ret = true; if(false == $merger->Merge($this->templ_page,$datamap)) { $this->logger->LogError("ConfirmPage: merge failed"); $ret = false; } header("pragma: no-cache"); header("cache-control: no-cache"); header("Content-Type: text/html"); echo $merger->getMessageBody(); return $ret; } } ///////Form Installer//////////////////// class FM_FormInstaller extends FM_Module { var $formdata_folder; var $formdata_folder_rel; var $error_str; var $response; var $encr_response; var $extra_headers; var $csv_maker; var $file_uploader; function FM_FormInstaller() { $this->formdata_folder=""; $this->formdata_folder_rel=""; $this->error_str=""; $this->response=""; $this->encr_response=true; $this->extra_headers = array(); $this->csv_maker=NULL; $this->file_uploader=NULL; } function SetCSVMaker(&$csvmkr) { $this->csv_maker = &$csvmkr; } function SetFileUploader(&$uploader) { $this->file_uploader = &$uploader; } function addError($error) { $this->error_str .= $error; $this->error_str .= "\n"; } function straighten_val($val) { $ret = str_replace("\n","\\n",$val); return $ret; } function appendResponse($name,$val) { $this->response .= "$name: ".$this->straighten_val($val); $this->response .= "\n"; } function appendResultResponse($is_success) { if($is_success) { $this->appendResponse("result","success"); } else { $this->appendResponse("result","failed"); } } function AddResponseHeader($name,$val) { $this->extra_headers[$name]=$val; } function ShowResponse() { $err=false; if($this->error_handler->IsSysError()) { $this->addError($this->error_handler->GetSysError()); } if(strlen($this->error_str)>0) { $err=true; $this->appendResponse("error",$this->error_str); $this->AddResponseHeader('Pragma','sforms-error'); $log_str = sprintf("FM_FormInstaller: reporting error:%s",$this->error_str); $this->logger->LogError($log_str); } $resp=""; if(($this->encr_response || true == $err) && (false == $this->config->sys_debug_mode)) { $this->AddResponseHeader('Content-type','application/sforms-e'); $resp = $this->Encrypt($this->response); } else { $resp = $this->response; } $this->AddResponseHeader('pragma','no-cache'); $this->AddResponseHeader('cache-control','no-cache'); $this->AddResponseHeader('Content-Length',strlen($resp)); foreach($this->extra_headers as $hdr_key => $hdr_val) { $this->logger->LogInfo("adding header $hdr_key => $hdr_val"); header("$hdr_key: $hdr_val"); } print($resp); if(true == $this->config->sys_debug_mode) { $this->logger->print_log(); } } function Decrypt($str) { //$blowfish = new Crypt_Blowfish($this->config->encr_key); $blowfish =& Crypt_Blowfish::factory('ecb'); $blowfish->setKey($this->config->encr_key); $bin_data = pack("H*",$str); $decr_str = $blowfish->decrypt($bin_data); if(PEAR::isError($decr_str)) { $this->logger->LogError(" decrypt error: ".$decr_str->getMessage()); return ""; } $decr_str = trim($decr_str); return $decr_str; } function Encrypt($str) { //echo " Encrypt $str "; //$blowfish = new Crypt_Blowfish($this->config->encr_key); $blowfish =& Crypt_Blowfish::factory('ecb'); $blowfish->setKey($this->config->encr_key); $encr = $blowfish->encrypt($str); $retdata = bin2hex($encr); return $retdata; } function Process(&$continue) { $continue=true; $globals = new FM_GlobalData(); $globals->GetGlobalVars(); if(isset($globals->post_vars[$this->config->config_update_var]) ) { $this->logger->LogInfo("FM_FormInstaller: config_update_var is set"); $this->error_handler->DisableSysErrorHandling(); $continue=false; if($this->ValidateConfigInput()) { $this->ProcessConfigUpdate(); } else { $this->ShowResponse(); } $this->error_handler->EnableSysErrorHandling(); } else { if(false == $this->config->installed) { $continue=false; $this->ShowFormNotInstalled(); } } } function ValidateConfigInput() { $ret=false; if(!isset($this->config->encr_key) || strlen($this->config->encr_key)<=0) { $this->addError(E_CONF_FORM_KEY_NOT_SET); } else if(!isset($this->config->form_id) || strlen($this->config->form_id)<=0) { $this->addError(E_CONF_FORM_ID_NOT_SET); } else if(!isset($this->globaldata->post_vars[$this->config->config_form_id_var])) { $this->addError(E_CONF_FORM_ID_NOT_SET); } else { $form_id = $this->globaldata->post_vars[$this->config->config_form_id_var]; $form_id = $this->Decrypt($form_id); if(strcmp($form_id,$this->config->form_id)!=0) { $this->addError(E_CONF_FORM_ID_NOT_MATCH); } else { $this->logger->LogInfo("FM_FormInstaller:ValidateConfigInput succeeded"); $ret=true; } } return $ret; } function ProcessConfigUpdate() { $cmd = $this->globaldata->post_vars[$this->config->config_update_var]; $this->logger->LogInfo("ProcessConfigUpdate: command $cmd"); $cmd = $this->Decrypt($cmd); $this->logger->LogInfo("ProcessConfigUpdate: command decrypted $cmd"); $val = ""; if(isset($this->globaldata->post_vars[$this->config->config_update_val])) { $val = $this->globaldata->post_vars[$this->config->config_update_val]; $val = $this->Decrypt($val); } $this->logger->LogInfo("ProcessConfigUpdate: $cmd:$val"); $this->process_command($cmd,$val); $this->ShowResponse(); } function ShowFormNotInstalled() { $this->logger->LogInfo("FM_FormInstaller: showing form not installed"); $this->DisplayError(E_CONF_FORM_NOT_INSTALLED_TITLE,E_CONF_FORM_NOT_INSTALLED); } function DisplayError($title,$error_str) { echo "$title

$title

$error_str"; } function process_command($cmd,$val) { switch($cmd) { case "qry_install": { $this->QryInstall($val); } break; case "update_folder": { $this->UpdateFolder($val); } break; case "data_file_list": { $this->get_data_file_list(); } break; case "get_file": { if(strlen($val)<=0) { $this->addError(E_CONF_FILE_NAME_NOTSET); } else { $this->get_file($val); } } break; case "rem_file": { if(strlen($val)<=0) { $this->addError(E_CONF_FILE_NAME_NOTSET); } else { $this->rem_file($val); } } break; case "log_file": { $this->get_log_file(); } break; case "get_attachment_list": { $this->get_attachment_list(); } break; case "get_attachment": { if(strlen($val)<=0) { $this->addError(E_CONF_FILE_NAME_NOTSET); } else { $this->get_attachment($val); } } break; case "ping": { $this->Ping(); } break; }//switch($cmd) } function Ping() { $this->logger->LogInfo("FM_FormInstaller: Ping"); $installed="no"; if(true == $this->config->installed) { $installed="yes"; } $this->appendResponse("is_installed",$installed); } function QryInstall($folder_proposed) { $formdata_folder = ""; $this->logger->LogInfo("FM_FormInstaller: QryInstall"); if(true == $this->config->installed) { $this->logger->LogInfo("FM_FormInstaller: QryInstall already installed."); } else { if(!isset($folder_proposed) || strlen($folder_proposed)<=0) { $root_folder = $this->get_root_path(); $this->logger->LogInfo("FM_FormInstaller: QryInstall root_folder: $root_folder"); $formdata_folder = sfm_make_path($root_folder,"formdata"); } else { $formdata_folder = $folder_proposed; } } if(strlen($formdata_folder)>0) { $this->appendResponse("folder",$formdata_folder); $result = $this->try_make_formdata_folder($formdata_folder); $this->appendResultResponse($result); } else { $this->appendResponse("error_code","unknown"); $this->logger->LogError("FM_FormInstaller: QryInstall: formdata_folder value is empty."); } } function UpdateFolder($data_folder) { $success = false; $this->logger->LogInfo("FM_FormInstaller: UpdateFolder $data_folder"); if(strlen($data_folder)<=0) { $this->addError(E_CONF_ERROR_FORM_DATA_FOLDER_EMPTY); } else { if($this->try_make_formdata_folder($data_folder)) { if($this->update_script_config($data_folder)) { $success = true; $this->config->form_file_folder = $this->formdata_folder_rel; $this->logger->LogInfo("installed the form:$this->formname ". "Form data folder: $this->formdata_folder_rel"); } } else { $this->logger->LogInfo("failed updating the folder"); } } $this->appendResultResponse($success); } function get_data_file_list() { $formid = $this->config->get_form_id(); $len = strlen($formid) ; $this->response=""; $this->logger->LogInfo("FM_FormInstaller: getting data file list"); $handle = opendir($this->getFormDataFolder()); if (!$handle) { $err = sprintf(E_ERR_FAIL_GET_FILE_LIST,$this->config->form_file_folder); $this->addError($err); return; } while(false !== ($file = readdir($handle)) ) { $formid_tmp = str_replace("-","\\-",$formid); if(preg_match("/$formid_tmp(.*?)\.csv/i",$file)) { $this->response .="$file\n"; } } } function get_attachment_list() { if(is_null($this->file_uploader)) { $this->addError(E_ERR_NO_FILE_UPLOAD_OBJ_SET); return false; } $upload_folder = $this->file_uploader->get_uploadfiles_folder(); $this->logger->LogInfo("get_attachment_list : upload_folder is $upload_folder"); $handle = opendir($upload_folder); if (!$handle) { $err = sprintf(E_ERR_FAIL_GET_FILE_LIST,$upload_folder); $this->addError($err); return false; } while(false !== ($file = readdir($handle)) ) { if ($file != "." && $file != "..") { $this->response .="$file\n"; } } return true; } function SliceDataFile(&$filename) { $csv_path=""; $this->csv_maker->GetCreateDataFilePath($csv_path); $csv_filename = basename($csv_path); $csv_filename = trim($csv_filename); $this->logger->LogInfo("FM_FormInstaller: SliceDataFile filename:$filename csv_filename:$csv_filename"); if(strcasecmp($csv_filename,$filename)==0) { $newfilepath=""; if($this->csv_maker->SliceFileForDownload($newfilepath)) { $this->logger->LogInfo("FM_FormInstaller: SliceDataFile new filename:$filename"); $filename = basename($newfilepath); } } } function get_log_file() { $log_file_path=$this->logger->get_log_file_path(); $this->logger->LogInfo("FM_FormInstaller: getting log file log_file_path:$log_file_path"); $logfile_name=basename($log_file_path); return $this->read_data_file($logfile_name); } function get_attachment($filename) { if(is_null($this->file_uploader)) { $this->addError(E_ERR_NO_FILE_UPLOAD_OBJ_SET); return false; } $upload_folder = $this->file_uploader->get_uploadfiles_folder(); $att_path = sfm_make_path($upload_folder,$filename); return $this->load_file_contents($att_path); } function rem_file($val) { $parts = explode('/',$val); $filename=$parts[0]; $is_attachment='n'; if(isset($parts[1])) { $is_attachment=$parts[1]; } $this->logger->LogInfo("FM_FormInstaller: rem_file $filename"); $base_folder = $this->getFormDataFolder(); if($is_attachment == 'a') { $this->logger->LogInfo("FM_FormInstaller: rem_file - is attachment"); if(is_null($this->file_uploader)) { $this->logger->LogError("FM_FormInstaller: rem_file file_uploader not set"); $this->addError(E_ERR_NO_FILE_UPLOAD_OBJ_SET); return false; } $base_folder = $this->file_uploader->get_uploadfiles_folder(); } $filename = trim($filename); if(strlen($filename)>0) { $filepath = sfm_make_path($base_folder,$filename); $success=false; if(unlink($filepath)) { $this->appendResponse("result","success"); $this->logger->LogInfo("FM_FormInstaller: rem_file removed file $filepath"); $success=true; } $this->appendResultResponse($success); } } function read_data_file($filename) { $filepath = sfm_make_path($this->getFormDataFolder(), $filename); return $this->load_file_contents($filepath); } function load_file_contents($filepath) { $filename = basename($filepath); $this->encr_response=false; $this->logger->LogInfo("load_file_contents filepath: $filepath"); $fp = fopen($filepath,"r"); if(!$fp) { $err = sprintf(E_CONF_FAIL_OPEN_FILE,$filepath); $this->addError($err); return false; } $filesize = filesize($filepath); $contents = fread($fp,$filesize); $this->AddResponseHeader('Content-Disposition',"attachment; filename=\"$filename\""); $this->response = $contents; fclose($fp); return true; } function get_file($val) { $parts = explode('/',$val); $filename=$parts[0]; $truncate=$parts[1]; $filename = trim($filename); $this->logger->LogInfo("FM_FormInstaller: get_file $filename truncate $truncate"); if(!is_null($this->csv_maker) && strcasecmp($truncate,"y")==0) { $this->SliceDataFile($filename); } return $this->read_data_file($filename); } function try_make_formdata_folder($folder_path) { $this->logger->LogInfo(" try_make_formdata_folder $folder_path"); return $this->make_formdata_folder($folder_path); } function update_script_config($formdata_folder) { $strconf = $this->get_conf_string($formdata_folder); $conf_file_content = CONST_PHP_TAG_START; $conf_file_content .= "\n"; $conf_file_content .= $this->config->getConfigIncludeSign()."\n"; $conf_file_content .= $strconf; $conf_file_content .= CONST_PHP_TAG_END; $conf_file_content .= "\n"; $conf_file_name = $this->config->getFormConfigIncludeFileName( $this->globaldata->server_vars['SCRIPT_FILENAME'],$this->formname); $this->logger->LogInfo(" Updating config file $conf_file_name "); if(!$this->checkExistingConfigFile($conf_file_name)) { $basename = basename($conf_file_name); $error_str = sprintf(E_CONFIG_FILE_EXISTS,$conf_file_name,$basename); $this->addError($error_str); return false; } return $this->update_script($conf_file_name,$conf_file_content); } function checkExistingConfigFile($conf_file) { $bret = true; if(file_exists($conf_file)) { $conf_content = file_get_contents($conf_file); $strsign = $this->config->getConfigIncludeSign(); $bret = sfm_checkConfigFileSign($conf_content,$strsign); } return $bret; } function get_conf_string($formdata_folder) { $strret = "\n\$formmailobj->setFormFileFolder('$formdata_folder');". "\n\$formmailobj->setIsInstalled(true);\n"; return $strret; } function get_root_path() { $script_url = $this->globaldata->server_vars['SCRIPT_NAME']; $script_file_path = $this->globaldata->server_vars['SCRIPT_FILENAME']; $this->logger->LogInfo("script_url $script_url\n script_file_path $script_file_path"); $url_parts = split('/',$script_url); $path_parts = split('[/\\]',$script_file_path); $nu = count($url_parts); $np = count($path_parts); for($i=0;$i<$nu;$i++) { $iu = $nu-$i-1; $ip = $np-$i-1; if(strcasecmp($url_parts[$iu],$path_parts[$ip])!=0) { break; } } $arr_root_path = array_slice($path_parts,0,$np - $i-1); $root_path = implode("/",$arr_root_path); return $root_path; } function make_formdata_folder($folder) { if(!file_exists($folder)) { if(!@mkdir($folder)) { $this->logger->LogInfo(" mkdir $folder failed"); $error_str = sprintf(E_CONF_ERROR_MAKE_FORMDATA_FOLDER,$folder); $this->addError($error_str); return false; } else { $this->logger->LogInfo(" mkdir $folder succeeded"); } } if(!$this->test_folder_write($folder)) { $this->logger->LogInfo(" test_folder_write $folder failed"); $error_str = sprintf(E_CONF_ERROR_WRITE_FORMDATA_FOLDER,$folder); $this->addError($error_str); return false; } else { $this->logger->LogInfo(" test_folder_write $folder succeeded"); } return true; } function test_folder_write($folder) { $file_path = sfm_make_path($folder,$this->formname.".log"); $i=1; while(file_exists($file_path) && $i < 100) { $file_path = sfm_make_path($folder,$this->formname."$i.log"); $i++; } if($i>=100){ return false; } $fp = @fopen($file_path,"w"); if(!$fp) { return false; } $data_line ="Form processor installed."; if(!fwrite($fp,$data_line)) { fclose($fp); return false; } fclose($fp); $read_back = file_get_contents($file_path); $ret=true; if(strcmp($read_back,$data_line) != 0) { $ret=false; } unlink($file_path); return true; } function find_relative_path($htmlpath,$scriptpath) { $html_parts = split("[/\\]",$htmlpath); $script_parts = split("[/\\]",$scriptpath); $nph = count($html_parts); $nps = count($script_parts); for($i=0; $i < $nph && $i<$nps;$i++) { if(strcasecmp($html_parts[$i],$script_parts[$i]) !=0) { break; } } $common_idx = $i-1; $rel_path=""; for($i=$common_idx+1;$i<$nph-1;$i++) { $rel_path .="../"; } if(strlen($rel_path)<=0) { $rel_path="./"; } $child_folders = array_slice($script_parts,$common_idx+1); $child_path = implode("/",$child_folders); $rel_path = $rel_path.$child_path; return $rel_path; } function update_script($script_path,$code) { $fp = @fopen($script_path,"w"); if(!$fp) { $this->logger->LogInfo("update_script: failed updating script "); $err = sprintf(E_ERR_FAIL_WRITING_TO_SCRIPT,$script_path); $this->addError($err); return false; } $bret = true; if(!fwrite($fp,$code)) { $bret = false; } $this->logger->LogInfo("update_script: updated the script "); fclose($fp); return $bret; } } ///////PageMerger//////////////////// class FM_PageMerger { var $message_body; function FM_PageMerger() { $this->message_body=""; } function Merge($content,$variable_map) { $this->message_body = $content; $N = 0; $m = preg_match_all("/%([\w]*)%/", $content,$matches,PREG_PATTERN_ORDER); if($m > 0 || count($matches) > 1) { $N = count($matches[1]); } for($i=0;$i<$N;$i++) { $val = ""; $key = $matches[1][$i]; if(isset($variable_map[$key])) { if(is_array($variable_map[$key])) { $val = implode(",",$variable_map[$key]); } else { $val = $variable_map[$key]; } } else if(strlen($key)<=0) { $val ='%'; } $this->message_body = str_replace($matches[0][$i],$val,$this->message_body); } return(strlen($this->message_body)>0?true:false); } function getMessageBody() { return $this->message_body; } } ///////Validator////////////////////// class ValidatorObj { var $variable_name; var $validator_string; var $error_string; var $condition; } class FM_FormValidator extends FM_Module { var $validator_array; var $errors; var $show_all_errors_together; var $error_hash; function FM_FormValidator() { $this->validator_array = array(); $this->show_all_errors_together=true; $this->error_hash = array(); } 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) { if(false == $this->ValidateForm($this->formvars)) { $continue=false; $this->error_handler->ShowInputError($this->error_hash,$this->formname); return false; } else { $this->logger->LogInfo("Validations succeeded"); $continue=true; } } function ValidateForm($form_variables) { $bret = true; $error_string=""; $error_to_display = ""; $vcount = count($this->validator_array); $this->logger->LogInfo("Validating form data: number of validations: $vcount" ); foreach($this->validator_array as $val_obj) { if(!$this->ValidateObject($val_obj,$form_variables,$error_string)) { $bret = false; $this->error_hash[$val_obj->variable_name] = $error_string; if(false == $this->show_all_errors_together) { break; } } } return $bret; } function getErrors() { return $this->errors; } 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]; } $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) { if(!preg_match("/([a-z_A-Z]*)\(([a-zA-Z0-9_]*),(.*)\)/",$condn,$res)) { return true; } $type = strtolower(trim($res[1])); $arg1 = trim($res[2]); $arg2 = trim($res[3]); $arg2 = trim($arg2,"\""); $bret=false; switch($type) { case "is_selected_radio": case "isequal": { if(isset($formvariables[$arg1]) && strcasecmp($formvariables[$arg1],$arg2)==0 ) { $bret=true; } break; }//case case "ischecked_single": { if(isset($formvariables[$arg1])) { $bret=true; } break; } case "contains": { if(isset($formvariables[$arg1]) && stristr($formvariables[$arg1],$arg2) != FALSE ) { $bret=true; } break; } case "greaterthan": { if(isset($formvariables[$arg1]) && floatval($formvariables[$arg1]) > floatval($arg2)) { $bret=true; } break; } case "lessthan": { if(isset($formvariables[$arg1]) && floatval($formvariables[$arg1]) < floatval($arg2)) { $bret=true; } break; } case "is_not_checked_single": { if(!isset($formvariables[$arg1]) ) { $bret=true; } break; } case "is_not_selected_radio": { if(!isset($formvariables[$arg1]) || strcasecmp($formvariables[$arg1],$arg2) !=0 ) { $bret=true; } break; } case "is_selected_list_item": case "is_checked_group": { if(isset($formvariables[$arg1])) { if(is_array($formvariables[$arg1])) { foreach($formvariables[$arg1] as $chk) { if(strcasecmp($chk,$arg2)==0) { $bret=true;break; } }//foreach } else { if(strcasecmp($formvariables[$arg1],$arg2)==0) { $bret=true;break; } }//else } break; }//case] case "is_not_selected_list_item": case "is_not_checked_group": { $bret=true; if(isset($formvariables[$arg1])) { if(is_array($formvariables[$arg1])) { foreach($formvariables[$arg1] as $chk) { if(strcasecmp($chk,$arg2)==0) { $bret=false;break; } }//foreach } else { if(strcasecmp($formvariables[$arg1],$arg2)==0) { $bret=false;break; } }//else } break; }//case }//switch return $bret; } function validate_req($input_value, &$default_error_message,$variable_name) { $bret = true; if(!isset($input_value) || strlen($input_value) <=0) { $bret=false; $default_error_message = sprintf(E_VAL_REQUIRED_VALUE,$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; //$extra_info = sprintf(E_VAL_MAXLEN_EXTRA_INFO,$max_len,$input_length); $default_error_message = sprintf(E_VAL_MAXLEN_EXCEEDED,$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(E_VAL_MINLEN_CHECK_FAILED,$min_len,$variable_name); } } return $bret; } function test_datatype($input_value,$reg_exp) { if(ereg($reg_exp,$input_value)) { return false; } return true; } function validate_email($email) { return eregi("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $email); } 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 = E_VAL_NUMERIC_VALUE_EXPECTED; $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; 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(E_VAL_LESSTHAN_CHECK_FAILED, $lessthan, $variable_name); $bret = false; }//if } return $bret ; } function validate_greaterthan($command_value,$input_value,$variable_name,&$default_error_message,&$extra_info ) { $bret = true; 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(E_VAL_GREATERTHAN_CHECK_FAILED, $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(E_VAL_SHOULD_SEL_CHECK_FAILED, $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(E_VAL_DONTSEL_CHECK_FAILED,$variable_name); break; } } } else { if($command_value == $input_value) { $bret=false; $default_error_message = sprintf(E_VAL_DONTSEL_CHECK_FAILED,$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])) { if(true == $this->validate_for_numeric_input($input_value,$bret,$extra_info) && true == $this->validate_for_numeric_input($formvariables[$command_value],$bret,$extra_info)) { $valueThis = doubleval($input_value); $valueOther = doubleval($formvariables[$command_value]); switch($command) { case "ltelmnt": { if($valueThis >= $valueOther) { $bret = false; $default_error_message = sprintf(E_VAL_LTELMNT_CHECK_FAILED,$variable_name,$command_value); } break; } case "leelmnt": { if($valueThis > $valueOther) { $bret = false; $default_error_message = sprintf(E_VAL_LEELMNT_CHECK_FAILED,$variable_name,$command_value); } break; } case "gtelmnt": { if($valueThis <= $valueOther) { $bret = false; $default_error_message = sprintf(E_VAL_GTELMNT_CHECK_FAILED,$variable_name,$command_value); } break; } case "geelmnt": { if($valueThis < $valueOther) { $bret = false; $default_error_message = sprintf(E_VAL_GEELMNT_CHECK_FAILED,$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 'req': { $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(E_VAL_ALNUM_CHECK_FAILED,$variable_name); } break; } case 'alnum_s': { $bret= $this->test_datatype($input_value,"[^A-Za-z0-9 ]"); if(false == $bret) { $default_error_message = sprintf(E_VAL_ALNUM_S_CHECK_FAILED,$variable_name); } break; } case 'num': case 'numeric': { $bret= $this->test_datatype($input_value,"[^0-9]"); if(false == $bret) { $default_error_message = sprintf(E_VAL_NUM_CHECK_FAILED,$variable_name); } break; } case 'alpha': { $bret= $this->test_datatype($input_value,"[^A-Za-z]"); if(false == $bret) { $default_error_message = sprintf(E_VAL_ALPHA_CHECK_FAILED,$variable_name); } break; } case 'alpha_s': { $bret= $this->test_datatype($input_value,"[^A-Za-z ]"); if(false == $bret) { $default_error_message = sprintf(E_VAL_ALPHA_S_CHECK_FAILED,$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 = E_VAL_EMAIL_CHECK_FAILED; } } 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(E_VAL_REGEXP_CHECK_FAILED,$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); if(is_array($input_value) && isset($input_value)) { $bret = (count($input_value) >= $min_count )?true:false; } else { $bret= false; $default_error_message = sprintf(E_VAL_SELMIN_CHECK_FAILED, $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(E_VAL_SELONE_CHECK_FAILED,$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(E_VAL_EQELMNT_CHECK_FAILED,$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(isset($formvariables[$command_value]) && strcmp($input_value,$formvariables[$command_value]) !=0 ) { $bret=true; } else { $bret= false; $default_error_message = sprintf(E_VAL_NEELMNT_CHECK_FAILED,$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; } }//switch return $bret; }//validdate command function ValidateFileUpload($variable_name,$command,$command_value,&$default_error_message) { $bret=true; if(NULL == $this->globaldata->files || !isset($this->globaldata->files)) { if(isset($this->formvars[$this->config->confirm_file_list_var])) { $this->logger->LogInfo("Validator: confirm_file_list_var is set. skipping file validations"); return true; } $default_error_message = sprintf(E_VAL_REQ_FILE_INPUT,$variable_name); return false; } switch($command) { case "req_file": { if(!isset($this->globaldata->files[$variable_name])|| filesize($this->globaldata->files[$variable_name]['tmp_name'])<=0) { $bret=false; $default_error_message = sprintf(E_VAL_REQ_FILE_INPUT,$variable_name); }//if break; }//case case "max_filesize": { if(isset($this->globaldata->files[$variable_name])) { $maxsize = intval(doubleval($command_value)*1024); if(filesize($this->globaldata->files[$variable_name]['tmp_name']) > $maxsize) { $bret=false; $default_error_message = sprintf(E_VAL_FILESIZE_EXCEEDED,$variable_name,$maxsize); }//if }//if break; }//case max_filesize case "file_extn": { if(isset($this->globaldata->files[$variable_name]) && strlen($this->globaldata->files[$variable_name]['name'])>0) { $orig_filename = $this->globaldata->files[$variable_name]['name']; $parts = pathinfo($orig_filename); $file_extn = $parts["extension"]; $allowed_extns=explode(";",$command_value); $found=false; foreach($allowed_extns as $extn) { if(strcasecmp($file_extn,$extn)==0) { $found=true; } } if(!$found) { $bret=false; $default_error_message = sprintf(E_VAL_EXTN_NOTALLOWED,$variable_name,$command_value); } } break; } }//switch return $bret; }//function }//config ///////Global Functions/////// function sfm_make_path($part1,$part2) { $part1 = rtrim($part1,"/\\"); $ret_path = $part1."/".$part2; return $ret_path; } function magicQuotesRemove(&$array) { if(!get_magic_quotes_gpc()) { return; } foreach($array as $key => $elem) { if(is_array($elem)) { magicQuotesRemove($elem); } else { $array[$key] = stripslashes($elem); }//else }//foreach } function CreateHiddenInput($name, $objvalue) { $objvalue = htmlentities($objvalue,ENT_QUOTES,"UTF-8"); $str_ret = " "; return $str_ret; } function convert_html_entities_in_formdata($skip_var,&$datamap) { foreach($datamap as $name => $value) { if(strlen($skip_var)>0 && strcmp($name,$skip_var)==0) { continue; } if(true == is_string($datamap[$name])) { $datamap[$name] = nl2br(htmlentities($datamap[$name],ENT_QUOTES,"UTF-8")); } }//foreach } function array_push_ref(&$target,&$value_array) { if(!is_array($target)) { return FALSE; } $target[]=&$value_array; return TRUE; } function sfm_checkConfigFileSign($conf_content,$strsign) { $conf_content = substr($conf_content,strlen(CONST_PHP_TAG_START)+1); $conf_content = ltrim($conf_content); if(0 == strncmp($conf_content,$strsign,strlen($strsign))) { return true; } return false; } /** * 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-2006 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: pear-code.inc,v 1.3 2007/02/02 20:17:42 Prasanth Exp $ * @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.4.11 * @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; 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 ($skipmsg) { $a = &new $ec($code, $mode, $options, $userinfo); return $a; } 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.4.11 * @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 (function_exists("debug_backtrace")) { if (@!PEAR::getStaticProperty('PEAR_Error', 'skiptrace')) { $this->backtrace = debug_backtrace(); } } 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() /** * 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: */ // +-----------------------------------------------------------------------+ // | Copyright (c) 2002-2003 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. | // | | // +-----------------------------------------------------------------------+ // | Author: Richard Heyes | // +-----------------------------------------------------------------------+ /** * * Raw mime encoding class * * What is it? * This class enables you to manipulate and build * a mime email from the ground up. * * Why use this instead of mime.php? * mime.php 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. * * Eg. * * // Since multipart/mixed has no real body, (the body is * // the subpart), we set the body argument to blank. * * $params['content_type'] = 'multipart/mixed'; * $email = new Mail_mimePart('', $params); * * // Here we add a text part to the multipart we have * // already. Assume $body contains plain text. * * $params['content_type'] = 'text/plain'; * $params['encoding'] = '7bit'; * $text = $email->addSubPart($body, $params); * * // Now add an attachment. Assume $attach is * the contents of the attachment * * $params['content_type'] = 'application/zip'; * $params['encoding'] = 'base64'; * $params['disposition'] = 'attachment'; * $params['dfilename'] = 'example.zip'; * $attach =& $email->addSubPart($body, $params); * * // Now build the email. Note that the encode * // function returns an associative array containing two * // elements, body and headers. You will need to add extra * // headers, (eg. Mime-Version) before sending. * * $email = $message->encode(); * $email['headers'][] = 'Mime-Version: 1.0'; * * * Further examples are available at http://www.phpguru.org * * TODO: * - Set encode() to return the $obj->encoded if encode() * has already been run. Unless a flag is passed to specifically * re-build the message. * * @author Richard Heyes * @version $Revision: 1.1 $ * @package Mail */ class Mail_mimePart { /** * The encoding type of this part * @var string */ var $_encoding; /** * An array of subparts * @var array */ var $_subparts; /** * The output of this part after being built * @var string */ var $_encoded; /** * Headers for this part * @var array */ var $_headers; /** * The body of this part (not encoded) * @var string */ var $_body; /** * Constructor. * * Sets up the object. * * @param $body - The body of the mime part if any. * @param $params - An associative array of 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 - Optional filename parameter for content disposition * description - Content description * charset - Character set to use * @access public */ function Mail_mimePart($body = '', $params = array()) { if (!defined('MAIL_MIMEPART_CRLF')) { define('MAIL_MIMEPART_CRLF', defined('MAIL_MIME_CRLF') ? MAIL_MIME_CRLF : "\r\n", TRUE); } foreach ($params as $key => $value) { switch ($key) { case 'content_type': $headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : ''); break; case 'encoding': $this->_encoding = $value; $headers['Content-Transfer-Encoding'] = $value; break; case 'cid': $headers['Content-ID'] = '<' . $value . '>'; break; case 'disposition': $headers['Content-Disposition'] = $value . (isset($dfilename) ? '; filename="' . $dfilename . '"' : ''); break; case 'dfilename': if (isset($headers['Content-Disposition'])) { $headers['Content-Disposition'] .= '; filename="' . $value . '"'; } else { $dfilename = $value; } break; case 'description': $headers['Content-Description'] = $value; break; case 'charset': if (isset($headers['Content-Type'])) { $headers['Content-Type'] .= '; charset="' . $value . '"'; } else { $charset = $value; } break; } } // 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; } /** * encode() * * Encodes and returns the email. Also stores * it in the encoded member variable * * @return An associative array containing two elements, * body and headers. The headers element is itself * an indexed array. * @access public */ function encode() { $encoded =& $this->_encoded; if (!empty($this->_subparts)) { srand((double)microtime()*1000000); $boundary = '=_' . md5(rand() . microtime()); $this->_headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF . "\t" . 'boundary="' . $boundary . '"'; // Add body parts to $subparts for ($i = 0; $i < count($this->_subparts); $i++) { $headers = array(); $tmp = $this->_subparts[$i]->encode(); foreach ($tmp['headers'] as $key => $value) { $headers[] = $key . ': ' . $value; } $subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body']; } $encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF . implode('--' . $boundary . MAIL_MIMEPART_CRLF, $subparts) . '--' . $boundary.'--' . MAIL_MIMEPART_CRLF; } else { $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding) . MAIL_MIMEPART_CRLF; } // Add headers to $encoded $encoded['headers'] =& $this->_headers; return $encoded; } /** * &addSubPart() * * Adds a subpart to current mime part and returns * a reference to it * * @param $body The body of the subpart, if any. * @param $params The parameters for the subpart, same * as the $params argument for constructor. * @return 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]; } /** * _getEncodedData() * * Returns encoded data based upon encoding passed to it * * @param $data The data to encode. * @param $encoding The encoding type to use, 7bit, base64, * or quoted-printable. * @access private */ function _getEncodedData($data, $encoding) { switch ($encoding) { case '8bit': case '7bit': return $data; break; case 'quoted-printable': return $this->_quotedPrintableEncode($data); break; case 'base64': return rtrim(chunk_split(base64_encode($data), 76, MAIL_MIMEPART_CRLF)); break; default: return $data; } } /** * quoteadPrintableEncode() * * Encodes data to quoted-printable standard. * * @param $input The data to encode * @param $line_max Optional max line length. Should * not be more than 76 chars * * @access private */ function _quotedPrintableEncode($input , $line_max = 76) { $lines = preg_split("/\r?\n/", $input); $eol = MAIL_MIMEPART_CRLF; $escape = '='; $output = ''; while(list(, $line) = each($lines)){ $linlen = strlen($line); $newline = ''; for ($i = 0; $i < $linlen; $i++) { $char = substr($line, $i, 1); $dec = ord($char); if (($dec == 32) AND ($i == ($linlen - 1))){ // convert space at eol only $char = '=20'; } elseif(($dec == 9) AND ($i == ($linlen - 1))) { // convert tab at eol only $char = '=09'; } elseif($dec == 9) { ; // Do nothing if a tab. } elseif(($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) { $char = $escape . strtoupper(sprintf('%02s', dechex($dec))); } if ((strlen($newline) + strlen($char)) >= $line_max) { // MAIL_MIMEPART_CRLF is not counted $output .= $newline . $escape . $eol; // soft line break; " =\r\n" is okay $newline = ''; } $newline .= $char; } // end of for $output .= $newline . $eol; } $output = substr($output, 0, -1 * strlen($eol)); // Don't want last crlf return $output; } } // End of class /* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ // +-----------------------------------------------------------------------+ // | Copyright (c) 2002-2003 Richard Heyes | // | Copyright (c) 2003-2005 The PHP Group | // | 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. | // | | // +-----------------------------------------------------------------------+ // | Author: Richard Heyes | // | Tomas V.V.Cox (port to PEAR) | // +-----------------------------------------------------------------------+ // // $Id: pear-mail.inc,v 1.1 2007/02/02 20:17:43 Prasanth Exp $ /** * Mime mail composer class. Can handle: text and html bodies, embedded html * images and attachments. * Documentation and examples of this class are avaible here: * http://pear.php.net/manual/ * * @notes 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 * * @author Richard Heyes * @author Tomas V.V.Cox * @package Mail * @access public */ class Mail_mime { /** * Contains the plain text part of the email * @var string */ var $_txtbody; /** * Contains the html part of the email * @var string */ var $_htmlbody; /** * contains the mime encoded text * @var string */ var $_mime; /** * contains the multipart content * @var string */ var $_multipart; /** * list of the attached images * @var array */ var $_html_images = array(); /** * list of the attachements * @var array */ var $_parts = array(); /** * Build parameters * @var array */ var $_build_params = array(); /** * Headers for the mail * @var array */ var $_headers = array(); /** * End Of Line sequence (for serialize) * @var string */ var $_eol; /** * Constructor function * * @access public */ function Mail_mime($crlf = "\r\n") { $this->_setEOL($crlf); $this->_build_params = array( 'text_encoding' => '7bit', 'html_encoding' => 'quoted-printable', '7bit_wrap' => 998, 'html_charset' => 'ISO-8859-1', 'text_charset' => 'ISO-8859-1', 'head_charset' => 'ISO-8859-1' ); } /** * Wakeup (unserialize) - re-sets EOL constant * * @access private */ function __wakeup() { $this->_setEOL($this->_eol); } /** * 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; } /** * Adds a html part to the mail * * @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) * @return mixed true on success or PEAR_Error object * @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; } /** * 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 use if $file is the image data * @param bool $isfilename Whether $file is a filename or not * Defaults to true * @return mixed true on success or PEAR_Error object * @access public */ function addHTMLImage($file, $c_type='application/octet-stream', $name = '', $isfilename = true) { $filedata = ($isfilename === true) ? $this->_file2str($file) : $file; if ($isfilename === true) { $filename = ($name == '' ? basename($file) : basename($name)); } else { $filename = basename($name); } if (PEAR::isError($filedata)) { return $filedata; } $this->_html_images[] = array( 'body' => $filedata, 'name' => $filename, 'c_type' => $c_type, 'cid' => md5(uniqid(time())) ); return true; } /** * Adds a file to the list of attachments. * * @param string $file The file name of the file to attach * OR the file data itself * @param string $c_type The content type * @param string $name The filename of the attachment * Only use if $file is the file data * @param bool $isFilename Whether $file is a filename or not * Defaults to true * @return mixed true on success or PEAR_Error object * @access public */ function addAttachment($file, $c_type = 'application/octet-stream', $name = '', $isfilename = true, $encoding = 'base64') { $filedata = ($isfilename === true) ? $this->_file2str($file) : $file; if ($isfilename === true) { // Force the name the user supplied, otherwise use $file $filename = (!empty($name)) ? $name : $file; } else { $filename = $name; } if (empty($filename)) { return PEAR::raiseError( 'The supplied filename for the attachment can\'t be empty' ); } $filename = basename($filename); if (PEAR::isError($filedata)) { return $filedata; } $this->_parts[] = array( 'body' => $filedata, 'name' => $filename, 'c_type' => $c_type, 'encoding' => $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) { if (!is_readable($file_name)) { return PEAR::raiseError('File is not readable ' . $file_name); } if (!$fd = fopen($file_name, 'rb')) { return PEAR::raiseError('Could not open ' . $file_name); } $filesize = filesize($file_name); if ($filesize == 0){ $cont = ""; }else{ $cont = fread($fd, $filesize); } fclose($fd); return $cont; } /** * Adds a text subpart to the mimePart object and * returns it during the build process. * * @param mixed The object to add the part to, or * null if a new object is to be created. * @param string 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']; if (is_object($obj)) { return $obj->addSubpart($text, $params); } else { return new Mail_mimePart($text, $params); } } /** * Adds a html subpart to the mimePart object and * returns it during the build process. * * @param mixed 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']; if (is_object($obj)) { return $obj->addSubpart($this->_htmlbody, $params); } else { return new Mail_mimePart($this->_htmlbody, $params); } } /** * 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['content_type'] = 'multipart/mixed'; return new Mail_mimePart('', $params); } /** * Adds a multipart/alternative part to a mimePart * object (or creates one), and returns it during * the build process. * * @param mixed 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'; if (is_object($obj)) { return $obj->addSubpart('', $params); } else { return new Mail_mimePart('', $params); } } /** * Adds a multipart/related part to a mimePart * object (or creates one), and returns it during * the build process. * * @param mixed 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'; if (is_object($obj)) { return $obj->addSubpart('', $params); } else { return new Mail_mimePart('', $params); } } /** * Adds an html image subpart to a mimePart object * and returns it during the build process. * * @param object The mimePart to add the image to * @param array 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']; $obj->addSubpart($value['body'], $params); } /** * Adds an attachment subpart to a mimePart object * and returns it during the build process. * * @param object The mimePart to add the image to * @param array The attachment information * @return object The image mimePart object * @access private */ function &_addAttachmentPart(&$obj, $value) { $params['content_type'] = $value['c_type']; $params['encoding'] = $value['encoding']; $params['disposition'] = 'attachment'; $params['dfilename'] = $value['name']; $obj->addSubpart($value['body'], $params); } /** * Builds the multipart message from the list ($this->_parts) and * returns the mime content. * * @param array Build parameters that change the way the email * is built. Should be associative. Can contain: * text_encoding - What encoding to use for plain text * Default is 7bit * html_encoding - What encoding to use for html * Default is quoted-printable * 7bit_wrap - Number of characters before text is * wrapped in 7bit encoding * Default is 998 * html_charset - The character set to use for html. * Default is iso-8859-1 * text_charset - The character set to use for text. * Default is iso-8859-1 * head_charset - The character set to use for headers. * Default is iso-8859-1 * @return string The mime content * @access public */ function &get($build_params = null) { if (isset($build_params)) { while (list($key, $value) = each($build_params)) { $this->_build_params[$key] = $value; } } if (!empty($this->_html_images) AND isset($this->_htmlbody)) { foreach ($this->_html_images as $value) { $regex = '#(\s)((?i)src|background|href(?-i))\s*=\s*(["\']?)' . preg_quote($value['name'], '#') . '\3#'; $rep = '\1\2=\3cid:' . $value['cid'] .'\3'; $this->_htmlbody = preg_replace($regex, $rep, $this->_htmlbody ); } } $null = null; $attachments = !empty($this->_parts) ? true : false; $html_images = !empty($this->_html_images) ? true : false; $html = !empty($this->_htmlbody) ? true : false; $text = (!$html AND !empty($this->_txtbody)) ? true : false; switch (true) { case $text AND !$attachments: $message =& $this->_addTextPart($null, $this->_txtbody); break; case !$text AND !$html AND $attachments: $message =& $this->_addMixedPart(); for ($i = 0; $i < count($this->_parts); $i++) { $this->_addAttachmentPart($message, $this->_parts[$i]); } break; case $text AND $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 AND !$attachments AND !$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 AND !$attachments AND $html_images: if (isset($this->_txtbody)) { $message =& $this->_addAlternativePart($null); $this->_addTextPart($message, $this->_txtbody); $related =& $this->_addRelatedPart($message); } else { $message =& $this->_addRelatedPart($null); $related =& $message; } $this->_addHtmlPart($related); for ($i = 0; $i < count($this->_html_images); $i++) { $this->_addHtmlImagePart($related, $this->_html_images[$i]); } break; case $html AND $attachments AND !$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 AND $attachments AND $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)) { $output = $message->encode(); $this->_headers = array_merge($this->_headers, $output['headers']); return $output['body']; } else { return false; } } /** * 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. * @return array Assoc array with the mime headers * @access public */ function &headers($xtra_headers = null) { // Content-Type header should already be present, // So just add mime version header $headers['MIME-Version'] = '1.0'; if (isset($xtra_headers)) { $headers = array_merge($headers, $xtra_headers); } $this->_headers = array_merge($headers, $this->_headers); return $this->_encodeHeaders($this->_headers); } /** * 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. * @return string Plain text headers * @access public */ function txtHeaders($xtra_headers = null) { $headers = $this->headers($xtra_headers); $ret = ''; foreach ($headers as $key => $val) { $ret .= "$key: $val" . MAIL_MIME_CRLF; } return $ret; } /** * Sets the Subject header * * @param string $subject String to set the subject to * access public */ function setSubject($subject) { $this->_headers['Subject'] = $subject; } /** * Set an email to the From (the sender) header * * @param string $email The email direction to add * @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 * @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 * @access public */ function addBcc($email) { if (isset($this->_headers['Bcc'])) { $this->_headers['Bcc'] .= ", $email"; } else { $this->_headers['Bcc'] = $email; } } /** * Encodes a header as per RFC2047 * * @param string $input The header data to encode * @return string Encoded data * @access private */ function _encodeHeaders($input) { foreach ($input as $hdr_name => $hdr_value) { preg_match_all('/(\w*[\x80-\xFF]+\w*)/', $hdr_value, $matches); foreach ($matches[1] as $value) { $replacement = preg_replace('/([\x80-\xFF])/e', '"=" . strtoupper(dechex(ord("\1")))', $value); $hdr_value = str_replace($value, '=?' . $this->_build_params['head_charset'] . '?Q?' . $replacement . '?=', $hdr_value); } $input[$hdr_name] = $hdr_value; } return $input; } /** * Set the object's end-of-line and define the constant if applicable * * @param string $eol End Of Line sequence * @access private */ function _setEOL($eol) { $this->_eol = $eol; if (!defined('MAIL_MIME_CRLF')) { define('MAIL_MIME_CRLF', $this->_eol, true); } } } // End of class // // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2003 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Chuck Hagenbuch | // +----------------------------------------------------------------------+ // // $Id: pear-mail.inc,v 1.1 2007/02/02 20:17:43 Prasanth Exp $ /** * 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.1 $ * @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); $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) { $this->_sanitizeHeaders($headers); // 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) { $parser = &new Mail_RFC822(); $addresses = $parser->parseAddressList($value, 'localhost', false); if (PEAR::isError($addresses)) { 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) { // 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 (PEAR::isError($addresses)) { return $addresses; } $recipients = array(); if (is_array($addresses)) { foreach ($addresses as $ob) { $recipients[] = $ob->mailbox . '@' . $ob->host; } } return $recipients; } } // +-----------------------------------------------------------------------+ // | Copyright (c) 2001-2002, 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. | // | | // +-----------------------------------------------------------------------+ // | Authors: Richard Heyes | // | Chuck Hagenbuch | // +-----------------------------------------------------------------------+ /** * RFC 822 Email address list validation Utility * * What is it? * * This class will take an address string, and parse it into it's consituent * parts, be that either addresses, groups, or combinations. Nested groups * are not supported. The structure it returns is pretty straight forward, * and is similar to that provided by the imap_rfc822_parse_adrlist(). Use * print_r() to view the structure. * * How do I use it? * * $address_string = 'My Group: "Richard" (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.1 $ * @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)) { 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)) { 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 an 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 = explode('"', $string); $string_cnt = count($string); for ($i = 0; $i < (count($string) - 1); $i++) if (substr($string[$i], -1) == '\\') $string_cnt--; return ($string_cnt % 2 === 0); } /** * 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; // +1 is for the trailing ) $_mailbox = substr($_mailbox, strpos($_mailbox, $comment)+strlen($comment)+1); } 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; } } } // // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright (c) 1997-2003 The PHP Group | // +----------------------------------------------------------------------+ // | This source file is subject to version 2.02 of the PHP license, | // | that is bundled with this package in the file LICENSE, and is | // | available at through the world-wide-web at | // | http://www.php.net/license/2_02.txt. | // | If you did not receive a copy of the PHP license and are unable to | // | obtain it through the world-wide-web, please send a note to | // | license@php.net so we can mail you a copy immediately. | // +----------------------------------------------------------------------+ // | Author: Chuck Hagenbuch | // +----------------------------------------------------------------------+ // // $Id: pear-mail.inc,v 1.1 2007/02/02 20:17:43 Prasanth Exp $ /** * internal PHP-mail() implementation of the PEAR Mail:: interface. * @package Mail * @version $Revision: 1.1 $ */ 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) { $this->_sanitizeHeaders($headers); // 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 (PEAR::isError($headerElements)) { 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; } } /** * Crypt_Blowfish allows for encryption and decryption on the fly using * the Blowfish algorithm. Crypt_Blowfish does not require the MCrypt * PHP extension, but uses it if available, otherwise it uses only PHP. * Crypt_Blowfish supports encryption/decryption with or without a secret key. * * * 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 Encryption * @package Crypt_Blowfish * @author Matthew Fonda * @copyright 2005 Matthew Fonda * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: encr-lib.inc,v 1.3 2007/03/13 18:54:07 Prasanth Exp $ * @link http://pear.php.net/package/Crypt_Blowfish */ /** * Engine choice constants */ /** * To let the Crypt_Blowfish package decide which engine to use * @since 1.1.0 */ define('CRYPT_BLOWFISH_AUTO', 1); /** * To use the MCrypt PHP extension. * @since 1.1.0 */ define('CRYPT_BLOWFISH_MCRYPT', 2); /** * To use the PHP-only engine. * @since 1.1.0 */ define('CRYPT_BLOWFISH_PHP', 3); /** * Example using the factory method in CBC mode * * $bf =& Crypt_Blowfish::factory('cbc'); * if (PEAR::isError($bf)) { * echo $bf->getMessage(); * exit; * } * $iv = 'abc123+='; * $key = 'My secret key'; * $bf->setKey($key, $iv); * $encrypted = $bf->encrypt('this is some example plain text'); * $bf->setKey($key, $iv); * $plaintext = $bf->decrypt($encrypted); * if (PEAR::isError($plaintext)) { * echo $plaintext->getMessage(); * exit; * } * // Encrypted text is padded prior to encryption * // so you may need to trim the decrypted result. * echo 'plain text: ' . trim($plaintext); * * * To disable using the mcrypt library, define the CRYPT_BLOWFISH_NOMCRYPT * constant. This is useful for instance on Windows platform with a buggy * mdecrypt_generic() function. * * define('CRYPT_BLOWFISH_NOMCRYPT', true); * * * @category Encryption * @package Crypt_Blowfish * @author Matthew Fonda * @author Philippe Jausions * @copyright 2005-2006 Matthew Fonda * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @link http://pear.php.net/package/Crypt_Blowfish * @version @package_version@ * @access public */ define('CRYPT_BLOWFISH_NOMCRYPT', true); class Crypt_Blowfish { /** * Implementation-specific Crypt_Blowfish object * * @var object * @access private */ var $_crypt = null; /** * Initialization vector * * @var string * @access protected */ var $_iv = null; /** * Holds block size * * @var integer * @access protected */ var $_block_size = 8; /** * Holds IV size * * @var integer * @access protected */ var $_iv_size = 8; /** * Holds max key size * * @var integer * @access protected */ var $_key_size = 56; /** * Crypt_Blowfish Constructor * Initializes the Crypt_Blowfish object (in EBC mode), and sets * the secret key * * @param string $key * @access public * @deprecated Since 1.1.0 * @see Crypt_Blowfish::factory() */ function Crypt_Blowfish($key) { $this->_crypt =& Crypt_Blowfish::factory('ecb', $key); if (!PEAR::isError($this->_crypt)) { $this->_crypt->setKey($key); } } /** * Crypt_Blowfish object factory * * This is the recommended method to create a Crypt_Blowfish instance. * * When using CRYPT_BLOWFISH_AUTO, you can force the package to ignore * the MCrypt extension, by defining CRYPT_BLOWFISH_NOMCRYPT. * * @param string $mode operating mode 'ecb' or 'cbc' (case insensitive) * @param string $key * @param string $iv initialization vector (must be provided for CBC mode) * @param integer $engine one of CRYPT_BLOWFISH_AUTO, CRYPT_BLOWFISH_PHP * or CRYPT_BLOWFISH_MCRYPT * @return object Crypt_Blowfish object or PEAR_Error object on error * @access public * @static * @since 1.1.0 */ function &factory($mode = 'ecb', $key = null, $iv = null, $engine = CRYPT_BLOWFISH_AUTO) { switch ($engine) { case CRYPT_BLOWFISH_AUTO: if (!defined('CRYPT_BLOWFISH_NOMCRYPT') && extension_loaded('mcrypt')) { $engine = CRYPT_BLOWFISH_MCRYPT; } else { $engine = CRYPT_BLOWFISH_PHP; } break; case CRYPT_BLOWFISH_MCRYPT: if (!PEAR::loadExtension('mcrypt')) { return PEAR::raiseError('MCrypt extension is not available.'); } break; } switch ($engine) { case CRYPT_BLOWFISH_PHP: $mode = strtoupper($mode); $class = 'Crypt_Blowfish_' . $mode; $crypt = new $class(null); break; case CRYPT_BLOWFISH_MCRYPT: $crypt = new Crypt_Blowfish_MCrypt(null, $mode); break; } if (!is_null($key) || !is_null($iv)) { $result = $crypt->setKey($key, $iv); if (PEAR::isError($result)) { return $result; } } return $crypt; } /** * Returns the algorithm's block size * * @return integer * @access public * @since 1.1.0 */ function getBlockSize() { return $this->_block_size; } /** * Returns the algorithm's IV size * * @return integer * @access public * @since 1.1.0 */ function getIVSize() { return $this->_iv_size; } /** * Returns the algorithm's maximum key size * * @return integer * @access public * @since 1.1.0 */ function getMaxKeySize() { return $this->_key_size; } /** * Deprecated isReady method * * @return bool * @access public * @deprecated */ function isReady() { return true; } /** * Deprecated init method - init is now a private * method and has been replaced with _init * * @return bool * @access public * @deprecated */ function init() { return $this->_crypt->init(); } /** * Encrypts a string * * Value is padded with NUL characters prior to encryption. You may * need to trim or cast the type when you decrypt. * * @param string $plainText the string of characters/bytes to encrypt * @return string|PEAR_Error Returns cipher text on success, PEAR_Error on failure * @access public */ function encrypt($plainText) { return $this->_crypt->encrypt($plainText); } /** * Decrypts an encrypted string * * The value was padded with NUL characters when encrypted. You may * need to trim the result or cast its type. * * @param string $cipherText the binary string to decrypt * @return string|PEAR_Error Returns plain text on success, PEAR_Error on failure * @access public */ function decrypt($cipherText) { return $this->_crypt->decrypt($cipherText); } /** * Sets the secret key * The key must be non-zero, and less than or equal to * 56 characters (bytes) in length. * * If you are making use of the PHP MCrypt extension, you must call this * method before each encrypt() and decrypt() call. * * @param string $key * @return boolean|PEAR_Error Returns TRUE on success, PEAR_Error on failure * @access public */ function setKey($key) { return $this->_crypt->setKey($key); } } /** * Crypt_Blowfish allows for encryption and decryption on the fly using * the Blowfish algorithm. Crypt_Blowfish does not require the mcrypt * PHP extension, but uses it if available, otherwise it uses only PHP. * Crypt_Blowfish support encryption/decryption with or without a secret key. * * 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 Encryption * @package Crypt_Blowfish * @author Matthew Fonda * @author Philippe Jausions * @copyright 2005-2006 Matthew Fonda * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: encr-lib.inc,v 1.3 2007/03/13 18:54:07 Prasanth Exp $ * @link http://pear.php.net/package/Crypt_Blowfish * @since 1.1.0 */ /** * Common class for PHP-only implementations * * @category Encryption * @package Crypt_Blowfish * @author Matthew Fonda * @author Philippe Jausions * @copyright 2005-2006 Matthew Fonda * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @link http://pear.php.net/package/Crypt_Blowfish * @version @package_version@ * @access public * @since 1.1.0 */ class Crypt_Blowfish_PHP extends Crypt_Blowfish { /** * P-Array contains 18 32-bit subkeys * * @var array * @access protected */ var $_P = array(); /** * Array of four S-Blocks each containing 256 32-bit entries * * @var array * @access protected */ var $_S = array(); /** * Whether the IV is required * * @var boolean * @access protected */ var $_iv_required = false; /** * Crypt_Blowfish_PHP Constructor * Initializes the Crypt_Blowfish object, and sets * the secret key * * @param string $key * @param string $mode operating mode 'ecb' or 'cbc' * @param string $iv initialization vector * @access protected */ function __construct($key = null, $iv = null) { $this->_iv = $iv . ((strlen($iv) < $this->_iv_size) ? str_repeat(chr(0), $this->_iv_size - strlen($iv)) : ''); if (!is_null($key)) { $this->setKey($key, $this->_iv); } } /** * Initializes the Crypt_Blowfish object * * @access private */ function _init() { $defaults = new Crypt_Blowfish_DefaultKey(); $this->_P = $defaults->P; $this->_S = $defaults->S; } /** * Workaround for XOR on certain systems * * @param integer|float $l * @param integer|float $r * @return float * @access protected */ function _binxor($l, $r) { $x = (($l < 0) ? (float)($l + 4294967296) : (float)$l) ^ (($r < 0) ? (float)($r + 4294967296) : (float)$r); return (float)(($x < 0) ? $x + 4294967296 : $x); } /** * Enciphers a single 64-bit block * * @param int &$Xl * @param int &$Xr * @access protected */ function _encipher(&$Xl, &$Xr) { if ($Xl < 0) { $Xl += 4294967296; } if ($Xr < 0) { $Xr += 4294967296; } for ($i = 0; $i < 16; $i++) { $temp = $Xl ^ $this->_P[$i]; if ($temp < 0) { $temp += 4294967296; } $Xl = ((($this->_S[0][($temp >> 24) & 255] + $this->_S[1][($temp >> 16) & 255] ) ^ $this->_S[2][($temp >> 8) & 255] ) + $this->_S[3][$temp & 255] ) ^ $Xr; $Xr = $temp; } $Xr = $this->_binxor($Xl, $this->_P[16]); $Xl = $this->_binxor($temp, $this->_P[17]); } /** * Deciphers a single 64-bit block * * @param int &$Xl * @param int &$Xr * @access protected */ function _decipher(&$Xl, &$Xr) { if ($Xl < 0) { $Xl += 4294967296; } if ($Xr < 0) { $Xr += 4294967296; } for ($i = 17; $i > 1; $i--) { $temp = $Xl ^ $this->_P[$i]; if ($temp < 0) { $temp += 4294967296; } $Xl = ((($this->_S[0][($temp >> 24) & 255] + $this->_S[1][($temp >> 16) & 255] ) ^ $this->_S[2][($temp >> 8) & 255] ) + $this->_S[3][$temp & 255] ) ^ $Xr; $Xr = $temp; } $Xr = $this->_binxor($Xl, $this->_P[1]); $Xl = $this->_binxor($temp, $this->_P[0]); } /** * Sets the secret key * The key must be non-zero, and less than or equal to * 56 characters (bytes) in length. * * If you are making use of the PHP mcrypt extension, you must call this * method before each encrypt() and decrypt() call. * * @param string $key * @param string $iv 8-char initialization vector (required for CBC mode) * @return boolean|PEAR_Error Returns TRUE on success, PEAR_Error on failure * @access public * @todo Fix the caching of the key */ function setKey($key, $iv = null) { static $keyHash = null; if (!is_string($key)) { return PEAR::raiseError('Key must be a string', 2); } $len = strlen($key); if ($len > $this->_key_size || $len == 0) { return PEAR::raiseError('Key must be less than ' . $this->_key_size . ' characters (bytes) and non-zero. Supplied key length: ' . $len, 3); } if ($this->_iv_required) { if (strlen($iv) != $this->_iv_size) { return PEAR::raiseError('IV must be ' . $this->_iv_size . '-character (byte) long. Supplied IV length: ' . strlen($iv), 7); } $this->_iv = $iv; } // If same key passed, no need to re-initialize internal arrays. // @todo This needs to be worked out better... //if ($keyHash == md5($key)) { // return true; //} /////////////removed buggy optimization PMJ $this->_init(); $k = 0; $data = 0; $datal = 0; $datar = 0; for ($i = 0; $i < 18; $i++) { $data = 0; for ($j = 4; $j > 0; $j--) { $data = $data << 8 | ord($key{$k}); $k = ($k+1) % $len; } $this->_P[$i] ^= $data; } for ($i = 0; $i <= 16; $i += 2) { $this->_encipher($datal, $datar); $this->_P[$i] = $datal; $this->_P[$i+1] = $datar; } for ($i = 0; $i < 256; $i += 2) { $this->_encipher($datal, $datar); $this->_S[0][$i] = $datal; $this->_S[0][$i+1] = $datar; } for ($i = 0; $i < 256; $i += 2) { $this->_encipher($datal, $datar); $this->_S[1][$i] = $datal; $this->_S[1][$i+1] = $datar; } for ($i = 0; $i < 256; $i += 2) { $this->_encipher($datal, $datar); $this->_S[2][$i] = $datal; $this->_S[2][$i+1] = $datar; } for ($i = 0; $i < 256; $i += 2) { $this->_encipher($datal, $datar); $this->_S[3][$i] = $datal; $this->_S[3][$i+1] = $datar; } $keyHash = md5($key); return true; } } /** * PHP implementation of the Blowfish algorithm in ECB mode * * 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 Encryption * @package Crypt_Blowfish * @author Matthew Fonda * @author Philippe Jausions * @copyright 2005-2006 Matthew Fonda * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: encr-lib.inc,v 1.3 2007/03/13 18:54:07 Prasanth Exp $ * @link http://pear.php.net/package/Crypt_Blowfish * @since 1.1.0 */ /** * Example * * $bf =& Crypt_Blowfish::factory('ecb'); * if (PEAR::isError($bf)) { * echo $bf->getMessage(); * exit; * } * $bf->setKey('My secret key'); * $encrypted = $bf->encrypt('this is some example plain text'); * $plaintext = $bf->decrypt($encrypted); * echo "plain text: $plaintext"; * * * @category Encryption * @package Crypt_Blowfish * @author Matthew Fonda * @author Philippe Jausions * @copyright 2005-2006 Matthew Fonda * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @link http://pear.php.net/package/Crypt_Blowfish * @version @package_version@ * @access public * @since 1.1.0 */ class Crypt_Blowfish_ECB extends Crypt_Blowfish_PHP { /** * Crypt_Blowfish Constructor * Initializes the Crypt_Blowfish object, and sets * the secret key * * @param string $key * @param string $iv initialization vector * @access public */ function Crypt_Blowfish_ECB($key = null, $iv = null) { $this->__construct($key, $iv); } /** * Class constructor * * @param string $key * @param string $iv initialization vector * @access public */ function __construct($key = null, $iv = null) { $this->_iv_required = false; parent::__construct($key, $iv); } /** * Encrypts a string * * Value is padded with NUL characters prior to encryption. You may * need to trim or cast the type when you decrypt. * * @param string $plainText string of characters/bytes to encrypt * @return string|PEAR_Error Returns cipher text on success, PEAR_Error on failure * @access public */ function encrypt($plainText) { if (!is_string($plainText)) { return PEAR::raiseError('Input must be a string', 0); } elseif (empty($this->_P)) { return PEAR::raiseError('The key is not initialized.', 8); } $cipherText = ''; $len = strlen($plainText); $plainText .= str_repeat(chr(0), (8 - ($len % 8)) % 8); for ($i = 0; $i < $len; $i += 8) { list(, $Xl, $Xr) = unpack('N2', substr($plainText, $i, 8)); $this->_encipher($Xl, $Xr); $cipherText .= pack('N2', $Xl, $Xr); } return $cipherText; } /** * Decrypts an encrypted string * * The value was padded with NUL characters when encrypted. You may * need to trim the result or cast its type. * * @param string $cipherText * @return string|PEAR_Error Returns plain text on success, PEAR_Error on failure * @access public */ function decrypt($cipherText) { if (!is_string($cipherText)) { return PEAR::raiseError('Cipher text must be a string', 1); } if (empty($this->_P)) { return PEAR::raiseError('The key is not initialized.', 8); } $plainText = ''; $len = strlen($cipherText); $cipherText .= str_repeat(chr(0), (8 - ($len % 8)) % 8); for ($i = 0; $i < $len; $i += 8) { list(, $Xl, $Xr) = unpack('N2', substr($cipherText, $i, 8)); $this->_decipher($Xl, $Xr); $plainText .= pack('N2', $Xl, $Xr); } return $plainText; } } class Crypt_Blowfish_DefaultKey { var $P = array(); var $S = array(); function Crypt_Blowfish_DefaultKey() { $this->P = array( 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b ); $this->S = array( array( 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a ), array( 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7 ), array( 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0 ), array( 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6 ) ); } } /////////Content Start///////////// $var10258="\n". " \n". " \n". " \n". "Survey\n". " \n". " \n". " \n". " \n". " \n". "
\n". "
\n". " \n". " \n". " \n". " \n". " \n". " \n". "
\n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". " \n". "
\n". "Survey\n". "
\n". "Name(optional):\n". " \n". " \n". "
\n". "Email(optional):\n". " \n". "
\n". "%Survey_Email_errorloc%\n". "
\n". " \n". "
\n". "
\n". "Please evaluate...\n". "
\n". "Question 1:*\n". " \n". "
\n". "%Survey_Question1_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 2:*\n". " \n". "
\n". "%Survey_Question2_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 3:*\n". " \n". "
\n". "%Survey_Question3_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 4:*\n". " \n". "
\n". "%Survey_Question4_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 1*\n". " \n". "
\n". "%Survey_Question5_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 1*\n". " \n". "
\n". "%Survey_Question6_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 1*\n". " \n". "
\n". "%Survey_Question7_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 1*\n". " \n". "
\n". "%Survey_Question8_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 1*\n". " \n". "
\n". "%Survey_Question9_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question 1*\n". " \n". "
\n". "%Survey_Question10_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "
\n". "text\n". "
\n". "Question11*\n". " \n". "
\n". "%Survey_Question11_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question12*\n". " \n". "
\n". "%Survey_Question12_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "Question13*\n". " \n". "
\n". "%Survey_Question13_errorloc%\n". "
\n". " \n". "1 \n". "2 \n". "3 \n". "4 \n". "5\n". "
\n". "
\n". "What especially did you like?\n". " \n". "
\n". "%Survey_Likes_errorloc%\n". "
\n". "\n". "
\n". "What especially did you dislike?\n". " \n". "
\n". "%Survey_Dislikes_errorloc%\n". "
\n". "\n". "
\n". "Comments\n". " \n". "
\n". "%Survey_Comments_errorloc%\n". "
\n". "\n". "
\n". "
\n". "
\n". "%sfm_error_display_loc%\n". "
\n". " \n". "
\n". " \n". "
\n". "
\n". "
\n". " \n". "This code was generated using the evaluation version of Simfatic Forms.
Simfatic Forms\n". "
\n". "
\n". "\n". " \n". "\n". ""; $var21255="/*\n". " -------------------------------------------------------------------------\n". " JavaScript Form Validator\n". " Version 5.0\n". " Part of Simfatic Forms software\n". " \n". " Copyright (C) 2003-2007 Simfatic Solutions. All rights reserved.\n". " This javascript code is installed as part of Simfatic Forms software.\n". " You may adapt this script for your own needs, provided these opening credit\n". " lines (down to the lower dividing line) are kept intact.\n". " You may not reprint or redistribute this code without permission from \n". " Simfatic Solutions.\n". " http://www.simfatic.com/\n". " ------------------------------------------------------------------------- \n". "*/\n". "\n". "function Validator(frmname)\n". "{\n". " this.validate_on_killfocus=false;\n". " this.formobj=document.forms[frmname];\n". " if(!this.formobj)\n". " {\n". " alert(\"Error: couldnot get Form object \"+frmname);\n". " return;\n". " }\n". " if(this.formobj.onsubmit)\n". " {\n". " this.formobj.old_onsubmit = this.formobj.onsubmit;\n". " this.formobj.onsubmit=null;\n". " }\n". " else\n". " {\n". " this.formobj.old_onsubmit = null;\n". " }\n". " this.formobj._sfm_form_name=frmname;\n". "\n". " this.formobj.onsubmit=form_submit_handler;\n". " this.addValidation = add_validation;\n". " this.setAddnlValidationFunction=set_addnl_vfunction;\n". " this.clearAllValidations = clear_all_validations;\n". " this.disable_validations = false;\n". " \n". " document.error_disp_handler = new sfm_ErrorDisplayHandler();\n". " \n". " this.EnableOnPageErrorDisplay=validator_enable_OPED;\n". " this.show_errors_together=false;\n". " this.EnableMsgsTogether=sfm_enable_show_msgs_together;\n". "}\n". "\n". "function set_addnl_vfunction(functionname)\n". "{\n". " this.formobj.addnlvalidation = functionname;\n". "}\n". "function sfm_enable_show_msgs_together()\n". "{\n". " this.show_errors_together=true;\n". " this.formobj.show_errors_together=true;\n". "}\n". "function clear_all_validations()\n". "{\n". " for(var itr=0;itr < this.formobj.elements.length;itr++)\n". " {\n". " this.formobj.elements[itr].validationset = null;\n". " }\n". "}\n". "function form_submit_handler()\n". "{\n". " var bRet = true;\n". " document.error_disp_handler.clear_msgs();\n". " for(var itr=0;itr < this.elements.length;itr++)\n". " {\n". " if(this.elements[itr].validationset &&\n". " !this.elements[itr].validationset.validate())\n". " {\n". " bRet = false;\n". " }\n". " if(!bRet && !this.show_errors_together)\n". " {\n". " break;\n". " }\n". " }\n". " if(!bRet)\n". " {\n". " document.error_disp_handler.FinalShowMsg();\n". " return false;\n". " }\n". "\n". " if(this.addnlvalidation)\n". " {\n". " str =\" var ret = \"+this.addnlvalidation+\"()\";\n". " eval(str);\n". " if(!ret) return ret;\n". " }\n". " return true;\n". "}\n". "\n". "function add_validation(itemname,descriptor,errstr)\n". "{\n". " var condition = null;\n". " if(arguments.length > 3)\n". " {\n". " condition = arguments[3]; \n". " }\n". " if(!this.formobj)\n". " {\n". " alert(\"Error: The form object is not set properly\");\n". " return;\n". " }//if\n". " var itemobj = this.formobj[itemname];\n". "\n". " if(itemobj.length && isNaN(itemobj.selectedIndex) )\n". " //for radio button; don't do for 'select' item\n". " {\n". " itemobj = itemobj[0];\n". " } \n". " if(!itemobj)\n". " {\n". " alert(\"Error: Couldnot get the input object named: \"+itemname);\n". " return;\n". " }\n". " if(true == this.validate_on_killfocus)\n". " {\n". " itemobj.onblur=handle_item_on_killfocus;\n". " }\n". " if(!itemobj.validationset)\n". " {\n". " itemobj.validationset = new ValidationSet(itemobj,this.show_errors_together);\n". " }\n". " itemobj.validationset.add(descriptor,errstr,condition);\n". " itemobj.validatorobj=this;\n". "}\n". "\n". "function handle_item_on_killfocus()\n". "{\n". " if(this.validatorobj.disable_validations == true)\n". " {\n". " /*\n". " To avoid repeated looping message boxes\n". " */\n". " this.validatorobj.disable_validations = false;\n". " return false;\n". " }\n". " \n". " if(null != this.validationset)\n". " {\n". " document.error_disp_handler.clear_msgs();\n". " if(false == this.validationset.validate())\n". " {\n". " document.error_disp_handler.FinalShowMsg();\n". " return false;\n". " }\n". " }\n". "}\n". "\n". "function validator_enable_OPED()\n". "{\n". " document.error_disp_handler.EnableOnPageDisplay();\n". "}\n". "\n". "function sfm_ErrorDisplayHandler()\n". "{\n". " this.msgdisplay = new AlertMsgDisplayer();\n". " this.EnableOnPageDisplay= edh_EnableOnPageDisplay;\n". " this.ShowMsg=edh_ShowMsg;\n". " this.FinalShowMsg=edh_FinalShowMsg;\n". " this.all_msgs=new Array();\n". " this.clear_msgs=edh_clear_msgs;\n". "}\n". "\n". "function edh_clear_msgs()\n". "{\n". " this.msgdisplay.clearmsg(this.all_msgs);\n". " this.all_msgs = new Array();\n". "}\n". "\n". "function edh_FinalShowMsg()\n". "{\n". " this.msgdisplay.showmsg(this.all_msgs);\n". "}\n". "\n". "function edh_EnableOnPageDisplay()\n". "{\n". " this.msgdisplay = new DivMsgDisplayer();\n". "}\n". "\n". "function edh_ShowMsg(msg,input_element)\n". "{\n". " var objmsg = new Array();\n". " objmsg[\"input_element\"] = input_element;\n". " objmsg[\"msg\"] = msg;\n". " this.all_msgs.push(objmsg);\n". "}\n". "\n". "function AlertMsgDisplayer()\n". "{\n". " this.showmsg = alert_showmsg;\n". " this.clearmsg=alert_clearmsg;\n". "}\n". "\n". "function alert_clearmsg(msgs)\n". "{\n". "\n". "}\n". "\n". "function alert_showmsg(msgs)\n". "{\n". " var whole_msg=\"\";\n". " var first_elmnt=null;\n". " for(var m in msgs)\n". " {\n". " if(null == first_elmnt)\n". " {\n". " first_elmnt = msgs[m][\"input_element\"];\n". " }\n". " whole_msg += msgs[m][\"msg\"] + \"\\n\";\n". " }\n". " \n". " alert(whole_msg);\n". "\n". " if(null != first_elmnt)\n". " {\n". " first_elmnt.focus();\n". " }\n". "}\n". "\n". "function sfm_show_error_msg(msg,input_elmt)\n". "{\n". " document.error_disp_handler.ShowMsg(msg,input_elmt);\n". "}\n". "\n". "function DivMsgDisplayer()\n". "{\n". " this.showmsg=div_showmsg;\n". " this.clearmsg=div_clearmsg;\n". "}\n". "\n". "function div_clearmsg(msgs)\n". "{\n". " for(var m in msgs)\n". " {\n". " var divname = element_div_name(msgs[m][\"input_element\"]);\n". " show_div_msg(divname,\"\");\n". " }\n". "}\n". "\n". "function element_div_name(input_element)\n". "{\n". " var divname = input_element.form._sfm_form_name + \"_\" + \n". " input_element.name + \"_errorloc\";\n". "\n". " divname = divname.replace(/[\\[\\]]/gi,\"\");\n". "\n". " return divname;\n". "}\n". "\n". "function div_showmsg(msgs)\n". "{\n". " var whole_msg;\n". " var first_elmnt=null;\n". " for(var m in msgs)\n". " {\n". " if(null == first_elmnt)\n". " {\n". " first_elmnt = msgs[m][\"input_element\"];\n". " }\n". " var divname = element_div_name(msgs[m][\"input_element\"]);\n". " show_div_msg(divname,msgs[m][\"msg\"]);\n". " }\n". " if(null != first_elmnt)\n". " {\n". " first_elmnt.focus();\n". " }\n". "}\n". "\n". "function show_div_msg(divname,msgstring)\n". "{\n". " if(document.layers)\n". " {\n". " divlayer = document.layers[divname];\n". " if(!divlayer){return;}\n". " divlayer.document.open();\n". " divlayer.document.write(msgstring);\n". " divlayer.document.close();\n". " }\n". " else\n". " if(document.all)\n". " {\n". " divlayer = document.all[divname];\n". " if(!divlayer){return;}\n". " divlayer.innerHTML=msgstring;\n". " }\n". " else\n". " if(document.getElementById)\n". " {\n". " divlayer = document.getElementById(divname);\n". " if(!divlayer){return;}\n". " divlayer.innerHTML =msgstring;\n". " }\n". " \n". " return false;\n". "}\n". "\n". "function ValidationDesc(inputitem,desc,error,condition)\n". "{\n". " this.desc=desc;\n". " this.error=error;\n". " this.itemobj = inputitem;\n". " this.condition = condition;\n". " this.validate=vdesc_validate;\n". "}\n". "function vdesc_validate()\n". "{\n". " if(this.condition != null )\n". " {\n". " if(!eval(this.condition))\n". " {\n". " return true;\n". " }\n". " }\n". " if(!validateInput(this.desc,this.itemobj,this.error))\n". " {\n". " this.itemobj.validatorobj.disable_validations=true;\n". " this.itemobj.focus();\n". " return false;\n". " }\n". " \n". " return true;\n". "}\n". "\n". "function ValidationSet(inputitem,msgs_together)\n". "{\n". " this.vSet=new Array();\n". " this.add= add_validationdesc;\n". " this.validate= vset_validate;\n". " this.itemobj = inputitem;\n". " this.msgs_together = msgs_together;\n". "}\n". "\n". "function add_validationdesc(desc,error,condition)\n". "{\n". " this.vSet[this.vSet.length]= \n". " new ValidationDesc(this.itemobj,desc,error,condition);\n". "}\n". "\n". "function vset_validate()\n". "{\n". " var bRet = true;\n". " for(var itr=0;itr= eval(objCompare.value)) \n". " {\n". " cmpstr = \" should be less than \"; \n". " bRet = false; \n". " }\n". " break;\n". " }//case\n". " case \"leelmnt\":\n". " {\n". " if(eval(objValue.value) > eval(objCompare.value)) \n". " {\n". " cmpstr = \" should be less than or equal to\"; \n". " bRet = false; \n". " }\n". " break;\n". " }//case \n". " case \"gtelmnt\":\n". " {\n". " if(eval(objValue.value) <= eval(objCompare.value)) \n". " {\n". " cmpstr = \" should be greater than\"; \n". " bRet = false; \n". " }\n". " break;\n". " }//case\n". " case \"geelmnt\":\n". " {\n". " if(eval(objValue.value) < eval(objCompare.value)) \n". " {\n". " cmpstr = \" should be greater than or equal to\"; \n". " bRet = false; \n". " }\n". " break;\n". " }//case\n". " case \"neelmnt\":\n". " {\n". " if(objValue.value.length > 0 &&\n". " objCompare.value.length > 0 &&\n". " objValue.value == objCompare.value)\n". " {\n". " cmpstr = \" should be different from \";\n". " bRet = false;\n". " }//if\n". " break; \n". " } \n". " }//switch\n". " if(bRet==false)\n". " {\n". " if(!strError || strError.length==0)\n". " {\n". " strError = objValue.name + cmpstr + objCompare.value; \n". " }//if\n". " sfm_show_error_msg(strError,objValue);\n". " }//if\n". " return bRet;\n". "}\n". "function TestSelMin(objValue,strMinSel,strError)\n". "{\n". " var bret = true;\n". " var objcheck = objValue.form.elements[objValue.name];\n". " var chkcount =0;\n". " if(objcheck.length)\n". " {\n". " for(var c=0;c < objcheck.length;c++)\n". " {\n". " if(objcheck[c].checked == \"1\")\n". " {\n". " chkcount++;\n". " }//if\n". " }//for\n". " }\n". " else\n". " {\n". " chkcount = (objcheck.checked == \"1\")?1:0;\n". " }\n". " var minsel = eval(strMinSel);\n". " if(chkcount < minsel)\n". " {\n". " if(!strError || strError.length ==0) \n". " { \n". " strError = \"Please Select atleast\"+minsel+\" check boxes for\"+objValue.name; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " bret = false;\n". " }\n". " return bret;\n". "}\n". "\n". "function TestSelMax(objValue,strMaxSel,strError)\n". "{\n". " var bret = true;\n". " var objcheck = objValue.form.elements[objValue.name];\n". " var chkcount =0;\n". " if(objcheck.length)\n". " {\n". " for(var c=0;c < objcheck.length;c++)\n". " {\n". " if(objcheck[c].checked == \"1\")\n". " {\n". " chkcount++;\n". " }//if\n". " }//for\n". " }\n". " else\n". " {\n". " chkcount = (objcheck.checked == \"1\")?1:0;\n". " }\n". " var maxsel = eval(strMaxSel);\n". " if(chkcount > maxsel)\n". " {\n". " if(!strError || strError.length ==0) \n". " { \n". " strError = \"Please Select atmost \"+maxsel+\" check boxes for\"+objValue.name; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " bret = false;\n". " }\n". " return bret;\n". "}\n". "function IsCheckSelected(objValue,chkValue)\n". "{\n". " var selected=false;\n". " var objcheck = objValue.form.elements[objValue.name];\n". " if(objcheck.length)\n". " {\n". " var idxchk=-1;\n". " for(var c=0;c < objcheck.length;c++)\n". " {\n". " if(objcheck[c].value == chkValue)\n". " {\n". " idxchk=c;\n". " break;\n". " }//if\n". " }//for\n". " if(idxchk>= 0)\n". " {\n". " if(objcheck[idxchk].checked==\"1\")\n". " {\n". " selected=true;\n". " }\n". " }//if\n". " }\n". " else\n". " {\n". " if(objValue.checked == \"1\")\n". " {\n". " selected=true;\n". " }//if\n". " }//else \n". "\n". " return selected;\n". "}\n". "\n". "function TestDontSelectChk(objValue,chkValue,strError)\n". "{\n". " var pass = true;\n". " pass = IsCheckSelected(objValue,chkValue)?false:true;\n". "\n". " if(pass==false)\n". " {\n". " if(!strError || strError.length ==0) \n". " { \n". " strError = \"Can't Proceed as you selected \"+objValue.name; \n". " }//if \n". " sfm_show_error_msg(strError,objValue);\n". " \n". " }\n". " return pass;\n". "}\n". "\n". "function TestShouldSelectChk(objValue,chkValue,strError)\n". "{\n". " var pass = true;\n". "\n". " pass = IsCheckSelected(objValue,chkValue)?true:false;\n". "\n". " if(pass==false)\n". " {\n". " if(!strError || strError.length ==0) \n". " { \n". " strError = \"You should select\"+objValue.name; \n". " }//if \n". " sfm_show_error_msg(strError,objValue);\n". " \n". " }\n". " return pass;\n". "}\n". "\n". "function TestRequiredInput(objValue,strError)\n". "{\n". " var ret = true;\n". " if(eval(objValue.value.length) == 0) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name + \" : Required Field\"; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret=false; \n". " }//if \n". "return ret;\n". "}\n". "function TestFileExtension(objValue,cmdvalue,strError)\n". "{\n". " var ret=false;\n". " var found=false;\n". "\n". " if(objValue.value.length <= 0)\n". " {//The 'required' validation is not done here\n". " return true;\n". " }\n". "\n". " var extns = cmdvalue.split(\";\");\n". " for(var i=0;i < extns.length;i++)\n". " {\n". " ext = objValue.value.substr(objValue.value.length - extns[i].length,extns[i].length);\n". " ext = ext.toLowerCase();\n". " if(ext == extns[i])\n". " {\n". " found=true;break;\n". " }\n". " }\n". " if(!found)\n". " {\n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name + \" allowed file extensions are: \"+cmdvalue; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret=false; \n". " }\n". " else\n". " {\n". " ret=true;\n". " }\n". " return ret;\n". "}\n". "function TestMaxLen(objValue,strMaxLen,strError)\n". "{\n". " var ret = true;\n". " if(eval(objValue.value.length) > eval(strMaxLen)) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name + \" : \"+ strMaxLen +\" characters maximum \"; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret = false; \n". " }//if \n". "return ret;\n". "}\n". "\n". "function TestMinLen(objValue,strMinLen,strError)\n". "{\n". " var ret = true;\n". " if(eval(objValue.value.length) < eval(strMinLen)) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name + \" : \" + strMinLen + \" characters minimum \"; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret = false; \n". " }//if \n". "return ret;\n". "}\n". "\n". "function TestInputType(objValue,strRegExp,strError,strDefaultError)\n". "{\n". " var ret = true;\n". "\n". " var charpos = objValue.value.search(strRegExp); \n". " if(objValue.value.length > 0 && charpos >= 0) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = strDefaultError;\n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret = false; \n". " }//if \n". " return ret;\n". "}\n". "\n". "function TestEmail(objValue,strError)\n". "{\n". "var ret = true;\n". " if(objValue.value.length > 0 && !validateEmail(objValue.value) ) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name+\": Enter a valid Email address \"; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret = false; \n". " }//if \n". "return ret;\n". "}\n". "\n". "function TestLessThan(objValue,strLessThan,strError)\n". "{\n". "var ret = true;\n". " if(isNaN(objValue.value)) \n". " { \n". " sfm_show_error_msg(objValue.name +\": Should be a number \",objValue); \n". " ret = false; \n". " }//if \n". " else\n". " if(eval(objValue.value) >= eval(strLessThan)) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name + \" : value should be less than \"+ strLessThan; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret = false; \n". " }//if \n". "return ret; \n". "}\n". "\n". "function TestGreaterThan(objValue,strGreaterThan,strError)\n". "{\n". "var ret = true;\n". " if(isNaN(objValue.value)) \n". " { \n". " sfm_show_error_msg(objValue.name+\": Should be a number \",objValue); \n". " ret = false; \n". " }//if \n". " else\n". " if(eval(objValue.value) <= eval(strGreaterThan)) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name + \" : value should be greater than \"+ strGreaterThan; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret = false;\n". " }//if \n". "return ret; \n". "}\n". "\n". "function TestRegExp(objValue,strRegExp,strError)\n". "{\n". "var ret = true;\n". " if( objValue.value.length > 0 && \n". " !objValue.value.match(strRegExp) ) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name+\": Invalid characters found \"; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret = false; \n". " }//if \n". "return ret;\n". "}\n". "function TestDontSelect(objValue,dont_sel_value,strError)\n". "{\n". "var ret = true;\n". " if(objValue.value == null) \n". " { \n". " sfm_show_error_msg(\"Error: dontselect command for non-select Item\",objValue); \n". " ret = false; \n". " } \n". " else\n". " if(objValue.value == dont_sel_value) \n". " { \n". " if(!strError || strError.length ==0) \n". " { \n". " strError = objValue.name+\": Please Select one option \"; \n". " }//if \n". " sfm_show_error_msg(strError,objValue); \n". " ret = false; \n". " } \n". "return ret;\n". "}\n". "\n". "function TestSelectOneRadio(objValue,strError)\n". "{\n". " var objradio = objValue.form.elements[objValue.name];\n". " var one_selected=false;\n". " for(var r=0;r < objradio.length;r++)\n". " {\n". " if(objradio[r].checked == \"1\")\n". " {\n". " one_selected=true;\n". " break;\n". " }\n". " }\n". " if(false == one_selected)\n". " {\n". " if(!strError || strError.length ==0) \n". " {\n". " strError = \"Please select one option from \"+objValue.name;\n". " } \n". " sfm_show_error_msg(strError,objValue);\n". " }\n". "return one_selected;\n". "}\n". "\n". "function TestSelectRadio(objValue,cmdvalue,strError,testselect)\n". "{\n". " var objradio = objValue.form.elements[objValue.name];\n". " var selected=false;\n". " \n". " for(var r=0;r < objradio.length;r++)\n". " {\n". " if(objradio[r].value == cmdvalue && objradio[r].checked == \"1\")\n". " {\n". " selected=true;\n". " break;\n". " }\n". " }\n". " if(testselect==true && false == selected || \n". " testselect==false && true == selected)\n". " {\n". " sfm_show_error_msg(strError,objValue);\n". " return false;\n". " }\n". "return true;\n". "}\n". "\n". "//* Checks each field in a form \n". "function validateInput(strValidateStr,objValue,strError) \n". "{ \n". "\n". " var ret = true;\n". " var epos = strValidateStr.search(\"=\"); \n". " var command = \"\"; \n". " var cmdvalue = \"\"; \n". " if(epos >= 0) \n". " { \n". " command = strValidateStr.substring(0,epos); \n". " cmdvalue = strValidateStr.substr(epos+1); \n". " } \n". " else \n". " { \n". " command = strValidateStr; \n". " } \n". " \n". " switch(command) \n". " { \n". " case \"req\": \n". " case \"required\": \n". " { \n". " ret = TestRequiredInput(objValue,strError)\n". " break; \n". " }\n". " case \"maxlength\": \n". " case \"maxlen\": \n". " { \n". " ret = TestMaxLen(objValue,cmdvalue,strError)\n". " break; \n". " }\n". " case \"minlength\": \n". " case \"minlen\": \n". " { \n". " ret = TestMinLen(objValue,cmdvalue,strError)\n". " break; \n". " }\n". " case \"alnum\": \n". " case \"alphanumeric\": \n". " { \n". " ret = TestInputType(objValue,\"[^A-Za-z0-9]\",strError, \n". " objValue.name+\": Only alpha-numeric characters allowed \");\n". " break; \n". " }\n". " case \"alnum_s\": \n". " case \"alphanumeric_space\": \n". " { \n". " ret = TestInputType(objValue,\"[^A-Za-z0-9\\\\s]\",strError, \n". " objValue.name+\": Only alpha-numeric characters and space allowed \");\n". " break; \n". " } \n". " case \"num\": \n". " case \"numeric\": \n". " { \n". " ret = TestInputType(objValue,\"[^0-9]\",strError, \n". " objValue.name+\": Only digits allowed \");\n". " break; \n". " }\n". " case \"alphabetic\": \n". " case \"alpha\": \n". " { \n". " ret = TestInputType(objValue,\"[^A-Za-z]\",strError, \n". " objValue.name+\": Only alphabetic characters allowed \");\n". " break; \n". " }\n". " case \"alphabetic_space\": \n". " case \"alpha_s\": \n". " { \n". " ret = TestInputType(objValue,\"[^A-Za-z\\\\s]\",strError, \n". " objValue.name+\": Only alphabetic characters and space allowed \");\n". " break; \n". " }\n". " case \"email\": \n". " { \n". " ret = TestEmail(objValue,strError);\n". " break; \n". " }\n". " case \"lt\": \n". " case \"lessthan\": \n". " { \n". " ret = TestLessThan(objValue,cmdvalue,strError);\n". " break; \n". " }\n". " case \"gt\": \n". " case \"greaterthan\": \n". " { \n". " ret = TestGreaterThan(objValue,cmdvalue,strError);\n". " break; \n". " }\n". " case \"regexp\": \n". " { \n". " ret = TestRegExp(objValue,cmdvalue,strError);\n". " break; \n". " }\n". " case \"dontselect\": \n". " { \n". " ret = TestDontSelect(objValue,cmdvalue,strError)\n". " break; \n". " }\n". " case \"dontselectchk\":\n". " {\n". " ret = TestDontSelectChk(objValue,cmdvalue,strError)\n". " break;\n". " }\n". " case \"shouldselchk\":\n". " {\n". " ret = TestShouldSelectChk(objValue,cmdvalue,strError)\n". " break;\n". " }\n". " case \"selmin\":\n". " {\n". " ret = TestSelMin(objValue,cmdvalue,strError);\n". " break;\n". " }\n". " case \"selmax\":\n". " {\n". " ret = TestSelMax(objValue,cmdvalue,strError);\n". " break;\n". " }\n". " case \"selone\":\n". " {\n". " ret = TestSelectOneRadio(objValue,strError);\n". " break;\n". " } \n". " case \"dontselectradio\":\n". " {\n". " ret = TestSelectRadio(objValue,cmdvalue,strError,false);\n". " break;\n". " }\n". " case \"selectradio\":\n". " {\n". " ret = TestSelectRadio(objValue,cmdvalue,strError,true);\n". " break;\n". " }\n". " //Comparisons\n". " case \"eqelmnt\": \n". " case \"ltelmnt\":\n". " case \"leelmnt\":\n". " case \"gtelmnt\":\n". " case \"geelmnt\":\n". " case \"neelmnt\":\n". " {\n". " return TestComparison(objValue,cmdvalue,command,strError);\n". " break;\n". " }\n". " case \"req_file\":\n". " {\n". " ret = TestRequiredInput(objValue,strError);\n". " break;\n". " }\n". " case \"file_extn\":\n". " {\n". " ret = TestFileExtension(objValue,cmdvalue,strError);\n". " break;\n". " }\n". "\n". " }//switch \n". " return ret; \n". "}\n". "function VWZ_IsListItemSelected(listname,value)\n". "{\n". " for(var i=0;i < listname.options.length;i++)\n". " {\n". " if(listname.options[i].selected == true &&\n". " listname.options[i].value == value) \n". " {\n". " return true;\n". " }\n". " }\n". " return false;\n". "}\n". "\n". "function VWZ_IsChecked(objcheck,value)\n". "{\n". " if(objcheck.length)\n". " {\n". " for(var c=0;c < objcheck.length;c++)\n". " {\n". " if(objcheck[c].checked == \"1\" && \n". " objcheck[c].value == value)\n". " {\n". " return true; \n". " }\n". " }\n". " }\n". " else\n". " {\n". " if(objcheck.checked == \"1\" )\n". " {\n". " return true; \n". " } \n". " }\n". " return false;\n". "}\n". "/*\n". " Copyright (C) 2003-2007 Simfatic Solutions . All rights reserved.\n". "*/ "; $var32683="New submission for the form:Survey"; $var11682="The following Data is submitted in the form named Survey by a visitor \n". "\n". " Name : %Name% \n". "\n". " Email : %Email% \n". "\n". " Question1 : %Question1% \n". "\n". " Question2 : %Question2% \n". "\n". " Question3 : %Question3% \n". "\n". " Question4 : %Question4% \n". "\n". " Question5 : %Question5% \n". "\n". " Question6 : %Question6% \n". "\n". " Question7 : %Question7% \n". "\n". " Question8 : %Question8% \n". "\n". " Question9 : %Question9% \n". "\n". " Question10 : %Question10% \n". "\n". " Question11 : %Question11% \n". "\n". " Question12 : %Question12% \n". "\n". " Question13 : %Question13% \n". "\n". " Likes : %Likes% \n". "\n". " Dislikes : %Dislikes% \n". "\n". " Comments : %Comments% \n". "\n". " Send : %Send% \n". "\n". " Visitor's IP Address : %_sfm_visitor_ip_% \n". "\n". " Form submission time : %_sfm_form_submision_time_% \n". "\n". ""; /////////Content End///////////// $formmailobj = new FormMail("Survey"); $formmailobj->setFormPage($var10258); $formmailobj->setFormID("0fa9b9f6-0ef2-403b-84ce-716b9da772b9"); $formmailobj->setFormKey("07ee4fb1-0df6-417c-bd71-46c331a78b56"); $formmailobj->setEmailFormatHTML(false); $formmailobj->EnableLogging(false); $formmailobj->SetErrorEmail("juergen.meyer@canterbury.ac.nz"); $fm_installer = new FM_FormInstaller(); $formmailobj->addModule($fm_installer); $formmailobj->setIsInstalled(true); $ref_file = new FM_RefFileDispatcher(); $formmailobj->addModule($ref_file); $ref_file->AddRefferedFile("genvalidator.js",$var21255); $form_page = new FM_FormPageRenderer(); $formmailobj->addModule($form_page); $validator = new FM_FormValidator(); $validator->addValidation("Email","email","The input for Email should be a valid email value"); $validator->addValidation("Question1","selone","Please select rating"); $validator->addValidation("Question2","selone","Please select rating"); $validator->addValidation("Question3","selone","Please select rating"); $validator->addValidation("Question4","selone","Please select rating"); $validator->addValidation("Question5","selone","Please select rating"); $validator->addValidation("Question6","selone","Please select rating"); $validator->addValidation("Question7","selone","Please select rating"); $validator->addValidation("Question8","selone","Please select rating"); $validator->addValidation("Question9","selone","Please select rating"); $validator->addValidation("Question10","selone","Please select rating"); $validator->addValidation("Question11","selone","Please select rating"); $validator->addValidation("Question12","selone","Please select rating"); $validator->addValidation("Question13","selone","Please select rating"); $validator->addValidation("Likes","maxlen=5120","The length of the input for Comments should not exceed 5120"); $validator->addValidation("Dislikes","maxlen=5120","The length of the input for Comments should not exceed 5120"); $validator->addValidation("Comments","maxlen=5120","The length of the input for Comments should not exceed 5120"); $formmailobj->addModule($validator); $datasender = new FM_FormDataSender($var32683,$var11682,"%Email%"); $datasender->AddToAddr("juergen.meyer@canterbury.ac.nz"); $formmailobj->addModule($datasender); $tu = new FM_ThankYouPage(); $tu->SetRedirURL("Thankyou.html"); $formmailobj->addModule($tu); $formmailobj->ProcessForm(); ?>