<?php
/*
 * This file is part of the easy-CMS project.
 * easy-CMS is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * easy-CMS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with easy-CMS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
 

include_once('config.inc.php');
include_once('classes/system/Mail.class.php');
include_once('classes/core/Site.class.php');

include_once('mailing/langs/langs.inc.php');


/**
 * default language
 **/

$lang = LANG_FR;

$site = &Site::getInstance();
$dbManipulator = &$site->getDBManipulator();


if(isset($_POST["lg"])){
  $_POST["lang"] = $_POST["lg"];
}

if(isset($_POST["lg_id"])){
  $_POST["lang_id"] = $_POST["lg_id"];
}


if(isset($_POST["lang"]) || isset($_GET["lang"])) {
	if(isset($_POST["lang"])) {
		$lang = $_POST["lang"];
	}
	else {
		$lang = $_GET["lang"];
	}
	switch($langId) {
		case LANG_EN:
			$langId = 1;
			break;
		case LANG_FR:
			$langId = 2;
			break;
		case LANG_NL:
			$langId = 3;
			break;
	}
}
else {
  if(isset($_POST["lang_id"]) || isset($_GET["lang_id"])) {
  	if(isset($_POST["lang_id"])) {
			$langId = $_POST["lang_id"];
		}
		else {
			$langId = $_GET["lang_id"];
		}
	}
	switch($langId) {
		case 1:
			$lang = LANG_EN;
			break;
		case 2:
			$lang = LANG_FR;
			break;
		case 3:
			$lang = LANG_NL;
			break;
	}
}

$mlId = 1;

if(isset($_POST["ml_id"]) || isset($_GET["ml_id"])) {
	if(isset($_POST["ml_id"])) {
		$mlId = $_POST["ml_id"];
	}
	else {
		$mlId = $_GET["ml_id"];
	}
}

$selectionListHtml = "";

$query = "SELECT * FROM `easy_cms_content_type_mailing_list` WHERE `lang_id` = '1';";
$result = $dbManipulator->sendQuery($query);

while($row = $dbManipulator->fetchArray($result)){
	$selected = "";
	if($mlId == $row['id']) {
		$selected = "selected=\"selected\"";
	}
	$selectionListHtml .= "<option value=\"".$row['id']."\" $selected>".$row['name']."</option>";
}

if(!isset($emlmTranslationsFiles[$lang])) {
	$lang = LANG_EN;
	$langId = 1;
}

include_once('mailing/langs/'.$emlmTranslationsFiles[$lang]);




define('SUBSCRIBED', 					1);
define('ALREADY_SUBSCRIBED', 	2);
define('CONFIRM_SUBSCRIBE', 	3);
define('CONFIRM_UNSUBSCRIBE', 4);
define('UNSUBSCRIBED', 				5);

/*
POST array variables :
$_POST["mid"]
$_POST["first"]
$_POST["last"]
$_POST["gender"]
$_POST["address"]
$_POST["lang"]
$_POST["country"]
$_POST["organisation"]
$_POST["position"]
$_POST["about"]
*/

/* sample confirm subscribe link : http://www.shift-zone.be/mlm/easy-mlm.php?mid=4&action=confirm_subscribe&code=332b3ad46c1783cf6785e8c34a76e656&lang=english*/
/* sample unsubscribe link : http://www.shift-zone.be/mlm/easy-mlm.php?action=unsubscribe&address=cedric@shift-zone.be*/
/* sample confirm unsubscribe link : http://www.shift-zone.be/mlm/easy-mlm.php?mid=4&action=confirm_unsubscribe&code=332b3ad46c1783cf6785e8c34a76e656*/

