<?php
include_once("_dirinfo.php");
include_once(PATH_TO_ROOT . "webcati/_class/class.WebPoints.php");

class mailObject {
	
	private $PersonalizationFieldArray = array("subject","content");
	private $loadedTemplateId = 0;
    
	function __construct($db)
	{
		$this->db = $db;
		$dbConfig = configLoader::loadConfig('paths');
		$this->wwwPath = $dbConfig['warpit_www'].'survey/index.php';
		$this->redirectPath = $dbConfig['redirectModul_www'].'redirect.php';
		$this->removalRequestLink = $dbConfig['warpit_www']."webuserspool/removalRequest.php";
	}
	
	
	/**
	 * Function loads core mail template
	 * 
	 * $aId is a Id from table _MailTemplates
	 * @param int $aId
	 * 
	 */
	function LoadMailTemplate( $aId ) 
	{
		// I delete predefined personalized variables
		unset($this->PersonElements);
		
		// if id template is allready loaded I don't load it again!
		if ($this->loadedTemplateId == $aId) return;
		 
		
		unset($this->Attachments);
		
		$sql = "SELECT * FROM ".DB_WARPIT_USERSPOOL."._MailAttachments WHERE template_id =".$aId;
		$result = $this->db->SQLexecute($sql);
		
		while ($zad = $this->db->fetchAssoc($result)) {
			if ($zad['embeded']) $this->AttachmentsEmbed[] = USERSPOOL_ATTACHMENTS.$zad['filePath'].$zad['fileName'];
				else  $this->Attachments[] = USERSPOOL_ATTACHMENTS.$zad['filePath'].$zad['fileName'];
		}
		
		
		// sql query for loading mail template
		$sql 	= " SELECT a.mail_from, a.subject, a.content,
							b.local, b.host, b.port, b.helo_message,  b.username, b.password, a.mail_from_label 
							  
						FROM ".DB_WARPIT_USERSPOOL."._Emails  as a
							LEFT JOIN ".DB_WARPIT_USERSPOOL."._SMTP_accounts as b ON a.id_account = b.id  
								WHERE a.id = ".$aId;
		//echo $sql."<br />";
		$result = $this->db->SQLexecute($sql);
		$zad 	= $this->db->fetchAssoc($result);		
		foreach ($zad as $key=>$val) $this->Elements->$key = $val;
		$this->loadedTemplateId = $aId;			
	
	}
	
	/**
	 *  loading all comboboxes and radiobuttons and all labels which are recoded in 
	 *  webuserspool fields
	 */
	function LoadExtraField() {
		
	   	  $sql = "SELECT a.`field_name` , b. *
					FROM ".DB_WARPIT_USERSPOOL."._InterviewerStructure AS a
					  LEFT JOIN ".DB_WARPIT_USERSPOOL.".user_input_labels AS b ON a.`id` = b.lab_field
		  				 WHERE b.id IS NOT NULL ";
		  $result = $this->db->SQLexecute($sql);
		  // Creating array with codes and labels
		  while ($zadetek = $this->db->fetchAssoc($result)) 
				$this->ExtraFieldLabels[$zadetek[field_name]][$zadetek[lab_code]] = $zadetek[lab_label];	
				
	}
    
    function prepereWebPoints($userId)
    {
        $wp = new WebPoints($this->db);
        

        $this->totalPoints = $wp->getTotalPoints($userId);
		$this->gainedPoints = $wp->getGainedPoints($userId);
		$this->usedPoints = $wp->getUsedPoints($userId);
    }
	
