Location: PHPKode > projects > Basic Announce > Basic Announce Version 4.0/system/mod_mass_mail.php
<?php
################################################################################
##              -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =-                 #
## --------------------------------------------------------------------------- #
##  ApPHP AdminPanel Pro                                                       #
##  Developed by:  ApPHP <hide@address.com>                                      #
##  License:       GNU LGPL v.3                                                #
##  Site:          http://www.apphp.com/php-adminpanel/                        #
##  Copyright:     ApPHP AdminPanel (c) 2006-2011. All rights reserved.        #
##                                                                             #
################################################################################

    session_start();
    
    require_once("../inc/classes/session.class.php");	
    require_once("../inc/checkAdminPagePermissions.php");

    require_once("../inc/config.inc.php");
    require_once("../inc/settings.inc.php");
	require_once("../inc/functions.inc.php");
	require_once("../modules/phpmailer/class.phpmailer.php");
	require_once("../inc/languages/".$SETTINGS['site_language'].".php");

	if(!module_istalled('mass_mail')) redirect_to("access_denied.php");
    if(!page_access_allowed($_SERVER['SCRIPT_NAME'])) redirect_to("access_denied.php");

    define ("_EMAIL_FROM", $SETTINGS['admin_email']);
    define ("_TESTING_EMAIL", $SETTINGS['admin_email']);

    // save mass mail settings
    $act            = isset($_GET['act']) ? $_GET['act'] : "";
    $package_size   = isset($_POST['package_size']) ? $_POST['package_size'] : "10";
    $template_name  = isset($_REQUEST['template_name']) ? $_REQUEST['template_name'] : "";
    $btnSubmit      = isset($_POST['btnSubmit']) ? $_POST['btnSubmit'] : "";
    $subject        = isset($_POST['subject']) ? $_POST['subject'] : "";
    $body           = isset($_POST['body']) ? $_POST['body'] : "";
    $body           = str_replace("%CURRENT YEAR%", date("Y"), $body);
	$body           = str_replace("%WEB SITE%", $SETTINGS['site_address'], $body);
	$body           = str_replace(array("\\n", "\n"), "<br>", $body);
    $body           = str_replace("\'", "'", $body);
    $body           = str_replace('\"', '"', $body);
    $email_to_req   = isset($_POST['email_to']) ? $_POST['email_to'] : "";
	$send_copy_to_admin = isset($_POST['send_copy_to_admin']) ? $_POST['send_copy_to_admin'] : "";
	$align_left     = ($SETTINGS['language_dir'] == "ltr") ? "left" : "right";
	$align_right    = ($SETTINGS['language_dir'] == "ltr") ? "right" : "left";
    $msg            = "";
    $template_content  = "";
    $template_subject  = "";
	$users_emails_count = "0";
	$send_email_error = "";
	
    if($act == "clean"){
		if(strtolower(_SITE_MODE) == "demo"){
			$msg = "<font color='#b60000'>This operation is blocked in demo version!</font>";			
		}else{
			if(module_istalled("users")){
				$sql = "UPDATE ".TABLE_USERS." SET newsletter_sent = 0 WHERE newsletter = 1 AND email != ''";
				$db->Exec($sql);
			}
			$sql = "UPDATE ".TABLE_ADMINS." SET newsletter_sent = 0 WHERE newsletter = 1 AND email != ''";
			$db->Exec($sql);                    
			$msg = draw_message("success", "All previously sent data was removed!", false, "100%", "../");                
		}
    }

    // Handle emails sending
    if($btnSubmit == "Send Email" && $body != "" && $subject != ""){        
		if(strtolower(_SITE_MODE) == "demo"){
			$msg = "<font color='#b60000'>This operation is blocked in demo version!</font>";			
		}else{
			$result = false;
			$count = "0";
			
			$email_to_parts = explode("|", $email_to_req);
			$email_to = isset($email_to_parts[0]) ? $email_to_parts[0] : "";
			$email_to_subtype = isset($email_to_parts[1]) ? $email_to_parts[1] : "";
			if($email_to_subtype == "all"){
				$user_where_clause = "";
			}else if($email_to_subtype == "uncategorized"){
				$user_where_clause = "group_id=0 AND";
			}else if($email_to_subtype != ""){
				$user_where_clause = "group_id=".$email_to_subtype." AND";
			}else{
				$user_where_clause = "";
			}

			if($email_to == "test"){
				$emails_total = "1";
				$result = send_email(_TESTING_EMAIL, _EMAIL_FROM, $subject, $body, $send_email_error);
				if($result){
					$count = $emails_total = "1";
				}            
			}else{

				if(module_istalled('users')){
					$sql = "SELECT COUNT(*) as cnt
							FROM ".TABLE_USERS."
							WHERE is_active = 1 AND newsletter = 1 AND newsletter_sent = 0 AND email != ''";
					$db->Query($sql);
					$users_emails_total = ($row = $db->FetchArray()) ? $row['cnt'] : "0";
				}
				$sql = "SELECT COUNT(*) as cnt
						FROM ".TABLE_ADMINS."
						WHERE newsletter = 1 AND newsletter_sent = 0 AND email != ''";
				$db->Query($sql);
				$admins_emails_total = ($row = $db->FetchArray()) ? $row['cnt'] : "0";

				if($email_to == "users"){
					$emails_total = $users_emails_total;
				}else if($email_to == "admins"){
					$emails_total = $admins_emails_total;
				}else if($email_to == "all"){
					$emails_total = $users_emails_total + $admins_emails_total;
				}

				$arr_emails_sent = array();
				if(module_istalled('users') && $email_to == "users" || $email_to == "all"){
					$sql = "SELECT id, first_name, last_name, email, username  
							FROM ".TABLE_USERS."
							WHERE is_active = 1 AND ".$user_where_clause." newsletter = 1 AND newsletter_sent = 0 AND email != '' 
							ORDER BY id
							LIMIT 0, ".$package_size;
					$db->Query($sql);
					$id_list = "";
					while($row = $db->FetchArray()){
						$body_send = $body;
						$id_list .= ", ".$row['id'];
						if(!array_key_exists($row['email'], $arr_emails_sent)){
							$result = true;						
							$body_send = str_replace("%FIRST NAME%", $row['first_name'], $body_send);
							$body_send = str_replace("%LAST NAME%", $row['last_name'], $body_send);
							$body_send = str_replace("%USER NAME%", $row['username'], $body_send);	
							$result = send_email($row['email'], _EMAIL_FROM, $subject, $body_send, $send_email_error);
							if($result) $count++;
							$arr_emails_sent[$row['email']] = $row['email'];
						}						
					}
					$sql = "UPDATE ".TABLE_USERS." SET newsletter_sent = 1 WHERE id IN (-1".$id_list.")";
					$db->Exec($sql);
				}

				if($email_to == "admins" || $email_to == "all"){					
					$sql = "SELECT id, email, first_name, last_name, username 
							FROM ".TABLE_ADMINS."
							WHERE newsletter = 1 AND newsletter_sent = 0 AND email != '' 
							ORDER BY id
							LIMIT  0, ".$package_size;
					$db->Query($sql);
					$id_list = "";
					while($row = $db->FetchArray()){					
						$body_send = $body;
						$id_list .= ", ".$row['id'];
						if(!array_key_exists($row['email'], $arr_emails_sent)){
							$result = true;						
							$body_send = str_replace("%FIRST NAME%", $row['first_name'], $body_send);
							$body_send = str_replace("%LAST NAME%", $row['last_name'], $body_send);
							$body_send = str_replace("%USER NAME%", $row['username'], $body_send);	
							$result = send_email($row['email'], _EMAIL_FROM, $subject, $body_send, $send_email_error);
							if($result) $count++;
							$arr_emails_sent[$row['email']] = $row['email'];
						}
					}
					$sql = "UPDATE ".TABLE_ADMINS." SET newsletter_sent = 1 WHERE id IN (-1".$id_list.")";
					$db->Exec($sql);
				}

				if($send_copy_to_admin == "1"){
					send_email(_TESTING_EMAIL, _EMAIL_FROM, $subject." (admin copy)", $body, $send_email_error);
				}
			}
				
			if($result){
				$msg = draw_message("success", "Status: ".$count." email/s from ".$emails_total." were successfully sent!", false, "100%", "../");                
			}else{
				if(!empty($send_email_error)){
					$msg = draw_message("error", strip_tags($send_email_error)."<br>Please try again later or check you Mail Settings.", false, "100%", "../");					
				}else{
					$msg = draw_message("error", "Status: an error occured while sending emails or there are no emails to be sent! Please try again later.", false, "100%", "../");
				}
			}           			
		}
    }    

    // Display appropriate email template
    if($template_name != ""){
        $sql = "SELECT * FROM ".TABLE_EMAIL_TEMPLATES." WHERE template_name = '".$template_name."'";
        $db->Query($sql);
        if($row = $db->FetchArray()){
            $template_content = $row['template_content'];
			$template_content = str_replace(array("\\n", "\n"), "", $template_content);
            $template_content = str_replace("''", "'", $template_content);
            $template_content = str_replace("\'", "'", $template_content);
            $template_content = str_replace('\"', '"', $template_content);
            $template_subject = $row['template_subject'];			
        }
    }

	if(module_istalled('users')){		
		// Get emails count for users
		$sql = "SELECT COUNT(*) as cnt FROM ".TABLE_USERS." WHERE newsletter = 1 AND newsletter_sent = 0 AND email != ''";
		$db->Query($sql);
		if($row = $db->FetchArray()){
			$users_emails_count = $row['cnt'];
		}		
	}
    
	// Get emails count for admins
    $admins_emails_count = "0";    
    $sql = "SELECT COUNT(*) as cnt FROM ".TABLE_ADMINS." WHERE newsletter = 1 AND newsletter_sent = 0 AND email != ''";
    $db->Query($sql);
    if($row = $db->FetchArray()){
        $admins_emails_count = $row['cnt'];
    }
    
	$emails_count = $users_emails_count + $admins_emails_count;

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
	<title><?php echo $SETTINGS['site_name']; ?> :: <?php echo lang('admin_panel'); ?></title>
    <meta http-equiv=Content-Type content="text/html; charset=utf-8">
    <!-- CSS style files -->
    <link href="../styles/<?php echo $SETTINGS['css_style'];?>/style.css" type="text/css" rel="stylesheet">
    <!-- JavaScript -->
	<script type="text/javascript">
    function OnSubmit_Check(){
        var email_to = (document.getElementById('email_to')) ? document.getElementById('email_to').value : "";
        if(email_to == ''){
            alert("Email Address (To) can not be empty! Please select.");
            document.getElementById('email_to').focus();
            return false;            
        } else if(document.getElementById('subject').value == ''){
            alert("Subject can not be empty! Please re-enter.");
            document.getElementById('subject').focus();
            return false;
        } else if(document.getElementById('body').value == ''){
            alert("Body can not be empty! Please re-enter.");
            document.getElementById('body').focus();
            return false;
        } else if(email_to == "all"){
            if(!confirm("Are you sure?")){
                return false;
            }
        }
        return true;
    }
	
	function trim(el){
		if(document.getElementById(el) && document.getElementById(el).value == '<?php echo _EMAIL_FROM; ?>'){
			document.getElementById(el).value = '';
		}
	}
    
	function untrim(el){
		if(document.getElementById(el) && document.getElementById(el).value == ''){
			document.getElementById(el).value = '<?php echo _EMAIL_FROM; ?>';
		}
	}
	
    function Mass_mail_time_period_On_Change(val){
        if(val == ""){
            document.getElementById("mass_mail_package_size").disabled = "disabled";
        }else{
            document.getElementById("mass_mail_package_size").disabled = "";            
        }
    }

    function Mail_Preview(){
    	var new_window = window.open('templates/mail_preview.html','name','height=500,width=600,scrollbars=yes,screenX=100,screenY=100');
    	if(window.focus) {new_window.focus()};
		var message = document.getElementById('body').value;
        message = message.replace(/\n/g, '<br>');
		new_window.document.writeln(message); 
    }

	function email_to_OnChange(val){
		var el_send_copy_to_admin = (document.getElementById('send_copy_to_admin')) ? document.getElementById('send_copy_to_admin') : null;
		if(val == 'admins' && el_send_copy_to_admin){
			el_send_copy_to_admin.disabled = 'disabled';
		}else{
			el_send_copy_to_admin.disabled = '';
		}
	}
    </script>
