Files
fmgapp/webservices/111Production.php

2591 lines
103 KiB
PHP
Executable File

<?php declare(strict_types=1); namespace IR\App\Webservices; if (!defined('IR_START')) exit('<pre>No direct script access allowed</pre>');
/**
* @framework iResponse Framework
* @version 1.0
* @author Amine Idrissi <contact@iresponse.tech>
* @date 2019
* @name Production.php
*/
# core
use IR\Core\Base as Base;
use IR\Core\Application as Application;
# helpers
use IR\App\Helpers\Authentication as Authentication;
use IR\App\Helpers\Permissions as Permissions;
use IR\App\Helpers\AuditLog as AuditLog;
use IR\App\Helpers\Page as Page;
use IR\App\Helpers\Api as Api;
# models
use IR\App\Models\Admin\MtaServer as MtaServer;
use IR\App\Models\Admin\SmtpServer as SmtpServer;
use IR\App\Models\Admin\ServerVmta as ServerVmta;
use IR\App\Models\Admin\SmtpUser as SmtpUser;
use IR\App\Models\Admin\Isp as Isp;
use IR\App\Models\Affiliate\AffiliateNetwork as AffiliateNetwork;
use IR\App\Models\Affiliate\Offer as Offer;
use IR\App\Models\Affiliate\Suppression as Suppression;
use IR\App\Models\Affiliate\FromName as FromName;
use IR\App\Models\Affiliate\Subject as Subject;
use IR\App\Models\Affiliate\Creative as Creative;
use IR\App\Models\Affiliate\Link as Link;
use IR\App\Models\Lists\DataList as DataList;
use IR\App\Models\Production\MtaProcess as MtaProcess;
use IR\App\Models\Production\SmtpProcess as SmtpProcess;
use IR\App\Models\Production\AutoResponder as AutoResponder;
use IR\App\Models\Production\TeamAuthorisation as TeamAuthorisation;
# orm
use IR\Orm\Query as Query;
# http
use IR\Http\Request as Request;
/**
* @name Production
* @description Production WebService
*/
class Production extends Base
{
/**
* @app
* @readwrite
*/
protected $app;
/**
* @name init
* @description initializing process before the action method executed
* @once
* @protected
*/
public function init()
{
# set the current application to a local variable
$this->app = Application::getCurrent();
}
/**
* @name getServers
* @description get servers action
* @before init
*/
public function getServers($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$type = $this->app->utils->arrays->get($parameters,'type');
$mailer_ids = $this->app->utils->arrays->get($parameters,'mailer-ids');
$servers=[];
if($mailer_ids!="" && count($mailer_ids)){
foreach ($mailer_ids as $mailer_id){
$mailer_id=preg_replace('/[^0-9]/i', '',$mailer_id);
if($mailer_ids=="")continue;
$authorisations = TeamAuthorisation::all(TeamAuthorisation::FETCH_ARRAY,['team_member_id = ?',$mailer_id]);
//print_r($authorisations);
$vmtasIds = [];
foreach ($authorisations as $authorisation)
{
$vmtasIds = array_merge($vmtasIds,array_unique(array_filter(explode(',',$authorisation['vmtas_ids']))));
}
if(count($vmtasIds))
{
$results = Application::getCurrent()->database('system')->execute("SELECT id,name,main_ip,provider_name FROM admin.mta_servers WHERE status='Activated' and is_installed and id IN (SELECT mta_server_id FROM admin.servers_vmtas WHERE id IN (" . implode(',',$vmtasIds) . ") ) order by naturalsort(name) asc");
if(count($results)){
foreach ($results as $row)
{
$servers[] = $row;
}
}
}
}
}else{
$servers = $type == 'mta' ? MtaServer::all(MtaServer::FETCH_ARRAY,['status = ? AND is_installed = ?',['Activated','t']],['id','name','main_ip','provider_name'],'naturalsort(name)','ASC')
: SmtpServer::all(SmtpServer::FETCH_ARRAY,['status = ?',['Activated']],['id','name'],'naturalsort(name)','ASC');
}
/*
$servers = $type == 'mta' ? MtaServer::all(MtaServer::FETCH_ARRAY,['status = ? AND is_installed = ?',['Activated','t']],['id','name','main_ip','provider_name'],'naturalsort(name)','ASC')
: SmtpServer::all(SmtpServer::FETCH_ARRAY,['status = ?',['Activated']],['id','name'],'naturalsort(name)','ASC');
*/
if(count($servers) > 0)
{
Page::printApiResults(200,'',['servers' => $servers]);
}
else
{
Page::printApiResults(500,'Servers not found !');
}
}
/**
* @name getVmtas
* @description get vmtas action
* @before init
*/
public function getVmtas($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$serverIds=[];
$serverIdsAll = $this->app->utils->arrays->get($parameters,'server-ids');
$vmtasType = $this->app->utils->arrays->get($parameters,'vmtas-type');
$ispId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'isp-id'));
$username = Authentication::getAuthenticatedUser()->getEmail();
//
foreach ($serverIdsAll as $key => $id) {
$id=preg_replace('/[^0-9]/i', '',$id);
if($id=="")continue;
$serverIds[]=$id;
}
//print_r($serverIds);exit;
if(count($serverIds) > 0)
{
$vmtas = [];
switch ($vmtasType)
{
case 'default-vmtas':
{
$vmtas = ServerVmta::all(ServerVmta::FETCH_ARRAY,['status = ? and mta_server_id in ? AND type = ?',['Activated',$serverIds,'Default']],
['id','mta_server_id','mta_server_name','type','ip','domain','custom_domain'],"mta_server_id,id");
break;
}
case 'smtp-vmtas':
{
$vmtas = ServerVmta::all(ServerVmta::FETCH_ARRAY,['status = ? and mta_server_id in ? AND type = ? ',['Activated',$serverIds,'SMTP']],['id','mta_server_id','mta_server_name','type','ip','domain','custom_domain'],"mta_server_id,id");
/*
if (Authentication::getAuthenticatedUser()->getMasterAccess()=="Enabled"){
$vmtas = ServerVmta::all(ServerVmta::FETCH_ARRAY,['status = ? and mta_server_id in ? AND type = ? ',['Activated',$serverIds,'SMTP']],['id','mta_server_id','mta_server_name','type','ip','domain','custom_domain']);
}else{
$vmtas = ServerVmta::all(ServerVmta::FETCH_ARRAY,['status = ? and mta_server_id in ? AND type = ? AND created_by = ? ',['Activated',$serverIds,'SMTP',$username]],['id','mta_server_id','mta_server_name','type','ip','domain','custom_domain']);
}
*/
break;
}
case 'merged-vmtas':
case 'custom-vmtas':
{
if($ispId > 0)
{
$vmtas = ServerVmta::all(ServerVmta::FETCH_ARRAY,['status = ? and mta_server_id in ? AND type = ? AND isp_id = ?',['Activated',$serverIds,'Custom',$ispId]],
['id','mta_server_id','mta_server_name','type','ip','domain','custom_domain'],"mta_server_id,id");
}
break;
}
case 'all-vmtas':
{
$vmtas = ServerVmta::all(ServerVmta::FETCH_ARRAY,['status = ? and mta_server_id in ?',['Activated',$serverIds]],
['id','mta_server_id','mta_server_name','type','ip','domain','custom_domain'],"mta_server_id,id");
break;
}
}
if(count($vmtas) == 0)
{
Page::printApiResults(500,'No vmtas found !');
}
Page::printApiResults(200,'',['vmtas' => $vmtas]);
}
else
{
Page::printApiResults(500,'Incorrect server id !');
}
}
/**
* @name captureCrative
* @description capture crative action
* @before init
*/
public function captureCrative($parameters = [])
{
# check for authentication
if (!Authentication::isUserAuthenticated()) {
Page::printApiResults(401, 'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(
Authentication::getAuthenticatedUser(),
'Production',
'sendProcess'
);
if ($access == false) {
Page::printApiResults(403, 'Access Denied !');
}
$creative = $this->app->utils->arrays->get($parameters, 'creative');
if ($creative != '') {
$url = '';
$creativeFile = $this->app->utils->strings->randomHex(5);
$this->app->utils->fileSystem->writeFile(
PUBLIC_PATH . DS . 'tools' . DS . $creativeFile . '.html',
str_replace('https', 'http', $creative)
);
shell_exec(
'wkhtmltoimage ' .
PUBLIC_PATH .
DS .
'tools' .
DS .
$creativeFile .
'.html ' .
PUBLIC_PATH .
DS .
'tools' .
DS .
$creativeFile .
'.jpg'
);
$this->app->utils->fileSystem->deleteFile(
PUBLIC_PATH . DS . 'tools' . DS . $creativeFile . '.html'
);
Page::printApiResults(200, '', [
'url' =>
$this->app->http->request->getBaseURL() .
RDS .
'tools' .
RDS .
$creativeFile .
'.jpg'
]);
} else {
Page::printApiResults(500, 'Incorrect creative !');
}
}
/**
* @name cropCrative
* @description crop crative action
* @before init
*/
public function cropCrative($parameters = [])
{
# check for authentication
if (!Authentication::isUserAuthenticated()) {
Page::printApiResults(401, 'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(
Authentication::getAuthenticatedUser(),
'Production',
'sendProcess'
);
if ($access == false) {
Page::printApiResults(403, 'Access Denied !');
}
$src = $this->app->utils->arrays->get($parameters, 'src');
$type = $this->app->utils->arrays->get($parameters, 'type');
$offerClick = $this->app->utils->arrays->get(
$parameters,
'offer-click-crop'
);
$offerUnsub = $this->app->utils->arrays->get(
$parameters,
'offer-unsub-crop'
);
$offerOptOut = $this->app->utils->arrays->get(
$parameters,
'offer-optout-crop'
);
if ($src != '') {
if ($type != '') {
$imageName = str_replace(
$this->app->http->request->getBaseURL() .
RDS .
'tools' .
RDS,
'',
$src
);
$images = [];
$html = '<html><head></head><body><center>' . PHP_EOL;
$top = 0;
switch ($type) {
case 'crop-images':
case 'crop-background':
# offer click case
if (
count($offerClick) &&
floatval($offerClick['w']) > 0
) {
$originalImage = imagecreatefromjpeg(
PUBLIC_PATH . DS . 'tools' . DS . $imageName
);
$croppedImage = imagecrop($originalImage, [
'x' => floatval($offerClick['x']),
'y' => floatval($offerClick['y']),
'width' => floatval($offerClick['w']),
'height' => floatval($offerClick['h'])
]);
if ($croppedImage !== false) {
imagejpeg(
$croppedImage,
PUBLIC_PATH .
DS .
'tools' .
DS .
'cropped_click_' .
$imageName
);
imagedestroy($croppedImage);
}
imagedestroy($originalImage);
# move image to media folder
$name =
$this->app->utils->strings->randomHex(8) .
'.jpg';
$this->app->utils->fileSystem->copyFileOrDirectory(
PUBLIC_PATH .
DS .
'tools' .
DS .
'cropped_click_' .
$imageName,
MEDIA_PATH . DS . $name
);
$images[] = MEDIA_PATH . DS . $name;
if ($type == 'crop-images') {
$html .=
'<a href="http://[domain]/[url]"><img src="http://[domain]/' .
$name .
'" alt="image"/></a><br/>' .
PHP_EOL;
} elseif ($type == 'crop-background') {
$html .=
'<a href="http://[domain]/[url]" style="display:block;background:url(http://[domain]/' .
$name .
');width:' .
floatval($offerClick['w']) .
'px;height:' .
floatval($offerClick['h']) .
'px;"></a><br>' .
PHP_EOL;
$top += floatval($offerClick['h']);
}
}
# offer unsub case
if (
count($offerUnsub) &&
floatval($offerUnsub['w']) > 0
) {
$originalImage = imagecreatefromjpeg(
PUBLIC_PATH . DS . 'tools' . DS . $imageName
);
$croppedImage = imagecrop($originalImage, [
'x' => floatval($offerUnsub['x']),
'y' => floatval($offerUnsub['y']),
'width' => floatval($offerUnsub['w']),
'height' => floatval($offerUnsub['h'])
]);
if ($croppedImage !== false) {
imagejpeg(
$croppedImage,
PUBLIC_PATH .
DS .
'tools' .
DS .
'cropped_unsub_' .
$imageName
);
imagedestroy($croppedImage);
}
imagedestroy($originalImage);
# move image to media folder
$name =
$this->app->utils->strings->randomHex(8) .
'.jpg';
$this->app->utils->fileSystem->copyFileOrDirectory(
PUBLIC_PATH .
DS .
'tools' .
DS .
'cropped_unsub_' .
$imageName,
MEDIA_PATH . DS . $name
);
$images[] = MEDIA_PATH . DS . $name;
if ($type == 'crop-images') {
$html .=
'<a href="http://[domain]/[unsub]"><img style="margin:-5px 0px" src="http://[domain]/' .
$name .
'" alt="image"/></a><br/>' .
PHP_EOL;
} elseif ($type == 'crop-background') {
$html .=
'<a href="http://[domain]/[unsub]" style="display:block;background:url(http://[domain]/' .
$name .
');width:' .
floatval($offerUnsub['w']) .
'px;height:' .
floatval($offerUnsub['h']) .
'px;"></a><br>' .
PHP_EOL;
$top += floatval($offerUnsub['h']);
}
}
# optout case
if (
count($offerOptOut) &&
floatval($offerOptOut['w']) > 0
) {
$originalImage = imagecreatefromjpeg(
PUBLIC_PATH . DS . 'tools' . DS . $imageName
);
$croppedImage = imagecrop($originalImage, [
'x' => floatval($offerOptOut['x']),
'y' => floatval($offerOptOut['y']),
'width' => floatval($offerOptOut['w']),
'height' => floatval($offerOptOut['h'])
]);
if ($croppedImage !== false) {
imagejpeg(
$croppedImage,
PUBLIC_PATH .
DS .
'tools' .
DS .
'cropped_optout_' .
$imageName
);
imagedestroy($croppedImage);
}
imagedestroy($originalImage);
# move image to media folder
$name =
$this->app->utils->strings->randomHex(8) .
'.jpg';
$this->app->utils->fileSystem->copyFileOrDirectory(
PUBLIC_PATH .
DS .
'tools' .
DS .
'cropped_optout_' .
$imageName,
MEDIA_PATH . DS . $name
);
$images[] = MEDIA_PATH . DS . $name;
if ($type == 'crop-images') {
$html .=
'<a href="http://[domain]/[optout]"><img src="http://[domain]/' .
$name .
'" alt="image"/></a><br/>' .
PHP_EOL;
} elseif ($type == 'crop-background') {
$html .=
'<a href="http://[domain]/[optout]" style="display:block;background:url(http://[domain]/' .
$name .
');width:' .
floatval($offerOptOut['w']) .
'px;height:' .
floatval($offerOptOut['h']) .
'px;"></a><br>' .
PHP_EOL;
}
}
break;
case 'crop-one-background':
# move image to media folder
$name =
$this->app->utils->strings->randomHex(8) . '.jpg';
$this->app->utils->fileSystem->copyFileOrDirectory(
PUBLIC_PATH . DS . 'tools' . DS . $imageName,
MEDIA_PATH . DS . $name
);
$size = getimagesize(MEDIA_PATH . DS . $name);
$images[] = MEDIA_PATH . DS . $name;
$html .=
'<div style="display:block;background:url(http://[domain]/' .
$name .
');width:' .
$size[0] .
'px;height:' .
$size[1] .
'px;position:relative;">' .
PHP_EOL;
# offer click case
if (
count($offerClick) &&
floatval($offerClick['w']) > 0
) {
$html .=
'<a href="http://[domain]/[url]" style="position:absolute;left:' .
floatval($offerClick['x']) .
'px;top:' .
floatval($offerClick['y']) .
'px;width:' .
floatval($offerClick['w']) .
'px;height:' .
floatval($offerClick['h']) .
'px;display: block;"></a>' .
PHP_EOL;
}
# offer unsub case
if (
count($offerUnsub) &&
floatval($offerUnsub['w']) > 0
) {
$html .=
'<a href="http://[domain]/[unsub]" style="position:absolute;left:' .
floatval($offerUnsub['x']) .
'px;top:' .
floatval($offerUnsub['y']) .
'px;width:' .
floatval($offerUnsub['w']) .
'px;height:' .
floatval($offerUnsub['h']) .
'px;display: block;"></a>' .
PHP_EOL;
}
# offer optout case
if (
count($offerOptOut) &&
floatval($offerOptOut['w']) > 0
) {
$html .=
'<a href="http://[domain]/[optout]" style="position:absolute;left:' .
floatval($offerOptOut['x']) .
'px;top:' .
floatval($offerOptOut['y']) .
'px;width:' .
floatval($offerOptOut['w']) .
'px;height:' .
floatval($offerOptOut['h']) .
'px;display: block;"></a>' .
PHP_EOL;
}
$html .= '</div>' . PHP_EOL;
break;
case 'crop-map':
# move image to media folder
$name =
$this->app->utils->strings->randomHex(8) . '.jpg';
$this->app->utils->fileSystem->copyFileOrDirectory(
PUBLIC_PATH . DS . 'tools' . DS . $imageName,
MEDIA_PATH . DS . $name
);
$images[] = MEDIA_PATH . DS . $name;
$mapName =
"map" . $this->app->utils->strings->randomHex(8);
$html .=
'<img src="http://[domain]/' .
$name .
'" alt="" usemap="#' .
$mapName .
'">' .
PHP_EOL;
$html .= '<map name="' . $mapName . '">' . PHP_EOL;
# offer click case
if (
count($offerClick) &&
floatval($offerClick['w']) > 0
) {
$x = floatval($offerClick['x']);
$y = floatval($offerClick['y']);
$w = $x + floatval($offerClick['w']);
$h = $y + floatval($offerClick['h']);
$html .=
'<area shape="rect" coords="' .
$x .
',' .
$y .
',' .
$w .
',' .
$h .
'" title="" alt="" href="http://[domain]/[url]" target="_self">' .
PHP_EOL;
}
# offer unsub case
if (
count($offerUnsub) &&
floatval($offerUnsub['w']) > 0
) {
$x = floatval($offerUnsub['x']);
$y = floatval($offerUnsub['y']);
$w = $x + floatval($offerUnsub['w']);
$h = $y + floatval($offerUnsub['h']);
$html .=
'<area shape="rect" coords="' .
$x .
',' .
$y .
',' .
$w .
',' .
$h .
'" title="" alt="" href="http://[domain]/[unsub]" target="_self">' .
PHP_EOL;
}
# offer optout case
if (
count($offerOptOut) &&
floatval($offerOptOut['w']) > 0
) {
$x = floatval($offerOptOut['x']);
$y = floatval($offerOptOut['y']);
$w = $x + floatval($offerOptOut['w']);
$h = $y + floatval($offerOptOut['h']);
$html .=
'<area shape="rect" coords="' .
$x .
',' .
$y .
',' .
$w .
',' .
$h .
'" title="" alt="" href="http://[domain]/[optout]" target="_self">' .
PHP_EOL;
}
$html .= '</map>' . PHP_EOL;
break;
}
$html .= '</center></body></html>' . PHP_EOL;
if (count($images)) {
# check for images servers if existed
$id = intval(
$this->app->utils->arrays->get(
$this->app->getSetting('application'),
'upload_center_id'
)
);
if ($id > 0) {
$server = ManagementServer::first(
ManagementServer::FETCH_ARRAY,
['id = ?', $id],
['id', 'name']
);
if (count($server)) {
# call iresponse api
$result = Api::call('Production', 'uploadImages', [
'images-paths' => $images
]);
if (count($result) == 0) {
Page::printApiResults(
500,
'No response found: ' .
__FUNCTION__ .
' : ' .
__CLASS__
);
}
if ($result['httpStatus'] == 500) {
Page::printApiResults(500, $result['message']);
}
}
}
}
# remove source image
$this->app->utils->fileSystem->deleteFile(
PUBLIC_PATH . DS . 'tools' . DS . $imageName
);
Page::printApiResults(200, '', ['creative' => $html]);
} else {
Page::printApiResults(500, 'Incorrect cropping type !');
}
} else {
Page::printApiResults(500, 'Incorrect image url !');
}
}
/**
* @name getSmtpUsers
* @description get smtp users action
* @before init
*/
public function getSmtpUsers($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$serverIds=[];
$serverIdsAll = $this->app->utils->arrays->get($parameters,'server-ids');
foreach ($serverIdsAll as $key => $id) {
$id=preg_replace('/[^0-9]/i', '',$id);
if($id=="")continue;
$serverIds[]=$id;
}
if(count($serverIds) > 0)
{
$smtpUsers = SmtpUser::all(SmtpUser::FETCH_ARRAY,['smtp_server_id IN ? AND status = ?',[$serverIds,'Activated']]);
if(count($smtpUsers) == 0)
{
Page::printApiResults(500,'No smtp users found !');
}
Page::printApiResults(200,'',['smtp-users' => $smtpUsers]);
}
else
{
Page::printApiResults(500,'Incorrect server id !');
}
}
/**
* @name getOffers
* @description get offers action
* @before init
*/
public function getOffers($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$affiliateNetworkId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'affiliate-network-id'));
if($affiliateNetworkId > 0)
{
$todayName = strtolower(trim(date('D')));
$offers = Offer::all(Offer::FETCH_ARRAY,["status = ? AND affiliate_network_id = ? AND available_days LIKE '%{$todayName}%'",['Activated',$affiliateNetworkId]],['id','name','production_id']);
if(count($offers) == 0)
{
Page::printApiResults(500,'No offers found !');
}
Page::printApiResults(200,'',['offers' => $offers]);
}
else
{
Page::printApiResults(500,'Incorrect sponsor id !');
}
}
/**
* @name getOfferDetails
* @description get offer details action
* @before init
*/
public function getOfferDetails($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$offerId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'offer-id'));
if($offerId > 0)
{
$fromNames = FromName::all(FromName::FETCH_ARRAY,['status = ? AND offer_id = ?',['Activated',$offerId]],['id','value']);
$subjects = Subject::all(Subject::FETCH_ARRAY,['status = ? AND offer_id = ?',['Activated',$offerId]],['id','value']);
$creatives = Creative::all(Creative::FETCH_ARRAY,['status = ? AND offer_id = ?',['Activated',$offerId]],['id','name']);
Page::printApiResults(200,'',['from-names' => $fromNames, 'subjects' => $subjects , 'creatives' => $creatives]);
}
else
{
Page::printApiResults(500,'Incorrect offer id !');
}
}
/**
* @name generateLinks
* @description generateLinks action
* @before init
*/
public function generateLinks($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$linkType = str_replace(['"','"'],"" ,$this->app->utils->arrays->get($parameters,'link-type'));
if($linkType != '')
{
$data = [];
$data['link-type'] = $linkType;
$data['offer-id'] = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'offer-id'));
$data['static-domain'] = str_replace(['"','"'],"" ,$this->app->utils->arrays->get($parameters,'static-domain'));
$data['send-type'] = str_replace(['"','"'],"" ,$this->app->utils->arrays->get($parameters,'send-type'));
$data['creative-id'] = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'creative-id'));
if($data['send-type'] == 'mta')
{
$data['vmta-id'] = preg_replace('/[^0-9|]/i', '',$this->app->utils->arrays->get($parameters,'vmta'));
}elseif($data['send-type'] == 'oapi')
{
$data['user-id'] = preg_replace('/[^0-9|]/i', '',$this->app->utils->arrays->get($parameters,'vmta'));
}
else
{
$data['smtp-user-id'] = preg_replace('/[^0-9|]/i', '',$this->app->utils->arrays->get($parameters,'vmta'));
}
# call iresponse api
$result = Api::call('Production','generateLinks',$data);
if(count($result) == 0)
{
Page::printApiResults(500,'No response found !');
}
if($result['httpStatus'] == 500)
{
Page::printApiResults(500,$result['message']);
}
if(count($result['data']) == 0)
{
Page::printApiResults(500,'No links generated !');
}
$table = "<table class='table table-bordered table-striped table-condensed'>";
$table .= "<thead><tr>";
$table .= "<td>Type</td><td>Link</td>";
$table .= "</tr></thead>";
$table .= "<tbody>";
foreach ($result['data'] as $key => $value) {
$table .= "<tr>";
$table .= "<td>".ucfirst(str_replace("-", " ", $key))."</td>";
$table .= "<td>" . $value. "</td>";
$table .= "</tr>";
}
/*
$table .= "<tr>";
$table .= "<td>Open link</td>";
$table .= "<td>" . $result['data']['open-link'] . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td>Click link</td>";
$table .= "<td>" . $result['data']['click-link'] . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td>Unsub link</td>";
$table .= "<td>" . $result['data']['unsub-link'] . "</td>";
$table .= "</tr>";
$table .= "<tr>";
$table .= "<td>Optout link</td>";
$table .= "<td>" . $result['data']['optout-link'] . "</td>";
$table .= "</tr>";
*/
$table .= "</tbody></table>";
Page::printApiResults(200,'',['links' => $table]);
}
else
{
Page::printApiResults(500,'Incorrect link encoding !');
}
}
/**
* @name getCreativeDetails
* @description get creative details action
* @before init
*/
public function getCreativeDetails($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$creativeId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'creative-id'));
if($creativeId > 0)
{
$creative = Creative::first(Creative::FETCH_ARRAY,['id = ?',$creativeId],['value']);
if(count($creative) == 0)
{
Page::printApiResults(500,'No creative found !');
}
$links = Link::all(Link::FETCH_ARRAY,['creative_id = ?',$creativeId]);
$html = html_entity_decode(base64_decode($creative['value']));
foreach ($links as $link)
{
if(strtolower($link['type']) == 'preview'){
$tag='[url]';
}elseif (strtolower($link['type']) == 'other1') {
$tag='[urlod1]';
}elseif (strtolower($link['type']) == 'other2') {
$tag='[urlod2]';
}elseif (strtolower($link['type']) == 'other3') {
$tag='[urlod3]';
}elseif (strtolower($link['type']) == 'other4') {
$tag='[urlod4]';
}else{
$tag='[unsub]';
}
//$tag = strtolower($link['type']) == 'preview' ? '[url]' : '[unsub]';
$html = str_replace($link['value'],'http://[domain]/' . $tag,$html);
}
$html .= PHP_EOL . '<br/><br/><span style="color:#888;font-size:11px;font-family:verdana;display:block;text-align:center;margin-top:10px">click <a href="http://[domain]/[optout]">here</a> to remove yourself from our emails list</span><br/><br/>';
Page::printApiResults(200,'',['creative' => $html]);
}
else
{
Page::printApiResults(500,'Incorrect creative id !');
}
}
/**
* @name getEmailsLists
* @description get emails lists action
* @before init
*/
public function getEmailsLists($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$data = [];
$dataProvidersIds = [];
$ispId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'isp-id'));
$dataProvidersIdsAll = $this->app->utils->arrays->get($parameters,'data-providers-ids',[]);
if($dataProvidersIdsAll!="" && count($dataProvidersIdsAll)>0){
foreach ($dataProvidersIdsAll as $key => $id) {
$id=preg_replace('/[^0-9]/i', '',$id);
if($id=="")continue;
$dataProvidersIds[]=$id;
}
}
if($ispId == 0)
{
Page::printApiResults(500,'Incorrect isp id !');
}
if(!is_array($dataProvidersIds) || count($dataProvidersIds) == 0)
{
Page::printApiResults(500,'Incorrect data providers ids !');
}
$lists = DataList::all(DataList::FETCH_ARRAY,['isp_id = ? AND data_provider_id IN ? AND status = ?',[$ispId,$dataProvidersIds,'Activated']],['id']);
if(!is_array($lists) || count($lists) == 0)
{
Page::printApiResults(500,'No data lists found !');
}
foreach ($lists as $list) { $data['data-lists-ids'][] = $list['id']; }
//
$data['offer-id'] = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'offer-id'));
$verticalIds = [];
if($this->app->utils->arrays->get($parameters,'verticals',[])!="" && count($this->app->utils->arrays->get($parameters,'verticals',[]))>0){
foreach ($this->app->utils->arrays->get($parameters,'verticals',[]) as $key => $id) {
$id=preg_replace('/[^0-9]/i', '',$id);
if($id=="")continue;
$verticalIds[]=$id;
}
}
$data['verticals-ids'] = $verticalIds;
$countrys = [];
if($this->app->utils->arrays->get($parameters,'countries',[])!="" && count($this->app->utils->arrays->get($parameters,'countries',[]))>0){
foreach ($this->app->utils->arrays->get($parameters,'countries',[]) as $key => $id) {
$id=str_replace(['"','"'],"" ,$id);
if($id=="")continue;
$countrys[]=$id;
}
}
$data['countries'] = $countrys;
$filters = [];
if($this->app->utils->arrays->get($parameters,'filters',[])!="" && count($this->app->utils->arrays->get($parameters,'filters',[]))>0){
foreach ($this->app->utils->arrays->get($parameters,'filters',[])as $key => $id) {
$key =str_replace(['"','"'],"" ,$key );
$id=str_replace(['"','"'],"" ,$id);
if($key=="" || $id=="")continue;
$filters[$key]=$id;
}
}
$data['filters'] = $filters;
$data['verticals-ids'] = is_array($data['verticals-ids']) && count($data['verticals-ids']) ? "'" . implode("','",$data['verticals-ids']) . "'" : '';
$data['countries'] = is_array($data['countries']) && count($data['countries']) ? "'" . implode("','",$data['countries']) . "'" : '';
# call iresponse api
$result = Api::call('Production','getEmailsLists',$data);
if(count($result) == 0)
{
Page::printApiResults(500,'No response found !');
}
if($result['httpStatus'] == 500)
{
Page::printApiResults(500,$result['message']);
}
if(count($result['data']) == 0)
{
Page::printApiResults(500,'No data lists found!');
}
Page::printApiResults(200,'',['lists' => $result['data']]);
}
/**
* @name uploadNegative
* @description uploadNegative action
* @before init
*/
public function uploadNegative()
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
# check for negative file
$files = $this->app->http->request->retrieve(Request::ALL,Request::FILES);
if(count($files) && key_exists('negative-file',$files))
{
$file = $this->app->utils->arrays->get($files,'negative-file');
if(intval($file['size']) > 0)
{
# start validations
if(intval($file['error']) > 0)
{
switch (intval($file['error']))
{
case UPLOAD_ERR_INI_SIZE:
{
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
}
case UPLOAD_ERR_FORM_SIZE:
{
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
}
case UPLOAD_ERR_PARTIAL:
{
$message = "The uploaded file was only partially uploaded";
break;
}
case UPLOAD_ERR_NO_TMP_DIR:
{
$message = "Missing a temporary folder";
break;
}
case UPLOAD_ERR_CANT_WRITE:
{
$message = "Failed to write file to disk";
break;
}
case UPLOAD_ERR_EXTENSION:
{
$message = "File upload stopped by extension";
break;
}
default:
{
$message = "Unknown upload error";
}
}
Page::printApiResults(500,"Negative upload error : $message !");
}
if(!in_array($file['type'],['text/plain']) || $file['size'] == 0)
{
Page::printApiResults(500,"Negative upload error : Unsupported file type !");
}
$negativeFile = $this->app->utils->strings->randomHex(8) . '.txt';
$this->app->utils->fileSystem->copyFileOrDirectory($file['tmp_name'],STORAGE_PATH . DS . 'negatives' . DS . $negativeFile);
Page::printApiResults(200,'Negtive file uploaded successfully !',['negative-file' => $negativeFile]);
}
else
{
Page::printApiResults(500,"Negative file is empty !");
}
}
else
{
Page::printApiResults(500,"Could not upload negative !");
}
}
/**
* @name deleteNegative
* @description deleteNegative action
* @before init
*/
public function deleteNegative($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$negativeFile = $this->app->utils->arrays->get($parameters,'negative-file','');
if($negativeFile != '' && file_exists(STORAGE_PATH . DS . 'negatives' . DS . $negativeFile))
{
$this->app->utils->fileSystem->deleteFile(STORAGE_PATH . DS . 'negatives' . DS . $negativeFile);
Page::printApiResults(200,'Negative file removed successfully !');
}
else
{
Page::printApiResults(500,'Negative file not found !');
}
}
/**
* @name getOfferDetails
* @description get offer details action
* @before init
*/
public function checkForSuppression($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$offerId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'offer-id'));
//$affiliateNetworkId = $this->app->utils->arrays->get($parameters,'affiliate-network-id');
$listsIds = $this->app->utils->arrays->get($parameters,'lists-ids');
if($offerId > 0)
{
$valid = false;
$offer = Offer::first(Offer::FETCH_ARRAY,['status = ? AND id = ?',['Activated',$offerId]],['id','last_suppression_updated_date','affiliate_network_id','name']);
//print_r($offer);
if($offer['name']=='WARMUP'){
Page::printApiResults(200,'',['valid' => true]);
}
$interval = intval($this->app->utils->arrays->get($this->app->getSetting('application'),'suppression_timer'));
if( count($offer))
{
//print_r($offer);
if($offer['last_suppression_updated_date'] != null && $offer['last_suppression_updated_date'] != '')
{
$today = strtotime(date('Y-m-d H:i:s'));
$suppDate = strtotime($offer['last_suppression_updated_date']);
$diff = (int) (($today - $suppDate) / 3600 / 24);
if($diff < $interval)
{
$valid = true;
}
}
if($valid){
$lists_ids="";
$Suppression = Suppression::all(Suppression::FETCH_ARRAY,["affiliate_network_id = ? AND offer_id = ? and finish_time >= current_date - interval '".$interval."' day ",[$offer['affiliate_network_id'],$offerId]],['lists_ids']);
//print_r($Suppression);
if(count($Suppression)){
foreach ($Suppression as $value) {
$lists_ids.=",".$value['lists_ids'].",";
}
}else{
$valid=false;
}
if(!empty($listsIds)){
foreach ($listsIds as $id) {
if (strpos($lists_ids, ','.$id.',') === false) {
$valid=false;
break;
}
}
}else{
$valid=false;
}
//print_r($listsIds);exit;
}
}else{
$valid=false;
}
Page::printApiResults(200,'',['valid' => $valid]);
}
else
{
Page::printApiResults(500,'Incorrect offer id !');
}
}
/**
* @name proceedSend
* @description proceed send/test action
* @before init
*/
public function proceedSend($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$parameters = $this->app->http->request->retrieve(Request::ALL,Request::POST);
if(count($parameters))
{
# drop
$parameters["headers"]=explode("\r\n__HEADER__SEPARATOR__\r\n", $parameters["headers"][0]);
$json = json_encode($parameters);
$type = strtolower(str_replace(' ','-',$this->app->utils->arrays->get($parameters,'type','test-all')));
$smtpMtaSwitch = $this->app->utils->arrays->get($parameters,'smtp-mta-type','mta');
# servers section
$serversIds = [];
$componentsIds = $this->app->utils->arrays->get($parameters,'selected-vmtas',[]);
$staticDomain = $this->app->utils->arrays->get($parameters,'static-domain','[domain]');
# auto responders
$autoRespondersIds = $this->app->utils->arrays->get($parameters,'auto-responders-ids',[]);
$autoRespondersIds = is_array($autoRespondersIds) && count($autoRespondersIds) > 0 ? implode(',',$autoRespondersIds) : '';
# negative
$negativeFile = $this->app->utils->arrays->get($parameters,'negative-file','');
# cpa section
$affiliateNetworkId = intval($this->app->utils->arrays->get($parameters,'affiliate-network-id',0));
$offerId = intval($this->app->utils->arrays->get($parameters,'offer-id',0));
# test emails section
$rcpts = array_filter(explode(PHP_EOL,$this->app->utils->arrays->get($parameters,'rcpts','')));
# emails lists section
$ispId = intval($this->app->utils->arrays->get($parameters,'isp-id'),0);
$dataProviderIds = $this->app->utils->arrays->get($parameters,'data-providers-ids',[]);
$listsIds = $this->app->utils->arrays->get($parameters,'lists',[]);
$dataStart = intval($this->app->utils->arrays->get($parameters,'data-start',0));
$dataCount = intval($this->app->utils->arrays->get($parameters,'data-count',0));
$dataDuplicate = intval($this->app->utils->arrays->get($parameters,'data-duplicate',1));
$dataDuplicate = $dataDuplicate == 0 ? 1 : $dataDuplicate;
$dataActualCount = $type == 'drop' ? $dataCount * $dataDuplicate : count($rcpts);
$receipientsCount = 0;
# begin validations
if($smtpMtaSwitch == 'smtp' && ($staticDomain == '' || $staticDomain == '[domain]'))
{
Page::printApiResults(500,'Static domain should not be empty nor [domain] !');
}
if(!is_array($componentsIds) || count($componentsIds) == 0)
{
Page::printApiResults(500,$smtpMtaSwitch == 'mta' ? 'No vmtas found !' : 'No smtp users found !');
}
$tmp = [];
foreach ($componentsIds as $value)
{
$tmp[] = intval($this->app->utils->arrays->get(explode('|',$value),1));
}
$componentsIds = array_filter(array_unique($tmp));
$components = $smtpMtaSwitch == 'mta' ? ServerVmta::all(ServerVmta::FETCH_ARRAY,['id IN ?',[$componentsIds]],['id','mta_server_id' => 'server_id'])
: SmtpUser::all(SmtpUser::FETCH_ARRAY,['id IN ?',[$componentsIds]],['id','smtp_server_id' => 'server_id']);
if(count($components) == 0)
{
Page::printApiResults(500,$smtpMtaSwitch == 'mta' ? 'No vmtas found !' : 'No smtp users found !');
}
if(count($components) != count($componentsIds))
{
Page::printApiResults(500,$smtpMtaSwitch == 'mta' ? 'Some vmtas are no longer available for you !' : 'Some smtp servers are no longer available for you !');
}
# collect servers ids
foreach ($components as $component)
{
$serversIds[] = intval($component['server_id']);
}
$serversIds = array_unique($serversIds);
if(count($serversIds) == 0)
{
Page::printApiResults(500,'No servers selected !');
}
$servers = $smtpMtaSwitch == 'mta' ? MtaServer::all(MtaServer::FETCH_ARRAY,['id IN ?',[$serversIds]],['id'])
: SmtpServer::all(SmtpServer::FETCH_ARRAY,['id IN ?',[$serversIds]],['id']);
if(count($servers) == 0)
{
Page::printApiResults(500,'No servers selected !');
}
if(count($servers) != count($serversIds))
{
Page::printApiResults(500,'Some mta servers are no longer available for you !');
}
# recipients validation
if(count($rcpts))
{
$invalidEmails = false;
foreach ($rcpts as $email)
{
$email = preg_replace( "/\r|\n/","", trim($email));
if(!empty($email) && !filter_var($email,FILTER_VALIDATE_EMAIL))
{
$invalidEmails = true;
}
if(filter_var($email, \FILTER_VALIDATE_EMAIL))
{
$receipientsCount++;
}
}
if($invalidEmails == true)
{
Page::printApiResults(500,'Please check your recipients , it looks like there is some invalid emails !');
}
}
if ($receipientsCount == 0)
{
Page::printApiResults(500,'Please insert at least one recipient!');
}
if($ispId == 0 || count(Isp::first(Isp::FETCH_ARRAY,['id = ?',$ispId],['id'])) == 0)
{
Page::printApiResults(500,'No isp selected !');
}
# check for empty placeholders
$placeholders = $this->app->utils->arrays->get($parameters,'placeholders');
$size = count($placeholders);
if($size > 0)
{
for ($index = 0; $index < $size; $index++)
{
if($this->app->utils->strings->contains($json,'[placeholder' . ($index + 1) . ']')
&& $this->app->utils->strings->trim(strval($placeholders[$index]) == ''))
{
Page::printApiResults(500,"Please check your placeholders " . ($index + 1) . " it's empty !");
}
}
}
# negative check
if($negativeFile != '' && !$this->app->utils->strings->contains($json,'[negative]'))
{
Page::printApiResults(500,"You have uploaded a negative file but you forgot its tag !");
}
# drop validations
if('drop' == $type)
{
if($this->app->utils->strings->contains($json,'[enc_b64_b]') || $this->app->utils->strings->contains($json,'[enc_hex_b]')
|| $this->app->utils->strings->contains($json,'[enc_qp_b]'))
{
foreach (['[enc_b64_','[enc_qp_','[enc_hex_'] as $val)
{
$match = [];
preg_match_all('~\\' . $val . 'b\\]([^{]*)\\' . $val . 'e\\]~i',$json,$match);
if(count($match) && count($match[1]))
{
foreach ($match[1] as $value)
{
if($this->app->utils->strings->contains($value,'[email]') || $this->app->utils->strings->contains($value,'[email_id]') ||
$this->app->utils->strings->contains($value,'[last_name]') || $this->app->utils->strings->contains($value,'[first_name]'))
{
Page::printApiResults(500,'Encryption tags should not contains email sensitive tags like [email] , [first_name] ...etc. !');
}
}
}
}
}
if($dataCount == 0)
{
Page::printApiResults(500,'Data count should be greater than 0 !');
}
if($affiliateNetworkId == 0 || count(AffiliateNetwork::first(AffiliateNetwork::FETCH_ARRAY,['id = ?',$affiliateNetworkId],['id'])) == 0)
{
Page::printApiResults(500,'No affiliate network selected !');
}
if($offerId == 0 || count(Offer::first(Offer::FETCH_ARRAY,['id = ?',$offerId],['id'])) == 0)
{
Page::printApiResults(500,'No offer selected !');
}
if(!is_array($dataProviderIds) || count($dataProviderIds) == 0)
{
Page::printApiResults(500,'No data provider selected !');
}
if(!is_array($listsIds) || count($listsIds) == 0)
{
Page::printApiResults(500,'No data lists selected !');
}
$lists = DataList::all(DataList::FETCH_ARRAY,['id IN ?',[$listsIds]],['id']);
if(count($lists) == 0)
{
Page::printApiResults(500,'No data lists selected !');
}
if(count($lists) != count($listsIds))
{
Page::printApiResults(500,'Some data lists are no longer available for you !');
}
}
# save the process into the database
$process = $smtpMtaSwitch == 'mta' ? new MtaProcess() : new SmtpProcess();
$process->setContent(base64_encode($json));
$process->setServersIds($this->app->utils->arrays->implode($serversIds));
$process->setProcessType($type);
$process->setStatus('In Progress');
$process->setStartTime(date('Y-m-d H:i:s'));
$process->setUserId(Authentication::getAuthenticatedUser()->getId());
$process->setTotalEmails($dataActualCount);
$process->setProgress(0);
$process->setAffiliateNetworkId($affiliateNetworkId);
$process->setOfferId($offerId);
$process->setIspId($ispId);
# negative case
if($negativeFile != '')
{
$process->setNegativeFilePath(STORAGE_PATH . DS . 'negatives' . DS . $negativeFile);
}
$process->setAutoRespondersIds($autoRespondersIds);
if($type == 'drop')
{
$process->setDataStart($dataStart);
$process->setDataCount($dataCount);
$process->setLists($this->app->utils->arrays->implode($listsIds));
}
$processId = 0;
try
{
$processId = $process->insert();
}
catch (Exception $e)
{
$e = new SystemException($e->getMessage(),500,$e);
$e->logError();
Page::printApiResults(500,'Could not save process information !');
}
if($processId == 0)
{
Page::printApiResults(500,'Could not save process information !');
}
$controller = $smtpMtaSwitch == 'mta' ? 'MtaProcesses' : 'SmtpProcesses';
$action = $type == 'drop' ? 'proceedDrop' : 'proceedTest';
//$action = $type == 'drop' ? 'proceedDropNew2' : 'proceedTest';
# register audit log
AuditLog::registerLog($processId,$controller,'Production Process',ucfirst($action));
# call iresponse api
Api::call($controller,$action,['process-id' => $processId],true);
Page::printApiResults(200,'Your process has been started !');
}
else
{
Page::printApiResults(500,'Parameters not found !');
}
}
/**
* @name proceedSendYahoo
* @description proceed send/test action
* @before init
*/
public function proceedSendYahoo($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$parameters = $this->app->http->request->retrieve(Request::ALL,Request::POST);
if(count($parameters))
{
# drop
$parameters["headers"]=explode("\r\n__HEADER__SEPARATOR__\r\n", $parameters["headers"][0]);
$json = json_encode($parameters);
$type = strtolower(str_replace(' ','-',$this->app->utils->arrays->get($parameters,'type','test-all')));
$smtpMtaSwitch = $this->app->utils->arrays->get($parameters,'smtp-mta-type','mta');
# servers section
$serversIds = [];
$componentsIds = $this->app->utils->arrays->get($parameters,'selected-vmtas',[]);
$staticDomain = $this->app->utils->arrays->get($parameters,'static-domain','[domain]');
# auto responders
$autoRespondersIds = $this->app->utils->arrays->get($parameters,'auto-responders-ids',[]);
$autoRespondersIds = is_array($autoRespondersIds) && count($autoRespondersIds) > 0 ? implode(',',$autoRespondersIds) : '';
# negative
$negativeFile = $this->app->utils->arrays->get($parameters,'negative-file','');
# cpa section
$affiliateNetworkId = intval($this->app->utils->arrays->get($parameters,'affiliate-network-id',0));
$offerId = intval($this->app->utils->arrays->get($parameters,'offer-id',0));
# test emails section
$rcpts = array_filter(explode(PHP_EOL,$this->app->utils->arrays->get($parameters,'rcpts','')));
# emails lists section
$ispId = intval($this->app->utils->arrays->get($parameters,'isp-id'),0);
$dataProviderIds = $this->app->utils->arrays->get($parameters,'data-providers-ids',[]);
$listsIds = $this->app->utils->arrays->get($parameters,'lists',[]);
$dataStart = intval($this->app->utils->arrays->get($parameters,'data-start',0));
$dataCount = intval($this->app->utils->arrays->get($parameters,'data-count',0));
$dataDuplicate = intval($this->app->utils->arrays->get($parameters,'data-duplicate',1));
$dataDuplicate = $dataDuplicate == 0 ? 1 : $dataDuplicate;
$dataActualCount = $type == 'drop' ? $dataCount * $dataDuplicate : count($rcpts);
$receipientsCount = 0;
# begin validations
if($smtpMtaSwitch == 'smtp' && ($staticDomain == '' || $staticDomain == '[domain]'))
{
Page::printApiResults(500,'Static domain should not be empty nor [domain] !');
}
if(!is_array($componentsIds) || count($componentsIds) == 0)
{
Page::printApiResults(500,$smtpMtaSwitch == 'mta' ? 'No vmtas found !' : 'No smtp users found !');
}
$tmp = [];
foreach ($componentsIds as $value)
{
$tmp[] = intval($this->app->utils->arrays->get(explode('|',$value),1));
}
$componentsIds = array_filter(array_unique($tmp));
$components = $smtpMtaSwitch == 'mta' ? ServerVmta::all(ServerVmta::FETCH_ARRAY,['id IN ?',[$componentsIds]],['id','mta_server_id' => 'server_id'])
: SmtpUser::all(SmtpUser::FETCH_ARRAY,['id IN ?',[$componentsIds]],['id','smtp_server_id' => 'server_id']);
if(count($components) == 0)
{
Page::printApiResults(500,$smtpMtaSwitch == 'mta' ? 'No vmtas found !' : 'No smtp users found !');
}
if(count($components) != count($componentsIds))
{
Page::printApiResults(500,$smtpMtaSwitch == 'mta' ? 'Some vmtas are no longer available for you !' : 'Some smtp servers are no longer available for you !');
}
# collect servers ids
foreach ($components as $component)
{
$serversIds[] = intval($component['server_id']);
}
$serversIds = array_unique($serversIds);
if(count($serversIds) == 0)
{
Page::printApiResults(500,'No servers selected !');
}
$servers = $smtpMtaSwitch == 'mta' ? MtaServer::all(MtaServer::FETCH_ARRAY,['id IN ?',[$serversIds]],['id'])
: SmtpServer::all(SmtpServer::FETCH_ARRAY,['id IN ?',[$serversIds]],['id']);
if(count($servers) == 0)
{
Page::printApiResults(500,'No servers selected !');
}
if(count($servers) != count($serversIds))
{
Page::printApiResults(500,'Some mta servers are no longer available for you !');
}
# recipients validation
if(count($rcpts))
{
$invalidEmails = false;
foreach ($rcpts as $email)
{
$email = preg_replace( "/\r|\n/","", trim($email));
if(!empty($email) && !filter_var($email,FILTER_VALIDATE_EMAIL))
{
$invalidEmails = true;
}
if(filter_var($email, \FILTER_VALIDATE_EMAIL))
{
$receipientsCount++;
}
}
if($invalidEmails == true)
{
Page::printApiResults(500,'Please check your recipients , it looks like there is some invalid emails !');
}
}
if ($receipientsCount == 0)
{
Page::printApiResults(500,'Please insert at least one recipient!');
}
if($ispId == 0 || count(Isp::first(Isp::FETCH_ARRAY,['id = ?',$ispId],['id'])) == 0)
{
Page::printApiResults(500,'No isp selected !');
}
# check for empty placeholders
$placeholders = $this->app->utils->arrays->get($parameters,'placeholders');
$size = count($placeholders);
if($size > 0)
{
for ($index = 0; $index < $size; $index++)
{
if($this->app->utils->strings->contains($json,'[placeholder' . ($index + 1) . ']')
&& $this->app->utils->strings->trim(strval($placeholders[$index]) == ''))
{
Page::printApiResults(500,"Please check your placeholders " . ($index + 1) . " it's empty !");
}
}
}
# negative check
if($negativeFile != '' && !$this->app->utils->strings->contains($json,'[negative]'))
{
Page::printApiResults(500,"You have uploaded a negative file but you forgot its tag !");
}
# drop validations
if('drop' == $type)
{
if($this->app->utils->strings->contains($json,'[enc_b64_b]') || $this->app->utils->strings->contains($json,'[enc_hex_b]')
|| $this->app->utils->strings->contains($json,'[enc_qp_b]'))
{
foreach (['[enc_b64_','[enc_qp_','[enc_hex_'] as $val)
{
$match = [];
preg_match_all('~\\' . $val . 'b\\]([^{]*)\\' . $val . 'e\\]~i',$json,$match);
if(count($match) && count($match[1]))
{
foreach ($match[1] as $value)
{
if($this->app->utils->strings->contains($value,'[email]') || $this->app->utils->strings->contains($value,'[email_id]') ||
$this->app->utils->strings->contains($value,'[last_name]') || $this->app->utils->strings->contains($value,'[first_name]'))
{
Page::printApiResults(500,'Encryption tags should not contains email sensitive tags like [email] , [first_name] ...etc. !');
}
}
}
}
}
if($dataCount == 0)
{
Page::printApiResults(500,'Data count should be greater than 0 !');
}
if($affiliateNetworkId == 0 || count(AffiliateNetwork::first(AffiliateNetwork::FETCH_ARRAY,['id = ?',$affiliateNetworkId],['id'])) == 0)
{
Page::printApiResults(500,'No affiliate network selected !');
}
if($offerId == 0 || count(Offer::first(Offer::FETCH_ARRAY,['id = ?',$offerId],['id'])) == 0)
{
Page::printApiResults(500,'No offer selected !');
}
if(!is_array($dataProviderIds) || count($dataProviderIds) == 0)
{
Page::printApiResults(500,'No data provider selected !');
}
if(!is_array($listsIds) || count($listsIds) == 0)
{
Page::printApiResults(500,'No data lists selected !');
}
$lists = DataList::all(DataList::FETCH_ARRAY,['id IN ?',[$listsIds]],['id']);
if(count($lists) == 0)
{
Page::printApiResults(500,'No data lists selected !');
}
if(count($lists) != count($listsIds))
{
Page::printApiResults(500,'Some data lists are no longer available for you !');
}
}
# save the process into the database
$process = $smtpMtaSwitch == 'mta' ? new MtaProcess() : new SmtpProcess();
$process->setContent(base64_encode($json));
$process->setServersIds($this->app->utils->arrays->implode($serversIds));
$process->setProcessType($type);
$process->setStatus('In Progress');
$process->setStartTime(date('Y-m-d H:i:s'));
$process->setUserId(Authentication::getAuthenticatedUser()->getId());
$process->setTotalEmails($dataActualCount);
$process->setProgress(0);
$process->setAffiliateNetworkId($affiliateNetworkId);
$process->setOfferId($offerId);
$process->setIspId($ispId);
# negative case
if($negativeFile != '')
{
$process->setNegativeFilePath(STORAGE_PATH . DS . 'negatives' . DS . $negativeFile);
}
$process->setAutoRespondersIds($autoRespondersIds);
if($type == 'drop')
{
$process->setDataStart($dataStart);
$process->setDataCount($dataCount);
$process->setLists($this->app->utils->arrays->implode($listsIds));
}
$processId = 0;
try
{
$processId = $process->insert();
}
catch (Exception $e)
{
$e = new SystemException($e->getMessage(),500,$e);
$e->logError();
Page::printApiResults(500,'Could not save process information !');
}
if($processId == 0)
{
Page::printApiResults(500,'Could not save process information !');
}
$controller = $smtpMtaSwitch == 'mta' ? 'MtaProcesses' : 'SmtpProcesses';
$action = $type == 'drop' ? 'proceedYahooDrop' : 'proceedYahooTest';
# register audit log
AuditLog::registerLog($processId,$controller,'Production Process',ucfirst($action));
# call iresponse api
Api::call($controller,$action,['process-id' => $processId],true);
Page::printApiResults(200,'Your process has been started !');
}
else
{
Page::printApiResults(500,'Parameters not found !');
}
}
/**
* @name getProcessServers
* @description getProcessServers action
* @before init
*/
public function getProcessServers($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$type = $this->app->utils->arrays->get($parameters,'type');
$method = '';
switch ($type)
{
case 'mt' : $method = 'mtaTests'; break;
case 'md' : $method = 'mtaDrops'; break;
case 'st' : $method = 'smtpTests'; break;
case 'sd' : $method = 'smtpDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processId = intval($this->app->utils->arrays->get($parameters,'id'));
if($processId > 0)
{
if($type == 'mt' || $type == 'st')
{
$table = $type == 'md' || $type == 'mt' ? 'mta_processes' : 'smtp_processes';
$serversTable = $type == 'md' || $type == 'mt' ? 'mta_servers' : 'smtp_servers';
$columns = ['t.id' => 'id',"replace((SELECT string_agg(name, ',') FROM admin.{$serversTable} s WHERE s.id = ANY (string_to_array(t.servers_ids,',')::int[])),',',' ')" => 'mta_servers_names'];
$query = $this->app->database('system')->query()->from("production.{$table} t",$columns);
$test = $query->where("t.id = ? AND t.process_type NOT LIKE 'drop'",[$processId])->order('t.id',Query::DESC)->first();
if(count($test) == 0)
{
Page::printApiResults(500,'No process found !');
}
$results = "<table class='table table-bordered table-striped table-condensed'>";
$results .= "<thead><tr>";
$results .= "<td>Id</td><td>Servers</td>";
$results .= "</tr></thead>";
$results .= "<tbody>";
$results .= "<tr>";
$results .= "<td>{$test['id']}</td>";
$results .= "<td>" . str_replace(' ','<br/>',$test['mta_servers_names']) . "</td>";
$results .= "</tr>";
$results .= "</tbody></table>";
}
else
{
$columns = ['i.sent_total','i.delivered','i.hard_bounced','i.soft_bounced'];
$processComponents = $type == 'md' || $type == 'mt' ? $this->app->database('system')->query()->from('production.mta_processes_ips i',$columns)
->join('admin.servers_vmtas v','v.id = i.server_vmta_id',['v.ip' => 'component','v.mta_server_name' => 'server'])
->where('i.process_id = ?',$processId)
->all()
: $this->app->database('system')->query()->from('production.smtp_processes_users i',$columns)
->join('admin.smtp_users u','u.id = i.smtp_user_id',['u.username' => 'component','u.smtp_server_name' => 'server'])
->where('i.process_id = ?',$processId)
->all();
if(count($processComponents) == 0)
{
Page::printApiResults(500,'No stats found for this drop !');
}
$stats = [];
$componentLabel = $type == 'md' || $type == 'mt' ? 'Ip' : 'SMTP User';
foreach ($processComponents as $processComponent)
{
if($processComponent['server'] != '')
{
if(!key_exists($processComponent['server'],$stats))
{
$stats[$processComponent['server']] = [
'ips' => [],
'total' => 0,
'delivered' => 0,
'soft_bounced' => 0,
'hard_bounced' => 0
];
}
$stats[$processComponent['server']]['ips'][] = [
'ip' => $processComponent['component'],
'total' => intval($processComponent['sent_total']),
'delivered' => intval($processComponent['delivered']),
'soft_bounced' => intval($processComponent['soft_bounced']),
'hard_bounced' => intval($processComponent['hard_bounced'])
];
$stats[$processComponent['server']]['total'] = $stats[$processComponent['server']]['total'] + intval($processComponent['sent_total']);
$stats[$processComponent['server']]['delivered'] = $stats[$processComponent['server']]['delivered'] + intval($processComponent['delivered']);
$stats[$processComponent['server']]['soft_bounced'] = $stats[$processComponent['server']]['soft_bounced'] + intval($processComponent['soft_bounced']);
$stats[$processComponent['server']]['hard_bounced'] = $stats[$processComponent['server']]['hard_bounced'] + intval($processComponent['hard_bounced']);
}
}
if(count($stats) == 0)
{
Page::printApiResults(500,'No stats found for this process !');
}
$download_data="";
$results = '<div style="float: right;"><a href="data:text/plain,#_downloadData_#" target="_blank" download="servers_list_'.$processId.'.csv" class="btn btn-outline blue"><i class="fa fa-terminal"></i> Download</a></div><br>
<div class="panel-group accordion scrollable" id="process-stats" style="margin-top: 20px;">';
$index = 0;
foreach ($stats as $server => $stat)
{
$download_data="Server : " . $server . "\n";
$download_data.="Ip;Total;Delivered;Soft Bounced;Hard Bounced\n";
$results .= '<div class="panel panel-default">';
$results .= '<div class="panel-heading">';
$results .= '<h4 class="panel-title">';
$results .= '<a class="accordion-toggle" data-toggle="collapse" data-parent="#drop-stats" href="#stats-' . $server . '"> Server : ' . $server . ' </a>';
$results .= '</h4>';
$results .= '</div>';
$collapse = $index == 0 ? 'in' : 'collapse';
$results .= '<div id="stats-' . $server . '" class="panel-collapse ' . $collapse . '">';
$results .= '<div class="panel-body">';
$results .= "<table class='table table-bordered table-striped table-condensed'>";
$results .= "<thead><tr>";
$results .= "<td><b>{$componentLabel}</b></td><td><b>Total</b></td><td><b>Delivered</b></td><td><b>Soft Bounced</b></td><td><b>Hard Bounced</b></td>";
$results .= "</tr></thead>";
$results .= "<tbody>";
foreach ($stat['ips'] as $ip)
{
$results .= "<tr>";
$results .= "<td>{$ip['ip']}</td>";
$results .= "<td>{$ip['total']}</td>";
$results .= "<td>{$ip['total']}</td>";
$results .= "<td>{$ip['soft_bounced']}</td>";
$results .= "<td>{$ip['hard_bounced']}</td>";
$results .= "</tr>";
$download_data.=$ip['ip'].";".$ip['total'].";".$ip['total'].";".$ip['soft_bounced'].";".$ip['hard_bounced']."\n";
}
$results .= "<tr>";
$results .= "<td><b>Total</b></td>";
$results .= "<td><b>{$stat['total']}</b></td>";
$results .= "<td><b>{$stat['delivered']}</b></td>";
$results .= "<td><b>{$stat['soft_bounced']}</b></td>";
$results .= "<td><b>{$stat['hard_bounced']}</b></td>";
$results .= "</tr>";
$download_data.="Total;".$stat['total'].";".$stat['total'].";".$stat['soft_bounced'].";".$stat['hard_bounced']."\n";
$results .= "</tbody></table>";
$results .= '</div>';
$results .= '</div>';
$results .= '</div>';
$index++;
}
$results .= '</div>';
$results =str_replace('#_downloadData_#',strtr(rawurlencode($download_data), ['%21'=>'!', '%2A'=>'*', '%27'=>"'", '%28'=>'(', '%29'=>')']),$results);
}
//print_r($download_data);exit;
Page::printApiResults(200,'',['servers' => $results]);
}
else
{
Page::printApiResults(500,'Incorrect process id !');
}
}
/**
* @name getProcessLists
* @description getProcessLists action
* @before init
*/
public function getProcessLists($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$type = $this->app->utils->arrays->get($parameters,'type');
$method = '';
switch ($type)
{
case 'md' : $method = 'mtaDrops'; break;
case 'sd' : $method = 'smtpDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$id = intval($this->app->utils->arrays->get($parameters,'id'));
if($id > 0)
{
$process = $type == 'md' || $type == 'mt' ? MtaProcess::first(MtaProcess::FETCH_ARRAY,['id = ?',$id],['id','lists','content'],'id','DESC')
: SmtpProcess::first(SmtpProcess::FETCH_ARRAY,['id = ?',$id],['id','lists','content'],'id','DESC');
if(count($process) == 0)
{
Page::printApiResults(500,'No process found !');
}
$datalists = [];
$res = DataList::all(DataList::FETCH_ARRAY,['status = ?','Activated'],['id','name']);
foreach ($res as $row)
{
$datalists[$row['id']] = $row['name'];
}
$table = "<table class='table table-bordered table-striped table-condensed'>";
$table .= "<thead><tr>";
$table .= "<td>Data Lists</td>";
$table .= "</tr></thead>";
$table .= "<tbody>";
if(count($process))
{
$json = json_decode(base64_decode($process['content']),true);
$filters = '(';
$filters .= array_key_exists('fresh-filter',$json) && $this->app->utils->arrays->get($json,'fresh-filter') == 'on' ? ' Fresh ,' : '';
$filters .= array_key_exists('clean-filter',$json) && $this->app->utils->arrays->get($json,'clean-filter') == 'on' ? ' Clean ,' : '';
$filters .= array_key_exists('openers-filter',$json) && $this->app->utils->arrays->get($json,'openers-filter') == 'on' ? ' Openers ,' : '';
$filters .= array_key_exists('clickers-filter',$json) && $this->app->utils->arrays->get($json,'clickers-filter') == 'on' ? ' Clickers ,' : '';
$filters .= array_key_exists('leaders-filter',$json) && $this->app->utils->arrays->get($json,'leaders-filter') == 'on' ? ' Leaders ,' : '';
$filters .= array_key_exists('unsubs-filter',$json) && $this->app->utils->arrays->get($json,'unsubs-filter') == 'on' ? ' Unsubscribers ,' : '';
$filters .= array_key_exists('optouts-filter',$json) && $this->app->utils->arrays->get($json,'optouts-filter') == 'on' ? ' Optouts ,' : '';
$filters .= array_key_exists('repliers-filter',$json) && $this->app->utils->arrays->get($json,'repliers-filter') == 'on' ? ' Repliers ,' : '';
$filters = $filters == '(' ? '( All )' : rtrim($filters,' ,') . ' )';
$table .= "<tr><td>";
foreach (explode(',',$process['lists']) as $listId)
{
if(key_exists($listId,$datalists))
{
$table .= "{$datalists[$listId]} {$filters} <br/>";
}
}
$table = rtrim($table,'<br/>');
$table .= "</td>";
$table .= "</tr>";
}
$table .= "</tbody></table>";
Page::printApiResults(200,'',['lists' => $table]);
}
else
{
Page::printApiResults(500,'Incorrect process id !');
}
}
/**
* @name executeProcessAction
* @description executeProcessAction action
* @before init
*/
public function executeProcessAction($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$type = $this->app->utils->arrays->get($parameters,'type');
$method = '';
switch ($type)
{
case 'mt' : $method = 'mtaTests'; break;
case 'md' : $method = 'mtaDrops'; break;
case 'st' : $method = 'smtpTests'; break;
case 'sd' : $method = 'smtpDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processesIds = $this->app->utils->arrays->get($parameters,'processes-ids',[]);
if(!is_array($processesIds) || count($processesIds) == 0)
{
Page::printApiResults(500,'No processes found !');
}
# call iresponse api
$result = Api::call('Production','executeProcessAction',$parameters);
if(count($result) == 0)
{
Page::printApiResults(500,'No response found !');
}
if($result['httpStatus'] == 500)
{
Page::printApiResults(500,$result['message']);
}
Page::printApiResults(200,$result['message']);
}
/**
* @name getProcess
* @description getProcess action
* @before init
*/
public function getProcess($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$processType = $this->app->utils->arrays->get($parameters,'process-type');
# check for permissions
$method = '';
switch ($processType)
{
case 'mt' : $method = 'mtaTests'; break;
case 'md' : $method = 'mtaDrops'; break;
case 'st' : $method = 'smtpTests'; break;
case 'sd' : $method = 'smtpDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processId = intval($this->app->utils->arrays->get($parameters,'process-id'));
$process = $processType == 'mt' || $processType == 'md' ? MtaProcess::first(MtaProcess::FETCH_ARRAY,['id = ?',$processId],['user_id','content'])
: SmtpProcess::first(SmtpProcess::FETCH_ARRAY,['id = ?',$processId],['content']);
if(count($process) == 0)
{
Page::printApiResults(500,'No process found !');
}
if(Authentication::getAuthenticatedUser()->getMasterAccess() != 'Enabled')
{
if(intval($process['user_id']) != intval(Authentication::getAuthenticatedUser()->getId()))
{
Page::printApiResults(500,'No process found !');
}
}
# inject process type
$process = json_decode(base64_decode($process['content']),true);
$process['process-type'] = $processType;
# return process array
Page::printApiResults(200,'',['process' => $process]);
}
/**
* @name getAutoReponder
* @description getAutoReponder action
* @before init
*/
public function getAutoReponder($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
$access = Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'AutoResponders','create');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$autoResponderId = intval($this->app->utils->arrays->get($parameters,'auto-responder-id'));
$autoResponder = AutoResponder::first(AutoResponder::FETCH_ARRAY,['id = ?',$autoResponderId],['content']);
if(count($autoResponder) == 0)
{
Page::printApiResults(500,'No auto responder found !');
}
# return process array
Page::printApiResults(200,'',['auto-responder' => json_decode(base64_decode($autoResponder['content']),true)]);
}
/**
* @name getMtaBounceLogs
* @description getMtaBounceLogs action
* @before init
*/
public function getMtaBounceLogs($parameters = [])
{
# check for authentication
if(!Authentication::isUserAuthenticated())
{
Page::printApiResults(401,'Only logged-in access allowed !');
}
# check users roles
Authentication::checkUserRoles();
# check for permissions
$processType = $this->app->utils->arrays->get($parameters,'process-type');
# check for permissions
$method = '';
switch ($processType)
{
case 'mt' : $method = 'MtaTests'; break;
case 'md' : $method = 'MtaDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'Production',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processesIds = $this->app->utils->arrays->get($parameters,'processes-ids',[]);
if(!is_array($processesIds) || count($processesIds) == 0)
{
Page::printApiResults(500,'No processes ids found !');
}
# call iresponse api
$result = Api::call('Pmta','getBounceLogs',['processes-ids' => $processesIds,'processes-type' => $processType]);
if(count($result) == 0)
{
Page::printApiResults(500,'No response found !');
}
if($result['httpStatus'] == 500)
{
Page::printApiResults(500,$result['message']);
}
$content = $this->app->utils->arrays->toCsv($result['data']);
$random = $this->app->utils->strings->random(8,true,true,false,false);
Page::printApiResults(200,'',['content' => $content,'name' => 'pmta_logs_' . $random . '.csv']);
}
/**
* @name MtaUpdateSent
* @description check email if we have it action
* @before init
*/
public function MtaUpdateSent($parameters = [])
{
$processId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'process-id'));
$sent_total = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'sent-total'));
$vmtas_sent = $this->app->utils->arrays->get($parameters,'vmtas-sent',[]);
if(count($vmtas_sent) > 0 && $processId > 0 )
{
foreach ($vmtas_sent as $server_vmta_id => $sent) {
$server_vmta_id = preg_replace('/[^0-9]/i', '',$server_vmta_id);
$sent = preg_replace('/[^0-9]/i', '',$sent);
if($server_vmta_id=="" || $sent=="" )continue;
$this->app->database('system')->execute("UPDATE production.mta_processes_ips SET sent_total = {$sent} WHERE server_vmta_id = {$server_vmta_id} and process_id = {$processId}");
}
//$this->app->database('system')->execute("UPDATE production.mta_processes SET finish_time = now()::timestamp(0), status= 'Completed' WHERE id = {$processId} and status='In Progress'");
Page::printApiResultsThenLogout(200,' correct ! ');
}
else if(count($sent_total) > 0 && $processId > 0 )
{
$this->app->database('system')->execute("UPDATE production.mta_processes SET progress = progress+{$sent_total} WHERE id = {$processId}");
Page::printApiResultsThenLogout(200,' correct ! ');
}
else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
}