<?php
/**
 * This file is for forum reminder
 *
 * This file is having forumReminderFormHandler class for forum reminder
 *
 * PHP version 5.0
 *
 * @category	Anova
 * @package		Admin
 * @author 		sridhar_68ag07
 * @copyright 	Copyright (c) 2009 {@link http://www.agriya.com Agriya Infoway}
 * @license		http://www.agriya.com Agriya Infoway Licence
 * @version		SVN: $Id: $
 * @since 		2008-12-26
 *
 **/
require_once('../common/configs/config.inc.php');
$CFG['mods']['include_files'][] = 'common/classes/swiftmailer/lib/EasySwift.php';
$CFG['lang']['include_files'][] =	'languages/%s/common/email_notify.inc.php';

//compulsory
$CFG['mods']['is_include_only']['html_header'] = false;
$CFG['html']['is_use_header'] = false;
/**
 * To include various types of files
 */
require($CFG['site']['project_path'].'common/application_top.inc.php');

set_time_limit(0);
class ForumReminderFormHandler extends FormHandler
	{
		 public function getCronMasterDetails($table_name, $cron_for)
			{
				$sql = 'SELECT upto_id FROM '.$table_name.
						' WHERE cron_for = '.$this->dbObj->Param($cron_for).' AND status = \'Started\' limit 0,1';

				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($cron_for));
				if (!$rs)
						trigger_db_error($this->dbObj);

				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
						return $row;
					}

				return false;
			}

		public function updateCronMaster($table_name, $cron_for, $status, $new_old, $upto=0, $total = 0)
			{
				$val_arr = array();
				$val_arr[] = $status;

				$sql = 'UPDATE '.$table_name .
						' SET '.
						'status='.$this->dbObj->Param($status);

				$sql .= ', upto_id = '.$this->dbObj->Param($upto);
				$val_arr[] = $upto;

				if ($total == 0)
					$sql .= ', total = '.$this->dbObj->Param($total);
					else
						$sql .= ', total = total + '.$this->dbObj->Param($total);
				$val_arr[] = $total;

				if ($new_old == 'new')
					{
						$sql .= ', start_time = '.$this->dbObj->SQLDate('Y-m-d H:i:s');
						$sql .= ', tot_finished_crons = tot_finished_crons + 1';
					}
				$sql .= ' WHERE cron_for = '.$this->dbObj->Param($cron_for);
				$val_arr[] = $cron_for;

				$stmt = $this->dbObj->Prepare($sql);
				$result = $this->dbObj->Execute($stmt, $val_arr);
				if (!$result)
						trigger_db_error($this->dbObj);
			}

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function emailForumDetails($upto_id, $check_count)
		    {
				$sql = 'SELECT max( response_id ) as response , topic_id , email_sent FROM '.$this->CFG['db']['tbl']['forum_response'].
					   ' WHERE email_sent <> \'Yes\' GROUP BY topic_id'.
					   ' ORDER BY response ASC LIMIT 0, 1';

				$stmt = $this->dbObj->Prepare($sql);
				$rsques = $this->dbObj->Execute($stmt);
				if (!$rsques)
				        trigger_db_error($this->dbObj);

				if ($rsques->PO_RecordCount())
					{

						$rowforum = $rsques->FetchRow();
						$sql = 'SELECT user_id FROM '.$this->CFG['db']['tbl']['user_bookmarked'].
								   ' WHERE user_id > '.$this->dbObj->Param($upto_id).
								   ' AND content_id = '.$rowforum['topic_id'].
								   ' AND content_type = \'Forum\''.
								   ' ORDER BY user_id ASC limit 0, '.$this->dbObj->Param($check_count);
						$stmt = $this->dbObj->Prepare($sql);
						$rsusersbookmark = $this->dbObj->Execute($stmt,array($upto_id, $check_count));
						if (!$rsusersbookmark)
						        trigger_db_error($this->dbObj);

						if ($count = $rsusersbookmark->PO_RecordCount())
								{

									$forum_id = $this->getForumTopicDetails($this->CFG['db']['tbl']['forum_topics'], $this->CFG['db']['tbl']['forums'], $rowforum['topic_id']);
									$admin_id = $this->getAdminUserId($this->CFG['db']['tbl']['users']);
									while($rowsusersbookmark = $rsusersbookmark->FetchRow()){

										$ret_arr = array('user_id'=>$rowsusersbookmark['user_id'],'count'=>$count);

										$reminder_subject = $this->LANG['forum_subscribed_email_subject'];
										$reminder_content = $this->LANG['forum_subscribed_email_content'];
										$send_email = true;


										if (!$send_email) continue;

										$receiver_details = $this->getUserDetailsFromUsersTable($this->CFG['db']['tbl']['users'], $rowsusersbookmark['user_id']);
										$reminder_subject = str_ireplace('VAR_USERNAME', $receiver_details['display_name'], $reminder_subject);

										$reminder_content = str_ireplace('VAR_USERNAME', $receiver_details['display_name'], $reminder_content);
										$reminder_content = str_ireplace('VAR_SITENAME', $this->CFG['site']['name'], $reminder_content);
										$reminder_content = str_ireplace('VAR_TOPIC_OF_FORUM', '<strong>'.$forum_id[1].'</strong>', $reminder_content);
										$question_link = getUrl('forumsresponses', '?title='.$forum_id[0].'&amp;topic_title='.$forum_id[1].'&amp;task=1', $forum_id[0].'/'.$forum_id[1].'/?task=1','root');
										$reminder_content = str_ireplace('VAR_LINK', '<a href="'.$question_link.'">'.$question_link.'</a>', $reminder_content);
										$this->_sendMail($receiver_details['email'],
														 $reminder_subject,
														 $reminder_content,
														 $this->CFG['site']['noreply_name'],
														 $this->CFG['site']['noreply_email']);

									}
								return $ret_arr;
								}
						 // while
					$this->updateForumResponseTableEmailSentStatus($rowforum['topic_id']);
					}
				return false;
		    }

		/**
		 * To send email
		 *
		 * @param 		string $to_email to email id
		 * @param 		string $subject subject
		 * @param		string $body mail body
		 * @param 		string $sender_name sender name
		 * @param 		string $sender_email sender email
		 * @return 		void
		 * @access 		private
		 */
		private function _sendMail($to_email, $subject, $body, $sender_name, $sender_email)
		{

				$this->buildEmailTemplate($subject, $body, false, true);
				$EasySwift = new EasySwift($this->getSwiftConnection());
				$EasySwift->flush();
				$EasySwift->addPart($this->getEmailContent(), "text/html");
				$from_address = $sender_name.'<'.$sender_email.'>';
				return $EasySwift->send($to_email, $from_address, $this->getEmailSubject());
			}


		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function getForumTopicDetails($table,$forum_table,$topic_field)
		    {
				$sql = 'SELECT f.seo_title as title,ft.seo_title as topic_title  FROM '.$table.' as ft,'.$forum_table.' as f WHERE f.forum_id=ft.forum_id and topic_id ='.$topic_field;
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
					    trigger_db_error($this->dbObj);
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
					}
				return	array($row['title'],$row['topic_title']);
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function updateForumResponseTableEmailSentStatus($qid)
		    {
				$sql = 'UPDATE '.$this->CFG['db']['tbl']['forum_response'].' SET email_sent=\'Yes\''.
						' WHERE topic_id='.$this->dbObj->Param('qid');
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt, array($qid));
				if (!$rs)
					    trigger_db_error($this->dbObj);
		    }

		/**
		 *
		 * @access public
		 * @return void
		 **/
		public function getAdminUserId($user_table)
		    {
				$sql = 'SELECT '.$this->getUserTableField('user_id').' AS user_id FROM '.$user_table.' WHERE '.$this->getUserTableField('user_access').' = \'Admin\' LIMIT 1';
				$stmt = $this->dbObj->Prepare($sql);
				$rs = $this->dbObj->Execute($stmt);
				if (!$rs)
						trigger_db_error($this->dbObj);
				$row = array('user_id'=> 1);
				if ($rs->PO_RecordCount())
					{
						$row = $rs->FetchRow();
					}
				return	$row['user_id'];
		    }
	}
//<<<<<-------------- Class ForumReminderFormHandler begins ---------------//
//-------------------- Code begins -------------->>>>>//
$reminder = new ForumReminderFormHandler();
$reminder->member_url = $CFG['site']['url'].$CFG['redirect']['member'].'/';

if ($cron_arr = $reminder->getCronMasterDetails($CFG['db']['tbl']['cron_master'], 'forums'))
{
	if ($autoindex_arr = $reminder->emailForumDetails($cron_arr['upto_id'], $CFG['question']['send_count']))
		$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'forums', 'Started', 'old',  $autoindex_arr['user_id'], $autoindex_arr['count']);
		else
			$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'forums', 'Started', 'new');}
else
	$reminder->updateCronMaster($CFG['db']['tbl']['cron_master'],'forums', 'Started', 'new');

?>
