<?php
/**
 * CHRONOFORMS version 1.0 stable
 * Copyright (c) 2006 Chrono_Man, ChronoEngine.com. All rights reserved.
 * Author: Chrono_Man (ChronoEngine.com)
 * See readme.html.
 * Visit http://www.ChronoEngine.com for regular update and information.
 **/

/* ensure that this file is called by another file */
defined('_JEXEC') or die('Restricted access');



/**
 * Load the HTML class
 */
require_once( JApplicationHelper::getPath( 'front_html' ) ); 
require_once( JApplicationHelper::getPath( 'class' ) );

$posted = array();
$posted = $_POST;
/**
 * Main switch statement
 */
switch( $task ) {
	case 'send':
		uploadandmail();
		break;
	default:
		showform($posted);
		break;
}
/**
 * End of main page
 *
 */

/**
 * Display the form for entry
 *
 */
function showform($posted)
{
    global $mainframe;
	$database =& JFactory::getDBO();

    $formname = JRequest::getVar( 'chronoformname', '', 'get', 'string', '' );
    //$formname = $_GET['chronoformname'];
	if ( !$formname ) {
		$query = "
            SELECT params
                FROM #__menu
                WHERE id='".$_GET['Itemid']."' AND type='component'";
		$database->setQuery( $query );
		$menudata = $database->loadResult();
		if ( $menudata ) {
			$registry = new JRegistry();
			$registry->loadINI( $menudata );
			$configs = $registry->toObject( );
			$formname = $configs->formname;
		}
	}
	$imver = "";
    $query = "
	   SELECT *
	       FROM #__chrono_contact
	       WHERE name = '$formname'";
    $database->setQuery( $query );
    $rows = $database->loadObjectList();
    $registry = new JRegistry();
	$registry->loadINI( $rows[0]->paramsall );
	$paramsvalues = $registry->toObject( );
    if ( trim($paramsvalues->imagever) == 'Yes' ) {
        $imver = '<input name="chrono_verification" type="text" id="chrono_verification" value="">
            &nbsp;&nbsp;<img src="'.JURI::Base()
            .'components/com_chronocontact/chrono_verification.php?imtype='.$paramsvalues->imtype.'">';
    }
	
	$htmlstring = $rows[0]->html;
	
	if( trim($paramsvalues->validate) == 'Yes'){
	// Easy Validation //
			preg_match_all('/name=("|\').*?("|\')/i', $htmlstring, $matches);
			$arr_required = explode(",", str_replace(" ","",$paramsvalues->val_required));
			$arr_validate_number = explode(",", str_replace(" ","",$paramsvalues->val_validate_number));
			$arr_validate_digits = explode(",", str_replace(" ","",$paramsvalues->val_validate_digits));
			$arr_validate_alpha = explode(",", str_replace(" ","",$paramsvalues->val_validate_alpha));
			$arr_validate_alphanum = explode(",", str_replace(" ","",$paramsvalues->val_validate_alphanum));
			$arr_validate_date = explode(",", str_replace(" ","",$paramsvalues->val_validate_date));
			$arr_validate_email = explode(",", str_replace(" ","",$paramsvalues->val_validate_email));
			$arr_validate_url = explode(",", str_replace(" ","",$paramsvalues->val_validate_url));
			$arr_validate_date_au = explode(",", str_replace(" ","",$paramsvalues->val_validate_date_au));
			$arr_validate_currency_dollar = explode(",", str_replace(" ","",$paramsvalues->val_validate_currency_dollar));
			$arr_validate_selection = explode(",", str_replace(" ","",$paramsvalues->val_validate_selection));
			$arr_validate_one_required = explode(",", str_replace(" ","",$paramsvalues->val_validate_one_required));
			
			$arr_all = array_merge($arr_required, $arr_validate_number, $arr_validate_digits, $arr_validate_alpha, $arr_validate_alphanum, $arr_validate_date, $arr_validate_email, $arr_validate_url, $arr_validate_date_au, 
			$arr_validate_currency_dollar, $arr_validate_selection, $arr_validate_one_required);
			
			foreach ($matches[0] as $match)
			{
				$new_match = preg_replace('/name=("|\')/i', '', $match);
				$new_match2 = preg_replace('/("|\')/', '', $new_match);
				$name = preg_replace('/name=("|\')/', '', $new_match2);
				$class_array = array();
				if(in_array($name,$arr_all)){
					if(in_array($name,$arr_required)){
						$class_array[] = "required";
					}
					if(in_array($name,$arr_validate_number)){
						$class_array[] = "validate-number";
					}
					if(in_array($name,$arr_validate_digits)){
						$class_array[] = "validate-digits";
					}
					if(in_array($name,$arr_validate_alpha)){
						$class_array[] = "validate-alpha";
					}
					if(in_array($name,$arr_validate_alphanum)){
						$class_array[] = "validate-alphanum";
					}
					if(in_array($name,$arr_validate_date)){
						$class_array[] = "validate-date";
					}
					if(in_array($name,$arr_validate_email)){
						$class_array[] = "validate-email";
					}
					if(in_array($name,$arr_validate_url)){
						$class_array[] = "validate-url";
					}
					if(in_array($name,$arr_validate_date_au)){
						$class_array[] = "validate-date-au";
					}
					if(in_array($name,$arr_validate_currency_dollar)){
						$class_array[] = "validate-currency-dollar";
					}
					if(in_array($name,$arr_validate_selection)){
						$class_array[] = "validate-selection";
					}
					if(in_array($name,$arr_validate_one_required)){
						$class_array[] = "validate-one-required";
					}
					$class_string = implode(" ",$class_array);
					$htmlstring = str_replace($match,$match.' class="'.$class_string.'"',$htmlstring);
				}
			}
		$rows[0]->html = $htmlstring;
		}
	/// end validation //
	
	
    HTML_ChronoContact::showform( $rows , $imver);
}

