<?php 
/*
Plugin Name: Smart form ajax
Plugin URI: http://www.naxialis.com
Description: Smart form ajax avec captchat
Author: Naxialis
Version: 2.0
Author URI: http://www.naxialis.com
License: GPL2

/********************** Setup, Install, Unistall*********************/
//Adds a shortcut action link in the plugin page, next to the activate and edit links 
add_filter('plugin_action_links', 'sfa_action_link', 10, 2);

/*Activation and deactivation hooks*/
register_activation_hook( __FILE__, 'sfa_db_install' );
register_deactivation_hook( __FILE__, 'sfa_db_uninstall');

//Creates a settings shortcut link
function sfa_action_link($link, $file) 
{
    static $sfa_plugin;

    if (!$sfa_plugin) {
        $sfa_plugin = plugin_basename(__FILE__);
    }

    if ($file == $sfa_plugin) 
	{       
        $settings_link = '<a href="' . get_bloginfo('wpurl') . '/wp-admin/admin.php?page=sfa-settings">'.__('Settings','sacf').'</a>';
        array_unshift($link, $settings_link);
    }

    return $link;
}

//Creates option array when plugin is activated
function sfa_db_install() 
{
    	$sfa_options = array(
			'b_name' => '',
			'b_email' => '',
			'captcha'=>'1',
			'c_color'=>'#0b83c2',
			'c_font'=>'arial.ttf',
			'c_size'=>'12',
			'subject'=>'1',
			's_name'=>'',
			's_address'=>'',
			'form_size'=>'100',
			'subject_req'=>'1',
			'phone_req'=>'1',
			'phone_mask'=>''
		);
		
		$sfa_msg_options = array(
			'empty' => 'Remplissez les champs suivant',
			'email_nv' => 'Vous devez entrer une adresse e-mail valide',
			'w_captcha'=>'Erreur captcha',
			'e_captcha'=>'Captcha est vide',
			'e_phone'=>'Entrer votre numéro de téléphone',
			'sub_req'=>'Entrer un sujet pour votre méssage',
			'success'=>'Merci, nous vous contacterons bientôt.'
		);
		
		if( !get_option( 'sfa_msg_settings' ))
		add_option( 'sfa_msg_settings', $sfa_msg_options );
		
		if( !get_option( 'sfa_settings' ))
		add_option( 'sfa_settings', $sfa_options );
}

//Delete option array when plugin is deactivated
function sfa_db_uninstall()
{
     delete_option('sfa_settings');
	 delete_option('sfa_msg_settings');
	 unset($_SESSION["secureWord"]);
}



/**************** Initializes plugin on Admin Page*************************/
//Initialize external files and creates a menu
add_action( 'admin_init', 'sfa_admin_init' );
add_action( 'admin_menu', 'sfa_admin_menu');					// Displays a option menu under the main OPTIONS menu
add_action( 'init', 'sfa_init_session', 1);

//Initializes external admin CSS and JS files
function sfa_admin_init() 
{
	//Loads CSS and JS files to Admin menu
	wp_enqueue_style( 'sacfAdminStyle', plugins_url( 'css/sacf-admin-style.css', __FILE__ ),array('farbtastic'));
	wp_enqueue_script( 'sacfAdminScript', plugins_url( 'js/sacf-admin-script.js', __FILE__ ),array('jquery','farbtastic'),'1.0',true);		
}

 //Sets up the admin menu
function sfa_admin_menu()
{
add_menu_page( __('Smart Form Ajax Contact - Options Page','sacf'), //Menu title
							__('SFA Settings','sacf'),  //Page Title
							'manage_options',  // The capability required for access to this item
							'sfa-settings', 		// the slug to use for the page in the URL
							'sfa_form_settings');	// The function to call to render the page
							
add_submenu_page('sfa-settings', __('Settings','sacf'), __('Settings','sacf'), 'manage_options', 'sfa-settings','sfa_form_settings');
add_submenu_page('sfa-settings', __('Edit Messages','sacf'), __('Edit Messages','sacf'), 'manage_options', 'sfa_test','sfa_error_settings');
//add_submenu_page('sacf', 'General', 'General', 'manage_options', 2,'sfa_form_settings'); 
}

 //Adds info links to Admin footer - Disabled by default
