<?php

/**
 * Obfuscates email address with mailto: to help prevent spam
 *
 * This function will re-format email addresses into inline JavaScript. The 
 * mailto: and following email address are obfuscated with base64 encoding and
 * output into a JavaScript function which then displays the mailto: link 
 * correctly. This function helps prevent spam by obfuscating plain text email 
 * addresses.
 *
 * @function securemail()
 *
 * @param (string) $email the email address to obfuscate
 * @param (string) $text  a text alternative to an email address to be displayed
 *
 * @return (string) 	  inline JavaScript that displays mailto: email address
 * 
 * @since 1.1.8
 *
 */
function securemail( $email, $text = '' ) {
	$text = ( $text == '' ) ? $email : $text;
	$uid = substr( 's' . base64_encode( mt_rand() ), 0, 8 );
	$link = base64_encode( "<a href=\"mailto:$email\">$text</a>" );
    return "<script id=\"$uid\">$uid.outerHTML=atob('$link')</script>";
}

/**
 * Obfuscates mailto: links in the mail content
 *
 * This function will replace plain text mailto: links within the WoprdPress
 * content to obfuscated inline JavaScript.
 *
 * @function securemail_content()
 *
 * @uses securemail()
 *
 * @param (string) $content the WordPress content
 *
 * @return (string) 		the Wordpress content after mailto: links have been 
 *							obfuscated
 * 
 * @since 1.1.1
 *
 */
function securemail_content( $content ) {
	
	$regex = '/<a href=[\"\']mailto:([^\"\']*)[\"\']>([^\"\'\<\>]*)<\/a>/i';
	
	if ( preg_match_all( $regex, $content, $matches, PREG_SET_ORDER ) ) {

		foreach ( $matches as $match ) {
			
			$to_replace = $match[0];
			$email = $match[1];
			$text = $match[2];
			$content = str_replace( $to_replace, securemail( $email, $text ), $content );
		}
	}
	return $content;
}
add_filter( 'the_content', 'securemail_content' );