We have received a request to refund $ $balance_to_transfer to you in Bitcoins. Below is the details of your request.
+ Please approve the Bitcoin address again before we send you Bitcoins. If you did not send any request or if any data below
+ is incorrect please report immediately.
+
+
+
BTC ADDRESS: $btc_addr
+
AMOUNT TO TRANSFER: $ $balance_to_transfer (DO NOT SEND MORE THAN $ $allowed_bid_amount.)
+
EMAIL: $senders_email
+
REMARKS: ".$remarks."
+
SENDER FB ID: facebook.com/".$fb_id."
+
+
+
";
+
+ $send_mail = $OrderClass->send_notice_mail($reciever_email, $email_from, $email_sender, $email_subject, $email_body);
+ $transfer_funds = null;
+ if($send_mail) {
+ /*Transfer funds from site to bank account*/
+ $transfer_funds = $OrderClass->fund_transfer($fund_type="E2BTC", $from="Exchange", $to=$btc_addr, $balance_to_transfer, $remarks, $assetType = 'traditional');
+ }
+
+ if ($transfer_funds) {
+ $mess = "E2BTC Transaction Success: Please check your mail to approve this request.";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->error = false;
+ $std->mesg[] = $mess;
+ $std->user = $validate_user;
+
+ } else {
+ $mess = "E2BTC error: Mail could not be sent. Try again.";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->error = true;
+ $std->mesg[] = $mess;
+ $std->user = $validate_user;
+ }
+ echo json_encode($std);
+ return true;
+ }
+}
+return false;
\ No newline at end of file
diff --git a/ajax/pending_orders.php b/ajax/pending_orders.php
index 71e097d..4b0821b 100644
--- a/ajax/pending_orders.php
+++ b/ajax/pending_orders.php
@@ -17,8 +17,8 @@ if (isset($_POST['subject']) && trim($_POST['subject'])=='placeOrder') {
if (isset($_POST['btn_id'], $_POST['qty'], $_POST['price'])) {
$btn_id = trim($_POST['btn_id']);
- $qty = two_decimal_digit($_POST['qty']);
- $item_price = two_decimal_digit($_POST['price']);
+ $qty = (float) $_POST['qty'];
+ $item_price = (float) $_POST['price'];
$orderStatusId = 2; // 0 -> cancelled; 1 -> complete; 2 -> pending
$std = new stdClass();
@@ -30,11 +30,15 @@ if (isset($_POST['subject']) && trim($_POST['subject'])=='placeOrder') {
if($btn_id == 'buy_btn') {
$orderTypeId = 0; // It is a buy
$OfferAssetTypeId= 'USD';
- $WantAssetTypeId = 'RTM';
+ $WantAssetTypeId = 'RMT';
+ $assetType = 'traditional';
+ $total_trade_val = $qty * $item_price;
} else if($btn_id == 'sell_btn') {
$orderTypeId = 1; // It is a sell
- $OfferAssetTypeId = 'RTM';
+ $OfferAssetTypeId = 'RMT';
$WantAssetTypeId = 'USD';
+ $assetType = 'btc';
+ $total_trade_val = $qty;
} else {
$std->error = true;
$std->msg = "Invalid button id.";
@@ -63,7 +67,55 @@ if (isset($_POST['subject']) && trim($_POST['subject'])=='placeOrder') {
return false;
}
- $place_order = $OrderClass->insert_pending_order($orderTypeId, abs($qty), abs($item_price), $orderStatusId, $OfferAssetTypeId, $WantAssetTypeId);
+ $user_current_bal = (float) $OrderClass->check_customer_balance($assetType, $user_id)->Balance;
+
+ $top_tbl = null;
+ if ($orderTypeId == 0) {
+ $top_tbl = TOP_BUYS_TABLE;
+ $user_active_orders = $OrderClass->get_active_order_of_user($user_id, $top_tbl);
+
+ $frozen_bal = 0;
+ if (is_array($user_active_orders) && !empty($user_active_orders)) {
+ foreach ($user_active_orders as $uao) {
+ $frozen_bal += (float) $uao->price * $uao->quantity;
+ }
+ }
+ $allowed_bid_amount = $user_current_bal - $frozen_bal;
+ $ext_st = "You can put bid up to $ $allowed_bid_amount only.";
+ $ext_st2 = "";
+ if ($allowed_bid_amount == 0) {
+ $ext_st = "You don't have any cash balance to spend.";
+ }
+ if ((float)$frozen_bal != 0) {
+ $ext_st2 = "You have already placed an order worth $ $frozen_bal.";
+ }
+ $msss = "Insufficient Balance: $ext_st2 $ext_st";
+
+ } elseif ($orderTypeId == 1) {
+ $top_tbl = TOP_SELL_TABLE;
+ $user_active_orders = $OrderClass->get_active_order_of_user($user_id, $top_tbl);
+ $frozen_bal = 0;
+ if (is_array($user_active_orders) && !empty($user_active_orders)) {
+ foreach ($user_active_orders as $uao) {
+ $frozen_bal += (float) $uao->quantity;
+ }
+ }
+ $allowed_bid_amount = $user_current_bal - $frozen_bal;
+ $ext_st = "You can sell maximum $allowed_bid_amount tokens.";
+ if ($allowed_bid_amount == 0) {
+ $ext_st = "You don't have any tokens to sell.";
+ }
+ $msss = "Insufficient Balance: You have already placed an order of $frozen_bal tokens. $ext_st";
+ }
+
+ if ($frozen_bal + $total_trade_val > $user_current_bal) {
+ $std->error = true;
+ $std->msg = $msss;
+ echo json_encode($std);
+ return false;
+ }
+
+ $place_order = $OrderClass->insert_pending_order($orderTypeId, $qty, $item_price, $orderStatusId, $OfferAssetTypeId, $WantAssetTypeId);
} else {
$std->error = true;
diff --git a/ajax/refresh_table.php b/ajax/refresh_table.php
index 5fdbe60..4e707e0 100644
--- a/ajax/refresh_table.php
+++ b/ajax/refresh_table.php
@@ -18,8 +18,8 @@ if (isset($_POST['task']) && trim($_POST['task'])=='refresh') {
if (isset($OrderClass, $UserClass)) {
- $buy_list = $OrderClass->get_top_buy_sell_list($top_table='active_buy_list', $asc_desc='DESC'); // buy
- $sell_list = $OrderClass->get_top_buy_sell_list($top_table='active_selling_list', $asc_desc='ASC'); // sell
+ $buy_list = $OrderClass->get_top_buy_sell_list(TOP_BUYS_TABLE, $asc_desc='DESC'); // buy
+ $sell_list = $OrderClass->get_top_buy_sell_list(TOP_SELL_TABLE, $asc_desc='ASC'); // sell
$std->buys = $buy_list;
$std->sells = $sell_list;
diff --git a/ajax/rm_root.php b/ajax/rm_root.php
new file mode 100644
index 0000000..2137ab5
--- /dev/null
+++ b/ajax/rm_root.php
@@ -0,0 +1,52 @@
+delete_orders_of_user($u_id_int);
+ }
+ $act_user = $UserClass->actions_user($u_id_int, $act);
+
+ if ($act_user) {
+ echo $u_id_str;
+ }
+ }
+ return false;
+ }
+
+}
\ No newline at end of file
diff --git a/ajax/transfer_balance_to_bank.php b/ajax/transfer_balance_to_bank.php
new file mode 100644
index 0000000..8ada6b4
--- /dev/null
+++ b/ajax/transfer_balance_to_bank.php
@@ -0,0 +1,180 @@
+mesg = array();
+ $std->error = true;
+ $std->user = null;
+
+ if (empty($account_number) || empty($balance_to_transfer)) {
+ $mess = "E2B error: Please fill all the required fields!";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->mesg[] = $mess;
+ $std->error = true;
+ echo json_encode($std);
+ return false;
+ }
+
+ if (!preg_match("/^[a-zA-Z0-9 \r\n]*$/",$remarks)) {
+ $mess = "E2B error: Only alphanumeric characters allowed in Remarks!";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->mesg[] = $mess;
+ $std->error = true;
+ echo json_encode($std);
+ return false;
+ }
+
+ if (strlen($remarks) > 250) {
+ $mess = "E2B error: Remarks up to 250 characters allowed only!";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->mesg[] = $mess;
+ $std->error = true;
+ echo json_encode($std);
+ return false;
+ }
+
+ $validate_user = $UserClass->check_user($user_id);
+
+ if($validate_user == "" || empty($validate_user)) {
+ $mess = "E2B error: No such user exist. Please login again.";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->error = true;
+ $std->mesg[] = $mess;
+ echo json_encode($std);
+ return false;
+ }
+
+ $senders_email = trim($validate_user->Email);
+
+ if (!is_email($senders_email)) {
+ $mess = "E2B error: Please provide a valid email id!";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->mesg[] = $mess;
+ $std->error = true;
+ echo json_encode($std);
+ return false;
+ }
+
+ $user_bank_details = $OrderClass->get_bank_details($user_id, $account_number);
+
+ if($user_bank_details == "" || empty($user_bank_details)) {
+ $mess = "E2B error: No such bank account exist. Please check bank details again.";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->error = true;
+ $std->mesg[] = $mess;
+ echo json_encode($std);
+ return false;
+ }
+
+ $customer_bal = (float) $OrderClass->check_customer_balance($assetType="traditional", $user_id)->Balance;
+
+ if ($balance_to_transfer > $customer_bal) {
+ $mess = "E2B transaction failed: You have insufficient balance to make this transfer. Your current Cash balance is $ $customer_bal.";
+ $std->error = true;
+ $std->mesg[] = $mess;
+ echo json_encode($std);
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ return false;
+ }
+
+ $msss = '';
+
+ // Check order in buys table
+ $OfferAssetTypeId= 'USD';
+ $WantAssetTypeId = 'RMT';
+ $assetType = 'traditional';
+ $user_active_orders = $OrderClass->get_active_order_of_user($user_id, TOP_BUYS_TABLE);
+ $frozen_bal_buys = 0;
+ $allowed_bid_amount = $customer_bal;
+ if (is_array($user_active_orders) && !empty($user_active_orders)) {
+ foreach ($user_active_orders as $uao) {
+ $frozen_bal_buys += (float) $uao->price * $uao->quantity;
+ }
+ $allowed_bid_amount = $customer_bal - $frozen_bal_buys;
+ $ext_st = "You can refund up to $ $allowed_bid_amount only.";
+ if ($allowed_bid_amount == 0) {
+ $ext_st = "You don't have any cash balance to refund.";
+ }
+ $msss = "Refund error: You have placed an order worth $ $frozen_bal_buys $ext_st Please cancel it or reduce your refund amount.";
+ }
+
+ if ($frozen_bal_buys + $balance_to_transfer > $customer_bal) {
+ $OrderClass->storeMessagesPublic(null, $user_id, $msss);
+ $std->error = true;
+ $std->mesg[] = $msss;
+ echo json_encode($std);
+ return false;
+ }
+
+ $reciever_email = [PI, FINANCE];
+ $email_from = RM;
+ $email_sender = EMAIL_SENDER_NAME;
+ $email_subject = EMAIL_SUBJECT;
+ $email_body = "
+
+
Fund Transfer Request
+
+
+
Transfer Type: Exchange Website to Bank Account(E2B)
+
RECIPIENT FULL NAME: ".$user_bank_details[0]->acc_holder."
+
BANK NAME: ".$user_bank_details[0]->bank_name."
+
BANK ACCOUNT NUMBER: ".$user_bank_details[0]->acc_num."
+
BRANCH: ".$user_bank_details[0]->branch_name."
+
FULL BANK ADDRESS: ".$user_bank_details[0]->bank_addr."
+
COUNTRY: ".$user_bank_details[0]->bank_ctry."
+
AMOUNT TO TRANSFER: $ $balance_to_transfer (DO NOT SEND MORE THAN $ $allowed_bid_amount.)
+
EMAIL: $senders_email
+
REMARKS: ".$remarks."
+
SENDER FB ID: facebook.com/".$fb_id."
+
+
+
";
+
+ $send_mail = $OrderClass->send_notice_mail($reciever_email, $email_from, $email_sender, $email_subject, $email_body);
+ $transfer_funds = null;
+ if($send_mail) {
+ /*Transfer funds fro site to bank account*/
+ $transfer_funds = $OrderClass->fund_transfer($fund_type="E2B", $from="Exchange", $to=$user_bank_details[0]->acc_num, $balance_to_transfer, $remarks, $assetType = 'traditional');
+ }
+
+ if ($transfer_funds) {
+ $mess = "E2B Transaction Success: Your request has been recorded and will be processed very soon by our team.";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->error = false;
+ $std->mesg[] = $mess;
+ $std->user = $validate_user;
+
+ } else {
+ $mess = "E2B error: Mail could not be sent. Try again.";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->error = true;
+ $std->mesg[] = $mess;
+ $std->user = $validate_user;
+ }
+ echo json_encode($std);
+ return true;
+ }
+}
+return false;
\ No newline at end of file
diff --git a/ajax/transfer_rtm_to_bchain.php b/ajax/transfer_rtm_to_bchain.php
new file mode 100644
index 0000000..bda50db
--- /dev/null
+++ b/ajax/transfer_rtm_to_bchain.php
@@ -0,0 +1,166 @@
+mesg = array();
+ $std->error = true;
+
+ if (empty($wallet_address) || empty($balance_to_transfer)) {
+ $mess = "E2W error: Please fill all the required fields!";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->mesg[] = $mess;
+ echo json_encode($std);
+ return false;
+ }
+
+ if (!preg_match('/^[A-Za-z0-9]*$/', $wallet_address)) {
+ $mess = "E2W error (Invalid Wallet Address): Only alphanumeric characters are allowed in wallet address!";
+ $std->mesg[] = $mess;
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ echo json_encode($std);
+ return false;
+ }
+
+ if (!preg_match("/^[a-zA-Z0-9 \r\n]*$/",$remarks)) {
+ $mess = "E2W error: Only alphanumeric characters are allowed in remarks!";
+ $std->mesg[] = $mess;
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ echo json_encode($std);
+ return false;
+ }
+
+ $customer_bal = (float) $OrderClass->check_customer_balance($assetType="btc", $user_id)->Balance;
+
+ if ($balance_to_transfer > $customer_bal) {
+ $mess = "E2W transaction failed: You have insufficient balance to make this transfer. Your current Token balance is $customer_bal RMTs.";
+ $std->error = true;
+ $std->mesg[] = $mess;
+ echo json_encode($std);
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ return false;
+ }
+
+ if ($balance_to_transfer < 0.0000000001) {
+ $mess = "E2W error: Please provide minimum amount of 0.0000000001 RMTs!";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->mesg[] = $mess;
+ echo json_encode($std);
+ return false;
+ }
+
+ if (strlen($remarks) > 250) {
+ $mess = "E2W error: Remarks up to 250 characters allowed only!";
+ $std->mesg[] = $mess;
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->error = true;
+ echo json_encode($std);
+ return false;
+ }
+
+ $validate_user = $UserClass->check_user($user_id);
+
+ if($validate_user == "" || empty($validate_user)) {
+ $mess = "No such user exist. Please login again.";
+ $std->error = true;
+ $std->mesg[] = $mess;
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ echo json_encode($std);
+ return false;
+ }
+
+ $email_id = trim($validate_user->Email);
+
+ if (!is_email($email_id)) {
+ $mess = "E2W error: Invalid email format!";
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ $std->mesg[] = $mess;
+ $std->error = true;
+ echo json_encode($std);
+ return false;
+ }
+
+ $reciever_email[] = AB;
+ $email_from = RM;
+ $email_sender = EMAIL_SENDER_NAME;
+ $email_subject = EMAIL_SUBJECT_RTM_TRANSFER;
+ $email_body = "
+
+
RMT Transfer Request
+
+
+
Transfer Type: Exchange Website to FLORINCOIN BLOCKCHAIN WALLET(E2W)
+
RECIPIENT FULL NAME: ".$log_fullName."
+
WALLET ADDRESS: ".$wallet_address."
+
AMOUNT TO TRANSFER: RMT $balance_to_transfer
+
EMAIL: $email_id
+
REMARKS: ".$remarks."
+
SENDER FB ID: facebook.com/".$fb_id."
+
+
+
";
+
+ $send_mail = $OrderClass->send_notice_mail($reciever_email, $email_from, $email_sender, $email_subject, $email_body);
+ $transfer_funds = null;
+ if($send_mail) {
+ $transfer_funds = $OrderClass->fund_transfer($fund_type="E2W", $from="Exchange", $to=$wallet_address, $balance_to_transfer, $remarks, $asset_type='btc');
+ }
+
+ if ($transfer_funds) {
+
+ $if_req_sent_to_bchain = sendReqtoURL($wallet_address, $balance_to_transfer);
+
+ if ($if_req_sent_to_bchain) {
+ $mess = "E2W Transaction Success: Your request has been recorded and will be processed very soon by our team.";
+ $std->error = false;
+ $std->mesg[] = $mess;
+ $std->user = $validate_user;
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ } else {
+ $mess = "E2W error: API request could not be sent. ";
+ $std->error = true;
+ $std->mesg[] = $mess;
+ $std->user = $validate_user;
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ return false;
+ }
+
+ } else {
+ $mess = "E2W error: Mail could not be sent. Try again.";
+ $std->error = true;
+ $std->mesg[] = $mess;
+ $std->user = $validate_user;
+ $OrderClass->storeMessagesPublic(null, $user_id, $mess);
+ }
+ echo json_encode($std);
+ return true;
+ }
+}
\ No newline at end of file
diff --git a/api/.htaccess b/api/.htaccess
new file mode 100644
index 0000000..0cdf203
--- /dev/null
+++ b/api/.htaccess
@@ -0,0 +1,4 @@
+RewriteEngine on
+RewriteCond %{REQUEST_FILENAME} !-d
+RewriteCond %{REQUEST_FILENAME} !-f
+RewriteRule . api.php [L]
\ No newline at end of file
diff --git a/api/api.php b/api/api.php
new file mode 100644
index 0000000..bf9856d
--- /dev/null
+++ b/api/api.php
@@ -0,0 +1,214 @@
+get('/market_price', function (Request $request, Response $response) {
+ try {
+ $OrderClass = new Orders();
+ $stmt = $OrderClass->LastTradedPrice();
+ $market_price = $stmt;
+
+ echo json_encode($market_price);
+
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Get Trade Volume in last 24 hours
+ $app->get("/trade_volume_in_24hr/{start}/{end}", function (Request $request, Response $response) {
+ try {
+
+ $starting = (string) trim($request->getAttribute('start'));
+ $ending = (string) trim($request->getAttribute('end'));
+
+ $t1 = Carbon::now()->subDays($starting)->format('Y-m-d 00:00:00');
+ $t2 = Carbon::now()->subDays($ending)->format('Y-m-d 00:00:00');
+
+ $ApiClass = new Api();
+ $vol = $ApiClass->trade_volume($t2, $t1);
+ $volume = $vol;
+ echo json_encode($volume);
+
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Get user to total balance ratio
+ $app->get("/token_ratio/{user_id}/{asset_type}", function (Request $request, Response $response) {
+ try {
+
+ $uid = (string) trim($request->getAttribute('user_id'));
+ $asset = (string) trim($request->getAttribute('asset_type'));
+
+ if ($asset == 'rmt') {
+ $asset = 'btc';
+ } else if($asset == 'cash') {
+ $asset = 'traditional';
+ } else {
+ echo '{"error": {"text": Invalid asset!}}';
+ return false;
+ }
+
+ $ApiClass = new Api();
+ $ratio = $ApiClass->user_token_to_total_tokens_ratio($uid, $asset);
+ $ratio_bal = $ratio;
+ echo json_encode($ratio_bal);
+
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Get total token volume and market cap
+ $app->get("/market_cap", function (Request $request, Response $response) {
+ try {
+ $OrderClass = new Orders();
+ $ApiClass = new Api();
+ $total_tokens_sold = $ApiClass->total_assets('btc');
+ $total = $total_tokens_sold;
+ $ltp = $OrderClass->LastTradedPrice();
+
+ $obj = [
+ 'total_token_sold'=> $total,
+ 'last_traded_price'=> $ltp
+ ];
+
+ echo json_encode($obj);
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Traders list
+ $app->get("/traders_list", function(Request $request, Response $response) {
+ try {
+ $OrderClass = new Orders();
+ $stmt = $OrderClass->UserBalanceList(1);
+ $list = $stmt;
+
+ echo json_encode($list);
+
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Trade Price History
+ $app->get("/trade_price_history/{start}/{end}", function(Request $request, Response $response) {
+ try {
+
+ $starting = (string) trim($request->getAttribute('start'));
+ $ending = (string) trim($request->getAttribute('end'));
+
+ $t1 = Carbon::now()->subDays($starting)->format('Y-m-d 00:00:00');
+ $t2 = Carbon::now()->subDays($ending)->format('Y-m-d 00:00:00');
+
+ $ApiClass = new Api();
+ $stmt = $ApiClass->TradedPriceHistory($t2, $t1);
+ $list = $stmt;
+
+ echo json_encode($list);
+
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Number of token in Buy or Sell
+ $app->get("/tokens_on_trade", function (Request $request, Response $response) {
+ try {
+ $ApiClass = new Api();
+ $total_tokens = $ApiClass->number_of_tokens_on_buy_sell();
+ $total = $total_tokens;
+ echo json_encode($total);
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Asset gain list
+ $app->get("/returns", function (Request $request, Response $response) {
+ try {
+ $ApiClass = new Api();
+ $return_list = $ApiClass->asset_gain_list();
+ $total = $return_list;
+ echo json_encode($total);
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Asset value by month
+ $app->get("/asset_by_month", function (Request $request, Response $response) {
+ try {
+ $ApiClass = new Api();
+ $asset_list = $ApiClass->asset_value_by_month();
+ $total = $asset_list;
+ echo json_encode($total);
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // My Actions
+ $app->get("/my_actions", function (Request $request, Response $response) {
+ try {
+ $ApiClass = new Api();
+ $action_list = $ApiClass->my_actions_numbers();
+ $total = $action_list;
+ echo json_encode($total);
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+ // Get total number of users
+ $app->get("/total_users", function (Request $request, Response $response) {
+ try {
+ $UserClass = new Users();
+ $users_sum = $UserClass->get_total_users_count();
+ $total = $users_sum;
+ echo json_encode($total);
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+
+ // Get Trade Volume week wise
+ $app->get("/trade_volume_by_week/{start}/{end}", function (Request $request, Response $response) {
+ try {
+
+ $starting = (string) trim($request->getAttribute('start'));
+ $ending = (string) trim($request->getAttribute('end'));
+
+ $t1 = Carbon::now()->subDays($starting)->format('Y-m-d 00:00:00');
+ $t2 = Carbon::now()->subDays($ending)->format('Y-m-d 00:00:00');
+
+ $ApiClass = new Api();
+ $vol = $ApiClass->week_wise_trade_volume($t2, $t1);
+ $volume = $vol;
+ echo json_encode($volume);
+
+ } catch (PDOException $e) {
+ echo '{"error": {"text": ' . $e->getMessage() . '}}';
+ }
+ });
+
+} else {
+ echo '{"error": {"text": "API could not be loaded."}}';
+}
+
+$app->run();
\ No newline at end of file
diff --git a/classes/Api.php b/classes/Api.php
new file mode 100644
index 0000000..ee175ec
--- /dev/null
+++ b/classes/Api.php
@@ -0,0 +1,244 @@
+databaseConnection()) {
+ if (trim($t1)==null || trim($t2)==null) {
+ return false;
+ }
+
+ $query = $this->db_connection->prepare(
+ "SELECT *, DAYOFWEEK(InsertDate) as DWNum FROM ".ORDERS_TABLE." WHERE `InsertDate` BETWEEN :t2 AND :t1"
+ );
+ $query->bindParam('t2', $t2);
+ $query->bindParam('t1', $t1);
+
+ $query->execute();
+
+ $vol_arr = array();
+
+ if ($cffuount = $query->rowCount() > 0) {
+ while ($vol = $query->fetchObject()) {
+ $vol_arr[] = $vol;
+ }
+ }
+ return $vol_arr;
+ }
+ return false;
+ }
+
+ public function user_token_to_total_tokens_ratio($user_id, $asset_type) {
+ if ($this->databaseConnection()) {
+
+ $assets = array(
+ 'user' => null,
+ 'total' => null
+ );
+
+ $query = $this->db_connection->prepare(
+ "SELECT SUM(Balance) AS TOTAL_BAL,
+ (SELECT Balance FROM ".CREDITS_TABLE." WHERE `AssetTypeId`=:ast AND `CustomerId`= :u_id) AS USER_BAL
+ FROM ".CREDITS_TABLE." WHERE `AssetTypeId`=:ast LIMIT 1"
+ );
+ $query->bindParam('u_id', $user_id);
+ $query->bindParam('ast', $asset_type);
+
+ $query->execute();
+
+ if ($query->rowCount() ==1) {
+ $balances = $query->fetchObject();
+ $assets['user'] = (float) $balances->USER_BAL;
+ $assets['total'] = (float) $balances->TOTAL_BAL;
+ }
+ return $assets;
+ }
+ return false;
+ }
+
+ public function total_assets($asset_type=null) {
+ $total_asset = null;
+ if ($this->databaseConnection()) {
+ $query = $this->db_connection->prepare(
+ "SELECT SUM(Balance) AS TOTAL_BAL
+ FROM ".CREDITS_TABLE." WHERE `AssetTypeId`= :ast LIMIT 1
+ ");
+ $query->bindParam('ast', $asset_type);
+
+ $query->execute();
+
+ if ($query->rowCount() == 1) {
+ $balances = $query->fetchObject();
+ $total_asset = (float) $balances->TOTAL_BAL;
+ }
+ }
+ return $total_asset;
+ }
+
+ public function TradedPriceHistory($t2, $t1) {
+ if ($this->databaseConnection()) {
+
+ $query = $this->db_connection->prepare("
+ SELECT `B_Amount`,InsertDate FROM ".TRANSACTIONS_TABLE."
+ WHERE InsertDate BETWEEN :t2 AND :t1
+ ORDER BY `InsertDate` ASC
+ ");
+
+ $query->bindParam('t2', $t2);
+ $query->bindParam('t1', $t1);
+
+ $query->execute();
+
+ $vol_arr = array();
+
+ if ($cffuount = $query->rowCount() > 0) {
+ while ($vol = $query->fetchObject()) {
+ $vol_arr[] = $vol;
+ }
+ }
+ return $vol_arr;
+ }
+ return false;
+ }
+
+ public function number_of_tokens_on_buy_sell() {
+ if ($this->databaseConnection()) {
+ $total = array();
+
+ $query = $this->db_connection->query(
+ "SELECT (
+ SELECT SUM(quantity)
+ FROM ".TOP_BUYS_TABLE."
+ ) AS TOTAL_BUYS,
+ ( SELECT SUM(quantity)
+ FROM ".TOP_SELL_TABLE."
+ ) AS TOTAL_SELLS,
+ ( SELECT SUM(Balance)
+ FROM ".CREDITS_TABLE."
+ WHERE AssetTypeId='btc'
+ ) AS TOTAL_TOKEN_BALANCE
+ ");
+
+ $query->execute();
+
+ $arr = [
+ 'token_on_buys'=>0,
+ 'token_on_sells'=>0,
+ 'all_tokens'=>0
+ ];
+
+ if ($query->rowCount() > 0) {
+ foreach ($query->fetchObject() as $q) {
+ $total[] = $q;
+ }
+ $arr['token_on_buys'] = $total[0];
+ $arr['token_on_sells'] = $total[1];
+ $arr['all_tokens'] = $total[2];
+ }
+
+ return $arr;
+ }
+ return false;
+ }
+
+ public function asset_gain_list() {
+ if ($this->databaseConnection()) {
+
+ $list = array();
+
+ $ltp = (float) $this->LastTradedPrice()->B_Amount;
+
+ $query = $this->db_connection->query("
+ SELECT DISTINCT(".TRANSACTIONS_TABLE.".a_buyer) AS INVESTOR_ID, (SELECT Name FROM ".USERS_TABLE." WHERE CustomerId = INVESTOR_ID) AS INVESTOR, SUM(".TRANSACTIONS_TABLE.".qty_traded * ".TRANSACTIONS_TABLE.".B_Amount) AS INVESTMENT,
+ (SELECT Balance * ".$ltp." FROM ".CREDITS_TABLE." WHERE `AssetTypeId`='btc' AND `CustomerId`=INVESTOR_ID) AS CURRENT_VALUE
+ FROM ".TRANSACTIONS_TABLE."
+ GROUP BY INVESTOR_ID
+ ");
+
+ $query->execute();
+
+ if ($query->rowCount() > 0) {
+ while ($li = $query->fetchObject()) {
+ $list[] = $li;
+ }
+ }
+ return $list;
+ }
+ return false;
+ }
+
+ public function asset_value_by_month() {
+ if ($this->databaseConnection()) {
+ $query = $this->db_connection->query("
+ SELECT SUM(qty_traded) AS QTY_TRADED, InsertDate, AVG(B_Amount) AS MAX_TRADE_PRICE
+ FROM ".TRANSACTIONS_TABLE." GROUP BY MONTH(InsertDate)
+ ");
+
+ $arr = array();
+
+ if ($query->rowCount() > 0) {
+ while ($stmt = $query->fetchObject()) {
+ $arr[] = $stmt;
+ }
+ }
+ return $arr;
+ }
+ return false;
+ }
+
+
+ public function my_actions_numbers() {
+ if ($this->databaseConnection()) {
+
+ $arr = array();
+ $query = $this->db_connection->query("SELECT fund_type, COUNT(`fund_type`) AS TOTAL, datetime
+ FROM ".TRANSFER_INFO_TABLE." GROUP BY fund_type");
+ while ($dat = $query->fetchObject()) {
+ $arr[] = $dat;
+ }
+ return $arr;
+ }
+ return false;
+ }
+
+ public function week_wise_trade_volume($t2, $t1) {
+
+ if ($this->databaseConnection()) {
+ if (trim($t1)==null || trim($t2)==null) {
+ return false;
+ }
+
+ $query = $this->db_connection->prepare(
+ "SELECT *, (SELECT WEEK(InsertDate)) AS WEEK_NUM
+ FROM ".ORDERS_TABLE." WHERE `InsertDate` BETWEEN :t2 AND :t1
+ AND `OrderStatusId`= 1
+ ORDER BY InsertDate ASC"
+ );
+ $query->bindParam('t2', $t2);
+ $query->bindParam('t1', $t1);
+
+ $query->execute();
+
+ $vol_arr = array();
+
+ if ($cffuount = $query->rowCount() > 0) {
+ while ($vol = $query->fetchObject()) {
+ $vol_arr[] = $vol;
+ }
+ }
+ return $vol_arr;
+ }
+ return false;
+ }
+
+
+
+
+}
\ No newline at end of file
diff --git a/classes/Orders.php b/classes/Orders.php
index 97456be..0703e64 100644
--- a/classes/Orders.php
+++ b/classes/Orders.php
@@ -11,13 +11,15 @@ class Orders extends Users {
protected $db_connection = null;
private $errors = array();
- private $orders_table = "orderbook";
- private $customers_table = "customer";
- private $top_buy_table = "active_buy_list";
- private $top_sell_table = "active_selling_list";
- private $customer_balance_table = "assetbalance";
- private $transaction_table = "transaction";
- private $bal_history = "bal_history";
+ private $orders_table = ORDERS_TABLE;
+ private $customers_table = USERS_TABLE;
+ private $top_buy_table = TOP_BUYS_TABLE;
+ private $top_sell_table = TOP_SELL_TABLE;
+ private $customer_balance_table = CREDITS_TABLE;
+ private $transaction_table = TRANSACTIONS_TABLE;
+ private $bal_history = CREDITS_HISTORY_TABLE;
+ private $bank_acc = ACCOUNTS_TABLE;
+ private $fund_trans = TRANSFER_INFO_TABLE;
private $customerId = 0;
private $orderTypeId = 0;
private $quantity = 0;
@@ -31,8 +33,12 @@ class Orders extends Users {
private function insert_order_in_active_table($top_table, $orderId, $price, $quantity) {
if ($this->databaseConnection()) {
+
+ $n = new DateTime("now", new DateTimeZone("Asia/Kolkata"));
+ $now = $n->format('Y-m-d H:i:s');
+
$query = $this->db_connection->prepare("INSERT INTO $top_table(`price`, `orderId`, `quantity`, `customerId`, `insertDate`)
- VALUES (:price, :orderId, :quantity, :user_id, NOW())");
+ VALUES (:price, :orderId, :quantity, :user_id, '$now')");
$query->bindParam("price", $price);
$query->bindParam("orderId", $orderId);
$query->bindParam("quantity", $quantity);
@@ -68,8 +74,11 @@ class Orders extends Users {
public function record_bal_history($user_id, $balance, $type) {
if ($this->databaseConnection()) {
+
+ $now = $this->time_now();
+
$query = $this->db_connection->prepare("INSERT INTO $this->bal_history (`id`, `user_id`, `balance`, `AssetType`, `datetime`)
- VALUES ('', :uid, :bal, :asset_type, NOW())");
+ VALUES ('', :uid, :bal, :asset_type, '$now')");
$query->bindParam('uid', $user_id);
$query->bindParam('bal', $balance);
$query->bindParam('asset_type', $type);
@@ -84,19 +93,19 @@ class Orders extends Users {
public function update_user_balance($assetType, $balance=null, $user_id) {
if ($this->databaseConnection()) {
-
+ $now = $this->time_now();
$sql = "";
- if ($balance != null) {
+ if ($balance >= 0) {
$sql .= "UPDATE $this->customer_balance_table ";
$sql .= " SET `Balance`= :balance, ";
- $sql .= " `UpdateDate`= NOW() ";
+ $sql .= " `UpdateDate`= '$now' ";
$sql .= " WHERE `CustomerId`= :user_id ";
$sql .= " AND `AssetTypeId`= :asset_type ";
$sql .= "LIMIT 1";
$query = $this->db_connection->prepare($sql);
- if ($balance != null) {
+ if ($balance >= 0) {
$query->bindParam("balance", $balance);
}
$query->bindParam("user_id", $user_id);
@@ -114,7 +123,7 @@ class Orders extends Users {
public function insert_pending_order($orderTypeId, $qty, $price, $orderStatusId, $OfferAssetTypeId=null, $WantAssetTypeId=null) {
if ($this->databaseConnection()) {
-
+ $now = $this->time_now();
$messages = null;
$this->customerId = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
@@ -163,7 +172,7 @@ class Orders extends Users {
}
$query = $this->db_connection->prepare("INSERT INTO $this->orders_table (`OrderId`, `CustomerId`, `OrderTypeId`, `OfferAssetTypeId`, `WantAssetTypeId`, `Quantity`, `Price`, `OrderStatusId`, `UpdateDate`, `InsertDate`, `SaveDate`)
- VALUES ('', " . $this->customerId . ", :a, :e, :f, :b, :c, :d, NULL, Now(), NULL)");
+ VALUES ('', " . $this->customerId . ", :a, :e, :f, :b, :c, :d, NULL, '$now', NULL)");
$query->bindParam(':a', $this->orderTypeId, PDO::PARAM_STR);
$query->bindParam(':e', $OfferAssetTypeId, PDO::PARAM_STR);
@@ -222,8 +231,9 @@ class Orders extends Users {
$top_list = array();
- $query = $this->db_connection->query("SELECT OrderId, customerId, Quantity, Price, (Quantity * Price) AS TOTAL_COST
- FROM $top_table
+ $query = $this->db_connection->query("SELECT $top_table.OrderId, $top_table.customerId, $top_table.Quantity, $top_table.Price, ".USERS_TABLE.".Name
+ FROM $top_table, ".USERS_TABLE."
+ WHERE $top_table.customerId = ".USERS_TABLE.".CustomerId
ORDER BY price $asc_desc
LIMIT $this->max_top_bids
");
@@ -283,6 +293,23 @@ class Orders extends Users {
return false;
}
+ public function get_active_order_of_user($user_id, $top_table) {
+ if ($this->databaseConnection()) {
+ $query = $this->db_connection->prepare("
+ SELECT * FROM $top_table WHERE `customerId`= :uid ORDER BY `insertDate` DESC
+ ");
+ $query->bindParam('uid', $user_id);
+ $query->execute();
+
+ $arr = array();
+ while ($qr = $query->fetchObject()) {
+ $arr[] = $qr;
+ }
+ return $arr;
+ }
+ return false;
+ }
+
public function OrderMatchingQuery() {
if ($this->databaseConnection()) {
@@ -325,7 +352,7 @@ class Orders extends Users {
private function updateOrderStatus($orderId=null, $status=null) {
if ($this->databaseConnection()) {
- $query = $this->db_connection->prepare("UPDATE `orderbook` SET `OrderStatusId`= '$status' WHERE `OrderId` = :id LIMIT 1");
+ $query = $this->db_connection->prepare("UPDATE ".ORDERS_TABLE." SET `OrderStatusId`= '$status' WHERE `OrderId` = :id LIMIT 1");
$query->bindParam("id", $orderId);
if ($query->execute()) {
return true;
@@ -378,14 +405,21 @@ class Orders extends Users {
if ($buyer_balance_cash < $cost_of_total_supply) {
/*Record the message*/
- //$this->storeMessages($buy_order_id, $buyer_id, $msg="Transaction failed: You have insufficient cash balance.");
- $message[] = "Transaction failed: You have insufficient cash balance.";
+ $this->storeMessages($buy_order_id, $buyer_id, $msg="Transaction failed: You have insufficient cash balance.");
+ if ($_SESSION['user_id'] == $buyer_id) {
+ $message[] = "Transaction failed: You have insufficient cash balance.";
+ }
+ // Delete the culprit order
+ $this->del_order($buy_order_id, $buyer_id);
break;
}
if (($seller_balance_btc == 0) || ($seller_balance_btc < $available->Quantity)) {
/*Record the message*/
- //$this->storeMessages($seller_order_id, $seller_id, $msg="Transaction failed: You had insufficient RMT balance");
- $message[] = "Transaction failed: You had insufficient RMT balance";
+ $this->storeMessages($seller_order_id, $seller_id, $msg="Transaction failed: You had insufficient RMT balance");
+ if ($_SESSION['user_id'] == $seller_id) {
+ $message[] = "Transaction failed: You had insufficient RMT balance";
+ }
+ $this->del_order($seller_order_id, $seller_id);
break;
}
@@ -397,15 +431,15 @@ class Orders extends Users {
$new_buyer_balance_cash = $buyer_balance_cash - $cost_of_total_supply; // traditional or cash
// subtract the debit access (customers balance of $ or BTC)
- $this->update_user_balance($assetType = 'btc', $balance = $new_buyer_balance_btc, $user_id = $buyer_id);
+ $this->update_user_balance($assetType = 'btc', $balance = $new_buyer_balance_btc, $buyer_id);
// increment the credit asset (customers balance of $ or BTC)
- $this->update_user_balance($assetType = 'traditional', $balance = $new_seller_balance_cash, $user_id = $seller_id);
+ $this->update_user_balance($assetType = 'traditional', $balance = $new_seller_balance_cash, $seller_id);
// record the commission in the commission account
// decrease respective balances
- $this->update_user_balance($assetType = 'btc', $balance = $new_seller_balance_btc, $user_id = $seller_id);
- $this->update_user_balance($assetType = 'traditional', $balance = $new_buyer_balance_cash, $user_id = $buyer_id);
+ $this->update_user_balance($assetType = 'btc', $balance = $new_seller_balance_btc, $seller_id);
+ $this->update_user_balance($assetType = 'traditional', $balance = $new_buyer_balance_cash, $buyer_id);
}
$this->demanded_qty = $this->demanded_qty - $available->Quantity;
@@ -447,12 +481,20 @@ class Orders extends Users {
if ($buyer_balance_cash < $cost_of_total_supply) {
/*Record the message*/
- //$this->storeMessages($buy_order_id, $buyer_id, $msg="Transaction failed: You had insufficient cash balance.");
+ $this->storeMessages($buy_order_id, $buyer_id, $msg="Transaction failed: You had insufficient cash balance.");
+ if ($_SESSION['user_id'] == $buyer_id) {
+ $message[] = "Transaction failed: You have insufficient cash balance.";
+ }
+ $this->del_order($buy_order_id, $buyer_id);
break;
}
if (($seller_balance_btc == 0) || ($seller_balance_btc < $available->Quantity)) {
/*Record the message*/
- //$this->storeMessages($seller_order_id, $seller_id, $msg="Transaction failed: You had insufficient RMT balance.");
+ $this->storeMessages($seller_order_id, $seller_id, $msg="Transaction failed: You had insufficient RMT balance.");
+ if ($_SESSION['user_id'] == $seller_id) {
+ $message[] = "Transaction failed: You had insufficient RMT balance";
+ }
+ $this->del_order($seller_order_id, $seller_id);
break;
}
@@ -513,12 +555,20 @@ class Orders extends Users {
if ($buyer_balance_cash < $cost_of_total_supply) {
/*Record the message*/
- //$this->storeMessages($buy_order_id, $buyer_id, $msg="Transaction failed: You had insufficient cash balance.");
+ $this->storeMessages($buy_order_id, $buyer_id, $msg="Transaction failed: You had insufficient cash balance.");
+ if ($_SESSION['user_id'] == $buyer_id) {
+ $message[] = "Transaction failed: You have insufficient cash balance.";
+ }
+ $this->del_order($buy_order_id, $buyer_id);
break;
}
if (($seller_balance_btc == 0) || ($seller_balance_btc < $this->demanded_qty)) {
/*Record the message*/
- //$this->storeMessages($seller_order_id, $seller_id, $msg="Transaction failed: You had insufficient RMT balance.");
+ $this->storeMessages($seller_order_id, $seller_id, $msg="Transaction failed: You had insufficient RMT balance.");
+ if ($_SESSION['user_id'] == $seller_id) {
+ $message[] = "Transaction failed: You had insufficient RMT balance";
+ }
+ $this->del_order($seller_order_id, $seller_id);
break;
}
@@ -590,10 +640,10 @@ class Orders extends Users {
private function record_transaction($buyer, $buy_order_id, $buy_amount, $buy_commission, $seller, $sell_order_id, $sell_amount, $sell_commission, $trade_qty) {
if ($this->databaseConnection()) {
-
+ $now = $this->time_now();
$query = $this->db_connection->prepare("
INSERT INTO $this->transaction_table(`TransactionId`, `a_buyer`, `A_OrderId`, `A_Amount`, `A_Commission`, `b_seller`, `B_OrderId`, `B_Amount`, `B_Commission`, `qty_traded`, `UpdateDate`, `InsertDate`, `SaveDate`)
- VALUES ('', :buyer,:buy_order_id, :buy_amount, :buy_commission, :seller, :sell_order_id, :sell_amount, :sell_commission, :trade_qty, NULL, NOW(), NOW())
+ VALUES ('', :buyer,:buy_order_id, :buy_amount, :buy_commission, :seller, :sell_order_id, :sell_amount, :sell_commission, :trade_qty, NULL, '$now', '$now')
");
$query->bindParam("buyer", $buyer);
$query->bindParam("buy_order_id", $buy_order_id);
@@ -626,9 +676,10 @@ class Orders extends Users {
private function update_quantity($top_table, $qty, $orderId) {
if ($this->databaseConnection()) {
+ $now = $this->time_now();
$query = $this->db_connection->prepare("
UPDATE $top_table
- SET `quantity`= :qty, `insertDate`=NOW()
+ SET `quantity`= :qty, `insertDate`='$now'
WHERE orderId = :orderId
LIMIT 1
");
@@ -644,9 +695,9 @@ class Orders extends Users {
private function insert_market_order($customerId, $orderTypeId, $OfferAssetTypeId=null, $WantAssetTypeId=null, $qty, $price) {
if ($this->databaseConnection()) {
-
+ $now = $this->time_now();
$query = $this->db_connection->prepare("INSERT INTO $this->orders_table (`OrderId`, `CustomerId`, `OrderTypeId`, `OfferAssetTypeId`, `WantAssetTypeId`, `Quantity`, `Price`, `OrderStatusId`, `MarketOrder`, `UpdateDate`, `InsertDate`, `SaveDate`)
- VALUES ('', :u, :a, :d, :e, :b, :c, 1, 1, NULL, Now(), NULL)
+ VALUES ('', :u, :a, :d, :e, :b, :c, 1, 1, NULL, '$now', NULL)
");
$query->bindParam(':u', $customerId, PDO::PARAM_INT);
$query->bindParam(':a', $orderTypeId, PDO::PARAM_INT);
@@ -688,7 +739,7 @@ class Orders extends Users {
if(is_float($qty) || is_int($qty)) {
if ($qty > 0) {
- $sell_list = $this->get_top_buy_sell_list($top_table='active_selling_list', $asc_desc='ASC');
+ $sell_list = $this->get_top_buy_sell_list($top_table=TOP_SELL_TABLE, $asc_desc='ASC');
if (!empty($sell_list)) {
@@ -775,7 +826,7 @@ class Orders extends Users {
// Delete the row from Sell list
$this->delete_order($this->top_sell_table, $available->OrderId);
- // Update Order Status in Orderbook
+ // Update Order Status in Order table
$this->UpdateOrderStatus($available->OrderId, '1');
$message[] = "Instant Transaction Successful: You bought $available->Quantity RMT at $ $available->Price per token for $ $cost_of_total_supply.";
@@ -850,7 +901,7 @@ class Orders extends Users {
// Delete the row from Sell list
$this->delete_order($this->top_sell_table, $available->OrderId);
- // Update Order Status in Orderbook
+ // Update Order Status in Order table
$this->UpdateOrderStatus($buy_order_id, '1');
$this->UpdateOrderStatus($available->OrderId, '1');
@@ -909,7 +960,7 @@ class Orders extends Users {
// update the quantity field for supply
$this->update_quantity($top_table = $this->top_sell_table, $available->Quantity, $available->OrderId);
- // Update Order Status in Orderbook
+ // Update Order Status in Order table
$this->UpdateOrderStatus($buy_order_id, '1');
$message[] = "Instant Transaction Successful: You bought $qty tokens at $ $available->Price per token for $ $cost_of_total_supply.";
@@ -925,8 +976,8 @@ class Orders extends Users {
}
if (($available->Quantity <= 0) && ($qty > 0) && ($key === $last_iter)) {
/*The supply of token is 0. Stop further transaction. */
- $message[] = "Instant Transaction failure: There's no token left to be sold any more. $qty tokens could not be sold.";
- $this->storeMessages($buy_order_id=null, $buyer_id, $msg="There's no token left to be sold any more. $qty tokens could not be sold.");
+ $message[] = "Instant Transaction failure: There's no token left to be sold any more. $qty tokens could not be bought.";
+ $this->storeMessages($buy_order_id=null, $buyer_id, $msg="There's no token left to be sold any more. $qty tokens could not be bought.");
}
}
return $message;
@@ -941,7 +992,7 @@ class Orders extends Users {
if(is_float($qty) || is_int($qty)) {
if ($qty > 0) {
- $buy_list = $this->get_top_buy_sell_list($top_table='active_buy_list', $asc_desc='DESC');
+ $buy_list = $this->get_top_buy_sell_list($top_table=TOP_BUYS_TABLE, $asc_desc='DESC');
if (!empty($buy_list)) {
foreach ($buy_list as $available) {
@@ -1022,7 +1073,7 @@ class Orders extends Users {
// Delete the row from buy list
$this->delete_order($this->top_buy_table, $available->OrderId);
- // Update Order Status in Orderbook
+ // Update Order Status in Order table
$this->UpdateOrderStatus($available->OrderId, '1');
// Record the transaction
@@ -1089,7 +1140,7 @@ class Orders extends Users {
$qty = $qty - $available->Quantity;
- // Update Order Status in Orderbook
+ // Update Order Status in Order table
$this->UpdateOrderStatus($sell_order_id, '1');
$this->UpdateOrderStatus($available->OrderId, '1');
@@ -1155,7 +1206,7 @@ class Orders extends Users {
// update the quantity field for supply
$this->update_quantity($top_table = $this->top_buy_table, $available->Quantity, $available->OrderId);
- // Update Order Status in Orderbook
+ // Update Order Status in Order table
$this->UpdateOrderStatus($sell_order_id, '1');
$message[] = "Instant Transaction Successful: You sold $qty tokens for $ $cost_of_total_supply.";
@@ -1186,8 +1237,8 @@ class Orders extends Users {
$list = array();
$query = $this->db_connection->query("
- SELECT TransactionId AS T_ID, a_buyer AS BUYER_ID, b_seller AS SELLER_ID, (SELECT customer.Name FROM customer WHERE customer.CustomerId=BUYER_ID) AS BUYER, (SELECT customer.Name FROM customer WHERE customer.CustomerId=SELLER_ID) AS SELLER, B_AMOUNT AS TRADE_PRICE, transaction.InsertDate, transaction.qty_traded AS TRADED_QTY
- FROM transaction, customer
+ SELECT TransactionId AS T_ID, a_buyer AS BUYER_ID, b_seller AS SELLER_ID, (SELECT ".USERS_TABLE.".Name FROM ".USERS_TABLE." WHERE ".USERS_TABLE.".CustomerId=BUYER_ID) AS BUYER, (SELECT ".USERS_TABLE.".Name FROM ".USERS_TABLE." WHERE ".USERS_TABLE.".CustomerId=SELLER_ID) AS SELLER, B_AMOUNT AS TRADE_PRICE, ".TRANSACTIONS_TABLE.".InsertDate, ".TRANSACTIONS_TABLE.".qty_traded AS TRADED_QTY
+ FROM ".TRANSACTIONS_TABLE.", ".USERS_TABLE."
GROUP BY T_ID
ORDER BY T_ID DESC
LIMIT $start, $limit
@@ -1212,16 +1263,16 @@ class Orders extends Users {
$extraQuerry = "";
if ($is_active != null) {
- $extraQuerry = "WHERE customer.is_active = 0 OR customer.is_active = 1";
+ $extraQuerry = "WHERE ".USERS_TABLE.".is_active = 0 OR ".USERS_TABLE.".is_active = 1";
} else {
- $extraQuerry = "WHERE customer.is_active = 1";
+ $extraQuerry = "WHERE ".USERS_TABLE.".is_active = 1";
}
$query = $this->db_connection->query("
- SELECT customer.CustomerId AS UID, customer.Name, customer.is_active,
- (SELECT assetbalance.Balance FROM assetbalance WHERE assetbalance.AssetTypeId='btc' AND assetbalance.CustomerId=UID) AS BTC,
- (SELECT assetbalance.Balance FROM assetbalance WHERE assetbalance.AssetTypeId='traditional' AND assetbalance.CustomerId=UID) AS CASH
- FROM customer, assetbalance
+ SELECT ".USERS_TABLE.".CustomerId AS UID, ".USERS_TABLE.".Name, ".USERS_TABLE.".is_active, ".USERS_TABLE.".fb_id AS FACEBOOK_ID,
+ (SELECT ".CREDITS_TABLE.".Balance FROM ".CREDITS_TABLE." WHERE ".CREDITS_TABLE.".AssetTypeId='btc' AND ".CREDITS_TABLE.".CustomerId=UID) AS BTC,
+ (SELECT ".CREDITS_TABLE.".Balance FROM ".CREDITS_TABLE." WHERE ".CREDITS_TABLE.".AssetTypeId='traditional' AND ".CREDITS_TABLE.".CustomerId=UID) AS CASH
+ FROM ".USERS_TABLE.", ".CREDITS_TABLE."
$extraQuerry
GROUP BY UID ORDER BY MAX(BTC) DESC
");
@@ -1241,7 +1292,7 @@ class Orders extends Users {
if ($this->databaseConnection()) {
$query = $this->db_connection->query("
- SELECT `B_Amount` FROM `transaction` ORDER BY `InsertDate` DESC LIMIT 1
+ SELECT `B_Amount`,InsertDate FROM ".TRANSACTIONS_TABLE." ORDER BY `InsertDate` DESC LIMIT 1
");
if ($query->rowCount() == 1) {
@@ -1259,7 +1310,7 @@ class Orders extends Users {
$list = array();
$query = $this->db_connection->prepare("
SELECT `OrderId`, `CustomerId`, `OrderTypeId`, `OfferAssetTypeId`, `WantAssetTypeId`, `Quantity`, `Price`, `OrderStatusId`, `MarketOrder`, `InsertDate`
- FROM `orderbook`
+ FROM ".ORDERS_TABLE."
WHERE `CustomerId`=:u_id
ORDER BY InsertDate DESC
LIMIT $start, $limit
@@ -1278,23 +1329,11 @@ class Orders extends Users {
return false;
}
- public function del_order($order_id) {
+ protected function cancel_order($order_id=null, $user_id=null) {
if ($this->databaseConnection()) {
-
- $user_id = 0;
- if (!isset($_SESSION['user_id'])) {
- return false;
- }
- $user_id = (int) $_SESSION['user_id'];
- $is_owner = $this->isUserOrderOwner($order_id, $user_id);
-
- if (!$is_owner) {
- return false;
- }
-
$query = $this->db_connection->prepare("
- DELETE FROM `active_buy_list` WHERE `orderId`=:id AND customerId = :cus_id;
- DELETE FROM `active_selling_list` WHERE `orderId`=:id AND customerId = :cus_id
+ DELETE FROM ".TOP_BUYS_TABLE." WHERE `orderId`=:id AND customerId = :cus_id;
+ DELETE FROM ".TOP_SELL_TABLE." WHERE `orderId`=:id AND customerId = :cus_id
");
$query->bindParam('id', $order_id);
@@ -1304,7 +1343,7 @@ class Orders extends Users {
unset($query); // Unset the query
$q = $this->db_connection->prepare("
- UPDATE `orderbook` SET `OrderStatusId`= 0
+ UPDATE ".ORDERS_TABLE." SET `OrderStatusId`= 0
WHERE `OrderId` = :ord
AND CustomerId = :cust_id
");
@@ -1315,29 +1354,64 @@ class Orders extends Users {
unset($q);
$query2 = $this->db_connection->prepare("
- SELECT * FROM `active_buy_list` WHERE `orderId`=:o_id;
- SELECT * FROM `active_selling_list` WHERE `orderId`=:o_id
+ SELECT * FROM ".TOP_BUYS_TABLE." WHERE `orderId`=:o_id;
+ SELECT * FROM ".TOP_SELL_TABLE." WHERE `orderId`=:o_id
");
$query2->bindParam('o_id', $order_id);
if ($query2->execute()) {
if ($query2->rowCount() == 0) {
+ if ($_SESSION['user_id']==ADMIN_ID) {
+ $this->storeMessages($order_id, ADMIN_ID, $msg="Order number $order_id was deleted by user id ".ADMIN_ID);
+ $this->storeMessages($order_id, $user_id, $msg="Order number $order_id was deleted by Admin.");
+ } else {
+ $this->storeMessages($order_id, $user_id, $msg="Order number $order_id was deleted by you.");
+ }
return true; // This means row was actually deleted
}
}
-
}
return false;
}
- private function storeMessages($order_id=null, $user_id=null, $msg=null) {
- if($this->databaseConnection()) {
+ public function del_order($order_id, $usid=null) {
+ if ($this->databaseConnection()) {
- $username = (string) trim($this->check_user($user_id)->Username);
+ $user_id = 0;
+ if (!isset($_SESSION['user_id'])) {
+ return false;
+ }
+ $user_id = (int) $_SESSION['user_id'];
+ // Allow Admin to delete order, if its not admin check owner of order
+ if ($usid == null) {
+ $is_owner = $this->isUserOrderOwner($order_id, $user_id);
+
+ if (!$is_owner) {
+ return false;
+ }
+ } else if(($usid != null) && ($user_id == ADMIN_ID)) { // This else part to be used by admin in delete_orders_of_user()
+ $user_id = $usid;
+ } else {
+ return false;
+ }
+
+ // Finally cancel the order
+ return $this->cancel_order($order_id, $user_id);
+ }
+ return false;
+ }
+
+ public function storeMessages($order_id=null, $user_id=null, $msg=null) {
+ if($this->databaseConnection()) {
+ $now = $this->time_now();
+ if ($user_id == false) {
+ return false;
+ }
+ $username = $this->get_username($user_id);
$query = $this->db_connection->prepare("
- INSERT INTO `messages`(`id`, `order_id`, `username_key`, `username`, `messages`, `datetime`)
- VALUES ('', :order_id, :user_id, :username, :msg, NOW())
+ INSERT INTO ".MSG_TABLE."(`id`, `order_id`, `username_key`, `username`, `messages`, `datetime`)
+ VALUES ('', :order_id, :user_id, :username, :msg, '$now')
");
$query->bindParam("order_id", $order_id);
$query->bindParam("user_id", $user_id);
@@ -1366,7 +1440,7 @@ class Orders extends Users {
}
$query = $this->db_connection->prepare("
SELECT COUNT(*) AS MY_TOTAL_MESSAGES
- FROM `messages`
+ FROM ".MSG_TABLE."
WHERE `username_key`=:u_id
");
$query->bindParam('u_id', $user_id);
@@ -1390,7 +1464,7 @@ class Orders extends Users {
}
$query = $this->db_connection->prepare("
SELECT COUNT(*) AS MY_TOTAL_ORDERS
- FROM `orderbook`
+ FROM ".ORDERS_TABLE."
WHERE `CustomerId`=:u_id
");
$query->bindParam('u_id', $user_id);
@@ -1414,7 +1488,7 @@ class Orders extends Users {
}
$query = $this->db_connection->prepare("
SELECT COUNT(*) AS MY_TOTAL_ORDERS
- FROM `transaction`
+ FROM ".TRANSACTIONS_TABLE."
WHERE `a_buyer`= :u_id OR `b_seller`= :u_id
");
$query->bindParam('u_id', $user_id);
@@ -1434,7 +1508,7 @@ class Orders extends Users {
$query = $this->db_connection->prepare("
SELECT COUNT(*) AS TOTAL_ORDERS
- FROM `transaction`
+ FROM ".TRANSACTIONS_TABLE."
");
if ($query->execute()) {
$fetch = $query->fetchObject();
@@ -1448,7 +1522,7 @@ class Orders extends Users {
private function isUserOrderOwner($order_id=0, $user_id=0) {
if ($this->databaseConnection()) {
$query = $this->db_connection->prepare("
- SELECT `OrderId` FROM `orderbook`
+ SELECT `OrderId` FROM ".ORDERS_TABLE."
WHERE `OrderId`=:o_id
AND `CustomerId`=:c_id
LIMIT 1
@@ -1464,5 +1538,184 @@ class Orders extends Users {
return false;
}
+ public function storeMessagesPublic($order_id=null, $user_id=null, $msg=null) {
+ if ($this->databaseConnection()) {
+ $this->storeMessages($order_id, $user_id, $msg);
+ }
+ }
+
+ /*Add bank account*/
+ public function add_bank_account($user_id, $holder, $bank_name, $account_num, $branch_name, $bank_addr, $bk_ctry) {
+ if ($this->databaseConnection()) {
+ $now = $this->time_now();
+ $query = $this->db_connection->prepare(
+ "INSERT INTO $this->bank_acc(`id`, `user_id`, `acc_holder`, `bank_name`, `acc_num`, `branch_name`, `bank_addr`, `bank_ctry`, `date_added`)
+ VALUES ('', :uid, :holder, :bk_name, :acc_num, :br_name, :addr, :ctry, '$now')"
+ );
+ $query->bindParam("uid", $user_id);
+ $query->bindParam("holder", $holder);
+ $query->bindParam("bk_name", $bank_name);
+ $query->bindParam("acc_num", $account_num);
+ $query->bindParam("br_name", $branch_name);
+ $query->bindParam("addr", $bank_addr);
+ $query->bindParam("ctry", $bk_ctry);
+
+ if ($query->execute()) {
+ $this->storeMessages(null, $user_id, $msg="You added a new bank account number $account_num.");
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public function send_notice_mail($reciever_email, $email_from, $email_sender, $email_subject, $email_body) {
+ $mail = new SendMail();
+ $do_mail = $mail->do_email($reciever_email, $email_from, $email_sender, $email_subject, $email_body);
+ if ($do_mail==true) {
+ return $do_mail;
+ }
+ return false;
+ }
+
+ public function get_bank_details($user_id, $acc=null) {
+ $acc_details = null;
+ if ($this->databaseConnection()) {
+
+ $ex = "";
+ if ($acc != null) {
+ $ex = "AND `acc_num`=:acc";
+ }
+
+ $query = $this->db_connection->prepare(
+ "SELECT * FROM $this->bank_acc WHERE `user_id`=:uid $ex"
+ );
+ $query->bindParam("uid", $user_id);
+ if ($acc != null) {
+ $query->bindParam("acc", $acc);
+ }
+ $query->execute();
+
+ if ($query->rowCount() > 0) {
+ while ($acc_info = $query->fetchObject()) {
+ $acc_details[] = $acc_info;
+ }
+ }
+ }
+ return $acc_details;
+ }
+
+ /*Fund transfer*/
+ public function fund_transfer($fund_type, $from, $to, $amount, $remarks, $assetType) {
+ $user_id = (isset($_SESSION['user_id']) && (int) $_SESSION['user_id'] != 0) ? $_SESSION['user_id'] : 0;
+ $now = $this->time_now();
+ if ($this->databaseConnection() && $user_id != 0) {
+
+ $user_bal_currently = (float)$this->check_customer_balance($assetType, $user_id)->Balance;
+
+ $new_bal = (float)$user_bal_currently - $amount;
+
+ $ft = $this->update_user_balance($assetType, $new_bal, $user_id);
+
+ if ($user_bal_currently == null || $ft == null) {
+ return false;
+ }
+
+ $sign = ($assetType == 'btc') ? 'RTM':'$';
+
+ $query = $this->db_connection->prepare(
+ "INSERT INTO ".TRANSFER_INFO_TABLE."(`id`, `user_id`, `fund_type`, `tr_from`, `tr_to`, `fund_amount`, `remarks`, `datetime`)
+ VALUES('', :uid, :fund_type, :tr_from, :tr_to, :tr_amount, :remarks, '$now')"
+ );
+ $query->bindParam('uid', $user_id);
+ $query->bindParam('fund_type', $fund_type);
+ $query->bindParam('tr_from', $from);
+ $query->bindParam('tr_to', $to);
+ $query->bindParam('tr_amount', $amount);
+ $query->bindParam('remarks', $remarks);
+
+ if ($query->execute()) {
+ $this->storeMessages(null, $user_id, $msg="You have requested to transfer $sign $amount to bank account number $to.");
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public function record_root_bal_update($uid, $bal_prev, $bal_now, $bal_type) {
+ if ($this->databaseConnection()) {
+ $now = $this->time_now();
+ $root = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0;
+ $query = $this->db_connection->prepare("
+ INSERT INTO ".ADMIN_BAL_RECORDS."(`BalStatusHistoryId`, `user_id`, `bal_prev`, `bal_now`, `type`, `root_id`, `UpdateDate`)
+ VALUES ('', :uid, :prev, :now, :btype, :root, '$now')
+ ");
+ $query->bindParam("uid", $uid);
+ $query->bindParam("prev", $bal_prev);
+ $query->bindParam("now", $bal_now);
+ $query->bindParam("btype", $bal_type);
+ $query->bindParam("root", $root);
+
+ if ($query->execute()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public function list_root_bal_changes() {
+ if ($this->databaseConnection()) {
+ $list_details = array();
+ $query = $this->db_connection->prepare("
+ SELECT ".ADMIN_BAL_RECORDS.".*, ".USERS_TABLE.".Name, ".USERS_TABLE.".Email
+ FROM ".ADMIN_BAL_RECORDS.", ".USERS_TABLE."
+ WHERE ".ADMIN_BAL_RECORDS.".user_id=".USERS_TABLE.".CustomerId
+ ORDER BY UpdateDate DESC
+ LIMIT 200
+ ");
+ $query->execute();
+
+ if ($query->rowCount() > 0) {
+ while ($list = $query->fetchObject()) {
+ $list_details[] = $list;
+ }
+ }
+ return $list_details;
+ }
+ return false;
+ }
+
+ public function get_last_order_date($date=null) {
+ if ($this->databaseConnection()) {
+ $query = $this->db_connection->query("SELECT * FROM `orderbook` WHERE `InsertDate`> '$date'");
+ if ($query->rowCount()) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public function delete_orders_of_user($user_id=null) {
+ if ($this->databaseConnection()) {
+ $order_ids = array();
+ $query = $this->db_connection->prepare("
+ SELECT orderId FROM ".TOP_BUYS_TABLE." WHERE `customerId`=:uid
+ UNION
+ SELECT orderId FROM ".TOP_SELL_TABLE." WHERE `customerId`=:uid
+ ");
+ $query->bindParam('uid', $user_id);
+ $query->execute();
+ if ($query->rowCount() > 0) {
+ while ($rr = $query->fetchObject()) {
+ $order_ids[] = $rr;
+ }
+ foreach ($order_ids as $oid) {
+ $this->del_order($oid->orderId, $user_id);
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+
}
diff --git a/classes/PHPMailer.php b/classes/PHPMailer.php
new file mode 100644
index 0000000..bfb8eca
--- /dev/null
+++ b/classes/PHPMailer.php
@@ -0,0 +1,2949 @@
+UseSendmailOptions) ) {
+ $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header);
+ } else {
+ $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params);
+ }
+ return $rt;
+ }
+
+ /**
+ * Outputs debugging info via user-defined method
+ * @param string $str
+ */
+ protected function edebug($str) {
+ switch ($this->Debugoutput) {
+ case 'error_log':
+ error_log($str);
+ break;
+ case 'html':
+ //Cleans up output a bit for a better looking display that's HTML-safe
+ echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet)." \n";
+ break;
+ case 'echo':
+ default:
+ //Just echoes exactly what was received
+ echo $str;
+ }
+ }
+
+ /**
+ * Constructor
+ * @param boolean $exceptions Should we throw external exceptions?
+ */
+ public function __construct($exceptions = false) {
+ $this->exceptions = ($exceptions == true);
+ }
+
+ /**
+ * Destructor
+ */
+ public function __destruct() {
+ if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely
+ $this->SmtpClose();
+ }
+ }
+
+ /**
+ * Sets message type to HTML.
+ * @param bool $ishtml
+ * @return void
+ */
+ public function IsHTML($ishtml = true) {
+ if ($ishtml) {
+ $this->ContentType = 'text/html';
+ } else {
+ $this->ContentType = 'text/plain';
+ }
+ }
+
+ /**
+ * Sets Mailer to send message using SMTP.
+ * @return void
+ */
+ public function IsSMTP() {
+ $this->Mailer = 'smtp';
+ }
+
+ /**
+ * Sets Mailer to send message using PHP mail() function.
+ * @return void
+ */
+ public function IsMail() {
+ $this->Mailer = 'mail';
+ }
+
+ /**
+ * Sets Mailer to send message using the $Sendmail program.
+ * @return void
+ */
+ public function IsSendmail() {
+ if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
+ $this->Sendmail = '/var/qmail/bin/sendmail';
+ }
+ $this->Mailer = 'sendmail';
+ }
+
+ /**
+ * Sets Mailer to send message using the qmail MTA.
+ * @return void
+ */
+ public function IsQmail() {
+ if (stristr(ini_get('sendmail_path'), 'qmail')) {
+ $this->Sendmail = '/var/qmail/bin/sendmail';
+ }
+ $this->Mailer = 'sendmail';
+ }
+
+ /////////////////////////////////////////////////
+ // METHODS, RECIPIENTS
+ /////////////////////////////////////////////////
+
+ /**
+ * Adds a "To" address.
+ * @param string $address
+ * @param string $name
+ * @return boolean true on success, false if address already used
+ */
+ public function AddAddress($address, $name = '') {
+ return $this->AddAnAddress('to', $address, $name);
+ }
+
+ /**
+ * Adds a "Cc" address.
+ * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
+ * @param string $address
+ * @param string $name
+ * @return boolean true on success, false if address already used
+ */
+ public function AddCC($address, $name = '') {
+ return $this->AddAnAddress('cc', $address, $name);
+ }
+
+ /**
+ * Adds a "Bcc" address.
+ * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
+ * @param string $address
+ * @param string $name
+ * @return boolean true on success, false if address already used
+ */
+ public function AddBCC($address, $name = '') {
+ return $this->AddAnAddress('bcc', $address, $name);
+ }
+
+ /**
+ * Adds a "Reply-to" address.
+ * @param string $address
+ * @param string $name
+ * @return boolean
+ */
+ public function AddReplyTo($address, $name = '') {
+ return $this->AddAnAddress('Reply-To', $address, $name);
+ }
+
+ /**
+ * Adds an address to one of the recipient arrays
+ * Addresses that have been added already return false, but do not throw exceptions
+ * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
+ * @param string $address The email address to send to
+ * @param string $name
+ * @throws phpmailerException
+ * @return boolean true on success, false if address already used or invalid in some way
+ * @access protected
+ */
+ protected function AddAnAddress($kind, $address, $name = '') {
+ if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
+ $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
+ if ($this->exceptions) {
+ throw new phpmailerException('Invalid recipient array: ' . $kind);
+ }
+ if ($this->SMTPDebug) {
+ $this->edebug($this->Lang('Invalid recipient array').': '.$kind);
+ }
+ return false;
+ }
+ $address = trim($address);
+ $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
+ if (!$this->ValidateAddress($address)) {
+ $this->SetError($this->Lang('invalid_address').': '. $address);
+ if ($this->exceptions) {
+ throw new phpmailerException($this->Lang('invalid_address').': '.$address);
+ }
+ if ($this->SMTPDebug) {
+ $this->edebug($this->Lang('invalid_address').': '.$address);
+ }
+ return false;
+ }
+ if ($kind != 'Reply-To') {
+ if (!isset($this->all_recipients[strtolower($address)])) {
+ array_push($this->$kind, array($address, $name));
+ $this->all_recipients[strtolower($address)] = true;
+ return true;
+ }
+ } else {
+ if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
+ $this->ReplyTo[strtolower($address)] = array($address, $name);
+ return true;
+ }
+ }
+ return false;
+}
+
+ /**
+ * Set the From and FromName properties
+ * @param string $address
+ * @param string $name
+ * @param boolean $auto Whether to also set the Sender address, defaults to true
+ * @throws phpmailerException
+ * @return boolean
+ */
+ public function SetFrom($address, $name = '', $auto = true) {
+ $address = trim($address);
+ $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
+ if (!$this->ValidateAddress($address)) {
+ $this->SetError($this->Lang('invalid_address').': '. $address);
+ if ($this->exceptions) {
+ throw new phpmailerException($this->Lang('invalid_address').': '.$address);
+ }
+ if ($this->SMTPDebug) {
+ $this->edebug($this->Lang('invalid_address').': '.$address);
+ }
+ return false;
+ }
+ $this->From = $address;
+ $this->FromName = $name;
+ if ($auto) {
+ if (empty($this->Sender)) {
+ $this->Sender = $address;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Check that a string looks roughly like an email address should
+ * Static so it can be used without instantiation, public so people can overload
+ * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is
+ * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to
+ * not allow a@b type valid addresses :(
+ * @link http://squiloople.com/2009/12/20/email-address-validation/
+ * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice.
+ * @param string $address The email address to check
+ * @return boolean
+ * @static
+ * @access public
+ */
+ public static function ValidateAddress($address) {
+ if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled
+ if (version_compare(PCRE_VERSION, '8.0') >= 0) {
+ return (boolean)preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address);
+ } else {
+ //Fall back to an older regex that doesn't need a recent PCRE
+ return (boolean)preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address);
+ }
+ } else {
+ //No PCRE! Do something _very_ approximate!
+ //Check the address is 3 chars or longer and contains an @ that's not the first or last char
+ return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1);
+ }
+ }
+
+ /////////////////////////////////////////////////
+ // METHODS, MAIL SENDING
+ /////////////////////////////////////////////////
+
+ /**
+ * Creates message and assigns Mailer. If the message is
+ * not sent successfully then it returns false. Use the ErrorInfo
+ * variable to view description of the error.
+ * @throws phpmailerException
+ * @return bool
+ */
+ public function Send() {
+ try {
+ if(!$this->PreSend()) return false;
+ return $this->PostSend();
+ } catch (phpmailerException $e) {
+ $this->mailHeader = '';
+ $this->SetError($e->getMessage());
+ if ($this->exceptions) {
+ throw $e;
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Prep mail by constructing all message entities
+ * @throws phpmailerException
+ * @return bool
+ */
+ public function PreSend() {
+ try {
+ $this->mailHeader = "";
+ if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
+ throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
+ }
+
+ // Set whether the message is multipart/alternative
+ if(!empty($this->AltBody)) {
+ $this->ContentType = 'multipart/alternative';
+ }
+
+ $this->error_count = 0; // reset errors
+ $this->SetMessageType();
+ //Refuse to send an empty message unless we are specifically allowing it
+ if (!$this->AllowEmpty and empty($this->Body)) {
+ throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
+ }
+
+ $this->MIMEHeader = $this->CreateHeader();
+ $this->MIMEBody = $this->CreateBody();
+
+ // To capture the complete message when using mail(), create
+ // an extra header list which CreateHeader() doesn't fold in
+ if ($this->Mailer == 'mail') {
+ if (count($this->to) > 0) {
+ $this->mailHeader .= $this->AddrAppend("To", $this->to);
+ } else {
+ $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;");
+ }
+ $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject))));
+ }
+
+ // digitally sign with DKIM if enabled
+ if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) {
+ $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
+ $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
+ }
+
+ return true;
+
+ } catch (phpmailerException $e) {
+ $this->SetError($e->getMessage());
+ if ($this->exceptions) {
+ throw $e;
+ }
+ return false;
+ }
+ }
+
+ /**
+ * Actual Email transport function
+ * Send the email via the selected mechanism
+ * @throws phpmailerException
+ * @return bool
+ */
+ public function PostSend() {
+ try {
+ // Choose the mailer and send through it
+ switch($this->Mailer) {
+ case 'sendmail':
+ return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
+ case 'smtp':
+ return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
+ case 'mail':
+ return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
+ default:
+ return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
+ }
+ } catch (phpmailerException $e) {
+ $this->SetError($e->getMessage());
+ if ($this->exceptions) {
+ throw $e;
+ }
+ if ($this->SMTPDebug) {
+ $this->edebug($e->getMessage()."\n");
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Sends mail using the $Sendmail program.
+ * @param string $header The message headers
+ * @param string $body The message body
+ * @throws phpmailerException
+ * @access protected
+ * @return bool
+ */
+ protected function SendmailSend($header, $body) {
+ if ($this->Sender != '') {
+ $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
+ } else {
+ $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
+ }
+ if ($this->SingleTo === true) {
+ foreach ($this->SingleToArray as $val) {
+ if(!@$mail = popen($sendmail, 'w')) {
+ throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
+ }
+ fputs($mail, "To: " . $val . "\n");
+ fputs($mail, $header);
+ fputs($mail, $body);
+ $result = pclose($mail);
+ // implement call back function if it exists
+ $isSent = ($result == 0) ? 1 : 0;
+ $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
+ if($result != 0) {
+ throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
+ }
+ }
+ } else {
+ if(!@$mail = popen($sendmail, 'w')) {
+ throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
+ }
+ fputs($mail, $header);
+ fputs($mail, $body);
+ $result = pclose($mail);
+ // implement call back function if it exists
+ $isSent = ($result == 0) ? 1 : 0;
+ $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
+ if($result != 0) {
+ throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Sends mail using the PHP mail() function.
+ * @param string $header The message headers
+ * @param string $body The message body
+ * @throws phpmailerException
+ * @access protected
+ * @return bool
+ */
+ protected function MailSend($header, $body) {
+ $toArr = array();
+ foreach($this->to as $t) {
+ $toArr[] = $this->AddrFormat($t);
+ }
+ $to = implode(', ', $toArr);
+
+ if (empty($this->Sender)) {
+ $params = " ";
+ } else {
+ $params = sprintf("-f%s", $this->Sender);
+ }
+ if ($this->Sender != '' and !ini_get('safe_mode')) {
+ $old_from = ini_get('sendmail_from');
+ ini_set('sendmail_from', $this->Sender);
+ }
+ $rt = false;
+ if ($this->SingleTo === true && count($toArr) > 1) {
+ foreach ($toArr as $val) {
+ $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params);
+ // implement call back function if it exists
+ $isSent = ($rt == 1) ? 1 : 0;
+ $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
+ }
+ } else {
+ $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params);
+ // implement call back function if it exists
+ $isSent = ($rt == 1) ? 1 : 0;
+ $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
+ }
+ if (isset($old_from)) {
+ ini_set('sendmail_from', $old_from);
+ }
+ if(!$rt) {
+ throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
+ }
+ return true;
+ }
+
+ /**
+ * Sends mail via SMTP using PhpSMTP
+ * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
+ * @param string $header The message headers
+ * @param string $body The message body
+ * @throws phpmailerException
+ * @uses SMTP
+ * @access protected
+ * @return bool
+ */
+ protected function SmtpSend($header, $body) {
+ require_once $this->PluginDir . 'class.smtp.php';
+ $bad_rcpt = array();
+
+ if(!$this->SmtpConnect()) {
+ throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
+ }
+ $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
+ if(!$this->smtp->Mail($smtp_from)) {
+ $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError()));
+ throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
+ }
+
+ // Attempt to send attach all recipients
+ foreach($this->to as $to) {
+ if (!$this->smtp->Recipient($to[0])) {
+ $bad_rcpt[] = $to[0];
+ // implement call back function if it exists
+ $isSent = 0;
+ $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
+ } else {
+ // implement call back function if it exists
+ $isSent = 1;
+ $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
+ }
+ }
+ foreach($this->cc as $cc) {
+ if (!$this->smtp->Recipient($cc[0])) {
+ $bad_rcpt[] = $cc[0];
+ // implement call back function if it exists
+ $isSent = 0;
+ $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
+ } else {
+ // implement call back function if it exists
+ $isSent = 1;
+ $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
+ }
+ }
+ foreach($this->bcc as $bcc) {
+ if (!$this->smtp->Recipient($bcc[0])) {
+ $bad_rcpt[] = $bcc[0];
+ // implement call back function if it exists
+ $isSent = 0;
+ $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
+ } else {
+ // implement call back function if it exists
+ $isSent = 1;
+ $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
+ }
+ }
+
+
+ if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
+ $badaddresses = implode(', ', $bad_rcpt);
+ throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
+ }
+ if(!$this->smtp->Data($header . $body)) {
+ throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
+ }
+ if($this->SMTPKeepAlive == true) {
+ $this->smtp->Reset();
+ } else {
+ $this->smtp->Quit();
+ $this->smtp->Close();
+ }
+ return true;
+ }
+
+ /**
+ * Initiates a connection to an SMTP server.
+ * Returns false if the operation failed.
+ * @param array $options An array of options compatible with stream_context_create()
+ * @uses SMTP
+ * @access public
+ * @throws phpmailerException
+ * @return bool
+ */
+ public function SmtpConnect($options = array()) {
+ if(is_null($this->smtp)) {
+ $this->smtp = new SMTP;
+ }
+
+ //Already connected?
+ if ($this->smtp->Connected()) {
+ return true;
+ }
+
+ $this->smtp->Timeout = $this->Timeout;
+ $this->smtp->do_debug = $this->SMTPDebug;
+ $this->smtp->Debugoutput = $this->Debugoutput;
+ $this->smtp->do_verp = $this->do_verp;
+ $index = 0;
+ $tls = ($this->SMTPSecure == 'tls');
+ $ssl = ($this->SMTPSecure == 'ssl');
+ $hosts = explode(';', $this->Host);
+ $lastexception = null;
+
+ foreach ($hosts as $hostentry) {
+ $hostinfo = array();
+ $host = $hostentry;
+ $port = $this->Port;
+ if (preg_match('/^(.+):([0-9]+)$/', $hostentry, $hostinfo)) { //If $hostentry contains 'address:port', override default
+ $host = $hostinfo[1];
+ $port = $hostinfo[2];
+ }
+ if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout, $options)) {
+ try {
+ if ($this->Helo) {
+ $hello = $this->Helo;
+ } else {
+ $hello = $this->ServerHostname();
+ }
+ $this->smtp->Hello($hello);
+
+ if ($tls) {
+ if (!$this->smtp->StartTLS()) {
+ throw new phpmailerException($this->Lang('connect_host'));
+ }
+ //We must resend HELO after tls negotiation
+ $this->smtp->Hello($hello);
+ }
+ if ($this->SMTPAuth) {
+ if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) {
+ throw new phpmailerException($this->Lang('authenticate'));
+ }
+ }
+ return true;
+ } catch (phpmailerException $e) {
+ $lastexception = $e;
+ //We must have connected, but then failed TLS or Auth, so close connection nicely
+ $this->smtp->Quit();
+ }
+ }
+ }
+ //If we get here, all connection attempts have failed, so close connection hard
+ $this->smtp->Close();
+ //As we've caught all exceptions, just report whatever the last one was
+ if ($this->exceptions and !is_null($lastexception)) {
+ throw $lastexception;
+ }
+ return false;
+ }
+
+ /**
+ * Closes the active SMTP session if one exists.
+ * @return void
+ */
+ public function SmtpClose() {
+ if ($this->smtp !== null) {
+ if($this->smtp->Connected()) {
+ $this->smtp->Quit();
+ $this->smtp->Close();
+ }
+ }
+ }
+
+ /**
+ * Sets the language for all class error messages.
+ * Returns false if it cannot load the language file. The default language is English.
+ * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
+ * @param string $lang_path Path to the language file directory
+ * @return bool
+ * @access public
+ */
+ function SetLanguage($langcode = 'en', $lang_path = 'language/') {
+ //Define full set of translatable strings
+ $PHPMAILER_LANG = array(
+ 'authenticate' => 'SMTP Error: Could not authenticate.',
+ 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
+ 'data_not_accepted' => 'SMTP Error: Data not accepted.',
+ 'empty_message' => 'Message body empty',
+ 'encoding' => 'Unknown encoding: ',
+ 'execute' => 'Could not execute: ',
+ 'file_access' => 'Could not access file: ',
+ 'file_open' => 'File Error: Could not open file: ',
+ 'from_failed' => 'The following From address failed: ',
+ 'instantiate' => 'Could not instantiate mail function.',
+ 'invalid_address' => 'Invalid address',
+ 'mailer_not_supported' => ' mailer is not supported.',
+ 'provide_address' => 'You must provide at least one recipient email address.',
+ 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
+ 'signing' => 'Signing Error: ',
+ 'smtp_connect_failed' => 'SMTP Connect() failed.',
+ 'smtp_error' => 'SMTP server error: ',
+ 'variable_set' => 'Cannot set or reset variable: '
+ );
+ //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
+ $l = true;
+ if ($langcode != 'en') { //There is no English translation file
+ $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
+ }
+ $this->language = $PHPMAILER_LANG;
+ return ($l == true); //Returns false if language not found
+ }
+
+ /**
+ * Return the current array of language strings
+ * @return array
+ */
+ public function GetTranslations() {
+ return $this->language;
+ }
+
+ /////////////////////////////////////////////////
+ // METHODS, MESSAGE CREATION
+ /////////////////////////////////////////////////
+
+ /**
+ * Creates recipient headers.
+ * @access public
+ * @param string $type
+ * @param array $addr
+ * @return string
+ */
+ public function AddrAppend($type, $addr) {
+ $addr_str = $type . ': ';
+ $addresses = array();
+ foreach ($addr as $a) {
+ $addresses[] = $this->AddrFormat($a);
+ }
+ $addr_str .= implode(', ', $addresses);
+ $addr_str .= $this->LE;
+
+ return $addr_str;
+ }
+
+ /**
+ * Formats an address correctly.
+ * @access public
+ * @param string $addr
+ * @return string
+ */
+ public function AddrFormat($addr) {
+ if (empty($addr[1])) {
+ return $this->SecureHeader($addr[0]);
+ } else {
+ return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
+ }
+ }
+
+ /**
+ * Wraps message for use with mailers that do not
+ * automatically perform wrapping and for quoted-printable.
+ * Original written by philippe.
+ * @param string $message The message to wrap
+ * @param integer $length The line length to wrap to
+ * @param boolean $qp_mode Whether to run in Quoted-Printable mode
+ * @access public
+ * @return string
+ */
+ public function WrapText($message, $length, $qp_mode = false) {
+ $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
+ // If utf-8 encoding is used, we will need to make sure we don't
+ // split multibyte characters when we wrap
+ $is_utf8 = (strtolower($this->CharSet) == "utf-8");
+ $lelen = strlen($this->LE);
+ $crlflen = strlen(self::CRLF);
+
+ $message = $this->FixEOL($message);
+ if (substr($message, -$lelen) == $this->LE) {
+ $message = substr($message, 0, -$lelen);
+ }
+
+ $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE
+ $message = '';
+ for ($i = 0 ;$i < count($line); $i++) {
+ $line_part = explode(' ', $line[$i]);
+ $buf = '';
+ for ($e = 0; $e $length)) {
+ $space_left = $length - strlen($buf) - $crlflen;
+ if ($e != 0) {
+ if ($space_left > 20) {
+ $len = $space_left;
+ if ($is_utf8) {
+ $len = $this->UTF8CharBoundary($word, $len);
+ } elseif (substr($word, $len - 1, 1) == "=") {
+ $len--;
+ } elseif (substr($word, $len - 2, 1) == "=") {
+ $len -= 2;
+ }
+ $part = substr($word, 0, $len);
+ $word = substr($word, $len);
+ $buf .= ' ' . $part;
+ $message .= $buf . sprintf("=%s", self::CRLF);
+ } else {
+ $message .= $buf . $soft_break;
+ }
+ $buf = '';
+ }
+ while (strlen($word) > 0) {
+ if ($length <= 0) {
+ break;
+ }
+ $len = $length;
+ if ($is_utf8) {
+ $len = $this->UTF8CharBoundary($word, $len);
+ } elseif (substr($word, $len - 1, 1) == "=") {
+ $len--;
+ } elseif (substr($word, $len - 2, 1) == "=") {
+ $len -= 2;
+ }
+ $part = substr($word, 0, $len);
+ $word = substr($word, $len);
+
+ if (strlen($word) > 0) {
+ $message .= $part . sprintf("=%s", self::CRLF);
+ } else {
+ $buf = $part;
+ }
+ }
+ } else {
+ $buf_o = $buf;
+ $buf .= ($e == 0) ? $word : (' ' . $word);
+
+ if (strlen($buf) > $length and $buf_o != '') {
+ $message .= $buf_o . $soft_break;
+ $buf = $word;
+ }
+ }
+ }
+ $message .= $buf . self::CRLF;
+ }
+
+ return $message;
+ }
+
+ /**
+ * Finds last character boundary prior to maxLength in a utf-8
+ * quoted (printable) encoded string.
+ * Original written by Colin Brown.
+ * @access public
+ * @param string $encodedText utf-8 QP text
+ * @param int $maxLength find last character boundary prior to this length
+ * @return int
+ */
+ public function UTF8CharBoundary($encodedText, $maxLength) {
+ $foundSplitPos = false;
+ $lookBack = 3;
+ while (!$foundSplitPos) {
+ $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
+ $encodedCharPos = strpos($lastChunk, "=");
+ if ($encodedCharPos !== false) {
+ // Found start of encoded character byte within $lookBack block.
+ // Check the encoded byte value (the 2 chars after the '=')
+ $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
+ $dec = hexdec($hex);
+ if ($dec < 128) { // Single byte character.
+ // If the encoded char was found at pos 0, it will fit
+ // otherwise reduce maxLength to start of the encoded char
+ $maxLength = ($encodedCharPos == 0) ? $maxLength :
+ $maxLength - ($lookBack - $encodedCharPos);
+ $foundSplitPos = true;
+ } elseif ($dec >= 192) { // First byte of a multi byte character
+ // Reduce maxLength to split at start of character
+ $maxLength = $maxLength - ($lookBack - $encodedCharPos);
+ $foundSplitPos = true;
+ } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
+ $lookBack += 3;
+ }
+ } else {
+ // No encoded character found
+ $foundSplitPos = true;
+ }
+ }
+ return $maxLength;
+ }
+
+
+ /**
+ * Set the body wrapping.
+ * @access public
+ * @return void
+ */
+ public function SetWordWrap() {
+ if($this->WordWrap < 1) {
+ return;
+ }
+
+ switch($this->message_type) {
+ case 'alt':
+ case 'alt_inline':
+ case 'alt_attach':
+ case 'alt_inline_attach':
+ $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
+ break;
+ default:
+ $this->Body = $this->WrapText($this->Body, $this->WordWrap);
+ break;
+ }
+ }
+
+ /**
+ * Assembles message header.
+ * @access public
+ * @return string The assembled header
+ */
+ public function CreateHeader() {
+ $result = '';
+
+ // Set the boundaries
+ $uniq_id = md5(uniqid(time()));
+ $this->boundary[1] = 'b1_' . $uniq_id;
+ $this->boundary[2] = 'b2_' . $uniq_id;
+ $this->boundary[3] = 'b3_' . $uniq_id;
+
+ if ($this->MessageDate == '') {
+ $result .= $this->HeaderLine('Date', self::RFCDate());
+ } else {
+ $result .= $this->HeaderLine('Date', $this->MessageDate);
+ }
+
+ if ($this->ReturnPath) {
+ $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>');
+ } elseif ($this->Sender == '') {
+ $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>');
+ } else {
+ $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>');
+ }
+
+ // To be created automatically by mail()
+ if($this->Mailer != 'mail') {
+ if ($this->SingleTo === true) {
+ foreach($this->to as $t) {
+ $this->SingleToArray[] = $this->AddrFormat($t);
+ }
+ } else {
+ if(count($this->to) > 0) {
+ $result .= $this->AddrAppend('To', $this->to);
+ } elseif (count($this->cc) == 0) {
+ $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
+ }
+ }
+ }
+
+ $from = array();
+ $from[0][0] = trim($this->From);
+ $from[0][1] = $this->FromName;
+ $result .= $this->AddrAppend('From', $from);
+
+ // sendmail and mail() extract Cc from the header before sending
+ if(count($this->cc) > 0) {
+ $result .= $this->AddrAppend('Cc', $this->cc);
+ }
+
+ // sendmail and mail() extract Bcc from the header before sending
+ if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
+ $result .= $this->AddrAppend('Bcc', $this->bcc);
+ }
+
+ if(count($this->ReplyTo) > 0) {
+ $result .= $this->AddrAppend('Reply-To', $this->ReplyTo);
+ }
+
+ // mail() sets the subject itself
+ if($this->Mailer != 'mail') {
+ $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
+ }
+
+ if($this->MessageID != '') {
+ $result .= $this->HeaderLine('Message-ID', $this->MessageID);
+ } else {
+ $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
+ }
+ $result .= $this->HeaderLine('X-Priority', $this->Priority);
+ if ($this->XMailer == '') {
+ $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)');
+ } else {
+ $myXmailer = trim($this->XMailer);
+ if ($myXmailer) {
+ $result .= $this->HeaderLine('X-Mailer', $myXmailer);
+ }
+ }
+
+ if($this->ConfirmReadingTo != '') {
+ $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
+ }
+
+ // Add custom headers
+ for($index = 0; $index < count($this->CustomHeader); $index++) {
+ $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
+ }
+ if (!$this->sign_key_file) {
+ $result .= $this->HeaderLine('MIME-Version', '1.0');
+ $result .= $this->GetMailMIME();
+ }
+
+ return $result;
+ }
+
+ /**
+ * Returns the message MIME.
+ * @access public
+ * @return string
+ */
+ public function GetMailMIME() {
+ $result = '';
+ switch($this->message_type) {
+ case 'inline':
+ $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
+ $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
+ break;
+ case 'attach':
+ case 'inline_attach':
+ case 'alt_attach':
+ case 'alt_inline_attach':
+ $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
+ $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
+ break;
+ case 'alt':
+ case 'alt_inline':
+ $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
+ $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"');
+ break;
+ default:
+ // Catches case 'plain': and case '':
+ $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet);
+ break;
+ }
+ //RFC1341 part 5 says 7bit is assumed if not specified
+ if ($this->Encoding != '7bit') {
+ $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
+ }
+
+ if($this->Mailer != 'mail') {
+ $result .= $this->LE;
+ }
+
+ return $result;
+ }
+
+ /**
+ * Returns the MIME message (headers and body). Only really valid post PreSend().
+ * @access public
+ * @return string
+ */
+ public function GetSentMIMEMessage() {
+ return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
+ }
+
+
+ /**
+ * Assembles the message body. Returns an empty string on failure.
+ * @access public
+ * @throws phpmailerException
+ * @return string The assembled message body
+ */
+ public function CreateBody() {
+ $body = '';
+
+ if ($this->sign_key_file) {
+ $body .= $this->GetMailMIME().$this->LE;
+ }
+
+ $this->SetWordWrap();
+
+ switch($this->message_type) {
+ case 'inline':
+ $body .= $this->GetBoundary($this->boundary[1], '', '', '');
+ $body .= $this->EncodeString($this->Body, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->AttachAll('inline', $this->boundary[1]);
+ break;
+ case 'attach':
+ $body .= $this->GetBoundary($this->boundary[1], '', '', '');
+ $body .= $this->EncodeString($this->Body, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->AttachAll('attachment', $this->boundary[1]);
+ break;
+ case 'inline_attach':
+ $body .= $this->TextLine('--' . $this->boundary[1]);
+ $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
+ $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
+ $body .= $this->LE;
+ $body .= $this->GetBoundary($this->boundary[2], '', '', '');
+ $body .= $this->EncodeString($this->Body, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->AttachAll('inline', $this->boundary[2]);
+ $body .= $this->LE;
+ $body .= $this->AttachAll('attachment', $this->boundary[1]);
+ break;
+ case 'alt':
+ $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
+ $body .= $this->EncodeString($this->AltBody, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
+ $body .= $this->EncodeString($this->Body, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ if(!empty($this->Ical)) {
+ $body .= $this->GetBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
+ $body .= $this->EncodeString($this->Ical, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ }
+ $body .= $this->EndBoundary($this->boundary[1]);
+ break;
+ case 'alt_inline':
+ $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
+ $body .= $this->EncodeString($this->AltBody, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->TextLine('--' . $this->boundary[1]);
+ $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
+ $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
+ $body .= $this->LE;
+ $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
+ $body .= $this->EncodeString($this->Body, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->AttachAll('inline', $this->boundary[2]);
+ $body .= $this->LE;
+ $body .= $this->EndBoundary($this->boundary[1]);
+ break;
+ case 'alt_attach':
+ $body .= $this->TextLine('--' . $this->boundary[1]);
+ $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
+ $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
+ $body .= $this->LE;
+ $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
+ $body .= $this->EncodeString($this->AltBody, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
+ $body .= $this->EncodeString($this->Body, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->EndBoundary($this->boundary[2]);
+ $body .= $this->LE;
+ $body .= $this->AttachAll('attachment', $this->boundary[1]);
+ break;
+ case 'alt_inline_attach':
+ $body .= $this->TextLine('--' . $this->boundary[1]);
+ $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
+ $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"');
+ $body .= $this->LE;
+ $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
+ $body .= $this->EncodeString($this->AltBody, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->TextLine('--' . $this->boundary[2]);
+ $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
+ $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3].'"');
+ $body .= $this->LE;
+ $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
+ $body .= $this->EncodeString($this->Body, $this->Encoding);
+ $body .= $this->LE.$this->LE;
+ $body .= $this->AttachAll('inline', $this->boundary[3]);
+ $body .= $this->LE;
+ $body .= $this->EndBoundary($this->boundary[2]);
+ $body .= $this->LE;
+ $body .= $this->AttachAll('attachment', $this->boundary[1]);
+ break;
+ default:
+ // catch case 'plain' and case ''
+ $body .= $this->EncodeString($this->Body, $this->Encoding);
+ break;
+ }
+
+ if ($this->IsError()) {
+ $body = '';
+ } elseif ($this->sign_key_file) {
+ try {
+ if (!defined('PKCS7_TEXT')) {
+ throw new phpmailerException($this->Lang('signing').' OpenSSL extension missing.');
+ }
+ $file = tempnam(sys_get_temp_dir(), 'mail');
+ file_put_contents($file, $body); //TODO check this worked
+ $signed = tempnam(sys_get_temp_dir(), 'signed');
+ if (@openssl_pkcs7_sign($file, $signed, 'file://'.realpath($this->sign_cert_file), array('file://'.realpath($this->sign_key_file), $this->sign_key_pass), null)) {
+ @unlink($file);
+ $body = file_get_contents($signed);
+ @unlink($signed);
+ } else {
+ @unlink($file);
+ @unlink($signed);
+ throw new phpmailerException($this->Lang('signing').openssl_error_string());
+ }
+ } catch (phpmailerException $e) {
+ $body = '';
+ if ($this->exceptions) {
+ throw $e;
+ }
+ }
+ }
+ return $body;
+ }
+
+ /**
+ * Returns the start of a message boundary.
+ * @access protected
+ * @param string $boundary
+ * @param string $charSet
+ * @param string $contentType
+ * @param string $encoding
+ * @return string
+ */
+ protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
+ $result = '';
+ if($charSet == '') {
+ $charSet = $this->CharSet;
+ }
+ if($contentType == '') {
+ $contentType = $this->ContentType;
+ }
+ if($encoding == '') {
+ $encoding = $this->Encoding;
+ }
+ $result .= $this->TextLine('--' . $boundary);
+ $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet);
+ $result .= $this->LE;
+ $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
+ $result .= $this->LE;
+
+ return $result;
+ }
+
+ /**
+ * Returns the end of a message boundary.
+ * @access protected
+ * @param string $boundary
+ * @return string
+ */
+ protected function EndBoundary($boundary) {
+ return $this->LE . '--' . $boundary . '--' . $this->LE;
+ }
+
+ /**
+ * Sets the message type.
+ * @access protected
+ * @return void
+ */
+ protected function SetMessageType() {
+ $this->message_type = array();
+ if($this->AlternativeExists()) $this->message_type[] = "alt";
+ if($this->InlineImageExists()) $this->message_type[] = "inline";
+ if($this->AttachmentExists()) $this->message_type[] = "attach";
+ $this->message_type = implode("_", $this->message_type);
+ if($this->message_type == "") $this->message_type = "plain";
+ }
+
+ /**
+ * Returns a formatted header line.
+ * @access public
+ * @param string $name
+ * @param string $value
+ * @return string
+ */
+ public function HeaderLine($name, $value) {
+ return $name . ': ' . $value . $this->LE;
+ }
+
+ /**
+ * Returns a formatted mail line.
+ * @access public
+ * @param string $value
+ * @return string
+ */
+ public function TextLine($value) {
+ return $value . $this->LE;
+ }
+
+ /////////////////////////////////////////////////
+ // CLASS METHODS, ATTACHMENTS
+ /////////////////////////////////////////////////
+
+ /**
+ * Adds an attachment from a path on the filesystem.
+ * Returns false if the file could not be found
+ * or accessed.
+ * @param string $path Path to the attachment.
+ * @param string $name Overrides the attachment name.
+ * @param string $encoding File encoding (see $Encoding).
+ * @param string $type File extension (MIME) type.
+ * @throws phpmailerException
+ * @return bool
+ */
+ public function AddAttachment($path, $name = '', $encoding = 'base64', $type = '') {
+ try {
+ if ( !@is_file($path) ) {
+ throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
+ }
+
+ //If a MIME type is not specified, try to work it out from the file name
+ if ($type == '') {
+ $type = self::filenameToType($path);
+ }
+
+ $filename = basename($path);
+ if ( $name == '' ) {
+ $name = $filename;
+ }
+
+ $this->attachment[] = array(
+ 0 => $path,
+ 1 => $filename,
+ 2 => $name,
+ 3 => $encoding,
+ 4 => $type,
+ 5 => false, // isStringAttachment
+ 6 => 'attachment',
+ 7 => 0
+ );
+
+ } catch (phpmailerException $e) {
+ $this->SetError($e->getMessage());
+ if ($this->exceptions) {
+ throw $e;
+ }
+ if ($this->SMTPDebug) {
+ $this->edebug($e->getMessage()."\n");
+ }
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Return the current array of attachments
+ * @return array
+ */
+ public function GetAttachments() {
+ return $this->attachment;
+ }
+
+ /**
+ * Attaches all fs, string, and binary attachments to the message.
+ * Returns an empty string on failure.
+ * @access protected
+ * @param string $disposition_type
+ * @param string $boundary
+ * @return string
+ */
+ protected function AttachAll($disposition_type, $boundary) {
+ // Return text of body
+ $mime = array();
+ $cidUniq = array();
+ $incl = array();
+
+ // Add all attachments
+ foreach ($this->attachment as $attachment) {
+ // CHECK IF IT IS A VALID DISPOSITION_FILTER
+ if($attachment[6] == $disposition_type) {
+ // Check for string attachment
+ $string = '';
+ $path = '';
+ $bString = $attachment[5];
+ if ($bString) {
+ $string = $attachment[0];
+ } else {
+ $path = $attachment[0];
+ }
+
+ $inclhash = md5(serialize($attachment));
+ if (in_array($inclhash, $incl)) { continue; }
+ $incl[] = $inclhash;
+ $filename = $attachment[1];
+ $name = $attachment[2];
+ $encoding = $attachment[3];
+ $type = $attachment[4];
+ $disposition = $attachment[6];
+ $cid = $attachment[7];
+ if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
+ $cidUniq[$cid] = true;
+
+ $mime[] = sprintf("--%s%s", $boundary, $this->LE);
+ $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
+ $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
+
+ if($disposition == 'inline') {
+ $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
+ }
+
+ //If a filename contains any of these chars, it should be quoted, but not otherwise: RFC2183 & RFC2045 5.1
+ //Fixes a warning in IETF's msglint MIME checker
+ if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) {
+ $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
+ } else {
+ $mime[] = sprintf("Content-Disposition: %s; filename=%s%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
+ }
+
+ // Encode as string attachment
+ if($bString) {
+ $mime[] = $this->EncodeString($string, $encoding);
+ if($this->IsError()) {
+ return '';
+ }
+ $mime[] = $this->LE.$this->LE;
+ } else {
+ $mime[] = $this->EncodeFile($path, $encoding);
+ if($this->IsError()) {
+ return '';
+ }
+ $mime[] = $this->LE.$this->LE;
+ }
+ }
+ }
+
+ $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
+
+ return implode("", $mime);
+ }
+
+ /**
+ * Encodes attachment in requested format.
+ * Returns an empty string on failure.
+ * @param string $path The full path to the file
+ * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
+ * @throws phpmailerException
+ * @see EncodeFile()
+ * @access protected
+ * @return string
+ */
+ protected function EncodeFile($path, $encoding = 'base64') {
+ try {
+ if (!is_readable($path)) {
+ throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
+ }
+ $magic_quotes = get_magic_quotes_runtime();
+ if ($magic_quotes) {
+ if (version_compare(PHP_VERSION, '5.3.0', '<')) {
+ set_magic_quotes_runtime(0);
+ } else {
+ ini_set('magic_quotes_runtime', 0);
+ }
+ }
+ $file_buffer = file_get_contents($path);
+ $file_buffer = $this->EncodeString($file_buffer, $encoding);
+ if ($magic_quotes) {
+ if (version_compare(PHP_VERSION, '5.3.0', '<')) {
+ set_magic_quotes_runtime($magic_quotes);
+ } else {
+ ini_set('magic_quotes_runtime', $magic_quotes);
+ }
+ }
+ return $file_buffer;
+ } catch (Exception $e) {
+ $this->SetError($e->getMessage());
+ return '';
+ }
+ }
+
+ /**
+ * Encodes string to requested format.
+ * Returns an empty string on failure.
+ * @param string $str The text to encode
+ * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
+ * @access public
+ * @return string
+ */
+ public function EncodeString($str, $encoding = 'base64') {
+ $encoded = '';
+ switch(strtolower($encoding)) {
+ case 'base64':
+ $encoded = chunk_split(base64_encode($str), 76, $this->LE);
+ break;
+ case '7bit':
+ case '8bit':
+ $encoded = $this->FixEOL($str);
+ //Make sure it ends with a line break
+ if (substr($encoded, -(strlen($this->LE))) != $this->LE)
+ $encoded .= $this->LE;
+ break;
+ case 'binary':
+ $encoded = $str;
+ break;
+ case 'quoted-printable':
+ $encoded = $this->EncodeQP($str);
+ break;
+ default:
+ $this->SetError($this->Lang('encoding') . $encoding);
+ break;
+ }
+ return $encoded;
+ }
+
+ /**
+ * Encode a header string to best (shortest) of Q, B, quoted or none.
+ * @access public
+ * @param string $str
+ * @param string $position
+ * @return string
+ */
+ public function EncodeHeader($str, $position = 'text') {
+ $x = 0;
+
+ switch (strtolower($position)) {
+ case 'phrase':
+ if (!preg_match('/[\200-\377]/', $str)) {
+ // Can't use addslashes as we don't know what value has magic_quotes_sybase
+ $encoded = addcslashes($str, "\0..\37\177\\\"");
+ if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
+ return ($encoded);
+ } else {
+ return ("\"$encoded\"");
+ }
+ }
+ $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
+ break;
+ case 'comment':
+ $x = preg_match_all('/[()"]/', $str, $matches);
+ // Fall-through
+ case 'text':
+ default:
+ $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
+ break;
+ }
+
+ if ($x == 0) { //There are no chars that need encoding
+ return ($str);
+ }
+
+ $maxlen = 75 - 7 - strlen($this->CharSet);
+ // Try to select the encoding which should produce the shortest output
+ if ($x > strlen($str)/3) { //More than a third of the content will need encoding, so B encoding will be most efficient
+ $encoding = 'B';
+ if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
+ // Use a custom function which correctly encodes and wraps long
+ // multibyte strings without breaking lines within a character
+ $encoded = $this->Base64EncodeWrapMB($str, "\n");
+ } else {
+ $encoded = base64_encode($str);
+ $maxlen -= $maxlen % 4;
+ $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
+ }
+ } else {
+ $encoding = 'Q';
+ $encoded = $this->EncodeQ($str, $position);
+ $encoded = $this->WrapText($encoded, $maxlen, true);
+ $encoded = str_replace('='.self::CRLF, "\n", trim($encoded));
+ }
+
+ $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
+ $encoded = trim(str_replace("\n", $this->LE, $encoded));
+
+ return $encoded;
+ }
+
+ /**
+ * Checks if a string contains multibyte characters.
+ * @access public
+ * @param string $str multi-byte text to wrap encode
+ * @return bool
+ */
+ public function HasMultiBytes($str) {
+ if (function_exists('mb_strlen')) {
+ return (strlen($str) > mb_strlen($str, $this->CharSet));
+ } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
+ return false;
+ }
+ }
+
+ /**
+ * Correctly encodes and wraps long multibyte strings for mail headers
+ * without breaking lines within a character.
+ * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
+ * @access public
+ * @param string $str multi-byte text to wrap encode
+ * @param string $lf string to use as linefeed/end-of-line
+ * @return string
+ */
+ public function Base64EncodeWrapMB($str, $lf=null) {
+ $start = "=?".$this->CharSet."?B?";
+ $end = "?=";
+ $encoded = "";
+ if ($lf === null) {
+ $lf = $this->LE;
+ }
+
+ $mb_length = mb_strlen($str, $this->CharSet);
+ // Each line must have length <= 75, including $start and $end
+ $length = 75 - strlen($start) - strlen($end);
+ // Average multi-byte ratio
+ $ratio = $mb_length / strlen($str);
+ // Base64 has a 4:3 ratio
+ $offset = $avgLength = floor($length * $ratio * .75);
+
+ for ($i = 0; $i < $mb_length; $i += $offset) {
+ $lookBack = 0;
+
+ do {
+ $offset = $avgLength - $lookBack;
+ $chunk = mb_substr($str, $i, $offset, $this->CharSet);
+ $chunk = base64_encode($chunk);
+ $lookBack++;
+ }
+ while (strlen($chunk) > $length);
+
+ $encoded .= $chunk . $lf;
+ }
+
+ // Chomp the last linefeed
+ $encoded = substr($encoded, 0, -strlen($lf));
+ return $encoded;
+ }
+
+ /**
+ * Encode string to RFC2045 (6.7) quoted-printable format
+ * @access public
+ * @param string $string The text to encode
+ * @param integer $line_max Number of chars allowed on a line before wrapping
+ * @return string
+ * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417
+ */
+ public function EncodeQP($string, $line_max = 76) {
+ if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3)
+ return quoted_printable_encode($string);
+ }
+ //Fall back to a pure PHP implementation
+ $string = str_replace(array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string));
+ $string = preg_replace('/[^\r\n]{'.($line_max - 3).'}[^=\r\n]{2}/', "$0=\r\n", $string);
+ return $string;
+ }
+
+ /**
+ * Wrapper to preserve BC for old QP encoding function that was removed
+ * @see EncodeQP()
+ * @access public
+ * @param string $string
+ * @param integer $line_max
+ * @param bool $space_conv
+ * @return string
+ */
+ public function EncodeQPphp($string, $line_max = 76, $space_conv = false) {
+ return $this->EncodeQP($string, $line_max);
+ }
+
+ /**
+ * Encode string to q encoding.
+ * @link http://tools.ietf.org/html/rfc2047
+ * @param string $str the text to encode
+ * @param string $position Where the text is going to be used, see the RFC for what that means
+ * @access public
+ * @return string
+ */
+ public function EncodeQ($str, $position = 'text') {
+ //There should not be any EOL in the string
+ $pattern = '';
+ $encoded = str_replace(array("\r", "\n"), '', $str);
+ switch (strtolower($position)) {
+ case 'phrase':
+ $pattern = '^A-Za-z0-9!*+\/ -';
+ break;
+
+ case 'comment':
+ $pattern = '\(\)"';
+ //note that we don't break here!
+ //for this reason we build the $pattern without including delimiters and []
+
+ case 'text':
+ default:
+ //Replace every high ascii, control =, ? and _ characters
+ //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode
+ $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern;
+ break;
+ }
+
+ if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
+ foreach (array_unique($matches[0]) as $char) {
+ $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
+ }
+ }
+
+ //Replace every spaces to _ (more readable than =20)
+ return str_replace(' ', '_', $encoded);
+}
+
+
+ /**
+ * Adds a string or binary attachment (non-filesystem) to the list.
+ * This method can be used to attach ascii or binary data,
+ * such as a BLOB record from a database.
+ * @param string $string String attachment data.
+ * @param string $filename Name of the attachment.
+ * @param string $encoding File encoding (see $Encoding).
+ * @param string $type File extension (MIME) type.
+ * @return void
+ */
+ public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = '') {
+ //If a MIME type is not specified, try to work it out from the file name
+ if ($type == '') {
+ $type = self::filenameToType($filename);
+ }
+ // Append to $attachment array
+ $this->attachment[] = array(
+ 0 => $string,
+ 1 => $filename,
+ 2 => basename($filename),
+ 3 => $encoding,
+ 4 => $type,
+ 5 => true, // isStringAttachment
+ 6 => 'attachment',
+ 7 => 0
+ );
+ }
+
+ /**
+ * Add an embedded attachment from a file.
+ * This can include images, sounds, and just about any other document type.
+ * @param string $path Path to the attachment.
+ * @param string $cid Content ID of the attachment; Use this to reference
+ * the content when using an embedded image in HTML.
+ * @param string $name Overrides the attachment name.
+ * @param string $encoding File encoding (see $Encoding).
+ * @param string $type File MIME type.
+ * @return bool True on successfully adding an attachment
+ */
+ public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '') {
+ if ( !@is_file($path) ) {
+ $this->SetError($this->Lang('file_access') . $path);
+ return false;
+ }
+
+ //If a MIME type is not specified, try to work it out from the file name
+ if ($type == '') {
+ $type = self::filenameToType($path);
+ }
+
+ $filename = basename($path);
+ if ( $name == '' ) {
+ $name = $filename;
+ }
+
+ // Append to $attachment array
+ $this->attachment[] = array(
+ 0 => $path,
+ 1 => $filename,
+ 2 => $name,
+ 3 => $encoding,
+ 4 => $type,
+ 5 => false, // isStringAttachment
+ 6 => 'inline',
+ 7 => $cid
+ );
+ return true;
+ }
+
+
+ /**
+ * Add an embedded stringified attachment.
+ * This can include images, sounds, and just about any other document type.
+ * Be sure to set the $type to an image type for images:
+ * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
+ * @param string $string The attachment binary data.
+ * @param string $cid Content ID of the attachment; Use this to reference
+ * the content when using an embedded image in HTML.
+ * @param string $name
+ * @param string $encoding File encoding (see $Encoding).
+ * @param string $type MIME type.
+ * @return bool True on successfully adding an attachment
+ */
+ public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = '') {
+ //If a MIME type is not specified, try to work it out from the name
+ if ($type == '') {
+ $type = self::filenameToType($name);
+ }
+
+ // Append to $attachment array
+ $this->attachment[] = array(
+ 0 => $string,
+ 1 => $name,
+ 2 => $name,
+ 3 => $encoding,
+ 4 => $type,
+ 5 => true, // isStringAttachment
+ 6 => 'inline',
+ 7 => $cid
+ );
+ return true;
+ }
+
+ /**
+ * Returns true if an inline attachment is present.
+ * @access public
+ * @return bool
+ */
+ public function InlineImageExists() {
+ foreach($this->attachment as $attachment) {
+ if ($attachment[6] == 'inline') {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Returns true if an attachment (non-inline) is present.
+ * @return bool
+ */
+ public function AttachmentExists() {
+ foreach($this->attachment as $attachment) {
+ if ($attachment[6] == 'attachment') {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Does this message have an alternative body set?
+ * @return bool
+ */
+ public function AlternativeExists() {
+ return !empty($this->AltBody);
+ }
+
+ /////////////////////////////////////////////////
+ // CLASS METHODS, MESSAGE RESET
+ /////////////////////////////////////////////////
+
+ /**
+ * Clears all recipients assigned in the TO array. Returns void.
+ * @return void
+ */
+ public function ClearAddresses() {
+ foreach($this->to as $to) {
+ unset($this->all_recipients[strtolower($to[0])]);
+ }
+ $this->to = array();
+ }
+
+ /**
+ * Clears all recipients assigned in the CC array. Returns void.
+ * @return void
+ */
+ public function ClearCCs() {
+ foreach($this->cc as $cc) {
+ unset($this->all_recipients[strtolower($cc[0])]);
+ }
+ $this->cc = array();
+ }
+
+ /**
+ * Clears all recipients assigned in the BCC array. Returns void.
+ * @return void
+ */
+ public function ClearBCCs() {
+ foreach($this->bcc as $bcc) {
+ unset($this->all_recipients[strtolower($bcc[0])]);
+ }
+ $this->bcc = array();
+ }
+
+ /**
+ * Clears all recipients assigned in the ReplyTo array. Returns void.
+ * @return void
+ */
+ public function ClearReplyTos() {
+ $this->ReplyTo = array();
+ }
+
+ /**
+ * Clears all recipients assigned in the TO, CC and BCC
+ * array. Returns void.
+ * @return void
+ */
+ public function ClearAllRecipients() {
+ $this->to = array();
+ $this->cc = array();
+ $this->bcc = array();
+ $this->all_recipients = array();
+ }
+
+ /**
+ * Clears all previously set filesystem, string, and binary
+ * attachments. Returns void.
+ * @return void
+ */
+ public function ClearAttachments() {
+ $this->attachment = array();
+ }
+
+ /**
+ * Clears all custom headers. Returns void.
+ * @return void
+ */
+ public function ClearCustomHeaders() {
+ $this->CustomHeader = array();
+ }
+
+ /////////////////////////////////////////////////
+ // CLASS METHODS, MISCELLANEOUS
+ /////////////////////////////////////////////////
+
+ /**
+ * Adds the error message to the error container.
+ * @access protected
+ * @param string $msg
+ * @return void
+ */
+ protected function SetError($msg) {
+ $this->error_count++;
+ if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
+ $lasterror = $this->smtp->getError();
+ if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) {
+ $msg .= '