<?php
/*
v1.1
    Copyright 2009-2010 GetWebActive  (email : cookies@getwebactive.com)
    Released under license from GetWebActive
    Use of this plugin is governed by the software licence included in the package. Contact the author if there is no licence in your package.
    *THIS IS NOT FREE SOFTWARE* 
    *All rights reserved* 

    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.
*/
class ar_gwa_newsletter {

function ar_gwa_newsletter() {
global $wpdb;
   $table_name = $wpdb->prefix . "ar_gwa_newsletter";
   if($wpdb->get_var("show tables like '$table_name'") != $table_name) {   
   $sql = "CREATE TABLE `$table_name` (
  `id` int(11) NOT NULL auto_increment,
  `listid` int(11) NOT NULL,
  `name` varchar(255) NOT NULL,
  `desc` varchar(255) NOT NULL,
  `content` text NOT NULL,
  `order` varchar(2) NOT NULL,
  `mtype` varchar(4) NOT NULL,
  PRIMARY KEY  (`id`)
  );";
   $results = $wpdb->query( $sql );

$tt = array("Kids"=>"kids_10.gif",
            "Swirly1"=>"swirly_bg03.gif",
            "Swirly2"=>"swirly_bg04.gif",
            "Abstract6"=>"abstract6.gif",
            "Abstract7"=>"abstract7.gif",
            "Cloud6"=>"cloud_6.gif",
            "Colorful5"=>"colorful5.gif",
            "Colorful6"=>"colorful6.gif",
            "Misc2"=>"misc2.gif",
            "Misc3"=>"misc3.gif",
            "Misc4"=>"misc4.gif",
            "Misc6"=>"misc6.gif",
            "Rainbow13"=>"rainbow_13.gif",
            "Retro23"=>"retro23.gif",
            "Retro8"=>"retro8.gif",
            "Star1"=>"star1.gif",
            "Summer1"=>"summer1.gif",
            "Summer2"=>"summer2.gif");
$purl = plugins_url();
$bname = get_bloginfo('name');   
 foreach($tt as $v=>$t) {
$wpdb->query("INSERT INTO ".$table_name." (`name`,`desc`,`order`,`content`,`mtype`) VALUES ('$v','Default $v (nimg/$t)',0,'".'<html><head></head><body><div align="left"><table align="center" border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#C0C0C0" width="409" height="432" id="AutoNumber1" bgcolor="#FFFFFF"><tr> <td width="455" height="60" valign="middle" style="background:url('.$purl.'/autoresponder-gwa/nimg/'.$t.');"><p align="center"><b><font face="Tahoma,Arial,Sans-serif" size="3">'.$bname.'<br>Community Newsletter</font></b></td></tr><tr> <td width="455" height="343" valign="top" bgcolor="#FFFFFF" style="background-color:#ffffff;background:url('.$purl.'/autoresponder-gwa/nimg/bkg_'.$t.');"><p style="padding: 5px;"><font face="Tahoma,Arial,Sans-serif" size="3">{CONTENT}</font></td></tr><tr> <td width="455" height="60" valign="middle" style="background:url('.$purl.'/autoresponder-gwa/nimg/'.$t.');"><p align="center"><b><font face="Tahoma,Arial,Sans-serif" size="3">'.$bname.'<br>Community Newsletter</font></b></td></tr><tr> <td width="457" height="1"></td></tr></table></div><div align="center"><table align="center" border="0" cellpadding="0" cellspacing="0" style="border-collapse: collapse" bordercolor="#111111" width="447" height="36" id="AutoNumber2"><tr> <td width="447" height="36"><p align="center"><font face="Tahoma" size="1" color="#666666">&lt;?Unsubscribe?&gt;<br> Sent to: &lt;?Name?&gt; at &lt;?Email?&gt;<br> Sent by: <a href="'.home_url().'">'.$bname.'</a></font></td></tr></table></div></body></html>'."','html')");
 }
 }
 if($wpdb->get_var("show columns from `".$wpdb->prefix."ar_gwa_msg` like 'nlid'") != 'nlid') {
 $sql = "ALTER TABLE `".$wpdb->prefix."ar_gwa_msg` ADD COLUMN `nlid` int(11) NOT NULL DEFAULT '0';";
 $wpdb->query( $sql ); 
 }
}

function echoWarning($msg) {
if(isset($msg) && $msg==1) echo '<tr><td colspan=2><div id="message" class="updated fade" style="width:450px"><p>'.__('You are using a Newsletter Template for this message.','argwa').'</p></div></td></tr>';
if(isset($msg) && $msg==2) echo '';
}

