Skip to content

Instantly share code, notes, and snippets.

@mikemattner
Last active December 11, 2015 02:58
Show Gist options
  • Save mikemattner/4534130 to your computer and use it in GitHub Desktop.
Save mikemattner/4534130 to your computer and use it in GitHub Desktop.
Core.js - This is the core of the JavaScript that I use on my own website using a combination of plugins and custom code. send.php - Using ajax, I then process data from the contact form on my site using a custom class (class.mmemail.php) in conjunction with the PHPMailer class.
<?php
// ~ class.mmemail.php
/**
* MM Email - PHPMailer Component Class
* NOTE: Requires PHP version 5 or later and PHPMailer
* PHPMailer - PHP email transport class - https://code.google.com/a/apache-extras.org/p/phpmailer/
* @author Mike Mattner
* @copyright 2011 Mike Mattner
* @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
*/
class mmEmail {
var $data = null;
var $time = null;
var $SMTP_host = null;
var $SMTP_username = null;
var $SMTP_password = null;
var $from = null;
var $from_name = null;
var $send_to = null;
var $send_name = null;
var $subject = null;
var $html_tmp = null;
var $txt_tmp = null;
static $instance;
public function __construct() {
self::$instance = $this;
}
public function format($pee, $br = 1) {
if ( trim($pee) === '' )
return '';
$pee = $pee . "\n"; // just to make things a little easier, pad the end
$pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
// Space things out a little
$allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)';
$pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
$pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
$pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
if ( strpos($pee, '<object') !== false ) {
$pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
$pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
}
$pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
// make paragraphs, including one at the end
$pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
$pee = '';
foreach ( $pees as $tinkle )
$pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
$pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
$pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
$pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
$pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
$pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
$pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
if ($br) {
$pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
$pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
$pee = str_replace('<WPPreserveNewline />', "\n", $pee);
}
$pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
$pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
if (strpos($pee, '<pre') !== false)
$pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
$pee = preg_replace( "|\n</p>$|", '</p>', $pee );
return $pee;
}
public function template($template) {
$sent = $this->data;
$time = $this->time;
$html_tmp = $this->html_tmp;
$text_tmp = $this->txt_tmp;
switch( $template ) {
case 'html' :
$message = $this->format($sent['message']);
ob_start();
@include( $html_tmp );
$body = ob_get_contents();
ob_end_clean();
break;
case 'text' :
ob_start();
@include( $text_tmp );
$body = ob_get_contents();
ob_end_clean();
break;
default :
break;
}
return stripslashes($body);
}
public function send() {
$html_body = $this->template('html'); //HTML Body
$text_body = $this->template('text'); //Text only body
require("class.phpmailer.php");
$mail = new PHPMailer();
$mail->IsSMTP(); //SMTP
$mail->Host = $this->SMTP_host;
$mail->SMTPAuth = true;
$mail->Username = $this->SMTP_username;
$mail->Password = $this->SMTP_password;
$mail->From = $this->from;
$mail->FromName = $this->from_name;
$mail->AddReplyTo($this->from, $this->from_name);
$mail->AddAddress($this->send_to, $this->send_name);
$mail->Subject = $this->subject;
$mail->IsHTML(true);
$mail->Body = $html_body;
$mail->AltBody = $text_body;
$result = $mail->Send();
if($result)
{
echo 'Mail sent.';
}
else
{
$result = $mail->ErrorInfo;
return $result;
}
}
}
?>
$(document).ready(function() {
// add prettyprint class to all <pre><code></code></pre> blocks
var prettify = false;
$("pre code").parent().each(function() {
$(this).addClass('prettyprint');
21 $(this).addClass('linenums');
prettify = true;
});
// if code blocks were found, bring in the prettifier...
if ( prettify ) {
$.getScript("http://www.mikemattner.com/wp-content/themes/v8mikemattner.com/assets/js/prettify/src/prettify.js", function() { prettyPrint() });
}
$('textarea').autosize();
/*Contact Form - Borrowed code*/
var Messages = {
loader: jQuery('<div class="loading"><img src="../images/loader.gif" /></div>'),
thanks: jQuery('<div class="success">Thanks for getting in touch!</div>'),
error: jQuery('<div class="errorm er">There seems to be a problem with the form, please try again.</div>'),
code: jQuery('<div class="errorm ercode">There seems to be a problem: </div>'),
};
var contact_form = jQuery('#contact_form');
var color = $('#check').attr('value');
$("dl.details label").inFieldLabels({ fadeOpacity: 0.25 });
$('#contactform').validate({
rules: {
email: {
required: true,
email: true
},
name: {
required: true
},
subject: {
required: true
},
message: {
required: true,
minlength: 1
},
check: {
required: true,
remote: "http://www.mikemattner.com/process/check.php"
}
},
messages: {
name: "Name required.",
message: "Say something...",
subject: "What's this about?",
email: {
required: "Email required.",
email: "Need valid email."
},
check: "THAT'S not right..."
},
errorElement: "label",
errorPlacement: function(error, element) {
error.insertAfter(element)
},
showErrors: function(errorMap, errorList, element, errorClass) {
var errorListSize = errorList.length;
this.defaultShowErrors();
if(errorListSize > 0) {
$('label.error').each(function() {
if ($(this).find('span').length <= 0) {
$(this).wrapInner('<span></span>');
}
});
}
},
success: function(label) {
label.remove()
},
submitHandler: function(form) {
var $this = jQuery(form);
$this.fadeTo('fast',0.25); //this hides the form
if (contact_form.find('.loading').length <= 0) {
contact_form.prepend(Messages.loader);
} else {
contact_form.find('.loading').show();
}
jQuery.ajax({
type: "POST",
url: $this.attr("action"),
data: $this.serialize(),
success: function(data, status) {
contact_form.find('.loading').delay('1000').fadeOut('fast');
$this.delay('1000').clearForm();
$("dl.details label").unbind().delay('1000').show().animate({ opacity: 1.0 }, 'fast').inFieldLabels({ fadeOpacity: 0.25 });
$this.fadeTo('fast',1.0);
if (contact_form.find('.success').length <= 0) {
setTimeout(function() {
contact_form.prepend(Messages.thanks);
contact_form.find('.success').delay('5000').fadeOut('fast');
}, 1000);
} else {
contact_form.find('.success').delay('1000').show();
contact_form.find('.success').delay('5000').fadeOut('fast');
}
},
error: function(xhr, status, error) {
contact_form.find('.loading').hide();
if (contact_form.find('.er').length <= 0) {
contact_form.prepend(Messages.error);
contact_form.find('.er').delay('5000').fadeOut('fast');
} else {
contact_form.find('.er').show();
contact_form.find('.er').delay('5000').fadeOut('fast');
}
$this.fadeTo('fast',1.0);
}
});
}
});
//Activate FancyBox
$("a[href$='.jpg'],a[href$='.png'],a[href$='.gif']").fancybox({
openEffect : 'elastic',
closeEffect : 'elastic',
padding : 0,
helpers : {
title : {
type : 'over'
}
}
});
//Randomize an RGBA color
function hue() {
var hue = 'rgba(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',1.0)';
return hue;
}
//Randomize link hover color
$("article section a,article h2 a, .about article a, article a, #footer a").hover(
function () {
$(this).css('color', hue());
},
function () {
$(this).removeAttr( 'style' );
}
);
$(".prev, .next, article .email_us a, .subme, #smart-archives-list ul li a,a.port_site_link,a.download_file,.portfolio-list ul li a").hover(
function () {
$(this).css({'background': hue(), 'color': '#fff'});
},
function () {
$(this).removeAttr( 'style' );
}
);
$(".find_more").hover(
function () {
var color = hue();
$(this).css({'background': color, 'border-color': color, 'color': '#fff'});
},
function () {
$(this).removeAttr( 'style' );
}
);
var l = 0;
function fancyActivate(){
//Button and Archive Link Backgrounds
$(".ed_perm .permalink a, .ed_perm a.post-edit-link").hover(
function () {
$(this).css({'background': hue(), 'color': '#fff'});
},
function () {
$(this).removeAttr( 'style' );
}
);
$('.ed_perm .permalink a').tipsy({gravity: 's', fade: true});
$('.ed_perm .post-edit-link').tipsy({gravity: 's', fade: true});
$("article.images .light-box .image-content, article.gallery .light-box .image-content").css({'opacity': 0.0});
$("article.images .light-box, article.gallery .light-box").hover(
function () {
$(this).find('.image-content').stop().animate({
opacity: 1.0
}, 400);
},
function () {
$(this).find('.image-content').stop().animate({
opacity: 0.0
}, 400);
}
);
l = 1;
}
function fancyDeactivate(){
$(".ed_perm .permalink a, .ed_perm a.post-edit-link, article.images .light-box, article.gallery .light-box").unbind();
$("article.images .light-box .image-content, article.gallery .light-box .image-content").css({'opacity': 1.0});
l = 0;
}
var width = $(window).width();
if(width > 958) {
if(l != 1) {
fancyActivate();
}
}
$(window).resize(function() {
var width = $(window).width();
if(width > 958) {
if(l != 1) {
fancyActivate();
}
}
if(width < 959) {
if ( l == 1 ) {
fancyDeactivate();
}
}
});
function _form_remove_class() {
var surround = $(".searchform_me");
var form = $(".searchform");
if ( ( form.val() == form.defaultValue ) || ( form.val() == '' ) ) {
surround.removeClass('searchform_me_hover');
}
}
function _form_add_class() {
var surround = $(".searchform_me");
surround.addClass('searchform_me_hover');
}
$(".searchform").click(_form_add_class).focus(_form_add_class).focusout(_form_remove_class).blur(_form_remove_class);
$("#logo a").hover(
function () {
$(this).stop().animate({
opacity: 0.5
}, 400);
},
function () {
$(this).stop().animate({
opacity: 1.0
}, 400);
}
);
$("a.pancake_link").hover(
function () {
$(this).find('span.btn').stop().animate({
opacity: 1.0
}, 100);
},
function () {
$(this).find('span.btn').stop().animate({
opacity: 0.0
}, 400);
}
);
$("a.proj_link").hover(
function () {
$(this).find('span.btn').stop().animate({
opacity: 1.0
}, 100);
},
function () {
$(this).find('span.btn').stop().animate({
opacity: 0.0
}, 400);
}
);
/*SHOW THE ADDITIONAL SEARCH OPTIONS*/
$('#search_btn').toggle(function() {
$('#further').animate({
opacity: 'show'/*,
height: 'toggle'*/
}, 400);
$("#search_btn").html("Close &uarr;");
$(this).addClass("search_icon_close");
$('#sr_btn').addClass("sr_btn_close");
}, function() {
$('#further').animate({
opacity: 'hide'/*,
height: 'toggle'*/
}, 400, function() {
$('#search_btn').removeClass("search_icon_close");
$('#sr_btn').removeClass("sr_btn_close");
$("#search_btn").html("Explore More &darr;");
});
});
$('#share_me').sharrre({
share: {
twitter: true,
facebook: true,
googlePlus: true
},
template: '<div class="box"><a href="#" class="twitter"><i class="icon-twitter"></i> Tweet</a><a href="#" class="facebook"><i class="icon-facebook-sign"></i> Like</a><a href="#" class="googleplus"><i class="icon-google-plus-sign"></i> Google+</a></div>',
enableHover: false,
enableTracking: true,
render: function(api, options){
$('.twitter').on('click', function() {
api.openPopup('twitter');
});
$('.facebook').on('click', function() {
api.openPopup('facebook');
});
$('.googleplus').on('click', function() {
api.openPopup('googlePlus');
});
}
});
});
<?php
/*
.-------------------------------------------------------------------------------.
| SEND EMAIL USING class.mmemail.php in conjucntion with class.phpmailer.php |
'-------------------------------------------------------------------------------'
*/
// Begin the session
session_start();
//POSTED FROM EMAIL FORM - Don't edit
$sent = array(
"name" => stripslashes($_POST['name']),
"email" => stripslashes($_POST['email']),
"subject" => stripslashes($_POST['subject']),
"message" => stripslashes($_POST['message']),
"ip_addr" => stripslashes($_POST['addr']),
"check" => stripslashes($_POST['check'])
);
/*
.--------------------------------------------------------.
| These are your basic settings |
'--------------------------------------------------------'
*/
$config = array(
// REQUIRED VALUES ------------------------------------
"timezone" => "TZ=America/Detroit", // Choose one of these: http://php.net/manual/en/timezones.php
"send_to" => "hello@mikemattner.com", // Address you'll be sending your email too.
"send_name" => "Mike Mattner", // Name associated with above address.
"smtp" => array(
"host" => "mail.mikemattner.com", // SMTP Host
"username" => "email@mikemattner.com", // SMTP Username
"password" => "password" // SMTP Password
),
//TEMPLATE NAMES - Change names as needed
"html_template" => "default_html.php", // File name for HTML template
"text_template" => "default_txt.php" // File name for basic text template
);
/*
.--------------------------------------------------------.
| DONT'T EDIT - Define a few constants. |
'--------------------------------------------------------'
*/
//Set Time Zone, and Time.
putenv($config['timezone']);
define('TIME',date('m/d/Y @ h:i a'));
//Constants for your message - if useful add more
define('NAME', $sent['name']); //Name of person sending you form data
define('EMAIL', $sent['email']); //What is the person's email
define('SUBJECT', $sent['subject']); //What are they discussing
define('MESSAGE', $sent['message']); //The message
//SMTP Login Info
define('SMTP_HOST', $config['smtp']['host']);
define('SMTP_USERNAME', $config['smtp']['username']);
define('SMTP_PASSWORD', $config['smtp']['password']);
//Who to send email, and the email subject
define('SEND_TO', $config['send_to']);
define('SEND_NAME', $config['send_name']);
//Templates and Directories
define( HTML_PATH, dirname( __FILE__ ) );
define( HTML_TEMPLATE_DIR, HTML_PATH . '/templates/' );
define( HTML_BASE_TEMPLATE, HTML_TEMPLATE_DIR . $config['html_template'] );
define( HTML_TXT_TEMPLATE, HTML_TEMPLATE_DIR . $config['text_template'] );
require("includes/class.mmemail.php");
$email = new mmEmail();
//////////////////////////////////////////////////////////////////////////////////////////
//EMAIL REQUEST
//////////////////////////////////////////////////////////////////////////////////////////
//Let's make sure we're human.
if(strtolower($_POST['check']) == strtolower($_SESSION['check_human'])) {
$email->data = $sent;
$email->time = TIME;
$email->SMTP_host = SMTP_HOST;
$email->SMTP_username = SMTP_USERNAME;
$email->SMTP_password = SMTP_PASSWORD;
$email->from = EMAIL;
$email->from_name = NAME;
$email->send_to = SEND_TO;
$email->send_name = SEND_NAME;
$email->subject = SUBJECT;
$email->html_tmp = HTML_BASE_TEMPLATE;
$email->txt_tmp = HTML_TXT_TEMPLATE;
$email->send();
} else {header("HTTP/1.1 403 Forbidden");}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment