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

jimport( 'joomla.plugin.plugin' );

class plgContentNewsletter_subscriber_Pro extends JPlugin {

  function plgContentNewsletter_subscriber_Pro( &$subject, $config ) {
    parent::__construct( $subject, $config );
  }

  function onPrepareContent(&$row, &$params, $page=0) {
    if (is_object($row)) {
        $text = &$row->text;
    }
    else {
      $text = &$row;
    }
    global $mainframe;

    if (JString::strpos($text, '{newsletter_subscriber_pro}') === false) {
      return true;
    }
    $plugin = & JPluginHelper::getPlugin('content', 'newsletter_subscriber_pro');
    $pluginParams = new JParameter($plugin->params);
    
    $db =& JFactory::getDBO();
    
    // email parameters
    $recipient = $pluginParams->def('email_recipient', 'email@email.com');
    $subject = $pluginParams->def('subject', 'New subscription to your site!');
    $fromName = $pluginParams->def('from_name', 'Newsletter Subscriber');
    $fromEmail = $pluginParams->def('from_email', 'newsletter_subscriber@yoursite.com');
    $sendingWithSetEmail = $pluginParams->def('sending_from_set', true);        
    
    // text parameters
    $myNameLabel = $pluginParams->def('name_label', 'Name:');
    $myEmailLabel = $pluginParams->def('email_label', 'Email:');
    $mailing_list_label = $pluginParams->def('mailing_list_label', 'Mailing Lists:');
    $buttonText = $pluginParams->def('button_text', 'Subscribe to Newsletter');
    $pageText = $pluginParams->def('page_text', 'Thank you for subscribing to our site.');
    $errorText = $pluginParams->def('errot_text', 'Your subscription could not be submitted. Please try again.');
    $noName = $pluginParams->def('no_name', 'Please write your name');
    $noEmail = $pluginParams->def('no_email', 'Please write your email');
    $invalidEmail = $pluginParams->def('invalid_email', 'Please write a valid email');
    $pre_text = $pluginParams->def('pre_text', '');
    
    // size & color parameters
    $nameWidth = $pluginParams->def('name_width', '20');
    $emailWidth = $pluginParams->def('email_width', '20');
    $buttonWidth = $pluginParams->def('button_width', '100');
    $thanksTextColor = $pluginParams->def('thank_text_color', '#FF0000');
    $errorTextColor = $pluginParams->def('error_text_color', '#FF0000');    
    
    // file parameters
    $saveList = $pluginParams->def('save_list', true);
    $savePath = $pluginParams->def('save_path', 'mailing_list.txt');    
    $saveFormat = $pluginParams->def('save_format', '%n (%e);');
    
    // url parameters
    $exact_url = $pluginParams->def('exact_url', true);
    $disable_https = $pluginParams->def('disable_https', false);
    $fixed_url = $pluginParams->def('fixed_url', true);
    $myFixedURL = $pluginParams->def('fixed_url_address', "");
    
    // anti spam parameters
    $enable_anti_spam = $pluginParams->def('enable_anti_spam', true);
    $myAntiSpamQuestion = $pluginParams->def('anti_spam_q', 'How many eyes has a typical person? (ex: 1)');
    $myAntiSpamAnswer = $pluginParams->def('anti_spam_a', '2');    
    $anti_spam_position = $pluginParams->def('anti_spam_position', 0);
    
    // multiple list parameters
    $show_select_list = $pluginParams->def('show_select_list', true);
    $fixed_ids = $pluginParams->def('fixed_ids', '');    
    
    // class suffix
    $classSuffix = $pluginParams->def('class_suffix', '');

    // find URL to post.
    if ($fixed_url) {
      $url = $myFixedURL;
    }
    else {
      if (!$exact_url) {
        $url = JURI::current();
      }
      else {
        if (!$disable_https) {
          $url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        }
        else {
          $url = "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
        }
      }
    }
 
    $myError = "";
    $errors = 3;        

    if (isset($_POST["nsp_name"])) {
      $errors = 0; 
      if ($enable_anti_spam) {
        if ($_POST["nsp_anti_spam_answer"] != $myAntiSpamAnswer) {
          $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Wrong anti-spam answer') . '</span><br/>';
        }
      }        
      if ($_POST["nsp_name"] === "") {
        $myError = $myError . '<span style="color: '.$errorTextColor.';">' . $noName . '</span><br/>';
        $errors = $errors + 1;
      }
      if ($_POST["nsp_email"] === "") {
        $myError = $myError. '<span style="color: '.$errorTextColor.';">' . $noEmail . '</span><br/>';
        $errors = $errors + 2;
      }
      if (!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/", $_POST["nsp_email"])) {
        $myError = $myError. '<span style="color: '.$errorTextColor.';">' . $invalidEmail . '</span><br/>';
        $errors = $errors + 2;
      }

      jimport('joomla.application.component.helper');
      $params = JComponentHelper::getParams( 'com_nspro' );

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

      $blackarray = explode(';', $blacklist);
      
      foreach ($blackarray as $black_email) {
        if ($_POST["nsp_email"] == $black_email) {
          $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Your email has been blacklisted.') . '</span><br/>';
          $errors = $errors + 2;    
          break;
        }
      }

      if ($myError == "") {
       
        $confirmSub = $params->get( 'send_confirm', '1');
        $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');
        $messageConfirm = $params->get('message_confirm', 'Thank you for subscribing at {conf_host} .<br/><br/><br/>{conf_link}Click to complete your Subscription{/conflink}<br/><br/>or copy this to your address bar<br/><br/>{conf_url}');
 
        if (!$confirmSub) {
  
          $myMessage = $myNameLabel . ' ' . $_POST["nsp_name"] . ', ' .
                       $myEmailLabel . ' ' . $_POST["nsp_email"] . ', ' .
                       date("r");
          $mailSender = &JFactory::getMailer();
          $mailSender->addRecipient($recipient);
          if ($sendingWithSetEmail) {
            $mailSender->setSender(array($fromEmail,$fromName));
          }
          else {
            $mailSender->setSender(array($_POST["nsp_email"],$_POST["nsp_name"]));
          }
          $mailSender->setSubject($subject);
          $mailSender->setBody($myMessage);
  
          // insert into the database
          $mlists = '';
          if ($_POST["mailing_lists2"]) {
            $myposts = $_POST["mailing_lists2"];
            foreach($myposts as $mpost) {
              if ($mlists == '') {
                $mlists = $mpost;
              }
              else {
                $mlists = $mlists . ',' . $mpost;
              }
            }
          }
          else if ($_POST["mailing_lists"]) {
            $mlists = $_POST["mailing_lists"];
          }  
          
          $query = 'INSERT INTO #__nspro_subs (`NAME`, `EMAIL`, `DATETIME`, `CONFIRMED`, `mailing_lists`) VALUES ("'.$_POST["nsp_name"].'", "'.$_POST["nsp_email"].'", "'.date("Y-m-d H:i:s").'", "1", "'.$mlists.'")';
          $db->setQuery($query);
          if (!$db->query()) {
            $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Email already exists. Please try again') . '</span><br/>';
            $errors = $errors + 2;            
          }
          else {
            if ($mailSender->Send() !== true) {
              $myReplacement = '<span style="color: '.$errorTextColor.';">' . $errorText . '</span>';
              $text = JString::str_ireplace('{newsletter_subscriber_pro}', $myReplacement, $text);
            }
            else {
              $myReplacement = '<span style="color: '.$thanksTextColor.';">' . $pageText . '</span>';
              $text = JString::str_ireplace('{newsletter_subscriber_pro}', $myReplacement, $text);
            }
            if ($saveList) {
              $file = fopen($savePath, "a");
              if ($file !== false) {          
                $mstring = JString::str_ireplace('%n', $_POST["nsp_name"], $saveFormat);
                $mstring = JString::str_ireplace('%e', $_POST["nsp_email"], $mstring); 
                fwrite($file, $mstring);
                fclose($file);
              }
            }
          }
  
          if ($myError == '') {
            return true;
          }
        }
        else {
          $confirm_url = 'index.php?option=com_nspro&amp;view=nspro&amp;layout=confirm&amp;nss=nsplgp';
          $uri = & JURI::getInstance();
          $myBase = JURI::base();
          
          $myConfirmationLink = $myBase.$confirm_url.'&amp;u='.md5($_POST["nsp_email"]);
  
          $myMessage = JString::str_ireplace('{conf_host}', $uri->getHost(), $messageConfirm);
          $myMessage = JString::str_ireplace('{conf_url}', $myConfirmationLink, $myMessage);
      
          $myMessage = JString::str_ireplace('{conf_link}', '<a href="' . $myConfirmationLink . '">', $myMessage);
          $myMessage = JString::str_ireplace('{/conf_link}', '</a>', $myMessage);

          // insert into the database to be able to confirm
          $mlists = '';
          if ($_POST["mailing_lists2"]) {
            $myposts = $_POST["mailing_lists2"];
            foreach($myposts as $mpost) {
              if ($mlists == '') {
                $mlists = $mpost;
              }
              else {
                $mlists = $mlists . ',' . $mpost;
              }
            }
          }
          else if ($_POST["mailing_lists"]) {
            $mlists = $_POST["mailing_lists"];
          }  
  
          $query = 'INSERT INTO #__nspro_subs (`NAME`, `EMAIL`, `DATETIME`, `CONFIRMED`, `mailing_lists`) VALUES ("'.$_POST["nsp_name"].'", "'.$_POST["nsp_email"].'", "'.date("Y-m-d H:i:s").'", "0", "'.$mlists.'")';
          $db->setQuery($query);
          if (!$db->query()) {
            $myError = $myError. '<span style="color: '.$errorTextColor.';">' . JText::_('Email already exists. Please try again') . '</span><br/>';
            $errors = $errors + 2;  
          }
          else {
            if (JUtility::sendMail($fromEmailConfirm, $fromNameConfirm, $_POST["nsp_email"], $subjectConfirm, $myMessage, true) !== true) {
              $myReplacement = '<span style="color: '.$errorTextColor.';">' . JText::_('Your subscription could not be completed') . '</span>';
            }
            else {
              $myReplacement = '<span style="color: '.$thanksTextColor.';">' . JText::_('An email has been sent to you to confirm your subscription') . '</span>';
            }
            $text = JString::str_ireplace('{newsletter_subscriber_pro}', $myReplacement, $text);
            return true;
          }
          
        }
      }
    }

    if ($recipient === "") {
      $myReplacement = '<span style="color: '.$errorTextColor.';">No recipient specified</span>';
      $text = JString::str_ireplace('{newsletter_subscriber_pro}', $myReplacement, $text);
      return true;
    }
    
    if ($recipient === "email@email.com") {
      $myReplacement = '<span style="color: '.$errorTextColor.';">'.JText::_('Mail Recipient is specified as email@email.com.').'<br/>'.JText::_('Please change it from the Plugin parameters.').'</span>';
      $text = JString::str_ireplace('{newsletter_subscriber_pro}', $myReplacement, $text);
      return true;
    }    

    $myReplacement = "";
    
    if ($myError != "") {
      $myReplacement = $myError;
    }    
    
    $myReplacement = $myReplacement . '<div class="nspro' . $classSuffix . '"><form action="' . $url . '" method="post">' . "\n" . 
                                      '<div class="nsprointro' . $mod_class_suffix . '">'.$pre_text.'</div>' . "\n" . 
                                      '<table>' . "\n";
    if ($enable_anti_spam) {
      if ($anti_spam_position == 0) {
        $myReplacement = $myReplacement . '<tr><td colspan="2">' . $myAntiSpamQuestion . '</td></tr><tr><td></td><td><input class="nspro inputbox ' . $classSuffix . '" type="text" name="nsp_anti_spam_answer" size="' . $nameWidth . '"/></td></tr>' . "\n";
      }
    }
    $myReplacement = $myReplacement . '<tr><td>' . $myNameLabel . '</td><td><input class="nspro inputbox' . $classSuffix . '" type="text" name="nsp_name" size="' . $nameWidth . '"';
    if (($errors & 1) != 1) {
      $myReplacement = $myReplacement . ' value="'.$_POST["nsp_name"].'"';
    }  
    $myReplacement = $myReplacement . '/></td></tr>' . "\n";
    $myReplacement = $myReplacement . '<tr><td>' . $myEmailLabel . '</td><td><input class="nspro inputbox' . $classSuffix . '" type="text" name="nsp_email" size="' . $emailWidth . '"';
    if (($errors & 2) != 2) {
      $myReplacement = $myReplacement . ' value="'.$_POST["nsp_email"].'"';
    }  
    $myReplacement = $myReplacement . '/></td></tr>' . "\n";

    if ($show_select_list == 0) {
      $myReplacement = $myReplacement . '<input type="hidden" name="mailing_lists" value="' . $fixed_ids . '"/>';
    }
    else {
      $myReplacement = $myReplacement . '<tr><td colspan="2">' . $mailing_list_label . '</td></tr>';
      $query = 'SELECT * FROM `#__nspro_lists` WHERE `published` = 1 ORDER BY `id`';
      $db->setQuery($query);
      $lists = $db->loadObjectList();
      if ($show_select_list == 1) {
        $fixedlist = explode(',', $fixed_ids);
        foreach($lists as $list) {
          foreach($fixedlist as $fxlid) {
            if ($list->id == $fxlid) {
              $myReplacement = $myReplacement . '<tr><td colspan="2"><input class="nspro inputbox' . $classSuffix . '" type="checkbox" name="mailing_lists2[]" value="' . $list->id . '"/> ' . $list->lname . '</td></tr>';
            }
          }
        }
      }
      else {
        foreach($lists as $list) {
          $myReplacement = $myReplacement . '<tr><td colspan="2"><input class="nspro inputbox' . $classSuffix . '" type="checkbox" name="mailing_lists2[]" value="' . $list->id . '"/> ' . $list->lname . '</td></tr>';
        }
      }
    }    
    
    if ($enable_anti_spam) {
      if ($anti_spam_position == 1) {
        $myReplacement = $myReplacement . '<tr><td colspan="2">' . $myAntiSpamQuestion . '</td></tr><tr><td></td><td><input class="nspro inputbox ' . $classSuffix . '" type="text" name="nsp_anti_spam_answer" size="' . $nameWidth . '"/></td></tr>' . "\n";
      }
    }    
    $myReplacement = $myReplacement . '<tr><td colspan="2"><input class="nspro button' . $classSuffix . '" type="submit" value="' . $buttonText . '" style="width: ' . $buttonWidth . '%;"/></td></tr>' . "\n";
    $myReplacement = $myReplacement . '</table></form></div>' . "\n";
    
    $text = JString::str_ireplace('{newsletter_subscriber_pro}', $myReplacement, $text);


    return true;
  }

}