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

$db =& JFactory::getDBO();

// email parameters
$recipient = $params->get('email_recipient', 'email@email.com');
$subject = $params->get('subject', 'New subscription to your site!');
$fromName = $params->get('from_name', 'Newsletter Subscriber');
$fromEmail = $params->get('from_email', 'newsletter_subscriber@yoursite.com');
$sendingWithSetEmail = $params->get('sending_from_set', true);

// text parameters
$myNameLabel = $params->get('name_label', 'Name:');
$myEmailLabel = $params->get('email_label', 'Email:');
$mailing_list_label = $params->get('mailing_list_label', 'Mailing Lists:');
$buttonText = $params->get('button_text', 'Subscribe to Newsletter');
$pageText = $params->get('page_text', 'Thank you for subscribing to our site.');
$errorText = $params->get('errot_text', 'Your subscription could not be submitted. Please try again.');
$noName = $params->get('no_name', 'Please write your name');
$noEmail = $params->get('no_email', 'Please write your email');
$invalidEmail = $params->get('invalid_email', 'Please write a valid email');
$pre_text = $params->get('pre_text', '');

// size & color parameters
$nameWidth = $params->get('name_width', '20');
$emailWidth = $params->get('email_width', '20');
$buttonWidth = $params->get('button_width', '100');
$thanksTextColor = $params->get('thank_text_color', '#FF0000');
$errorTextColor = $params->get('error_text_color', '#FF0000');

// file parameters
$saveList = $params->get('save_list', true);
$savePath = $params->get('save_path', 'mailing_list.txt');
$saveFormat = $params->get('save_format', '%n (%e);');

// url parameters
$exact_url = $params->get('exact_url', true);
$disable_https = $params->get('disable_https', false);
$fixed_url = $params->get('fixed_url', true);
$myFixedURL = $params->get('fixed_url_address', "");

// anti spam parameters
$enable_anti_spam = $params->get('enable_anti_spam', true);
$myAntiSpamQuestion = $params->get('anti_spam_q', 'How many eyes has a typical person? (ex: 1)');
$myAntiSpamAnswer = $params->get('anti_spam_a', '2');
$anti_spam_position = $params->get('anti_spam_position', 0);

// multiple list parameters
$show_select_list = $params->get('show_select_list', 2);
$fixed_ids = $params->get('fixed_ids', '');

// module class suffix
$mod_class_suffix = $params->get('moduleclass_sfx', '');

// 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["mp_name"])) {
  $errors = 0;
  if ($enable_anti_spam) {
    if ($_POST["modnsp_anti_spam_answer"] != $myAntiSpamAnswer) {
      $myError = '<span style="color: '.$errorTextColor.';">' . JText::_('Wrong anti-spam answer') . '</span><br/>';
    }
  }
  if ($_POST["mp_name"] === "") {
    $myError = $myError . '<span style="color: '.$errorTextColor.';">' . $noName . '</span><br/>';
    $errors = $errors + 1;
  }
  if ($_POST["mp_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["mp_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["mp_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{/conf_link}<br/><br/>or copy this to your address bar<br/><br/>{conf_url}');
        
    // if we don't use the confirmation process    
    if (!$confirmSub) {
      $myMessage = $myNameLabel . ' ' . $_POST["mp_name"] . ', ' .
                   $myEmailLabel . ' ' . $_POST["mp_email"] . ', ' .
                   date("r");
      $mailSender = &JFactory::getMailer();
      $mailSender->addRecipient($recipient);
      if ($sendingWithSetEmail) {
        $mailSender->setSender(array($fromEmail,$fromName));
      }
      else {
        $mailSender->setSender(array($_POST["mp_email"],$_POST["mp_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["mp_name"].'", "'.$_POST["mp_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 inserted, send the mail
        if ($mailSender->Send() !== true) {
          $myReplacement = '<span style="color: '.$errorTextColor.';">' . $errorText . '</span>';
          print $myReplacement;
        }
        else {
          $myReplacement = '<span style="color: '.$thanksTextColor.';">' . $pageText . '</span>';
          print $myReplacement;
        }
        // save to the global list file
        if ($saveList) {          
          $file = fopen($savePath, "a");
          if ($file !== false) {          
            $mstring = JString::str_ireplace('%n', $_POST["mp_name"], $saveFormat);
            $mstring = JString::str_ireplace('%e', $_POST["mp_email"], $mstring); 
            fwrite($file, $mstring);
            fclose($file);
          }
        }
      }
      
      if ($myError == '') {
        return true;
      }
    } // if we use the confirmation process 
    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["mp_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["mp_name"].'", "'.$_POST["mp_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["mp_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>';
        }
        print $myReplacement;
      }

      if ($myError == '') {
        return true;
      }
    }
  }
}


if ($recipient === "") {
  $myReplacement = '<span style="color: '.$errorTextColor.';">'.JText::_('No recipient specified').'</span>';
  print $myReplacement;
  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 Module parameters.').'</span>';
  print $myReplacement;
  return true;
}

if ($myError != "") {
  print $myError;
}

print '<div class="modnspro' . $mod_class_suffix . '"><form action="' . $url . '" method="post">' . "\n".
      '<div class="modnsprointro' . $mod_class_suffix . '">'.$pre_text.'</div>' . "\n";
print '<table>';
if ($enable_anti_spam) {
  if ($anti_spam_position == 0) {
    print '<tr><td colspan="2">' . $myAntiSpamQuestion . '</td></tr><tr><td></td><td><input class="modnspro inputbox ' . $mod_class_suffix . '" type="text" name="modnsp_anti_spam_answer" size="' . $nameWidth . '"/></td></tr>' . "\n";
  }
}
print '<tr><td>' . $myNameLabel . '</td><td><input class="modnspro inputbox' . $mod_class_suffix . '" type="text" name="mp_name" size="' . $nameWidth . '"';
if (($errors & 1) != 1) {
  print ' value="'.$_POST["mp_name"].'"';
}
print '/></td></tr>' . "\n";
print '<tr><td>' . $myEmailLabel . '</td><td><input class="modnspro inputbox' . $mod_class_suffix . '" type="text" name="mp_email" size="' . $emailWidth . '"';
if (($errors & 2) != 2) {
  print ' value="'.$_POST["mp_email"].'"';
}
print '/></td></tr>' . "\n";

if ($show_select_list == 0) {
  print '<input type="hidden" name="mailing_lists" value="' . $fixed_ids . '"/>';
}
else {
  print '<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) {
          print '<tr><td colspan="2"><input class="modnspro inputbox' . $mod_class_suffix . '" type="checkbox" name="mailing_lists2[]" value="' . $list->id . '"/> ' . $list->lname . '</td></tr>';
        }
      }
    }
  }
  else {
    foreach($lists as $list) {
      print '<tr><td colspan="2"><input class="modnspro inputbox' . $mod_class_suffix . '" type="checkbox" name="mailing_lists2[]" value="' . $list->id . '"/> ' . $list->lname . '</td></tr>';
    }
  }
}

if ($enable_anti_spam) {
  if ($anti_spam_position == 1) {
    print '<tr><td colspan="2">' . $myAntiSpamQuestion . '</td></tr><tr><td></td><td><input class="modnspro inputbox ' . $mod_class_suffix . '" type="text" name="modnsp_anti_spam_answer" size="' . $nameWidth . '"/></td></tr>' . "\n";
  }
}
print '<tr><td colspan="2"><input class="modnspro button' . $mod_class_suffix . '" type="submit" value="' . $buttonText . '" style="width: ' . $buttonWidth . '%"/></td></tr></table></form></div>' . "\n";
return true;
