<?php
#-------------------------------------------------------------------------
# Module: simpleform
# Author: Rolf Tjassens
#-------------------------------------------------------------------------
# CMS Made Simple is (c) 2004 - 2011 by Ted Kulp (wishy@cmsmadesimple.org)
# CMS Made Simple is (c) 2011 - 2014 by The CMSMS Dev Team
# This project's homepage is: http://www.cmsmadesimple.org
# The module's homepage is: http://dev.cmsmadesimple.org/projects/simpleform
#-------------------------------------------------------------------------
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#-------------------------------------------------------------------------

function smarty_cms_function_simpleform($params, &$smarty) {
	
	$config = cmsms()->GetConfig();
	
	// Parameters and strings
	$have_captcha = '';
	$want_captcha = isset($params['captcha']) ? $params['captcha'] : '';
	$lang = isset($params['lang']) ? $params['lang'] : 'en';
	$name = isset($params['name']) ? $params['name'] : '';
	$email = isset($params['email']) ? $params['email'] : '';
	$subject = isset($params['subject']) ? $params['subject'] : '';
	$message = isset($params['message']) ? $params['message'] : '';
	$website = '';
	$error = $error_name = $error_email = $error_subject = $error_message = $error_captcha = '';
	
	$captcha = cms_utils::get_module('Captcha');
	if ( isset($captcha) ) { $have_captcha = TRUE; }
	
	if (empty($params['sendto'])) {
		echo '<div class="simpleform_text_error">An email address must be specified in order to use the <b>simpleform</b> plugin!</div>';
		return;
	} else {
		$sendto = $params['sendto'];
	}
	
	// Multilingual language strings
	if ( $lang == 'de' ) {
	$langstrings = 'submission_error:Fehler beim Versand,submission_successful:Die Nachricht wurde erfolgreich versandt,mail_error:Beim Versand der Nachricht ist ein Fehler aufgetreten,name:Name,email:E-mail,subject:Betreff,message:Nachricht,website:Webseite,spam_protection:Spamschutz,submit:Versenden'; }
	else if ( $lang == 'fr' ) {
	$langstrings = 'submission_error:Erreur de soumission&nbsp;,submission_successful:Mail correctement envoyé,mail_error:Erreur technique. Mail non envoyé,name:Nom,email:Email,subject:Sujet,message:Message,website:Site Web,spam_protection:Protection anti-spam,submit: Envoyer'; }
	else if ( $lang == 'hi' ) {
	$langstrings = 'submission_error:प्रस्तुत त्रुटि,submission_successful:मेल सफलतापूर्वक भेजा,mail_error:तकनीकी त्रुटि. मेल भेजा नहीं है,name:नाम,email:ईमेल,subject:विषय,message:संदेश,website:वेबसाइट,spam_protection:स्पैम सुरक्षा,submit:जमा करें'; }
	else if ( $lang == 'pt' ) {
	$langstrings = 'submission_error:Erro ao submeter formulário,submission_successful:Email enviado com sucesso,mail_error:Erro técnico. Email não foi enviado,name:Nome,email:Email,subject:Assunto,message:Mensagem,website:Website,spam_protection:Protecção anti-spam,submit:Submeter'; }
	else if ( $lang == 'nl' ) {
	$langstrings = 'submission_error:Verzendfout,submission_successful:Mail is succesvol verzonden,mail_error:Technische fout! Mail is niet verstuurd,name:Naam,email:E-mail,subject:Onderwerp,message:Bericht,website:Website,spam_protection:Spam beveiliging,submit:Versturen'; }
	else if ( $lang == 'no' ) {
	$langstrings = 'submission_error:Feil ved sending,submission_successful:E-post ble sendt,mail_error:Technical error. E-post ble ikke sendt,name:Navn,email:E-post,subject:Emne,message:Melding,website:Nettside,spam_protection:Søppelpost beskyttelse,submit:Send'; }
	// Your language not included? Update the xx's in these lines:
	else if ( $lang == 'xx' ) {
	$langstrings = 'submission_error:xx,submission_successful:xx,mail_error:xx,name:xx,email:xx,subject:xx,message:xx,website:xx,spam_protection:xx,submit:xx'; }
	else {
	$langstrings = 'submission_error:Submission error,submission_successful:Mail sent successfully,mail_error:Technical error. Mail is not sent,name:Name,email:Email,subject:Subject,message:Message,website:Website,spam_protection:Spam protection,submit:Submit'; }
	
	$lang = array();
	$strings = explode(',' , $langstrings);
	foreach ($strings as $string)
	{
		$part = explode(':' , $string, 2);
		$lang[$part[0]] = $part[1];
	}
	
	// Form submission
	if ($_SERVER['REQUEST_METHOD']=='POST')
	{
		if (!empty($_POST['name'])) $name = cfSanitize($_POST['name']);
		if (!empty($_POST['email'])) $email = cfSanitize($_POST['email']);
		if (!empty($_POST['subject'])) $subject = cfSanitize($_POST['subject']);
		if (!empty($_POST['message'])) $message = $_POST['message'];
		if (!empty($_POST['website'])) $website = $_POST['website'];
		if ( $have_captcha != '' && $want_captcha != '' ) 
		{
			if (!empty($_POST['captcha_response'])) { $captcha_response = $_POST['captcha_response']; }
		}
		
		// Mail headers
		$extra = "From: $name <$email>\r\n";
		$charset = isset(cmsms()->config['default_encoding']) && cmsms()->config['default_encoding'] != '' ? cmsms()->config['default_encoding'] : 'utf-8';
		$extra .= "Content-Type: text/plain; charset=" . $charset . "\r\n";
		
		// Errors
		if ( empty($name) ) { $error = 1; $error_name = 1; }
		if ( empty($email) ) { $error = 1; $error_email = 1; }
		if ( !validEmail($email) ) { $error = 1; $error_email = 1; }
		if ( empty($subject) ) { $error = 1; $error_subject = 1; }
		if ( empty($message) ) { $error = 1; $error_message = 1; }
		if ( $have_captcha != '' && $want_captcha != '' )
		{
			if ( empty($captcha_response) ) { $error = 1; $error_captcha = 1; }
			elseif (! ($captcha->checkCaptcha($captcha_response))) { $error = 1; $error_captcha = 1; }
		}
		
		// On error display error message, else sent email and show submission message
		if ( !empty($error) || $website != '' )
		{
			echo '<div class="simpleform_text_error"><p>' . $lang['submission_error'] . '!</p></div>';
		}
		elseif (@mail($sendto, $subject, $message . "\n\n\n\nIP: " . $_SERVER["REMOTE_ADDR"] . ' | ' . $_SERVER["HTTP_USER_AGENT"] , $extra))
		{
			echo '<div><p>' . $lang['submission_successful'] . '!</p></div>';
			return;
		} else {
			echo '<div class="simpleform_text_error"><p>' . $lang['mail_error'] . '!</p></div>';
			return;
		}
	}
	
    if (isset($_SERVER['REQUEST_URI'])) 
    {
        $action = $_SERVER['REQUEST_URI'];
    }
    else
    {
        $action = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : '';
        if (isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != '') 
        {
            $action .= '?'.$_SERVER['QUERY_STRING'];
		}
	}
?>

<div class="simpleform">
	<form action="<?php echo $action ?>" method="post">
	<div<?php if ($error_name != '') echo ' class="simpleform_text_error"'; ?>>
		<label for="name"><?php echo $lang['name']; ?> :</label>
		<input type="text" id="name" name="name" value="<?php echo htmlspecialchars($name); ?>" />
	</div>
	<div<?php if ($error_email != '') echo ' class="simpleform_text_error"'; ?>>
		<label for="email"><?php echo $lang['email']; ?> : </label>
		<input type="email" id="email" name="email" value="<?php echo htmlspecialchars($email); ?>" />
	</div>
	<div<?php if ($error_subject != '') echo ' class="simpleform_text_error"'; ?>>
		<label for="subject"><?php echo $lang['subject']; ?> : </label>
		<input type="text" id="subject" name="subject" value="<?php echo htmlspecialchars($subject); ?>" />
	</div>
	<div<?php if ($error_message != '') echo ' class="simpleform_text_error"'; ?>>
		<label for="message"><?php echo $lang['message']; ?> : </label>
		<textarea id="message" name="message" rows="12" cols="48"><?php echo htmlspecialchars($message); ?></textarea>
	</div>
	<div class="simpleform_website">
		<label for="website"><?php echo $lang['website']; ?> : </label>
		<input type="text" id="website" name="website" value="<?php echo htmlspecialchars($website); ?>" />
	</div>
<?php

if ( $have_captcha != '' && $want_captcha != '' ) 
{
?>
	<div<?php if ($error_captcha != '') echo ' class="simpleform_text_error"'; ?>>
		<label for="captcha"><?php echo $lang['spam_protection']; ?> : </label>
		<input type="text" id="captcha" name="captcha_response" value="" />
<?php
		echo '<div>' . $captcha->getCaptcha() . '</div>';
?>
	</div>
<?php
}
?>
	<div>
		<label>&nbsp;</label>
		<input type="submit" class="button" value="<?php echo $lang['submit']; ?>" /> 
	</div>
	</form>
	</div>

<?php
} // End of function