function sfa_admin_footer() 
{
	$plugin_data = get_plugin_data( __FILE__ );
	printf('%1$s plugin | Version %2$s | by %3$s | %4$s<br />', $plugin_data['Title'], $plugin_data['Version'], $plugin_data['Author'],'<a href="http://www.naxialis.com/">Site Web</a>');	
}

//Gets data from get_option('sfa_settings'); - Thisi is used by radio inputs
function sfa_getVal($type)
{
	$options = get_option('sfa_settings');
	return ( $options[$type] );
}

//Gets error messages from get_option('sfa_msg_settings');
function sfa_displayError($type)
{
	$eoptions = get_option('sfa_msg_settings');	
	$errorType = '<span class="errorMsg">'.$eoptions[$type].'</span><br/>';	
	return $errorType;
}

//Displays success message
function sfa_displayMsg($type)
{
	$eoptions = get_option('sfa_msg_settings');	
	$msgType = '<span id="successMsg">'.$eoptions[$type].'</span><br/>';	
	return $msgType;
}

//Displays SACF settings form in Admin's page
function sfa_form_settings()
{
	 if (!current_user_can('manage_options')) 
	 wp_die("Vous n'avez pas les permissions suffisantes pour accéder à cette page.");
    
	else
	include_once('sfa_form.php');
}

//Displays SACF error messages form in Admin's page
 function sfa_error_settings()
 {
	if (!current_user_can('manage_options')) 
	 wp_die("Vous n'avez pas les permissions suffisantes pour accéder à cette page.");
    
	else
	include_once('sfa_error_settings.php'); 
 }

//Adds a submenu to Settings menu - disabled by default
function sfa_admin_actions() 
{
	add_options_page("Simple Ajax Contact Form - Options Page", "SACF Options", 1, "SACF", "sfa_admin");
}


/********************** Displays Contact Form *******************************/
add_action( 'wp_enqueue_scripts', 'sfa_load_client_script');
add_shortcode( 'sfa_contact_form', 'sfa_display_form');   //enter this in your post or page [sfa_contact_form] to display the contact form
add_action('wp_head', 'sfa_load_into_head' ); 
 // AJAX add actions
add_action( 'wp_ajax_the_ajax_hook', 'sfa_process_form' );
add_action( 'wp_ajax_nopriv_the_ajax_hook', 'sfa_process_form' ); // need this to serve non logged in users

//Process our contact form using AJAX	
function sfa_process_form()
{
	include_once('proccess.php');
}

//loads client JS file
function sfa_load_client_script()
{
	wp_enqueue_style( 'sacfStyle', plugins_url( 'css/sacf-contact-form-style.css', __FILE__ ));	
	wp_enqueue_script( 'sacfPhoneMask', plugins_url( 'js/jquery.maskedinput-1.3.min.js', __FILE__ ));
		
	//Ajax
	wp_enqueue_script( 'my-ajax-handle', plugin_dir_url( __FILE__ ) . 'js/sacf-script.js');	
    wp_localize_script( 'my-ajax-handle', 'the_ajax_script', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );	
}

//adds js to the head of your template
function sfa_load_into_head() 
{ 
$sfa_options = get_option('sfa_settings');
$cap = '
<script type="text/javascript"> 

	function reloadCaptcha()
	{
		var time = new Date();
		var current = time.getTime();
		jQuery("#scf-captcha-img").attr("src","'.plugins_url( 'captcha.php', __FILE__ ).'?x="+ current);
		
	}
</script>'; 
echo $cap;
} 

