Files
fmgapp/webservices/Oapi.php

1423 lines
50 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 Oapi.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\OapiUser as OapiUser;
use IR\App\Models\Production\OapiProcess as OapiProcess;
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\Creative as Creative;
use IR\App\Models\Affiliate\Link as Link;
use IR\App\Models\Lists\DataList as DataList;
use IR\App\Models\Production\TeamAuthorisation as TeamAuthorisation;
# orm
use IR\Orm\Query as Query;
# http
use IR\Http\Request as Request;
/**
* @name Oapi
* @description Oapi WebService
*/
class Oapi 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 getProcessServers
* @description getProcessServers action
* @before init
*/
public function checkToken($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(),'OapiUsers','add');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$usersIds = $this->app->utils->arrays->get($parameters,'users-ids',[]);
if(!is_array($usersIds) || count($usersIds) == 0)
{
Page::printApiResults(500,'No user ids found !');
}
$usersIds=array_filter(array_unique($usersIds));
$allUsers=[];
$allUsers = OapiUser::all(OapiUser::FETCH_ARRAY,['id IN ?',[$usersIds]],['id',"email","password","tenant_id","client_id","secret_id","token","code","refresh_token"]);
if(count($allUsers) == 0)
{
Page::printApiResults(500,'No user found for this ids !');
}
$results = "<table class='table table-bordered table-striped table-condensed'>";
$results .= "<thead><tr>";
$results .= "<td>Id</td>";
$results .= "<td>Email</td>";
$results .= "<td>Password</td>";
$results .= "<td>Status</td>";
$results .= "</tr></thead>";
$results .= "<tbody>";
foreach ($allUsers as $user) {
$status="";
$login_url ="https://login.microsoftonline.com/".$user["tenant_id"]."/oauth2/v2.0/authorize";
if($user["token"]!=""){
if(!$this->checkTokenKey($user["token"])){
$newtoken=$this->getNewToken($user);
if($newtoken!=""){
$OapiUser = new OapiUser();
$OapiUser->setId(intval($user["id"]));
$OapiUser->load();
$OapiUser->setToken(trim($newtoken));
$OapiUser->setMessage('ok');
$OapiUser->update();
$status="ok";
}else{
$params = array ('client_id' =>$user["client_id"],
'redirect_uri' =>'https://sonetmart.shop/saveOfficeTokenNew.php',
'response_type' =>'code',
'scope' =>'User.Read profile openid email Mail.Send Mail.Read offline_access',
'state'=>$user["id"]
);
$authURL=$login_url.'?'.http_build_query ($params);
$status="<a target='_blank' href='".$authURL."'>Get Token</a>";
$OapiUser = new OapiUser();
$OapiUser->setId(intval($user["id"]));
$OapiUser->load();
$OapiUser->setMessage('check');
$OapiUser->update();
}
}else{
$OapiUser = new OapiUser();
$OapiUser->setId(intval($user["id"]));
$OapiUser->load();
$OapiUser->setMessage('ok');
$OapiUser->update();
$status="ok";
}
}else{
/*
$params = array ('client_id' =>$user["client_id"],
'redirect_uri' =>'https://sonetmart.shop/saveOfficeTokenNew.php',
'response_type' =>'code',
'scope' =>'User.Read profile openid email Mail.Send offline_access',
'state'=>$user["id"]
);
$authURL=$login_url.'?'.http_build_query ($params);
$status="<a target='_blank' href='".$authURL."'>Get Token</a>";
*/
if(!$this->checkTokenKeyNew($user)){
$status="check";
$OapiUser = new OapiUser();
$OapiUser->setId(intval($user["id"]));
$OapiUser->load();
$OapiUser->setMessage('check');
$OapiUser->update();
}else{
$OapiUser = new OapiUser();
$OapiUser->setId(intval($user["id"]));
$OapiUser->load();
$OapiUser->setMessage('ok');
$OapiUser->update();
$status="ok";
}
}
$results .= "<tr><td>".$user["id"]."</td><td>".$user["email"]."</td><td>".$user["password"]."</td><td>".$status."</td></tr>";
}
$results .= "</tbody></table>";
Page::printApiResults(200,'',['users' => $results]);
}
public function checkTokenKey($token){
$ch = curl_init ();
curl_setopt ($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '.$token,'Conent-type: application/json'));
curl_setopt ($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/me/");
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$response=curl_exec ($ch);
$rez = json_decode ($response,true);
if(isset($rez["mail"])){
return true;
}
return false;
}
public function checkTokenKeyNew($user){
$url = 'https://login.microsoftonline.com/' . $user["tenant_id"] . '/oauth2/v2.0/token';
$form_params = [
'grant_type' => 'client_credentials',
'tenant' => $user["tenant_id"] ,
'client_id' => $user["client_id"],
'client_secret' => $user["secret_id"],
'scope' => 'https://graph.microsoft.com/.default',
];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($form_params));
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$responseCode = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$token=json_decode($response ,true);
//print_r($token);
curl_close($ch);
if (!isset($token["access_token"])) return false;
$ch = curl_init ();
curl_setopt ($ch, CURLOPT_HTTPHEADER, array ('Authorization: Bearer '.$token["access_token"],'Conent-type: application/json'));
//curl_setopt ($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/me/");
curl_setopt ($ch, CURLOPT_URL, "https://graph.microsoft.com/v1.0/users/".$user["email"]);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$response=curl_exec ($ch);
//print_r($response);
$rez = json_decode ($response,true);
if(isset($rez["mail"])){
return true;
}
return false;
}
public function getNewToken($user){
$ch = curl_init('https://login.microsoftonline.com/common/oauth2/v2.0/token');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "client_id=".$user["client_id"]."&scope=User.Read profile openid email Mail.Read Mail.Send offline_access&code=".$user["code"]."&grant_type=refresh_token&refresh_token=".$user["refresh_token"]."&client_secret=".$user["secret_id"]."");
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
$rez = json_decode ($response,true);
if(isset($rez["access_token"])){
return $rez["access_token"];
}
return false;
}
/**
* @name deleteAttachment
* @description deleteNegative action
* @before init
*/
public function deleteAttachment($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(),'OapiProduction','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$negativeFile = $this->app->utils->arrays->get($parameters,'attachment-file','');
if($negativeFile != '' && file_exists(STORAGE_PATH . DS . 'attachment' . DS . $negativeFile))
{
$this->app->utils->fileSystem->deleteFile(STORAGE_PATH . DS . 'attachment' . DS . $negativeFile);
Page::printApiResults(200,'Attachment file removed successfully !');
}
else
{
Page::printApiResults(500,'Attachment file not found !');
}
}
/**
* @name uploadNegative
* @description uploadNegative action
* @before init
*/
public function uploadAttachment()
{
# 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(),'OapiProduction','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
# check for attachment file
$files = $this->app->http->request->retrieve(Request::ALL,Request::FILES);
if(count($files) && key_exists('attachment-file',$files))
{
$file = $this->app->utils->arrays->get($files,'attachment-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,"attachment upload error : $message !");
}
if(!in_array($file['type'],['text/plain']) || $file['size'] == 0)
{
Page::printApiResults(500,"attachment upload error : Unsupported file type !");
}
$negativeFile = $this->app->utils->strings->randomHex(8) . '.txt';
$this->app->utils->fileSystem->copyFileOrDirectory($file['tmp_name'],STORAGE_PATH . DS . 'attachment' . DS . $negativeFile);
Page::printApiResults(200,'Attachment file uploaded successfully !',['attachment-file' => $negativeFile]);
}
else
{
Page::printApiResults(500,"Attachment file is empty !");
}
}
else
{
Page::printApiResults(500,"Could not upload attachment !");
}
}
/**
* @name OapiProceedSend
* @description proceed send/test action
* @before init
*/
public function OapiProceedSend($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(),'OapiProduction','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$parameters = $this->app->http->request->retrieve(Request::ALL,Request::POST);
//print_r($parameters);exit;
if(count($parameters))
{
# drop
$json = json_encode($parameters);
$type = strtolower(str_replace(' ','-',$this->app->utils->arrays->get($parameters,'type','test-all')));
//print_r($json);exit;
# servers section
$serversIds = [];
$serversIds = $this->app->utils->arrays->get($parameters,'users',[]);
$staticDomain = $this->app->utils->arrays->get($parameters,'static-domain','[domain]');
$fromName = $this->app->utils->arrays->get($parameters,'from-name','');
$subject = $this->app->utils->arrays->get($parameters,'subject','');
# negative
$negativeFile = $this->app->utils->arrays->get($parameters,'negative-file','');
# attachment
$attachmentFile = $this->app->utils->arrays->get($parameters,'attachment-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;
$tmp = [];
foreach ($serversIds as $value)
{
$tmp[] = intval($value);
}
$serversIds = array_filter(array_unique($tmp));
if(count($serversIds) == 0)
{
Page::printApiResults(500,'No user selected !');
}
$servers = OapiUser::all(OapiUser::FETCH_ARRAY,['id IN ?',[$serversIds]],['id']);
if(count($servers) == 0)
{
Page::printApiResults(500,'No user selected !');
}
if(count($servers) != count($serversIds))
{
Page::printApiResults(500,'Some user are no longer available for you !');
}
if($fromName == "")
{
Page::printApiResults(500,'Please insert from name!');
}
if($subject == "")
{
Page::printApiResults(500,'Please insert subject!');
}
# 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 = new OapiProcess() ;
$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);
}
# attachment case
if($attachmentFile != '')
{
$process->setNegativeFilePath(STORAGE_PATH . DS . 'attachment' . DS . $attachmentFile);
}
$process->setAutoRespondersIds('');
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 = 'OapiProcesses' ;
$action = $type == 'drop' ? 'proceedDrop' : 'proceedTest';
# register audit log
AuditLog::registerLog($processId,$controller,'Production Process',ucfirst($action));
# call iresponse api
Api::callapi($controller,$action,['process-id' => $processId],true);
Page::printApiResults(200,'Your process has been started !');
}
else
{
Page::printApiResults(500,'Parameters not found !');
}
}
/**
* @name getOapiProcessUsers
* @description getRdpProcessServers action
* @before init
*/
public function getOapiProcessUsers($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 'ot' : $method = 'oapiTests'; break;
case 'od' : $method = 'oapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'OapiProduction',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processId = intval($this->app->utils->arrays->get($parameters,'id'));
if($processId > 0)
{
if($type == 'ot' )
{
$columns = ['t.id' => 'id',"replace((SELECT string_agg(email, ',') FROM admin.oapi_users s WHERE s.id = ANY (string_to_array(t.servers_ids,',')::int[])),',',' ')" => 'oapi_users_emails'];
$query = $this->app->database('system')->query()->from("production.oapi_processes 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>Users</td>";
$results .= "</tr></thead>";
$results .= "<tbody>";
$results .= "<tr>";
$results .= "<td>{$test['id']}</td>";
$results .= "<td>" . str_replace(' ','<br/>',$test['oapi_users_emails']) . "</td>";
$results .= "</tr>";
$results .= "</tbody></table>";
}
else
{
$columns = ['i.sent_total'];
$processComponents = $this->app->database('system')->query()->from('production.oapi_processes_users i',$columns)
->join('admin.oapi_users v','v.id = i.user_id',['i.user_id' => 'id','v.email' => 'user'])
->where('i.process_id = ?',$processId)
->all();
if(count($processComponents) == 0)
{
Page::printApiResults(500,'No stats found for this drop !');
}
$sentStats=[];
if($this->app->utils->fileSystem->fileExists(LOGS_PATH.DS."oapi_processes_users".DS.$processId)){
$lines=explode(PHP_EOL, $this->app->utils->fileSystem->readFile(LOGS_PATH.DS."oapi_processes_users".DS.$processId));
if(!empty($lines)){
foreach ($lines as $value) {
if($value=="")continue;
$jsn=json_decode($value,true);
if(empty($jsn))continue;
foreach ($jsn as $useId=>$stat) {
$sentStats[$useId]=$stat;
}
}
}
}
$stats = [];
$componentLabel = 'User' ;
foreach ($processComponents as $processComponent)
{
if($processComponent['id'] != '')
{
if(!key_exists($processComponent['id'],$stats))
{
$stats[$processComponent['id']] = [
'total' => 0,
'user' => ""
];
}
if(!empty($sentStats) && key_exists($processComponent['id'],$sentStats))
{
$stats[$processComponent['id']]['total'] = $stats[$processComponent['id']]['total'] + intval($sentStats[$processComponent['id']]);
$stats[$processComponent['id']]['user'] = $processComponent['user'];
}else{
//$stats[$processComponent['id']]['total'] = $stats[$processComponent['id']]['total'] + intval($processComponent['sent_total']);
//$stats[$processComponent['id']]['user'] = $processComponent['user'];
}
}
}
if(count($stats) == 0)
{
Page::printApiResults(500,'No stats found for this process !');
}
$results = '<div class="panel-group accordion scrollable" id="process-stats">';
$index = 0;
//print_r($stats);exit;
$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-detail"> Detail </a>';
$results .= '</h4>';
$results .= '</div>';
//$collapse = $index == 0 ? 'in' : 'collapse';
$results .= '<div id="stats-detail" class="panel-collapse in">';
$results .= '<div class="panel-body">';
$results .= "<table class='table table-bordered table-striped table-condensed'>";
$results .= "<thead><tr>";
$results .= "<td><b>user</b></td><td><b>Total</b></td>";
$results .= "</tr></thead>";
$results .= "<tbody>";
$total=0;
foreach ($stats as $server => $stat)
{
$results .= "<tr>";
$results .= "<td>{$stat['user']}</td>";
$results .= "<td>{$stat['total']}</td>";
$results .= "</tr>";
$total+=$stat['total'];
}
$results .= "<tr>";
$results .= "<td><b>Total</b></td>";
$results .= "<td><b>{$total}</b></td>";
$results .= "</tr>";
$results .= "</tbody></table>";
$results .= '</div>';
$results .= '</div>';
$results .= '</div>';
$index++;
$results .= '</div>';
}
Page::printApiResults(200,'',['servers' => $results]);
}
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 'ot' : $method = 'oapiTests'; break;
case 'od' : $method = 'oapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'OapiProduction',$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
$action='executeProcessActionOapi';
$result = Api::callapi('Production',$action,$parameters);
if(count($result) == 0)
{
Page::printApiResults(500,'No response found ! 22');
}
if($result['httpStatus'] == 500)
{
Page::printApiResults(500,$result['message']);
}
Page::printApiResults(200,$result['message']);
}
/**
* @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 'od' : $method = 'oapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'OapiProduction',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$id = intval($this->app->utils->arrays->get($parameters,'id'));
if($id > 0)
{
$process = OapiProcess::first(OapiProcess::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 getOapiProcess
* @description getOapiProcess action
* @before init
*/
public function getOapiProcess($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 'ot' : $method = 'oapiTests'; break;
case 'od' : $method = 'oapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'OapiProduction',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processId = intval($this->app->utils->arrays->get($parameters,'process-id'));
$process = OapiProcess::first(OapiProcess::FETCH_ARRAY,['id = ?',$processId],['user_id','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;
$allUsers = OapiUser::all(OapiUser::FETCH_ARRAY,['id IN ?',[$process['users']]],['email'],'id','ASC');
$AllUsersDomain=[];
foreach ($allUsers as $key => $value) {
$domain=explode("@", $value["email"])[1];
if( !in_array($domain, $AllUsersDomain)){
$AllUsersDomain[]=$domain;
}
}
$process['users-domain'] = $AllUsersDomain;
# return process array
Page::printApiResults(200,'',['process' => $process]);
}
/**
* @name getUsers
* @description get servers action
* @before init
*/
public function getUsers($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(),'OapiProduction','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=[];
$servers = OapiUser::all(OapiUser::FETCH_ARRAY,['status = ? and message = ?',['Activated','ok']],['id','email'],'id','ASC');
if(count($servers) > 0)
{
Page::printApiResults(200,'',['users' => $servers]);
}
else
{
Page::printApiResults(500,'Users not found !');
}
}
/**
* @name getDomains
* @description get Admins action
* @before init
*/
public function getDomains($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 !');
}
$AllUsers=OapiUser::all(OapiUser::FETCH_ARRAY,['status = ? ',['Activated']],['id','email'],'id','ASC');
$AllUsersDomain=[];
foreach ($AllUsers as $key => $value) {
if (strpos($value["email"], "@") !== false) {
$domain=explode("@", $value["email"])[1];
$AllUsersDomain[$domain]=$domain;
}
}
if(count($AllUsersDomain) > 0)
{
Page::printApiResults(200,'',['domains' => $AllUsersDomain]);
}
else
{
Page::printApiResults(500,'domains not found !');
}
}
/**
* @name getUsersDomain
* @description get servers action
* @before init
*/
public function getUsersDomain($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(),'OapiProduction','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
//$Domains = $this->app->utils->arrays->get($parameters,'domains');
$Domains = $this->app->utils->arrays->get($parameters,'domains',[]);
//print_r($Domains);exit;
if(is_array($Domains) && count($Domains) > 0){
$users = [];
$allUsers=[];
//$allUsers = OapiUser::all(OapiUser::FETCH_ARRAY,['status = ? and message = ?',['Activated','ok']],['id','email','message'],'id','ASC');
$allUsers = OapiUser::all(OapiUser::FETCH_ARRAY,['status = ? ',['Activated']],['id','email','message'],'id','ASC');
//print_r($allUsers);
if(count($allUsers)>0){
foreach ($allUsers as $key => $value) {
if (strpos($value["email"], "@") !== false) {
$domain=explode("@", $value["email"])[1];
if(in_array($domain,$Domains )){
//print_r($value);
$users[]=$value;
}
}
}
}
if(count($users) > 0)
{
Page::printApiResults(200,'',['users' => $users]);
}else{
Page::printApiResults(500,'Users not found !');
}
}else{
Page::printApiResults(500,'Incorrect Domains !');
}
}
/**
* @name OapiUpdateSent
* @description check email if we have it action
* @before init
*/
public function OapiUpdateSent($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'));
//$users_sent = $this->app->utils->arrays->get($parameters,'users-sent');
$users_sent = $this->app->utils->arrays->get($parameters,'users-sent',[]);
//print_r($users_sent);
if(count($users_sent) > 0 && $processId > 0 )
{
/*
foreach ($users_sent as $userId => $userSent) {
if(is_numeric($userId) && is_numeric($userSent)){
//$this->app->database('system')->execute("UPDATE production.oapi_processes_users SET sent_total = {$userSent} WHERE process_id= {$processId} and user_id = {$userId}");
}
}
//$this->app->database('system')->execute("UPDATE production.oapi_processes SET progress = (select sum(sent_total) from production.oapi_processes_users WHERE process_id= {$processId} ) WHERE id = {$processId}");
*/
$this->app->utils->fileSystem->writeFile(LOGS_PATH.DS."oapi_processes_users".DS.$processId,json_encode($users_sent).chr(10),FILE_APPEND);
Page::printApiResultsThenLogout(200,' correct ! ');
}elseif($sent_total>0){
$this->app->database('system')->execute("UPDATE production.oapi_processes SET progress = progress+{$sent_total} WHERE id = {$processId}");
Page::printApiResultsThenLogout(200,' correct ! ');
}
else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
/**
* @name OapiUpdateTestSent
* @description check email if we have it action
* @before init
*/
public function OapiUpdateTestSent($parameters = [])
{
$processId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'process-id'));
$total_sent = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'total-sent'));
$status = preg_replace('/[^a-zA-Z0-9]/i', '',$this->app->utils->arrays->get($parameters,'status'));
//print_r($users_sent);
if(is_numeric($total_sent) && $processId > 0 && strlen($status) > 0 )
{
$this->app->database('system')->execute("UPDATE production.oapi_processes SET progress = progress +".$total_sent." WHERE id = ".$processId." ");
$this->app->database('system')->execute("UPDATE production.oapi_processes SET finish_time = now()::timestamp(0), status= '".$status."' WHERE id = ".$processId." and status='In Progress' ");
Page::printApiResultsThenLogout(200,' correct ! ');
}
else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
/**
* @name OapiUpdateStatus
* @description check email if we have it action
* @before init
*/
public function OapiUpdateStatus($parameters = [])
{
$processId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'process-id'));
$status = preg_replace('/[^a-zA-Z0-9]/i', '',$this->app->utils->arrays->get($parameters,'status'));
//print_r($users_sent);
if( strlen($status) > 0 && $processId > 0 )
{
$this->app->database('system')->execute("UPDATE production.oapi_processes SET finish_time = now()::timestamp(0), status= '".$status."' WHERE id = ".$processId." and status='In Progress' ");
Page::printApiResultsThenLogout(200,' correct ! ');
}
else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
}