/**
 * Respond to a submitted form
 *
 */
function uploadandmail()
{
    global $mainframe;
	$database =& JFactory::getDBO();
		
		// Block SPAM through the submit URL
		if ( empty($_POST) ) {
			echo "You are not allowed to access this URL directly, POST array is empty";
			return;
		}
    

    /**
     * Retrieve form data from the database
     */
    $formname = JRequest::getVar( 'chronoformname', '', 'get', 'string', '' );
    //$formname = $_GET['chronoformname'];
    $query     = "
	   SELECT *
	       FROM #__chrono_contact
	       WHERE name='$formname'";
    $database->setQuery( $query );
    $rows = $database->loadObjectList();
	$registry = new JRegistry();
	$registry->loadINI( $rows[0]->titlesall );
	$titlesvalues = $registry->toObject( );
	$registry = new JRegistry();
	$registry->loadINI( $rows[0]->paramsall );
	$paramsvalues = $registry->toObject( );
	
    $error_found = false;
    /**
     * If imageversification is on check the code
     */
    if ( trim($paramsvalues->imagever) == 'Yes' ) {
		/*if (session_name() != md5('chrono')){
			session_write_close();
		}
		session_name(md5('chrono'));
		*/
		//session_start();
		$session =& JFactory::getSession();
		$sessionvar = $session->get('chrono_verification', 'default', md5('chrono'));
		$chrono_verification = strtolower($_POST['chrono_verification']);
		if ( md5($chrono_verification ) != $sessionvar ) {
			showErrorMessage('Sorry, You have entered a wrong verification code, Please try again!!');
			showform($_POST);
			return;
        }else{
			unset($_SESSION['chrono_verification']);
		}
    }
	
	/**
     * if $debug is true then ChronoForms will show diagnostic output
     */
    $debug = $paramsvalues->debug;
    if ( $debug ) {
        echo "_POST: ";
        print_r($_POST);
        echo "<br />";
    }

    /**
     * Upload attachments
     */
	$attachments = array();
	if ( trim($paramsvalues->uploads == 'Yes' ) && trim($paramsvalues->uploadfields) ) {
		//$allowed_s1 = explode(",", trim($paramsvalues->uploadfields));
			if ( is_array($paramsvalues->uploadfields) ) {
			$allowed_s1 = implode('|', $paramsvalues->uploadfields);
			} else {
			$allowed_s1 = $paramsvalues->uploadfields;
			}
			$allowed_s1 = explode(",", trim($allowed_s1));
		
		foreach ( $allowed_s1 as $allowed_1 ) {
			$allowed_s2      = explode(":", trim($allowed_1));
			$allowed_s3      = explode("|", trim($allowed_s2[1]));
			$original_name   = $_FILES[$allowed_s2[0]]['tmp_name'];
			$filename        = date('YmdHis').'_'.preg_replace('`[^a-z0-9-_.]`i','',$_FILES[$allowed_s2[0]]['name']);
			$fileok          = true;
			if ( $original_name ) {
				if ( ($_FILES[$allowed_s2[0]]["size"] / 1024) > trim($paramsvalues->uploadmax) ) {
					$fileok = false;
					showErrorMessage('Sorry, Your uploaded file size exceeds the allowed limit.');
					exit();
				}
				if ( ($_FILES[$allowed_s2[0]]["size"] / 1024) < trim($paramsvalues->uploadmin) ) {
					$fileok = false;
					showErrorMessage('Sorry, Your uploaded file size is less than the allowed limit');
					exit();
				}
				$fn     = $_FILES[$allowed_s2[0]]['name'];
				$fext   = substr($fn, strrpos($fn, '.') + 1);
				if ( !in_array($fext, $allowed_s3) ) {
					$fileok = true;
					showErrorMessage('Sorry, Your uploaded file type is not allowed');
					exit();
				}
				if ( $fileok ) {
					$uploadedfile = handle_uploaded_files($original_name, $filename);
					if ( $uploadedfile ) {
                        $attachments[$allowed_s2[0]] = $uploadedfile;
					}
				}
			}
		}
	}

	/* Do Onsubmit before_email plugins*/
	
	$ava_plugins = explode(",",$paramsvalues->plugins);
	$ava_plugins_order = explode(",",$paramsvalues->mplugins_order);
	//$ava_plugins_array = array();
	array_multisort($ava_plugins_order, $ava_plugins);
	foreach($ava_plugins as $ava_plugin){
		$query     = "SELECT * FROM #__chrono_contact_plugins WHERE form_id='".$rows[0]->id."' AND event='ONSUBMIT' AND name='".$ava_plugin."'";
		$database->setQuery( $query );
		$plugins = $database->loadObjectList();
		if(count($plugins)){
			require_once(JPATH_SITE."/components/com_chronocontact/plugins/".$ava_plugin.".php");
			${$ava_plugin} = new $ava_plugin();
			//$params = mosParseParams($plugins[0]->params);
			$registry3 = new JRegistry();
			$registry3->loadINI( $plugins[0]->params );
			$params = $registry3->toObject( );
			if($params->onsubmit == 'before_email'){
				${$ava_plugin}->onsubmit( 'com_chronocontact', $params, $plugins[0] );
			}
		}
	}


	/**
	 * If there are no errors and e-mail is required then build and send it.
	 */
	if ( ($rows[0]->emailresults != 0) && !$error_found ) {
	    /**
         * Clean the list of fields to be omitted from the results email
         */
	    if ( trim($paramsvalues->omittedfields ) != '' ) {
	       $omittedlist = explode(",", $paramsvalues->omittedfields);
        }
	    $htmlstring = $rows[0]->html;
	    /**
	     * Find all the 'name's in the html-string and add to the $matches array
	     */
	    preg_match_all('/name=("|\').*?("|\')/i', $htmlstring, $matches);
	    /**
	     * clean the matches array
	     */
	    $names = array();
	    foreach ( $matches[0] as $name ) {
	        $name = preg_replace('/name=("|\')/i', '', $name);
	        $name = preg_replace('/("|\')/', '', $name);
	        $name = preg_replace('/name=("|\')/', '', $name);
	        if ( strpos($name, '[]') ) {
	            $name = str_replace('[]', '', $name);
	        }
	        $names[] = trim($name);
	    }
	    $names = array_unique($names);
	    /**
	     * Associate field values with names and implode arrays
	     */
	    $fields = array();
	    foreach ( $names as $name ) {
	        if ( is_array($_POST[$name])) {
	            $fields[$name] = implode(", ", $_POST[$name]);
	        } else {
	            $fields[$name] = $_POST[$name];
	        }
	    }
	    /**
	     * Main E-mail type switch
	     *
	     * Case 2: Use 'my template'
	     * Case 3: Not in use
	     * Case 1 & default: use field titles
	     */
	    switch ($paramsvalues->email_type) {

	        case 2:
	            /**
	             * Use 'my template'
	             */
	            if ( $debug ) { echo "Case 2: Use template<br />"; }
	            $html_message = $rows[0]->emailtemplate;
				ob_start();
				eval( "?>".$html_message );
				$html_message = ob_get_clean();
				//ob_end_clean();
	            foreach ( $fields as $name => $post) {
				    $html_message = preg_replace("/\\{".$name."\\}/", $post, $html_message);
	            }
	            break;

	        case 3:
	            /**
	             * Not in use

	             $htmlstring2  = preg_replace('/(<input.*name=)(")(.*?)(")(.*>)/', '$3', $htmlstring);
	             $html_message = preg_replace('/(<select.*?name=)(")(.*?)(")(.*?select>)/s',
	           '$3', $htmlstring2);
	             */
	            if ( $debug ) { echo "Case 3: Under development<br />"; }
	            $html_message = 'Still under development';

	            break;

	        case 1:
	        default:
	            /**
	             * Use Field Titles and table layout (default)
	             */
	            if ( $debug ) { echo "Case 1: Use table layout<br />"; }
	            $col_names = array();
	            if ( !is_array($omittedlist) ) {
	                $omittedlist = array();
	            }
	            $html_message = "<table cellpadding='0' cellspacing='0' border='0' width='100%'>";
                foreach ( $fields as $name => $post) {
	                if ( in_array($name, $omittedlist) ) {
	                    continue;
	                }
	                /**
	                 * Substitute element titles for field names
	                 */
	                if ( trim($titlesvalues->$name) ) {
	                    $name = $titlesvalues->$name;
	                }
	                $html_message .= "<tr height='10'>
	                   <td width='40%' class='tablecell1'>$name</td>
	                   <td width='60%' class='tablecell2'>$post</td>
	                   </tr>";
	            }
	            $html_message .= "</table>";
	            break;
	    }
        /**
         * Add IP address if required
         */
	    if ( $paramsvalues->recip == "Yes" ) {
	        $html_message .= "<br /><br />Submitted by ".$_SERVER['REMOTE_ADDR'];
	    }
	    /**
	     * Wrap page code around the html message body
	     */
	    $html_message = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">
						  <html>
							  <head>
								  <title></title>
								  <base href=\"JURI::base()/\" />
								  <style type=\"text/css\">
								  "."
								  </style>
							  </head>
							  <body>$html_message</body></html>";
							  
	}
	    /**
	     * Run the On-submit 'pre e-mail' code if there is any
	     */
	    if ( !empty($rows[0]->onsubmitcodeb4) ) {
			eval( "?>".$rows[0]->onsubmitcodeb4 );
		}
	
	if ( ($rows[0]->emailresults != 0) && !$error_found ) {
		/**
		 * The send e-mail switch
		 * Case 1: 'Yes' standard (not in use)
		 * Case 2: 'Yes' custom (default)
		 */
	    switch ( $rows[0]->emailresults ) {
	        /**
	         * E-mail the results - 'Yes' standard
	         * Not in use!
	         */
	        case 1:
	            if ( $debug) { echo "E-mail: 'Yes' standard<br />"; }
	            $from        = $chronocontact_params->get('from_email');
	            $fromname    = $chronocontact_params->get('from_name');
	            $subject     = $chronocontact_params->get('subject');
	            $recipient[] = $chronocontact_params->get('primary_email');
	            break;

	        case 2:
	        default:
	            /**
	             * E-mail the results - 'Yes' custom
	             */
	            if ( $debug) { echo "E-mail: 'Yes' custom<br />"; }
	            $from      = $paramsvalues->from_email;
	            $fromname  = $paramsvalues->from_name;
	            $subject   = $rows[0]->emailsubject;
	            $recipient = str_replace(" ","",$rows[0]->extraemail);
	            $recipient = explode(",", $recipient);
				if(trim($paramsvalues->ccemail)){
					$ccemails = str_replace(" ","",$paramsvalues->ccemail);
					$ccemails = explode(",", $ccemails);
				}else{
					$ccemails = NULL;
				}
				if(trim($paramsvalues->bccemail)){
					$bccemails = str_replace(" ","",$paramsvalues->bccemail);
					$bccemails = explode(",", $bccemails);
				}else{
					$bccemails = NULL;
				}
				if(trim($paramsvalues->replyto_email)){
					$replyto_email = str_replace(" ","",$paramsvalues->replyto_email);
					$replyto_email = explode(",", $replyto_email);
				}else{
					$replyto_email = NULL;
				}
				if(trim($paramsvalues->replyto_name)){
					$replyto_name = str_replace(" ","",$paramsvalues->replyto_name);
					$replyto_name = explode(",", $replyto_name);
				}else{
					$replyto_name = NULL;
				}
	            break;
	    }
	    //$replyto   = $chronocontact_params->get('replyto_email');
        /**
         * Substitute field values if they are set
         */
	    if ( trim($paramsvalues->subjectfield) != "" ) {
	        $subject       = $_POST[$paramsvalues->subjectfield];
	    }
	    if ( trim($paramsvalues->fromemailfield) != "" ) {
	        $from          = $_POST[$paramsvalues->fromemailfield];
	    }
	    if ( trim($paramsvalues->fromnamefield) != "" ) {
	        $fromname      = $_POST[$paramsvalues->fromnamefield];
	    }
	    if ( trim($paramsvalues->emailfield) != "" ) {
	        $recipient[]   = $_POST[$paramsvalues->emailfield];
	    }
		if ( trim($paramsvalues->ccfield) != "" ) {
	        $ccemails[]   = $_POST[$paramsvalues->ccfield];
	    }
		if ( trim($paramsvalues->bccfield) != "" ) {
	        $bccemails[]   = $_POST[$paramsvalues->bccfield];
	    }
	    /**
	     * Send the email(s)
	     */
	    $email_sent = JUtility::sendMail($from, $fromname, $recipient, $subject, $html_message, true,
	       $ccemails, $bccemails, $attachments, $replyto_email, $replyto_name );
		if ( $debug ) {
			if ($email_sent)echo "Email sent ";
			if (!$email_sent)echo "Email not sent ";
		}
	    // :: HACK :: insert debug
		if ( $debug ) {
		    echo "<h4>E-mail message</h4>
            <div style='border:1px solid black; padding:6px;margin:6px;'>
		    <p>From: $fromname [$from]<br />
		    To:  ".implode($recipient,', ')."<br />
		    Subject: $subject</p>
		    $html_message<br /></div>";
		}
		// :: end hack ::

	}
	if ( !$error_found ) {
	/*************** check to see if order was specified, if not then use the default old one ************************/
		if((!$paramsvalues->plugins_order)&&(!$paramsvalues->onsubmitcode_order)&&(!$paramsvalues->autogenerated_order)){
			$paramsvalues->autogenerated_order=3;
			$paramsvalues->onsubmitcode_order=2;
			$paramsvalues->plugins_order=1;
		}
	
		for($ixx = 1 ; $ixx <= 3; $ixx++){
			if($paramsvalues->plugins_order == $ixx){
				$ava_plugins = explode(",",$paramsvalues->plugins);
				$ava_plugins_order = explode(",",$paramsvalues->mplugins_order);
				//$ava_plugins_array = array();
				array_multisort($ava_plugins_order, $ava_plugins);
				foreach($ava_plugins as $ava_plugin){
					$query     = "SELECT * FROM #__chrono_contact_plugins WHERE form_id='".$rows[0]->id."' AND event='ONSUBMIT' AND name='".$ava_plugin."'";
					$database->setQuery( $query );
					$plugins = $database->loadObjectList();
					if(count($plugins)){
						require_once(JPATH_SITE."/components/com_chronocontact/plugins/".$ava_plugin.".php");
						${$ava_plugin} = new $ava_plugin();
						$registry2 = new JRegistry();
						$registry2->loadINI( $plugins[0]->params );
						$params = $registry2->toObject( );
						if($params->onsubmit != 'before_email'){
							${$ava_plugin}->onsubmit( 'com_chronocontact', $params , $plugins[0] );
						}
					}
				}
			}
			/**
			 * Run the On-submit 'post e-mail' code if there is any
			 */
			if($paramsvalues->onsubmitcode_order == $ixx){
				if ( !empty($rows[0]->onsubmitcode) ) {
					eval( "?>".$rows[0]->onsubmitcode );
				}
			}
	
			/**
			 * Run the SQL query if there is one
			 */
			if($paramsvalues->autogenerated_order == $ixx){
				if ( !empty($rows[0]->autogenerated) ) {
					eval( "?>".$rows[0]->autogenerated );
				}
			}
		}
		/**
		 * Redirect the page if requested
		 */
		if ( !empty($rows[0]->redirecturl) ) {
			$mainframe->redirect($rows[0]->redirecturl);
		}
		//}
	}
}
/**
 * Handle uploaded files
 *
 * @param unknown_type $uploadedfile
 * @param string $filename
 * @param string $limits
 * @param string $directory
 * @return unknown
 */
function handle_uploaded_files($uploadedfile, $filename, $limits = TRUE, $directory = FALSE)
{
    //global $mosConfig_absolute_path, $mosConfig_fileperms;
	//$fileperms = "0644";
    /*if ( strlen($mosConfig_fileperms) > 0 ) {
        $fileperms = octdec($mosConfig_fileperms);
    }*/
    $uploaded_files = "";
    $upload_path = JPATH_SITE.'/components/com_chronocontact/upload/';
    if ( is_file($uploadedfile) ) {
        $targetfile = $upload_path.$filename;
        while ( file_exists($targetfile) ) {
            $targetfile = $upload_path.rand(1,1000).'_'.$filename;
        }
        move_uploaded_file($uploadedfile, $targetfile);
        //if ( strlen($fileperms) > 0 ) {
        //    chmod($targetfile, $fileperms);
        //}
        $uploaded_files = $targetfile;
    }
    return $uploaded_files;
}

/**
 * Display JavaScript alert box as error message
 *
 * @param string $message
 */
function showErrorMessage($message) {
    echo "<script> alert('$message'); </script>\n";
}
?>