date_default_timezone_set('Europe/London');
$db_host = 'localhost'; // Database Host for WHMCS Install
$db_username = 'paymy_whmcs';
$db_password = 'y6R3p%40n';
$db_name = 'paymy_whmcs';
DEFINE("DBHOST",$db_host);
DEFINE("DBUSER",$db_username);
DEFINE("DBPASS",$db_password);
DEFINE("DBNAME",$db_name);
$template = 'Portal'; // Default Template
$install_path = ''; // The install path after public_html - Add trailing slash
$CONFIG['rooturl'] = 'https://'.$_SERVER['HTTP_HOST'].'/';
$CONFIG['booking_url'] = 'https://bill.pay-me.co.uk/';
$CONFIG['whmcs_url'] = $CONFIG['va_whmcs_url'] = 'https://bill.pay-me.co.uk/includes/api.php';
$CONFIG['whmcs_user'] = $CONFIG['va_whmcs_user'] = 'mardon2k7';
$CONFIG['whmcs_pass'] = $CONFIG['va_whmcs_pass'] = '165897';
$CONFIG['whmcs_hash'] = $CONFIG['va_whmcs_hash'] = 'MwybvyTIKfOU8wXU2fkREbE86YwduYRBcYGa444BWPW0RlRJBiDvw4OUtmfxo7Rs';
?>
class Invoice
{
protected $pdf = NULL;
protected $invoiceId = 0;
protected $data = array();
protected $output = array();
protected $totalBalance = 0;
protected $gateway = NULL;
protected $gatewayModulesWhereCallbacksMightBeDelayed = array("paypal", "paypalcheckout");
public function __construct($invoiceId = 0)
{
if ($invoiceId) {
$this->setID($invoiceId);
}
}
public function setID($invoiceId)
{
$this->invoiceId = (int) $invoiceId;
$loaded = $this->loadData();
return $loaded;
}
public function getID()
{
return $this->invoiceId;
}
public function getRequest($id)
{
$data = get_requests('', $id);
if(is_array($data))
{
return $data;
}
return 'fail';
}
protected function loadData($force = true)
{
if (!$force && count($this->data)) {
return false;
}
$invoiceModel = $this->getRequest($this->invoiceId);
if($invoiceModel == 'fail') return false;
$this->invoiceId = $invoiceModel['invoiceid'];
if($this->invoiceId == 0) return false;
$invoiceData["model"] = $invoiceModel;
$invoiceData["invoiceid"] = $invoiceData["invoiceid"];
$invoiceData["balance"] = sprintf("%01.2f", $invoiceData["amount"]);
$this->data = $invoiceData;
return true;
}
public function getData($var = "")
{
$this->loadData(false);
return isset($this->data[$var]) ? $this->data[$var] : $this->data;
}
protected function formatForOutput()
{
global $currency;
$this->output = $this->data;
$explode = explode(' ', $this->output["model"]["created_at"]);
$this->output["datecreated"] = $explode[0];
//$currency = getCurrency($this->getData("userid"));
//$array = array("subtotal", "credit", "tax", "total", "balance", "amountpaid");
foreach ($array as $v) {
//$this->output[$v] = formatCurrency($this->output[$v]);
}
if (!function_exists("getClientsDetails")) {
require ROOTDIR . "/includes/clientfunctions.php";
}
foreach($this->data['model'] as $key => $val)
{
$clientsdetails[$key] = $val;
}
$array = array("invoicedate", "duedate", "datepaid");
foreach ($array as $v) {
$this->output[$v] = substr($this->output["model"][$v], 0, 10) != "0000-00-00" ? fromMySQLDate($this->output[$v], $v == "datepaid" ? "1" : "0", 1) : "";
}
$clientsdetails["country"] = $clientsdetails["countryname"];
$this->output["amount"] = $this->data['model']['amount'];
$this->output["tax"] = $this->data['model']['tax'];
$this->output["clientsdetails"] = $clientsdetails;
$this->output["customfields"] = $customfields;
//$taxData1 = getTaxRate(1, $clientsdetails["state"], $clientsdetails["countrycode"]);
//$taxData2 = getTaxRate(2, $clientsdetails["state"], $clientsdetails["countrycode"]);
$taxName1 = $taxData1["name"];
$taxName2 = $taxData2["name"];
if ($taxName1 != "") {
$this->output["taxname"] = $taxName1;
} else {
$this->output["taxname"] = "";
$this->output["taxrate"] = "0";
}
if ($taxName2 != "") {
$this->output["taxname2"] = $taxName2;
} else {
$this->output["taxname2"] = "";
$this->output["taxrate2"] = "0";
}
$this->output["pagetitle"] = 'Invoice #' . $this->output["model"]["invoiceid"];
$payto[] = $this->data['model']['seller_firstname'].' '.$this->data['model']['seller_firstname'];
$payto[] = $this->data['model']['seller_address1'];
if($this->data['model']['seller_address2']) $payto[] = $this->data['model']['seller_address2'];
$payto[] = $this->data['model']['seller_city'];
$payto[] = $this->data['model']['seller_state'];
$payto[] = $this->data['model']['seller_postcode'];
if(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.jpg'))
{
$profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.jpg';
}elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.png'))
{
$profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.png';
}elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.jpeg'))
{
$profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.jpeg';
}elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.gif'))
{
$profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.gif';
}elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.JPG'))
{
$profilephoto = ROOTDIR.'/uploads/user_uploads/'.$this->data['model']['relid'].'_profilephoto.JPG';
}
$this->output["profilephoto"] = $profilephoto;
$this->output["payto"] = $payto;
$this->output["seller_companyname"] = $this->data['model']['seller_companyname'];
}
public function getOutput($pdf = false)
{
$this->loadData(false);
$this->formatForOutput();
if ($pdf) {
$this->makePDFFriendly();
}
return $this->output;
}
public function getLineItems($entityDecode = false)
{
$request = get_requests('', $this->getID());
$invoiceitems = array();
if(is_array($request['multirequest']))
{
foreach($request['multirequest'] as $key => $data)
{
$qty = $data["qty"];
$description = $data["name"];
$amount = $data["price"];
$taxed = $data["taxed"] ? true : false;
if ($entityDecode) {
$description = htmlspecialchars(Sanitize::decode($description));
} else {
$description = nl2br($description);
}
$invoiceitems[] = array("id" => (int) $key, "description" => $description, "rawamount" => $amount, "amount" => $amount, "taxed" => $taxed, "qty" => $qty);
}
} else {
if ($entityDecode) {
$description = htmlspecialchars(Sanitize::decode($request['description']));
} else {
$description = nl2br($request['description']);
}
$invoiceitems[] = array("id" => (int) $request['id'], "description" => $description, "rawamount" => $request['amount'], "amount" => $request['amount'], "tax" => $request['istaxed']);
}
return $invoiceitems;
}
public function pdfCreate()
{
$this->pdf = new PDF();
return $this->pdf;
}
protected function makePDFFriendly()
{
$this->output["companyname"] = $this->output["seller_companyname"];
$this->output["companyaddress"] = $this->output["payto"];
$this->output = Sanitize::decode($this->output);
return true;
}
public function pdfInvoicePage($invoiceId = 0)
{
$this->setID($invoiceId);
$tplvars = $this->getOutput(true);
if($tplvars['model']['id'] == '') return false;
$tplvars["invoiceitems"] = $this->getLineItems(true);
$tplvars["pdfFont"] = \Configuration::get_config("TCPDFFont");
$this->pdfAddPage("invoicepdf.tpl", $tplvars);
return $tplvars['model']['invoiceid'];
}
public function pdfAddPage($tplfile, array $tplvars)
{
global $_LANG;
$templateName = switch_theme(''.$_SESSION['user']['groupid']);
$tplFileExtension = "." . pathinfo($tplfile, PATHINFO_EXTENSION);
$baseTplFilename = preg_replace("/" . $tplFileExtension . "\$/", "", $tplfile);
$headerTplFile = ROOTDIR . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $templateName . DIRECTORY_SEPARATOR . $baseTplFilename . "header" . $tplFileExtension;
$footerTplFile = ROOTDIR . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $templateName . DIRECTORY_SEPARATOR . $baseTplFilename . "footer" . $tplFileExtension;
if (file_exists($headerTplFile)) {
$this->pdf->setHeaderTplFile($headerTplFile);
}
if (file_exists($footerTplFile)) {
$this->pdf->setFooterTplFile($footerTplFile);
}
$this->pdf->setTemplateVars($tplvars);
$this->pdf->setPrintHeader(true);
$this->pdf->setPrintFooter(true);
$this->pdf->AddPage();
$this->pdf->SetFont(\Configuration::get_config("TCPDFFont"), "", 10);
$this->pdf->SetTextColor(0);
foreach ($tplvars as $k => $v) {
${$k} = $v;
}
$pdf =& $this->pdf;
include ROOTDIR . DIRECTORY_SEPARATOR . "templates" . DIRECTORY_SEPARATOR . $templateName . DIRECTORY_SEPARATOR . $tplfile;
return true;
}
public function pdfOutput()
{
return $this->pdf->Output("", "S");
}
public function getTotalBalance()
{
return $this->totalBalance;
}
public function getTotalBalanceFormatted()
{
return formatCurrency($this->getTotalBalance());
}
}
if (!function_exists('set_details_mods')):
function set_details_mods()
{
global $connectmysql_modsdetails_mods;
global $db_host, $db_name, $db_username, $db_password;
$connectmysql_modsdetails_mods['dbhost'] = $db_host;
$connectmysql_modsdetails_mods['dbname'] = $db_name;
$connectmysql_modsdetails_mods['dbuser'] = $db_username;
$connectmysql_modsdetails_mods['dbpass'] = $db_password;
}
endif;
if (!function_exists('database_connect')):
function database_connect()
{
global $connectmysql_mods;
global $connectmysql_modsdetails_mods;
$connectmysql_mods = mysqli_connect($connectmysql_modsdetails_mods['dbhost'], $connectmysql_modsdetails_mods['dbuser'], $connectmysql_modsdetails_mods['dbpass']);
$selected_db = mysqli_select_db($connectmysql_mods, $connectmysql_modsdetails_mods['dbname']);
if (!$selected_db)
{
return false;
}
}
endif;
if (!function_exists('select_query')):
function select_query($table, $fields, $where, $orderby = "", $orderbyorder = "", $limit = "", $innerjoin = "", $userHandle = null)
{
global $query_count;
global $mysql_errors;
global $connectmysql_mods;
if (!$fields)
{
$fields = "*";
}
$query = "SELECT " . $fields . " FROM " . db_make_safe_field($table);
if ($innerjoin)
{
$query .= " INNER JOIN " . db_escape_string($innerjoin) . "";
}
if ($where)
{
if (is_array($where))
{
$criteria = array();
foreach ($where as $origkey => $value)
{
$key = db_make_safe_field($origkey);
if (is_array($value))
{
if ($key == "default")
{
$key = "`default`";
}
if ($value['sqltype'] == "LIKE")
{
$criteria[] = "" . $key . " LIKE '%" . db_escape_string($value['value']) . "%'";
continue;
}
if ($value['sqltype'] == "NEQ")
{
$criteria[] = "" . $key . "!='" . db_escape_string($value['value']) . "'";
continue;
}
if ($value['sqltype'] == ">" && db_is_valid_amount($value['value']))
{
$criteria[] = "" . $key . ">" . $value['value'];
continue;
}
if ($value['sqltype'] == "<" && db_is_valid_amount($value['value']))
{
$criteria[] = "" . $key . "<" . $value['value'];
continue;
}
if ($value['sqltype'] == "<=" && db_is_valid_amount($value['value']))
{
$criteria[] = "" . $origkey . "<=" . $value['value'];
continue;
}
if ($value['sqltype'] == ">=" && db_is_valid_amount($value['value']))
{
$criteria[] = "" . $origkey . ">=" . $value['value'];
continue;
}
if ($value['sqltype'] == "TABLEJOIN")
{
$criteria[] = "" . $key . "=" . db_escape_string($value['value']) . "";
continue;
}
if ($value['sqltype'] == "IN")
{
$criteria[] = "" . $key . " IN (" . db_build_in_array($value['values']) . ")";
continue;
}
if ($value['sqltype'] == "DATEGREATER")
{
$criteria[] = "" . $origkey . ">=" . $value['value'];
continue;
}
if ($value['sqltype'] == "DATELESS")
{
$criteria[] = "" . $origkey . "<=" . $value['value'];
continue;
}
exit("Invalid input condition");
continue;
}
if (substr($key, 0, 3) == "MD5")
{
$key = explode("(", $origkey, 2);
$key = explode(")", $key[1], 2);
$key = db_make_safe_field($key[0]);
$key = "MD5(" . $key . ")";
}
else
{
$key = db_build_quoted_field($key);
}
$criteria[] = "" . $key . "='" . db_escape_string($value) . "'";
}
$query .= " WHERE " . implode(" AND ", $criteria);
}
else
{
$query .= " WHERE " . $where;
}
}
if ($orderby)
{
$orderbysql = tokenizeOrderby($orderby, $orderbyorder);
$query .= " ORDER BY " . implode(",", $orderbysql);
}
if ($limit)
{
if (strpos($limit, ","))
{
$limit = explode(",", $limit);
$limit = (int)$limit[0] . "," . (int)$limit[1];
}
else
{
$limit = (int)$limit;
}
$query .= " LIMIT " . $limit;
}
//echo $query.'
';
//return $query.'
';
$handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods);
$result = mysqli_query($handle, $query);
if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors))
{
}
++$query_count;
return $result;
}
endif;
if (!function_exists('tokenizeOrderby')):
function tokenizeOrderby($input, $default_ordering = "ASC", $userHandle = null)
{
$field_separator = ",";
$field_begin = "`";
$field_end = "`";
$seg_qualifier = ".";
$qualifier = $field_end . $seg_qualifier . $field_begin;
$order_up_rev = "CSA ";
$order_down_rev = "CSED ";
if ($default_ordering)
{
$default_ordering = trim($default_ordering);
}
else
{
$default_ordering = "ASC";
}
$default_ordering_rev = strrev(" " . $default_ordering);
if ($default_ordering_rev != $order_up_rev && $default_ordering_rev != $order_down_rev)
{
$default_ordering_rev = $order_up_rev;
}
$tokenizedFields = array();
$i = 0;
$field = strtok($input, $field_separator);
while ($i < 30 && $field !== false)
{
$field = trim($field);
if (!$field)
{
continue;
}
while (strpos($field, $field_begin) === 0)
{
$field = substr($field, 1);
}
$rev_field = strrev($field);
$ordering_field_rev = "";
if (strpos($rev_field, $order_up_rev) === 0)
{
$ordering_field_rev .= $order_up_rev;
$rev_field = substr($rev_field, strlen($order_up_rev));
}
else
{
if (strpos($rev_field, $order_down_rev) === 0)
{
$ordering_field_rev .= $order_down_rev;
$rev_field = substr($rev_field, strlen($order_down_rev));
}
else
{
$ordering_field_rev .= $default_ordering_rev;
}
}
while (strpos($rev_field, $field_end) === 0)
{
$rev_field = substr($rev_field, 1);
}
$field = strrev($rev_field);
$field_parts = explode($qualifier, $field, 2);
$safe_field_parts = array();
foreach ($field_parts as $key => $part)
{
$tmp_part = db_make_safe_field($part);
if ($tmp_part === trim($part))
{
$safe_field_parts[] = $tmp_part;
continue;
}
}
if (1 < count($safe_field_parts))
{
$field = implode($qualifier, $safe_field_parts);
}
else
{
$field = array_shift($safe_field_parts);
}
if ($field)
{
$tokenizedFields[] = $field_begin . $field . $field_end . strrev($ordering_field_rev);
}
$field = strtok($field_separator);
++$i;
}
return $tokenizedFields;
}
endif;
if (!function_exists('update_query')):
function update_query($table, $array, $where, $userHandle = null)
{
global $query_count;
global $mysql_errors;
global $connectmysql_mods;
$query = "UPDATE " . db_make_safe_field($table) . " SET ";
foreach ($array as $key => $value)
{
$query .= db_build_quoted_field($key) . "=";
$key = db_make_safe_field($key);
if ($value === "now()")
{
$query .= "'" . date("Y-m-d H:i:s") . "',";
continue;
}
if ($value === "+1")
{
$query .= "`" . $key . "`+1,";
continue;
}
if ((is_array($value) && isset($value['type'])) && $value['type'] == "AES_ENCRYPT")
{
$query .= sprintf("AES_ENCRYPT('%s','%s'),", db_escape_string($value['text']) , db_escape_string($value['hashkey']));
continue;
}
if ($value === "NULL")
{
$query .= "NULL,";
continue;
}
if (substr($value, 0, 2) === "+=" && db_is_valid_amount(substr($value, 2)))
{
$query .= "`" . $key . "`+" . substr($value, 2) . ",";
continue;
}
if (substr($value, 0, 2) === "-=" && db_is_valid_amount(substr($value, 2)))
{
$query .= "`" . $key . "`-" . substr($value, 2) . ",";
continue;
}
$query .= "'" . db_escape_string($value) . "',";
}
$query = substr($query, 0, 0 - 1);
if (is_array($where))
{
$query .= " WHERE";
foreach ($where as $key => $value)
{
if (substr($key, 0, 4) == "MD5(")
{
$key = "MD5(" . db_make_safe_field(substr($key, 4, 0 - 1)) . ")";
}
else
{
$key = db_make_safe_field($key);
if ($key == "order")
{
$key = "`order`";
}
}
$query .= " " . $key . "='" . db_escape_string($value) . "' AND";
}
$query = substr($query, 0, 0 - 4);
}
else
{
if ($where)
{
$query .= " WHERE " . $where;
}
}
//echo $query.'
';
$handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods);
$result = mysqli_query($handle, $query);
if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors))
{
}
++$query_count;
}
endif;
if (!function_exists('insert_query')):
function insert_query($table, $array, $userHandle = null)
{
global $query_count;
global $mysql_errors;
global $connectmysql_mods;
$fieldnamelist = $fieldvaluelist = "";
$query = "INSERT INTO " . db_make_safe_field($table) . " ";
foreach ($array as $key => $value)
{
$fieldnamelist .= db_build_quoted_field($key) . ",";
if ($value === "now()")
{
$fieldvaluelist .= "'" . date("Y-m-d H:i:s") . "',";
continue;
}
if ($value === "NULL")
{
$fieldvaluelist .= "NULL,";
continue;
}
$fieldvaluelist .= "'" . db_escape_string($value) . "',";
}
$fieldnamelist = substr($fieldnamelist, 0, 0 - 1);
$fieldvaluelist = substr($fieldvaluelist, 0, 0 - 1);
$query .= "(" . $fieldnamelist . ") VALUES (" . $fieldvaluelist . ")";
//echo $query;
$handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods);
$result = mysqli_query($handle, $query);
if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors))
{
}
++$query_count;
$id = mysqli_insert_id($connectmysql_mods);
return $id;
}
endif;
if (!function_exists('delete_query')):
function delete_query($table, $where, $userHandle = null)
{
global $query_count;
global $mysql_errors;
global $connectmysql_mods;
$query = "DELETE FROM " . db_make_safe_field($table) . " WHERE ";
if (is_array($where))
{
foreach ($where as $key => $value)
{
$query .= db_build_quoted_field($key) . "='" . db_escape_string($value) . "' AND ";
}
$query = substr($query, 0, 0 - 5);
}
else
{
$query .= $where;
}
$handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods);
$result = mysqli_query($handle, $query);
if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors))
{
}
++$query_count;
}
endif;
if (!function_exists('db_build_quoted_field')):
function db_build_quoted_field($key)
{
$field_quote = "`";
$parts = explode(".", $key, 3);
foreach ($parts as $k => $name)
{
$clean_name = db_make_safe_field($name);
if ($clean_name !== $name)
{
exit("Unexpected input field parameter in database query.");
}
$parts[$k] = $field_quote . $clean_name . $field_quote;
}
return implode(".", $parts);
}
endif;
if (!function_exists('full_query')):
function full_query($query, $userHandle = null)
{
global $query_count;
global $mysql_errors;
global $connectmysql_mods;
$handle = (is_resource($userHandle) ? $userHandle : $connectmysql_mods);
$result = mysqli_query($handle, $query);
if (!$result && ($CONFIG['SQLErrorReporting'] || $mysql_errors))
{
}
++$query_count;
return $result;
}
endif;
if (!function_exists('get_query_val')):
function get_query_val($table, $field, $where, $orderby = "", $orderbyorder = "", $limit = "", $innerjoin = "")
{
$result = select_query($table, $field, $where, $orderby, $orderbyorder, $limit, $innerjoin);
$data = mysqli_fetch_array($result);
return $data[0];
}
endif;
if (!function_exists('get_query_vals')):
function get_query_vals($table, $field, $where, $orderby = "", $orderbyorder = "", $limit = "", $innerjoin = "")
{
$result = select_query($table, $field, $where, $orderby, $orderbyorder, $limit, $innerjoin);
$data = mysqli_fetch_array($result);
return $data;
}
endif;
if (!function_exists('db_escape_string')):
function db_escape_string($string)
{
global $connectmysql_mods;
$string = mysqli_real_escape_string($connectmysql_mods, $string);
return $string;
}
endif;
if (!function_exists('db_escape_array')):
function db_escape_array($array)
{
$array = array_map("db_escape_string", $array);
return $array;
}
endif;
if (!function_exists('db_escape_numarray')):
function db_escape_numarray($array)
{
$array = array_map("intval", $array);
return $array;
}
endif;
if (!function_exists('db_build_in_array')):
function db_build_in_array($array, $allow_empty = false)
{
$in = "";
foreach ($array as $k => $v)
{
if (!trim($v) && !$allow_empty)
{
unset($array[$k]);
continue;
}
if (is_numeric($v))
{
$v;
continue;
}
$array[$k] = "'" . db_escape_string($v) . "'";
}
return implode(",", $array);
}
endif;
if (!function_exists('db_make_safe_field')):
function db_make_safe_field($field)
{
return db_escape_string(preg_replace("/[^a-z0-9_.,]/i", "", $field));
}
endif;
if (!function_exists('db_build_update_array')):
function db_build_update_array($fields, $arrayhandler = "serialize")
{
global $whmcs;
$array = array();
foreach ($fields as $key)
{
$array[$key] = $whmcs->get_req_var($key);
if (is_array($array[$key]))
{
if ($arrayhandler == "serialize")
{
$array[$key] = serialize($array[$key]);
continue;
}
if ($arrayhandler == "implode")
{
$array[$key] = implode(",", $array[$key]);
continue;
}
continue;
}
}
return $array;
}
endif;
if (!function_exists('db_make_safe_date')):
function db_make_safe_date($date)
{
$dateparts = explode("-", $date);
$date = (int)$dateparts[0] . "-" . str_pad((int)$dateparts[1], 2, "0", STR_PAD_LEFT) . "-" . str_pad((int)$dateparts[2], 2, "0", STR_PAD_LEFT);
return db_escape_string($date);
}
endif;
if (!function_exists('db_make_safe_human_date')):
function db_make_safe_human_date($date)
{
$date = toMySQLDate($date);
return db_make_safe_date($date);
}
endif;
if (!function_exists('db_is_valid_amount')):
function db_is_valid_amount($amount)
{
return preg_match('/^-?[0-9\.]+$/', $amount) === 1 ? true : false;
}
endif;
if (!function_exists('mysqli_field_name')):
function mysqli_field_name($result, $field_offset)
{
$properties = mysqli_fetch_field_direct($result, $field_offset);
return is_object($properties) ? $properties->name : null;
}
endif;
set_details_mods();
database_connect();
?>
function save_send_pushnotification($uid, $type, $title, $message, $img)
{
$arr['relid'] = $uid;
$arr['noti_type'] = $type;
$arr['header'] = $title;
$arr['message'] = $message;
$arr['datetime'] = 'now()';
$arr['viewed'] = '0';
$arr['push_ios'] = '1';
$arr['push_sent'] = 'now()';
insert_query("tblclients_notifications", $arr);
send_pushnotification($uid, $title, $message, $img);
logActivity("Push notification sent (".$title.")", $_SESSION['uid']);
}
function send_pushnotification($uid, $title, $message, $img)
{
$query = full_query('SELECT * FROM tblclients_ios WHERE relid="'.$uid.'"');
if(mysqli_num_rows($query) > 0)
{
while($res = mysqli_fetch_assoc($query))
{
fire_pushnotification($res['push_id'], $title, $message, $img);
}
}
}
function fire_pushnotification($to, $title, $message, $img)
{
$msg = $message;
$content = array(
"en" => $msg
);
$headings = array(
"en" => $title
);
if ($img == '') {
$fields = array(
'app_id' => 'f990f727-92e2-4a93-aeaa-22b49825e8f5',
"headings" => $headings,
'include_player_ids' => array($to),
'large_icon' => "",
'content_available' => true,
'contents' => $content
);
} else {
$ios_img = array(
"id1" => $img
);
$fields = array(
'app_id' => 'f990f727-92e2-4a93-aeaa-22b49825e8f5',
"headings" => $headings,
'include_player_ids' => array($to),
'contents' => $content,
"big_picture" => $img,
'large_icon' => "https://www.google.co.in/images/branding/googleg/1x/googleg_standard_color_128dp.png",
'content_available' => true,
"ios_attachments" => $ios_img
);
}
$headers = array(
'Authorization: key=MDc0MWJlNTMtZmVkOS00ZWEzLTgyZGEtYWFlMjcxMzQwZDMy',
'Content-Type: application/json; charset=utf-8'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://onesignal.com/api/v1/notifications');
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
?>
function sendMessage($template, $func_id, $extra = "", $displayresult = "", $attachment = "")
{
global $_LANG;
global $currency;
global $fromname;
global $fromemail;
global $currentPackage;
$sysurl = 'https://www.app.pay-me.co.uk/';
$nosavemaillog = false;
$firstname = $email = $attachmentfilename = "";
$email_merge_fields = array();
$messageName = (string) $template;
$attachments_dir = "/var/www/vhosts/paymyservices.co.uk/public_html/application/uploads/invoices/";
$userid = $func_id;
if (is_string($template)) {
$template = get_template_content($userid, "", $messageName);
}
$subject = $template['subject'];
$message = $template['message'];
$fromname = $template['fromName'];
$fromemail = $template['fromEmail'];
if ($template['disabled']) {
if ($displayresult) {
echo "
The '" . $messageName . "' email template has been disabled (" . Sanitize::makeSafeForOutput($template->subject) . ")
"; } return false; } if ($template['group'] == "invoice") { $appointment_query = select_query("tblclient_requests", "*", array("customer_relid"=>$userid,"relid"=>$extra['uid'], "id"=>$extra['id'])); $appointment_data = mysqli_fetch_array($appointment_query); $clientid = $appointment_data['relid']; $clientdetails = getuserdetails($clientid); $email_merge_fields['fullname'] = $clientdetails['firstname'].' '.$clientdetails['lastname']; $email_merge_fields['fname'] = $clientdetails['firstname']; $email_merge_fields['email'] = $clientdetails['email']; $email_merge_fields['paycode'] = $appointment_data['paycode']; $email_merge_fields['description'] = $appointment_data['description']; $email_merge_fields['date'] = date("d/m/Y", strtotime($appointment_data['datetime'])); $email_merge_fields['time'] = date("H:i", strtotime($appointment_data['datetime'])).' - '. date("H:i", strtotime($appointment_data['endtime'])); $email_merge_fields['amount'] = '£'.$appointment_data['amount']; $header_title = "Invoice #".$appointment_data['invoiceid']; $fromemail = "paymentrequests@pay-me.co.uk"; } else { if($template['group'] == 'appointment') { $appointment_query = select_query("tblclients_appointments", "*", array("customer_relid"=>$userid,"relid"=>$extra['uid'], "id"=>$extra['id'])); $appointment_data = mysqli_fetch_array($appointment_query); $clientid = $appointment_data['relid']; $clientdetails = getuserdetails($clientid); $email_merge_fields['fullname'] = $clientdetails['firstname'].' '.$clientdetails['lastname']; $email_merge_fields['fname'] = $clientdetails['firstname']; $email_merge_fields['email'] = $clientdetails['email']; $email_merge_fields['description'] = $appointment_data['description']; $email_merge_fields['date'] = date("d/m/Y", strtotime($appointment_data['datetime'])); $email_merge_fields['time'] = date("H:i", strtotime($appointment_data['datetime'])).' - '. date("H:i", strtotime($appointment_data['endtime'])); $header_title = "Appointment Confirmed"; $fromemail = "appointments@pay-me.co.uk"; } else { if($template['group'] == 'request') { $header_title = "New Payment Request"; $appointment_query = select_query("tblclient_requests", "*", array("customer_relid"=>$userid,"relid"=>$extra['uid'], "id"=>$extra['id'])); $appointment_data = mysqli_fetch_array($appointment_query); $clientid = $appointment_data['relid']; $clientdetails = getuserdetails($clientid); $email_merge_fields['fullname'] = $clientdetails['firstname'].' '.$clientdetails['lastname']; $email_merge_fields['fname'] = $clientdetails['firstname']; $email_merge_fields['email'] = $clientdetails['email']; $email_merge_fields['paycode'] = $appointment_data['paycode']; $email_merge_fields['description'] = $appointment_data['description']; $email_merge_fields['date'] = date("d/m/Y", strtotime($appointment_data['datetime'])); $email_merge_fields['time'] = date("H:i", strtotime($appointment_data['datetime'])).' - '. date("H:i", strtotime($appointment_data['endtime'])); $header_title = "Payment Request: £".$appointment_data['amount']; $fromemail = "paymentrequests@pay-me.co.uk"; } } } if ($userid) { $result2 = select_query("tblclients_customers", "*", array("id" => $userid)); $data2 = mysqli_fetch_array($result2); if (empty($firstname) && empty($email)) { $firstname = $data2["firstname"]; $email = $data2["email"]; } $lastname = $data2["lastname"]; $companyname = $data2["companyname"]; $address1 = $data2["address1"]; $address2 = $data2["address2"]; $city = $data2["city"]; $state = $data2["state"]; $postcode = $data2["postcode"]; $country = $data2["country"]; $phonenumber = $data2["phonenumber"]; $datecreated = fromMySQLDate($data2["created_at"], 0, 1); //$currency = getCurrency($userid); $totalInvoices = get_query_val("tblclient_requests", "SUM(amount)", array("customer_relid" => $userid, "status" => "Unpaid")); } if (!$email) { return false; } $fname = trim($firstname . " " . $lastname); if ($companyname) { $fname .= " (" . $companyname . ")"; } $email_merge_fields["client_id"] = $userid; $email_merge_fields["client_name"] = $fname; $email_merge_fields["client_first_name"] = $firstname; $email_merge_fields["client_last_name"] = $lastname; $email_merge_fields["client_company_name"] = $companyname; $email_merge_fields["client_email"] = $email; $email_merge_fields["client_address1"] = $address1; $email_merge_fields["client_address2"] = $address2; $email_merge_fields["client_city"] = $city; $email_merge_fields["client_state"] = $state; $email_merge_fields["client_postcode"] = $postcode; $email_merge_fields["client_country"] = $country; $email_merge_fields["client_phonenumber"] = $phonenumber; $email_merge_fields["client_signup_date"] = $datecreated; foreach($email_merge_fields as $key => $val) { $before[] = "{".$key."}"; $after[] = $val; } $subject = str_replace($before, $after, $subject); $message = str_replace($before, $after, $message); $pretext = '
|
Email Sent Successfully to " . Sanitize::makeSafeForOutput((string) $firstname . " " . $lastname) . "
"; } insert_query("tblclients_emails", array("relid" => $extra['uid'], "customer_relid"=>$userid, "subject" => $subject, "message" => $message, "date" => "now()", "to" => $email, "created_at"=>"now()")); $emailuserlink = 0 < $userid ? " - Customer ID: " . $userid : ""; logActivity("Email Sent to " . $firstname . " " . $lastname . " (" . $subject . ") " . $emailuserlink, $extra['uid'], $userid); $mail->ClearAddresses(); if($currentPackage['payment_reminders'] != 'Unlimited'){ deduct_Email(array("userid"=>$extra['uid'])); } return 'sent'; } } catch (phpmailerException $e) { logActivity("Email Sending Failed - " . $e->getMessage() . " (Customer ID: " . $userid . " - Subject: " . $subject . ")", "none"); if ($displayresult) { echo "Email Sending Failed - " . $e->errorMessage() . "
"; } } catch (Exception $e) { logActivity("Email Sending Failed - " . $e->getMessage() . " (Customer ID: " . $userid . " - Subject: " . $subject . ")", "none"); if ($displayresult) { echo "Email Sending Failed - " . $e->getMessage() . "
"; } } return true; } function pdfInvoice($requestid, $checkPDF = NULL) { $invoice = new Invoice(); $invoice->pdfCreate(); $check = $invoice->pdfInvoicePage($requestid); if($checkPDF) { if(!$check) return false; return true; } if(!$check) return false; $pdfdata = $invoice->pdfOutput(); return array("data"=>$pdfdata, "id"=>$check); } function GenerateInvoice($id, $send = FALSE) { $viewpdf = false; if($_GET['type'] == 'i') $viewpdf = true; $pdfdata = pdfInvoice($id); if(!$pdfdata) return false; $filenameSuffix = preg_replace("|[\\\\/]+|", "-", $id); if($send) { $date = date('ymdhis'); $link = '/var/www/vhosts/paymyservices.co.uk/public_html/application/uploads/invoices/Invoice_'.$pdfdata['id'].'_'.$date.'.pdf'; unlink($link); file_put_contents( $link, $pdfdata['data']); return 'Invoice_'.$pdfdata['id'].'_'.$date.'.pdf'; } header("Pragma: public"); header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0, private"); header("Cache-Control: private", false); header("Content-Type: application/pdf"); header("Content-Disposition: " . ($viewpdf ? "inline" : "attachment") . "; filename=\"" . 'Invoice' . '_'.$pdfdata['id'] .".pdf\""); header("Content-Transfer-Encoding: binary"); header("Content-Length: " . strlen($pdfdata['data'])); echo $pdfdata['data']; die(); } class Sanitize { public static function makeSafeForOutput($val) { $input = new Sanitize(); $val = $input->decode($val); return $input->encode($val); } public static function convertToCompatHtml($val) { $input = new Sanitize(); $val = $input->decode($val); $val = $input->decode($val); return $input->encodeToCompatHTML($val); } public static function encode($val) { $input = new Sanitize(); if (is_bool($val)) { return $val; } if (is_numeric($val)) { return $val; } if (is_string($val)) { return $input->encodeString($val); } if (is_array($val)) { return $input->encodeArray($val); } if (is_object($val)) { return $val; } return ""; } public static function encodeToCompatHTML($val) { $input = new Sanitize(); if (is_bool($val)) { return $val; } if (is_numeric($val)) { return $val; } if (is_string($val)) { return $input->encodeStringToCompatHTML($val); } if (is_array($val)) { return $input->encodeArrayToCompatHTML($val); } if (is_object($val)) { return $val; } return ""; } public static function decode($val) { $input = new Sanitize(); if (is_bool($val)) { return $val; } if (is_numeric($val)) { return $val; } if (is_string($val)) { return $input->decodeString($val); } if (is_array($val)) { return $input->decodeArray($val); } if (is_object($val)) { return $val; } return ""; } protected function encodeArray($array) { foreach ($array as $k => $v) { $array[$k] = $this->encode($v); } return $array; } protected function encodeArrayToCompatHTML($array) { foreach ($array as $k => $v) { $array[$k] = $this->encodeToCompatHTML($v); } return $array; } protected function decodeArray($array) { foreach ($array as $k => $v) { $array[$k] = $this->decode($v); } return $array; } protected function encodeString($val) { return htmlspecialchars($val, ENT_QUOTES); } protected function encodeStringToCompatHTML($val) { static $mask = NULL; if (!isset($mask)) { $mask = $this->getCompatBitmask(); } return htmlspecialchars($val, $mask); } public function getCompatBitmask() { $mask = ENT_COMPAT; if (defined("ENT_HTML401")) { $mask = $mask | ENT_HTML401; } return $mask; } protected function decodeString($val) { $val = str_replace(" ", " ", $val); return html_entity_decode($val, ENT_QUOTES); } public static function maskEmailVerificationId($message) { $mask = "verificationId=%2A"; $regex = "%verificationId=[0-9a-f]{40}%i"; $maskedMessage = preg_replace($regex, $mask, $message); return $maskedMessage; } public static function escapeSingleQuotedString($content) { $content = str_replace("\\", "\\\\", $content); $content = str_replace("'", "\\'", $content); return $content; } public static function stripTags($val, $allowedTags = "") { $input = new Sanitize(); if (is_bool($val)) { return $val; } if (is_numeric($val)) { return $val; } if (is_string($val)) { return $input->stripTagsFromString($val, $allowedTags); } if (is_array($val)) { return $input->stripTagsFromArray($val, $allowedTags); } if (is_object($val)) { return $val; } return ""; } protected function stripTagsFromString($val, $allowedTags) { $val = $this->decodeString($val); $val = strip_tags($val, $allowedTags); return $this->encodeString($val); } protected function stripTagsFromArray(array $array, $allowedTags) { foreach ($array as $k => $v) { $array[$k] = $this->stripTags($v, $allowedTags); } return $array; } } function uuidv4($data) { $data = openssl_random_pseudo_bytes(16); assert(strlen($data) == 16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0100 $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10 return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } ?> function update_email_template($v) { if($v['custom'] == '0') { $insert = array("relid"=>$_SESSION['uid'], "group"=>$v['group'], "type"=>"email", "name"=>$v['name'], "subject"=>$v['subject'], "message"=>$v['message'], "fromname"=>"{fullname}", "fromemail"=>"{email}","custom"=>"1","plaintext"=>"1","created_at"=>"now()"); $insertid = insert_query("tblclient_emailtemplates", $insert); echo $insertid; } else { update_query("tblclient_emailtemplates", array("subject"=>$v['subject'], "message"=>$v['message']), array("id"=>$v['id'], "relid"=>$_SESSION['uid'], "custom"=>"1")); echo $v['id']; } die(); } function get_template_content($userid, $type = NULL, $name) { if($type) { $find = select_query("tblclient_emailtemplates", "*", array("relid"=>$userid,"type"=>$type,"name"=>$name,"custom"=>"1")); } else { $find = select_query("tblclient_emailtemplates", "*", array("relid"=>$userid,"name"=>$name,"custom"=>"1")); } if(mysqli_num_rows($find) > 0) { $data = mysqli_fetch_array($find); } else { if($type) { $find = select_query("tblclient_emailtemplates", "*", array("relid"=>"0","type"=>$type,"name"=>$name,"custom"=>"0")); } else { $find = select_query("tblclient_emailtemplates", "*", array("relid"=>"0","name"=>$name,"custom"=>"0")); } $data = mysqli_fetch_array($find); } return $data; } function get_email_templates($type, $id = NULL) { $uid = $_SESSION['uid']; if($id) { $query = full_query("SELECT * FROM `tblclient_emailtemplates` WHERE `id` = '$id'"); $res = mysqli_fetch_array($query); $name = $res['name']; $query2 = full_query("SELECT * FROM `tblclient_emailtemplates` WHERE `relid` = '$uid' AND `name` LIKE '$name' "); if(mysqli_num_rows($query2) > 0) { $data = mysqli_fetch_array($query2); return $data; } return $res; } else { $query = full_query("SELECT * FROM `tblclient_emailtemplates` WHERE `relid` = '0' AND `type` LIKE '$type' "); while($res = mysqli_fetch_assoc($query)) { $arr[$res['name']] = $res; } $query = full_query("SELECT * FROM `tblclient_emailtemplates` WHERE `relid` = '$uid' AND `type` LIKE '$type' "); while($res = mysqli_fetch_assoc($query)) { $arr[$res['name']] = $res; } return $arr; } } if (!function_exists('randomPassword')) { function randomPassword() { $alphabet = "abcdefghijklmnopqrstuwxyz0123456789"; $pass = array(); //remember to declare $pass as an array $alphaLength = strlen($alphabet) - 1; //put the length -1 in cache for ($i = 0; $i < 5; $i++) { $n = rand(0, $alphaLength); $pass[] = $alphabet[$n]; } return implode($pass); //turn the array into a string } } if (!function_exists('resetpassword')) { function resetpassword($v) { $_SESSION['email_has_account'] = 'no'; $var = checkLogin($v['email']); $password2 = randomPassword(); if(is_array($var)) { sendresetpassword($var, '', $password2); $_SESSION['email_has_account'] = 'yes'; } if(is_array($var2)) { sendresetpassword($var2, 'nsb', $password2); $_SESSION['email_has_account'] = 'yes'; } $_SESSION['error_login'] = 'resetpassword'; } } if (!function_exists('sendresetpassword')) { function sendresetpassword($v, $type, $password2) { global $CONFIG; if($type == 'nsb') { $url = $CONFIG['nsb_whmcs_url']; # URL to WHMCS API file $username = $CONFIG['nsb_whmcs_user']; # Admin username goes here $password = $CONFIG['nsb_whmcs_pass']; # Admin password goes here } else { $url = $CONFIG['whmcs_url']; # URL to WHMCS API file $username = $CONFIG['whmcs_user']; # Admin username goes here $password = $CONFIG['whmcs_pass']; # Admin password goes here } $postfields["username"] = $username; $postfields["password"] = md5($password); $postfields["action"] = "updateclient"; $postfields["clientid"] = $v['userid']; $postfields["password2"] = $password2; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 100); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); $data = curl_exec($ch); curl_close($ch); $data = explode(";", $data); foreach ($data AS $temp) { $temp = explode("=", $temp); $results[$temp[0]] = $temp[1]; } if ($results["result"] == "success") { $postfields["username"] = $username; $postfields["password"] = md5($password); $postfields["action"] = "SendEmail"; $postfields["id"] = $v['userid']; $postfields["customtype"] = 'general'; $postfields["custommessage"] = 'Hi {$client_first_name},'; print_r($results); echo '';*/ if ($results["result"]=="success") { $query = full_query('SELECT * FROM tblclients WHERE id="'.$results['userid'].'"'); $data2 = mysqli_fetch_array($query); if($data2['status'] == 'Closed'): return 'nouser'; else: return $results; endif; } else { return 'nouser'; } } endif; ?> function upload_new_file($v) { $upload = 'err'; if(!empty($_FILES['file'])){ $targetDir = ROOTDIR.'/uploads/user_uploads/'; $allowTypes = array('jpg', 'png', 'jpeg', 'gif', 'JPG'); $fileName = basename($_FILES['file']['name']); $fileType = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION); if(in_array($fileType, $allowTypes)) { $type = $_POST['type']; $postid = $_SESSION['postid']; $list_date = date("Y-m-d-H-i-s"); $name = $_SESSION['uid'].'_profilephoto'; $targetFilePath = $targetDir.$name.'.'.$fileType; foreach (glob($targetDir.$name.".*") as $filename) { unlink($filename); } if(move_uploaded_file($_FILES['file']['tmp_name'], $targetFilePath)){ //$img_url = uploadAmazon($name.'.'.$fileType); //unlink($targetFilePath); $upload = '../../../uploads/user_uploads/'.$name.'.'.$fileType.'?nocache='.date('ymdhis');; } } } echo $upload; die(); } ?> define("K_TCPDF_EXTERNAL_CONFIG", true); define("PDF_CREATOR", "PAY-ME"); define("PDF_AUTHOR", "PAY-ME"); define("PDF_HEADER_TITLE", ""); define("PDF_HEADER_STRING", ""); define("PDF_MARGIN_FOOTER", 15); define("PDF_MARGIN_TOP", 25); class PDF extends \TCPDF { protected $paperSize = NULL; protected $headerTplFile = ""; protected $footerTplFile = ""; protected $templateVars = array(); public function __construct() { $unicode = strtolower(substr(\Configuration::get_config("Charset"), 0, 3)) != "iso"; $paperSize = \Configuration::get_config("PDFPaperSize"); if (!$paperSize) { $paperSize = "A4"; } $this->paperSize = $paperSize; parent::__construct("P", "mm", strtoupper($paperSize), $unicode, \Configuration::get_config("Charset"), false); $this->SetCreator("Pay-Me"); $this->SetAuthor("Pay-Me"); $this->SetMargins(15, 25, 15); $this->SetFooterMargin(15); $this->SetAutoPageBreak(true, 25); $this->setLanguageArray(array("a_meta_charset" => \Configuration::get_config("Charset"), "a_meta_dir" => "ltr", "a_meta_language" => "en", "w_page" => "page")); } public function setHeaderTplFile($headerTplFile) { $this->headerTplFile = $headerTplFile; } public function setFooterTplFile($footerTplFile) { $this->footerTplFile = $footerTplFile; } public function setTemplateVars(array $tplVars) { $this->templateVars = $tplVars; } public function Header() { if ($this->headerTplFile) { foreach ($this->templateVars as $k => $v) { ${$k} = $v; } $pdf =& $this; include $this->headerTplFile; } } public function Footer() { if ($this->footerTplFile) { foreach ($this->templateVars as $k => $v) { ${$k} = $v; } $pdf =& $this; include $this->footerTplFile; } } public function SetFont($family, $style = "", $size = NULL, $fontfile = "", $subset = "default", $out = true) { $adminFontSetting = \Configuration::get_config("TCPDFFont"); if (in_array($adminFontSetting, $this->fontlist)) { $familyOverride = $adminFontSetting; } else { if (in_array($family, $this->fontlist)) { $familyOverride = $family; } else { $familyOverride = PDF_FONT_NAME_MAIN; } } parent::SetFont($familyOverride, $style, $size, $fontfile, $subset, $out); } } function acceptOrder($orderid) { $command = 'AcceptOrder'; $postData = array( 'orderid' => $orderid, 'sendemail' => true, ); $adminUsername = ''; // Optional for WHMCS 7.2 and later $results = localAPI($command, $postData, $adminUsername); } function buyPlan($v) { $pid = $v['pid']; if($pid == '4') { $v['bundle'] = '20'; $v['emailbundle'] = '50'; }elseif($pid == '3') { $v['bundle'] = '100'; $v['emailbundle'] = '500'; }elseif($pid == '2') { $v['bundle'] = '200'; $v['emailbundle'] = '10000'; } $order = api_AddOrder($pid); $invoiceid = $order['invoiceid']; $orderid = $order['orderid']; if($invoiceid > 0) { $capture = api_CapturePayment($invoiceid); if($capture['result'] == 'success') { acceptOrder($orderid); return array("result"=>'success', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle'], "emailbundle"=>$v['emailbundle']); } else { return array("result"=>'error', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle'], "emailbundle"=>$v['emailbundle']); } } else { acceptOrder($orderid); return array("result"=>'success', "invoiceid"=>$invoiceid, "orderid"=>$orderid, "bundle"=>$v['bundle'], "emailbundle"=>$v['emailbundle']); } } function updateSettings($v) { $where['relid'] = $_SESSION['uid']; if($v['paymentreminders']) { if($v['paymentreminders'] =='no'){ $remind = '0'; } else { $remind="1"; } $arr['payment_reminders'] = $remind; //$query = full_query('UPDATE tblclient_notification_settings SET payment_reminders="'.$remind.'" WHERE relid="'.$_SESSION['uid'].'"'); update_query("tblclient_notification_settings", $arr, $where); if($v['day'] >= 0) { $arr['day'] = $v['day']; if($v['payment_time']) $arr['time'] = $v['payment_time']; if($v['send_sms'] == 'true'){ $arr['send_sms'] = 1; } else { $arr['send_sms'] = 0; } update_query("tblclient_notification_settings", $arr, $where); print_r($arr); } } if($v['appointreminders']) { if($v['appointreminders'] =='no'){ $appoint = '0'; } else { $appoint="1"; } $arr['appointment_reminders'] = $appoint; //$query = full_query('UPDATE tblclient_notification_settings SET payment_reminders="'.$remind.'" WHERE relid="'.$_SESSION['uid'].'"'); update_query("tblclient_notification_settings", $arr, $where); if($v['day'] >= 0) { $arr['appointment_day'] = $v['day']; if($v['time']) $arr['appointment_time'] = $v['time']; if($v['send_sms'] == 'true'){ $arr['appointment_send_sms'] = 1; } else { $arr['appointment_send_sms'] = 0; } update_query("tblclient_notification_settings", $arr, $where); } } if($v['hasinvoicing']) { if($v['hasinvoicing'] =='no'){ $hasinvoicing = '0'; } else { $hasinvoicing="1"; } $arr['hasinvoicing'] = $hasinvoicing; $arr['invoiceaddress'] = $v['invoiceaddress']; update_query("tblclient_notification_settings", $arr, $where); } } function get_notification_settings() { $notification_settings = full_query("SELECT * FROM tblclient_notification_settings WHERE relid='".$_SESSION['uid']."'"); $notification_settings = mysqli_fetch_array($notification_settings); return $notification_settings; } ?> function logActivity($description, $relid = "0", $customer_relid = "0") { $remote_ip = CurrentUser::getIP(); if (!isset($username)) { if (isset($_SESSION["uid"])) { $username = "Client"; } else { $username = "System"; } } if (!$userid && isset($_SESSION["uid"])) { $userid = $_SESSION["uid"]; } insert_query("tblclients_activitylog", array("date" => "now()", "description" => $description, "user" => $username, "relid" => $relid, "customer_relid"=>$customer_relid, "ipaddr" => $remote_ip)); } function toMySQLDate($date) { global $CONFIG; $day = substr($date, 8, 2); $month = substr($date, 5, 2); $year = substr($date, 0, 4); $hours = substr($date, 11, 2); $minutes = substr($date, 14, 2); $seconds = substr($date, 17, 2); if ($hours && !$seconds) { $seconds = "00"; } $date = $year . "-" . $month . "-" . $day; if ($hours) { $date .= " " . $hours . ":" . $minutes . ":" . $seconds; } return $date; } function fromMySQLDate($date, $time = "", $client = "", $zerodateval = "") { global $CONFIG; global $timeoffset; if (substr($date, 0, 10) == "0000-00-00" && $zerodateval) { return $zerodateval; } $year = substr($date, 0, 4); $month = substr($date, 5, 2); $day = substr($date, 8, 2); $hours = substr($date, 11, 2); $minutes = substr($date, 14, 2); $seconds = substr($date, 17, 2); if ($timeoffset) { $hours = $hours + $timeoffset; $new_time = mktime($hours, $minutes, $seconds, $month, $day, $year); $year = date("Y", $new_time); $month = date("m", $new_time); $day = date("d", $new_time); $hours = date("H", $new_time); $minutes = date("i", $new_time); $seconds = date("s", $new_time); } if ($client && $CONFIG['ClientDateFormat']) { if ($CONFIG['ClientDateFormat'] == "full") { $date = date("jS F Y", mktime(0, 0, 0, $month, $day, $year)); } else { if ($CONFIG['ClientDateFormat'] == "shortmonth") { $date = date("jS M Y", mktime(0, 0, 0, $month, $day, $year)); } else { if ($CONFIG['ClientDateFormat'] == "fullday") { $date = date("l, F jS, Y", mktime(0, 0, 0, $month, $day, $year)); } } } if ($time) { $date .= " (" . $hours . ":" . $minutes . ")"; } } else { $date = $CONFIG['DateFormat']; $date = str_replace("YYYY", $year, $date); $date = str_replace("MM", $month, $date); $date = str_replace("DD", $day, $date); if ($time) { $date .= " " . $hours . ":" . $minutes; } } return $date; } function validateDateInput($date) { $sqldate = toMySQLDate($date); $dateonly = explode(" ", $sqldate); $dateparts = explode("-", $dateonly[0]); list($year, $month, $day) = $dateparts; if (is_numeric($day) && is_numeric($month) && is_numeric($year)) { return checkdate($month, $day, $year); } return false; } function MySQL2Timestamp($datetime) { $val = explode(" ", $datetime, 2); $date = explode("-", $val[0]); if ($val[1]) { $time = explode(":", $val[1]); } else { $time = "00:00:00"; } return mktime($time[0], $time[1], $time[2], $date[1], $date[2], $date[0]); } function getTodaysDate($client = "") { return fromMySQLDate(date("Y-m-d"), 0, $client); } function xdecrypt($ckey, $string) { $string = base64_decode($string); $keys = array(); $c_key = base64_encode(sha1(md5($ckey))); $c_key = substr($c_key, 0, round(ord($ckey[0]) / 5)); $c2_key = base64_encode(md5(sha1($ckey))); $last = strlen($ckey) - 1; $c2_key = substr($c2_key, 1, round(ord($ckey[$last]) / 7)); $c3_key = base64_encode(sha1(md5($c_key) . md5($c2_key))); $mid = round($last / 2); $c3_key = substr($c3_key, 1, round(ord($ckey[$mid]) / 9)); $c_key = $c_key . $c2_key . $c3_key; $c_key = base64_encode($c_key); for ($i = 0; $i < strlen($c_key); $i++) { $keys[] = $c_key[$i]; } for ($i = 0; $i < strlen($string); $i++) { $id = $i % count($keys); $ord = ord($string[$i]); ord($keys[$id]); $ord = $ord xor ord($keys[$id]); $id++; $ord = $ord and ord($keys[$id]); ($ord = $ord) && ord($keys[$id]); $id++; $ord = $ord or ord($keys[$id]); ($ord = $ord) || ord($keys[$id]); $id++; $ord = $ord - ord($keys[$id]); $string[$i] = chr($ord); } return base64_decode($string); } if(!function_exists("encrypt_decrypt")) { function encrypt_decrypt($action, $string) { $output = false; $encrypt_method = "AES-256-CBC"; $secret_key = 'SBUCVDXFYGZJ3K4M5P7Q8RATBUCWEXFYH2J3K5N6P7R9SATCVDWEYGZH2J'; $secret_iv = '3K4M6P7Q8SATBUDWEXFZH2J3M5N6P8R9SAUCVDWEYGZH2K4M5N7Q8R9TBU'; // hash $key = hash('sha256', $secret_key); // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning $iv = substr(hash('sha256', $secret_iv), 0, 16); if ( $action == 'encrypt' ) { $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv); $output = str_replace("=", "|", base64_encode($output)); } else if( $action == 'decrypt' ) { $output = openssl_decrypt(str_replace("=", "|", base64_decode($string)), $encrypt_method, $key, 0, $iv); } return $output; } } if (!function_exists('array_key_first')) { function array_key_first(array $arr) { foreach($arr as $key => $unused) { return $key; } return NULL; } } if(!function_exists("get_url_data")) { function get_url_data() { global $CONFIG; global $url_path; $arr = array(); $url_arr = explode("/", $_SERVER['REQUEST_URI']); foreach($url_arr as $url) { if($url != '') { $arr[] = $url; } } $count = array_search($url_path,$url_arr,true); $a['start'] = $count; $a['total'] = count($arr); $a['url'] = $arr; return $a; } } if(!function_exists('load_hooks')) { function load_hooks() { global $CONFIG; ob_start(); include_once(realpath(__DIR__ . DIRECTORY_SEPARATOR . "hookfunctions.php")); ob_end_clean(); } } if(!function_exists('system_settings')) { function system_settings() { $query = full_query("SELECT * FROM `tblconfiguration`"); while($res = mysqli_fetch_assoc($query)) { $a[$res['setting']] = $res['value']; } $a['template'] = 'Resellers'; return $a; } } ?> class Configuration { public static function get_config($key) { $query = select_query("tblconfiguration", "value", array("setting"=>$key)); $data = mysqli_fetch_array($query); return htmlspecialchars_decode($data['value']); } } function get_notications() { $query = full_query("SELECT * FROM tblclients_notifications WHERE relid='".$_SESSION['uid']."' ORDER BY datetime DESC"); while($res = mysqli_fetch_assoc($query)) { $arr[$res['id']]['title'] = $res['header']; $arr[$res['id']]['noti_type'] = $res['noti_type']; $arr[$res['id']]['friendlydate'] = notification_timeago($res['datetime']); $arr[$res['id']]['seen'] = $res['viewed']; } return $arr; } function notification_timeago($time_ago) { $time_ago = strtotime($time_ago); $cur_time = time(); $time_elapsed = $cur_time - $time_ago; $seconds = $time_elapsed ; $minutes = round($time_elapsed / 60 ); $hours = round($time_elapsed / 3600); $days = round($time_elapsed / 86400 ); $weeks = round($time_elapsed / 604800); $months = round($time_elapsed / 2600640 ); $years = round($time_elapsed / 31207680 ); // Seconds if($seconds <= 60){ return "just now"; } //Minutes else if($minutes <=60){ if($minutes==1){ return "one minute ago"; } else{ return "$minutes minutes ago"; } } //Hours else if($hours <=24){ if($hours==1){ return "an hour ago"; }else{ return "$hours hrs ago"; } } //Days else if($days <= 7){ if($days==1){ return "yesterday"; }else{ return "$days days ago"; } } //Weeks else if($weeks <= 4.3){ if($weeks==1){ return "a week ago"; }else{ return "$weeks weeks ago"; } } //Months else if($months <=12){ if($months==1){ return "a month ago"; }else{ return "$months months ago"; } } //Years else{ if($years==1){ return "one year ago"; }else{ return "$years years ago"; } } } ?> function set_user_variables() { global $CONFIG; global $currentPackage; global $email_credits; global $sms_credits; global $remainingLimits; if($_SESSION['uid'] > 0) { $sms_credits = getCredits(); $email_credits = getEmailCredits(); $remainingLimits = remainingLimits(); //$notification_settings = get_notification_settings(); $_SESSION['user'] = getuserdetails($_SESSION['uid']); $_SESSION['user']['sms_credits'] = number_format(($sms_credits['balance'] + $sms_credits['paidbalance']), 0); if($currentPackage['payment_reminders'] == 'Unlimited') { $_SESSION['user']['email_credits'] = '∞'; } else { $_SESSION['user']['email_credits'] = number_format(($email_credits['balance'] + $email_credits['paidbalance']), 0); } if(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.jpg')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.jpg?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.png')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.png?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.jpeg')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.jpeg?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.gif')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.gif?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.JPG')) { $_SESSION['user']['profilephoto'] = '../../../uploads/user_uploads/'.$_SESSION['uid'].'_profilephoto.JPG?nocache='.date('ymdhis'); } $_SESSION['user']['notification']['login'] = $notification_settings['login']; $_SESSION['user']['notification']['payment'] = $notification_settings['payment']; $_SESSION['user']['notification']['booking'] = $notification_settings['booking']; $_SESSION['user']['notification']['system'] = $notification_settings['system']; $_SESSION['user']['getstarted'] = $notification_settings['getstarted']; $_SESSION['user']['paymentreminders']['payment_reminders'] = $notification_settings['payment_reminders']; $_SESSION['user']['paymentreminders']['payment_day'] = get_payment_day($notification_settings['day']); $_SESSION['user']['paymentreminders']['payment_day_setting'] = $notification_settings['day']; $_SESSION['user']['paymentreminders']['payment_time'] = date('h:i A', strtotime($notification_settings['time'])); $_SESSION['user']['paymentreminders']['payment_time_setting'] = $notification_settings['time']; $_SESSION['user']['paymentreminders']['payment_sms_notification'] = $notification_settings['send_sms']; $_SESSION['user']['paymentreminders']['appointment_reminders'] = $notification_settings['appointment_reminders']; $_SESSION['user']['paymentreminders']['appointment_day'] = get_payment_day($notification_settings['appointment_day']); $_SESSION['user']['paymentreminders']['appointment_day_setting'] = $notification_settings['appointment_day']; $_SESSION['user']['paymentreminders']['appointment_time'] = date('h:i A', strtotime($notification_settings['appointment_time'])); $_SESSION['user']['paymentreminders']['appointment_time_setting'] = $notification_settings['appointment_time']; $_SESSION['user']['paymentreminders']['appointment_sms_notification'] = $notification_settings['sappointment_end_sms']; $_SESSION['user']['invoicing']['hasinvoicing'] = $notification_settings['hasinvoicing']; $_SESSION['user']['invoicing']['businessname'] = $notification_settings['businessname']; $_SESSION['user']['invoicing']['businessaddress'] = $notification_settings['businessaddress']; $_SESSION['user']['invoicing']['businesspostcode'] = $notification_settings['businesspostcode']; $_SESSION['user']['invoicing']['businessemail'] = $notification_settings['businessemail']; $_SESSION['user']['invoicing']['registrationnumber'] = $notification_settings['registrationnumber']; $_SESSION['user']['invoicing']['vatregistrationnumber'] = $notification_settings['vatregistrationnumber']; $query_brand = full_query("SELECT mod_brands.* FROM `mod_brands` LEFT JOIN tblclient_brands ON tblclient_brands.brandid=mod_brands.id WHERE tblclient_brands.relid = '".$_SESSION['uid']."' "); } else { //$_SERVER['PHP_SELF'] $query_brand = full_query("SELECT mod_brands.* FROM `mod_brands` LEFT JOIN tblclient_brands ON tblclient_brands.brandid=mod_brands.id WHERE mod_brands.brand_url = '".$_SERVER['HTTP_HOST']."' "); } if(mysqli_num_rows($query_brand) > 0) { $data = mysqli_fetch_array($query_brand); $_SESSION['brand_name'] = $data['brand_name']; $_SESSION['brand_logo'] = $data['brand_logo']; $_SESSION['logo_width'] = $data['logo_width']; $_SESSION['primary_col'] = $data['primary_col']; $_SESSION['secondary_col'] =$data['secondary_col']; $_SESSION['link_col'] = $data['link_col']; } else { $_SESSION['brand_name'] = $data['brand_logo']; $_SESSION['brand_logo'] = $data['brand_logo']; $_SESSION['logo_width'] = $data['logo_width']; $_SESSION['primary_col'] = $data['primary_col']; $_SESSION['secondary_col'] =$data['secondary_col']; $_SESSION['link_col'] = $data['link_col']; } } if(!function_exists('get_payment_day')) { function get_payment_day($id) { switch ($id) { case 0: return 'Every Day'; break; case 1: return 'Every Monday'; break; case 2: return 'Every Tuesday'; break; case 3: return 'Every Wednesday'; break; case 4: return 'Every Thursday'; break; case 5: return 'Every Friday'; break; case 6: return 'Every Saturday'; break; case 7: return 'Every Sunday'; break; } } } if(!function_exists('switch_theme')) { function switch_theme($group) { switch ($group) { case 0: return 'Portal'; break; case 1: return 'Development'; break; default: return 'Portal'; } } } if (!function_exists('get_client_ip')) { function get_client_ip() { $ipaddress = ''; if (getenv('HTTP_CLIENT_IP')) $ipaddress = getenv('HTTP_CLIENT_IP'); else if(getenv('HTTP_X_FORWARDED_FOR')) $ipaddress = getenv('HTTP_X_FORWARDED_FOR'); else if(getenv('HTTP_X_FORWARDED')) $ipaddress = getenv('HTTP_X_FORWARDED'); else if(getenv('HTTP_FORWARDED_FOR')) $ipaddress = getenv('HTTP_FORWARDED_FOR'); else if(getenv('HTTP_FORWARDED')) $ipaddress = getenv('HTTP_FORWARDED'); else if(getenv('REMOTE_ADDR')) $ipaddress = getenv('REMOTE_ADDR'); else $ipaddress = 'UNKNOWN'; return $ipaddress; } } if (!function_exists('create_page')) { function create_page($page_data) { global $CONFIG; global $defaulturl; global $install_path; global $currentPackage; global $rp; $ca = new ClientArea(); $ca->initPage($page_data['theme']); if(is_array($_SESSION['accounts'])) $ca->assign('numaccounts',count($_SESSION['accounts'])); $ca->assign('todaysdate', date("l jS F Y", strtotime('today GMT'))); $ca->assign('datetoday', date("d/m/Y")); $ca->assign('clientip', get_client_ip()); $ca->assign('useragent', $_SERVER['HTTP_USER_AGENT']); $ca->assign('currentpackage', $currentPackage); $ca->assign('nocache', date('ymdhis')); $notifications = header_get_notifications(); if(is_array($notifications)) $ca->assign('notifications', $notifications); $ca->assign("theme_folder", '//' . $_SERVER['HTTP_HOST'] . '/templates/' . $page_data['theme'] . '/'); if($install_path) { $ca->assign("rooturl", '//' . $_SERVER['HTTP_HOST'] . '/' . $install_path); } else { $ca->assign("rooturl", '//' . $_SERVER['HTTP_HOST'] . '/' ); } $ca->assign("editor", true); if (is_array($CONFIG)) { foreach ($CONFIG as $k => $v) { if ($k == 'HeaderCode') if ($v != '') $v = urldecode($v); if ($k == 'FooterCode') if ($v != '') $v = urldecode($v); $ca->assign($k, $v); } } if (is_array($page_data)) { foreach ($page_data as $a => $b) { if ($a == 'HeaderCode') if ($b != '') $b = urldecode($b); if ($a == 'FooterCode') if ($b != '') $b = urldecode($b); if ($a == 'title') $ca->assign('coursetitle', $b); $ca->assign('' . $a . '', $b); } } foreach ($_SESSION as $a => $b) { if ($a == 'HeaderCode') if ($b != '') $b = urldecode($b); if ($a == 'FooterCode') if ($b != '') $b = urldecode($b); if ($a == 'title') $ca->assign('coursetitle', $b); $ca->assign('' . $a . '', $b); } if (is_array($page_data['content'])) { foreach ($page_data['content'] as $a => $b) { if ($a == 'HeaderCode') if ($b != '') $b = urldecode($b); if ($a == 'FooterCode') if ($b != '') $b = urldecode($b); $ca->assign('' . $a . '', urldecode($b)); } } if ($_GET['error']) { $ca->assign("alert_message", create_alert_box($_GET['error'], 'danger')); } if ($_GET['warning']) { $ca->assign("alert_message", create_alert_box($_GET['warning'], 'warning')); } if ($_GET['success']) { $ca->assign("alert_message", create_alert_box($_GET['success'], 'success')); } $ca->assign("theme", $page_data['theme']); $ca->assign("themes_folder", "templates/".$page_data['theme']."/"); $ca->assign("rootdir_theme", ROOTDIR."/templates/".$page_data['theme']."/"); if ($page_data['type'] == '404') { http_response_code(404); $ca->setTemplate("404"); } else { if($rp) { $page_data['template'] = 'includes/'.$rp; } if(!$_POST['subaction'] == 'payOverdue') { $balance = get_overdue_data(); if(is_array($balance)) { if(count($balance) > 0) { $_GET['type'] = 'payinvoice'; $ca->assign('overdueInvoices', $balance['invoices']); $ca->assign('overdueTotal', $balance['total']); $page_data['template'] = 'myplan'; } } } if($_POST['subaction'] == 'payOverdue') { $balance = invoices_capture($_POST); if(is_array($balance)) { if(count($balance) > 0) { $_GET['type'] = 'payinvoice'; $ca->assign('haserror', true); $ca->assign('overdueInvoices', $balance['invoices']); $ca->assign('overdueTotal', $balance['total']); $page_data['template'] = 'myplan'; } } } if($_SESSION['user']['getstarted']) { $page_data['template'] = 'getstarted'; } if($rp) { $split = explode('/', $page_data['template']); $countsplit = count($split) - 1; $last_variable = $split[$countsplit]; unset($split[$countsplit]); $implode = implode("/",$split).'/php/'.$last_variable.'.php'; if (file_exists( ROOTDIR . '/templates/' . $page_data['theme'] . '/' . $implode)) { include(ROOTDIR . '/templates/' . $page_data['theme'] . '/' . $implode); } } else { if (file_exists('' . ROOTDIR . '/templates/' . $page_data['theme'] . '/php/' . $page_data['template'] . '.php')) { include('' . ROOTDIR . '/templates/' . $page_data['theme'] . '/php/' . $page_data['template'] . '.php'); } } $ca->assign("page_name", $page_data['template']); $ca->setTemplate($page_data['template']); } if($_POST['ajax']) { call_user_func($_POST['func'], $_POST); die(); } $ca->addOutputHookFunction("ClientAreaPageViewEmail"); $ca->output(); $_SESSION['error_login'] = ''; $_SESSION['error_resetpassword'] = ''; } } if (!function_exists('loadPage')) { function loadPage($theme) { global $CONFIG; global $install_path; global $currentPackage; global $rp; $currentPackage = get_product_details(); if($install_path) { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' . $install_path; } else { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' ; } $url_data = get_url_data(); $page_arr = array(); $count = $url_data['total']; $v = $url_data['url']; $rp = $_GET['rp']; if ($count ) { $count = $count; if ($v[$count] == $v[($count)]) { $number = '0'; $error = 1; } } else { $v[0] = 'front-page'; } if($v[0] == 'logout') { full_query("DELETE FROM tblclients_ios WHERE uuid='".$_SESSION['uuid']."'"); unset($_COOKIE['uuid']); unset($_COOKIE['onesignal_push_id']); destroy_login(); header('Location: '.$rooturl); } foreach($v as $u => $b) { if (preg_match('/\?\b/', $b)) { $check_page = explode("?", $b); if ($check_page[1]) { $count = $count - 1; $get = explode("&", $check_page[1]); foreach ($get as $g) { $h = explode("=", $g); $_GET[$h[0]] = $h[1]; } } } } if($_SERVER['HTTP_HOST'] == 'www.pay.pay-me.co.uk') { if($v[0] != 'paylink') { header('Location: https://www.pay-me.co.uk'); } } if($v[0] == 'paylink') { if($_SERVER['HTTP_HOST'] != 'www.pay.pay-me.co.uk') { if($v[0] == 'paylink') { header('Location: https://www.pay.pay-me.co.uk/paylink/?code='.$_GET['code']); } } if (file_exists('' . ROOTDIR . '/templates/' . $theme . '/' . $v[0] . '.tpl')) { $page_arr['id'] = ''; $page_arr['type'] = ''; $page_arr['url'] = ''; $page_arr['pagetitle'] = ucwords(str_replace("-", " ", $v['1'])) . ' - ' . $title[$current_lang]['course']['sitetitle']; $page_arr['title'] = ucwords(str_replace("-", " ", $v['1'])); $page_arr['meta'] = $title[$current_lang]['course']['sitetitle'] . ' ' . $res['page'] . ' Page'; $page_arr['template'] = $v[0]; $page_arr['page_name'] = $v[0]; $page_arr['theme'] = $theme; $request_arr = getPaymentScreen($_GET['code']); if($request_arr == 'false') { header('Location: /404/'); } $page_arr['header_request'] = $request_arr['request']; $page_arr['header_request']['user'] = getuserdetails($request_arr['request']['relid']); if(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.jpg')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.jpg?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.png')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.png?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.jpeg')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.jpeg?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.gif')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.gif?nocache='.date('ymdhis'); }elseif(file_exists(ROOTDIR.'/uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.JPG')) { $page_arr['header_request']['user']['profilephoto'] = '../../../uploads/user_uploads/'.$request_arr['request']['relid'].'_profilephoto.JPG?nocache='.date('ymdhis'); } } else { $page_arr['id'] = ''; $page_arr['pagetitle'] = 'Page Not Found'; $page_arr['type'] = '404'; $page_arr['url'] = ''; $page_arr['title'] = '404 Not Found'; $page_arr['meta'] = '404 Not Found'; $page_arr['content'] = 'Not Found'; $page_arr['theme'] = $theme; } } else { if($_GET['uuid']) { if(!isset($_COOKIE['uuid'])) { setcookie('uuid', $_GET['uuid'], (time() + (86400 * 30) * 3650), "/"); setcookie('os', $_GET['os'], (time() + (86400 * 30) * 3650), "/"); setcookie('onesignal_push_id', $_GET['onesignal_push_id'], (time() + (86400 * 30) * 3650), "/"); } } if(!isset($_COOKIE['uuid'])) { } else { $_GET['uuid'] = $_COOKIE['uuid']; $_GET['onesignal_push_id'] = $_COOKIE['onesignal_push_id']; $_GET['os'] = $_COOKIE['os']; } if (!$_SESSION['uid']) { $find_uuid = full_query("SELECT * FROM tblclients_ios WHERE uuid='".$_GET['uuid']."'"); $uuid = mysqli_fetch_assoc($find_uuid); if($_GET['uuid']) { if(!$uuid['uuid']) { $_SESSION['uuid'] = $_GET['uuid']; } else { $_SESSION['uid'] = $uuid['relid']; if($_GET['onesignal_push_id']) { full_query("UPDATE tblclients_ios SET push_id='".$_GET['onesignal_push_id']."' WHERE id='".$uuid['id']."'"); } if($_SESSION['onesignal_push_id']) { full_query("UPDATE tblclients_ios SET push_id='".$_SESSION['onesignal_push_id']."' WHERE id='".$uuid['id']."'"); } $_SESSION['uuid'] = $uuid['uuid']; header('Location: ../../'); } } if($_GET['onesignal_push_id']) { if(!$uuid['onesignal_push_id']) { $_SESSION['onesignal_push_id'] = $_GET['onesignal_push_id']; } else { $_SESSION['onesignal_push_id'] = $uuid['onesignal_push_id']; header('Location: ../../'); } } $allowed_url = array('login', 'forgotpassword'); if($v[0] == 'front-page') $v[0] = 'login'; if(in_array($v[0], $allowed_url)) { check_invoice_page(); set_user_variables(); $theme = switch_theme($_SESSION['user']['groupid']); if (file_exists('' . ROOTDIR . '/templates/'.$theme.'/'.$v[0].'.tpl')) { $page_arr['id'] = ''; $page_arr['type'] = ''; $page_arr['url'] = ''; $page_arr['pagetitle'] = ucwords(str_replace("-", " ", $v['1'])) . ' - ' . $title[$current_lang]['course']['sitetitle']; $page_arr['title'] = ucwords(str_replace("-", " ", $v['1'])); $page_arr['meta'] = $title[$current_lang]['course']['sitetitle'] . ' ' . $res['page'] . ' Page'; $page_arr['template'] = $v[0]; $page_arr['page_name'] = $v[0]; $page_arr['theme'] = $theme; } } else { set_user_variables(); if (file_exists('' . ROOTDIR . '/templates/Portal/login.tpl')) { $page_arr['id'] = ''; $page_arr['type'] = ''; $page_arr['url'] = ''; $page_arr['pagetitle'] = ucwords(str_replace("-", " ", $v['1'])) . ' - ' . $title[$current_lang]['course']['sitetitle']; $page_arr['title'] = ucwords(str_replace("-", " ", $v['1'])); $page_arr['meta'] = $title[$current_lang]['course']['sitetitle'] . ' ' . $res['page'] . ' Page'; $page_arr['template'] = 'login'; $page_arr['page_name'] = 'login'; $page_arr['theme'] = 'Portal'; } } } else { set_user_variables(); $theme = switch_theme($_SESSION['user']['groupid']); if (preg_match('/\?\b/', $v[0])) { $v[0] = 'front-page'; } if(!$currentPackage['product']) { $v[0] = 'getstarted'; } if (file_exists('' . ROOTDIR . '/templates/' . $theme . '/' . $v[0] . '.tpl')) { $page_arr['id'] = ''; $page_arr['type'] = ''; $page_arr['url'] = ''; $page_arr['pagetitle'] = ucwords(str_replace("-", " ", $v['1'])) . ' - ' . $title[$current_lang]['course']['sitetitle']; $page_arr['title'] = ucwords(str_replace("-", " ", $v['1'])); $page_arr['meta'] = $title[$current_lang]['course']['sitetitle'] . ' ' . $res['page'] . ' Page'; $page_arr['template'] = $v[0]; $page_arr['page_name'] = $v[0]; $page_arr['theme'] = $theme; } else { $page_arr['id'] = ''; $page_arr['pagetitle'] = 'Page Not Found'; $page_arr['type'] = '404'; $page_arr['url'] = ''; $page_arr['title'] = '404 Not Found'; $page_arr['meta'] = '404 Not Found'; $page_arr['content'] = 'Not Found'; $page_arr['theme'] = $theme; } } } return $page_arr; } } ?> function getPaymentScreen($code, $gateway = NULL, $returnArr = NULL) { //SELECT * FROM `tblclient_requests` WHERE `paycode` LIKE 'cY78Na' $query = select_query('tblclient_requests', '*', array("paycode"=>$code)); if(mysqli_num_rows($query) > 0) { $data = mysqli_fetch_array($query); $request = full_query("SELECT tblclients_customers.*, tblclient_requests.*, tblclients_customers.id as userid FROM tblclient_requests LEFT JOIN tblclients_customers ON tblclients_customers.id = tblclient_requests.customer_relid WHERE tblclient_requests.`id`='".$data['id']."'"); $request_data = mysqli_fetch_array($request); $request_data['multirequest'] = json_decode($request_data['multirequest'], true); $arr['request'] = $request_data; if($gateway) { $arr['gateway_settings'] = get_active_gateways($data['relid'], $gateway); } else { $arr['gateways'] = get_active_gateways($data['relid'], '', true); } return $arr; } else { return 'false'; } } ?> function filter_year_options($id = NULL) { $year = date('Y'); for ($x = 0; $x <= 10; $x++) { $newyear = ($year - $x); $selected=''; if($id == $newyear) $selected='selected="selected"'; $return .= ''; } return $return; } function filter_months_options($id = NULL) { for ($x = 1; $x <= 12; $x++) { $month = sprintf("%02d", $x); $selected=''; if($id == $month) $selected='selected="selected"'; $return .= ''; } return $return; } function get_active_gateways($userid, $selected_gateway = NULL, $isarr = NULL) { $result = select_query("tbl_client_paymentgateways", "", array("userid"=>$userid), "setting", "ASC"); while ($data = mysqli_fetch_array($result)) { $gwv_gateway = $data["gateway"]; $gwv_setting = $data["setting"]; $gwv_value = $data["value"]; $GatewayValues[$gwv_gateway][$gwv_setting] = $gwv_value; } $includedmodules = array(); $dh = opendir(ROOTDIR."/includes/modules/gateways/"); while (false !== ($file = readdir($dh))) { $fileext = explode(".", $file, 2); if (trim($file) && $file != "index.php" && 1 < count($fileext) && $fileext[1] == "php" && !in_array($fileext[0], $includedmodules)) { $includedmodules[] = $fileext[0]; $gwv_modulename = $fileext[0]; //echo $gwv_modulename.''; require_once ROOTDIR . "/includes/modules/gateways/" . $gwv_modulename . ".php"; //echo ' - Included
" . $GatewayValues[$modulename]['name'] . "\n
Please wait while you are redirected...
" . "" . ""; return $output; } public function getWorkflowType() { if ($this->getMetaDataValue("TokenWorkflow") === true) { return static::WORKFLOW_TOKEN; } if ($this->functionExists("credit_card_input")) { return static::WORKFLOW_ASSISTED; } if ($this->functionExists("remoteinput")) { return static::WORKFLOW_REMOTE; } if ($this->functionExists("nolocalcc")) { return static::WORKFLOW_NOLOCALCARDINPUT; } if ($this->functionExists("storeremote")) { return static::WORKFLOW_TOKEN; } if ($this->functionExists("capture") || $this->getMetaDataValue("gatewayType") === self::GATEWAY_CREDIT_CARD && $this->getMetaDataValue("processingType") === self::PROCESSING_OFFLINE) { return static::WORKFLOW_MERCHANT; } return static::WORKFLOW_THIRDPARTY; } public function isTokenised() { $tokenizedWorkflows = array(static::WORKFLOW_ASSISTED, static::WORKFLOW_REMOTE, static::WORKFLOW_NOLOCALCARDINPUT, static::WORKFLOW_TOKEN); return in_array($this->getWorkflowType(), $tokenizedWorkflows); } public function supportsLocalBankDetails() { return $this->functionExists("localbankdetails"); } public function supportsAutoCapture() { return $this->functionExists("capture") || $this->getProcessingType() == self::PROCESSING_OFFLINE; } public function getBaseGatewayType() { $type = "3rdparty"; if ($this->supportsAutoCapture()) { $type = "creditcard"; } if ($this->supportsLocalBankDetails()) { $type = "bankaccount"; } return $type; } public function getProcessingType() { if ($this->isMetaDataValueSet("processingType")) { return $this->getMetaDataValue("processingType"); } return null; } public function isSupportedCurrency($currencyCode) { if (!$this->isMetaDataValueSet("supportedCurrencies") || in_array($currencyCode, $this->getMetaDataValue("supportedCurrencies"))) { return true; } return false; } } class Gateways { private $modulename = ""; private static $gateways = NULL; private $displaynames = array(); public function __construct() { } public function getDisplayNames() { $result = select_query("tbl_client_paymentgateways", "gateway,value", array("setting" => "name"), "order", "ASC"); while ($data = mysql_fetch_array($result)) { $this->displaynames[$data["gateway"]] = $data["value"]; } return $this->displaynames; } public function getDisplayName($gateway) { if (empty($this->displaynames)) { $this->getDisplayNames(); } return array_key_exists($gateway, $this->displaynames) ? $this->displaynames[$gateway] : $gateway; } public static function isNameValid($gateway) { if (!is_string($gateway) || empty($gateway)) { return false; } if (!ctype_alnum(str_replace(array("_", "-"), "", $gateway))) { return false; } return true; } public static function getActiveGateways() { if (is_array(self::$gateways)) { return self::$gateways; } self::$gateways = array(); $result = select_query("tbl_client_paymentgateways", "DISTINCT gateway", ""); while ($data = mysql_fetch_array($result)) { $gateway = $data[0]; if (Gateways::isNameValid($gateway)) { self::$gateways[] = $gateway; } } return self::$gateways; } public function isActiveGateway($gateway) { $gateways = $this->getActiveGateways(); return in_array($gateway, $gateways); } public static function makeSafeName($gateway) { $validgateways = Gateways::getActiveGateways(); return in_array($gateway, $validgateways) ? $gateway : ""; } public function getAvailableGateways($invoiceid = "") { $validgateways = array(); $result = full_query("SELECT DISTINCT gateway, (SELECT value FROM tbl_client_paymentgateways g2 WHERE g1.gateway=g2.gateway AND setting='name' LIMIT 1) AS `name`, (SELECT `order` FROM tbl_client_paymentgateways g2 WHERE g1.gateway=g2.gateway AND setting='name' LIMIT 1) AS `order` FROM `tbl_client_paymentgateways` g1 WHERE setting='visible' AND value='on' ORDER BY `order` ASC"); while ($data = mysql_fetch_array($result)) { $validgateways[$data[0]] = $data[1]; } if ($invoiceid) { $invoiceid = (int) $invoiceid; $invoicegateway = get_query_val("tblinvoices", "paymentmethod", array("id" => $invoiceid)); $result = select_query("tblinvoiceitems", "", array("type" => "Hosting", "invoiceid" => $invoiceid)); while ($data = mysql_fetch_assoc($result)) { $relid = $data["relid"]; if ($relid) { $result2 = full_query("SELECT pg.disabledgateways AS disabled FROM tblhosting h LEFT JOIN tblproducts p on h.packageid = p.id LEFT JOIN tblproductgroups pg on p.gid = pg.id where h.id = " . (int) $relid); $data2 = mysql_fetch_assoc($result2); $gateways = explode(",", $data2["disabled"]); foreach ($gateways as $gateway) { if (array_key_exists($gateway, $validgateways) && $gateway != $invoicegateway) { unset($validgateways[$gateway]); } } } } if (array_key_exists($invoicegateway, $validgateways) === false) { $validgateways[$invoicegateway] = get_query_val("tbl_client_paymentgateways", "value", array("setting" => "name", "gateway" => $invoicegateway)); } } return $validgateways; } public function getFirstAvailableGateway() { $gateways = $this->getAvailableGateways(); return key($gateways); } public function getCCDateMonths() { $months = array(); for ($i = 1; $i <= 12; $i++) { $months[] = str_pad($i, 2, "0", STR_PAD_LEFT); } return $months; } public function getCCStartDateYears() { $startyears = array(); for ($i = date("Y") - 12; $i <= date("Y"); $i++) { $startyears[] = $i; } return $startyears; } public function getCCExpiryDateYears() { $expiryyears = array(); for ($i = date("Y"); $i <= date("Y") + 12; $i++) { $expiryyears[] = $i; } return $expiryyears; } } function markread($v) { global $CONFIG; global $defaulturl; global $install_path; if($install_path) { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' . $install_path; } else { $rooturl = '//' . $_SERVER['HTTP_HOST'] . '/' ; } if($v['global']) { $query = full_query('SELECT * FROM `tbl_notifications` WHERE id="'.$v['id'].'" AND `type` = "global"'); $data = mysqli_fetch_array($query); $link = $data['link']; $linkexternal = $data['linkexternal']; $query = full_query("INSERT INTO tbl_notification_global (`notification_id`, `uid`, `read`, `readtime`) VALUES ('".$v['id']."', '".$_SESSION['uid']."', '1', NOW())"); } else { $query = full_query('UPDATE `tbl_notifications` SET `read` = "1", readtime = NOW() WHERE id="'.$v['id'].'" AND `uid` = "'.$_SESSION['uid'].'"'); $query = full_query('SELECT * FROM `tbl_notifications` WHERE id="'.$v['id'].'" AND `uid` = "'.$_SESSION['uid'].'"'); $data = mysqli_fetch_array($query); $link = $data['link']; $linkexternal = $data['linkexternal']; } $rooturl = $rooturl . $link; if($linkexternal) { header('Location: '.$link); } else { header('Location: '.$rooturl); } die(); } function header_get_notifications() { $arr = array(); $query = full_query('SELECT * FROM `tbl_notifications` WHERE uid="'.$_SESSION['uid'].'" AND `read` = "0" OR type="global" ORDER BY `datetime` DESC'); if(mysqli_num_rows($query) > 0) { while($res = mysqli_fetch_assoc($query)) { if($res['type'] == 'global') { $query2 = full_query('SELECT * FROM `tbl_notification_global` WHERE uid="'.$_SESSION['uid'].'" AND notification_id = "'.$res['id'].'" AND `read` = "1"'); if(mysqli_num_rows($query2) == 0) { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['message'] = $res['message']; $arr[$res['id']]['link'] = $res['link']; $arr[$res['id']]['datetime'] = humanTiming($res['datetime']); $arr[$res['id']]['read'] = $res['read']; $arr[$res['id']]['type'] = $res['type']; } } else { $arr[$res['id']]['id'] = $res['id']; $arr[$res['id']]['message'] = $res['message']; $arr[$res['id']]['link'] = $res['link']; $arr[$res['id']]['datetime'] = humanTiming($res['datetime']); $arr[$res['id']]['read'] = $res['read']; $arr[$res['id']]['type'] = $res['type']; } } } return $arr; } if(!function_exists('pagination')) { function pagination($links, $list_class, $page, $total, $limit) { $page = createLinks($links, $list_class, $page, $total, $limit); return $page; } } if(!function_exists('createLinks')) { function createLinks( $links, $list_class, $page, $total, $limit ) { if ( $limit == 'all' ) { return ''; } if($total > 0) { $explode = explode('?', $_SERVER['REQUEST_URI']); if(count($explode) > 1) { $url = str_replace("&page=".$_GET['page'],"", $_SERVER['REQUEST_URI']); $url = str_replace("?page=".$_GET['page'],"", $url); $uri = $url.'&'; } else { $uri = '?'; } $last = ceil( $total / $limit ); $start = ( ( $page - $links ) > 0 ) ? $page - $links : 1; $end = ( ( $page + $links ) < $last ) ? $page + $links : $last; $html = '");
}
}
if(!function_exists('getSiteCurrency'))
{
function getSiteCurrency($id)
{
$query = full_query('SELECT * FROM tblcurrencies WHERE suffix="'.$id.'"');
$data = mysqli_fetch_assoc($query);
$arr = array();
$arr['suffix'] = $data['suffix'];
$arr['prefix'] = $data['prefix'];
$arr['rate'] = $data['rate'];
return $arr;
}
}
if(!function_exists('sanitize_output'))
{
function sanitize_output($buffer)
{
$search = array(
'/\>[^\S ]+/s', // strip whitespaces after tags, except space
'/[^\S ]+\/' // Remove HTML comments
);
$replace = array(
'>',
'<',
'\\1',
''
);
$buffer = preg_replace($search, $replace, $buffer);
return $buffer;
}
}
?>
function api_CapturePayment($invoiceid)
{
$command = 'CapturePayment';
$postData = array(
'invoiceid' => $invoiceid,
);
$adminUsername = ''; // Optional for WHMCS 7.2 and later
$results = localAPI($command, $postData, $adminUsername);
return $results;
}
function api_AddOrder($pid, $price = NULL)
{
$command = 'AddOrder';
$postData = array(
'clientid' => $_SESSION['uid'],
'pid' => array($pid),
'billingcycle' => array('monthly'),
'paymentmethod' => 'stripe',
);
if($price > 0)
{
$postData['priceoverride'] = $price;
}
$adminUsername = ''; // Optional for WHMCS 7.2 and later
$results = localAPI($command, $postData, $adminUsername);
return $results;
}
function interpretMaskedPasswordChangeForStorage($newPassword, $originalPassword)
{
if (!$newPassword) {
return "";
}
if (hasmaskedpasswordchanged($newPassword, $originalPassword)) {
return encrypt(WHMCS\Input\Sanitize::decode($newPassword));
}
return false;
}
function localAPI($command, $values, $other = NULL)
{
$url = 'https://bill.pay-me.co.uk/includes/api.php';
$values['action'] = $command;
$values['identifier'] = 'XKqWjLJzmYkQ2Nf6gzESSd7C5B58nJY1';
$values['secret'] = 'qkBZ2Q0pX0BSnytLLLThb10N8QWj28RF';
$values['responsetype'] = 'json';
// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://bill.pay-me.co.uk/includes/api.php');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
http_build_query(
$values
)
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);
return $jsonData;
}
?>
add_hook('ClientAreaFooterOutput', 1, function($vars) {
//return 'This is a custom output on the footer';
});
?>
if($_POST)
{
$v = $_POST;
if(defined('iscallback'))
{
} else {
if($_SESSION['uid'])
{
if(function_exists($v['function']))
{
call_user_func($v['function'], $v);
if($v['jquery']) die();
}
} else {
if($v['function'] == 'login' )
{
if(function_exists($v['function']))
{
call_user_func($v['function'], $v);
}
} elseif($v['function'] == 'resetpassword' )
{
if(function_exists($v['function']))
{
call_user_func($v['function'], $v);
}
} elseif($v['subactionfunction'])
{
} else {
die('Authorisation Token Missing');
}
}
}
}
if($_GET)
{
if($_SESSION['uid'] > 0)
{
$k = $_GET;
if(function_exists($k['function']))
{
call_user_func($k['function'], $k);
if($v['jquery']) die();
}
} else {
$v = $_GET;
$allowed = array('loginAgain', 'adminLogin');
if(in_array($v['function'], $allowed))
{
if(function_exists($v['function']))
{
call_user_func($v['function'], $v);
}
}
}
}