<?php
### GENERATES UNIQUE CODE ###################################################
	if (!function_exists('getUniqueCode')) :
		function getUniqueCode( $length = "" ) {
			$code = md5(uniqid(rand(), true));
		 	if ($length != "") return substr($code, 0, $length); else return $code;
		}
	endif;
### SANITIZE - A variable cleaning function #################################
function clean_var($variable) {
	return strip_tags(stripslashes(trim(rtrim($variable))));
}
### Break text into chunks for direct messages
function blow_chunks_on_twitter( $content ) {
	$content = trim(implode(' - ', $content)." - Sent via Jigowatt WordPress AJAX Contact Forms");
	$content = chunk_split( $content, 134, "<!--Break_ME-->" );
	$content = explode( "<!--Break_ME-->", $content );
	$content = array_filter($content);
	// Prepend and append each chunk with ...
	$content = array_map('add_dots_to_array', $content);
	// Remove Last ...
	$content[(sizeof($content)-1)] = "...".str_replace('...','',$content[(sizeof($content)-1)]);
	// Remove First ...
	$content[0] = str_replace('...','',$content[0])."...";
	// Send in reverse order so it makes sense in Twitter
	$content = array_reverse($content);
	return $content;
}
function add_dots_to_array( $string ) {
	return '...'.$string.'...';
}
###  Twitter Direct Message CURL function ###################################################
function twittermessage($user, $message, $consumer_key, $consumer_secret, $token, $secret) { // Twitter Direct Message function, do not edit.
	require_once('twitter/EpiCurl.php');
    require_once('twitter/EpiOAuth.php');
    require_once('twitter/EpiTwitter.php');
	$Twitter = new EpiTwitter($consumer_key, $consumer_secret);
    $Twitter->setToken($token, $secret);
    $direct_message = $Twitter->post_direct_messagesNew( array('user' => $user, 'text' => $message) );
    $tweet_info = $direct_message->responseText;
}
### PROCESS A POSTED FORM ###################################################
function process_jigowatt_form( $form ) {
	if(!$_POST || !$form) return;
		global $found_shortcodes;
		$posted = array();
		$error = '';
		$headers = '';
		/* Scan the form's code for shortcodes and find out which are required */
		$form_code = strip_tags($form->form_code);
		$found_shortcodes = array();
		$comments = array();
		add_shortcode('input_box', 'jigowatt_find_shortcode');
		add_shortcode('select_box', 'jigowatt_find_shortcode');
		add_shortcode('message_box', 'jigowatt_find_shortcode');
		do_shortcode($form_code);
		remove_shortcode('input_box');
		remove_shortcode('select_box');
		remove_shortcode('message_box');
		foreach ($found_shortcodes as $field) :
			if ($field['name']) :
				if ($field['type']=='submit') continue; // no need to process submit boxes
				$posted[$field['name']] = $_POST['jigowatt_'.$field['name']];
				$comments[] = "".ucwords($field['name']).": ".PHP_EOL."\t\t".stripslashes($posted[$field['name']]);
				// Required field
				if ($field['required']=="true" && empty($posted[$field['name']])) :
					 $error .= '<li>Escribe algo en el mensaje</li>';
					
					// duplico arriva: $error .= '<li>“'.ucwords($field['name']).'” '.__(': campo obligatorio','jigowatt').'.</li>';
				endif;
				// Types
				if ($field['type']) :
					switch ($field['type']) :
						case "email" :
							if(!is_email($posted[$field['name']])) $error .= __('<li>Dirección de email incorrecta</li>','jigowatt');
							//$headers = "From: ".$posted[$field['name']]."\r\n\\";
							//$headers .= "Reply-To: info@example.com\r\n\\";
							// To send HTML mail, the Content-type header must be set
							//$headers  = 'MIME-Version: 1.0' . "\r\n";
							$headers = 'Content-type: text/html; charset=utf-8' . "\r\n";
							
							// Additional headers. 
							// en el plugin WP SMTP para que autentique
							$mail_interesado = $posted[$field['name']];
							$headers .= 'From: VendoAndroid <buzonautomatico@vendoandroid.com>' . "\r\n";
							$headers .= 'Reply-to: '.$mail_interesado.'' . "\r\n";
							
							$address = get_the_author_meta('user_email', $author_id);
							
						break;
					endswitch;
				endif;
			endif;
		endforeach;
		$posted = array_map('clean_var', $posted);
		// Captcha
		if ( isset($_POST['jigowatt_image_captcha']) ) :
			if (isset($_POST['jigowatt_image_captcha'])) :
		    	$posted_verify   = trim(stripslashes($_POST['jigowatt_image_captcha']));
		   		$posted_verify   = md5($posted_verify);
		   	else :
		   		$posted_verify = '';
		   	endif;
			$session_verify = $_SESSION['verify'];
			if (empty($session_verify)) $session_verify = $_COOKIE['verify'];
			if($session_verify != $posted_verify) {
	    		$error .= __('<li>Código antispam incorrecto</li>','jigowatt');
	    	}
		endif;
		
		
		if($error != '') {
			echo '<div class="error_message">'.__('¡Atención! Algo falla:','jigowatt').'';
			echo '<ul class="error_messages">' . $error . '</ul>';
			echo '</div>';
		} else {
		$post_tmp = get_post($_REQUEST['current_post_id']);
		$author_id = $post_tmp->post_author;
		$address = get_the_author_meta('user_email', $author_id);
		$e_subject = __('Alguien se ha interesado por tu anuncio en VendoAndroid','jigowatt');
		// Advanced Configuration Option.
		// You can change this if you feel that you need to.
		// Developers, you may wish to add more fields to the form, in which case you must be sure to add them here.
		$msg  = __('¡Hola! Un usuario se ha interesado en tu anuncio:'). PHP_EOL . PHP_EOL;
		$msg .= __('<a href="'.get_permalink($post_tmp).'">Título:'.get_the_title($post_tmp).' target="_blank"</a>') . PHP_EOL . PHP_EOL;
		$msg .= implode(PHP_EOL, $comments) . PHP_EOL . PHP_EOL;
		$msg .= "-------------------------------------------------------------------------------------------\r\n";
		$msg .= 'Mensaje enviado desde <a href="http://vendoandroid.com" target="_blank"><strong>VendoAndroid.com</strong></a>';
		$msg = wordwrap( $msg, 70 );
		$twitter_data = unserialize($form->twitter_data);
		if(isset($twitter_data['twitter_name']) && isset($twitter_data['twitter_ckey']) && isset($twitter_data['twitter_csecret']) && isset($twitter_data['twitter_token']) && isset($twitter_data['twitter_secret'])) {
			// Spilt into smaller messages if its long
			$twitter_msg = blow_chunks_on_twitter($comments);
			foreach ($twitter_msg as $t) :
				twittermessage($twitter_data['twitter_name'], $t, $twitter_data['twitter_ckey'], $twitter_data['twitter_csecret'], $twitter_data['twitter_token'], $twitter_data['twitter_secret']);
			endforeach;
		}
		if( wp_mail($address, $e_subject, $msg, $headers) ) {
			 echo "<fieldset>";
			 echo "<div id='success_page'>";
			 echo __("<h3>¡Hecho!</h3>",'jigowatt');			 
			 echo __("<p>Tu mensaje ha sido enviado al anunciante.</p>",'jigowatt');
			 echo "</div>";
			 echo "</fieldset>";
		 } else {
			 echo __('¡Huy! Error. Prueba de nuevo.','jigowatt');
		 }
	}
}