Example #1
0
 protected function convert_currency($amount, $from, $to)
 {
     if (defined('STRICT_TYPES') && CAMEL_CASE == '1') {
         return self::parameters(['amount' => [DT::INT64, DT::FLOAT], 'from' => DT::STRING, 'to' => DT::STRING])->call(__FUNCTION__)->with($amount, $from, $to)->returning([DT::STRING, DT::BOOL]);
     } else {
         return convert_currency($amount, $from, $to);
     }
 }
Example #2
0
 function proceed_old($data)
 {
     // Default account currency id: 16; RUB
     $main_currency_id = 16;
     $lead = '';
     $sale = '';
     if (isset($data['s'])) {
         $arr_currencies = get_active_currencies();
         $conversion_currency_code = strtoupper($data['c']);
         if ($conversion_currency_code == 'RUB') {
             $conversion_currency_code = 'RUR';
         }
         $conversion_currency_id = 0;
         foreach ($arr_currencies as $id => $cur) {
             if ($cur['code'] == $conversion_currency_code) {
                 $conversion_currency_id = $id;
             }
         }
         // Currency is not found in active, use default currency
         if ($conversion_currency_id == 0) {
             $conversion_currency_id = $main_currency_id;
         }
         if ($conversion_currency_id == $main_currency_id) {
             $conversion_profit = $data['a'];
         } else {
             $conversion_profit = convert_currency($data['a'], $conversion_currency_id, $main_currency_id, date('Y-m-d'));
         }
         $conversion_profit_currency = $data['a'];
         $r = mysql_query('SELECT `id` FROM `tbl_clicks` WHERE `subid` = "' . mysql_real_escape_string($data['s']) . '"');
         if (mysql_num_rows($r) > 0) {
             $f = mysql_fetch_assoc($r);
             switch ($data['t']) {
                 case 'lead':
                     $lead = ',`is_lead` = 1';
                     break;
                 case 'sale':
                     $sale = ', `is_sale` = 1';
                     break;
             }
             if (($sale != '' || $lead != '') && isset($data['a'])) {
                 mysql_query("UPDATE `tbl_clicks` SET\n                                    `conversion_currency_sum`='" . mysql_real_escape_string($conversion_profit_currency) . "',\n                                    `conversion_currency_id`='" . mysql_real_escape_string($conversion_currency_id) . "',\n                                    `conversion_price_main` = '" . mysql_real_escape_string($conversion_profit) . "' " . $lead . $sale . '
                               WHERE
                                 `id` = ' . $f['id']);
             }
         }
         $r = mysql_query('SELECT `id` FROM `tbl_conversions` WHERE `subid` = "' . mysql_real_escape_string($data['s']) . '"');
         if (mysql_num_rows($r) > 0) {
             $f = mysql_fetch_assoc($r);
             if (isset($data['a'])) {
                 mysql_query("UPDATE `tbl_conversions` SET\n                                    `currency_id`='" . mysql_real_escape_string($conversion_currency_id) . "',\n                                    `profit_currency`='" . mysql_real_escape_string($conversion_profit_currency) . "',\n                                    `profit` = '" . mysql_real_escape_string($conversion_profit) . "'\n                                  WHERE\n                                    `id` = '" . mysql_real_escape_string($f['id']) . "'");
             }
         } else {
             mysql_query("INSERT INTO `tbl_conversions` (`network`, `currency_id`, `profit_currency`, `profit`, `subid`, `status`, `t20`, `date_add`) " . "VALUES\n                        (\n                            '" . mysql_real_escape_string($data['n']) . "',\n                            '" . mysql_real_escape_string($conversion_currency_id) . "',\n                            '" . mysql_real_escape_string($conversion_profit_currency) . "',\n                            '" . mysql_real_escape_string($conversion_profit) . "',\n                            '" . mysql_real_escape_string($data['s']) . "',\n                            1,\n                            '" . mysql_real_escape_string($data['c']) . "', NOW()\n                        )");
         }
     }
 }
Example #3
0
 /**
  * Shortcode callback function to convert value in one currency into another
  *
  * @uses convert_currency()
  *
  * @since 1.4.0
  *
  * @param  array $atts Shortcode attributes.
  * @return string The resulting converted amount
  */
 public function currency_conversion_shortcode($atts)
 {
     $args = shortcode_atts(array('amount' => '', 'from' => '', 'in' => '', 'round' => 2), $atts);
     // convert currency
     $conversion = convert_currency(floatval($args['amount']), strtoupper($args['from']), strtoupper($args['in']));
     // round result
     $rounding = intval($args['round']) >= 0 ? intval($args['round']) : 2;
     $converted_amount = round($conversion, $rounding);
     return '<span class="currency converted-currency">' . $converted_amount . '</span>';
 }
function get_sales_flow_data($request_parameters, $report_name, $limit = 20, $offset = 0)
{
    // Default currency for this account: RUB (16)
    $main_currency_id = 16;
    // Fill currency list
    global $arr_currencies_list;
    if (!(is_array($arr_currencies_list) && count($arr_currencies_list) > 0)) {
        $arr_currencies_list = get_active_currencies();
    }
    $allowed_report_in_params = array('report_type' => 'actions_count', 'range_type' => 'daily', 'main_column' => 'source_name', 'filter_actions' => 'actions', 'filter_by' => '', 'filter_value' => '', 'currency_id' => '16', 'timezone_offset' => get_current_timezone_shift(), 'date_start' => get_current_day('-7 days'), 'date_end' => get_current_day(), 'report_period' => 'lastweek');
    //  Remove empty values and get only allowed keys
    $IN = array_replace($allowed_report_in_params, array_intersect_key(array_filter($request_parameters), $allowed_report_in_params));
    // Add default report params
    $IN['report_params'] = isset($request_parameters['report_params']) ? $request_parameters['report_params'] : null;
    // Fill report range
    report_period_to_dates($IN);
    $sql_select = array();
    $sql_join = array();
    $sql_where = array();
    $sql_order = array();
    $sql_limit = 'LIMIT ' . _str($limit + 1) . ' OFFSET ' . _str($offset);
    // Apply timezone offset
    $date_add_tz = "CONVERT_TZ(tbl_conversions.date_add, '+00:00', '" . _str($IN['timezone_offset']) . "') as click_date";
    if (in_array($IN['timezone_offset'], array('+00:00', '-00:00', '00:00'))) {
        $date_add_tz = 'tbl_conversions.date_add as click_date';
    }
    $sql_select[] = $date_add_tz;
    if (in_array($IN['timezone_offset'], array('+00:00', '-00:00', '00:00'))) {
        // Same timezones in DB and report
        $sql_date_start = "'" . _str($IN['date_start']) . " 00:00:00'";
        $sql_date_end = "'" . _str($IN['date_end']) . " 23:59:59'";
    } else {
        $timezone_offset_inverted = timezone_shift_invert($IN['timezone_offset']);
        $sql_date_start = "CONVERT_TZ('" . _str($IN['date_start']) . " 00:00:00', '+00:00', '" . _str($timezone_offset_inverted) . "')";
        $sql_date_end = "CONVERT_TZ('" . _str($IN['date_end']) . " 23:59:59', '+00:00', '" . _str($timezone_offset_inverted) . "')";
    }
    if ($IN['filter_by'] == 'subid' && $IN['filter_value'] != '') {
        // Looking for sale, no need to limit search by date range
        $sql_where[] = "tbl_conversions.subid='" . _str($IN['filter_value']) . "'";
    } else {
        $sql_where[] = "tbl_conversions.date_add BETWEEN {$sql_date_start} AND {$sql_date_end}";
    }
    $sql_select[] = 'tbl_conversions.*';
    $sql_order[] = 'date_add desc';
    // 1. Get sales list
    $sql = 'SELECT ' . implode(', ', $sql_select) . '
          FROM
              tbl_conversions
              ' . implode(' ', $sql_join) . '
          WHERE
              ' . implode(' AND ', $sql_where) . '
          ORDER BY ' . implode(', ', $sql_order) . "\n          {$sql_limit}";
    $result = mysql_query($sql);
    $arr_sales = array();
    while ($row = mysql_fetch_assoc($result)) {
        $arr_sales["'" . _str($row['subid']) . "'"] = $row;
    }
    // 2. Get clicks for sales
    $arr_sales_clicks = array();
    $arr_sales_subids = array_keys($arr_sales);
    $subids = implode(',', $arr_sales_subids);
    $sql = "select\n        tbl_clicks.*,\n        tbl_offers.offer_name\n        FROM\n          tbl_clicks\n        left join\n          tbl_offers on tbl_clicks.out_id=tbl_offers.id\n      where\n        subid in ({$subids})";
    $result = mysql_query($sql);
    $arr_parent_ids = array();
    while ($row = mysql_fetch_assoc($result)) {
        if ($row['parent_id'] > 0) {
            $arr_parent_ids[] = "'" . _str($row['parent_id']) . "'";
        }
        $arr_sales_clicks["'" . _str($row['subid']) . "'"] = $row;
    }
    $parent_ids = implode(',', $arr_parent_ids);
    $sql = "select tbl_clicks.* from tbl_clicks where id in ({$parent_ids})";
    $result = mysql_query($sql);
    $arr_parent_clicks = array();
    while ($row = mysql_fetch_assoc($result)) {
        $arr_parent_clicks[$row['id']] = $row;
    }
    $arr_report_data = array();
    function net_loader($class)
    {
        include_once _TRACK_LIB_PATH . '/postback/' . $class . '.php';
    }
    spl_autoload_register('net_loader');
    include _TRACK_LIB_PATH . "/class/common.php";
    include _TRACK_LIB_PATH . "/class/custom.php";
    $arr_default_network_params = array('date_add', 'profit', 'status', 'subid', 'txt_status', 'type');
    $i = 0;
    $more = 0;
    foreach ($arr_sales as $subid => $row) {
        if ($i == $limit) {
            $more = 1;
            break;
        }
        $arr_report_data[$i]['short_date'] = mysqldate2short($row['click_date']);
        $arr_report_data[$i]['offer_name'] = $arr_sales_clicks[$subid]['offer_name'];
        // Network name
        $class_name = $row['network'];
        if (class_exists($class_name, true)) {
            $t = new $class_name();
            if (method_exists($t, 'get_params_info')) {
                $arr_class_params = $t->get_params_info();
                $arr_report_data[$i]['network_params'] = array();
                foreach ($row as $key => $val) {
                    if (isset($arr_class_params[$key]) && !in_array($key, $arr_default_network_params)) {
                        if (trim($val) != '') {
                            $arr_report_data[$i]['network_params']['values'][] = array('caption' => $arr_class_params[$key]['caption'], 'value' => $val);
                        }
                    }
                }
            }
        }
        $arr_report_data[$i]['network_name'] = $row['network'];
        $arr_report_data[$i]['source_name'] = $arr_sales_clicks[$subid]['source_name'] == '' ? '' : format_cell_value('source_name', $arr_sales_clicks[$subid]['source_name']);
        // Campaign name
        $arr_report_data[$i]['campaign_name'] = implode(' — ', array_filter(array($arr_sales_clicks[$subid]['campaign_name'], $arr_sales_clicks[$subid]['ads_name'])));
        $arr_report_data[$i]['placement'] = format_cell_value('referer_domain', $arr_sales_clicks[$subid]['referer_domain']);
        $arr_report_data[$i]['subid'] = $row['subid'];
        if ($row['currency_id'] == $IN['currency_id']) {
            $arr_report_data[$i]['profit'] = format_cell_value('profit', $row['profit_currency'], $IN);
        } else {
            $arr_report_data[$i]['profit'] = format_cell_value('profit', convert_currency($row['profit'], $main_currency_id, $IN['currency_id'], date('Y-m-d')), $IN);
        }
        // $arr_report_data[$i]['status']=$row['txt_status'];
        switch ($row['txt_status']) {
            case 'approved':
                $arr_report_data[$i]['status-icon'] = "fa fa-check";
                $arr_report_data[$i]['status-title'] = "Подтвержден";
                break;
            case 'waiting':
                $arr_report_data[$i]['status-icon'] = "fa fa-hourglass-o";
                $arr_report_data[$i]['status-title'] = "В обработке";
                break;
            case 'rejected':
                $arr_report_data[$i]['status-icon'] = "fa fa-close";
                $arr_report_data[$i]['status-title'] = "Отклонен";
                break;
            default:
                $arr_report_data[$i]['status'] = mb_strtolower($row['txt_status'], 'UTF-8');
                break;
        }
        if (isset($arr_parent_clicks[$arr_sales_clicks[$subid]['parent_id']])) {
            // Fill sale parameters from parent click
            $arr_report_data[$i]['source_name'] = $arr_parent_clicks[$arr_sales_clicks[$subid]['parent_id']]['source_name'];
        }
        // FILL CLICK INFO
        if (isset($arr_parent_clicks[$subid])) {
            $click_info = $arr_parent_clicks[$subid];
        } else {
            $click_info = $arr_sales_clicks[$subid];
        }
        // Conversion ID
        $arr_report_data[$i]['conversion_id'] = $row['id'];
        // Date
        $arr_report_data[$i]['date'] = mysqldate2string($row['click_date']);
        // Location
        $arr_report_data[$i]['country'] = format_cell_value('country', $click_info['country']);
        $arr_report_data[$i]['location'] = implode(', ', array_filter(array($arr_report_data[$i]['country'], $click_info['state'], $click_info['city'])));
        // ISP
        $arr_report_data[$i]['isp'] = $click_info['isp'];
        // IP
        $arr_report_data[$i]['ip'] = $click_info['user_ip'];
        // Subaccount
        $arr_report_data[$i]['subaccount'] = $click_info['subaccount'];
        // SubID
        $arr_report_data[$i]['subid'] = $click_info['subid'];
        // OS
        $arr_report_data[$i]['os'] = implode(' ', array_filter(array($click_info['user_os'], $click_info['user_os_version'])));
        // Device
        $arr_report_data[$i]['device'] = implode(' ', array_filter(array($click_info['user_platform'], $click_info['user_platform_info'], $click_info['user_platform_info_extra'])));
        // Device type
        if ($click_info['is_phone'] == 1) {
            $arr_report_data[$i]['tablet_icon'] = 'phone';
        } elseif ($click_info['is_tablet'] == 1) {
            $arr_report_data[$i]['tablet_icon'] = 'tablet';
        } else {
            $arr_report_data[$i]['tablet_icon'] = '';
        }
        // User-agent
        $arr_report_data[$i]['user_agent'] = $click_info['user_agent'];
        // Browser
        $arr_report_data[$i]['browser'] = implode(' ', array_filter(array($click_info['user_browser'], $click_info['user_browser_version'])));
        // Referer
        $referer_host = parse_url($click_info['referer'], PHP_URL_HOST);
        $referer = str_replace($referer_host, idn_to_utf8($referer_host), $click_info['referer']);
        $arr_report_data[$i]['full_referer'] = urldecode(str_replace(array('http://www.', 'www.'), '', $referer));
        // Keyword
        $arr_report_data[$i]['keyword'] = $click_info['search_string'];
        // Link params	campaign_param1, campaign_param2, campaign_param3, campaign_param4, campaign_param5
        $campaign_params = params_list($click_info, 'campaign_param');
        if (!empty($campaign_params)) {
            $arr_report_data[$i]['link_params'] = join('; ', $campaign_params);
        }
        // Visit params	click_param_name1, click_param_value1, …, click_param_name15, click_param_value15
        $click_params = params_list($click_info, 'click_param_value', $click_info['source_name']);
        if (!empty($click_params)) {
            $arr_report_data[$i]['click_params'] = join('; ', $click_params);
        }
        $i++;
    }
    return array($more, $arr_report_data, $offset);
}
Example #5
0
$html['banner'] = $project['banner'];
$html['title'] = $project['name'];

$result = $db->query("SELECT * FROM `apartment` WHERE `project`=".$db->sql($_GET['id'])." ORDER BY `bedrooms` DESC,`bathrooms` DESC,`area_max` DESC,`area_min` DESC");
$i = 0;
while ($apartment = $db->fetch_array($result)) {
	if ($apartment['plan'] == '') {
		$apartment['plan'] = $config['default_floorplan'];
	}
	
	$apartment['bedrooms'] = convert_rooms($apartment['bedrooms']);
	$apartment['bathrooms'] = convert_rooms($apartment['bathrooms']);
	$apartment['area_min'] = convert_area($apartment['area_min']);
	$apartment['area_max'] = convert_area($apartment['area_max']);
	$apartment['price_min'] = convert_currency($apartment['price_min']);
	$apartment['price_max'] = convert_currency($apartment['price_max']);
	
	$compiled_phrase['area'] = phrase($phrase['areas_de_x_hasta_y'], $apartment['area_min'].$area, $apartment['area_max'].$area);
	
	$compiled_phrase['price'] = phrase(
										($project['vende'] ? $phrase['ofertas_desde_x_hasta_y'] : $apartment['ofertas_desde_x_hasta_y']), 
										$symbol.$apartment['price_min'].' '.$currency, 
										$symbol.$apartment['price_max'].' '.$currency);
						
	if ($apartment['y'] > $config['size_mediabox']) {
		$multiplier = $config['size_mediabox']/$apartment['y'];
		$apartment['x'] *= $multiplier;
		$apartment['y'] = $config['size_mediabox'];
	}
					
	$html['javascript_inline_apartments'] .= '{src:"'.$config['url'].$config['dir_floorplan'].$apartment['plan'].'",caption:"",type:"jpg",width:"'.$apartment['x'].'",height:"'.$apartment['y'].'"},'."\n";
Example #6
0
function EmailInvoice($id, $invoice_type = 1)
{
    //getpost_ifset(array('customer', 'posted', 'Period', 'cardid','exporttype','choose_billperiod','id','invoice_type'));
    if ($invoice_type == "") {
        $invoice_type = 1;
    }
    if ($invoice_type == 1) {
        $cardid = $id;
        if ($cardid == "") {
            exit("Invalid ID");
        }
    }
    if ($invoice_type == 2) {
        if ($id == "" || !is_numeric($id)) {
            exit(gettext("Invalid ID"));
        }
    }
    if ($invoice_type == 1) {
        $invoice_heading = gettext("Unbilled Details");
        $invocie_top_heading = gettext("Unbilled Invoice Details for Card Number");
    } else {
        $invoice_heading = gettext("Billed Details");
        $invocie_top_heading = gettext("Billed Invoice Details for Card Number");
    }
    $DBHandle = DbConnect();
    $num = 0;
    if ($invoice_type == 1) {
        $QUERY = "Select username, vat, t1.id from cc_card t1 where t1.id = {$cardid}";
    } else {
        $QUERY = "Select username, vat, t1.id from cc_card t1, cc_invoices t2 where t1.id = t2.cardid and t2.id = {$id}";
    }
    $res_user = $DBHandle->Execute($QUERY);
    if ($res_user) {
        $num = $res_user->RecordCount();
    }
    if ($num > 0) {
        $userRecord = $res_user->fetchRow();
        $customer = $userRecord[0];
        $vat = $userRecord[1];
        $customerID = $userRecord[2];
    } else {
        exit(gettext("No User found"));
    }
    if (!isset($current_page) || $current_page == "") {
        $current_page = 0;
    }
    // this variable specifie the debug type (0 => nothing, 1 => sql result, 2 => boucle checking, 3 other value checking)
    $FG_DEBUG = 0;
    // The variable FG_TABLE_NAME define the table name to use
    $FG_TABLE_NAME = "cc_call t1";
    // The variable Var_col would define the col that we want show in your table
    // First Name of the column in the html page, second name of the field
    $FG_TABLE_COL = array();
    $FG_TABLE_COL[] = array(gettext("Calldate"), "starttime", "18%", "center", "SORT", "19", "", "", "", "", "", "display_dateformat");
    $FG_TABLE_COL[] = array(gettext("Source"), "src", "10%", "center", "SORT", "30");
    $FG_TABLE_COL[] = array(gettext("Callednumber"), "calledstation", "18%", "right", "SORT", "30", "", "", "", "", "", "");
    $FG_TABLE_COL[] = array(gettext("Destination"), "destination", "18%", "center", "SORT", "30", "", "", "", "", "", "remove_prefix");
    $FG_TABLE_COL[] = array(gettext("Duration"), "sessiontime", "8%", "center", "SORT", "30", "", "", "", "", "", "display_minute");
    if (!(isset($customer) && $customer > 0) && !(isset($entercustomer) && $entercustomer > 0)) {
        $FG_TABLE_COL[] = array(gettext("Cardused"), "username", "11%", "center", "SORT", "30");
    }
    $FG_TABLE_COL[] = array(gettext("Cost"), "sessionbill", "9%", "center", "SORT", "30", "", "", "", "", "", "display_2bill");
    $FG_TABLE_DEFAULT_ORDER = "t1.starttime";
    $FG_TABLE_DEFAULT_SENS = "DESC";
    // This Variable store the argument for the SQL query
    $FG_COL_QUERY = 't1.starttime, t1.src, t1.calledstation, t1.destination, t1.sessiontime  ';
    if (!(isset($customer) && $customer > 0) && !(isset($entercustomer) && $entercustomer > 0)) {
        $FG_COL_QUERY .= ', t1.username';
    }
    $FG_COL_QUERY .= ', t1.sessionbill';
    if (LINK_AUDIO_FILE == 'YES') {
        $FG_COL_QUERY .= ', t1.uniqueid';
    }
    $FG_COL_QUERY_GRAPH = 't1.callstart, t1.duration';
    // The variable LIMITE_DISPLAY define the limit of record to display by page
    $FG_LIMITE_DISPLAY = 500;
    // Number of column in the html table
    $FG_NB_TABLE_COL = count($FG_TABLE_COL);
    //This variable will store the total number of column
    $FG_TOTAL_TABLE_COL = $FG_NB_TABLE_COL;
    if ($FG_DELETION || $FG_EDITION) {
        $FG_TOTAL_TABLE_COL++;
    }
    if ($FG_DEBUG == 3) {
        echo "<br>Table : {$FG_TABLE_NAME}  \t- \tCol_query : {$FG_COL_QUERY}";
    }
    $instance_table = new Table($FG_TABLE_NAME, $FG_COL_QUERY);
    $instance_table_graph = new Table($FG_TABLE_NAME, $FG_COL_QUERY_GRAPH);
    if (is_null($order) || is_null($sens)) {
        $order = $FG_TABLE_DEFAULT_ORDER;
        $sens = $FG_TABLE_DEFAULT_SENS;
    }
    if ($posted == 1) {
        $SQLcmd = '';
        $SQLcmd = do_field($SQLcmd, 'src', 'src');
        $SQLcmd = do_field($SQLcmd, 'dst', 'calledstation');
    }
    $date_clause = '';
    // Period (Month-Day)
    if (DB_TYPE == "postgres") {
        $UNIX_TIMESTAMP = "";
    } else {
        $UNIX_TIMESTAMP = "UNIX_TIMESTAMP";
    }
    $lastdayofmonth = date("t", strtotime($tostatsmonth . '-01'));
    if ($Period == "Month") {
        if ($frommonth && isset($fromstatsmonth)) {
            $date_clause .= " AND {$UNIX_TIMESTAMP}(t1.starttime) >= {$UNIX_TIMESTAMP}('{$fromstatsmonth}-01')";
        }
        if ($tomonth && isset($tostatsmonth)) {
            $date_clause .= " AND {$UNIX_TIMESTAMP}(t1.starttime) <= {$UNIX_TIMESTAMP}('" . $tostatsmonth . "-{$lastdayofmonth} 23:59:59')";
        }
    } else {
        if ($fromday && isset($fromstatsday_sday) && isset($fromstatsmonth_sday) && isset($fromstatsmonth_shour) && isset($fromstatsmonth_smin)) {
            $date_clause .= " AND {$UNIX_TIMESTAMP}(t1.starttime) >= {$UNIX_TIMESTAMP}('{$fromstatsmonth_sday}-{$fromstatsday_sday} {$fromstatsmonth_shour}:{$fromstatsmonth_smin}')";
        }
        if ($today && isset($tostatsday_sday) && isset($tostatsmonth_sday) && isset($tostatsmonth_shour) && isset($tostatsmonth_smin)) {
            $date_clause .= " AND {$UNIX_TIMESTAMP}(t1.starttime) <= {$UNIX_TIMESTAMP}('{$tostatsmonth_sday}-" . sprintf("%02d", intval($tostatsday_sday)) . " {$tostatsmonth_shour}:{$tostatsmonth_smin}')";
        }
    }
    if (strpos($SQLcmd, 'WHERE') > 0) {
        $FG_TABLE_CLAUSE = substr($SQLcmd, 6) . $date_clause;
    } elseif (strpos($date_clause, 'AND') > 0) {
        $FG_TABLE_CLAUSE = substr($date_clause, 5);
    }
    if (isset($customer) && $customer > 0) {
        if (strlen($FG_TABLE_CLAUSE) > 0) {
            $FG_TABLE_CLAUSE .= " AND ";
        }
        $FG_TABLE_CLAUSE .= "t1.username='******'";
    } else {
        if (isset($entercustomer) && $entercustomer > 0) {
            if (strlen($FG_TABLE_CLAUSE) > 0) {
                $FG_TABLE_CLAUSE .= " AND ";
            }
            $FG_TABLE_CLAUSE .= "t1.username='******'";
        }
    }
    if (strlen($FG_TABLE_CLAUSE) > 0) {
        $FG_TABLE_CLAUSE .= " AND ";
    }
    if ($invoice_type == 1) {
        $FG_TABLE_CLAUSE .= "t1.starttime >(Select CASE  WHEN max(cover_enddate) IS NULL THEN '0001-01-01 01:00:00' ELSE max(cover_enddate) END from cc_invoices WHERE cardid = '{$cardid}')";
    } else {
        $FG_TABLE_CLAUSE .= "t1.starttime >(Select cover_startdate  from cc_invoices where id ='{$id}') AND t1.stoptime <(Select cover_enddate from cc_invoices where id ='{$id}') ";
    }
    if (!$nodisplay) {
        $list = $instance_table->Get_list($DBHandle, $FG_TABLE_CLAUSE, $order, $sens, null, null, $FG_LIMITE_DISPLAY, $current_page * $FG_LIMITE_DISPLAY);
    }
    $_SESSION["pr_sql_export"] = "SELECT {$FG_COL_QUERY} FROM {$FG_TABLE_NAME} WHERE {$FG_TABLE_CLAUSE}";
    /************************/
    $QUERY = "SELECT substring(t1.starttime,1,10) AS day, sum(t1.sessiontime) AS calltime, sum(t1.sessionbill) AS cost, count(*) as nbcall FROM {$FG_TABLE_NAME} WHERE " . $FG_TABLE_CLAUSE . "  GROUP BY substring(t1.starttime,1,10) ORDER BY day";
    //extract(DAY from calldate)
    if (!$nodisplay) {
        $list_total_day = $instance_table->SQLExec($DBHandle, $QUERY);
        $nb_record = $instance_table->Table_count($DBHandle, $FG_TABLE_CLAUSE);
    }
    // GROUP BY DESTINATION FOR THE INVOICE
    $QUERY = "SELECT destination, sum(t1.sessiontime) AS calltime, \n\tsum(t1.sessionbill) AS cost, count(*) as nbcall FROM {$FG_TABLE_NAME} WHERE " . $FG_TABLE_CLAUSE . "  GROUP BY destination";
    if (!$nodisplay) {
        $list_total_destination = $instance_table->SQLExec($DBHandle, $QUERY);
    }
    //end IF nodisplay
    /************************************************ DID Billing Section *********************************************/
    // Fixed + Dial = 0 ; Fixed = 1 ; Dail = 2 ; Free = 3
    // 1. Billing Type:: All DID Calls that have DID Type 0 and 2
    if ($invoice_type == 1) {
        $QUERY = "SELECT t1.amount, t1.creationdate, t1.description, t3.countryname, t2.did, t1.currency " . " FROM cc_charge t1 LEFT JOIN (cc_did t2, cc_country t3 ) ON ( t1.id_cc_did = t2.id AND t2.id_cc_country = t3.id ) " . " WHERE (t1.chargetype = 1 OR t1.chargetype = 2) AND t1.id_cc_card = " . $cardid . " AND t1.creationdate >(Select CASE  WHEN max(cover_enddate) IS NULL THEN '0001-01-01 01:00:00' ELSE max(cover_enddate) END from cc_invoices)";
    } else {
        $QUERY = "SELECT t1.amount, t1.creationdate, t1.description, t3.countryname, t2.did, t1.currency " . " FROM cc_charge t1 LEFT JOIN (cc_did t2, cc_country t3 ) ON ( t1.id_cc_did = t2.id AND t2.id_cc_country = t3.id ) " . " WHERE (t1.chargetype = 2 OR t1.chargetype = 1) AND t1.id_cc_card = " . $customerID . " AND t1.creationdate > (Select cover_startdate  from cc_invoices where id ='{$id}') AND t1.creationdate <(Select cover_enddate from cc_invoices where id ='{$id}')";
    }
    if (!$nodisplay) {
        $list_total_did = $instance_table->SQLExec($DBHandle, $QUERY);
    }
    /*************************************************CHARGES SECTION START ************************************************/
    // Charge Types
    // Connection charge for DID setup = 1
    // Monthly Charge for DID use = 2
    // Subscription fee = 3
    // Extra charge =  4
    if ($invoice_type == 1) {
        $QUERY = "SELECT t1.id_cc_card, t1.iduser, t1.creationdate, t1.amount, t1.chargetype, t1.id_cc_did, t1.currency, t1.description" . " FROM cc_charge t1, cc_card t2 WHERE (t1.chargetype <> 1 AND t1.chargetype <> 2) " . " AND t2.username = '******' AND t1.id_cc_card = t2.id AND t1.creationdate >= (Select CASE WHEN max(cover_enddate) is NULL " . " THEN '0001-01-01 01:00:00' ELSE max(cover_enddate) END from cc_invoices) Order by t1.creationdate";
    } else {
        $QUERY = "SELECT t1.id_cc_card, t1.iduser, t1.creationdate, t1.amount, t1.chargetype, t1.id_cc_did, t1.currency, t1.description" . " FROM cc_charge t1, cc_card t2 WHERE (t1.chargetype <> 2 AND t1.chargetype <> 1)" . " AND t2.username = '******' AND t1.id_cc_card = t2.id AND " . " t1.creationdate >(Select cover_startdate  from cc_invoices where id ='{$id}') " . " AND t1.creationdate <(Select cover_enddate  from cc_invoices where id ='{$id}')";
    }
    if (!$nodisplay) {
        $list_total_charges = $instance_table->SQLExec($DBHandle, $QUERY);
    }
    /*************************************************CHARGES SECTION END ************************************************/
    if ($nb_record <= $FG_LIMITE_DISPLAY) {
        $nb_record_max = 1;
    } else {
        if ($nb_record % $FG_LIMITE_DISPLAY == 0) {
            $nb_record_max = intval($nb_record / $FG_LIMITE_DISPLAY);
        } else {
            $nb_record_max = intval($nb_record / $FG_LIMITE_DISPLAY) + 1;
        }
    }
    /*************************************************************/
    if (isset($customer) && $customer > 0 || isset($entercustomer) && $entercustomer > 0) {
        $FG_TABLE_CLAUSE = "";
        if (isset($customer) && $customer > 0) {
            $FG_TABLE_CLAUSE = " username='******' ";
        } elseif (isset($entercustomer) && $entercustomer > 0) {
            $FG_TABLE_CLAUSE = " username='******' ";
        }
        $instance_table_customer = new Table("cc_card", "id,  username, lastname, firstname, address, city, state, country, zipcode, phone, email, fax, activated, creationdate");
        $info_customer = $instance_table_customer->Get_list($DBHandle, $FG_TABLE_CLAUSE, "id", "ASC", null, null, null, null);
    }
    if ($invoice_type == 1) {
        $QUERY = "Select CASE WHEN max(cover_enddate) is NULL THEN '0001-01-01 01:00:00' ELSE max(cover_enddate) END from cc_invoices WHERE cardid = " . $cardid;
    } else {
        $QUERY = "Select cover_enddate,cover_startdate  from cc_invoices where id ='{$id}'";
    }
    if (!$nodisplay) {
        $invoice_dates = $instance_table->SQLExec($DBHandle, $QUERY);
        if ($invoice_dates[0][0] == '0001-01-01 01:00:00') {
            $invoice_dates[0][0] = $info_customer[0][13];
        }
    }
    require '../Public/pdf-invoices/html2pdf/html2fpdf.php';
    ob_start();
    $currencies_list = get_currencies();
    //For DID DIAL & Fixed + Dial
    $totalcost = 0;
    if (is_array($list_total_destination) && count($list_total_destination) > 0) {
        $mmax = 0;
        $totalcall = 0;
        $totalminutes = 0;
        foreach ($list_total_destination as $data) {
            if ($mmax < $data[1]) {
                $mmax = $data[1];
            }
            $totalcall += $data[3];
            $totalminutes += $data[1];
            $totalcost += $data[2];
        }
    }
    ?>
	<table cellpadding="0"  align="center">
	<tr>
	<td align="center">
	<img src="<?php 
    echo Images_Path;
    ?>
/asterisk01.jpg" align="middle">
	</td>
	</tr>
	</table>
	<br>
	<center><h4><font color="#FF0000"><?php 
    echo $invocie_top_heading;
    ?>
&nbsp;<?php 
    echo $info_customer[0][1];
    ?>
 </font></h4></center>
	<br>
	<br>
		<table cellspacing="0" cellpadding="2" align="center" width="80%" >
		 
		  <tr>
			<td colspan="2" bgcolor="#FFFFCC"><font size="5" color="#FF0000"><?php 
    echo $invoice_heading;
    ?>
</font></td>
		  </tr>
		  <tr>
			<td valign="top" colspan="2"></td>
		  </tr>	 
		<tr>
		  <td width="35%">&nbsp; </td>
		  <td >&nbsp; </td>
		</tr>
		<tr>
		  <td width="35%" ><font color="#003399"><?php 
    echo gettext("Name");
    ?>
&nbsp; :</font> </td>
		  <td  ><font color="#003399"><?php 
    echo $info_customer[0][3] . " " . $info_customer[0][2];
    ?>
</font></td>
		</tr>
		<tr>
		  <td width="35%" ><font color="#003399"><?php 
    echo gettext("Card Number");
    ?>
&nbsp; :</font></td>
		  <td  ><font color="#003399"><?php 
    echo $info_customer[0][1];
    ?>
</font> </td>
		</tr>
		<?php 
    if ($invoice_type == 1) {
        ?>
		<tr>
		  <td width="35%" ><font color="#003399"><?php 
        echo gettext("From Date");
        ?>
&nbsp; :</font></td>
		  <td><font color="#003399"><?php 
        echo display_dateonly($invoice_dates[0][0]);
        ?>
 </font></td>
		</tr>  		
		  <?php 
    } else {
        ?>
		<tr>
		 <td width="35%" ><font color="#003399"><?php 
        echo gettext("From Date");
        ?>
&nbsp; :</font></td>
		 <td  ><font color="#003399"><?php 
        echo display_dateonly($invoice_dates[0][1]);
        ?>
 </font></td>
		</tr>
		<tr>
		  <td width="35%" ><font color="#003399"><?php 
        echo gettext("To Date");
        ?>
&nbsp; :</font></td>
		  <td><font color="#003399"><?php 
        echo display_dateonly($invoice_dates[0][0]);
        ?>
 </font></td>
		</tr>  
		  <?php 
    }
    ?>
		  </table>
		  <table align="center" width="80%">
		  	<?php 
    if (is_array($list_total_destination) && count($list_total_destination) > 0) {
        ?>
				<tr>
					<td colspan="4" align="center"><font> <b><?php 
        echo gettext("By Destination");
        ?>
</b></font> </td>
				</tr>
				<tr bgcolor="#CCCCCC">
				  <td  width="29%"><font color="#003399"><b><?php 
        echo gettext("Destination");
        ?>
 </b></font></td>
				  <td width="38%" ><font color="#003399"><b><?php 
        echo gettext("Duration");
        ?>
</b></font> </td>
				 
				  <td width="12%" align="center" ><font color="#003399"><b><?php 
        echo gettext("Calls");
        ?>
 </b></font></td>
				  <td   align="right"><font color="#003399"><b><?php 
        echo gettext("Amount") . " (" . BASE_CURRENCY . ")";
        ?>
 </b></font></td>
				</tr>
				<?php 
        $i = 0;
        foreach ($list_total_destination as $data) {
            $i = ($i + 1) % 2;
            $tmc = $data[1] / $data[3];
            if (!isset($resulttype) || $resulttype == "min") {
                $tmc = sprintf("%02d", intval($tmc / 60)) . ":" . sprintf("%02d", intval($tmc % 60));
            } else {
                $tmc = intval($tmc);
            }
            if (!isset($resulttype) || $resulttype == "min") {
                $minutes = sprintf("%02d", intval($data[1] / 60)) . ":" . sprintf("%02d", intval($data[1] % 60));
            } else {
                $minutes = $data[1];
            }
            if ($mmax > 0) {
                $widthbar = intval($data[1] / $mmax * 200);
            }
            ?>
				<tr class="invoice_rows">
				  <td width="29%" ><font color="#003399"><?php 
            echo $data[0];
            ?>
</font></td>
				  <td width="38%" ><font color="#003399"><?php 
            echo $minutes;
            ?>
 </font></td>
				  
				  <td width="12%" align="right" ><font color="#003399"><?php 
            echo $data[3];
            ?>
</font> </td>
				  <td  align="right" ><font color="#003399"><?php 
            display_2bill($data[2]);
            ?>
</font></td>
				</tr>
				<?php 
        }
        if (!isset($resulttype) || $resulttype == "min") {
            $total_tmc = sprintf("%02d", intval($totalminutes / $totalcall / 60)) . ":" . sprintf("%02d", intval($totalminutes / $totalcall % 60));
            $totalminutes = sprintf("%02d", intval($totalminutes / 60)) . ":" . sprintf("%02d", intval($totalminutes % 60));
        } else {
            $total_tmc = intval($totalminutes / $totalcall);
        }
        ?>
   
				 <tr >
				  <td width="29%" >&nbsp;</td>
				  <td width="38%" >&nbsp;</td>              
				  <td width="12%" >&nbsp; </td>
				  <td  >&nbsp; </td>
				  
				</tr>
				<tr bgcolor="#CCCCCC">
				  <td width="29%" ><font color="#003399"><?php 
        echo gettext("TOTAL");
        ?>
 </font></td>
				  <td width="38%" ><font color="#003399"><?php 
        echo $totalminutes;
        ?>
</font></td>			  
				  <td width="12%"  align="right"><font color="#003399"><?php 
        echo $totalcall;
        ?>
 </font></td>
				  <td  align="right" ><font color="#003399"><?php 
        display_2bill($totalcost - $totalcost_did);
        ?>
</font> </td>
				</tr> 			  
				<tr >
				  <td width="29%">&nbsp;</td>
				  <td width="38%">&nbsp;</td>
				  
				  <td width="12%">&nbsp; </td>
				  <td >&nbsp; </td>
				  
				</tr>			
				<?php 
    }
    ?>
				</table>
				
				<table align="center" width="80%">
				<!-- Start Here ****************************************-->
				<?php 
    $mmax = 0;
    $totalcall = 0;
    $totalminutes = 0;
    $totalcost_day = 0;
    if (is_array($list_total_day) && count($list_total_day) > 0) {
        foreach ($list_total_day as $data) {
            if ($mmax < $data[1]) {
                $mmax = $data[1];
            }
            $totalcall += $data[3];
            $totalminutes += $data[1];
            $totalcost_day += $data[2];
        }
        ?>
					
					<tr>
					<td colspan="4" align="center"><b><?php 
        echo gettext("By Date");
        ?>
</b> </td>
					</tr>
				  <tr bgcolor="#CCCCCC">
				  <td  width="29%"><font color="#003399"><b><?php 
        echo gettext("Date");
        ?>
</b> </font></td>
				  <td width="38%" ><font color="#003399"><b><?php 
        echo gettext("Duration");
        ?>
</b> </font></td>
				  
				  <td width="12%" align="center" ><font color="#003399"><b><?php 
        echo gettext("Calls");
        ?>
</b> </font></td>
				  <td width="21%"  align="right"><font color="#003399"><b><?php 
        echo gettext("Amount") . " (" . BASE_CURRENCY . ")";
        ?>
</b> </font></td>
				</tr>
				<?php 
        $i = 0;
        foreach ($list_total_day as $data) {
            $i = ($i + 1) % 2;
            $tmc = $data[1] / $data[3];
            if (!isset($resulttype) || $resulttype == "min") {
                $tmc = sprintf("%02d", intval($tmc / 60)) . ":" . sprintf("%02d", intval($tmc % 60));
            } else {
                $tmc = intval($tmc);
            }
            if (!isset($resulttype) || $resulttype == "min") {
                $minutes = sprintf("%02d", intval($data[1] / 60)) . ":" . sprintf("%02d", intval($data[1] % 60));
            } else {
                $minutes = $data[1];
            }
            if ($mmax > 0) {
                $widthbar = intval($data[1] / $mmax * 200);
            }
            ?>
				<tr class="invoice_rows">
				  <td width="29%" ><font color="#003399"><?php 
            echo $data[0];
            ?>
</font></td>
				  <td width="38%" ><font color="#003399"><?php 
            echo $minutes;
            ?>
 </font></td>
				  
				  <td width="12%"  align="right"><font color="#003399"><?php 
            echo $data[3];
            ?>
 </font></td>
				  <td width="21%" align="right" ><font color="#003399"><?php 
            display_2bill($data[2]);
            ?>
</font></td>
				</tr>
				 <?php 
        }
        if (!isset($resulttype) || $resulttype == "min") {
            $total_tmc = sprintf("%02d", intval($totalminutes / $totalcall / 60)) . ":" . sprintf("%02d", intval($totalminutes / $totalcall % 60));
            $totalminutes = sprintf("%02d", intval($totalminutes / 60)) . ":" . sprintf("%02d", intval($totalminutes % 60));
        } else {
            $total_tmc = intval($totalminutes / $totalcall);
        }
        ?>
               
				 <tr >
				  <td width="29%" >&nbsp;</td>
				  <td width="38%" >&nbsp;</td>
				  
				  <td width="12%" >&nbsp; </td>
				  <td width="21%" >&nbsp; </td>
				  
				</tr>
				<tr bgcolor="#CCCCCC">
				  <td width="29%" ><font color="#003399"><?php 
        echo gettext("TOTAL");
        ?>
 </font></td>
				  <td width="38%" ><font color="#003399"><?php 
        echo $totalminutes;
        ?>
</font></td>			  
				  <td width="12%" align="right" ><font color="#003399"><?php 
        echo $totalcall;
        ?>
</font> </td>
				  <td width="21%" align="right" ><font color="#003399"><?php 
        display_2bill($totalcost_day);
        ?>
 </font></td>
				</tr>        
				<tr >
				  <td width="29%">&nbsp;</td>
				  <td width="38%">&nbsp;</td>
				 
				  <td width="12%">&nbsp; </td>
				  <td width="21%">&nbsp; </td>
				  
				</tr>				
					<?php 
    }
    ?>
    
				
				<!-- END HERE ******************************************-->
		 
		</table>
		 <table align="center" width="80%">
		 <?php 
    if (is_array($list_total_did) && count($list_total_did) > 0) {
        ?>
		 <tr>
		  <td>
		  
			<table width="100%" align="left" cellpadding="0" cellspacing="0">
					<tr>
					<td colspan="5" align="center"><font><b><?php 
        echo gettext("DID Billing");
        ?>
</b></font> </td>
					</tr>
				<tr  bgcolor="#CCCCCC">
				  <td  width="20%"> <font color="#003399"><b><?php 
        echo gettext("Charge Date");
        ?>
 </b></font></td>
				  <td width="13%" ><font color="#003399"><b><?php 
        echo gettext("DID");
        ?>
 </b></font></td>
				  <td width="14%" ><font color="#003399"><b><?php 
        echo gettext("Country");
        ?>
</b></font> </td>
				  <td width="41%" ><font color="#003399"><b><?php 
        echo gettext("Description");
        ?>
 </b></font></td>  			  
				  <td width="12%"  align="right"><font color="#003399"><b><?php 
        echo gettext("Amount") . " (" . BASE_CURRENCY . ")";
        ?>
</b></font> </td>
				</tr>
				<?php 
        $i = 0;
        $totaldidcost = 0;
        foreach ($list_total_did as $data) {
            $totaldidcost = $totaldidcost + convert_currency($currencies_list, $data[0], $data[5], BASE_CURRENCY);
            ?>
				 <tr class="invoice_rows">
				  <td width="20%" ><font color="#003399"><?php 
            echo $data[1];
            ?>
</font></td>
				  <td width="13%" ><font color="#003399">&nbsp;<?php 
            echo $data[4];
            ?>
</font> </td>
				  <td width="14%" ><font color="#003399">&nbsp;<?php 
            echo $data[3];
            ?>
 </font></td>
				  <td width="41%" ><font color="#003399"><?php 
            echo $data[2];
            ?>
</font> </td>			  
				  <td width="12%" align="right" ><font color="#003399"><?php 
            convert_currency($currencies_list, $data[0], $data[5], BASE_CURRENCY) . " " . BASE_CURRENCY;
            ?>
</font></td>
				</tr>
				 <?php 
        }
        $totalcost = $totalcost + $totaldidcost;
        ?>
   
				 <tr >
				  <td width="20%" >&nbsp;</td>
				  <td width="13%" >&nbsp;</td>
				  <td width="14%" >&nbsp; </td>
				  <td width="41%" >&nbsp; </td>			 
				  <td width="12%" >&nbsp; </td>			  
				</tr>
				<tr bgcolor="#CCCCCC" >
				  <td width="20%" ><font color="#003399"><?php 
        echo gettext("TOTAL");
        ?>
 </font></td>
				  <td ><font color="#003399">&nbsp;</font></td>			  
				  <td width="14%" ><font color="#003399">&nbsp;</font> </td>
				  <td width="41%" ><font color="#003399">&nbsp;</font> </td>			  
				  <td width="12%" align="right" ><font color="#003399"><?php 
        display_2bill($totaldidcost);
        ?>
</font> </td>
				</tr>  
				<tr>
				  <td width="20%">&nbsp;</td>
				  <td width="13%">&nbsp;</td>
				  <td width="14%">&nbsp; </td>
				  <td width="41%">&nbsp; </td>			 
				  <td width="12%">&nbsp; </td>
				</tr>
			
			</table>
			
		  </td>
		  </tr>
		  <?php 
    }
    ?>
		   <tr>
			<td>
			<!-------------------------EXTRA CHARGE START HERE ---------------------------------->
		
		 <?php 
    $i = 0;
    $extracharge_total = 0;
    if (is_array($list_total_charges) && count($list_total_charges) > 0) {
        ?>
			<table width="100%" align="left" cellpadding="0" cellspacing="0">
				<tr>
				<td colspan="4" align="center"><font><b><?php 
        echo gettext("Extra Charges");
        ?>
</b></font> </td>
				</tr>
				<tr  bgcolor="#CCCCCC">
				  <td  width="20%"> <font color="#003399"><b><?php 
        echo gettext("Date");
        ?>
 </b></font></td>
				  <td width="19%" ><font color="#003399"><b><?php 
        echo gettext("Type");
        ?>
 </b></font></td>
				  <td width="43%" ><font color="#003399"><b><?php 
        echo gettext("Description");
        ?>
</b></font> </td>			
				  <td width="18%"  align="right"><font color="#003399"><b><?php 
        echo gettext("Amount") . " (" . BASE_CURRENCY . ")";
        ?>
</b></font> </td>
				</tr>
				<?php 
        foreach ($list_total_charges as $data) {
            $extracharge_total = $extracharge_total + convert_currency($currencies_list, $data[3], $data[6], BASE_CURRENCY);
            ?>
				 <tr class="invoice_rows">
				  <td width="20%" ><font color="#003399"><?php 
            echo $data[2];
            ?>
</font></td>
				  <td width="19%" ><font color="#003399">
				  <?php 
            if ($data[4] == 1) {
                echo gettext("Setup Charges");
            }
            if ($data[4] == 2) {
                echo gettext("DID Montly Use");
            }
            if ($data[4] == 3) {
                echo gettext("Subscription Fee");
            }
            if ($data[4] == 4) {
                echo gettext("Extra Charges");
            }
            ?>
				  </font> </td>
				  <td width="43%" ><font color="#003399"><?php 
            echo $data[7];
            ?>
</font></td>			 
				  <td width="18%" align="right" ><font color="#003399"><?php 
            echo convert_currency($currencies_list, $data[3], $data[6], BASE_CURRENCY) . " " . BASE_CURRENCY;
            ?>
</font></td>
				</tr>
				 <?php 
        }
        //for loop end here
        ?>
				 <tr >
				  <td width="20%" >&nbsp;</td>
				  <td width="19%" >&nbsp;</td>
				  <td width="43%" >&nbsp; </td>			 
				  <td width="18%" >&nbsp; </td>
				  
				</tr>
				<tr bgcolor="#CCCCCC" >
				  <td width="20%" ><font color="#003399"><?php 
        echo gettext("TOTAL");
        ?>
 </font></td>
				  <td ><font color="#003399">&nbsp;</font></td>			  
				  <td width="43%" ><font color="#003399">&nbsp;</font> </td>			  
				  <td width="18%" align="right" ><font color="#003399"><?php 
        echo display_2bill($extracharge_total);
        ?>
</font> </td>
				</tr>    			        
				<tr >
				  <td width="20%">&nbsp;</td>
				  <td width="19%">&nbsp;</td>
				  <td width="43%">&nbsp; </td>			  
				  <td width="18%">&nbsp; </td>			  
				</tr>		
			</table>		
			<?php 
    }
    //if check end here
    $totalcost = $totalcost + $extracharge_total;
    ?>
<!-----------------------------EXTRA CHARGE END HERE ------------------------------->		
			
			</td>
			</tr>
		  
		 <tr>
		 <td><img src="<?php 
    echo Images_Path;
    ?>
/spacer.jpg" align="middle" height="30px"></td>
		 </tr>
		 <tr bgcolor="#CCCCCC" >
		 <td  align="right" width="100%"><font color="#003399"><b><?php 
    echo gettext("Total");
    ?>
 = <?php 
    display_2bill($totalcost);
    ?>
&nbsp;</b></font></td>
		 </tr>
		 <tr bgcolor="#CCCCCC" >
		 <td  align="right" width="100%"><font color="#003399"><b><?php 
    echo gettext("VAT");
    ?>
 = <?php 
    $prvat = $vat / 100 * $totalcost;
    display_2bill($prvat);
    ?>
&nbsp;</b></font></td>
		 </tr>
		 <tr>
		 <td><img src="<?php 
    echo Images_Path;
    ?>
/spacer.jpg" align="middle" height="30px"></td>
		 </tr>
		 <tr bgcolor="#CCCCCC" >
		 <td  align="right" width="100%"><font color="#003399"><b><?php 
    echo gettext("Grand Total");
    ?>
 = <?php 
    echo display_2bill($totalcost + $prvat);
    ?>
&nbsp;</b></font></td>
		 </tr>
		 <tr>
		 <td><img src="<?php 
    echo Images_Path;
    ?>
/spacer.jpg" align="middle" height="30px"></td>
		 </tr>
		 </table>
		
	<table cellspacing="0" cellpadding="2" width="80%" align="center">
	<tr>
		<td colspan="3">&nbsp;</td>
		</tr>           			
		<tr>
		  <td  align="left">Status :&nbsp;<?php 
    if ($info_customer[0][12] == 't') {
        ?>
		  <img src="<?php 
        echo Images_Path;
        ?>
/connected.jpg">
		  <?php 
    } else {
        ?>
		  <img src="<?php 
        echo Images_Path;
        ?>
/terminated.jpg">
		  <?php 
    }
    ?>
 </td>              
		</tr>
		<tr>	  
		  <td  align="left">&nbsp; <img src="<?php 
    echo Images_Path;
    ?>
/connected.jpg"> &nbsp;<?php 
    echo gettext("Connected");
    ?>
 
		  &nbsp;&nbsp;&nbsp;<img src="<?php 
    echo Images_Path;
    ?>
/terminated.jpg">&nbsp;<?php 
    echo gettext("Disconnected");
    ?>
 
		  </td>
	</table>

<?php 
    $html = ob_get_contents();
    // delete output-Buffer
    ob_end_clean();
    $pdf = new HTML2FPDF();
    $pdf->DisplayPreferences('HideWindowUI');
    $pdf->AddPage();
    $pdf->WriteHTML($html);
    $stream = $pdf->Output('UnBilledDetails_' . date("d/m/Y-H:i") . '.pdf', 'S');
    //================================Email Template Retrival Code ===================================
    $QUERY = "SELECT mailtype, fromemail, fromname, subject, messagetext, messagehtml FROM cc_templatemail WHERE mailtype='invoice' ";
    $res = $DBHandle->Execute($QUERY);
    $num = 0;
    if ($res) {
        $num = $res->RecordCount();
    }
    if (!$num) {
        echo "<br>Error : No email Template Found";
        exit;
    }
    for ($i = 0; $i < $num; $i++) {
        $listtemplate[] = $res->fetchRow();
    }
    list($mailtype, $from, $fromname, $subject, $messagetext, $messagehtml) = $listtemplate[0];
    if ($FG_DEBUG == 1) {
        echo "<br><b>mailtype : </b>{$mailtype}</br><b>from:</b> {$from}</br><b>fromname :</b> {$fromname}</br><b>subject</b> : {$subject}</br><b>ContentTemplate:</b></br><pre>{$messagetext}</pre></br><hr>";
    }
    //================================================================================================
    $ok = send_email_attachment($from, $info_customer[0][10], $subject, $messagetext, 'UnBilledDetails_' . date("d/m/Y-H:i") . '.pdf', $stream);
    return $ok;
}
Example #7
0
 public function revenue(Request $request)
 {
     $data = array();
     $data['page'] = 'revenue';
     //total turnoveUserr
     $totalTurnoverINR = Order::where('payment_status', 2)->where('currency', 'INR')->sum('amount');
     $totalTurnoverUSD = Order::where('payment_status', 2)->where('currency', 'USD')->sum('amount');
     if ($totalTurnoverUSD > 0) {
         $totalTurnoverINR = $totalTurnoverINR + convert_currency('USD', 'INR', $totalTurnoverUSD);
     }
     $data['totalTurnover'] = number_format($totalTurnoverINR, 2, '.', ',');
     $totalFeeINR = Order::where('payment_status', 2)->where('currency', 'INR')->sum('txnfee');
     $totalFeeUSD = Order::where('payment_status', 2)->where('currency', 'USD')->sum('txnfee');
     if ($totalFeeUSD > 0) {
         $totalFeeINR = $totalFeeINR + convert_currency('USD', 'INR', $totalFeeUSD);
     }
     $data['totalTxnFee'] = number_format($totalFeeINR, 2, '.', ',');
     //earnings
     $totalCredit = Fund::select(array(DB::raw('sum(amount) as amount'), 'currency'))->where('txn_type', 1)->groupBy('currency')->lists('amount', 'currency');
     if (isset($totalCredit['USD']) && $totalCredit['USD'] > 0) {
         $totalCredit['INR'] = $totalCredit['INR'] + convert_currency('USD', 'INR', $totalCredit['USD']);
     }
     $totalCredit = $totalCredit['INR'];
     //refunds
     $totalDebit = Fund::select(array(DB::raw('sum(amount) as amount'), 'currency'))->where('txn_type', 0)->groupBy('currency')->lists('amount', 'currency');
     if (isset($totalDebit['USD']) && $totalDebit['USD'] > 0) {
         $totalDebit['INR'] = $totalDebit['INR'] + convert_currency('USD', 'INR', $totalDebit['USD']);
     }
     $totalDebit = $totalDebit['INR'];
     //total income
     $data['totalRevenue'] = number_format($totalCredit - $totalDebit, 2, '.', ',');
     $data['totalCredit'] = number_format($totalCredit, 2, '.', ',');
     $data['totalDebit'] = number_format($totalDebit, 2, '.', ',');
     //total income from jobs / services / contest
     $totalCreditINR = Fund::select(array(DB::raw('sum(amount) as amount'), 'source_type'))->where('txn_type', 1)->where('currency', 'INR')->groupBy('source_type')->lists('amount', 'source_type');
     $totalCreditUSD = Fund::select(array(DB::raw('sum(amount) as amount'), 'source_type'))->where('txn_type', 1)->where('currency', 'USD')->groupBy('source_type')->lists('amount', 'source_type');
     foreach ($totalCreditINR as $key => $credits) {
         $tmpInr = isset($totalCreditUSD[$key]) ? convert_currency('USD', 'INR', $totalCreditUSD[$key]) : 0.0;
         $totalCreditINR[$key] = $totalCreditINR[$key] + $tmpInr;
     }
     $startDate = date('Y-m-d', strtotime('-12 month'));
     $endDate = date('Y-m-d');
     $fundStatsUSD = Fund::select(DB::raw('sum(amount) as amount'), DB::raw('date(created_at) as date'))->where('txn_type', 1)->where('currency', 'USD')->where('created_at', '>=', $startDate)->where('created_at', '<=', $endDate)->groupBy('source_type')->groupBy('updated_at')->lists('amount', 'date');
     $fundStatsINR = Fund::select(DB::raw('sum(amount) as amount'), DB::raw('date(created_at) as date'))->where('txn_type', 1)->where('currency', 'INR')->where('created_at', '>=', $startDate)->where('created_at', '<=', $endDate)->groupBy('source_type')->groupBy('updated_at')->lists('amount', 'date');
     $debitStatsUSD = Fund::select(DB::raw('sum(amount) as amount'), DB::raw('date(created_at) as date'))->where('txn_type', 0)->where('currency', 'USD')->where('created_at', '>=', $startDate)->where('created_at', '<=', $endDate)->groupBy('source_type')->groupBy('updated_at')->lists('amount', 'date');
     $debitStatsINR = Fund::select(DB::raw('sum(amount) as amount'), DB::raw('date(created_at) as date'))->where('txn_type', 0)->where('currency', 'INR')->where('created_at', '>=', $startDate)->where('created_at', '<=', $endDate)->groupBy('source_type')->groupBy('updated_at')->lists('amount', 'date');
     $statsDataUSD = array();
     foreach ($fundStatsUSD as $date => $amount) {
         $statsDataUSD[strtotime($date)] = convert_currency('USD', 'INR', $amount);
     }
     $statsData = array();
     $maxValue = 50;
     foreach ($fundStatsINR as $date => $amount) {
         $date = strtotime($date);
         $tmp = isset($statsDataUSD[$date]) ? floatval($amount) + $statsDataUSD[$date] : floatval($amount);
         $statsData[$date] = $tmp;
         $maxValue = $tmp > $maxValue ? $tmp : $maxValue;
     }
     $statsDebitDataUSD = array();
     foreach ($debitStatsUSD as $date => $amount) {
         $statsDebitDataUSD[strtotime($date)] = convert_currency('USD', 'INR', $amount);
     }
     $statsDebitData = array();
     foreach ($debitStatsINR as $date => $amount) {
         $date = strtotime($date);
         $tmp = isset($statsDebitDataUSD[$date]) ? floatval($amount) + $statsDebitDataUSD[$date] : floatval($amount);
         $statsDebitData[$date] = $tmp;
     }
     $xtmp = array();
     for ($i = 365; $i >= 0; $i--) {
         $date = strtotime($endDate . '-' . $i . ' day');
         if (isset($statsData[$date])) {
             $xtmp[] = array('x' => $date, 'y' => $statsData[$date]);
         } else {
             $xtmp[] = array('x' => $date, 'y' => 0);
         }
         if (isset($statsDebitData[$date])) {
             $debitTmp[] = array('x' => $date, 'y' => $statsDebitData[$date]);
         } else {
             $debitTmp[] = array('x' => $date, 'y' => 0);
         }
     }
     $tmp = array();
     $tmp[] = array('key' => 'Earnings', 'values' => $xtmp, 'color' => '#2ca02c');
     $tmp[] = array('key' => 'Redunds & Chargebacks', 'values' => $debitTmp, 'color' => '#ff7f0e');
     $data['totalCreditJob'] = isset($totalCreditINR['1']) ? number_format($totalCreditINR['1'], 2, '.', ',') : 0.0;
     $data['totalCreditExtInv'] = isset($totalCreditINR['2']) ? number_format($totalCreditINR['2'], 2, '.', ',') : 0.0;
     $data['totalCreditMembership'] = isset($totalCreditINR['3']) ? number_format($totalCreditINR['3'], 2, '.', ',') : 0.0;
     $data['totalCreditFeatured'] = isset($totalCreditINR['4']) ? number_format($totalCreditINR['4'], 2, '.', ',') : 0.0;
     $data['totalCreditProposalBuy'] = isset($totalCreditINR['5']) ? number_format($totalCreditINR['5'], 2, '.', ',') : 0.0;
     $data['totalCreditTxnAdmin'] = isset($totalCreditINR['6']) ? number_format($totalCreditINR['6'], 2, '.', ',') : 0.0;
     $data['totalCreditPartialPay'] = isset($totalCreditINR['7']) ? number_format($totalCreditINR['7'], 2, '.', ',') : 0.0;
     $data['revenueData'] = $tmp;
     $data['maxValue'] = $maxValue;
     return view('backend.revenue')->with($data);
 }
function order_difference($request, $conv_currency = 'INR')
{
    $order_diff = in_session_currency($request['currency'], round($request['amount'], 2)) - in_session_currency($request['currency'], round($request['wallet_balance'], 2), '2');
    if ($conv_currency == 'USD') {
        return $order_diff;
    } else {
        $order_diff = convert_currency(Session::get('currency'), 'INR', $order_diff, 3);
        return $order_diff;
    }
}
Example #9
0
function project_sidebar() {
	global $db, $con, $html, $config, $currency, $symbol, $area, $logger, $_GET, $phrase;
	
	if ($con->estrato == -1) {
		$min = 4;
		$max = 6;
	}
	
	else {
		$min = $con->estrato-1;
		$max = $con->estrato+1;
		
		if ($max > 6) {
			$min--;
		}
		if ($min < 0) {
			$max++;
		}
	}
	
	$project = $db->query_first("SELECT * FROM `project` WHERE `id`!=".$db->sql($_GET['id'])." AND `estrato`>=".$db->sql($min)." AND `estrato`<=".$db->sql($max)." AND `vende` > 0 ORDER BY RAND()");
	
	if (!$project['id']) {
		$logger->log("Had to search for any old project to fill in the sidebar");
		$project = $db->query_first("SELECT * FROM `project` WHERE `id`!=".$db->sql($_GET['id'])." ORDER BY RAND()");
	}
	
	$project['price_min'] = convert_currency($project['price_min']);
	$project['price_max'] = convert_currency($project['price_max']);
	$project['area_min'] = convert_area($project['area_min']);
	$project['area_max'] = convert_area($project['area_max']);
	
	eval('$html["sidebars"] .= "'.fetch_template('sidebar_project').'";');
}
Example #10
0
 function GenerateChargeItems()
 {
     if (!$this->IsCoveringCharges()) {
         if ($this->verbose_level >= 1) {
             echo "\nCharges not covered. Skipping ChargeItems generation.";
         }
         return;
     }
     global $chargetype_list;
     $nb_items = count($this->list_items);
     //Get the calls destination wise and calculate total cost
     if (is_array($this->list_total_charge)) {
         foreach ($this->list_total_charge as $data) {
             $chargeitem = array($chargetype_list[$data[6]], $data[11] > 0 ? $data[13] : $data[7], $data[11] > 0 ? $data[12] : '', $data[10], $data[9], $data[3], 0, 0, 1, 0, convert_currency($this->currencies_list, $data[4], strtoupper($data[5]), strtoupper($this->invoice_currency)));
             // look for identical item
             $found = false;
             foreach ($this->list_items as &$item) {
                 if ($found = $item[0] == $chargeitem[0] && $item[1] == $chargeitem[1] && $item[3] == $chargeitem[3] && $item[4] == $chargeitem[4] && $item[9] == $chargeitem[9] && $item[10] == $chargeitem[10]) {
                     $item[2] = '';
                     $item[8]++;
                     if ($this->verbose_level >= 2) {
                         echo "\n #Similar Item: ";
                         print_r($item);
                     }
                     break;
                 }
             }
             if (!$found) {
                 if ($this->verbose_level >= 2) {
                     echo "\n #Item: ";
                     print_r($chargeitem);
                 }
                 $this->list_items[] = $chargeitem;
             }
         }
     } else {
         throw new Exception('Unable to generate Call Items because Calls were not listed');
     }
     if ($this->verbose_level >= 1) {
         echo "\n" . (count($this->list_items) - $nb_items) . ' charge items generated';
     }
 }
Example #11
0
			<?php 
        $i = 0;
        foreach ($list_total_day_charge as $data) {
            $i = ($i + 1) % 2;
            ?>
            <tr class="invoice_rows">
              <td width="37%" ><font color="#003399"><?php 
            echo $data[0];
            ?>
</font></td>
              <td width="41%" ><font color="#003399"><?php 
            echo $data[2];
            ?>
 </font></td>			 
              <td  align="right" ><font color="#003399"><?php 
            echo convert_currency($currencies_list, $data[1], $data[3], $selected_currency) . " " . $selected_currency;
            ?>
</font></td>
            </tr>
			  <?php 
        }
        ?>
 
			 <tr >
              <td width="37%" >&nbsp;</td>
              <td width="41%" >&nbsp;</td>              
			  <td width="22%" >&nbsp; </td>		  
            </tr>
            <tr bgcolor="#CCCCCC">
              <td width="37%" ><font color="#003399"><?php 
        echo gettext("TOTAL");
Example #12
0
			<?php 
        $i = 0;
        foreach ($list_total_day_charge as $data) {
            $i = ($i + 1) % 2;
            ?>
            <tr class="invoice_rows">
              <td width="37%" ><font color="#003399"><?php 
            echo display_GMT($data[0], $_SESSION["gmtoffset"], 0);
            ?>
</font></td>
              <td width="41%" ><font color="#003399"><?php 
            echo $data[2];
            ?>
 </font></td>			 
              <td  align="right" ><font color="#003399"><?php 
            echo number_format(convert_currency($currencies_list, $data[1], $data[3], $selected_currency), 3) . " " . $selected_currency;
            ?>
</font></td>
            </tr>
			  <?php 
        }
        ?>
 
			 <tr >
              <td width="37%" >&nbsp;</td>
              <td width="41%" >&nbsp;</td>              
			  <td width="22%" >&nbsp; </td>		  
            </tr>
            <tr bgcolor="#CCCCCC">
              <td width="37%" ><font color="#003399"><?php 
        echo gettext("TOTAL");
 $FG_TABLE_CLAUSE = " id_cc_card='{$Customer['0']}' AND creationdate > '{$cover_startdate}'";
 $QUERY_CHARGE = "SELECT id, id_cc_card, iduser, creationdate, amount, chargetype, description, id_cc_did, currency, id_cc_subscription_fee FROM cc_charge" . " WHERE {$FG_TABLE_CLAUSE}";
 $list_total_charge = $instance_table->SQLExec($A2B->DBHandle, $QUERY_CHARGE, 1);
 $num = 0;
 $num = count($list_total_charge);
 if ($verbose_level >= 1) {
     echo "\n QUERY_CHARGE = {$QUERY_CHARGE}";
     echo "\n Number of Charge for '{$Customer['6']}' Found: " . $num;
 }
 //Get the calls destination wise and calculate total cost
 if (is_array($list_total_charge) && count($list_total_charge) > 0) {
     foreach ($list_total_charge as $data) {
         $charge_amount = $data[4];
         $charge_currency = $data[8];
         $base_currency = $A2B->config['global']['base_currency'];
         $charge_converted = convert_currency($currencies_list, $charge_amount, strtoupper($charge_currency), strtoupper($base_currency));
         if ($verbose_level >= 1) {
             echo "\n charge_amount = {$charge_amount} - charge_currency = {$charge_currency} " . " - charge_converted={$charge_converted} - base_currency={$base_currency}";
         }
         $totalcharge += 1;
         $totalcost += $charge_converted;
     }
 }
 if ($verbose_level >= 1) {
     echo "\n AFTER DESTINATION : totalcharge = {$totalcharge} - totalcost = {$totalcost}";
 }
 //************************************* INSERT INVOICE *************************************************
 if ($Customer[7] > 0 && $totalcost > 0) {
     $totaltax = $totalcost / 100 * $Customer[7];
 }
 // Here we have to Create a Insert Statement to insert Records into the Invoices Table.
function import_sale_info($lead_type, $amount, $currency_id, $subid)
{
    // Default account currency id: 16; RUB
    $main_currency_id = 16;
    if ($lead_type == 'sale') {
        if ($currency_id != $main_currency_id) {
            // Perform conversion to main currency
            $conversion_price_main = convert_currency($amount, $currency_id, $main_currency_id, date('Y-m-d'));
        } else {
            $conversion_price_main = $amount;
        }
    }
    $sql = "select id from tbl_conversions where subid='" . _str($subid) . "' and type='" . _str($lead_type) . "' limit 2";
    $result = db_query($sql) or die(mysql_error());
    $arr = array();
    while ($row = mysql_fetch_assoc($result)) {
        $arr[] = $row;
    }
    if (count($arr) == 2) {
        // Found at least two sales with same click id, do nothing
        return;
    }
    $row = $arr[0];
    if ($row['id'] > 0) {
        $id = $row['id'];
        $sql = "update tbl_conversions set profit='" . _str($conversion_price_main) . "', profit_currency='" . _str($amount) . "', currency_id='" . _str($currency_id) . "', date_add=NOW() where id='" . _str($id) . "'";
        db_query($sql) or die(mysql_error());
    } else {
        $sql = "insert into tbl_conversions (profit, profit_currency, currency_id, subid, date_add, type) values ('" . _str($conversion_price_main) . "', '" . _str($amount) . "', '" . _str($currency_id) . "', '" . _str($subid) . "', NOW(), '" . _str($lead_type) . "')";
        db_query($sql) or die(mysql_error());
    }
    switch ($lead_type) {
        case 'sale':
            $sql = "UPDATE tbl_clicks SET\n                      conversion_price_main='" . _str($conversion_price_main) . "',\n                      conversion_currency_id='" . _str($currency_id) . "',\n                      conversion_currency_sum='" . _str($amount) . "',\n                      is_sale='1'\n                      WHERE subid='" . _str($subid) . "'";
            break;
        case 'lead':
            $sql = "update tbl_clicks set is_lead='1' where subid='" . _str($subid) . "'";
            break;
    }
    db_query($sql) or die(mysql_error());
    return;
}
Example #15
0
            write_log(LOGFILE_EPAYMENT, basename(__FILE__) . ' line:' . __LINE__ . "-MoneyBookers Transaction Verification Status: Failed | md5sig =" . $md5sig . " Reproduced Signature = " . $sig_string . " Generated String = " . $sec_string);
            $security_verify = false;
        }
        $currCurrency = $currency;
        break;
    case "authorizenet":
        $currCurrency = BASE_CURRENCY;
        break;
    default:
        write_log(LOGFILE_EPAYMENT, basename(__FILE__) . ' line:' . __LINE__ . "-NO SUCH EPAYMENT FOUND");
        exit;
}
//If security verification fails then send an email to administrator as it may be a possible attack on epayment security.
$currencyObject = new currencies();
$currencies_list = get_currencies();
$amount_paid = convert_currency($currencies_list, $transaction_data[0][2], $currCurrency, BASE_CURRENCY);
if ($security_verify == false) {
    $QUERY = "SELECT mailtype, fromemail, fromname, subject, messagetext, messagehtml FROM cc_templatemail WHERE mailtype='epaymentverify' ";
    $res = $DBHandle_max->Execute($QUERY);
    $num = 0;
    if ($res) {
        $num = $res->RecordCount();
    }
    if (!$num) {
        write_log(LOGFILE_EPAYMENT, basename(__FILE__) . ' line:' . __LINE__ . "-NO EMAIL TEMPLATE FOUND TO SEND WARNING EMAIL TO ADMINISTRATOR FOR EPAYMENT VERIFICATION FAILURE");
        exit;
    }
    for ($i = 0; $i < $num; $i++) {
        $listtemplate[] = $res->fetchRow();
    }
    list($mailtype, $from, $fromname, $subject, $messagetext, $messagehtml) = $listtemplate[0];
Example #16
0
        write_log(LOGFILE_EPAYMENT, basename(__FILE__) . ' line:' . __LINE__ . "- RESULT : " . $pnp_transaction_array['FinalStatus']);
        // $pnp_transaction_array['FinalStatus'] = 'badcard';
        //echo "<pre>".print_r ($pnp_transaction_array, true)."</pre>";
        $transaction_detail = serialize($pnp_transaction_array);
        break;
    default:
        write_log(LOGFILE_EPAYMENT, basename(__FILE__) . ' line:' . __LINE__ . "-NO SUCH EPAYMENT FOUND");
        exit;
}
if (empty($transaction_data[0]['vat']) || !is_numeric($transaction_data[0]['vat'])) {
    $VAT = 0;
} else {
    $VAT = $transaction_data[0]['vat'];
}
write_log(LOGFILE_EPAYMENT, basename(__FILE__) . ' line:' . __LINE__ . "curr amount {$currAmount} {$currCurrency} BASE_CURRENCY=" . BASE_CURRENCY);
$amount_paid = convert_currency($currencies_list, $currAmount, $currCurrency, BASE_CURRENCY);
$amount_without_vat = $amount_paid / (1 + $VAT / 100);
//If security verification fails then send an email to administrator as it may be a possible attack on epayment security.
if ($security_verify == false) {
    write_log(LOGFILE_EPAYMENT, basename(__FILE__) . ' line:' . __LINE__ . "- security_verify == False | END");
    try {
        //TODO: create mail class for agent
        $mail = new Mail('epaymentverify', null);
    } catch (A2bMailException $e) {
        write_log(LOGFILE_EPAYMENT, basename(__FILE__) . ' line:' . __LINE__ . "-transactionID={$transactionID}" . " ERROR NO EMAIL TEMPLATE FOUND");
        exit;
    }
    $mail->replaceInEmail(Mail::$TIME_KEY, date("y-m-d H:i:s"));
    $mail->replaceInEmail(Mail::$PAYMENTGATEWAY_KEY, $transaction_data[0][4]);
    $mail->replaceInEmail(Mail::$ITEM_AMOUNT_KEY, $amount_paid . $currCurrency);
    // Add Post information / useful to track down payment transaction without having to log
Example #17
0
             $arr_campaign_ads = explode('-', $IN['value']);
             $sql = "SELECT " . $arr_sql['select'] . " FROM " . $arr_sql['from'] . " " . $arr_sql['join'] . " WHERE\n                            campaign_name='" . _str($arr_campaign_ads[0]) . "' AND\n                            ads_name='" . _str($arr_campaign_ads[1]) . "' AND\n                        " . $arr_sql['where'];
             break;
         default:
             $sql = "SELECT " . $arr_sql['select'] . " FROM " . $arr_sql['from'] . " " . $arr_sql['join'] . " WHERE `" . _str($IN['main_column']) . "`='" . _str($IN['value']) . "' AND " . $arr_sql['where'];
             break;
     }
     if ($IN['currency'] == $main_currency_id) {
         if ($IN['clicks_count'] > 0) {
             $cost_per_click = $IN['cost'] / $IN['clicks_count'];
         } else {
             $cost_per_click = 0;
         }
     } else {
         if ($IN['clicks_count'] > 0) {
             $cost_per_click = convert_currency($IN['cost'], $IN['currency_id'], $main_currency_id, $IN['date_start'], $IN) / $IN['clicks_count'];
         } else {
             $cost_per_click = 0;
         }
     }
     $result = mysql_query($sql);
     $arr_ids = array();
     while ($row = mysql_fetch_assoc($result)) {
         $arr_ids[] = $row['id'];
     }
     $sql = "update tbl_clicks set tbl_clicks.click_price='" . _str($cost_per_click) . "' where id IN (" . implode(',', $arr_ids) . ")";
     mysql_query($sql);
     exit;
     break;
 case 'change_current_timezone':
     change_current_timezone($_REQUEST['id']);
            echo gettext("DID Montly Use");
        }
        if ($data[4] == 3) {
            echo gettext("Subscription Fee");
        }
        if ($data[4] == 4) {
            echo gettext("Extra Charges");
        }
        ?>
			  </font> </td>
  			  <td width="43%" ><font color="#003399"><?php 
        echo $data[7];
        ?>
</font></td>			 
              <td width="18%" align="right" ><font color="#003399"><?php 
        echo convert_currency($currencies_list, $data[3], $data[6], BASE_CURRENCY) . " " . BASE_CURRENCY;
        ?>
</font></td>
            </tr>
			 <?php 
    }
    //for loop end here
    ?>
			 <tr >
              <td width="20%" >&nbsp;</td>
              <td width="19%" >&nbsp;</td>
              <td width="43%" >&nbsp; </td>			 
			  <td width="18%" >&nbsp; </td>
			  
            </tr>
            <tr bgcolor="#CCCCCC" >
Example #19
0
 function process_conversion($data)
 {
     // Default account currency id: 16; RUB
     $main_currency_id = 16;
     $cnt = count($this->params);
     $i = 0;
     $is_lead = isset($data['is_lead']) ? 1 : 0;
     $is_sale = isset($data['is_sale']) ? 1 : 0;
     unset($data['is_lead']);
     unset($data['is_sale']);
     $arr_currencies = get_active_currencies();
     $conversion_currency_code = strtoupper($data['txt_param20']);
     if ($conversion_currency_code == 'RUB') {
         $conversion_currency_code = 'RUR';
     }
     $conversion_currency_id = 0;
     foreach ($arr_currencies as $id => $cur) {
         if ($cur['code'] == $conversion_currency_code) {
             $conversion_currency_id = $id;
         }
     }
     // Currency is not found in active, use default currency
     if ($conversion_currency_id == 0) {
         $conversion_currency_id = $main_currency_id;
     }
     if ($conversion_currency_id == $main_currency_id) {
         $conversion_profit = $data['profit'];
     } else {
         $conversion_profit = convert_currency($data['profit'], $conversion_currency_id, $main_currency_id, date('Y-m-d'));
     }
     $conversion_profit_currency = $data['profit'];
     // Специальная обработка "статусного постбэка" от сети CTR.
     // В этом случае приходит только статус, связанный с остальными данными через order_id (i3)
     // и нужно поменять статус соостветствующей конвертации.
     $ctr_order = false;
     // флаг, о том, что некоторые операции (замену логов) выполнять не нужно,
     // так как это не полный запрос, а только статус
     if ($data['network'] == 'CTR' and !empty($data['status'])) {
         $q = 'SELECT * FROM `tbl_conversions` WHERE (`i3` = "' . mysql_real_escape_string($data['i3']) . '"
         AND `network` = "CTR") LIMIT 1';
         if ($rs = db_query($q) and mysql_num_rows($rs) > 0) {
             $r = mysql_fetch_assoc($rs);
             $data['subid'] = $r['subid'];
         }
         dmp($data);
         foreach ($data as $k => $v) {
             if (!in_array($k, array('network', 'i3', 'status', 'txt_status', 'ak', 'date_add', 'subid'))) {
                 unset($data[$k]);
             }
         }
         $ctr_order = true;
     }
     if (isset($data['subid']) && $data['subid'] != '') {
         $table = 'tbl_clicks';
         $subid = $data['subid'];
         // мы скоро обнулим массив data, а subid нам ещё понадобится
         $status = $data['status'];
         // Проверяем есть ли клик с этим SibID
         $q = 'SELECT `id`, `is_sale`, `is_lead` FROM `' . $table . '` WHERE `subid` = "' . mysql_real_escape_string($subid) . '"';
         $r = mysql_query($q) or die($q . '<br />' . mysql_error());
         if (mysql_num_rows($r) > 0) {
             $f = mysql_fetch_assoc($r);
             $click_id = $f['id'];
             if ($data['profit'] > 0) {
                 $is_lead = $f['is_lead'] > 0 ? 1 : 0;
                 $is_sale = 1;
             } else {
                 $is_lead = 1;
                 $is_sale = $f['is_sale'] > 0 ? 1 : 0;
             }
             $q = "UPDATE `" . $table . "` SET\n                `is_sale` = " . intval($is_sale) . ",\n                `is_lead` = " . intval($is_lead) . ",\n                `conversion_currency_sum` = '" . mysql_real_escape_string($conversion_profit_currency) . "',\n                `conversion_currency_id` = '" . mysql_real_escape_string($conversion_currency_id) . "',\n                `conversion_price_main` = '" . mysql_real_escape_string($conversion_profit) . "'\n                WHERE `id` = '" . mysql_real_escape_string($click_id) . "'";
             mysql_query($q) or die(mysql_error());
         }
         // ----------------------------
         // Готовим данные для конверсии
         // ----------------------------
         $upd = array();
         // Инициализируем массив для запроса на обновление
         // Дополнительные поля, которых нет в $params, но которые нам нужны в БД
         $additional_fields = array('date_add', 'txt_status', 'status', 'network', 'type');
         foreach ($data as $name => $value) {
             if (array_key_exists($name, $this->params) or in_array($name, $additional_fields)) {
                 $upd[$name] = $value;
                 unset($data[$name]);
             }
         }
         $upd['date_add'] = mysql_now();
         // date('Y-m-d H:i:s');
         $upd['profit'] = $conversion_profit;
         $upd['currency_id'] = $conversion_currency_id;
         $upd['profit_currency'] = $conversion_profit_currency;
         // Проверяем, есть ли уже конверсия с таким SubID
         $q = "SELECT * FROM `tbl_conversions` WHERE `subid` = '" . mysql_real_escape_string($subid) . "' LIMIT 1";
         $r = db_query($q) or die(mysql_error());
         if (mysql_num_rows($r) > 0) {
             $f = mysql_fetch_assoc($r);
             $upd['id'] = $conv_id = $f['id'];
             $q = updatesql($upd, 'tbl_conversions', 'id');
             db_query($q);
             // Чистим логи
             if (!$ctr_order) {
                 db_query('DELETE FROM `tbl_postback_params` WHERE `conv_id` = ' . $f['id']) or die(mysql_error());
             }
         } else {
             $q = insertsql($upd, 'tbl_conversions');
             db_query($q);
             $conv_id = mysql_insert_id();
         }
         // Нужно ли нам отменить продажу?
         if ($status == 2) {
             delete_sale($click_id, $conv_id, 'sale');
         }
         // Пишем postback логи
         foreach ($data as $name => $value) {
             if (strpos($name, 'pbsave_') !== false) {
                 $name = str_replace('pbsave_', '', $name);
                 $ins = array('conv_id' => $conv_id, 'name' => $name, 'value' => value);
                 $q = insertsql($ins, 'tbl_postback_params');
                 db_query($q);
             }
         }
     }
 }
