<?php

/**
* @version 2.8.16
* @package Joomla 2.5
* @subpackage DT Register
* @copyright Copyright (C) 2006 DTH Development
* @copyright contact dthdev@dthdevelopment.com
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
*/

// Make sure we're being called from the command line, not a web interface
if (array_key_exists('REQUEST_METHOD', $_SERVER)) die();


// Set flag that this is a parent file.
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);

error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', 1);
global $mainframe;
class Climainframe {
    
	function isAdmin() {
		 
		 return true;
	}
}

class JApplication 
{
   protected static $instances = array();
   public static function getInstance($client, $config = array(), $prefix = 'J')
	{
		
		return self::$instances[$client];
	}
	
	public function enqueueMessage($msg, $type = 'message')
	{
	
	}
	function isAdmin() {
		 
		 return true;
	}

}

$mainframe = new Climainframe();
chdir(dirname(__FILE__));
// Load system defines
chdir("../../");

if (file_exists(dirname(dirname(dirname(__FILE__))) . '/defines.php'))
{
	require_once dirname(dirname(dirname(__FILE__))) . '/defines.php';
}

if (!defined('_JDEFINES'))
{
	
	define('JPATH_BASE', getcwd());
	require_once JPATH_BASE . '/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
require_once JPATH_BASE.'/includes/application.php';
require_once JPATH_LIBRARIES . '/import.php';
require_once JPATH_LIBRARIES . '/cms.php';

// Force library to be in JError legacy mode
//JError::$legacy = true;

// Load the configuration
require_once JPATH_CONFIGURATION . '/configuration.php';
// Get the framework.
require_once JPATH_LIBRARIES . '/import.php';

// Bootstrap the CMS libraries.
require_once JPATH_LIBRARIES . '/cms.php';

// Force library to be in JError legacy mode
JError::$legacy = true;

// Import necessary classes not handled by the autoloaders
jimport('joomla.application.menu');
jimport('joomla.environment.uri');
jimport('joomla.event.dispatcher');
jimport('joomla.utilities.utility');
jimport('joomla.utilities.arrayhelper');

if (!defined('DTR_COM_COMPONENT')){

	define('DTR_COM_COMPONENT',"com_dtregister");

	define("DTR_COMPONENT",str_replace("com_","",'DT_COM_COMPONENT'));

}
define('JPATH_COMPONENT_ADMINISTRATOR',JPATH_ADMINISTRATOR."/components/com_dtregister");
		
JLoader::register('DtrModel' , JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'lib'.DS.'dtmodel.php');

JLoader::register('DtrModeladmin' , JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'lib'.DS.'dtmodeladmin.php');
JLoader::register('DtrTable' , JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'lib'.DS.'dttable.php');
JLoader::register('DT_Tagparser' , JPATH_SITE.DS.'administrator'.DS.'components'.DS.'com_dtregister'.DS.'lib'.DS.'tagparser.php');
include_once(JPATH_SITE."/administrator/components/com_dtregister/models/user.php");
include_once(JPATH_SITE."/administrator/components/com_dtregister/models/config.php");
include_once(JPATH_SITE."/administrator/components/com_dtregister/models/reminder.php");
include_once(JPATH_SITE."/administrator/components/com_dtregister/models/paymentmethod.php");
include_once(JPATH_SITE."/administrator/components/com_dtregister/models/fieldtype.php");
$config = new DtregisterModelConfig(array());

$config->setGlobal();
jimport('joomla.application.component.helper');
jimport('phpmailer.phpmailer');
class DTmail extends PHPMailer
{
	/**
	 * @var    array  JMail instances container.
	 * @since  11.3
	 */
	protected static $instances = array();

	/**
	 * @var    string  Charset of the message.
	 * @since  11.1
	 */
	public $CharSet = 'utf-8';

	/**
	 * Constructor
	 */
	public function __construct()
	{
		// PHPMailer has an issue using the relative path for its language files
		$this->SetLanguage('joomla', JPATH_PLATFORM . '/phpmailer/language/');
	}

	/**
	 * Returns the global email object, only creating it
	 * if it doesn't already exist.
	 *
	 * NOTE: If you need an instance to use that does not have the global configuration
	 * values, use an id string that is not 'Joomla'.
	 *
	 * @param   string  $id  The id string for the JMail instance [optional]
	 *
	 * @return  JMail  The global JMail object
	 *
	 * @since   11.1
	 */
	public static function getInstance($id = 'Joomla')
	{
		if (empty(self::$instances[$id]))
		{
			self::$instances[$id] = new DTmail;
		}

		return self::$instances[$id];
	}

	/**
	 * Send the mail
	 *
	 * @return  mixed  True if successful, a JError object otherwise
	 *
	 * @since   11.1
	 */
	public function Send()
	{
		if (($this->Mailer == 'mail') && !function_exists('mail'))
		{
			//return JError::raiseNotice(500, JText::_('JLIB_MAIL_FUNCTION_DISABLED'));
		}

		@$result = parent::Send();

		if ($result == false)
		{
			// TODO: Set an appropriate error number
			//$result = JError::raiseNotice(500, JText::_($this->ErrorInfo));
		}

		return $result;
	}

	/**
	 * Set the email sender
	 *
	 * @param   array  $from  email address and Name of sender
	 *                        <code>array([0] => email Address [1] => Name)</code>
	 *
	 * @return  JMail  Returns this object for chaining.
	 *
	 * @since   11.1
	 */
	public function setSender($from)
	{
		if (is_array($from))
		{
			// If $from is an array we assume it has an address and a name
			if (isset($from[2]))
			{
				// If it is an array with entries, use them
				$this->SetFrom(JMailHelper::cleanLine($from[0]), JMailHelper::cleanLine($from[1]), (bool) $from[2]);
			}
			else
			{
				$this->SetFrom(JMailHelper::cleanLine($from[0]), JMailHelper::cleanLine($from[1]));
			}
		}
		elseif (is_string($from))
		{
			// If it is a string we assume it is just the address
			$this->SetFrom(JMailHelper::cleanLine($from));
		}
		else
		{
			// If it is neither, we throw a warning
			JError::raiseWarning(0, JText::sprintf('JLIB_MAIL_INVALID_EMAIL_SENDER', $from));
		}

		return $this;
	}

	/**
	 * Set the email subject
	 *
	 * @param   string  $subject  Subject of the email
	 *
	 * @return  JMail  Returns this object for chaining.
	 *
	 * @since   11.1
	 */
	public function setSubject($subject)
	{
		$this->Subject = JMailHelper::cleanLine($subject);

		return $this;
	}

	/**
	 * Set the email body
	 *
	 * @param   string  $content  Body of the email
	 *
	 * @return  JMail  Returns this object for chaining.
	 *
	 * @since   11.1
	 */
	public function setBody($content)
	{
		/*
		 * Filter the Body
		 * TODO: Check for XSS
		 */
		$this->Body = JMailHelper::cleanText($content);

		return $this;
	}

	/**
	 * Add recipients to the email
	 *
	 * @param   mixed  $recipient  Either a string or array of strings [email address(es)]
	 * @param   mixed  $name       Either a string or array of strings [name(s)]
	 *
	 * @return  JMail  Returns this object for chaining.
	 *
	 * @since   11.1
	 */
	public function addRecipient($recipient, $name = '')
	{
		// If the recipient is an array, add each recipient... otherwise just add the one
		if (is_array($recipient))
		{
			foreach ($recipient as $to)
			{
				$to = JMailHelper::cleanLine($to);
				$this->AddAddress($to);
			}
		}
		else
		{
			$recipient = JMailHelper::cleanLine($recipient);
			$this->AddAddress($recipient);
		}

		return $this;
	}

	/**
	 * Add carbon copy recipients to the email
	 *
	 * @param   mixed  $cc    Either a string or array of strings [email address(es)]
	 * @param   mixed  $name  Either a string or array of strings [name(s)]
	 *
	 * @return  JMail  Returns this object for chaining.
	 *
	 * @since   11.1
	 */
	public function addCC($cc, $name = '')
	{
		// If the carbon copy recipient is an array, add each recipient... otherwise just add the one
		if (isset($cc))
		{
			if (is_array($cc))
			{
				foreach ($cc as $to)
				{
					$to = JMailHelper::cleanLine($to);
					parent::AddCC($to);
				}
			}
			else
			{
				$cc = JMailHelper::cleanLine($cc);
				parent::AddCC($cc);
			}
		}

		return $this;
	}

	/**
	 * Add blind carbon copy recipients to the email
	 *
	 * @param   mixed  $bcc   Either a string or array of strings [email address(es)]
	 * @param   mixed  $name  Either a string or array of strings [name(s)]
	 *
	 * @return  JMail  Returns this object for chaining.
	 *
	 * @since   11.1
	 */
	public function addBCC($bcc, $name = '')
	{
		// If the blind carbon copy recipient is an array, add each recipient... otherwise just add the one
		if (isset($bcc))
		{
			if (is_array($bcc))
			{
				foreach ($bcc as $to)
				{
					$to = JMailHelper::cleanLine($to);
					parent::AddBCC($to);
				}
			}
			else
			{
				$bcc = JMailHelper::cleanLine($bcc);
				parent::AddBCC($bcc);
			}
		}

		return $this;
	}

	/**
	 * Add file attachments to the email
	 *
	 * @param   mixed  $attachment  Either a string or array of strings [filenames]
	 * @param   mixed  $name        Either a string or array of strings [names]
	 * @param   mixed  $encoding    The encoding of the attachment
	 * @param   mixed  $type        The mime type
	 *
	 * @return  JMail  Returns this object for chaining.
	 *
	 * @since   11.1
	 */
	                                  
	public function addAttachment($attachment, $name = '', $encoding = 'base64', $type = 'application/octet-stream',$disposition = 'attachment')
	{
		// If the file attachments is an array, add each file... otherwise just add the one
		if (isset($attachment))
		{
			if (is_array($attachment))
			{
				foreach ($attachment as $file)
				{
					parent::AddAttachment($file, $name, $encoding, $type);
				}
			}
			else
			{
				parent::AddAttachment($attachment, $name, $encoding, $type);
			}
		}

		return $this;
	}

	/**
	 * Add Reply to email address(es) to the email
	 *
	 * @param   array  $replyto  Either an array or multi-array of form
	 *                           <code>array([0] => email Address [1] => Name)</code>
	 * @param   mixed  $name     Either an array or single string
	 *
	 * @return  JMail  Returns this object for chaining.
	 *
	 * @since   11.1
	 */
	public function addReplyTo($replyto, $name = '')
	{
		// Take care of reply email addresses
		if (is_array($replyto[0]))
		{
			foreach ($replyto as $to)
			{
				$to0 = JMailHelper::cleanLine($to[0]);
				$to1 = JMailHelper::cleanLine($to[1]);
				parent::AddReplyTo($to0, $to1);
			}
		}
		else
		{
			$replyto0 = JMailHelper::cleanLine($replyto[0]);
			$replyto1 = JMailHelper::cleanLine($replyto[1]);
			parent::AddReplyTo($replyto0, $replyto1);
		}

		return $this;
	}

	/**
	 * Use sendmail for sending the email
	 *
	 * @param   string  $sendmail  Path to sendmail [optional]
	 *
	 * @return  boolean  True on success
	 *
	 * @since   11.1
	 */
	public function useSendmail($sendmail = null)
	{
		$this->Sendmail = $sendmail;

		if (!empty($this->Sendmail))
		{
			$this->IsSendmail();

			return true;
		}
		else
		{
			$this->IsMail();

			return false;
		}
	}

	/**
	 * Use SMTP for sending the email
	 *
	 * @param   string   $auth    SMTP Authentication [optional]
	 * @param   string   $host    SMTP Host [optional]
	 * @param   string   $user    SMTP Username [optional]
	 * @param   string   $pass    SMTP Password [optional]
	 * @param   string   $secure  Use secure methods
	 * @param   integer  $port    The SMTP port
	 *
	 * @return  boolean  True on success
	 *
	 * @since   11.1
	 */
	public function useSMTP($auth = null, $host = null, $user = null, $pass = null, $secure = null, $port = 25)
	{
		$this->SMTPAuth = $auth;
		$this->Host = $host;
		$this->Username = $user;
		$this->Password = $pass;
		$this->Port = $port;

		if ($secure == 'ssl' || $secure == 'tls')
		{
			$this->SMTPSecure = $secure;
		}

		if (($this->SMTPAuth !== null && $this->Host !== null && $this->Username !== null && $this->Password !== null)
			|| ($this->SMTPAuth === null && $this->Host !== null))
		{
			$this->IsSMTP();

			return true;
		}
		else
		{
			$this->IsMail();

			return false;
		}
	}

	/**
	 * Function to send an email
	 *
	 * @param   string   $from         From email address
	 * @param   string   $fromName     From name
	 * @param   mixed    $recipient    Recipient email address(es)
	 * @param   string   $subject      email subject
	 * @param   string   $body         Message body
	 * @param   boolean  $mode         false = plain text, true = HTML
	 * @param   mixed    $cc           CC email address(es)
	 * @param   mixed    $bcc          BCC email address(es)
	 * @param   mixed    $attachment   Attachment file name(s)
	 * @param   mixed    $replyTo      Reply to email address(es)
	 * @param   mixed    $replyToName  Reply to name(s)
	 *
	 * @return  boolean  True on success
	 *
	 * @since   11.1
	 */
	public function sendMail($from, $fromName, $recipient, $subject, $body, $mode = false, $cc = null, $bcc = null, $attachment = null,
		$replyTo = null, $replyToName = null)
	{
		$this->setSubject($subject);
		$this->setBody($body);

		// Are we sending the email as HTML?
		if ($mode)
		{
			$this->IsHTML(true);
		}

		$this->addRecipient($recipient);
		$this->addCC($cc);
		$this->addBCC($bcc);
		$this->addAttachment($attachment);

		// Take care of reply email addresses
		if (is_array($replyTo))
		{
			$numReplyTo = count($replyTo);

			for ($i = 0; $i < $numReplyTo; $i++)
			{
				$this->addReplyTo(array($replyTo[$i], $replyToName[$i]));
			}
		}
		elseif (isset($replyTo))
		{
			$this->addReplyTo(array($replyTo, $replyToName));
		}

		// Add sender to replyTo only if no replyTo received
		$autoReplyTo = (empty($this->ReplyTo)) ? true : false;
		$this->setSender(array($from, $fromName, $autoReplyTo));

		return $this->Send();
	}

	/**
	 * Sends mail to administrator for approval of a user submission
	 *
	 * @param   string  $adminName   Name of administrator
	 * @param   string  $adminEmail  Email address of administrator
	 * @param   string  $email       [NOT USED TODO: Deprecate?]
	 * @param   string  $type        Type of item to approve
	 * @param   string  $title       Title of item to approve
	 * @param   string  $author      Author of item to approve
	 * @param   string  $url         A URL to included in the mail
	 *
	 * @return  boolean  True on success
	 *
	 * @since   11.1
	 */
	public function sendAdminMail($adminName, $adminEmail, $email, $type, $title, $author, $url = null)
	{
		$subject = JText::sprintf('JLIB_MAIL_USER_SUBMITTED', $type);

		$message = sprintf(JText::_('JLIB_MAIL_MSG_ADMIN'), $adminName, $type, $title, $author, $url, $url, 'administrator', $type);
		$message .= JText::_('JLIB_MAIL_MSG') . "\n";

		$this->addRecipient($adminEmail);
		$this->setSubject($subject);
		$this->setBody($message);

		return $this->Send();
	}
}
 $conf = JFactory::getConfig();
 $smtpauth = ($conf->get('smtpauth') == 0) ? null : 1;
  $smtpuser = $conf->get('smtpuser');
  $smtppass = $conf->get('smtppass');
  $smtphost = $conf->get('smtphost');
  $smtpsecure = $conf->get('smtpsecure');
  $smtpport = $conf->get('smtpport');
  $mailfrom = $conf->get('mailfrom');
  $fromname = $conf->get('fromname');
  $mailer = $conf->get('mailer');

  // Create a JMail object
  $mail = DTmail::getInstance();

  // Set default sender without Reply-to
  $mail->SetFrom(JMailHelper::cleanLine($mailfrom), JMailHelper::cleanLine($fromname), 0);

  // Default mailer is to use PHP's mail function
  switch ($mailer)
  {
	  case 'smtp':
		  $mail->useSMTP($smtpauth, $smtphost, $smtpuser, $smtppass, $smtpsecure, $smtpport);
		  break;

	  case 'sendmail':
		  $mail->IsSendmail();
		  break;

	  default:
		  $mail->IsMail();
		  break;
  }

JFactory::$mailer =  null;


JFactory::$mailer = $mail;
$dt_mail = JFactory::getMailer();

DtrTable::addIncludePath(JPATH_ADMINISTRATOR.DS.'components'.DS.DTR_COM_COMPONENT.DS.'models');
class Updatecron extends JApplicationCli
{
	/**
	 * Entry point for the script
	 *
	 * @return  void
	 *
	 * @since   2.5
	 */
	public function execute()
	{
		
		
		$this->_db = $db = JFactory::getDBO();
	   
		$reminder = & DtrTable::getInstance('Reminder','DtrTable');
		$reminders = $reminder->find();
		foreach($reminders as $reminder) {
			
			$records = $this->get_records($reminder);
			$reminderT = &  DtrTable::getInstance('Reminder','DtrTable');
			$reminderT->load($reminder->id);
			$files = $reminderT->files;
			
			foreach($records as $record) {
				$this->send($record,$reminder->message,$reminder->subject,$reminderT->files);
			}
		}

	}
	
	function send($record,$message="",$subject= "",$files =  array()) {
		global $DT_mailfrom,$DT_fromname,$thanksmsg,$admin_registrationemail,$admin_notification,$subject_admin_registrationemail,$admin_email_from_user;
		global $sendEmailToGroup;
		$event = & DtrTable::getInstance('event','Table');
		$user = & DtrTable::getInstance('Duser','Table');
		$user->load($record->userId);	  
	    $user->TableEvent->load($user->eventId);
		$Tagparser = new DT_Tagparser();
		$groupmsg = $Tagparser->getTagcontent('GROUP_MEMBER',$message);
		
		$memberdata = "";
      
	  if($user->type == 'G'){
	      $memeber_msg = array();
		  foreach($user->members as $member){

			    $message = $Tagparser->parsetags($groupmsg,$member);
				$memeber_msg[] = $message;
				$memberdata .= $message;
				$subject_mem = $Tagparser->parsetags($subject,$member);
	
		  }
		  
		  if($sendEmailToGroup ==1){
			$i = 0;
		  	foreach($user->members as $member){
		  	  $Tagparser->parse_password = true;
			  $usermsg = $Tagparser->replaceTagContent('GROUP_MEMBER',$message,$memeber_msg[$i]);
			  $message = $Tagparser->parsetags($usermsg,$member); 
			  $subject = $Tagparser->parsetags($subject,$member);
			  $attachments = array();
			  if(is_array($user->TableEvent->file) && $this->status != -2){
				  foreach($user->TableEvent->file as $attach){
					  $attachments[] = $attach->path;
				  }
			  }
			   
			   if(isset($member->email) && $member->email != ""  && $sendEmailToGroup ==1 ){
					 echo $member->email."\n";
				    // JUTility::sendMail( $DT_mailfrom, strip_tags(html_entity_decode($DT_fromname)),$member->email,strip_tags(html_entity_decode($subject)),$message,1,null,null,$attachments);
					
					  $DT_mailfrom = strip_tags(html_entity_decode($DT_fromname));
					
	                  $dt_mail = JFactory::getMailer();
					  foreach($attachments as $attachment){
						$dt_mail->addAttachment($attachment);
					  }
					  $dt_mail->addRecipient($member->email);
					  $dt_mail->isHTML(true);
					  $dt_mail->addReplyTo(array($DT_mailfrom, $DT_fromname));
					  $dt_mail->setSender(array($DT_mailfrom, $DT_fromname));
					  $dt_mail->setSubject(strip_tags(html_entity_decode($subject)));
					  $dt_mail->setBody($message);
					  $sent = $dt_mail->Send();

			   }
			  $i++;
		  	}
		  }
		
	  }
	  
	  $Tagparser->parse_password = true;
	  $usermsg = $Tagparser->replaceTagContent('GROUP_MEMBER',$message,$memberdata);
	  $message = $Tagparser->parsetags($usermsg,$user); 
	  
	  $subject = $Tagparser->parsetags($subject,$user);

	  $email = $user->getFieldByName('email');
       
      $attachments = array();
	  if(is_array($files) ){
		  foreach($files as $attach){
			  $attachments[] = $attach['path'];
		  }
	  }
	  
	  $this->out($email);
	   // echo "Subject : ".$subject."\n ";
	   // echo "Message : ".$message."\n ";
	  
	 
	// JUTility::sendMail( $DT_mailfrom, strip_tags(html_entity_decode($DT_fromname)),$email,strip_tags(html_entity_decode($subject)),$message,1,null,null,$attachments);
	           $DT_mailfrom = strip_tags(html_entity_decode($DT_fromname));
					
				$dt_mail = JFactory::getMailer();
				foreach($attachments as $attachment){
				  $dt_mail->addAttachment($attachment);
				}
				$dt_mail->addRecipient($email);
				$dt_mail->isHTML(true);
				$dt_mail->addReplyTo(array($DT_mailfrom, $DT_fromname));
				$dt_mail->setSender(array($DT_mailfrom, $DT_fromname));
				$dt_mail->setSubject(strip_tags(html_entity_decode($subject)));
				$dt_mail->setBody($message);
				
				//print_r($dt_mail);die;
				$sent = $dt_mail->Send();		
		
	}
	
	function get_records($reminder = 0) {
		
		if($reminder->timer == 0){
			$timer = $reminder->timer + 1;
		} else {
		    $timer = $reminder->timer;
		}
		$condition = "";
		if($reminder->eventId) {
			$condition =  " and e.slabId = '".$reminder->eventId."'";
		}
		 $query = "SELECT u.userId
FROM #__dtregister_user u
  INNER JOIN #__dtregister_group_event e
    ON e.slabId = u.eventId
    WHERE  DATEDIFF(e.dtstart,NOW()) = $timer and u.status in (0,1) ".$condition; // DATEDIFF(e.dtstart,NOW()) = $timer and
	    $this->_db->setQuery($query);
		//echo $this->_db->getQuery()."\n";
		$records = $this->_db->loadObjectList();
		return $records;
	}
}

JApplicationCli::getInstance('Updatecron')->execute();
