<?php
/**
 * Joomla! 1.5 component NS Pro
 *
 * @version $Id: controller.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');

jimport( 'joomla.application.component.controller' );
require_once( JPATH_COMPONENT.DS.'helpers'.DS.'helper.php' );

/**
 * NS Pro Controller
 *
 * @package Joomla
 * @subpackage NS Pro
 */
class NsproController extends JController {

    /**
     * Constructor
     * @access private
     * @subpackage NS Pro
     */
    function __construct() {
        //Get View
        if(JRequest::getCmd('view') == '') {
            JRequest::setVar('view', 'default');
        }
        $this->item_type = 'Default';
        parent::__construct();

        $this->registerTask( 'add'  ,   'edit' );
    }

    /**
     * Method to display the view
     *
     * @access  public
     */
    function display()
    {
        parent::display();
    }

    /**
     * display the edit form
     * @return void
     */
    function edit()
    {
        JRequest::setVar( 'view', 'nspro' );
        JRequest::setVar( 'layout', 'form'  );
        JRequest::setVar('hidemainmenu', 1);

        parent::display();
    }

    function qconfirm()
    {
        $array = JRequest::getVar('cid',  0, '', 'array');
        $mId = (int)$array[0];

        $db =& JFactory::getDBO();

        $query = 'UPDATE `#__nspro_subs` SET `confirmed` = "1" WHERE `id` = "'.$mId.'"';

        $db->setQuery($query);

        if ($db->query()) {
          $msg = 'Subscriber(s) confirmed';
        }
        else {
          $msg = 'Error confirming Subscriber(s)';
        }


        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
    }

    function quconfirm()
    {
        $array = JRequest::getVar('cid',  0, '', 'array');
        $mId = (int)$array[0];

        $db =& JFactory::getDBO();

        $query = 'UPDATE `#__nspro_subs` SET `confirmed` = "0" WHERE `id` = "'.$mId.'"';

        $db->setQuery($query);

        if ($db->query()) {
          $msg = 'Subscriber(s) unconfirmed';
        }
        else {
          $msg = 'Error unconfirming Subscriber(s)';
        }


        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
    }


    /**
     * save a record (and redirect to main page)
     * @return void
     */
    function save()
    {
        $model = $this->getModel('subscribers');

        if ($model->store($post)) {
            $msg = JText::_( 'Subscriber Saved!' );
        } else {
            $msg = JText::_( 'Error Saving Subscriber' );
        }

        // Check the table in so it can be edited.... we are done with it anyway
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
    }