function addAction($data1=NULL,$data2=NULL) {
global $wpdb;
if(isset($data1)){
$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_newsletter WHERE id='{$data1}'";
$top = $wpdb->get_results($qry);
$top = $top[0]->content;
}
if(isset($data2)){
$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_newsletter WHERE id='{$data2}'";
$bot = $wpdb->get_results($qry);
$bot = $bot[0]->content;
}
$zim[] = $top;
$zim[] = $bot;
return $zim;
}

function addForm($s=NULL,$t=NULL) {
?><tr><td colspan=2><?php _e("Select a Newsletter Template to be used with the message contents below.",'argwa');?></td></tr>
		<td><?php _e('TEMPLATE','argwa');?></td>
		<td>
		<select name="nlTop" /><?php echo $this->ar_gwa_tpl_list($s,$t);?></select>&nbsp;<a href="admin.php?page=ar_gwa_newsletter&nlCreate=1"><?php _e('Add Newsletter Template','argwa');?></a>
		</td>
	</tr>
<?php
}

function ar_gwa_tpl_list($filter=NULL,$filter2=NULL) {
global $wpdb;
if($filter)
$filter = "WHERE listid=$filter";
if($filter2)
$filter3 = "WHERE id='$filter2'";
$qry = "SELECT * FROM ".$wpdb->prefix."ar_gwa_newsletter";
$res = $wpdb->get_results($qry);
$html = '<option value="0">'.__('None','argwa').'</option>';
foreach($res as $ras) {
$silect='';
if($ras->id==$filter2) $silect = 'selected';
 $html .= '<option value="'.$ras->id.'" '.$silect.'>'.$ras->name.' ('.$ras->mtype.')</option>';
 }
 return $html;
}