Example #20
0
/**
 * Get the currency exchange rate.
 * Gets the exchange rate of one currency to another.
 *
 * @since 	1.0.0
 *
 * @param  string $currency       Currency code to convert from.
 * @param  string $other_currency Currency code to convert to.
 * @return float|int
 */
function get_exchange_rate($currency, $other_currency)
{
    $currency = strtoupper($currency);
    $other_currency = strtoupper($other_currency);
    $rate = $currency == $other_currency ? 1 : convert_currency(1, $currency, $other_currency);
    return $rate;
}
     $sql .= " LIMIT {$groupcard} OFFSET " . $page * $groupcard;
 } else {
     $sql .= " LIMIT " . $page * $groupcard . ", {$groupcard}";
 }
 if ($verbose_level >= 1) {
     echo "==> SELECT CARD QUERY : {$sql}\n";
 }
 $result_card = $instance_table->SQLExec($A2B->DBHandle, $sql);
 foreach ($result_card as $mycard) {
     if ($verbose_level >= 1) {
         print_r($mycard);
     }
     if ($verbose_level >= 1) {
         echo "------>>>  ID = " . $mycard[0] . " - CARD =" . $mycard[3] . " - BALANCE =" . $mycard[1] . " \n";
     }
     $amount_converted = convert_currency($currencies_list, $myservice_fee, strtoupper($myservice_cur), strtoupper($mycard[2]));
     if ($verbose_level >= 1) {
         echo "AMOUNT TO REMOVE FROM THE CARD ->" . $amount_converted;
     }
     if (abs($amount_converted) > 0) {
         // CHECK IF WE HAVE AN AMOUNT TO REMOVE
         $QUERY = "UPDATE cc_card SET credit=credit-'" . $amount_converted . "' WHERE id=" . $mycard[0];
         $result = $instance_table->SQLExec($A2B->DBHandle, $QUERY, 0);
         if ($verbose_level >= 1) {
             echo "==> UPDATE CARD QUERY: \t{$QUERY}\n";
         }
         // ADD A CHARGE
         $QUERY = "INSERT INTO cc_charge (id_cc_card, id_cc_subscription_fee, chargetype, amount, currency, description) " . "VALUES ('" . $mycard[0] . "', '{$myservice_id}', '3', '{$amount_converted}', '" . strtoupper($mycard[2]) . "','" . $mycard[5] . ' - ' . $myservice_label . "')";
         $result_insert = $instance_table->SQLExec($A2B->DBHandle, $QUERY, 0);
         if ($verbose_level >= 1) {
             echo "==> INSERT CHARGE QUERY={$QUERY}\n";