</head>

<!-- BEGIN MAIN CONTENT ARE -->
<body dir="<?php echo $SETTINGS['language_dir'];?>">
<?php echo page_breadcrumbs(); ?>
<br />
<form class='panel_form' action="mod_mass_mail.php" method="post" style="margin-top:0px; padding-top:0px;">
    <table align="center" width="90%" border='0'>
    <tr>
        <td width="70%" align="<?php echo $align_left; ?>" valign="top" align="left">
		    <?php echo ((!empty($msg)) ? $msg."<br>" : ""); ?>
			
            <fieldset style='height:410px;'>
			<legend style='margin:0 2px;'><b>Form:</b></legend>
            <table width="97%" align="center" border='0'>
            <tr>
                <td align="<?php echo $align_right; ?>" nowrap>
					<label><?php echo lang('template'); ?>:</label><br />
					<a href="mail_templates_manager.php">[<?php echo lang('manage_templates'); ?>]</a>				
				</td>
                <td></td>
                <td>
					<table align="<?php echo $align_left; ?>" cellpadding="0" cellspacing="0">
					<tr valign="middle">
						<td>
							<select name="template_name" id="template_name" title="<?php echo lang('email_template'); ?>" style="margin-bottom:3px;" onchange="document.location.href='mod_mass_mail.php?template_name='+this.value">
								<option value=''>-- <?php echo lang('select'); ?> --</option>
								<?php
									$sql = "SELECT * FROM ".TABLE_EMAIL_TEMPLATES." ORDER BY is_system DESC, template_name ASC";
									$db->Query($sql);
									while($row = $db->FetchArray()){
										echo "<option value='".$row['template_name']."' ";
										echo (($row['is_system'] == "1") ? " style='background-color:#ffffcc;color:#000055'" : "");
										echo "".(($template_name == $row['template_name']) ? "selected='selected'" : "").">".$row['template_ddl_name']."</option>";
									}
								?>                        
							</select>						
						</td>
						<td>&nbsp;&nbsp;&nbsp;<?php echo lang('package_size'); ?>:&nbsp;</td>
						<td>
							<select name="package_size" id="package_size" title="<?php echo lang('package_size'); ?>" style="margin-bottom:3px;">
								<option value="10">10</option>
								<option value="20">20</option>
								<option value="30">30</option>
								<option value="40">40</option>
								<option value="50">50</option>
							</select>    						
						</td>
					</tr>
					</table>                    
                </td>
            </tr>
            <tr>
                <td align="<?php echo $align_right; ?>" nowrap><label><?php echo lang('email_address'); ?> (To):</label></td>
                <td><span class="req">*</span></td>
                <td>
                    <select name="email_to" id="email_to" title="<?php echo lang('email_address'); ?> (To)" style="margin-bottom:3px;" onchange='email_to_OnChange(this.value)'>
                        <option value=''>-- <?php echo lang('select'); ?> --</option>
                        <option value='test'>== <?php echo lang('test_email_to_admin'); ?> ==</option>
						<?php
							if(module_istalled('users')){
								echo "<optgroup label='".lang('users')."'>";
								echo "<option value='users|all'>all (".$users_emails_count.")</option>";	
								
								$sql = "SELECT ug.id, ug.group_name, ug.group_description,
											(SELECT COUNT(*) FROM ".TABLE_USERS." u WHERE u.group_id = ug.id AND u.is_active = 1 AND u.newsletter = 1 AND u.newsletter_sent = 0 AND u.email != '') as users_count
										FROM ".TABLE_USERS_GROUPS." ug
										ORDER BY ug.group_name ASC";					
								$db->Query($sql);
								$user_groups_emails_count = 0;
								while($row = $db->FetchArray()){
									if($row['users_count']){
										echo "<option value='users|".$row['id']."'>".$row['group_name']." (".$row['users_count'].")</option>";
										$user_groups_emails_count += $row['users_count'];												
									}
								}
								$user_non_groups_emails = $users_emails_count - $user_groups_emails_count;
								echo "<option value='users|uncategorized'>Uncategorized (".$user_non_groups_emails.")</option>";										
								echo "</optgroup>";
							}
						?>						
						<option value='admins'>Admins (<?php echo $admins_emails_count; ?>)</option>
						<?php if(module_istalled('users')) echo "<option value='all'>Users & Admins (".$emails_count.")</option>"; ?>
                    </select>
                </td>
            </tr>            
            <tr>
                <td align="<?php echo $align_right; ?>" nowrap><label for="email"><?php echo lang('email_address'); ?> (From):</label></td>
                <td><span class="req">*</span></td>
                <td>
                    <input type="text" name="email" style="width:210px" id="email" title="<?php echo lang('email_address'); ?> (From)" onfocus="trim('email')" onblur="untrim('email')" value="<?php echo _EMAIL_FROM; ?>">
                </td>
            </tr>
            <tr valign="top">
                <td align="<?php echo $align_right; ?>" nowrap><label><?php echo lang('subject'); ?>:</label></td>
                <td><span class="req">*</span></td>
                <td>
                    <input type="text" style="width:390px" name="subject" id="subject" title="<?php echo lang('subject'); ?>" value="<?php echo $template_subject;?>" />
                </td>
            </tr>
            <tr valign="top">
                <td align="<?php echo $align_right; ?>" nowrap><label><?php echo lang('body'); ?>:</label></td>
                <td><span class="req">*</span></td>
                <td>
                    <textarea style="width:98%" rows="12" name="body" id="body" title="<?php echo lang('body'); ?>"><?php echo $template_content;?></textarea>
                </td>
            </tr>
            <tr><td colspan="3" nowrap style="height:6px;"></td></tr>
            <tr>
                <td align="<?php echo $align_right; ?>" nowrap><a href="javascript:void(0);" onclick="Mail_Preview()">[<?php echo lang('preview'); ?>]</a></td>
                <td></td>
                <td>
					<div style='float:left'><input type="checkbox" id="send_copy_to_admin" name="send_copy_to_admin" <?php echo (($send_copy_to_admin == "1") ? "checked='checked'" : ""); ?> value="1"> Send copy to admin</div>
                    <div style='float:right'><input class="form_button" type="submit" name="btnSubmit" value="<?php echo lang('send_email'); ?>" onclick='return OnSubmit_Check();'>&nbsp;&nbsp;</div>
                </td>
            </tr>
            </table>
            </fieldset>
        </td>
		<td width="8%"></td>
        <td width="22%" align="<?php echo $align_left; ?>" valign="top">		
            <h3><?php echo lang('mass_mail'); ?></h3>
		
            <table width="98%" border='0'>
            <tr>
                <td><b><?php echo lang('variables'); ?>:</b></td>
			</tr>
            <tr>
                <td>
					%FIRST NAME%<br />
					%LAST NAME%<br />
					%USER NAME%<br />
					%CURRENT YEAR%<br />
					%WEB SITE%<br />
					<br />            
					<a href="mod_mass_mail.php?act=clean" onclick="return confirm('<?php echo lang('alert_are_you_sure'); ?>');">[<?php echo lang('clean_data'); ?>]</a>
				</td>
			</tr>
			</table>
        </td>
    </tr>
    </table>    
</form>

<br />
</body>
</html>
Return current item: Basic Announce