/*
SQL table schema :
CREATE TABLE easy_mlm (
  id int(11) NOT NULL auto_increment,
  list_id int(11) NOT NULL default '1',
  first_name varchar(255) NOT NULL default '',
  last_name varchar(255) NOT NULL default '',
  email varchar(255) NOT NULL default '',
  send tinyint(4) NOT NULL default '0',
  remove tinyint(4) NOT NULL default '0',
  `code` varchar(32) NOT NULL default '',
  gender char(1) NOT NULL default '',
  position varchar(255) NOT NULL,
  about varchar(255) NOT NULL,
  lang varchar(50) NOT NULL default '',
  country varchar(50) NOT NULL default '',
  organisation varchar(50) NOT NULL default '',
  PRIMARY KEY  (id)
);
*/


function formatValue($value) {
	return Node::convertUTFStringToASCII($value);
}


$MaxSize['firstName'] = 45;
$MaxSize['lastName'] 	= 45;
$MaxSize['eMail'] 		= 128;

$errorMessages[0] = LANG_EMLM_NO_EMAIL."<br />\n";
$errorMessages[1] = LANG_EMLM_EMAIL_TOO_LONG."<br />\n";
$errorMessages[2] = LANG_EMLM_FIRSTNAME_TOO_LONG."<br />\n";
$errorMessages[3] = LANG_EMLM_LASTNAME_TOO_LONG."<br />\n";
$errorMessages[4] = LANG_EMLM_INVALID_EMAIL."<br />\n";
$errorMessages[5] = LANG_EMLM_EMAIL_NOT_IN_DB."<br />\n";
$errorMessages[6] = LANG_EMLM_EMAIL_ALREADY_IN_DB."<br />\n";
$errorMessages[7] = LANG_EMLM_NO_FIRSTNAME."<br />\n";
$errorMessages[8] = LANG_EMLM_NO_LASTNAME."<br />\n";


$state 				= 0;
$errors 			= "";

$firstName 		= "";
$lastName 		= "";
$eMailAddress = "";