//Displays contact form
function sfa_display_form()
{
	global $sfa_options;
	$sfa_options = get_option('sfa_settings');
	$sfa_test ='';
	
	$sfa_test = '<div style="width:'.$sfa_options['form_size'].'%; float:left;">
								<form id="scf-form" action="" method="POST">
									<div id="scf-msg" class="allCorners"></div>
									
									<label><b>*</b>'. __("Name",'sacf') .'</label>
									<input type="text" name="scf-name" class="txt" id="scf-name" /><div class="sfa_clear"></div>
									
							
																		
									</label>';
									
									$sfa_test .= '<label>';
									$sfa_test .= __('Prénom','sacf') .'</label>
																	<input type="text" name="scf-prenom" class="txt" id="scf-prenom" /><div class="sfa_clear"></div>';
									
									if($sfa_options['phone_req'] == '1')
									{
										$sfa_test .= '<b>*</b>';
									}
									$sfa_test .= '<label>';
									$sfa_test .=  __('Telephone','sacf') .'</label>
									<input type="text" name="scf-phone" class="txt" id="scf-phone" /><div class="sfa_clear"></div>
									
									<label><b>*</b>'. __('E-Mail','sacf') .'</label>
									<input type="text" name="scf-email" class="txt" id="scf-email" /><div class="sfa_clear"></div>';

									
									
									// post type
									
									$sfa_test .= '<label>';
									$sfa_test .= __('Votre demande','sacf') .'</label>
									<select class="select" id="scf-post-type" name="scf-post-type">';
									$sfa_test .= '<option value="">---------------</option>'; 
									
									
									$sfa_test .= '<option value="Affiliations&#8211;partenariats" '. selected( $_POST['selected'], 'Affiliations&#8211;partenariats' ) .'>Affiliations&#8211;partenariats</option>
									<option value="Articles&#8211;contenus du site" '. selected( $_POST['selected'], 'Articles&#8211;contenus du site' ).'>Articles&#8211;contenus du site</option>
			<option value="Comptabilite" '. selected( $_POST['selected'], 'Comptabilit&eacute;' ).'>Comptabilit&eacute;</option>
			<option value="Devis" '. selected( $_POST['selected'], 'Devis' ).'>Devis</option>
			<option value="Formations&#8211;Analyses de risques dans votre Ets" '. selected( $_POST['selected'], 'Formations&#8211;Analyses de risques dans votre Ets' ).'>Formations&#8211;Analyses de risques dans votre Ets</option>
			<option value="Inscriptions&#8211;Statut membre" '. selected( $_POST['selected'], 'Inscriptions&#8211;Statut membre' ).'>Inscriptions&#8211;Statut membre</option>
			<option value="Jobs" '. selected( $_POST['selected'], 'Jobs' ).'>Jobs</option>
			<option value="Propositions&#8211;Critiques" '. selected( $_POST['selected'], 'Propositions&#8211;Critiques' ).'>Propositions&#8211;Critiques</option>';
									
									 
									$sfa_test .= '<option value="">Autre</option>';
									$sfa_test .= '</select>';
									
									// post type fin
									
									if($sfa_options['subject'] == '1')
									{
										$sfa_test .= '<label>';
										if($sfa_options['subject_req'] == '1')
										{
											$sfa_test .= '';
										}
										
										$sfa_test .= __('Si autre précisez','sacf') .'</label>
																	<input type="text" name="scf-subject" class="txt" id="scf-subject" /><div class="sfa_clear"></div>';
									}
									
								
									
		$sfa_test .= '<label><b>*</b>'. __('Votre demande','sacf') .'</label>
									<textarea id="scf-comment" name="scf-comment" class="txtarea" ></textarea><div class="sfa_clear"></div>';
									
									
									if($sfa_options['captcha'] == '1')
									{
										$sfa_test .= '<label>Capcha : </label><img border="0" id="scf-captcha-img" src="'.plugins_url( 'captcha.php', __FILE__ ).'" alt="Captcha"><a href="JavaScript: reloadCaptcha();" /><img class="refresh" border="0" alt="Click here" src="'.plugins_url( 'images/refresh.png', __FILE__ ).'" /></a>
									
										
											<input type="text" maxlength="6" name="scf-captcha" id="scf-captcha" />
										';
									}									
									
		$sfa_test .=  '<div id="submit_cont">
									<div id="loader"></div>
									<input type="submit" name="scf-submit" id="scf-submit" value="'. __('Send','sacf') .'" />
								</div>
									<input name="action" type="hidden" value="the_ajax_hook" />
									
								</form></div><div class="sfa_clear"></div>';
								
	return $sfa_test;
	
}