function admin_ar_gwa_tpl() {
global $wpdb;
$wpdb->show_errors();
$tbl_name = $wpdb->prefix.'ar_gwa_newsletter';
if($_REQUEST['act'] == 'del')
{
	// delete messages
	$xID = $_REQUEST['lID'];
   for($i = 0; $i < count($xID); $i++)
	 {
		$wpdb->query("DELETE FROM " . $tbl_name . " WHERE id='{$xID[$i]}'");
	 }
	$msg = __("Newsletter Template deleted successfully.",'argwa');
?>
<div id="">
<div class="wrap">
<?php if(isset($msg)) echo '<div id="message" class="updated fade"><p>'.$msg.'</p></div></div></div>';
}	

if($_REQUEST['nltid']>0 && isset($_REQUEST['nlBody']) && isset($_REQUEST['nlname'])) {
$wpdb->query("UPDATE ".$tbl_name." set `name`='".$wpdb->escape($_REQUEST['nlname'])."',`content`='".$wpdb->escape($_REQUEST['nlBody'])."',`desc`='".$_REQUEST['nlarea']."',mtype='".$_REQUEST['mType']."' WHERE id='".$_REQUEST['nltid']."'");
$record = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."ar_gwa_newsletter WHERE id='".$_REQUEST['nltid']."'");
$msg = __('Updated template record #','argwa').$_REQUEST['nltid'];
} else if($_REQUEST['nltid']>0 && (!isset($_REQUEST['nlBody']) || !isset($_REQUEST['nlorder']) ) && isset($_REQUEST['nlCreate'])) {
$msg = __('Empty value. Try Again!','argwa');
} else if($_REQUEST['nltid']==0 && isset($_REQUEST['nlBody']) && isset($_REQUEST['nlname'])) {
$lid = $wpdb->query("INSERT INTO ".$tbl_name." (`name`,`desc`,`order`,`content`,`mtype`) VALUES ('".$wpdb->escape($_REQUEST['nlname'])."','".$wpdb->escape($_REQUEST['nlarea'])."','".$_REQUEST['nlorder']."','".$_REQUEST['nlBody']."','".$_REQUEST['mType']."')");
$msg = __('Newsletter Template ID#','argwa').$lid.' '.__('added','argwa').'.';
} else if($nltid = $_REQUEST['nltid']) {
$record = $wpdb->get_row("SELECT * FROM ".$wpdb->prefix."ar_gwa_newsletter WHERE id='".$nltid."'");
}
#echo $msg;exit;
if(($lid || !isset($msg) ) && !isset($nltid) && !$_REQUEST['nlCreate']) {

$orderby = '`order`';
$tbl_name = $wpdb->prefix.'ar_gwa_newsletter';
$arSql = "SELECT * FROM " . $tbl_name . " ORDER BY ".$orderby;
$res = $wpdb->get_results($arSql);

if($res) {
?>
<div id="">
<div class="wrap">
<?php if(isset($msg)) echo '<div id="message" class="updated fade"><p>'.$msg.'</p></div>';?>
<form action="?page=ar_gwa_newsletter" method="post"><h2><?php printf(__("Manage Newsletter Template (%d)",'argwa'),count($res));?></h2><input type="submit" name="nlCreate" value="<?php _e('Create Newsletter Template','argwa');?>" class="button"><!--<textarea name="nldesc"></textarea>--></form>
<form action="?page=ar_gwa_newsletter" method="post" id="lists-filter">
<table class="widefat">
	<thead>
	<tr>
	<th scope="col" class="check-column"><input type="checkbox" onclick="checkAll(document.getElementById('lists-filter'));" /></th>
	<th scope="col"><a href="?page=ar_gwa_newsletter&orderby=name&dir=<?=$dir;?>"><?php _e("Name",'argwa');?></a></th>
	<th scope="col"><a href="?page=ar_gwa_newsletter&orderby=desc&dir=<?=$dir;?>"><?php _e("Desc",'argwa');?></a></th>
	<th scope="col"><a href="?page=ar_gwa_newsletter&orderby=mtype&dir=<?=$dir;?>"><?php _e("Type",'argwa');?></a></th>
	<th scope="col"><?php _e("Update",'argwa');?></th>
	</tr>
	</thead>
	<tbody>
	<tr id='post-1' class='alternate author-self status-publish' valign="top">
<?php
if($res){
	foreach($res as $row)
	{	
//    $row->xID = ar_gwa_getlistname($row->xID);
	echo '<tr><th scope="row" class="check-column"><input type="checkbox" name="lID[]" value="'.$row->id.'" /></th>'
		.'<td>'.$row->name.'</td><td><abbr title="'.$row->desc.'">'.$row->desc.'</abbr></td><td><abbr title="'.$row->mtype.'">'.$row->mtype.'</abbr></td>'
		.'<td><a href="?page=ar_gwa_newsletter&nltid='.$row->id.'">'.__('Update','argwa').'</a></td></tr>';
  }
}
  ?>
	</tbody>
<?php
	echo '</table><p>&nbsp;</p>';
	echo '<p><input type="submit" class="button" value="'.__("Delete Checked",'argwa').'">';
	echo '<input type="hidden" name="act" value="del"></p>';
	echo '</form>';
} else {
$msg = __("Please create a template to continue. Click CREATE.",'argwa');
?>
<div id="">
<div class="wrap">
<h2 style='display:inline;'><?php printf(__("newsletter Manager (%d)",'argwa'),count($res));?></h2>
<?php if(isset($msg)) echo '<div id="message" class="updated fade"><p>'.$msg.'</p></div>';?>
<form action="?page=ar_gwa_newsletter" method="post">Newsletter Template Name: for your use only.<br /><input type="text" name="nlname" value="" size="65"><br /><br />Newsletter Template Description: for your use only.<br /><textarea name="nlarea" cols=50 rows=3></textarea><br /><input type="submit" name="nlCreate" value="<?php _e("Create Newsletter Template",'argwa');?>" class="button"></form>
</div></div>
<?php
}
?>
<div id="ajax-response"></div>
<div class="tablenav">
<br class="clear" />
</div>
<br class="clear" />
</div>
</div><!-- wpbody --><?php
} else if((isset($_REQUEST['nlCreate']) || isset($_REQUEST['nltid'])) && !isset($_REQUEST['nlStep']) && (isset($record) || $lid==0)) {
$slect = 'selected';
$strt = "toggleEditor('editorContent');";
if(($record->mtype == 'html' | $record->mtype == 'hmtl') || (isset($_REQUEST['nlCreate']))) {
$slected = 'selected';
unset($slect);
}
if (function_exists('wp_tiny_mce') ) wp_tiny_mce( false ,
array(
"editor_selector" => "editorContent",
"plugins" => "spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
"theme_advanced_buttons1" => "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,styleselect,formatselect,fontselect,fontsizeselect",
"theme_advanced_buttons2" => "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
"theme_advanced_buttons3" => "hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen,|,spellchecker",
"extended_valid_elements" => "form[*],div[*],style[*],p[*],table[*],td[*]",
"skin" => "o2k7",
"skin_variant" => "silver",)
);
echo "<script type=\"text/javascript\">\n<!--
function toggleEditor(id) {
	if (!tinyMCE.getInstanceById(id))
		tinyMCE.execCommand('mceAddControl', false, id);
	else
		tinyMCE.execCommand('mceRemoveControl', false, id);
}\n";
echo "\n-->\n</script>";
?>
<div id="">
<div class="wrap">

<form name="mForm" method="post" action="?page=ar_gwa_newsletter">
<input type="hidden" name="nltid" value="<?=$record->id;?>">
<h2><?php _e("Add/Edit Newsletter Template",'argwa');?></h2>
<table align="center" width="725">
	<tr>
		<td><?php _e("Name:",'argwa');?>&nbsp;</td>
		<td> <?php echo argwa_get_note('45');?>
    
<?php
    if($record->name!='')
      echo $record->name.'<input type="hidden" name="nlname" value="'.$record->name.'">';
    else if ($_REQUEST['nlname']!='')
      echo $wpdb->escape($_REQUEST['nlname']).'<input type="hidden" name="nlname" value="'.$wpdb->escape($_REQUEST['nlname']).'">';
    else {
    ?>        
    <input type="text" name="nlname" style="width:167px;" maxlength="254" value="<?=$record->name;?>">&nbsp;<?php _e("For identification only.",'argwa'); } ?></td>
	</tr>
	<tr>
		<td><?php _e("Description:",'argwa');?>&nbsp;</td>
		<td><?php
    if($record->desc)
      echo $record->desc.'<input type="hidden" name="nlarea" value="'.$record->desc.'">';
    else if ($_REQUEST['nlarea']!='')
      echo $wpdb->escape($_REQUEST['nlarea']).'<input type="hidden" name="nlarea" value="'.$wpdb->escape($_REQUEST['nlarea']).'">';
    else {
    ?>        
    <textarea name="nlarea" class="nlarea" id="nlarea" style="width:300px;"><?php echo $record->name;?></textarea>&nbsp;<?php _e("Private (for identification only.)",'argwa'); } ?></td>
	</tr>
	<tr>
		<td><?php _e("Format",'argwa');?></td>
		<td>
		<select name="mType" style="width:100px;" onchange="toggleEditor('editorContent')"/>
		<option value="html" <?php echo $slected;?>><?php _e("HTML",'argwa');?></option>
		<option value="text" <?php echo $slect;?>><?php _e("PLAIN TEXT",'argwa');?></option>
		</select> <?php _e("Switch & Save HTML Display or Plain-Text Editor.",'argwa');?>   
		</td>
	</tr>
	<tr>
		<td valign="top"><?php _e("BODY",'argwa');?></td>
		<td><div style="background-color:#e4f2fd;border:solid 1px #22ff55;padding:5px;width:587px;"><strong><span color="red">IMPORTANT:</span> THIS IS ONLY A TEMPLATE FOR YOUR <a href="?page=ar_gwa_edit_message">MESSAGES</a>.</strong><br> Use the tag <strong style="color:#000">{CONTENT}</strong> inserted where you want your message text displayed. Normally this will be in the main content block of the html template.</div><textarea id="editorContent" class="editorContent" name="nlBody" cols="55" rows="47" style="width:570px; height:400px;"><?php echo stripslashes(htmlentities($record->content));?></textarea></td>

	</tr>
<tr>
		<td>&nbsp;</td><td style="background-color:#e4f2fd;border:solid 1px #22ff55;padding:5px;width:560px;"><?php _e('<strong>Personalize your Templates!</strong> <span style="color:#f00">*USE ONLY THE TAGS BELOW*</span><br />Use these custom tags when mailing your lists from this page.','argwa');?> <strong style="font-size:9pt;"> <&#63;Name&#63;> <&#63;Email&#63;> <&#63;Unsubscribe&#63;> <&#63;Archive&#63;> <&#63;Field1&#63;> <&#63;Field2&#63;> <&#63;Field3&#63;> <&#63;Field4&#63;> <&#63;Field5&#63;> <?php if(file_exists(dirname(__FILE__).'/ar_gwa_user_edit.php'))echo "<&#63;Update&#63;>";?></strong></td>
</tr>
	<tr>
		<td>&nbsp;</td>
		<td><input type="submit" class="button" value="<?php 
    if(isset($record)) 
      _e('Edit','argwa');
    else
      _e('Add','argwa');
    echo ' ';      
    _e('Newsletter Template Record','argwa');      
    ?>"></td>
	
  </tr>
</table>
<input type="hidden" name="act" value="add">
</form><?=$ctag?>
</div>
</div>
<?php
}
}

 function helpText() {
 $return[]= __('Email Message Newsletter Templates','argwa');
 $return[]= __('newsletter are used to add a common header or footer to message. Once created you simply need to select the newsletter to add to the message to give them a consistent look. Can be created as HTML or Plain-Text depending upon your intended message format. Once added to a message they will be part of the saved message content and editing the template will have no effect on the existing message with the assigned template. All DYNAMIC FIELDS can be included in both header and footer the template contents. NOTE: Header and Footer will be inserted to surround the content entered in the message window.','argwa');
 return $return;
 }

  function optionDelete() {
  global $wpdb;
  $wpdb->query("DROP TABLE ".$wpdb->prefix."ar_gwa_newsletter");
  }
}
?>