if(isset($_POST["action"]) || isset($_GET["action"])) {

	if(isset($_POST["action"])) {
    $action = $_POST["action"];
  }
  else {
    $action = $_GET["action"];
  }
	if(isset($_GET["mid"])) {
    $mid = $_GET["mid"];
  }

 	if(isset($_GET["code"])) {
    $code = $_GET["code"];
  }

	switch($action) {
		case "confirm_subscribe":
			if(isset($mid) && isset($code)) {
				if(is_numeric($mid)) {
					// check if the mid address is in the database
	    		$query = "select * from `easy_mlm` where `id` = '$mid';";
	    		$result = $dbManipulator->sendQuery($query);
          if(!($row = $dbManipulator->fetchArray($result))) {
            //$errors .= $errorMessages[5];
            //hack attempt !
            break;
          }
          else {
            if($row["code"] != $code) {
              //hack attempt !
              break;
            }
            //check the send bit and the hash code
            if($row["send"] == "0") {
/**
*
* adding to the mailing list
*
*/
	        		$query = "insert into `easy_cms_content_type_mailing_subscriber` ( `id` , `lang_id` , `acl_id` , `published` , `deleted` , `mailing_list_id`, `firstname` , `lastname` , `email` ) value ('$mid', '1', '1', '1', '0', '".$row['list_id']."', '".$row['first_name']."', '".$row['last_name']."', '".$row['email']."');";
	        		$dbManipulator->sendQuery($query);

	        		//set the bit for sending e-mails
	        		$query = "update `easy_mlm` set `send` = '1' WHERE `id` = '$mid';";
	        		$dbManipulator->sendQuery($query);
							$state = SUBSCRIBED;
            }
            else {
               $state = ALREADY_SUBSCRIBED;
            }
          }
			  }
			}
			break;
		case "confirm_unsubscribe":
			if(isset($mid) && isset($code)) {
				if(is_numeric($mid)) {
					// check if the mid address is in the database
	    		$query = "select * from `easy_mlm` where `id` = '$mid';";
	    		$result = $dbManipulator->sendQuery($query);
          if(!($row = $dbManipulator->fetchArray($result))) {
            //$errors .= $errorMessages[5];
            //hack attempt !
            break;
          }
          else {
            // test the hashcode
            if($row["code"] != $code) {
              //url error or hack attempt !
              break;
            }
            // test the removal bit
            if($row["remove"] == "1") {
/**
*
* removing from the mailing list
*
*/
	        		//delete the subscriber object
	        		$query = "update `easy_cms_content_type_mailing_subscriber` set `deleted` = '1' where `id` = '$mid';";
	        		$dbManipulator->sendQuery($query);

              // remove the record from the database
              $query = "delete from `easy_mlm` WHERE `id` = '$mid';";
              $dbManipulator->sendQuery($query);
              $state = UNSUBSCRIBED;
            }
          }
        }
			}
			break;
		case "subscribe":
			if(strlen($_POST["first"]) < 1) {
				$errors .= $errorMessages[7];
			}
			if(strlen($_POST["last"]) < 1) {
				$errors .= $errorMessages[8];
			}

 			if(isset($_POST["first"]) && strlen($_POST["first"]) > $MaxSize['firstName']) {
 				$errors .= $errorMessages[2];
 			}

 			if(isset($_POST["last"]) && strlen($_POST["last"]) > $MaxSize['lastName']) {
 				$errors .= $errorMessages[3];
 			}

	   	if(isset($_POST["gender"]) && strlen($_POST["gender"]) > 0) {
 				$gender = $_POST["gender"];
 			}
 			else {
 				$errors .= $errorMessages[9];
 			}

			$firstName = ucfirst(formatValue($_POST["first"]));
			$lastName = ucfirst(formatValue($_POST["last"]));
			$position = $_POST["position"];
			$organisation = $_POST["organisation"];
			$country = $_POST["country"];

			if(isset($_POST["address"]) && strlen($_POST["address"]) > 0) {
				$eMailAddress = formatValue($_POST["address"]);
				$eMailAddress = strtolower($eMailAddress);

				if(strlen($_POST["address"]) > $MaxSize['eMail']) {
					$errors .= $errorMessages[1];
				}
				if(!Mail::isValidMail($_POST["address"])){
					$errors .= $errorMessages[4];
				}

				if(strlen($errors) > 0) {
					break;
				}

				// check if the e-mail address is already in the database
				$query = "select * from `easy_mlm` where `list_id` = '$mlId' and `email` like '$eMailAddress';";
				$result = $dbManipulator->sendQuery($query);
        if($row = $dbManipulator->fetchArray($result)) {
          $mid = $row["id"];
          $code = $row["code"];
          if($row["send"] == "1") {
            $errors .= $errorMessages[6];
            break;
        	}
     		}
     		else {
       		// add infos into DB
       		$code = md5(uniqid(rand()));
			  	$query = "insert into `easy_mlm` (`id` , `list_id`, `first_name` , `last_name` , `email` , `send`, `remove`, `code`, `gender`, `position`, `about`, `lang`, `country`, `organisation`) VALUES ('', '$mlId', '$firstName', '$lastName', '$eMailAddress', '0', '0', '$code', '$gender', '$position', '$about', '$lang', '$country', '$organisation');";
			  	$dbManipulator->sendQuery($query);
          $mid = $dbManipulator->getLastId();
				}

				// send subscription confirmation mail
				$langConfirmSubject = LANG_EMLM_CONFIRM_SUBSCRIBE_SUBJECT;
				$langConfirmSubject = str_replace("__%ORG_NAME%__", ORG_NAME, $langConfirmSubject);

				$langConfirmMessage = LANG_EMLM_CONFIRM_SUBSCRIBE_MESSAGE;
				$langConfirmMessage = str_replace("__%FIRSTNAME%__", $firstName, $langConfirmMessage);
				$langConfirmMessage = str_replace("__%LASTNAME%__", $lastName, $langConfirmMessage);
				$langConfirmMessage = str_replace("__%ORG_URL%__", ORG_URL, $langConfirmMessage);
				$langConfirmMessage = str_replace("__%ORG_MLM_ROOT_URL%__", ORG_MLM_ROOT_URL, $langConfirmMessage);
				$langConfirmMessage = str_replace("__%MID%__", $mid, $langConfirmMessage);
				$langConfirmMessage = str_replace("__%CODE%__", $code, $langConfirmMessage);
				$langConfirmMessage = str_replace("__%LANG%__", $lang, $langConfirmMessage);
				$langConfirmMessage = str_replace("__%ORG_ABUSE%__", ORG_ABUSE, $langConfirmMessage);
				$langConfirmMessage = str_replace("__%ORG_SIG%__", ORG_SIG, $langConfirmMessage);


				$mail = &new Mail($langConfirmSubject, $langConfirmMessage);
				$mail->setSenderMail(ORG_MAIL);
				$mail->setSenderFirstname(ORG_NAME);
				$mail->addRecipientTO($eMailAddress);
				$mail->send();
				//sendMail(ORG_MAIL, $eMailAddress, $langConfirmSubject, $langConfirmMessage, ORG_NAME);
				$state = CONFIRM_SUBSCRIBE;
			}
			else {
				$errors .= $errorMessages[0];
			}
			break;
		case "unsubscribe":
			if(isset($_POST["address"]) || isset($_GET["address"])) {
				if(!isset($_POST["address"])) {
					$_POST["address"] = $_GET["address"];
				}
				if(strlen($_POST["address"]) > $MaxSize['eMail']) {
					$errors .= $errorMessages[1];
				}

				if(!Mail::isValidMail($_POST["address"])){
					$errors .= $errorMessages[4];
					break;
				}

				$eMailAddress = strtolower($_POST["address"]);

				$query = "select * from `easy_mlm` where `list_id` = '$mlId' and `email` like '$eMailAddress';";
				$result = $dbManipulator->sendQuery($query);

				if(!($row = $dbManipulator->fetchArray($result))){
					$errors .= $errorMessages[5];
				}
				else {
					$firstName = $row["first_name"];
					$lastName = $row["last_name"];
					$eMailAddress = $row["email"];
					$mid = $row["id"];
					$code = $row["code"];

					$lang =  $row["lang"];

       		//set the bit for removing record
  				$query = "update `easy_mlm` set `remove` = '1' WHERE `id` = '$mid';";
  				$dbManipulator->sendQuery($query);

					// send unsubscription confirmation mail

					$langConfirmSubject = LANG_EMLM_CONFIRM_UNSUBSCRIBE_SUBJECT;
					$langConfirmSubject = str_replace("__%ORG_NAME%__", ORG_NAME, $langConfirmSubject);

					$langConfirmMessage = LANG_EMLM_CONFIRM_UNSUBSCRIBE_MESSAGE;
					$langConfirmMessage = str_replace("__%FIRSTNAME%__", $firstName, $langConfirmMessage);
					$langConfirmMessage = str_replace("__%LASTNAME%__", $lastName, $langConfirmMessage);
					$langConfirmMessage = str_replace("__%ORG_MLM_ROOT_URL%__", ORG_MLM_ROOT_URL, $langConfirmMessage);
					$langConfirmMessage = str_replace("__%ORG_URL%__", ORG_URL, $langConfirmMessage);
					$langConfirmMessage = str_replace("__%MID%__", $mid, $langConfirmMessage);
					$langConfirmMessage = str_replace("__%CODE%__", $code, $langConfirmMessage);
					$langConfirmMessage = str_replace("__%LANG%__", $lang, $langConfirmMessage);
					$langConfirmMessage = str_replace("__%ORG_ABUSE%__", ORG_ABUSE, $langConfirmMessage);
					$langConfirmMessage = str_replace("__%ORG_SIG%__", ORG_SIG, $langConfirmMessage);

					$mail = &new Mail($langConfirmSubject, $langConfirmMessage);
					$mail->setSenderMail(ORG_MAIL);
					$mail->addRecipientTO($eMailAddress, ORG_NAME);
					$mail->send();
					//sendMail(ORG_MAIL, $eMailAddress, $langConfirmSubject, $langConfirmMessage, ORG_NAME);
					$state = CONFIRM_UNSUBSCRIBE;
				}
			}
			break;
		default:
			break;
	}
}
$htmlContentPart = "";


