<?php
/**
 * Joomla! 1.5 component NS Pro
 *
 * @version $Id: nspro.php 2009-04-28 01:47:12 svn $
 * @author Christopher Mavros
 * @package Joomla
 * @subpackage NS Pro
 * @license GNU/GPL
 *
 * Pro Version of Newsletter Subscriber.
Provides:
Keep subscriptions in database
Unsubscription Page
Optional Confirmation on subscribe/unsubscribe
Subscription Manager
Send Newsletters
Newsletter Manager
Subscription Statistics
Unique Emails (does not allow duplicates)
 *
 * This component file was created using the Joomla Component Creator by Not Web Design
 * http://www.notwebdesign.com/joomla_component_creator/
 *
 */

// no direct access
defined('_JEXEC') or die('Restricted access');

// Import Joomla! libraries
jimport('joomla.application.component.model');

class NsproModelNewsletters extends JModel {
    function __construct()
    {
        parent::__construct();

        $array = JRequest::getVar('cid',  0, '', 'array');
        $this->setId((int)$array[0]);
    }

    /**
     * Method to set the NsNewsletters identifier
     *
     * @access  public
     * @param   int NsNewsletters identifier
     * @return  void
     */
    function setId($id)
    {
        // Set id and wipe data
        $this->_id      = $id;
        $this->_data    = null;
    }

    function getNewsletter()
    {
        $db =& JFactory::getDBO();
        // Load the data
        if (empty( $this->_data )) {
            $query = ' SELECT * FROM #__nspro_newsletters '.
                    '  WHERE id = '.$this->_id;
            $db->setQuery( $query );
            $this->_data = $db->loadObject();
        }
        if (!$this->_data) {
            $this->_data = new stdClass();
            $this->_data->id = 0;
            $this->_data->fName  = null;
            $this->_data->fEmail = null;
            $this->_data->subject = null;
            $this->_data->message = null;
            $this->_data->datetime = null;
            $this->_data->sent = false;
        }
        return $this->_data;
    }

    function getNewsletterById($id)
    {
        $db =& JFactory::getDBO();

        $query = ' SELECT * FROM #__nspro_newsletters '.
                 '  WHERE id = '.$id;
        $db->setQuery( $query );
        $ndata = $db->loadObject();
        return $ndata;
    }

    function getNewsletters($limit, $limitstart) {
        $db =& JFactory::getDBO();

        $query = 'SELECT * FROM #__nspro_newsletters';

        $newsletterss = $this->_getList( $query , $limitstart, $limit);

        return $newsletterss;
    }

    function getNewslettersCount() {
        $db =& JFactory::getDBO();

        $query = 'SELECT COUNT(*) FROM #__nspro_newsletters';

        $db->setQuery( $query );
        $nCount = $db->loadResult();

        return $nCount;
    }

    /**
     * Method to store a record
     *
     * @access  public
     * @return  boolean True on success
     */
    function store()
    {
        $db =& JFactory::getDBO();
        $row =& $this->getTable('nsnewsletters');
        //$data = JRequest::get( 'post' );
        $data = $_POST;
        $data['message'] = stripcslashes($data['message']);

        // Bind the form fields to the nsnewsletters table
        if (!$row->bind($data)) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        // Make sure the nsnewsletters records are valid
        if (!$row->check()) {
            $this->setError($db->getErrorMsg());
            return false;
        }

        // Store the nsnewsletters table to the database
        if (!$row->store()) {
            $this->setError( $row->getErrorMsg() );
            return false;
        }

        return true;
    }

    /**
     * Method to delete record(s)
     *
     * @access  public
     * @return  boolean True on success
     */
    function delete()
    {
        $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

        $row =& $this->getTable('nsnewsletters');

        if (count( $cids ))
        {
            foreach($cids as $cid) {
                if (!$row->delete( $cid )) {
                    $this->setError( $row->getErrorMsg() );
                    return false;
                }
            }
        }
        return true;
    }

    function send() {
      $cids = JRequest::getVar( 'cid', array(0), 'post', 'array' );

      $target_dir = JPATH_ADMINISTRATOR.DS."components/com_nspro/uploads/";

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      $component = JComponentHelper::getComponent( 'com_nspro' );
      $params = new JParameter( $component->params );

      $newsletter_delay = $params->get( 'newsletter_delay', '' );

      $db =& JFactory::getDBO();
      $query = 'SELECT * FROM #__nspro_subs WHERE `confirmed` = 1';
      $db->setQuery($query);
      $msubs = $db->loadRowList();

      if ($newsletter_delay != '') {
        $mtlim = $newsletter_delay * count($cids) * count($msubs) + 20;
        set_time_limit($mtlim);
      }

      if (count($cids) > 0) {
        $errors = 0;
        $error_report = '';
        foreach($cids as $cid) {
          $mnewsletter = $this->getNewsletterById($cid);
          $newslists = array();
          if ($mnewsletter->mailing_lists !== '') {
            $newslists = explode(',', $mnewsletter->mailing_lists);
          }

          $query = 'SELECT * FROM #__nspro_subs WHERE `confirmed` = 1';
          if (count($newslists) > 0) {
            $query = $query . ' AND (';
            $firstpass = true;
            foreach ($newslists as $newslist) {
              if ($firstpass) {
                $query = $query . '(FIND_IN_SET("'.$newslist.'", `mailing_lists`) > 0)';
                $firstpass = false;
              }
              else {
                $query = $query . 'OR (FIND_IN_SET("'.$newslist.'", `mailing_lists`) > 0)';
              }
            }
            $query = $query . ')';
          }
          $query = $query . ' ORDER BY `email`';
          $db->setQuery($query);
          $msubs = $db->loadRowList();

          foreach($msubs as $msub) {
            $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=' . $mnewsletter->id;
            $myEDLLink = $mybase.'index.php?option=com_nspro&layout=editlists'.'&u='.md5($msub[2]);
            $mMessage = JString::str_ireplace('{unsubscribe_link}', $myLink, $mnewsletter->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` = ' . $mnewsletter->id . ' ORDER BY `id`';
            $db->setQuery($query);
            $mattachments = $db->loadObjectList();

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

            if (JUtility::sendMail($mnewsletter->fEmail, $mnewsletter->fName, $msub[2], $mnewsletter->subject, $mMessage, true, null, null, $attachment) !== true) {
              $errors = $errors + 1;
              $error_report = JText::_('Error sending Newsletter ID:') . ' ' . $mnewsletter->id . ', ' . JText::_('Subscriber Email:') . ' ' . $msub[2] . ', '. JText::_('Date & Time:') . ' ' . date('r') . "\n";
              break;
            }
            if ($newsletter_delay != '') {
              sleep($newsletter_delay);
            }
          }
          if ($error_report != '') {
            $target_file = JPATH_ADMINISTRATOR.DS."components/com_nspro/error_report.txt";
            $file = fopen($target_file, "a");
            if ($file !== false) {           
              fwrite($file, $error_report);
              fclose($file);
            }
            break;
          }
          $query = 'UPDATE `#__nspro_newsletters` SET `sent` = "1" WHERE `id` = "'.$cid.'"';
          $db->setQuery($query);
          $db->query();
          $query = 'UPDATE `#__nspro_newsletters` SET `datetime` = "'.date('Y-m-d H:i:s').'" WHERE `id` = "'.$cid.'"';
          $db->setQuery($query);
          $db->query();
        }
      }

      if ($errors > 0) {
        return $errors.' '.JText::_('newsletters could not be sent');
      }
      return true;
    }

}
?>