function smarty_cms_help_function_simpleform() {
?>

<div id="page_tabs">
    <div id="general">General</div>
	<div id="start">Getting started</div>
	<div id="stylesheet">Sample stylesheet</div>
	<div id="support">Support</div>
    <div id="copyright">Copyright and License</div>
</div>

<div id="page_content">
	<div id="general_c">
		<p>The <b>simpleform</b> plugin displays a simple contact form at the website. It is a one file plugin and doesn't have an Admin page.<br />
		It provides a name, an email, a subject and a message field. All fields can be pre-filled automatically.<br />
		The lay-out and the supplied sample stylesheet supports responsive webdesign.<br />
		<br />
		If you need more extended features, you should install the CMSMS <a href="http://dev.cmsmadesimple.org/projects/formbuilder" target="_blank">Formbuilder module</a> &raquo;<br />
		<br />
		<b>Anti-spam features</b><br />
		Honeypot anti-spam - This protection is always enabled. The idea is that automated web bots only look for the form fields and can't resist to add some information. As the specific <em>"website"</em> field is hidden from real, human visitors you know it should never contain anything.<br />
		Captcha - The <em>simpleform</em> plugin supports the CMSMS <a href="http://dev.cmsmadesimple.org/projects/captcha" target="_blank">Captcha module</a>, to enable it you need to add the captcha parameter to the plugin tag.</p>
	</div>
	<div id="start_c">
		<p><b>Installation guide:</b><br />
		<b>1.</b> Copy the file <em>function.simpleform.php</em> to the plugins folder of the CMSMS website<br />
		<br />
		<b>2.</b> Create a stylesheet and attach it to the page template. For help go to the <a href="http://docs.cmsmadesimple.org/layout/stylesheets#basic-usage" target="_blank">CMSMS docs website</a> &raquo;<br />
		   The content of the stylesheet is in the next tab "Sample stylesheet"<br />
		<br />
		<b>3.</b> Read the plugins help text in the Admin panel, go to Extentions >> Tags and click on the name <em>simpleform</em><br />
		<br />
		<b>4.</b> Just insert the tag with the required (and optional) parameters into the page or template. Some examples are:</p>
		<br />
		<p><b>Required:</b></p>
		<p style="border:1px solid #ddd; padding:10px; background-color:#f3f3f3"><code>{simpleform sendto='name@domain.com'}</code></p>
		<br />
		<p><b>Optional:</b></p>
		<p style="border:1px solid #ddd; padding:10px; background-color:#f3f3f3"><code>{simpleform sendto='name@domain.com,name@otherdomain.com'}</code></p>
		<br />
		<p style="border:1px solid #ddd; padding:10px; background-color:#f3f3f3"><code>{simpleform sendto='name@domain.com' lang='nl'}</code></p>
		<br />
		<p style="border:1px solid #ddd; padding:10px; background-color:#f3f3f3"><code>{simpleform sendto='name@domain.com' captcha='true'}</code></p>
		<br />
		<p style="border:1px solid #ddd; padding:10px; background-color:#f3f3f3"><code>{simpleform sendto='name@domain.com' captcha='true' lang='de'}</code></p>
		<br />
		<p style="border:1px solid #ddd; padding:10px; background-color:#f3f3f3"><code>{simpleform sendto='name@domain.com' captcha='true' lang='nl' subject='Informatie aanvraag'}</code></p>
		<br />
		<p>Multilingual websites, where $lang is a two character language code:</p>
		<p style="border:1px solid #ddd; padding:10px; background-color:#f3f3f3"><code>{simpleform sendto='name@domain.com' lang=$lang}</code></p>
		<br />
		
		<p><b>Parameters:</b></p>
		<ul>
			<li><b>sendto <em>(required)</em></b> - Comma seperated list of email addresses that the message will be sent to.</li>
			<li>captcha - Use Captcha response test (Captcha module must be installed). Default value is false.</li>
			<li>lang - Change the language of the form and email. Available are: en(default), de, fr, hi, pt, nl and no.<br /></li>
			<li>name - Gives the name field a default value, which can be overwritten by the website visitor.</li>
			<li>email - Gives the email field a default value, which can be overwritten by the website visitor.</li>
			<li>subject - Gives the subject field a default value, which can be overwritten by the website visitor.</li>
			<li>message - Gives the message field a default value, which can be overwritten by the website visitor.</li>
		</ul>
		<br />
	</div>
	<div id="stylesheet_c">
		<p>A sample stylesheet:</p>
<pre>
[[* +++++ Multiple Used Values +++++ *]]
[[assign var='label_width' value='150']]
[[assign var='field_width' value='300']]
[[assign var='field_border' value='border: #ccc solid 2px;']]
[[assign var='field_border_hover' value='border: #666 solid 2px;']]
[[capture assign='rounded_corners']]border-radius: 5px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;[[/capture]]

[[* +++++ Stylesheet +++++ *]]
.simpleform div {
  margin: 0 0 5px 0;
}
.simpleform div div {
  margin: 0 0 0 [[$label_width]]px;
  padding: 0 0 5px 0;
}
.simpleform input[type="email"],
.simpleform input[type="text"],
.simpleform textarea {
  width: [[$field_width]]px;
  margin: 0 5px 0 0;
  font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
  font-size: 13px;
  [[$field_border]]
  [[$rounded_corners]]
}
.simpleform textarea {
  height: 100px;
}
.simpleform input[type="email"]:hover,
.simpleform input[type="text"]:hover,
.simpleform textarea:hover {
  [[$field_border_hover]]
  cursor: default;
}
.simpleform input[type="submit"] {
  width: [[$field_width+4]]px;
  margin: 10px 0 0 0;
  [[$field_border]]
  [[$rounded_corners]]
  cursor: pointer;
}
.simpleform input[type="submit"]:hover {
  [[$field_border_hover]]
}
.simpleform label {
  width: [[$label_width]]px;
  float: left;
}
.simpleform_text_error {
  color: #f00;
  font-weight: bold;
}
.captchapict {
  width: [[$field_width]]px;
  [[$field_border]]
  [[$rounded_corners]]
}
.simpleform_website,
.simpleform_website * {
  display: none !important;
}
</pre>
		<br />
	</div>
	<div id="support_c">
		<p>This module does not contain any commercial support. If you have problems, ask for help in the:</p>
		<ul>
			<li><a href="http://forum.cmsmadesimple.org/" target="_blank">CMS Made Simple forums</a>,</li>
			<li><a href="irc://irc.freenode.net/cms" target="_blank"><abbr title="Internet Relay Chat">IRC</abbr> chat</a>,</li>
			<li>or write an email to the author</li>
		</ul>
		<br />
	</div>
	<div id="copyright_c">
		<p>Copyright &copy; 2014, Rolf Tjassens [rolf at cmsmadesimple dot org]. All Rights Are Reserved.</p>
		<br />
		<p>This module has been released under the <a href="http://www.gnu.org/licenses/licenses.html#GPL" target="_blank">GNU Public License v3</a>.<br />
		However, as a special exception to the GPL, this software is distributed as an add on module to CMS Made Simple&trade;.<br />
		You may only use this software when there is a clear and obvious indication in the Admin section that the site was built with <b>CMS Made Simple&trade;</b>.</p>
	</div>	
</div>

<?php
} // End of function

function smarty_cms_about_function_simpleform() {
        ?>
		<p>Author: Rolf Tjassens [rolf at cmsmadesimple dot org]</p>
		<p>Version: 1.0</p>
		<p>Change History:</p>
		<ul>
			<li>08-08-2014 - Initial release</li>
			<li>This plugin is based on the contact_form plugin created by Brett Batie and Simon van der Linden</li>
		</ul>
		<?php
} // End of function

function cfsanitize($content) {
        return str_replace(array("\r", "\n"), "", trim($content));
} // End of function

function validEmail($email) {
        if (!preg_match("/^([\w|\.|\-|_]+)@([\w||\-|_]+)\.([\w|\.|\-|_]+)$/i", $email)) {
                return false;
                exit;
        }
        return true;
} // End of function

#
# End of file
#
?>