	function prepareCatiLinks($aProjectId,$aUserId) {
		
		
		
		
		$sql = " SELECT loginSID FROM ".DB_WARPIT_WEBCATI_BASE."._www_ids 
						WHERE 
								id_user 	= ".$aUserId." 
							AND user_type 	= 2 
							AND	id_project 	= ".$aProjectId;
		//echo $sql;
		$res = $this->db->SQLexecute($sql);
		if ($this->db->NumRows($res)) {
			
			$zad = $this->db->fetchAssoc($res);
			$this->catiLink = $zad['loginSID'];
		
		} else {
			$this->catiLink = substr(md5(time().$aUserId.$aProjectId),0,15)."-";
			$sql = "INSERT INTO ".DB_WARPIT_WEBCATI_BASE."._www_ids 
					SET id_user 	= ".$aUserId.",
						user_type 	= 2,
						id_project 	= ".$aProjectId.", 
						id_site		= 0,
						loginSID 	= '".$this->catiLink."'";
			$this->db->SQLexecute($sql);
			$lastId =  $this->db->GetLastInsertId();			
			$sql = "UPDATE ".DB_WARPIT_WEBCATI_BASE."._www_ids 
						SET loginSID = CONCAT(loginSID,id) WHERE id = ".$lastId;				
			$this->db->SQLexecute($sql);
			$this->catiLink .= $lastId;
		} 
		
		
	}
	
	/**
	 * Preparing link for redirection link
	 *
	 * @param integer $aProjectId
	 * @param integer $aUserId
	 */
	
	function prepareRedirectLinks($aProjectId,$aUserId) {
		
		$this->RedirectLink = "<a href=\"".$this->redirectPath."?redirectID=".$aUserId."&project_id=".$aProjectId."\">";
		
	}
	
	
	/**
	 * This function replaces all personaliyation tags with real data
	 *
	 * For input argument you just insert array with keys and replacing values.
	 * 
	 * @param array $aChangeArray
	 */
	function Personalization($aChangeArray = array()) 
	{
	    
		$tmpChange = array();
				
		foreach ($aChangeArray as $key=>$val) {
			if ($this->ExtraFieldLabels[$key]) 				
				$tmpChange['[!'.$key.']'] = $this->ExtraFieldLabels[$key][$val];
			 else 
				$tmpChange['[!'.$key.']'] = $val;			 
		}
		
		// area for preparing and inserting link into mail template
		// first I prepare empty strings, just in case if we have
		// defined link in mail template, but we don't send with
		// connection to project
		$tmpChange['[!catiLink]'] = "";
		$tmpChange['[/catiLink]'] = "";		
		// if link exists I make string replacement
		if ($this->catiLink) { 
			$tmpChange['[!catiLink]'] = "<a href=".$this->wwwPath."?loginSID=".$this->catiLink.">";	
			$tmpChange['[/catiLink]'] = "</a>";	 
		}
		
		$tmpChange['[!catiLinkText]'] = $this->wwwPath."?loginSID=".$this->catiLink;
		$tmpChange['[!loginSID]'] = $this->catiLink;
		// end of link inserting into mail template
		
		$tmpChange['[!redirection]'] = "";
		$tmpChange['[/redirection]'] = "";	
		
		
		$tmpChange['[!sid]'] = md5("sidXdses893721".$aChangeArray['id']);	
		
			
		// if link exists I make string replacement
		if ($this->RedirectLink) { 
			$tmpChange['[!redirection]'] = $this->RedirectLink;	
			$tmpChange['[/redirection]'] = "</a>";		 
		}
		
			$tmpChange['[!removalRequest]'] = "<a href=\"".$this->removalRequestLink."?email=".$aChangeArray['email']."&secureToken=".md5($aChangeArray['email'].$aChangeArray['id'])."\">";
		$tmpChange['[/removalRequest]'] = "</a>";
	    if(isset($this->gainedPoints))
       {
            $tmpChange['[!gainedPoints]'] = "";
            $tmpChange['[!gainedPoints]'] =  $this->gainedPoints;
       }
	   if(isset($this->totalPoints))
       {
            $tmpChange['[!totalPoints]'] = "";
            $tmpChange['[!totalPoints]'] =  $this->totalPoints;
       }
	   if(isset($this->usedPoints))
       {
            $tmpChange['[!usedPoints]'] = "";
            $tmpChange['[!usedPoints]'] =  $this->usedPoints;
       }
        
        
		foreach ($this->PersonalizationFieldArray as $fields) $this->PersonElements->$fields = strtr($this->Elements->$fields,$tmpChange);
		
	}
	
	
	
	
}

?>