<?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 NsproModelDefault extends JModel {

    function __construct()
    {
        parent::__construct();

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

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

    function getList()
    {
        $db =& JFactory::getDBO();
        // Load the data
        if (empty( $this->_data )) {
            $query = ' SELECT * FROM #__nspro_lists '.
                    '  WHERE id = '.$this->_id;
            $db->setQuery( $query );
            $this->_data = $db->loadObject();
        }
        if (!$this->_data) {
            $this->_data = new stdClass();
            $this->_data->id = 0;
            $this->_data->lname  = null;
            $this->_data->published = false;
            $this->_data->notes = null;
        }
        return $this->_data;
    }

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

        $query = 'SELECT * FROM #__nspro_lists ORDER BY `id`';

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

        return $lists;
    }

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

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

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

        return $lCount;
    }

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

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

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

        // Store the nssubs 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('nslists');

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

        $db     =& JFactory::getDBO();

        $cid        = JRequest::getVar( 'cid', array(), '', 'array' );
        $publish    = $i;

        JArrayHelper::toInteger($cid);

        $cids = implode( ',', $cid );

        $query = 'UPDATE `#__nspro_lists`'
        . ' SET `published` = ' . (int) $publish
        . ' WHERE `id` IN ( '. $cids .' )';
        $db->setQuery( $query );
        if (!$db->query())
        {
            JError::raiseError(500, $db->getErrorMsg() );
        }

        if (count( $cid ) == 1)
        {
            $row =& $this->getTable('nslists');
            $row->checkin( $cid[0] );
        }

        return true;
    }        

    function insertLine($iname, $iemail, $idatetime, $iconfirmed, $ilists) {
      $db =& JFactory::getDBO();
      $query = 'INSERT INTO #__nspro_subs (`name`, `email`, `datetime`, `confirmed`, `mailing_lists`) VALUES ("'.$iname.'", "'.$iemail.'", "'.$idatetime.'", "'.$iconfirmed.'", "'.$ilists.'")';

      $db->setQuery( $query );
      return $db->query();

    }

    function importFromNSFile($filename) {

      $handle = fopen($filename, "r");
      $contents = fread($handle, filesize($filename));
      fclose($handle);

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );
      $component = JComponentHelper::getComponent( 'com_nspro' );
      $params = new JParameter( $component->params );
      
      $delimtype = $params->get( 'import_ns_delimiter', '0' );
      if ($delimtype == '1') {
        $startDelim = '<';
        $endDelim   = '>';
      }
      else if ($delimtype == '2') {
        $startDelim = '[';
        $endDelim   = ']';
      }
      else if ($delimtype == '3') {
        $startDelim = '{';
        $endDelim   = '}';
      }
      else {
        $startDelim = '(';
        $endDelim   = ')';
      }

      $atleastone = false;
      $startChar = 0;
      $fromChar = JString::strpos($contents, $startDelim);
      while ($fromChar !== false) {
        $myRecipientsName = JString::substr($contents, $startChar, $fromChar - $startChar - 1);
        $toChar = JString::strpos($contents, $endDelim, $fromChar);
        $myRecipient = JString::substr($contents, $fromChar+1, $toChar-$fromChar-1);

        $atleastone = true;
        $this->insertLine($myRecipientsName, $myRecipient, date('Y-m-d H:i:s'), 1, '');

        $fromChar = JString::strpos($contents, $startDelim, $toChar);
        $startChar = $toChar+2;
      }

      if ($atleastone == false) {
        return 'No subscribers found.';
      }

      return true;

    }

    function importFromTextFile($filename) {

      $handle = fopen($filename, "r");
      $contents = fread($handle, filesize($filename));
      fclose($handle);

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

      $contents = preg_replace('/\r\n|\r/', "\n", $contents);

      $lines = explode("\n", $contents);

      $atleastone = false;
      foreach ($lines as $line) {
        if ($line == '') {
          continue;
        }
        $values = explode($idelim, $line);
        $atleastone = true;
        $this->insertLine($values[0], $values[1], $values[2], $values[3], $values[4]);
      }

      if ($atleastone == false) {
        return 'No subscribers found.';
      }

      return true;

    }

    function importFromExcelFile($filename) {

      $handle = fopen($filename, "r");
      $contents = fread($handle, filesize($filename));
      fclose($handle);

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

      $contents = preg_replace('/\r\n|\r/', "\n", $contents);

      $lines = explode("\n", $contents);

      $atleastone = false;
      foreach ($lines as $line) {
        if ($line == '') {
          continue;
        }
        $values = explode($idelim, $line);
        $atleastone = true;
        $this->insertLine($values[0], $values[1], $values[2], $values[3], $values[4]);
      }

      if ($atleastone == false) {
        return 'No subscribers found.';
      }

      return true;

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

      $query = 'SELECT * FROM #__users ORDER BY `id`';

      $db->setQuery($query);

      $users = $db->loadObjectList();
      
      $msubs = $this->getAllSubs();
      
      foreach($users as $user) {
        $found = false;
        for ($i = 0; $i < count($msubs); $i++) {
          if ($msubs[$i]->email == $user->email) {
            $found = true;
            break;
          }
        }
        if (!$found) {
          $this->insertLine($user->name, $user->email, $user->registerDate, 1, '');
        }
      }
      
      return true;
    }

}
?>