<?php
defined('_JEXEC') or die('Restricted access');

$db =& JFactory::getDBO();
$subs = $this->subs;
$error = '';
$message = '';

if ($_POST) {
  if ($_POST["editmailsubmit"]) {

    $query = 'SELECT * FROM `#__nspro_subs` WHERE `email` = "' . mysql_escape_string($_POST["editmail"]) . '"';
    $db->setQuery($query);

    $msub = $db->loadObject();

    if ($msub) {
      header("Location: index.php?option=com_nspro&controller=nspro&task=edit&cid[]=".$msub->id);
    }
    else {
      $error = JText::_('Email not found in subscriber list');
    }
  }
  else if ($_POST["delmailsubmit"]) {

    $query = 'SELECT * FROM `#__nspro_subs` WHERE `email` = "' . mysql_escape_string($_POST["delmail"]) . '"';
    $db->setQuery($query);

    $msub = $db->loadObject();

    if ($msub) {
      $query = 'DELETE FROM `#__nspro_subs` WHERE `email` = "' . mysql_escape_string($_POST["delmail"]) . '"';
      $db->Execute($query);

      // we have to reload subscriber list
      $query = 'SELECT * FROM `#__nspro_subs` ORDER BY `id`';
      $db->setQuery($query);
      $subs = $db->loadObjectList();

      $message = JText::_('Subscriber deleted successfully');
    }
    else {
      $error = JText::_('Email not found in subscriber list');
    }
  }
  else if ($_POST["newsletterToMail"]) {

    $query = 'SELECT * FROM `#__nspro_newsletters` WHERE `id` = "' . mysql_escape_string($_POST["newsletterIdToSend"]) . '"';
    $db->setQuery($query);
    
    $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

    $nsl = $db->loadObject();

    if ($nsl) {

      $mybase = JString::str_ireplace('/administrator/', '/', JURI::base());
      $myLink = $mybase.'index.php?option=com_nspro&layout=confirmunsub'.'&u='.md5($_POST["emailToSend"]);
      $myFTFLink = $mybase.'index.php?option=com_nspro&task=forwardtofriend&nid=' . $nsl->id;
      $myEDLLink = $mybase.'index.php?option=com_nspro&layout=editlists'.'&u='.md5($_POST["emailToSend"]);
      $mMessage = JString::str_ireplace('{unsubscribe_link}', $myLink, $nsl->message);
      $mMessage = JString::str_ireplace('{subscriber_name}', JText::_('Friend'), $mMessage);
      $mMessage = JString::str_ireplace('{subscriber_email}', $_POST["emailToSend"], $mMessage);
      $mMessage = JString::str_ireplace('{forward_to_friend_link}', '<a href="'. $myFTFLink .'">', $mMessage);
      $mMessage = JString::str_ireplace('{/forward_to_friend_link}', '</a>', $mMessage);
      $mMessage = JString::str_ireplace('{unsub_quick}', '<a href="'. $myLink .'">', $mMessage);
      $mMessage = JString::str_ireplace('{/unsub_quick}', '</a>', $mMessage);
      $mMessage = JString::str_ireplace('{edit_list_link}', '<a href="'. $myEDLLink .'">', $mMessage);
      $mMessage = JString::str_ireplace('{/edit_list_link}', '</a>', $mMessage);

      // links and images fix
      $mMessage = preg_replace('#src[ ]*=[ ]*\"(?!https?://)(?:\.\./|\./|/)?#',  'src="'.$mybase.'/',  $mMessage);
      $mMessage = preg_replace('#href[ ]*=[ ]*\"(?!https?://)(?:\.\./|\./|/)?#', 'href="'.$mybase.'/', $mMessage);

      $query = 'SELECT * FROM `#__nspro_newsletter_attachments` WHERE `newsletter_id` = ' . $nsl->id . ' ORDER BY `id`';
      $db->setQuery($query);
      $mattachments = $db->loadObjectList();

      $attachment = array();
      if (count($mattachments) > 0) {
        foreach( $mattachments as $mat) {
          $attachment[] = $target_dir.$mat->filename;
        }
      }

      if (JUtility::sendMail($nsl->fEmail, $nsl->fName, $_POST["emailToSend"], $nsl->subject, $mMessage, true, null, null, $attachment) !== true) {
        $error = JText::_('Newsletter could not be sent');
      }
      else {
        $message = JText::_('Newsletter sent successfully');
      }
    }
    else {
      $error = JText::_('Newsletter ID not found');
    }
  }
  else if ($_POST["selnewslettersend"]) {

    $query = 'SELECT * FROM `#__nspro_newsletters` WHERE `id` = "' . mysql_escape_string($_POST["newsletterIdToSend"]) . '"';
    $db->setQuery($query);

    $nsl = $db->loadObject();

    if ($nsl) {

      if (count($_POST["subscribersToSend"]) > 0) {
        $errorCount = 0;
        foreach($_POST["subscribersToSend"] as $msubId) {

          $query = 'SELECT * FROM `#__nspro_subs` WHERE `id` = "' . mysql_escape_string($msubId) . '"';
          $db->setQuery($query);

          $msub = $db->loadRow();

          if ($msub) {
            $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";
            
            $mybase = JString::str_ireplace('/administrator/', '/', JURI::base());
            $myLink = $mybase.'index.php?option=com_nspro&layout=confirmunsub'.'&u='.md5($msub[2]);
            $myFTFLink = $mybase.'index.php?option=com_nspro&task=forwardtofriend&nid=' . $nsl->id;
            $myEDLLink = $mybase.'index.php?option=com_nspro&layout=editlists'.'&u='.md5($msub[2]);
            $mMessage = JString::str_ireplace('{unsubscribe_link}', $myLink, $nsl->message);
            $mMessage = JString::str_ireplace('{subscriber_name}', $msub[1], $mMessage);
            $mMessage = JString::str_ireplace('{subscriber_email}', $msub[2], $mMessage);
            $mMessage = JString::str_ireplace('{forward_to_friend_link}', '<a href="'. $myFTFLink .'">', $mMessage);
            $mMessage = JString::str_ireplace('{/forward_to_friend_link}', '</a>', $mMessage);
            $mMessage = JString::str_ireplace('{unsub_quick}', '<a href="'. $myLink .'">', $mMessage);
            $mMessage = JString::str_ireplace('{/unsub_quick}', '</a>', $mMessage);
            $mMessage = JString::str_ireplace('{edit_list_link}', '<a href="'. $myEDLLink .'">', $mMessage);
            $mMessage = JString::str_ireplace('{/edit_list_link}', '</a>', $mMessage);            

            // links and images fix
            $mMessage = preg_replace('#src[ ]*=[ ]*\"(?!https?://)(?:\.\./|\./|/)?#',  'src="'.$mybase.'/',  $mMessage);
            $mMessage = preg_replace('#href[ ]*=[ ]*\"(?!https?://)(?:\.\./|\./|/)?#', 'href="'.$mybase.'/', $mMessage);
            
            $query = 'SELECT * FROM `#__nspro_newsletter_attachments` WHERE `newsletter_id` = ' . $nsl->id . ' ORDER BY `id`';
            $db->setQuery($query);
            $mattachments = $db->loadObjectList();

            $attachment = array();
            if (count($mattachments) > 0) {
              foreach( $mattachments as $mat) {
                $attachment[] = $target_dir.$mat->filename;
              }
            }
            
            if (JUtility::sendMail($nsl->fEmail, $nsl->fName, $msub[2], $nsl->subject, $mMessage, true, null, null, $attachment) !== true) {
              $errorCount = $errorCount + 1;
            }
          }
          else {
            $errorCount = $errorCount + 1;
          }
        } //foreach

        if ($errorCount != 0) {
          $error = $errorCount . JText::_(' messages could not be sent');
        }
        else {
          $message = JText::_('Newsletter(s) sent successfully');
        }
      }
      else {
        $error = JText::_('No Subscribers specified');
      }
    }
    else {
      $error = JText::_('Newsletter ID not found');
    }
  }
}