    /**
     * remove record(s)
     * @return void
     */
    function remove()
    {
        $model = $this->getModel('subscribers');
        if(!$model->delete()) {
            $msg = JText::_( 'Error: One or More Subscribers Could not be Deleted' );
        } else {
            $msg = JText::_( 'Subscriber(s) Deleted' );
        }

        $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg );
    }

    /**
     * cancel editing a record
     * @return void
     */
    function cancel()
    {
        $msg = JText::_( 'Operation Cancelled' );
        $this->setRedirect( 'index.php?option=com_nspro&view=subscribers', $msg );
    }

    /**
     * display the edit form
     * @return void
     */
    function ledit()
    {
        JRequest::setVar( 'view', 'listedit' );
        JRequest::setVar( 'layout', 'form'  );
        JRequest::setVar('hidemainmenu', 1);

        parent::display();
    }

    /**
     * save a record (and redirect to main page)
     * @return void
     */
    function lsave()
    {
        $model = $this->getModel('lists');

        if ($model->store()) {
            $msg = JText::_( 'List Saved!' );
        } else {
            $msg = JText::_( 'Error Saving List' );
        }

        $link = 'index.php?option=com_nspro';
        $this->setRedirect($link, $msg);
    }

    /**
     * remove record(s)
     * @return void
     */
    function lremove()
    {
        $model = $this->getModel('lists');
        if(!$model->delete()) {
            $msg = JText::_( 'Error: One or More Lists Could not be Deleted' );
        } else {
            $msg = JText::_( 'List(s) Deleted' );
        }

        $this->setRedirect( 'index.php?option=com_nspro', $msg );
    }

    /**
     * cancel editing a record
     * @return void
     */
    function lcancel()
    {
        $msg = JText::_( 'Operation Cancelled' );
        $this->setRedirect( 'index.php?option=com_nspro', $msg );
    }

    function publish()
    {
        $model = $this->getModel('default');

        if ($model->publish(( $this->getTask() == 'publish' ? 1 : 0 ))) {
            $msg = JText::_( 'List(s) Published!' );
        } else {
            $msg = JText::_( 'Error Publishing List(s)' );
        }

        $this->setRedirect( 'index.php?option=com_nspro', $msg );
    }

    function unpublish()
    {
        $model = $this->getModel('default');

        if ($model->publish(( $this->getTask() == 'publish' ? 1 : 0 ))) {
            $msg = JText::_( 'List(s) Unpublished!' );
        } else {
            $msg = JText::_( 'Error Unpublishing List(s)' );
        }

        $this->setRedirect( 'index.php?option=com_nspro', $msg );
    }

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

        $confirm_url = 'index.php?option=com_nspro&view=nspro&layout=confirm&nss=nsplgp';
        $myBase = JString::str_ireplace('/administrator/', '/', JURI::base());
        $uri = & JURI::getInstance();

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

        $errors = 0;

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

        $fromNameConfirm = $params->get('from_name_confirm', 'Newsletter Subscriber');
        $fromEmailConfirm = $params->get('from_email_confirm', 'newsletter_subscriber@yoursite.com');
        $subjectConfirm = $params->get('subject_confirm', 'Subscription Confirmation');

        if (count( $cids )) {
          foreach($cids as $cid) {
            $query = 'SELECT * FROM `#__nspro_subs` WHERE `id` = "'.$cid.'"';
            $db->setQuery( $query );
            $msub = $db->loadObject();
            $myMessage = JText::_('Thank you for subscribing at ').$uri->getHost()." .\n<br/>\n<br/>".
                         "\n<br/>".'<a href="'.$myBase.$confirm_url.'&u='.md5($msub->email).'">'.JText::_('Click to complete your Subscription').
                         "</a>\n<br/>\n<br/>".JText::_('or copy this to your address bar')."\n<br/>\n<br/>".$myBase.$confirm_url.'&u='.md5($msub->email);
            if (JUtility::sendMail($fromEmailConfirm, $fromNameConfirm, $msub->email, $subjectConfirm, $myMessage, true) !== true) {
              $errors = $errors + 1;
            }
          }
        }

        if ($errors > 0) {
          $msg = JText::_( 'Error Sending Confirmation(s)' );
        }
        else {
          $msg = JText::_( 'Confirmation(s) sent!' );
        }

        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
    }

    function exporttxt() {

      $db =& JFactory::getDBO();

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

      $db->setQuery($query);

      $msubs = $db->loadObjectList();

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

      $export_delim = $params->get('export_delimiter', ',');
      $export_time  = $params->get('export_time', '5');

      $file = 'components/com_nspro/uploads/export_list.txt';

      $handle = fopen($file, 'w');

      if ($handle == false) {
        $msg = 'Error saving file';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      foreach ($msubs as $msub) {
        fwrite($handle, $msub->name.$export_delim.$msub->email.$export_delim.$msub->datetime.$export_delim.$msub->confirmed.$export_delim.$msub->mailing_lists.$export_delim."\n");
      }

      fclose($handle);

      $exported = true;

      if ($exported) {
        setcookie('export_txt', MD5('export_txt'), time()+60*$export_time);
        $msg = JText::_( 'Text File Exported' ) . '. <a href="components/com_nspro/uploads/gettxt.php" target="_blank">'.JText::_('Click to download').'.</a>';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
      }
      else {
        $msg = JText::_( 'Error Exporting Text File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

    }

    function exportcsv() {

      $db =& JFactory::getDBO();

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

      $db->setQuery($query);

      $msubs = $db->loadObjectList();

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

      $export_delim = $params->get('export_delimiter', ',');
      $export_time  = $params->get('export_time', '5');

      $file = 'components/com_nspro/uploads/export_list.csv';

      $handle = fopen($file, 'w');

      if ($handle == false) {
        $msg = 'Error saving file';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      foreach ($msubs as $msub) {
        fwrite($handle, $msub->name.$export_delim.$msub->email.$export_delim.$msub->datetime.$export_delim.$msub->confirmed.$export_delim.$msub->mailing_lists.$export_delim."\n");
      }

      fclose($handle);

      $exported = true;

      if ($exported) {
        setcookie('export_csv', MD5('export_csv'), time()+60*$export_time);
        $msg = JText::_( 'Excel File Exported' ) . '. <a href="components/com_nspro/uploads/getcsv.php" target="_blank">'.JText::_('Click to download').'.</a>';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
      }
      else {
        $msg = JText::_( 'Error Exporting Excel File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

    }

    function exportns() {

      $db =& JFactory::getDBO();

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

      $db->setQuery($query);

      $msubs = $db->loadObjectList();

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

      $export_time  = $params->get('export_time', '5');

      $file = 'components/com_nspro/uploads/mailing_list.txt';

      $handle = fopen($file, 'w');

      if ($handle == false) {
        $msg = 'Error saving file';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      foreach ($msubs as $msub) {
        fwrite($handle, $msub->name.' ('.$msub->email.'); ');
      }

      fclose($handle);

      $exported = true;

      if ($exported) {
        setcookie('export_ns', MD5('export_ns'), time()+60*$export_time);
        $msg = JText::_( 'NS File Exported' ) . '. <a href="components/com_nspro/uploads/getns.php" target="_blank">'.JText::_('Click to download').'.</a>';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
      }
      else {
        $msg = JText::_( 'Error Exporting NS File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

    }

    function exportxml() {

      $db =& JFactory::getDBO();

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

      $db->setQuery($query);

      $msubs = $db->loadObjectList();

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

      $export_time  = $params->get('export_time', '5');

      $file = 'components/com_nspro/uploads/export_list.xml';

      $handle = fopen($file, 'w');

      if ($handle == false) {
        $msg = 'Error saving file';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      fwrite($handle, '<root>'."\n".'<nspro_xml>'."\n");

      foreach ($msubs as $msub) {
        fwrite($handle, '  <nspro_subscriber id="'.$msub->id.'">'."\n".'    <name>'.$msub->name.'</name>'."\n".'    <email>'.$msub->email.'</email>'."\n".'    <datetime>'.$msub->datetime.'</datetime>'."\n".'    <confirmed>'.$msub->confirmed.'</confirmed>'.'<mailing_lists>'.$msub->mailing_lists.'</mailing_lists>'."\n".'  </nspro_subscriber>'."\n");
      }

      fwrite($handle, '</nspro_xml>'."\n".'</root>');

      fclose($handle);

      $exported = true;

      if ($exported) {
        setcookie('export_xml', MD5('export_xml'), time()+60*$export_time);
        $msg = JText::_( 'XML File Exported' ) . '. <a href="components/com_nspro/uploads/getxml.php" target="_blank">'.JText::_('Click to download').'.</a>';
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg);
      }
      else {
        $msg = JText::_( 'Error Exporting NS File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

    }

    function importFromJoomla() {

      $model = $this->getModel('subscribers');
      $imported = $model->importFromJoomlaUsers();

      if ($imported == true) {
        $msg = JText::_( 'Data Imported From Joomla Users' );
      }
      else {
        $msg = JText::_( 'Error Importing From Joomla Users' ).': '.$imported;
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      $link = 'index.php?option=com_nspro&view=subscribers';
      $this->setRedirect($link, $msg);
    }

    function importtxt() {

      $target_dir = "components/com_nspro/uploads/";

      $target_path = basename( $_FILES['uploadedfile']['name']);

      $target_path = JString::str_ireplace('/', '', $target_path);

      $uploaded = false;
      if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_dir.$target_path)) {
        $uploaded = true;
      }

      if (!$uploaded) {
        $msg = JText::_( 'Error Uploading File' );
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      $model = $this->getModel('subscribers');

      $imported = 'Unknown Error';

      if ($_POST["inputtype"] == '1') {
        $imported = $model->importFromTextFile($target_dir.$target_path);
      }
      else if ($_POST["inputtype"] == '2') {
        $imported = $model->importFromExcelFile($target_dir.$target_path);
      }
      else {
        $imported = $model->importFromNSFile($target_dir.$target_path);
      }

      if ($imported == true) {
        $msg = JText::_( 'Data Imported From Text/Excel File' );
      }
      else {
        $msg = JText::_( 'Error Importing From Text File' ).': '.$imported;
        $link = 'index.php?option=com_nspro&view=subscribers';
        $this->setRedirect($link, $msg, 'error');
      }

      $link = 'index.php?option=com_nspro&view=subscribers';
      $this->setRedirect($link, $msg);
    }

    /**
     * display the edit form
     * @return void
     */
    function nedit()
    {
        JRequest::setVar( 'view', 'newsletteredit' );
        JRequest::setVar( 'layout', 'form'  );
        JRequest::setVar('hidemainmenu', 1);

        parent::display();
    }

    /**
     * save a record (and redirect to main page)
     * @return void
     */
    function nsave()
    {
        $model = $this->getModel('newsletters');

        if ($model->store()) {
            $msg = JText::_( 'Newsletter Saved!' );
        } else {
            $msg = JText::_( 'Error Saving Newsletter' );
        }

        // Check the table in so it can be edited.... we are done with it anyway
        $link = 'index.php?option=com_nspro&view=newsletters';
        $this->setRedirect($link, $msg);
    }

    /**
     * remove record(s)
     * @return void
     */
    function nremove()
    {
        $model = $this->getModel('newsletters');
        if(!$model->delete()) {
            $msg = JText::_( 'Error: One or More Newsletters Could not be Deleted' );
        } else {
            $msg = JText::_( 'Newsletter(s) Deleted' );
        }

        $this->setRedirect( 'index.php?option=com_nspro&view=newsletters', $msg );
    }

    /**
     * cancel editing a record
     * @return void
     */
    function ncancel()
    {
        $msg = JText::_( 'Operation Cancelled' );
        $this->setRedirect( 'index.php?option=com_nspro&view=newsletters', $msg );
    }

    function nsend() {
      $model = $this->getModel('newsletters');

      $nresult = $model->send($post);

      if ($nresult === true) {
          $msg = JText::_( 'Message(s) sent!' );
      } else {
          $msg = JText::_( 'Error Sending Messages' ).': '.$nresult . '. Please check the <a href="components/com_nspro/error_report.txt" target="_blank">error report file</a>.';
      }

      $link = 'index.php?option=com_nspro&view=newsletters';
      $this->setRedirect($link, $msg);
    }

    function attachfile() {

      $db =& JFactory::getDBO();

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

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

      $msg = JText::_( 'Attachment(s) uploaded successfully' );

      for ($i = 0; $i < 5; $i ++) {
        $uploaded = false;
        if ($_FILES['file_' . $i]) {
          $realname = basename( $_FILES['file_' . $i]['name']);
          $target_path = $realname;
          $target_path = JString::str_ireplace('/', '', $target_path);
          if(move_uploaded_file($_FILES['file_' . $i]['tmp_name'], $target_dir.$target_path)) {
            $uploaded = true;
          }

          if (!$uploaded) {
            //$msg = JText::_( 'Error Uploading Attachments' );
            // seems that I come here even if the file is not uploaded.
            // so im just going to leave it like that for the moment.
            break;
          }

          if ($uploaded) {
            $mfiletypes = $params->get('upfiletypes', 'jpg;jpeg;png;bmp;pdf;gif;txt;csv;zip;doc;rar;7z;wmv;wma;mp3;xls;xml;htm;html;psd;');
            $allowedTypes = explode(';', strtolower($mfiletypes));
            if (!in_array(end(explode(".", strtolower($fileField['name']))), $allowedTypes)) {
              $msg = JText::_( 'Attachment Filetype not allowed: ' ) . end(explode(".", strtolower($fileField['name'])));
              $link = 'index.php?option=com_nspro&view=newsletters&task=nedit&cid[]=' . $_POST['newsletter_id'];
              $this->setRedirect($link, $msg);
            }
          }

          if ($uploaded) {
            $query = 'INSERT INTO `#__nspro_newsletter_attachments` (`newsletter_id`, `filename`) ' .
                     'VALUES ('. $_POST['newsletter_id'] .', "'.$realname.'")';
            $db->setQuery($query);
            $db->Query();
          }
        }
      }

      $link = 'index.php?option=com_nspro&view=newsletters&task=nedit&cid[]=' . $_POST['newsletter_id'];
      $this->setRedirect($link, $msg);
    }

    function deleteattachments() {

      $db =& JFactory::getDBO();

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

      $msg = JText::_( 'Attachment(s) Deleted Successfully' );

      $attachment_ids = $_POST['attachment'];
      foreach($attachment_ids as $aid) {

        $query = 'SELECT * FROM `#__nspro_newsletter_attachments` WHERE `id` = ' . $aid;
        $db->setQuery($query);
        $mat = $db->loadObject();
        unlink($target_dir.$mat->filename);

        $query = 'DELETE FROM `#__nspro_newsletter_attachments` WHERE `id` = ' . $aid;
        $db->setQuery($query);
        if (!$db->Query()) {
          $msg = JText::_( 'Error Deleting Attachment(s)' );
        }
      }
      $link = 'index.php?option=com_nspro&view=newsletters&task=nedit&cid[]=' . $_POST['newsletter_id'];
      $this->setRedirect($link, $msg);
    }

}
?>