All pastes #590354 Raw Edit

Unnamed

public text v1 · immutable
#590354 ·published 2007-06-26 14:40 UTC
rendered paste body
<?php
/* 
Plugin Name: Mail List
Version: beta 0.91
Plugin URI: http://www.blue-anvil.com
Author: <a href="http://www.blue-anvil.com">Mike Jolley</a>
Description: Allows anyone to register for a newsletter/mailing list. Automatically adds registered users to the list.
*note: Mail() function headers based on the 'mass mailer' plugin by Brance Gillihan (http://www.clearblueproductions.com).
Thanks to Anthony Brewwit (www.designbit.co.uk for the form validation)
========================================================================================
&#65533; Copyright 2006  Mike Jolley  (jolley dot small at googlemail dot com)

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.
*/ 

function wp_maillist($content)
{
	global $submenu;
	add_management_page('MailList', 'MailList', 6, basename(__FILE__), 'maillist_admin');
	add_submenu_page('post.php', __("Write email", "MailList"), __("Write email", "MailList"), 6, basename(__FILE__), 'maillist_write');
}
add_action('admin_menu', 'wp_maillist');

function maillist_css() {
?>
<style type="text/css">
<!--
	.error{background: lightcoral;border: 1px solid #e64f69;margin: 1em 5% 10px;padding: 0 1em 0 1em;}
	.center		{ text-align: center;	}
	.right		{ text-align: right;	}
	.left		{ text-align: left;		}
	.top		{ vertical-align: top;	}
	.bold		{ font-weight: bold;	}
	.private	{ color: #e64f69;		}
	a:link,a:visited,a:hover{text-decoration:none;border:none;}
	#bar{margin:64px;margin-top:16px;margin-bottom:16px;padding:8px;background-color:#F1F1F1;}	

  .form {
  	position: static;overflow: hidden;
  }
	.form legend{color:#999;font-weight:bold;font-size:1.3em;}
  .form label{font-size:1.2em; color:#333; font-weight:bold;}
  .formleft {width: 20%;text-align: right;
  	clear: both;float: left;display: inline;padding: 4px;	margin: 5px 0;
  }
  .formright {
  	width: 75%;	text-align: left;	float: right;	display: inline;	padding: 4px;	margin: 5px 0;	color:#555;
	}
	.validateform input:focus{border:1px solid red;}
  	
//-->
</style>
<!--validation for adding users-->
<script language="javascript" type="text/javascript">

/*you ready mike here we go, presenting the mikeForm*/
/* ok this first bit validates email using regular expression variable (re) this makes sure amongst other things that theres no whitespace, that theres a peroid, thats theres an @ sign etc etc, u owe me for the extra attention on this bit */
re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;	

function submitIt(mikeForm) {				/* when user tries to send from it calls this function (submitIt) */

if(mikeForm.user_name.value == "")	{		/* if user_name value is null, alert box, return false and highlight field */
alert("you must enter a Username")				
mikeForm.user_name.focus()	
return false
}	

if(mikeForm.user_email.value == "")	{		/* if user_email value is null, alert box, return false and highlight field */
alert("you must enter a email address")				
mikeForm.user_email.focus()	
return false
}	

if (re.test(mikeForm.user_email.value)) {	/* test checks the validity of email against variable re valid returns true */
return true
}
alert("Invalid email address")				/* invalid returns false, and alert box */
mikeForm.user_email.focus()
mikeForm.user_email.select()
return false
}

</script>
<?php
}
add_action('admin_head', 'maillist_css');

# make the form display on content where tag found
add_filter('the_content', 'maillist_signup_form');
# the signup form output function
function maillist_signup_form($content='') {

# prepare forms
$mailform=$_REQUEST['mailform'];
$user_name=$_REQUEST['mail_name'];
$user_email=$_REQUEST['mail_address'];

if ($mailform=='submit') {
    if ((empty($user_name) || empty($user_email))){
    	 $code='2';
    }
    else {
    	 $code='1'; 
			 global $wpdb;
			 $compare = $wpdb->get_results("SELECT * FROM `WP_MAILLIST` WHERE user_email='$user_email' LIMIT 1;");
    	 if ( empty($compare) ) {			
   		 		 # add if not there
					$num = rand(100000, 999999);					
					$wpdb->query("INSERT INTO WP_MAILLIST (mail_key, user_name, user_email, user_registered, listed) VALUES ('$num', '$user_name', '$user_email', 'false', 'true')");
   				} else {
					$wpdb->query("UPDATE WP_MAILLIST SET listed='true' WHERE user_email='$user_email';");
          $code='3';
					}
}}
if ($code=='1'){
$forms='<p>You have successfully joined the mailing list.</p>';
} elseif ($code=='2'){
	$forms='<p>Please fill in all of the fields.</p>';
	$forms.='<form id="maillist_form" name="editthemail" action="'.$PHP_SELF.'?mailform=submit" method="post">';
	$forms.='<div class="label"><label for="mail_name">Your name</label></div>';
	$forms.='<div class="input"><input type="text" name="mail_name" value="'.$user_name.'" /></div>';
	$forms.='<div class="label"><label for="mail_address">Your email address</label></div>';
	$forms.='<div class="input"><input type="text" name="mail_address" value="'.$user_email.'" /></div>';									
	$forms.='<div class="input"><input type="submit" value="Submit" class="submit"/></div>';
	$forms.='</form>';
} elseif ($code=='3'){
	$forms='<p>You are in the mailing list.</p>';
}
else {
  $forms='<form id="maillist_form" name="editthemail" action="'.$PHP_SELF.'?mailform=submit" method="post">';
	$forms.='<div class="label"><label for="mail_name">Your name</label></div>';
	$forms.='<div class="input"><input type="text" name="mail_name" /></div>';
	$forms.='<div class="label"><label for="mail_address">Your email address</label></div>';
	$forms.='<div class="input"><input type="text" name="mail_address" /></div>';									
	$forms.='<div class="input"><input type="submit" value="Submit" class="submit"/></div>';
	$forms.='</form>';
}

# string replace, looking for <!--mail_sign_up-->
$content = str_replace("<!--mail_sign_up-->", "$forms", "$content");
return $content;
}

add_action('wp_head', 'maillist_form_css');
function maillist_form_css() {
echo '<link rel="stylesheet" type="text/css" media="screen" href="'.get_bloginfo('wpurl').'/wp-content/plugins/maillist.css" />';
}


function maketables(){

#check if the tables exist already
				  global $wpdb, $tableposts, $tablepost2cat;
          $tableExists = false;
					$tableExists2 = false;
					$tableExists3 = false;
          $tables = $wpdb->get_results("show tables;");
          foreach ( $tables as $table )
          {
          	foreach ( $table as $value )
          	{
          		if ( $value == WP_MAILLIST )
          		{$tableExists=true;}
							if ( $value == WP_MAILLIST_OPTIONS )
          		{$tableExists2=true;}
							if ( $value == WP_MAILLIST_CACHE )
          		{$tableExists3=true;}
          	}
          }					
					if ( !$tableExists2 )
          {          	$sql = "CREATE TABLE WP_MAILLIST_OPTIONS (
          				 		`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                      `sender` TEXT NULL ,       						
                      `reply` TEXT NULL ,
                      `title` TEXT NULL ,
          						`postsnumber` TEXT NULL ,
											`postscats` TEXT NULL ,
											`footer` TEXT NULL ,
          				PRIMARY KEY ( `id` )
          			)";
          	$wpdb->get_results($sql);   
						$wpdb->query("INSERT INTO WP_MAILLIST_OPTIONS (sender, reply, title, postsnumber, postscats, footer) VALUES ('LorumIpsum.com', 'Lorum@Ipsum.com', 'Recent articles from LorumIpsum.com', '4', '15,13', 'Copyright LorumIpsum.com 2006')");
          	
          }
					
					if ( !$tableExists3 )
          {          	$sql = "CREATE TABLE WP_MAILLIST_CACHE (
          				 		`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,                               						
                      `user_id` INT UNSIGNED NOT NULL ,
          				PRIMARY KEY ( `id` )
          			)";
          	$wpdb->get_results($sql);          	
          }
          if ( !$tableExists )
          {          	$sql = "CREATE TABLE WP_MAILLIST (
          				 		`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
                      `mail_key` FLOAT UNSIGNED NOT NULL,          						
                      `user_name` VARCHAR ( 20 ) NOT NULL ,
                      `user_email` VARCHAR ( 100 ) NOT NULL UNIQUE,
          						`user_registered` VARCHAR ( 20 ) NULL ,
											`listed` VARCHAR ( 20 ) NOT NULL ,
          				PRIMARY KEY ( `id` )
          			)";
          	$wpdb->get_results($sql);          	
          }
#return to where called from
return;
}

function reindex(){

#this function checks whether any new users exist, if so adding them to the mailing list (if they havent already unsubscibed)
global $wpdb;
$users = $wpdb->get_results("SELECT * FROM `wp_users`;");
foreach ($users as $user) {
# check users table against mailing list table
$compare = $wpdb->get_results("SELECT * FROM `WP_MAILLIST` WHERE user_email='$user->user_email' LIMIT 1;");
    if ( empty($compare) ) {
	
		 if ( !empty($user->user_email) ) {
    # add if not there
		$num = rand(100000, 999999);
		$wpdb->query("INSERT INTO WP_MAILLIST (mail_key, user_name, user_email, user_registered, listed) VALUES ('$num', '$user->user_nicename', '$user->user_email', 'true', 'true')");
   
		}
		}//end compare if
		else {
				  $id=$compare[0]->id;
      		//they are registered and in maillist, so make sure they show up as 'registered;
      		if ($compare[0]->user_registered=='true'){
					//do nothing
      		} else {
      		$wpdb->query("UPDATE WP_MAILLIST SET user_registered='true',user_name='$user->user_nicename' WHERE id=$id;");
          }          				
		}
}//end foreach

#now check for deleted users
$users = $wpdb->get_results("SELECT * FROM `WP_MAILLIST`;");
  foreach($users as $user){
  		$compare = $wpdb->get_results("SELECT * FROM `wp_users` WHERE user_email='$user->user_email' LIMIT 1;");
			 if ( empty($compare) ) {
			 $id=$user->id;
			 #user doesent exist anymore
			 $wpdb->query("UPDATE WP_MAILLIST SET user_registered='false' WHERE id=$id;");		 
			 }
  }
}

function sendmail_preview(){
global $wpdb;
# get user options from table
$option = $wpdb->get_results("SELECT * FROM `WP_MAILLIST_OPTIONS` LIMIT 1;");
# process options
$option_sender=$option[0]->sender;	
$option_reply=$option[0]->reply;
$option_title=$option[0]->title;
$option_postsnumber=$option[0]->postsnumber;
$option_postscats=$option[0]->postscats;
$option_footer=$option[0]->footer;
#process categories
$option_cats = explode(",", $option_postscats);

# get the post data
$message=$_REQUEST['messagebox'];
$message2=$message;
$subject=$_REQUEST['subject'];		

			$toself=$_REQUEST['toself'];
			$recent=$_REQUEST['recent'];
			$sendto=$_REQUEST['sendto'];	 
#prepare message

			#validate
			$search[]='%URL%';
			$replace[]='<i>Site link</i>';
										
			$search[]='%NAME%';
			$replace[]="<i>User name</i>";
			
			$message2=str_replace($search,$replace,$message2);
			
			$message2 = preg_replace( "/(\n\r|\r\n|\r|\n)/", "<BR>", $message2);
			
      # prepare message footer
			# Are we adding the recent articles?
				$recentart=false;
			if(!empty($recent)) {
					$recentart=true;
					//get recent articles and add to footer
					$first_run=true;
					$recent_query="SELECT DISTINCT * FROM wp_posts LEFT JOIN wp_post2cat ON wp_posts.ID = wp_post2cat.post_id";
					if (!empty($option_cats)){
					$recent_query.=" WHERE ";
					foreach ($option_cats as $cat) {
    					if ($first_run==false){
    						 $recent_query.=" OR ";
    					}
							else {$first_run=false;}
					$recent_query.="category_id=".$cat;
					}
					}
					$recent_query.=" ORDER by post_date DESC LIMIT ".$option_postsnumber.";";
					
					$recent = $wpdb->get_results("$recent_query");
					$footer.="<HR><B>".$option_title."</B><BR><BR>";
					foreach ($recent as $rec) {
    					$post=get_post($rec->ID);
    					$title = $post->post_title;
							$excerpt=$post->post_excerpt;
							if (empty($excerpt)){
    							$excerpt=$post->post_content;
    							$chars = 25;
                  $text = $text." ";
                  $text = substr($excerpt,0,$chars);
                  $text = substr($text,0,strrpos($text,' '));
                  $text = $text."[..]";
    							$excerpt=$text;
							}
    					$links= get_permalink($rec->ID);
							$links=strip_tags($links);
							$links=htmlspecialchars($links);
    					
							$excerpt=strip_tags($excerpt);
							$excerpt=htmlspecialchars($excerpt);
							$title=strip_tags($title);
							$title=htmlspecialchars($title);							
							$footer.='<B><a href="'.$links.'">'.$title.'</a></B><BR>
							'.$excerpt.'<BR>';
					}
			}			
			# add the unsubcribe links
			$footer.="<HR>".$option_footer." | Unsubscribe<BR>";
			#add footer to message body
			$message2.=$footer;
		
      #create array of the data to preview
      $mail['message']=$message;	
			$mail['message2']=$message2;
			$mail['subject']=$subject;
			$mail['toself']=$toself;
			$mail['recent']=$recent;
			$mail['sendto']=$sendto;
      # return the preview
return ($mail);
}

function sendmail() {
global $wpdb;
# get user options from table
$option = $wpdb->get_results("SELECT * FROM `WP_MAILLIST_OPTIONS` LIMIT 1;");
# process options
$option_sender=$option[0]->sender;	
$option_reply=$option[0]->reply;
$option_title=$option[0]->title;
$option_postsnumber=$option[0]->postsnumber;
$option_postscats=$option[0]->postscats;
$option_footer=$option[0]->footer;
#process categories
$option_cats = explode(",", $option_postscats);

			unset($footer);
			$toself=$_REQUEST['toself'];
			$recent=$_REQUEST['recent'];
			$sendto=$_REQUEST['sendto'];	
			global $wpdb;
			global $sel;
			#get users from tables to deliver to
			if($sendto=='mail') {
						$mailinglist = $wpdb->get_results("SELECT * FROM `WP_MAILLIST` WHERE listed='true';");
			} elseif($sendto=='reg') {
						$mailinglist = $wpdb->get_results("SELECT * FROM `WP_MAILLIST` WHERE user_registered='true';");
			}	else {
						$mailinglist = $wpdb->get_results("SELECT * FROM WP_MAILLIST INNER JOIN WP_MAILLIST_CACHE ON WP_MAILLIST.id = WP_MAILLIST_CACHE.user_id;");
			}
      #get data to be sent
      $header=$_REQUEST['header'];
      $message=$_REQUEST['message'];
      $subject=$_REQUEST['subject'];
      #prepare emails and validate
			#first ready the header
			#prepare header (from)
			$header = "NFLdreams.com";  
			# write headers
			$reply_address="jolley_small@tesco.net";
			$headers = "From: ".$option_sender." <".$option_reply.">\r\n" .
					 "Reply-To: ".$option_reply."" . "\r\n" .
				   "X-Mailer: PHP/" . phpversion() . "\r\n" .
				   "MIME-Version: 1.0\r\n" .
				   "Content-Type: text/html; charset=utf-8\r\n" .
				   "Content-Transfer-Encoding: 8bit\r\n\r\n";		  									 
			#prepare message body
			# validate subject and message setup
			$blogurl = get_bloginfo('url');
    	$blogname = get_settings('blogname');
    	$link = '<a href="'.$blogurl.'">'.$blogname.'</a>';
			
			$message = preg_replace( "/(\n\r|\r\n|\r|\n)/", "<BR>", $message);
			
			# prepare message footer
			# Are we adding the recent articles?
			$recentart=false;
			if(!empty($recent)) {
					//get recent articles and add to footer
					$first_run=true;
					$recent_query="SELECT DISTINCT * FROM wp_posts LEFT JOIN wp_post2cat ON wp_posts.ID = wp_post2cat.post_id";
					if (!empty($option_cats)){
					$recent_query.=" WHERE ";
					foreach ($option_cats as $cat) {
    					if ($first_run==false){
    						 $recent_query.=" OR ";
    					}
							else {$first_run=false;}
					$recent_query.="category_id=".$cat;
					}
					}
					$recent_query.=" ORDER by post_date DESC LIMIT ".$option_postsnumber.";";
					
					$recent = $wpdb->get_results("$recent_query");
					
					$footer.="<HR><B>".$option_title."</B><BR><BR>";
					foreach ($recent as $rec) {
    					$post=get_post($rec->ID);
    					$title = $post->post_title;
							$excerpt=$post->post_excerpt;
							if (empty($excerpt)){
    							$excerpt=$post->post_content;
    							$chars = 25;
                  $text = $text." ";
                  $text = substr($excerpt,0,$chars);
                  $text = substr($text,0,strrpos($text,' '));
                  $text = $text."[..]";
    							$excerpt=$text;
							}
    					$links= get_permalink($rec->ID);
							$links=strip_tags($links);
							$links=htmlspecialchars($links);    					
							$excerpt=strip_tags($excerpt);
							$excerpt=htmlspecialchars($excerpt);
							$title=strip_tags($title);
							$title=htmlspecialchars($title);							
							$footeradd='<B><a href="'.$links.'">'.$title.'</a></B><BR>'.$excerpt.'<BR>';
							$footeradd=trim($footeradd);
							$footer.=$footeradd;
					}
			}			
			#check if sending copy to self
			$mailself=false;
			if(!empty($toself)) {
    			global $userdata;
          get_currentuserinfo();
          $id=$userdata->ID;
					$self = $wpdb->get_results("SELECT * FROM `wp_users` WHERE ID=$id;");
					foreach ($self as $val) {
					$addy=$val->user_email;
					
					# add the unsubcribe links
    			$footer_self=$footer.'<HR>'.$option_footer.' Unsubscribe<BR>';
    			#add footer to message body
    			$message_self=$message.$footer_self;
					
					# validate subject and message setup    			
							unset($search);
							unset($replace);
					$search[]='%URL%';
        	$replace[]=$link;
					
					$search[]='%NAME%';
        	$replace[]=$val->user_nicename;
        			
        	$subject_self=str_replace($search,$replace,$subject);
					$message_self=str_replace($search,$replace,$message_self);
					
					}
					$mailself=true;
			}
			$count=0;
			# send them to the maillist
			if ( !empty($mailinglist) ) {
			foreach ($mailinglist as $mail) {	
							# add the unsubcribe links
        			$footer_un='<HR>'.$option_footer.' <a href="'.get_settings('siteurl').'/mail_unsubscribe.php?unsubscribe='.$mail->mail_key.'&usermail='.$mail->user_email.'">Unsubscribe</a><BR>';
        			#validate
							#add footer to message body
							$subject_user=$subject;
        			$message_user=$message;
							unset($search);
							unset($replace);
        			$search[]='%URL%';
        			$replace[]=$link;        										
        			$search[]='%NAME%';
        			$replace[]=$mail->user_name;
        			
        			$subject_user=str_replace($search,$replace,$subject_user);
        			$message_user=str_replace($search,$replace,$message_user);
							
        			$message_user=$message_user.$footer.$footer_un;		
							$message_user=wordwrap($message_user,70);
							mail($mail->user_email, $subject_user, $message_user, $headers);
							$count++;
			}//end foreach		
			}			
			#send to self
			if ($mailself==true){
				 		$message_self=wordwrap($message_self,70);
				 		mail($addy, $subject_self, $message_self, $headers);
						$count++;
			}//end mailself
			
			return($count);
}



function maillist_write(){
# This is the main part of the wordpress admin interface for maillist; the sending mail screen.

# page formatting
?>
<div class="wrap">
<?php

# get action from url
$action=$_REQUEST['action'];
global $selected;
$selected=$_REQUEST['sel'];
$doaction=$_REQUEST['doaction'];
if (($doaction=='selective') || ($selected=='sel')){
	 $sel=true;
}
$type=$_REQUEST['type'];
      if (!empty($action)){
            # switch for the action
            switch ($action){
      			
      						 case 'preview':
									 			# validate form
      						 			$mail=sendmail_preview();
												?>
												<div style="background-color:#ddd;"><?php
												echo $mail['message2'];
												?></div><?php
												# echo send button, mail in hidden field
												?>
												<?php if ($selected=='sel'){ ?>
    												<form name="editthemail" action="<?php print("$PHP_SELF"); ?>?page=maillist.php&sel=sel" method="post">
														<?php } else { ?>
														<form name="editthemail" action="<?php print("$PHP_SELF"); ?>?page=maillist.php" method="post">
														<?php } ?>
																<input type="hidden" name="message" value="<?php echo $mail['message']; ?>" />
																<input type="hidden" name="subject" value="<?php echo $mail['subject']; ?>" />	
																<input type="hidden" name="toself" value="<?php echo $mail['toself']; ?>" />
																<input type="hidden" name="sendto" value="<?php echo $mail['sendto']; ?>" />
																<input type="hidden" name="recent" value="<?php echo $mail['recent']; ?>" />
																
        												<p class="submit" style="text-align:left !important;"><input type="submit" value="Edit" /></p>
    												</form>
														<?php if ($selected=='sel'){ ?>
														<form name="sendthemail" action="<?php print("$PHP_SELF"); ?>?page=maillist.php&action=send&sel=sel" method="post">
														<?php } else { ?>
														<form name="sendthemail" action="<?php print("$PHP_SELF"); ?>?page=maillist.php&action=send" method="post">
														<?php } ?>
																<input type="hidden" name="message" value="<?php echo $mail['message']; ?>" />
																<input type="hidden" name="subject" value="<?php echo $mail['subject']; ?>" />	
																<input type="hidden" name="toself" value="<?php echo $mail['toself']; ?>" />
																<input type="hidden" name="sendto" value="<?php echo $mail['sendto']; ?>" />
																<input type="hidden" name="recent" value="<?php echo $mail['recent']; ?>" />
																
        												<p class="submit" style="text-align:left !important;"><input type="submit" value="Send" /></p>
    												</form>
												<?php
      						 break;
									 
									 case 'send':
      						 			 # send custom email to mailing list
												 $count=sendmail();
												 global $wpdb;
												 $wpdb->query("DROP TABLE WP_MAILLIST_CACHE;");
												 ?>
												 <h3>Messages Sent</h3>
												 <p>A total of <?php echo $count; ?> email messages were sent.</p>
												 <?php
      						 break;
      			
      			} //end case
                 
      } else {
# check tables exist
maketables();
# check list is up to date
reindex();
			# get previous post data (if user wants to edit the preview)
			$header=$_REQUEST['header'];
			$message=$_REQUEST['message'];
			$subject=$_REQUEST['subject'];	
				
			$toself=$_REQUEST['toself'];
			$recent=$_REQUEST['recent'];
			$sendto=$_REQUEST['sendto'];		
			
      # Write the send mail form
			?>
			<div class="form">
			<?php if ($sel==false){ ?>
			<form name="sendmail" action="<?php print("$PHP_SELF"); ?>?page=maillist.php&action=preview" method="post">
			<?php } else { ?>
			<form name="sendmail" action="<?php print("$PHP_SELF"); ?>?page=maillist.php&action=preview&sel=sel" method="post">
			<?php } ?>
			<h2>Send an email to the mailing list</h2>
			<p><strong>Available variables</strong></p>
			<ul>
			<li><strong>%NAME%</strong> - User's full name</li>
      <li><strong>%URL%</strong> - Site's url/link</li>
			</ul>
    			<fieldset>
    			<legend>Message</legend>
    			<div class="formleft"><label for="sendto">Send to:</label></div>
    			<div class="formright">
					<?php if (($sel==true)){ ?>
					<select disabled="disabled" name="sendto">
					<option selected="selected"  value="sel">Selected users</option>					
					</select>
					
					<?php } else { ?>
					<select name="sendto">
					<option <?php if ($sendto=='mail') {echo 'selected="selected"';} ?> value="mail">Mailing List</option>
					<option <?php if ($sendto=='reg') {echo 'selected="selected"';} ?> value="reg">Registered Users</option>
					</select>
					<?php } ?>
					</div>
    			<div class="formleft"><label for="subject">Subject:</label></div>
    			<div class="formright"><input type="text" value="<?php echo $subject; ?>" name="subject" id="subject" /></div>
    			<div class="formleft"><label for="messagebox">Message body:</label></div>
    			<div class="formright"><textarea rows="15" cols="100%" name="messagebox" id="messagebox"><?php echo $message; ?></textarea></div>
    			</fieldset>			
    			<fieldset>
    			<legend>Options</legend>
					<div class="formleft"><label for="toself">Send copy to self?</label></div>
					<div class="formright"><input type="checkbox" id="toself" name="toself" <?php if (empty($toself)) {} else {echo 'checked="checked"';} ?> /></div>
					<div class="formleft"><label for="recent">Include recent posts?</label></div>
					<div class="formright"><input type="checkbox" id="recent" name="recent" <?php if (empty($recent)) {} else {echo 'checked="checked"';} ?> /></div>  			
    			</fieldset>	
					<fieldset>
    			<legend>Send</legend>
					
					<div class="formright"><p class="submit" style="text-align:left !important;"><input type="submit" value="Preview" /></p></div>
					
					</fieldset>	
      </form>  
			</div>
			
      <?php
      } // end  if (!empty($action))

# page formatting
?>
</div>

<?php			
}

function cache_users(){
									 /////////////////////caching of users///////////////////////
									 $found=false;
									 global $wpdb;
									 $users = $wpdb->get_results("SELECT * FROM WP_MAILLIST;");
									 foreach ($users as $user) {
									 				 #get input from form if exists
													 $current_post="check_".$user->id;
													 $current=$_POST[$current_post];
													 if (!empty($current)){
													 //add to cache db
													 $curr_id=$user->id;													 
													 $wpdb->query("INSERT INTO WP_MAILLIST_CACHE (user_id) VALUES ($curr_id)");
          	
													 $found=true;
                   				 }
									 }
									 /////////////////////caching of users///////////////////////
									 return($found);
}

function maillist_admin(){
# This is the admin section for maillist
?>
<div class="wrap">
<h2>Mailing List admin</h2>
<p>Here you can change options to do with sending emails to the mailing list, and manage users*.</p>
<p>*note: It is recommended you do not delete users from the mailing list unless they are no longer registered, since they will be re-indexed.</p>
<p>Instead just set 'subscribed' to 'false'.</p>
<?php
# check tables exist
maketables();
# check list is up to date
reindex();
global $wpdb;
# get action if set 
$action=$_REQUEST['action'];
$doaction=$_REQUEST['doaction'];
if ($doaction==submit){
	 $option=$_REQUEST['actionsel'];
	 switch ($option){      			
      						 case '1':
									 			$action='sendmail';
									 break;
									 case '2':
									 			$action='removeuser';
									 break;
									 case '3':
									 			$action='deleteuser';
									 break;
									 case '4':
									 			$action='subuser';
									 break;
									 }
}
if (!empty($action)){
            # switch for the action
            switch ($action){
      			
      						 case 'adduser':
									 # add user
									 # write forms ?>
                      <form style="overflow:hidden;" class="validateform" action="<?php print("$PHP_SELF"); ?>?page=maillist.php&action=adduser_done" method="post" name="mikeForm" onSubmit="return submitIt(this)" >
                      <fieldset>
                      <h4><legend>User details</legend></h4>
                      <div class="formleft"><label for="user_name">Name:</label></div>
                      <div class="formright"><input type="text" name="user_name" id="user_name" style="width:60%;" /></div>
                      <div class="formleft"><label for="user_email">Email:</label></div>
                      <div class="formright"><input type="text" name="user_email" id="user_email" style="width:60%;" /></div>
                      </fieldset>
                      <div class="formright"><p class="submit" style="text-align:left !important;" ><input type="submit" name="submit" value="go"></div>
                      </form>
									 <?php
									 break;
									 case 'adduser_done':
									 #add new user to db
									 $user_name=$_POST['user_name'];
									 $user_email=$_POST['user_email'];
									 $exists=false;
									 global $wpdb;
									 $users = $wpdb->get_results("SELECT * FROM `WP_MAILLIST`;");
									 foreach ($users as $user) {
									 				 # check users table against new user
													 if ($user->user_email==$user_email) {
													 		$exists=true;
													 }
									 }//end foreach
									 if ($exists==false){
									 		# add if not there
                      $num = rand(100000, 999999);
                      $result=$wpdb->query("INSERT INTO WP_MAILLIST (mail_key, user_name, user_email, user_registered, listed) VALUES ('$num', '$user_name', '$user_email', 'false', 'true')");
                   		#check if successful
											if ( empty($result)){
												 echo '<h2>Sorry, save failed</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';		 
									 		} else {
												 echo '<h2>New user saved</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
											}
									 } else {
									 	 echo '<h2>User not saved, email address already in Database</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';		 
									 }
									 break;
									 case 'deleteuser':
									 # delete users
									 $found=cache_users();
									 if ($found==true){
									 echo '<h2>Are you sure you want to delete the selected users?</h2>
												<p><a href="'.$PHP_SELF.'?page=maillist.php&action=delete">[yes]</a></p>
												<p><a href="'.$PHP_SELF.'?page=maillist.php">[no]</a></p>';
												} else {
												echo '<h2>No users selected</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
												}
									 break;
									 case 'removeuser':
									 # unsubscribe users
									 $found=cache_users();
									 if ($found==true){
									 echo '<h2>Are you sure you want to unsubscribe the selected users?</h2>
												<p><a href="'.$PHP_SELF.'?page=maillist.php&action=unsub">[yes]</a></p>
												<p><a href="'.$PHP_SELF.'?page=maillist.php">[no]</a></p>';
												} else {
												echo '<h2>No users selected</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
									}
									 break;
									 case 'subuser':
									 # RE-subscribe users
									 $found=cache_users();
									 if ($found==true){
									 echo '<h2>Are you sure you want to Re-subscribe the selected users?</h2>
												<p><a href="'.$PHP_SELF.'?page=maillist.php&action=resub">[yes]</a></p>
												<p><a href="'.$PHP_SELF.'?page=maillist.php">[no]</a></p>';
												} else {
												echo '<h2>No users selected</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
									}
									 break;
									 case 'sendmail':
									 # send to selected
									 $found=cache_users();
									 if ($found==true){
									 echo '<h2>Are you sure you want to send email to the selected users?</h2>
												<p><a href="'.get_settings('siteurl').'/wp-admin/post.php?page=maillist.php&doaction=selective">[yes]</a></p>
												<p><a href="'.$PHP_SELF.'?page=maillist.php">[no]</a></p>';
												} else {
												echo '<h2>No users selected</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
									 }												
									 break;
									 case 'save':
									 		 $set=$_POST['set'];	
											 $sender=$_POST['sender'];	
											 $reply=$_POST['reply'];	
											 $title=$_POST['titleb'];	
											 $postsnumber=$_POST['postsnumber'];	
											 $postscats=$_POST['postscats'];	
											 $footer=$_POST['footerb'];
    									 # CHECK if form submitted
											 if (isset($set)){
    									 # save options
    									 $wpdb->query("UPDATE WP_MAILLIST_OPTIONS SET sender='$sender', reply='$reply', title='$title', postsnumber='$postsnumber', postscats='$postscats', footer='$footer' WHERE id=1;");
              				 echo '<h2>Options saved</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';	
											 }else{			
											 echo '<h2>Options NOT saved, error encounted</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';}		 
									 break;
									 case 'default':
									 			echo '<h2>Are you sure you want to reset the options?</h2>
												<p><a href="'.$PHP_SELF.'?page=maillist.php&action=default2">[yes]</a></p>
												<p><a href="'.$PHP_SELF.'?page=maillist.php">[no]</a></p>';
									 break;
									 case 'default2':
									 			$wpdb->query("DROP TABLE WP_MAILLIST_OPTIONS;");
												echo '<h2>Options reset</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
									 break;
									 case 'delete':
									 			$users = $wpdb->get_results("SELECT * FROM WP_MAILLIST_CACHE;");
												foreach($users as $user){
														$wpdb->query("DELETE FROM WP_MAILLIST WHERE id=$user->user_id;");
														
												}												
												$wpdb->query("DROP TABLE WP_MAILLIST_CACHE;");
												echo '<h2>Users deleted</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
									 break;
									 case 'unsub':
									 			$users = $wpdb->get_results("SELECT * FROM WP_MAILLIST_CACHE;");
												foreach($users as $user){
									 		 			$wpdb->query("UPDATE WP_MAILLIST SET listed='false' WHERE id=$user->user_id;");
														
              				  }												
											  $wpdb->query("DROP TABLE WP_MAILLIST_CACHE;");
												echo '<h2>Users unsubscribed</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
									 break;
									 case 'resub':
									 			$users = $wpdb->get_results("SELECT * FROM WP_MAILLIST_CACHE;");
												foreach($users as $user){
									 		 			$wpdb->query("UPDATE WP_MAILLIST SET listed='true' WHERE id=$user->user_id;");
														
              				  }												
											  $wpdb->query("DROP TABLE WP_MAILLIST_CACHE;");
												echo '<h2>Users Re-subscribed</h2><p><a href="'.$PHP_SELF.'?page=maillist.php">Go back</a></p>';
									 break;
							}



# Write custom newsletter to mailing list
} else {
# Echo the users subscribed & options
$options = $wpdb->get_results("SELECT * FROM `WP_MAILLIST_OPTIONS` LIMIT 1;");
?>
<h3>Options</h3>
  <form style="overflow:hidden;" action="<?php print("$PHP_SELF"); ?>?page=maillist.php&action=save" method="post">
        <fieldset>
        <h4><legend>Email options</legend></h4>
								<div class="formleft"><label for="sendto">Sender:</label></div>
          			<div class="formright"><input type="text" name="sender" id="sender" style="width:60%;" value="<?php echo $options[0]->sender; ?>" /></div>
          			<div class="formleft"><label for="sendto">Reply address:</label></div>
          			<div class="formright"><input type="text" name="reply" id="reply" style="width:60%;" value="<?php echo $options[0]->reply; ?>" /></div>
				</fieldset>
			  <fieldset>
        <h4><legend>Recent article options</legend></h4>
								<div class="formleft"><label for="sendto">Title:</label></div>
          			<div class="formright"><input type="text" name="titleb" id="titleb" style="width:60%;" value="<?php echo $options[0]->title; ?>" /></div>
								<div class="formleft"><label for="sendto">Number of posts to show:</label></div>
          			<div class="formright"><input type="text" name="postsnumber" id="postsnumber" style="width:60%;" value="<?php echo $options[0]->postsnumber; ?>" /></div>
          			<div class="formleft"><label for="sendto">Post category id's (seperate each id with , )</label></div>
          			<div class="formright"><input type="text" name="postscats" id="postscats" style="width:60%;" value="<?php echo $options[0]->postscats; ?>" /></div>
				</fieldset>
				<fieldset>
        <h4><legend>Footer options</legend></h4>
								<div class="formleft"><label for="sendto">Text to display in footer (html allowed)</label></div>
          			<div class="formright"><textarea rows="6" name="footerb" id="footerb" style="width:60%;"><?php echo $options[0]->footer; ?></textarea></div>
				</fieldset>			
				<input type="hidden" name="set" id="set" value="set" />
				<div class="formright"><p class="submit" style="text-align:left !important;" ><input type="submit" name="submit" value="<?php _e('Save') ?>"/> <a href="<?php print("$PHP_SELF"); ?>?page=maillist.php&action=default">Restore Defaults</a></p></div>                					
  </form>

<h3>Subscribed users</h3>

<?php
echo '<p><a href="'.$PHP_SELF.'?page=maillist.php&action=adduser">Add user</a></p>';
global $wpdb;
# query mailing list
$users = $wpdb->get_results("SELECT * FROM `WP_MAILLIST`;");
if (!empty($users)){
?>
	 			<form name="form1" action="<?php print("$PHP_SELF"); ?>?page=maillist.php&doaction=submit" method="post">
						
                  <table width="100%" cellpadding="3" cellspacing="3">
                  <tr style="text-align:left;">
                  <th scope="col"><?php _e(' ') ?></th>
                  <th scope="col"><?php _e('Name') ?></th>
                  <th scope="col"><?php _e('Email') ?></th>
                  <th scope="col"><?php _e('Registered') ?></th>
                  <th scope="col"><?php _e('Subscribed') ?></th>
                  </tr>
<?php
            	    $class = '';
						      foreach ($users as $user){	
            			$class = ($class == 'alternate') ? '' : 'alternate';
            			?>
            			<tr style="text-align:left;" class="<?php echo $class; ?>">
            				<th scope="row"><input type="checkbox" id="check_<?php echo $user->id; ?>" name="check_<?php echo $user->id; ?>" /></th>
            				<th><?php echo $user->user_name; ?></th>
            				<td><?php echo '<a href="mailto:'.$user->user_email.'">'.$user->user_email.'</a>'; ?></td>										
            				<td><?php echo $user->user_registered; ?></td>										
										<td><?php echo $user->listed; ?></td>
									</tr>
							
									<?php
									}
									?>
								</table>
								<fieldset>
                <legend><?php _e('Action on selected') ?></legend>
                <select name="actionsel" style="display:inline;">										
            				<option value="1">Send mail to selected</option>
										<option value="4">Re-subscribe selected</option>
            				<option value="2">Unsubscribe selected</option>
            				<option value="3">Delete Selected</option>
                </select>            
                <p class="submit" style="display:inline;text-align:left !important;" ><input type="submit" name="submit" value="<?php _e('GO') ?>"/></p><br />
                </fieldset>
				</form>
<?php
} else {
echo '<p>Mailing list is empty</p>';
}
}
?>
</div>
<?php
}
?>