if ($message != '') {
  print '<dl id="system-message"><dt class="message">Message</dt><dd class="message message fade"><ul><li>';
  print $message;
  print '</li></ul></dd></dl>';
}

if ($error != '') {
  print '<dl id="system-message"><dt class="error">Error</dt><dd class="message error fade"><ul><li>';
  print $error;
  print '</li></ul></dd></dl>';
}

?>
<table width="100%" style="border: #ccc 1px solid; background: #f9f9f9;"><tr><td valign="top"><p><h2>NS Pro Toolkit</h2></p>
<p>A collection of tools to make NS Pro easier to use.</p>
<p>
<table><tr><td>
<!-- Tool 1: editmail -->
<fieldset style="width: 350px;">
<legend>Tool #1: Edit Subscriber</legend>
<form action="index.php?option=com_nspro&view=toolkit" method="post"><table><tr><td>Edit By Email:</td><td>
<input type="text" size="40" class="nspro inputbox" name="editmail" /></td><td><input type="submit" class="nspro button" name="editmailsubmit" value="Edit Subscriber"/></td></tr>
</table></form>
</fieldset>
<!-- Tool 2: delmail -->
<fieldset style="width: 350px;">
<legend>Tool #2: Delete Subscriber</legend>
<form action="index.php?option=com_nspro&view=toolkit" method="post"><table><tr><td>Delete By Email:</td><td>
<input type="text" size="40" class="nspro inputbox" name="delmail" /></td><td><input type="submit" class="nspro button" name="delmailsubmit" value="Delete Subscriber"/></td></tr>
</table></form>
</fieldset>
<!-- Tool 3: newsletterToMail -->
<fieldset style="width: 350px;">
<legend>Tool #3: Send Newsletter</legend>
<form action="index.php?option=com_nspro&view=toolkit" method="post">
<table>
<tr><td>Newsletter ID:</td><td><input type="text" size="25" class="nspro inputbox" name="newsletterIdToSend" /></td></tr>
<tr><td>Target Email:</td><td><input type="text" size="50" class="nspro inputbox" name="emailToSend" /></td></tr>
<td colspan="2"><input type="submit" class="nspro button" name="newsletterToMail" value="Send Newsletter"/></td></tr>
</table></form>
</fieldset>
</td><td>
<!-- Tool 4: selnewslettersend -->
<fieldset style="width: 450px;">
<legend>Tool #4: Selective Newsletter</legend>
<form action="index.php?option=com_nspro&view=toolkit" method="post"><table><tr><td style="width: 80px;">Newsletter ID:</td><td>
<input type="text" size="20" class="nspro inputbox" name="newsletterIdToSend" /></td></tr>
<tr>
<td colspan="2">
<select multiple="multiple" name="subscribersToSend[]" size="11" style="width: 420px;">
<?php
  foreach ($subs as $sub) {
    print '<option value="' . $sub->id . '">' . $sub->id . ': ' . $sub->email . '</option>';
  }
?>
</select>
</td>
</tr>
<tr><td colspan="2"><input type="submit" class="nspro button" name="selnewslettersend" value="Send Newsletter"/></td></tr>
</table></form>
</fieldset>
</td></tr></table>
</p><br/>
<p><small>Please suggest more tools at <a href="http://mavrosxristoforos.com/index.php/forum">NS Pro Feature Request Forum</a></small></p>
</td></tr></table>

<center><small><i>NS Pro by <a href="http://www.mavrosxristoforos.com/">Mavrosxristoforos.com</a> Copyright 2010</i></small></center>