Files
fmgapp/webservices/Fapi.php

1203 lines
43 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 Fapi.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\FapiAccount as FapiAccount;
use IR\App\Models\Admin\FapiAdmin as FapiAdmin;
use IR\App\Models\Production\FapiProcess as FapiProcess;
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 Fapi
* @description Fapi WebService
*/
class Fapi 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 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 FapiProceedSend
* @description proceed send/test action
* @before init
*/
public function FapiProceedSend($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,'accounts',[]);
$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 account selected !');
}
$servers = FapiAccount::all(FapiAccount::FETCH_ARRAY,['id IN ?',[$serversIds]],['id']);
if(count($servers) == 0)
{
Page::printApiResults(500,'No account selected !');
}
if(count($servers) != count($serversIds))
{
Page::printApiResults(500,'Some account 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 !");
}
}
}
# 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 FapiProcess() ;
$process->setContent(base64_encode($json));
$process->setServersIds($this->app->utils->arrays->implode($serversIds));
$process->setProcessType($type);
$process->setStatus('In Progress');
$process->setAccountsReady('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);
$process->setAccountsPrepare(0);
$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 = 'FapiProcesses' ;
$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 getFapiProcessUsers
* @description getFapiProcessUsers action
* @before init
*/
public function getFapiProcessUsers($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 'ft' : $method = 'fapiTests'; break;
case 'fd' : $method = 'fapiDrops'; 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)
{
$columns = ['i.sent_total'];
$processComponents = $this->app->database('system')->query()->from('production.fapi_processes_users i',$columns)
->join('admin.fapi_accounts v','v.id = i.user_id',['i.user_id' => 'id','v.name' => 'Account'])
->where('i.process_id = ?',$processId)
->all();
//print_r($processComponents);exit;
if(count($processComponents) == 0)
{
Page::printApiResults(500,'No stats found for this process !');
}
$sentStats=[];
if($this->app->utils->fileSystem->fileExists(LOGS_PATH.DS."fapi_processes_users".DS.$processId)){
$lines=explode(PHP_EOL, $this->app->utils->fileSystem->readFile(LOGS_PATH.DS."fapi_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 = [];
foreach ($processComponents as $processComponent)
{
if($processComponent['id'] != '')
{
if(!key_exists($processComponent['id'],$stats))
{
$stats[$processComponent['id']] = [
'total' => 0,
'account' => "",
'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']]['account'] = $processComponent['account'];
$stats[$processComponent['id']]['message'] = $sentStats[$processComponent['id']]['error'];
}else{
$stats[$processComponent['id']]['total'] = 0;
$stats[$processComponent['id']]['account'] = $processComponent['account'];
}
}
}
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>Account</b></td><td><b>Total</b></td></td><td><b>Message</b></td>";
$results .= "</tr></thead>";
$results .= "<tbody>";
$total=0;
foreach ($stats as $server => $stat)
{
$results .= "<tr>";
$results .= "<td>{$stat['account']}</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 .= "<td><b></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 'ft' : $method = 'fapiTests'; break;
case 'fd' : $method = 'fapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'FapiProduction',$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='executeProcessActionFapi';
$result = Api::call('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 = FapiProcess::first(FapiProcess::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 getFapiProcess
* @description getFapiProcess action
* @before init
*/
public function getFapiProcess($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 'ft' : $method = 'fapiTests'; break;
case 'fd' : $method = 'fapiDrops'; break;
}
$access = $method != '' && Permissions::checkForAuthorization(Authentication::getAuthenticatedUser(),'FapiProduction',$method);
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$processId = intval($this->app->utils->arrays->get($parameters,'process-id'));
$process = FapiProcess::first(FapiProcess::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;
$allAccounts = FapiAccount::all(FapiAccount::FETCH_ARRAY,['id IN ?',[$process['accounts']]],['admin_id'],'id','ASC');
$AllAdminsId=[];
foreach ($allAccounts as $key => $value) {
$AllAdminsId[$value["admin_id"]]=$value["admin_id"];
}
$AdminsId=[];
foreach ($AllAdminsId as $key => $value) {
$AdminsId[]=$value;
}
$process['admins'] = $AdminsId;
# return process array
Page::printApiResults(200,'',['process' => $process]);
}
/**
* @name getAccounts
* @description get Accounts action
* @before init
*/
public function getAccounts($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 !');
}
$accounts=[];
$accounts = FapiAccount::all(FapiAccount::FETCH_ARRAY,['status = ? ',['Activated']],['id','name','admin_name'],'id','ASC');
if(count($accounts) > 0)
{
Page::printApiResults(200,'',['accounts' => $accounts]);
}
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(),'Production','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$admins=[];
$admins = FapiAdmin::all(FapiAdmin::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 getAdminUsers
* @description get AdminUsers action
* @before init
*/
public function getAdminAccounts($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(),'FapiProduction','sendProcess');
if($access == false)
{
Page::printApiResults(403,'Access Denied !');
}
$AdminId = $this->app->utils->arrays->get($parameters,'admin-ids');
if(count($AdminId) > 0){
$accounts = [];
$accounts = FapiAccount::all(FapiAccount::FETCH_ARRAY,['status = ? and admin_id in ? ',['Activated',$AdminId]],['id','name','admin_name'],'admin_id,id','ASC');
if(count($accounts) > 0)
{
Page::printApiResults(200,'',['accounts' => $accounts]);
}else{
Page::printApiResults(500,'Accounts not found !');
}
}else{
Page::printApiResults(500,'Incorrect Admin id !');
}
}
/**
* @name FapiUpdateSent
* @description check email if we have it action
* @before init
*/
public function FapiUpdateSent($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($processId > 0 && $sent_total > 0 )
{
$this->app->database('system')->execute("UPDATE production.fapi_processes SET progress = progress+{$sent_total} WHERE id = {$processId}");
$this->app->utils->fileSystem->writeFile(LOGS_PATH.DS."fapi_processes_users".DS.$processId,json_encode($users_sent).chr(10),FILE_APPEND);
Page::printApiResultsThenLogout(200,' correct ! ');
}else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
/**
* @name FapiUpdateSentTest
* @description check email if we have it action
* @before init
*/
public function FapiUpdateSentTest($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 = json_decode( base64_decode( $users_sent),true);
//print_r($users_sent);
if($processId > 0 && $sent_total > 0 )
{
$this->app->database('system')->execute("UPDATE production.fapi_processes SET progress = progress+{$sent_total} WHERE id = {$processId}");
$this->app->utils->fileSystem->writeFile(LOGS_PATH.DS."fapi_processes_users".DS.$processId,json_encode($users_sent).chr(10),FILE_APPEND);
Page::printApiResultsThenLogout(200,' correct ! ');
}else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
/**
* @name FapiUpdateChangeTemplate
* @description FapiUpdateChangeTemplate
* @before init
*/
public function FapiUpdateChangeTemplate($parameters = [])
{
$processId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'process-id'));
$accountId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'account-id'));
$accountStatus = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'account-status'));
if(is_numeric($accountId) && $processId > 0 && is_numeric($accountStatus) )
{
$this->app->database('system')->execute("UPDATE production.fapi_processes_users SET ready = ".$accountStatus." WHERE process_id = ".$processId." and user_id = ".$accountId." ");
$this->app->database('system')->execute("UPDATE production.fapi_processes SET accounts_prepare=accounts_prepare+1 WHERE id = ".$processId." ");
Page::printApiResultsThenLogout(200,' correct ! ');
}
else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
/**
* @name FapiUpdateReadyStatus
* @description check email if we have it action
* @before init
*/
public function FapiUpdateReadyStatus($parameters = [])
{
$processId = preg_replace('/[^0-9]/i', '',$this->app->utils->arrays->get($parameters,'process-id'));
if( $processId > 0 )
{
$this->app->database('system')->execute("UPDATE production.fapi_processes SET accounts_ready= 'Completed' WHERE id = ".$processId."");
Page::printApiResultsThenLogout(200,' correct ! ');
}
else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
/**
* @name FapiCreateProject
* @description check email if we have it action
* @before init
*/
public function FapiCreateProject($parameters = [])
{
$infos = json_decode(base64_decode( $this->app->utils->arrays->get($parameters,'token')),true);
if( !empty($infos) && isset($infos["email"]) && isset($infos["name"]) && isset($infos["token"]) && isset($infos["credential"]))
{
$infos["email"]=str_replace(['.','"',"'"], '', strtolower($infos['email']));
$infos["name"]=preg_replace('/[^a-zA-Z0-9]/i', '', $infos['name']);
if($infos["email"]!="" && $infos["name"]!="" && $infos["token"]!="" && $infos["credential"]!="" ){
$adminId=0;
$resultAdmin=$this->app->database('system')->execute("SELECT id,name from admin.fapi_admin where replace(LOWER(email),'.','') = '".$infos["email"]."'");
if(!empty($resultAdmin)){
$adminId=$resultAdmin[0]["id"];
}else{
Page::printApiResultsThenLogout(500,'Email not exist !');
}
$resultAcc=$this->app->database('system')->execute("SELECT count(*) from admin.fapi_accounts where admin_id = ".$adminId." and name ='".$infos["name"]."' ");
if($resultAcc[0]["count"]==0){
$this->app->database('system')->execute("INSERT into admin.fapi_accounts (id,admin_id,admin_name,status,name,token,credential,created_by,last_updated_by,created_date,last_updated_date) values(nextval('admin.seq_id_fapi_accounts'),".$adminId.",'".$resultAdmin[0]["name"]."','Activated','".$infos["name"]."','".json_encode($infos["token"]) ."','".json_encode($infos["credential"])."','khamlichi.1990@gmail.com','khamlichi.1990@gmail.com',now()::timestamp(0),now()::timestamp(0)); ");
}else{
$this->app->database('system')->execute("UPDATE admin.fapi_accounts set name='".$infos["name"]."', token='".json_encode($infos["token"]) ."',credential='".json_encode($infos["credential"])."',last_updated_by='khamlichi.1990@gmail.com',last_updated_date=now()::timestamp(0) where admin_id = ".$adminId." and name ='".$infos["name"]."' ");
}
$this->app->database('system')->execute("UPDATE admin.fapi_admin set users_count=(select count(*) from admin.fapi_accounts where admin_id = ".$adminId.") where id = ".$adminId." ");
Page::printApiResultsThenLogout(200,' correct ! ');
}else{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
else
{
Page::printApiResultsThenLogout(500,'Incorrect parameters !');
}
}
/**
* @name FapiUpdateStatus
* @description check email if we have it action
* @before init
*/
public function FapiUpdateStatus($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'));
if( strlen($status) > 0 && $processId > 0 )
{
$this->app->database('system')->execute("UPDATE production.fapi_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 !');
}
}
}