Files
fmgapp/webservices/Gapi.php

1735 lines
62 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\GapiUser as GapiUser;
use IR\App\Models\Admin\GapiAdmin as GapiAdmin;
use IR\App\Models\Production\GapiProcess as GapiProcess;
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;
# Gapi
use Google\Client;
use Google\Service\Gmail;
# orm
use IR\Orm\Query as Query;
# http
use IR\Http\Request as Request;
/**
* @name Gapi
* @description Gapi WebService
*/
class Gapi 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(),'GapiUsers','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));
$columns = ['u.id','u.email','u.token','ad.credential'];
$allUsers=[];
foreach ($usersIds as $userId) {
$allUsers[] = $this->app->database('system')->query()->from('admin.gapi_users u',$columns)
->join('admin.gapi_admin ad','ad.id = u.admin_id' ,['ad.email' => 'admin','u.password' => 'password','u.message' => 'message'])
->where('u.id = ?',intval($userId))
->first();
}
//print_r($allUsers);exit;
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="";
if(isset($user['credential']) && $user['credential']!="" ){
$client = new Client();
$client->setAuthConfig(json_decode($user['credential'] , true)); // Credentails file path
$client->setScopes(["https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/gmail.modify","https://www.googleapis.com/auth/gmail.settings.basic","https://www.googleapis.com/auth/gmail.settings.sharing"]);
$client->setApplicationName("Gapi");
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
$file_token="";
if($this->app->utils->fileSystem->fileExists(STORAGE_PATH. DS . 'gapi_token' . DS .$user["id"])){
$file_token=$this->app->utils->fileSystem->readFile(STORAGE_PATH. DS . 'gapi_token' . DS .$user["id"]);
}
if(isset($file_token) && $file_token!=""){
//$client->setAccessToken(json_decode($user['token'] , true));
$client->setAccessToken(json_decode($file_token , true));
}
if ($client->isAccessTokenExpired() || $user['message']=="token"){
if(!$client->getRefreshToken() || $user['message']=="token")
{
$authURL = $client->createAuthUrl();
//print_r($client);exit;
$status="<a target='_blank' href='".$authURL."'>Get Token</a>";
}else{
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
//$credentials = json_encode($client->getAccessToken(),JSON_PRETTY_PRINT,JSON_UNESCAPED_UNICODE);
$this->app->utils->fileSystem->writeFile(STORAGE_PATH. DS . 'gapi_token' . DS .$user["id"],json_encode($client->getAccessToken()));
$GapiUser = new GapiUser();
$GapiUser->setId(intval($user["id"]));
$GapiUser->load();
$GapiUser->setMessage('ok');
//$GapiUser->setToken(json_encode($client->getAccessToken()));
$GapiUser->update();
$status="ok";
}
}else{
$GapiUser = new GapiUser();
$GapiUser->setId(intval($user["id"]));
$GapiUser->load();
$GapiUser->setMessage('ok');
$GapiUser->update();
$status="ok";
}
}else{
$status="Add Admin Credentials";
}
$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]);
}
/**
* @name getProcessServers
* @description getProcessServers action
* @before init
*/
public function tokenInfos($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(),'GapiUsers','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));
$columns = ['u.id','u.email','u.token','ad.credential'];
$allUsers=[];
foreach ($usersIds as $userId) {
$allUsers[] = $this->app->database('system')->query()->from('admin.gapi_users u',$columns)
->join('admin.gapi_admin ad','ad.id = u.admin_id' ,['ad.email' => 'admin','u.password' => 'password','u.message' => 'message'])
->where('u.id = ?',intval($userId))
->first();
}
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>Infos (email,password,client_id,Admin)</td>";
$results .= "<tbody>";
foreach ($allUsers as $user) {
$status="";
if(isset($user['credential']) && $user['credential']!="" ){
$crd=json_decode($user['credential'] , true);
$emailAdmin=explode("email=",$crd["web"]["redirect_uris"][0])[1] ;
$client_id=$crd["web"]["client_id"] ;
$results .= "<tr><td>".$user["email"].",".$user["password"].",".$client_id.",".$emailAdmin."</td></tr>";
}
}
$results .= "</tbody></table>";
Page::printApiResults(200,'',['users' => $results]);
}
/**
* @name getProcessServers
* @description getProcessServers action
* @before init
*/
public function tokenInfosExtra($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(),'GapiUsers','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));
$firstUsers = $this->app->database('system')->query()->from('admin.gapi_users',['id','email'])->where('id = ?',intval($usersIds[0]))->first();
if(!is_array($firstUsers) || count($firstUsers) == 0)
{
Page::printApiResults(500,'No user found !');
}
$domain=explode("@", $firstUsers["email"])[1];
$allUsers=$this->app->database('system')->query()->from('admin.gapi_users u',['u.id','u.email','ad.email' => 'admin','ad.credential','u.password' => 'password','u.recovry' => 'recovry','prx.host' ,'prx.port' ,'prx.user_name' => 'proxyusername','prx.password' => 'proxypassword'])
->join('admin.gapi_admin ad','ad.id = u.admin_id' )
->join('admin.proxy prx','prx.id = u.proxy_id' )
->where("u.email like ? ",["%@".$domain])
->order("u.email")
->all();
//print_r($allUsers);exit;
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>Infos (user,pass,ip-proxy,port,proxy-username,proxy-password,recovery,client-id,admin)</td>";
$results .= "<tbody></tbody></table>";
$results .= "<textarea class='col-md-12 form-control' style='height: 500px !important;'>";
foreach ($allUsers as $user) {
//print_r($user);
if(isset($user['credential']) && $user['credential']!="" ){
$crd=json_decode($user['credential'] , true);
$emailAdmin=explode("email=",$crd["web"]["redirect_uris"][0])[1] ;
$client_id=$crd["web"]["client_id"] ;
$results .= $user["email"].",".$user["password"].",".$user["host"].",".$user["port"].",".$user["proxyusername"].",". str_replace([' ',"\n","\r","\n\r","\t"], '', $user["proxypassword"]).",".$user["recovry"].",".$client_id.",".$emailAdmin.PHP_EOL;
}
}
$results .= "</textarea>";
Page::printApiResults(200,'',['users' => $results]);
}
/**
* @name getProcessServers
* @description getProcessServers action
* @before init
*/
public function checkTokenOld($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(),'GapiUsers','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));
$columns = ['u.id','u.email'];
$allUsers=[];
foreach ($usersIds as $userId) {
$allUsers[] = $this->app->database('system')->query()->from('admin.gapi_users u',$columns)
->join('admin.gapi_admin ad','ad.id = u.admin_id' ,['ad.email' => 'admin'])
->where('u.id = ?',intval($userId))
->first();
}
//print_r($allUsers);exit;
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>Status</td>";
$results .= "</tr></thead>";
$results .= "<tbody>";
foreach ($allUsers as $user) {
$status="";
if($this->app->utils->fileSystem->fileExists(STORAGE_PATH. DS . 'credentials' . DS . $user["admin"].DS .'credentials.json')){
$client = new Client();
$client->setAuthConfig(STORAGE_PATH. DS . 'credentials' . DS . $user["admin"].DS .'credentials.json'); // Credentails file path
$client->setScopes(["https://www.googleapis.com/auth/userinfo.email","https://www.googleapis.com/auth/gmail.modify"]);
$client->setApplicationName("Gapi");
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
//echo '---'.$user["email"].'---';exit;
if($this->app->utils->fileSystem->fileExists(STORAGE_PATH. DS . 'credentials' . DS .'tokens'. DS . $user["email"].'.json')){
$accessToken = json_decode($this->app->utils->fileSystem->readFile(STORAGE_PATH. DS . 'credentials' . DS .'tokens'. DS . $user["email"].'.json') , true);
$client->setAccessToken($accessToken);
}
if ($client->isAccessTokenExpired()){
if(!$client->getRefreshToken())
{
$authURL = $client->createAuthUrl();
$status="<a target='_blank' href='".$authURL."'>Get Token</a>";
}else{
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
$credentials = json_encode($client->getAccessToken(),JSON_PRETTY_PRINT,JSON_UNESCAPED_UNICODE);
$this->app->utils->fileSystem->writeFile(STORAGE_PATH. DS . 'credentials' . DS .'tokens'. DS . $user["email"].'.json',$credentials);
$GapiUser = new GapiUser();
$GapiUser->setId(intval($user["id"]));
$GapiUser->load();
$GapiUser->setMessage('ok');
$GapiUser->update();
$status="ok";
}
}else{
$GapiUser = new GapiUser();
$GapiUser->setId(intval($user["id"]));
$GapiUser->load();
$GapiUser->setMessage('ok');
$GapiUser->update();
$status="ok";
}
}else{
$status="Add Admin Credentials";
}
$results .= "<tr><td>".$user["id"]."</td><td>".$user["email"]."</td><td>".$status."</td></tr>";
}
$results .= "</tbody></table>";
Page::printApiResults(200,'',['users' => $results]);
}
/**
* @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(),'GapiProduction','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(),'GapiProduction','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 GapiProceedSend
* @description proceed send/test action
* @before init
*/
public function GapiProceedSend($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(),'GapiProduction','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$parameters = $this->app->http->request->retrieve(Request::ALL,Request::POST);
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]');
# 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 servers selected !');
}
$servers = GapiUser::all(GapiUser::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 rdp 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 = new GapiProcess() ;
$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 = 'GapiProcesses' ;
$action = $type == 'drop' ? 'proceedDrop' : '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 getGapiProcessUsers
* @description getRdpProcessServers action
* @before init
*/
public function getGapiProcessUsers($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 'gt' : $method = 'gapiTests'; break;
case 'gd' : $method = 'gapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'GapiProduction',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processId = intval($this->app->utils->arrays->get($parameters,'id'));
if($processId > 0)
{
if($type == 'gt' )
{
$columns = ['i.sent_total'];
$processComponents = $this->app->database('system')->query()->from('production.gapi_processes_users i',$columns)
->join('admin.gapi_users v','v.id = i.user_id',['i.user_id' => 'id','v.email' => 'user','i.message'=>'message'])
->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."gapi_processes_users".DS.$processId)){
$lines=explode(PHP_EOL, $this->app->utils->fileSystem->readFile(LOGS_PATH.DS."gapi_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;
}
}
}
}
//print_r($processComponents);exit;
$stats = [];
$componentLabel = 'User' ;
foreach ($processComponents as $processComponent)
{
if($processComponent['id'] != '')
{
if(!key_exists($processComponent['id'],$stats))
{
$stats[$processComponent['id']] = [
'total' => 0,
'user' => "",
'message' => ""
];
}
if(!empty($sentStats) && key_exists($processComponent['id'],$sentStats))
{
$stats[$processComponent['id']]['total'] = $stats[$processComponent['id']]['total'] + intval($sentStats[$processComponent['id']]['sent']);
$stats[$processComponent['id']]['user'] = $processComponent['user'];
$stats[$processComponent['id']]['message'] = $sentStats[$processComponent['id']]['error'];
}else{
//$stats[$processComponent['id']]['total'] = $stats[$processComponent['id']]['total'] + intval($processComponent['sent_total']);
//$stats[$processComponent['id']]['user'] = $processComponent['id'];
//$stats[$processComponent['id']]['message'] = $processComponent['message'];
}
}
}
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><td><b>Message</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 .= "<td>{$stat['message']}</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>';
}
else
{
$columns = ['i.sent_total'];
$processComponents = $this->app->database('system')->query()->from('production.gapi_processes_users i',$columns)
->join('admin.gapi_users v','v.id = i.user_id',['i.user_id' => 'id','v.email' => 'user','i.message'=>'message'])
->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."gapi_processes_users".DS.$processId)){
$lines=explode(PHP_EOL, $this->app->utils->fileSystem->readFile(LOGS_PATH.DS."gapi_processes_users".DS.$processId));
if(!empty($lines)){
foreach ($lines as $value) {
if($value=="")continue;
$jsn=json_decode($value,true);
//print_r(count($jsn).chr(10));
if(empty($jsn))continue;
foreach ($jsn as $useId=>$stat) {
$sentStats[$useId]=$stat;
}
}
}
}
//print_r(count($sentStats));exit;
$stats = [];
$componentLabel = 'User' ;
foreach ($processComponents as $processComponent)
{
if($processComponent['id'] != '')
{
if(!key_exists($processComponent['id'],$stats))
{
$stats[$processComponent['id']] = [
'total' => 0,
'user' => "",
'message' => ""
];
}
if(!empty($sentStats) && key_exists($processComponent['id'],$sentStats))
{
$stats[$processComponent['id']]['total'] = $stats[$processComponent['id']]['total'] + intval($sentStats[$processComponent['id']]['sent']);
$stats[$processComponent['id']]['user'] = $processComponent['user'];
$stats[$processComponent['id']]['message'] = $sentStats[$processComponent['id']]['error'];
}else{
//$stats[$processComponent['id']]['total'] = $stats[$processComponent['id']]['total'] + intval($processComponent['sent_total']);
$stats[$processComponent['id']]['user'] = $processComponent['user'];
//$stats[$processComponent['id']]['message'] = $processComponent['message'];
}
}
}
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;
$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><td><b>Message</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 .= "<td>{$stat['message']}</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 'gt' : $method = 'gapiTests'; break;
case 'gd' : $method = 'gapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'GapiProduction',$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='executeProcessActionGapi';
$result = Api::call('Production',$action,$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 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 'gd' : $method = 'gapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'GapiProduction',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$id = intval($this->app->utils->arrays->get($parameters,'id'));
if($id > 0)
{
$process = GapiProcess::first(GapiProcess::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 .= "{$listId} {$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 getGapiProcess
* @description getRdpProcess action
* @before init
*/
public function getGapiProcess($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 'gt' : $method = 'gapiTests'; break;
case 'gd' : $method = 'gapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'GapiProduction',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processId = intval($this->app->utils->arrays->get($parameters,'process-id'));
$process = GapiProcess::first(GapiProcess::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;
$admins = GapiUser::all(GapiUser::FETCH_ARRAY,['id IN ?',[$process['users']]],['admin_id'],'id','ASC');
$AllAdminsId=[];
foreach ($admins as $key => $value) {
$AllAdminsId[$value["admin_id"]]=$value["admin_id"];
}
$AdminsId=[];
foreach ($AllAdminsId as $key => $value) {
$AdminsId[]=$value;
}
$process['users-admin'] = $AdminsId;
//print_r($process);exit;
# 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(),'GapiProduction','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 = GapiUser::all(GapiUser::FETCH_ARRAY,['status = ? and message = ?',['Activated','ok']],['id','email','admin_name'],'id','ASC');
if(count($servers) > 0)
{
Page::printApiResults(200,'',['users' => $servers]);
}
else
{
Page::printApiResults(500,'Users not found !');
}
}
/**
* @name getAdmins
* @description get Admins action
* @before init
*/
public function getAdmins($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(),'GapiProduction','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$admins=[];
$admins = GapiAdmin::all(GapiAdmin::FETCH_ARRAY,['status = ? ',['Activated']],['id','name'],'id','ASC');
if(count($admins) > 0)
{
Page::printApiResults(200,'',['admins' => $admins]);
}
else
{
Page::printApiResults(500,'Admins not found !');
}
}
/**
* @name AdminUsers
* @description get AdminUsers action
* @before init
*/
public function getAdminUsers($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(),'GapiProduction','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$AdminId = $this->app->utils->arrays->get($parameters,'admin-ids');
if(count($AdminId) > 0){
$users = [];
$users = GapiUser::all(GapiUser::FETCH_ARRAY,['status = ? and admin_id in ? ',['Activated',$AdminId]],['id','email','admin_name'],'id','ASC');
if(count($users) > 0)
{
Page::printApiResults(200,'',['users' => $users]);
}else{
Page::printApiResults(500,'Users not found !');
}
}else{
Page::printApiResults(500,'Incorrect Admin id !');
}
}
/**
* @name GapiUpdateSent
* @description check email if we have it action
* @before init
*/
public function GapiUpdateSent($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);
$status = preg_replace('/[^a-zA-Z0-9]/i', '',$this->app->utils->arrays->get($parameters,'status'));
if(count($users_sent) > 0 && $processId > 0 )
{
foreach ($users_sent as $userId => $userinfos) {
if(is_numeric($userId) ){
$userSent=preg_replace('/[^0-9]/i', '',$userinfos["sent"]);
if(!is_numeric($userSent) )continue;
$error=preg_replace('/[^a-zA-Z0-9 ]/i', '',$userinfos["error"]);
$this->app->database('system')->execute("UPDATE production.gapi_processes_users SET sent_total = {$userSent} ,message = '{$error}' WHERE process_id= {$processId} and user_id = {$userId}");
}
}
$this->app->utils->fileSystem->writeFile(LOGS_PATH.DS."gapi_processes_users".DS.$processId,json_encode($users_sent).chr(10),FILE_APPEND);
$this->app->database('system')->execute("UPDATE production.gapi_processes SET progress = (select sum(sent_total) from production.gapi_processes_users WHERE process_id= {$processId} ) WHERE id = {$processId}");
Page::printApiResultsThenLogout(200,' correct ! ');
}elseif($sent_total>0){
$this->app->database('system')->execute("UPDATE production.gapi_processes SET progress = progress+{$sent_total} WHERE id = {$processId}");
Page::printApiResultsThenLogout(200,' correct ! ');
}
else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
/**
* @name GapiUpdateTestSent
* @description check email if we have it action
* @before init
*/
public function GapiUpdateTestSent($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);
$users_sent = $this->app->utils->arrays->get($parameters,'users-sent',[]);
if(count($users_sent) > 0 && $processId > 0 )
{
foreach ($users_sent as $userId => $userinfos) {
if(is_numeric($userId) ){
$userSent=preg_replace('/[^0-9]/i', '',$userinfos["sent"]);
if(!is_numeric($userSent) )continue;
$error=preg_replace('/[^a-zA-Z0-9 ]/i', '',$userinfos["error"]);
//$this->app->database('system')->execute("UPDATE production.gapi_processes_users SET sent_total = {$userSent} ,message = '{$error}' WHERE process_id= {$processId} and user_id = {$userId}");
if($error=="token"){
$this->app->database('system')->execute("UPDATE admin.gapi_users SET message = '{$error}' WHERE id = {$userId}");
}
}
}
$this->app->utils->fileSystem->writeFile(LOGS_PATH.DS."gapi_processes_users".DS.$processId,json_encode($users_sent).chr(10),FILE_APPEND);
}
if(is_numeric($total_sent) && $processId > 0 && strlen($status) > 0 )
{
$this->app->database('system')->execute("UPDATE production.gapi_processes SET progress = progress +".$total_sent." WHERE id = ".$processId." ");
$this->app->database('system')->execute("UPDATE production.gapi_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 GapiUpdateStatus
* @description check email if we have it action
* @before init
*/
public function GapiUpdateStatus($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.gapi_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 !');
}
}
}