switch($state) {
	case SUBSCRIBED :
		$htmlContentPart = LANG_EMLM_SUBSCRIBED_NOTICE;
		break;
	case UNSUBSCRIBED :
		$htmlContentPart = LANG_EMLM_UNSUBSCRIBED_NOTICE;
		$htmlContentPart = str_replace("__%ORG_NAME%__", ORG_NAME, $htmlContentPart);
		break;
	case ALREADY_SUBSCRIBED :
		$htmlContentPart = LANG_EMLM_ALREADY_SUBSCRIBED_NOTICE;
		break;
	case CONFIRM_SUBSCRIBE :
		$htmlContentPart = LANG_EMLM_CONFIRM_SUBSCRIBE_NOTICE;
		break;
	case CONFIRM_UNSUBSCRIBE :
		$htmlContentPart = LANG_EMLM_CONFIRM_UNSUBSCRIBE_NOTICE;
		break;
}

$htmlOutput = file_get_contents(ORG_TEMPLATE_URL);
$htmlForm   = file_get_contents(ORG_FORM_URL);

if($state == 0) {
	$htmlForm = str_replace("__%MAILING_LIST_SELECTION%__", $selectionListHtml, $htmlForm);
	$htmlForm = str_replace("__%FIRSTNAME_LABEL%__", LANG_EMLM_FIRSTNAME_LABEL, $htmlForm);
	$htmlForm = str_replace("__%LASTNAME_LABEL%__", LANG_EMLM_LASTNAME_LABEL, $htmlForm);
	$htmlForm = str_replace("__%EMAIL_LABEL%__", LANG_EMLM_EMAIL_LABEL, $htmlForm);
	$htmlForm = str_replace("__%MAILING_LIST_LABEL%__", LANG_EMLM_MAILING_LIST_LABEL, $htmlForm);
	$htmlForm = str_replace("__%VALIDATE_BUTTON_LABEL%__", LANG_EMLM_VALIDATE_BUTTON_LABEL, $htmlForm);
	$htmlForm = str_replace("__%FIRSTNAME%__", $firstName, $htmlForm);
	$htmlForm = str_replace("__%LASTNAME%__", $lastName, $htmlForm);
	$htmlForm = str_replace("__%EMAIL%__", $eMailAddress, $htmlForm);
	$htmlForm = str_replace("__%POSITION%__", $position, $htmlForm);
	$htmlForm = str_replace("__%ORGANISATION%__", $organisation, $htmlForm);
	$htmlForm = str_replace("__%COUNTRY%__", $country, $htmlForm);
	$htmlForm = str_replace("__%LANG_LEGAL_NOTICE%__", LANG_EMLM_LEGAL_NOTICE, $htmlForm);
	$htmlOutput = str_replace("__%CONTENT%__", $htmlForm, $htmlOutput);
}
else {
	$htmlOutput = str_replace("__%CONTENT%__", $htmlContentPart, $htmlOutput);
}

$langNewsletterNotice = LANG_EMLM_NEWSLETTER_NOTICE;
$langNewsletterNotice = str_replace("__%ORG_MAIL%__", ORG_MAIL, $langNewsletterNotice);


$htmlOutput = str_replace("__%ORG_LOGO%__", ORG_LOGO, $htmlOutput);
$htmlOutput = str_replace("__%ORG_URL%__", ORG_URL, $htmlOutput);
$htmlOutput = str_replace("__%NEWSLETTER_NOTICE%__", $langNewsletterNotice, $htmlOutput);
$htmlOutput = str_replace("__%LANG_FORM_TITLE%__", LANG_EMLM_FORM_TITLE, $htmlOutput);
$htmlOutput = str_replace("__%ERRORS%__", $errors, $htmlOutput);

print($htmlOutput);
?>