<?
	require_once("objects/modules/_base.php");

	$spaw_root = getenv('DOCUMENT_ROOT').dirname($PHP_SELF).'/objects/extern/spaw/';
	include_once $spaw_root.'spaw_control.class.php';

	define('CAT_MOD_MAIL_SEND',1);
	define('CAT_MOD_MAIL_STAT',2);

	class ModMail extends ModBase
	{				
		function ModMail() 
		{
			$this->ModBase();
			$this->title = $GLOBALS[cat_m_mod_mail];
		}
	
		function show()
		{
			global $cat_db, $cat_max_file_size;
			
			$s = "
			<script language='javascript'>
			<!--

			function removeFileIn(button){
				tr = button;
				while (tr.tagName != 'TR') tr = tr.parentNode;
				tr.parentNode.removeChild(tr);
				checkLast();
			}


			function addFileIn(button){
				tr = button;			
				while (tr.tagName != 'TR') tr = tr.parentNode;

				var idSuffix = Math.round(Math.random()*10000);
				var newNode = tr.parentNode.insertBefore(tr.cloneNode(true),tr.nextSibling);
				childs = newNode.getElementsByTagName('td');

				for (var i = 0; i < childs.length; i++){
					if (childs[i].className == 'files') childs[i].innerHTML = '<input name=\"m_upload_' + idSuffix + '\" size=\"40\" type=\"file\">';
				}
				checkLast();			
			}

			function checkLast(){
				btns = document.getElementsByName('remove');
				for (i = 0; i < btns.length; i++){
					btns[i].disabled = (btns.length == 1) ? true : false;
				}
			}
			
			// -->
			</script>
			";

			$s .= "<table border='0' cellpadding='5' cellspacing='1' width='100%' class='pt9'>";

			$s .= "<form enctype='multipart/form-data' action='".$this->URL."&cat_opt=".CAT_MOD_MAIL_SEND."' method='post' name='rf'>";

			$s .= "<tr><td class='einfo' width='20%' align='right' valign='top'><nobr><font class='etitle'>";
			$s .= $GLOBALS[cat_m_mail_from];
			$s .= "</font></nobr></td><td class='eedit' width='80%'><input type='text' name='m_from' size='60' maxlength='128' value='".$GLOBALS['c_m_from']."'></td></tr>";

			$s .= "<tr><td class='einfo' width='20%' align='right' valign='top'><nobr><font class='etitle'>";
			$s .= $GLOBALS[cat_m_mail_to];
			$s .= "</font></nobr></td><td class='eedit' width='80%'><select name='m_to' size='1' style='width: 200px'>";
			
			$res = $cat_db->query("select cat_domains.id_domains as id, cat_tables.title as ttitle, cat_domains.title as title,cat_domains.in_table from cat_domains,cat_tables where cat_tables.name=cat_domains.in_table and cat_domains.name like '%mail'");				

			foreach($res as $r) {
				$s .= "<option value='$r[id]'>$r[ttitle] : $r[title]</option>";				

				$qes = $cat_db->query("select * from cat_domains where in_table='$r[in_table]' order by pos");
				$domains = array();
				foreach($qes as $q) {
					eval('$obj = new '.$q['object'].'($q);');	
					if(is_object($obj) && $obj->isValid()) array_push($domains,$obj);
				};
				
				$z = "";					
				foreach($domains as $d) {
					if($d->isParKey()) 
						$z .= "<td>".$d->onFilterForm(array())."</td>";
				}
				
			};

			$s .= "</select>";
			if(strlen($z) > 1) 
				$s .= "<br><table  border='0' cellspacing='0' cellpadding='0' class='pt8'><tr>$z</tr></table>";	
			$s .= "</td></tr>";


			$s .= "<tr><td class='einfo' width='20%' align='right' valign='top'><nobr><font class='etitle'>";
			$s .= $GLOBALS[cat_m_mail_subj];
			$s .= "</font></nobr></td><td class='eedit' width='80%'><input type='text' name='m_subj' size='60' maxlength='128'></td></tr>";

			$s .= "<tr><td class='einfo' width='20%' align='right' valign='top'><nobr><font class='etitle'>";
			$s .= $GLOBALS[cat_m_mail_mess];
			$s .= "</font></nobr></td><td class='eedit' width='80%'>";		
			$sw = new SPAW_Wysiwyg('m_message',"");
			$s .= $sw->getHtml();
			$s .= "</td></tr>";

			$s .= "<tr><td class='einfo' width='20%' align='right' valign='top'><nobr><font class='etitle'>";
			$s .= $GLOBALS[cat_m_mail_afile];
			$s .= "</font></nobr></td><td class='eedit' width='80%'>
				<table border='0' cellspacing='0' cellpadding='0' width='100%'>
				<tr valign='top'>
				<td width='99%' class='files'><input type='file' size='40' name='m_upload'></td>
				<td nowrap align='right'>
				<input type='button' name='remove' value=' - ' onClick='removeFileIn(this);' class='sub'>
				<input type='button' value=' + ' onClick='addFileIn(this);' class='sub'></td>
				</tr>
				</table>
			</td></tr>";

			$s .= "<tr><td class='einfo' colspan='2' align='right' valign='top'>";
			$s .= "<input type='submit' class='sub' value='$GLOBALS[cat_m_action]'$ea>";
			$s .= "</td></tr>";

			$s .= "</form>";

			$s .= "<tr><td align='center' valign='top' colspan='2'><nobr><font class='etitle'>";
			$s .= "<a href='?cat_pos=control&cat_mod=ModMail&cat_opt=".CAT_MOD_MAIL_STAT."'><img src='images/retrain.gif' border='0' alt=''>&nbsp;".$GLOBALS[cat_m_mail_proto]."</a>";
			$s .= "</font></nobr></td></tr>";

			$s .= "</table>";

			$s .= "
			<script language='javascript'>
			<!--
				checkLast();
			// -->
			</script>
			";
			
			return $s;		
		}


		function applyTask()
		{

			global	$cat_db;

			$from = $GLOBALS['m_from'];
			$to = $GLOBALS['m_to'];
			$subj = $GLOBALS['m_subj'];
			$message = stripslashes($GLOBALS['m_message']);

			if(strlen($from) > 1 && strlen($subj) > 1 && strlen($message) > 1) {

				$to_limit = array();
				$res = $cat_db->query("select in_table from cat_domains where id_domains='$to'");				

				if(count($res) == 1) {
					$qes = $cat_db->query("select * from cat_domains where in_table='".$res[0][in_table]."' order by pos");
					$domains = array();
					foreach($qes as $q) {
						eval('$obj = new '.$q['object'].'($q);');	
						if(is_object($obj) && $obj->isValid()) array_push($domains,$obj);
					};
				
					foreach($domains as $d) {
						if($d->isParKey() && strlen($d->getFromInput()) > 0) { 
							array_push($to_limit,$d->name."=\"".$d->getFromInput()."\"");
						        if($d->isSelfParKey()) {
						        	$a = $d->getAllChilds($d->getFromInput());
								
								foreach($a as $k) {
									array_push($to_limit,$d->name."=\"".$k."\"");
								};

							};
						}
					}
					
				};



				setcookie('c_m_from',$GLOBALS['m_from'],time() + 31536000);		

				$uid = 	strtoupper(uniqid(time()));				
				$ilist = array();
				
				if(preg_match('/<IMG src="([^"]*)">/',$message,$r)) {
					$img['id'] = md5($r[1]);
					$img['file'] = getenv('DOCUMENT_ROOT').$r[1];
					
					$ext = strtolower(substr(basename($r[1]),-3));
					if($ext == "epg" || $est == "jpg") {
						$img['type'] = 'jpeg';
					};
					if($ext == "gif") {
						$img['type'] = 'gif';
					};
					if($ext == "iff" || $est == "tif") {
						$img['type'] = 'tiff';
					};
					if($ext == "png") {
						$img['type'] = 'png';
					};
					
					$message = str_replace($r[1],"cid:$img[id]",$message);
					array_push($ilist,$img);
                                }                 				

				

				$data = "------------".$uid."\nContent-Type:text/html; charset=Windows-1251\n";
				$data .= "Content-Transfer-Encoding: 8bit\n\n";
				$data .= "<html>\n<body bgcolor='#ffffff' style='font-family: Verdana, Tahoma, san-serif; font-size: 9pt'>\n";
				$data .= $message;
				$data .= "</body>\n</html>";
				$data .= "\n\n";

				foreach($ilist as $img) {
					if(!file_exists($img['file']) || is_dir($img['file'])) break;
					$i = fopen($img['file'],"rb");
					$data .= "------------".$uid."\n";
					$data .= "Content-Type: image/$img[type]; ";
					$data .= "name=\"".basename($img['file'])."\"\n";
					$data .= "Content-Transfer-Encoding: base64\n";
					$data .= "Content-ID: <$img[id]>\n\n";
					$data .= chunk_split(base64_encode(fread($i,filesize($img['file']))))."\n\n";
				};

				$flist = array();
				$tmp = "temp/";
				
				foreach($_FILES as $f) {
					move_uploaded_file($f['tmp_name'],$tmp.$f[name]);
					array_push($flist,$tmp.$f[name]);
				};

				foreach($flist as $fn) {
					if(!file_exists($fn) || is_dir($fn)) break;
					$f = fopen($fn,"rb");
					$data .= "------------".$uid."\n";
					$data .= "Content-Type: application/octet-stream; ";
					$data .= "name=\"".basename($fn)."\"\n";
					$data .= "Content-Transfer-Encoding: base64\n";
					$data .= "Content-Disposition: attachment;";
					$data .= "filename=\"".basename($fn)."\"\n\n";
					$data .= chunk_split(base64_encode(fread($f,filesize($fn))))."\n\n";
					fclose($f);
					unlink($fn);
				};
				
				if(count($to_limit) > 0) $t_l = implode(' OR ',$to_limit);
				else $t_l = '';

				$cat_db->query("insert into cat_mail_tasks values(0,'$from','$to','$t_l','$subj','$uid','".addslashes($data)."',now(),'0')");

				$s = "<table border='0' cellpadding='5' cellspacing='1' width='100%' class='pt9'>";
				$s .= "<tr><td align='left' valign='top'><div style='font-family: Courier New, fixed'>";
			
				$s .= nl2br(htmlspecialchars($data));

				$s .= "</div></td></tr>";
				$s .= "</table>";
			
			} else {
				$s = "<table border='0' cellpadding='5' cellspacing='1' width='100%' class='pt9'>";
				$s .= "<tr><td align='center' valign='top'><font color='#cc0000'>";
			
				$s .= $GLOBALS[cat_m_mail_error_nodata];

				$s .= "</font></td></tr>";
				$s .= "</table>";

			};						
		        return $s;
		} 

		function showStat()
		{
			global $cat_db;			

			$res = $cat_db->query("select * from cat_mail_tasks order by tmark desc");
			
			$s = "<b>$GLOBALS[cat_m_mail_proto]</b><br/>";
			$s .= "<table border='0' cellpadding='5' cellspacing='1' width='100%' class='pt9'>";
			$i = false;

			$s .= "<tr>";
			$s .= "<td align='center' valign='top' class='header'><nobr>";			
			$s .= $GLOBALS[cat_m_mail_time];
			$s .= "</nobr></td>";
			$s .= "<td align='center' valign='top' class='header'><nobr>";			
			$s .= $GLOBALS[cat_m_mail_subj];
			$s .= "</nobr></td>";
			$s .= "<td align='center' valign='top' class='header'><nobr>";			
			$s .= $GLOBALS[cat_m_mail_status];
			$s .= "</nobr></td>";
			$s .= "</tr>";

			foreach($res as $r) {	
				if($i) $style = 'finfo';
				else $style = 'ninfo';

				$s .= "<tr>";
				$s .= "<td align='left' valign='top' class='$style'><nobr>";			
				$s .= dateToStr($r['tmark']);
				$s .= "</nobr></td>";
				$s .= "<td align='left' valign='top' class='$style' width='100%'>";			
				$s .= $r['subj'];
				$s .= "</td>";
				$s .= "<td align='left' valign='top' class='$style'><nobr>";			
				if($r['state'] == 0) $s .= $GLOBALS[cat_m_mail_notsend];
				else $s .= $GLOBALS[cat_m_mail_send];
				$s .= "</nobr></td>";
				$s .= "</tr>";

				$i = !$i;
			};
			$s .= "</table>";			

			return $s;

		} 		
				

		function execute($user)
		{
			global	$cat_opt;

			$s = '';			
			if($user->isEdit('ModMail')) {
 				$s = "<font class='title'>$GLOBALS[cat_m_mod_mail]</font><br><br>";
				switch($cat_opt) {
					case(CAT_MOD_MAIL_SEND): {
						$s .= $this->applyTask();
						break;
					};	
					case(CAT_MOD_MAIL_STAT): {
						$s .= $this->showStat();
						break;
					};	
					default: {
						$s .= $this->show();
					};			
				};
			};
			return $s;
		}
	
	};

?>