/**************************** Extra functions *******************************/
//start session and loads languages
function sfa_init_session()
{	
	if (!session_id())
	session_start();
	
	load_plugin_textdomain('sacf', false, basename(dirname(__FILE__)) . '/language/');
}

//Converts HEX to RGB colors
function sfa_HexToRGB($hex) 
{
	$hex = ereg_replace("#", "", $hex);
	$color = array();		
		$color['r'] = hexdec(substr($hex, 0, 2));
		$color['g'] = hexdec(substr($hex, 2, 2));
		$color['b'] = hexdec(substr($hex, 4, 2));		
	return $color;
}

//Displays fonts type from the font directory
function sfa_selectFont()
{			
			$fileCount=1;
			$filePath= WP_PLUGIN_DIR ."/smart-form-ajax/fonts/";
			$dir = opendir($filePath); 
			
			
			while ($file = readdir($dir)) 
			{ 
				 if (preg_match("/\.ttf/i",$file))// || eregi("\.TTF",$file)) 
				 { 			 
					$displayFont = strtoupper(substr($file, 0, strlen($file)-4));
				 	$options = get_option('sfa_settings');
					if ( $file == $options['c_font'] )
					{
						echo '<input type="radio" name="sfa_fontGroup" id="font_'.$fileCount.'" class="radioType" value="'.$file.'" checked="checked" />'. $displayFont.'<div class="sfa_clear"></div>';
					}
					else
					{
						echo '<input type="radio" name="sfa_fontGroup" id="font_'.$fileCount.'" class="radioType" value="'.$file.'" />'. $displayFont.'<div class="sfa_clear"></div>';
					}					
					$fileCount++;
				  }
			}	
			closedir($dir);
}

//sends email 
function sfa_send_email($sender,$last_name,$s_email,$phone,$sub,$post_type,$autres,$comment)
{
	$sfa_options = get_option('sfa_settings');
	
	$display_subject = $sfa_options['subject_req'];
	$sendTo = $sfa_options['b_email'];
	
	
	$emailSubject = 'Contact ' .$sfa_options['b_name'];
	
	
	
	
	$dateSent = date(" d-m-Y \a H:i:s");  
	// Send email in HTML format, the Content-type header must be set
	$headers  = "MIME-Version: 1.0" . "\r\n";
	$headers .= "Content-type: text/html; charset=\"".get_settings('blog_charset')."\"\r\n";		
	$headers .= "From: " .$sender." <" .$s_email. ">" ."\r\n";
	
	$message = '
																					
							<table>								
								<tr><td><b>'.__('Nom', 'sacf').'</b></td><td>'.$sender.'</td></tr>
								
								<tr><td><b>'.__('Prénom', 'sacf').'</b></td><td>'.$last_name.'</td></tr>
								
								<tr><td><b>'.__('Téléphone', 'sacf').'</b></td><td>'.$phone.'</td></tr>';
								
								$message .= '<tr><td><b>'.__('Email', 'sacf').'</b></td><td>'.$s_email.'</td></tr>';
								
								$message .= '<tr><td><b>'.__('Autre','sacf').'</b></td><td>'.stripslashes($autres).'</td></tr>';
								
								$message .= '<tr><td><b>'.__('Demande','sacf').'</b></td><td>'.stripslashes($post_type).'</td></tr>';
								
								
								
								$message .= '<tr><td><b>'.__('Date', 'sacf').'</b></td><td>'.$dateSent.'</td></tr>
							</table><br/>
							
							<div>
								
								'.stripslashes($comment).'
								
							</div>';
							
																					
							
	mail($sendTo, $emailSubject, $message, $headers);
}

?>