Exemple #1
0
 public static function send($content, $mobile)
 {
     require_once 'sender_qixintong.php';
     //即时发送
     $res = sendSMS(self::uid, self::pwd, $mobile, $content);
     return $res;
 }
 /**
  * 根据注册用户的手机号,获取手机验证码
  * @param $tel
  */
 public function getSmsCode($tel)
 {
     //生成随机的短信验证码
     $smsCode = \Org\Util\String::randNumber(1000, 9999);
     //将手机验证码存入redis中,当前手机号作为键.用作后面的验证
     S($tel, $smsCode, 60);
     //发送验证信息
     sendSMS('注册验证', '{"code":"' . $smsCode . '","product":"京西商城"}', $tel, 'SMS_4730837');
 }
 /**
  * 获取短信的验证码
  * @param $tel
  */
 public function getSMSCode($tel)
 {
     //随机码
     $str = String::randNumber(1000, 9999);
     //>>1.将验证码保存到redis中.保存30秒
     S($tel, $str, 300);
     //>>2.发送短信
     sendSMS('注册验证', '{"code":"' . $str . '","product":"京西商城"}', $tel, 'SMS_2245271');
 }
Exemple #4
0
 function send()
 {
     sendSMS(array($this->phone), $this->message, $this->w->Auth->user()->login);
     // always store a fresh line item
     $this->dt_created = null;
     $this->creator_id = null;
     $this->id = null;
     $this->insert();
 }
Exemple #5
0
function send_sms_code($mobile, $str)
{
    $uid = '57141';
    //用户账号
    $pwd = 'd6m574';
    //密码
    $content = $str . ',请不要把验证码泄露给其他人。如非本人操作,可不用理会。【阿依达商贸】';
    //内容
    //即时发送
    return sendSMS($uid, $pwd, $mobile, $content);
}
Exemple #6
0
function SMSSend($mobile, $content, $mobileids = '', $time = '', $mid = '')
{
    $http = 'http://api.sms.cn/mtutf8/';
    //短信接口
    $uid = 'chaoweichuangyuan';
    //用户账号
    $pwd = 'ChaoweiUct';
    //密码
    $mobileids = $mobile . (string) rand(1000, 9999);
    return sendSMS($http, $uid, $pwd, $mobile, $content, $mobileids, $time, $mid);
}
Exemple #7
0
function sms_send_yimei($phone, $content) {
		//global $INI;
	$content = $content."【米粒团】";//短信签名自己修改
	$smslog = sms_deal($phone,$content);
	if(!$smslog){
		$res = '111';//表示发送的短信信息存入数据库失败,不执行发送请求
	}else{
		$res = sendSMS(array($phone),$content);
	}
	return trim(strval($res))=='0' ? true : strval($res);
}
Exemple #8
0
 public static function send_text()
 {
     // Simple SMS send function
     function sendSMS($username, $password, $to, $message, $originator)
     {
         $URL = 'http://api.textmarketer.co.uk/gateway/' . "?username={$username}&password={$password}&option=xml";
         $URL .= "&to={$to}&message=" . urlencode($message) . '&orig=' . urlencode($originator);
         $fp = fopen($URL, 'r');
         return fread($fp, 1024);
     }
     // Example of use
     $response = sendSMS('myUsername', 'myPassword', '4477777777', 'My test message', 'TextMessage');
     echo $response;
 }
Exemple #9
0
 function sendSMS($mobileNumber, $notificationText)
 {
     //#############################################################
     $baseURL = "https://enabler.intelligentcloud.biz/SendSmsService/OneAPI_REST_v1_0/routing";
     $version = "1";
     $relativeURL = "/" . $version . "/smsmessaging/outbound/" . urlencode($this->smsNumber) . "/requests";
     $urlString = $baseURL . $relativeURL;
     $data = array('address' => urlencode($mobileNumber), 'senderAddress' => urlencode($this->smsNumber), 'message' => urlencode($notificationText));
     $data_string = "";
     foreach ($data as $key => $value) {
         $data_string .= $key . '=' . $value . '&';
     }
     rtrim($data_string, '&');
     $obj = json_decode(sendSMS($urlString, $data_string));
     if (property_exists($obj, 'requestError')) {
         //do something, log error.
     } else {
         $confirmationURL = $obj->{'resourceReference'}->{'resourceURL'} . "/deliveryInfos";
         $this->followupSMS($confirmationURL);
     }
 }
Exemple #10
0
function sendSMSAlert($geoAssId, $devDateTime)
{
    $db = new Database(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
    $db->connect();
    $getData = "SELECT * FROM tb_assigngeofence,tb_deviceinfo,tb_geofence_info,tb_clientinfo WHERE ci_id = tag_clientId AND tgi_id = tag_geofenceId AND di_id = tag_diId AND tag_id = " . $geoAssId;
    $resData = mysql_query($getData);
    if (@mysql_affected_rows() > 0) {
        $fetData = mysql_fetch_assoc($resData);
        $from = "";
        $to = $fetData[tag_alertSrc];
        if ($fetData[di_deviceName]) {
            $devName = $fetData[di_deviceName];
        } else {
            $devName = $fetData[di_deviceId];
        }
        if ($fetData[tag_inout] == "in") {
            $status = "entered zone";
        } else {
            $status = "left zone";
        }
        $msg = "Dear " . ucfirst($fetData[ci_clientName]) . "! " . $devName . " has " . $status . " " . $fetData[tgi_name] . " at " . date("H:i:s", strtotime($devDateTime)) . " - " . $fetData[ci_weburl];
        //echo $msg;
        $smsres = sendSMS($from, $to, $msg);
        $smsdata['tsi_mobileno'] = $fetData[tag_alertSrc];
        $smsdata['tsi_tgai_id'] = $geoAssId;
        $smsdata['tsi_smsResult'] = $smsres;
        $smsdata['tsi_message'] = urlencode($msg);
        $smsdata['tsi_smsType'] = "GEOALERT";
        //print_r($smsdata);
        //exit;
        if ($db->query_insert("tb_smsinfo", $smsdata)) {
            $res = 1;
        } else {
            $res = 0;
        }
        return $res;
        //print_r($fetData);
    }
}
Exemple #11
0
function register($fname, $lname, $email, $pass, $phone, $plan)
{
    //header('Location: '.get_bloginfo('url').'/?p=r&status=good&f='.$fname.'&u='.$username.'&e='.$email.'$p='.$phone.'&pl='.$plan);
    global $wpdb;
    $username = strtolower(substr($fname, 0, 1) . $lname);
    # start by checking if the user already exists
    $row = $wpdb->get_row("SELECT * FROM userinfo WHERE username ='******' OR email = '{$email}'");
    if (!empty($row->username)) {
        header('Location: ' . get_bloginfo('url') . '/?p=r&status=bad');
    } else {
        $sql = "INSERT INTO userinfo(username,firstname,lastname,email,mobilephone) \n            \t\tVALUES('{$username}','{$fname}', '{$lname}', '{$email}', '{$phone}')";
        $sql1 = "INSERT INTO radcheck(username,attribute,op,value)\n\t\t\t\t\t VALUES('{$username}','Cleartext-Password',':=','{$pass}')";
        $date = date('d M Y', strtotime(date('d M Y') . ' +2 day'));
        $sql2 = "INSERT INTO radcheck(username,attribute,op,value)\n\t\t\t\t\t VALUES('{$username}','Expiration',':=','{$date}')";
        $sql3 = "INSERT INTO radusergroup(username,groupname)\n\t\t\t\t\tVALUES('{$username}','{$plan}')";
        $wpdb->query($sql);
        $wpdb->query($sql1);
        $wpdb->query($sql2);
        $wpdb->query($sql3);
        sendSMS($phone, $username, $pass);
        sendEmail($email, $username, $plan);
        header('Location: ' . get_bloginfo('url') . '/?p=r&status=good&f=' . $fname . '&u=' . $username . '&e=' . $email . '$p=' . $phone . '&pl=' . $plan . '&ps=' . $pass);
    }
}
Exemple #12
0
 function getListInvalidFutureBuyingOrder($OrderDate, $StockExchangeID)
 {
     // End 20100723 - Them $StockExchangeID ------------------------------------------------------- //
     $function_name = 'getListInvalidFutureBuyingOrder';
     $struct = '{urn:' . $this->class_name . '}' . $function_name . 'Struct';
     if (authenUser(func_get_args(), $this, $function_name) > 0) {
         return returnXML(func_get_args(), $this->class_name, $function_name, $this->_ERROR_CODE, $this->items, $this);
     }
     if (!required($OrderDate)) {
         $this->_ERROR_CODE = 30480;
     } elseif (!required($StockExchangeID)) {
         $this->_ERROR_CODE = 30001;
     } else {
         // $query = sprintf( "CALL sp_getListInvalidFutureBuyingOrder('%s' )", $OrderDate );
         $query = sprintf("CALL sp_getListInvalidFutureBuyingOrder('%s', '%s' )", $OrderDate, $StockExchangeID);
         $rs = $this->_MDB2_WRITE->extended->getAll($query);
         $this->_MDB2_WRITE->disconnect();
         $count = count($rs);
         for ($i = 0; $i < $count; $i++) {
             // 20100723 - Quang change ---------------------------------
             // $vip = checkVIPAccount($AccountNo);// 1: exist 0: not exist
             $vip = checkVIPAccount($rs[$i]['accountno']);
             // 1: exist 0: not exist
             // End 20100723 - Quang change -----------------------------
             if (strpos(PAGODA_ACCOUNT, $rs[$i]['accountno']) === false && $vip == 0) {
                 if ($rs[$i]['ordersideid'] == ORDER_BUY) {
                     switch ($rs[$i]['bankid']) {
                         case DAB_ID:
                             $dab =& new CDAB();
                             $dab_rs = $dab->cancelBlockMoney($rs[$i]['bankaccount'], $rs[$i]['accountno'], $rs[$i]['id'], $rs[$i]['amount']);
                             break;
                         case VCB_ID:
                             $dab =& new CVCB();
                             $newOrderID = $rs[$i]['id'] . $rs[$i]['unitcode'];
                             $dab_rs = $dab->cancelBlockMoney($rs[$i]['accountno'], $newOrderID, $rs[$i]['amount']);
                             break;
                         case NVB_ID:
                             $dab =& new CNVB();
                             $dab_rs = $dab->cancelBlockMoney(substr($rs[$i]['id'] . date("His"), 3), $rs[$i]['bankaccount'], $rs[$i]['amount'], $rs[$i]['id']);
                             break;
                         case OFFLINE:
                             $query = sprintf("CALL sp_VirtualBank_Cancel('%s', %u, %u, %f, '%s')", $rs[$i]['accountno'], OFFLINE, $rs[$i]['id'], $rs[$i]['amount'], $function_name);
                             $this->_MDB2_WRITE->connect();
                             $off_rs = $this->_MDB2_WRITE->extended->getRow($query);
                             $this->_MDB2_WRITE->disconnect();
                             $dab_rs = $off_rs['varerror'];
                             break;
                     }
                     // switch
                     if ($dab_rs == 0) {
                         $success = 1;
                     } else {
                         $success = 0;
                     }
                     $this->_MDB2_WRITE->connect();
                     $query = sprintf("CALL sp_updateFromApprovedToDeniedForFutureBuyingOrder( %u, %u )", $rs[$i]['id'], $success);
                     $update_rs = $this->_MDB2_WRITE->extended->getRow($query);
                     $this->_MDB2_WRITE->disconnect();
                 }
                 // BUY order
                 $bank_result .= $rs[$i]['accountno'] . "   " . $rs[$i]['id'] . "   " . $rs[$i]['amount'] . " --> " . $dab_rs . "\r\n";
                 $arraySMS['Phone'] = $rs[$i]['mobilephone'];
                 $OrderSide = $rs[$i]['ordersideid'] == ORDER_BUY ? "Mua" : "Ban";
                 $arraySMS['Content'] = "EPS: Lenh " . $OrderSide . " " . $rs[$i]['symbol'] . " - TK: " . $rs[$i]['accountno'] . " khong hop le do sai gia Tran/San";
                 sendSMS($arraySMS);
             }
             // PAGODA_ACCOUNT
         }
         // for
         mailSMTP('Quản lý Đặt lệnh', '*****@*****.**', '*****@*****.**', '*****@*****.**', '', 'Danh sách lệnh đặt trước không hợp lệ - StockExchangeID:' . $StockExchangeID, 'Danh sách lệnh đặt trước không hợp lệ \\r\\n <br>' . $bank_result);
         // mailSMTP('Quản lý Đặt lệnh','*****@*****.**','*****@*****.**','*****@*****.**', '', 'Danh sách lệnh đặt trước không hợp lệ - StockExchangeID:'.$StockExchangeID,'Danh sách lệnh đặt trước không hợp lệ \r\n <br>'.$bank_result);
         $filename = $_SERVER['DOCUMENT_ROOT'] . "/bank/unlock/" . date("Ymd");
         file_put_contents($filename, $bank_result);
     }
     return returnXML(func_get_args(), $this->class_name, $function_name, $this->_ERROR_CODE, $this->items, $this);
 }
Exemple #13
0
        $cat_2 = $examTypeMarks_->cat2Marks($term_id, $stud_id, $subject_id);
        $mid_term = $examTypeMarks_->midtermMarks($term_id, $stud_id, $subject_id);
        $end_term = $examTypeMarks_->endtermMarks($term_id, $stud_id, $subject_id);
        $average = $examTypeMarks_->averageGrade($term_id, $stud_id, $subject_id);
        $average = number_format($average['key1'], 1);
        $grade = $average['key2'];
        $classPosition = $examTypeMarks_->classPosition($term_id, $stud_id, $subject_id);
        $message_part2_ = strtoupper(substr($subject_name, 0, 3)) . ' :' . $average . $grade;
        $message_part2 = $message_part2 . '; ' . $message_part2_;
    }
    //end while
} else {
    echo 'No details for now.';
}
$total_Avg = number_format($total, 2);
$studentProfile_ = new studentProfile();
$meanPoints = $studentProfile_->studMeanPoints($stud_id, $term_id);
$meanPoints = $meanPoints['key2'];
$studentPosition = $studentProfile_->studentPosition($term_id, $stud_id);
$message_part3 = 'TOTAL:' . $total . ' MEAN POINTS:' . $meanPoints . ' PST:' . $studentPosition;
$message_part1 = 'NAME: ' . $fname . ' ' . $mname . ' ' . $lname . ' ' . $adminNo . ' ' . $class_name . ' ' . $term_name . ' :' . $year_name;
$message = $message_part1 . ' ' . $message_part2 . ' ' . $message_part3 . ' Sent from Nyandarua High School';
echo $message;
function sendSMS($number, $message)
{
    $Namba = urlencode($number);
    $Message = urlencode($message);
    file("http://localhost:8011/send/sms/" . $Namba . "/" . $Message . "/");
}
sendSMS($number, $message);
echo 'message sent';
 public function doSendVerify($account, $verify, $type)
 {
     switch ($type) {
         case 'mobile':
             $content = modC('SMS_CONTENT', '{$verify}', 'USERCONFIG');
             $content = str_replace('{$verify}', $verify, $content);
             $content = str_replace('{$account}', $account, $content);
             $res = sendSMS($account, $content);
             return $res;
             break;
         case 'email':
             //发送验证邮箱
             $content = modC('REG_EMAIL_VERIFY', '{$verify}', 'USERCONFIG');
             $content = str_replace('{$verify}', $verify, $content);
             $content = str_replace('{$account}', $account, $content);
             $res = send_mail($account, modC('WEB_SITE_NAME', 'OpenSNS开源社交系统', 'Config') . '邮箱验证', $content);
             return $res;
             break;
     }
 }
function tach_send_callback()
{
    global $panda;
    $ok = !empty($panda['ok_ok']) ? esc_url($panda['ok_ok']) : 'javascript:void(0);';
    $vk = !empty($panda['vk_vk']) ? esc_url($panda['vk_vk']) : 'javascript:void(0);';
    check_ajax_referer('cr-special-string', 'security');
    $phone = $_POST['phone'];
    $name = $_POST['name'];
    $text = $_POST['text'] ? $_POST['text'] : '';
    $email = !empty($panda['e_mail']) ? $panda['e_mail'] : '';
    $defaults = array('post_title' => 'Заявка на подбор репетитора c id' . $text, 'post_content' => $phone . '<br>' . $name, 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'send');
    $post_id = wp_insert_post($defaults);
    wp_mail($email, 'Заявка на подбор репетитора ' . get_home_url(), 'Вы получили новую заявку на подбор репетитора № ' . $post_id . ' Телефон клиента ' . $phone . ', Имя клиента, ' . $name . ', Репетитор -  ' . $text);
    $texte = "Садись, 5!: Ваша заявка №" . $post_id . " получена. Мы свяжемся с Вами. Наш тел: 412-413";
    sendSMS($phone, $texte);
    $date = date('G');
    if ($date > 21 && $date < 8) {
        $mess = '<br>Мы свяжемся с вами после 8:00 утра';
    } else {
        $mess = '';
    }
    echo '<a href="#" class="close"></a>
        <div class="litebox-top">Отлично!</div>
        <div class="popup-content">
            <div class="litebox-blod litebox-blod2">
                ' . $name . ', ваша заявка № ' . $post_id . ' получена. Мы перезвоним,<br>
                уточним детали и бесплатно подберем <br>
                подходящего специалиста.' . $mess . '
            </div>
            <div class="litebox-text">
                А пока подпишитесь на наши группы в социальных сетях,<br>
                чтобы узнавать новости из сферы образования и оставаться <br>
                в хорошем настроении!
            </div>
            <div class="popup-sots">
                <a href="' . $vk . '" class="vk-link2">Вконтакте</a>
                <a href="' . $ok . '" class="odnoklasniki-link2">Одноклассники</a>
            </div>
        </div>';
    wp_die();
}
Exemple #16
0
function delivery($order_id, $deliery_id, $express_no)
{
    /* 定义当前时间 */
    define('GMTIME_UTC', gmtime());
    // 获取 UTC 时间戳
    /* 取得参数 */
    $delivery = array();
    $delivery['invoice_no'] = $express_no;
    $action_note = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';
    /* 根据发货单id查询发货单信息 */
    if (!empty($delivery_id)) {
        $delivery_order = delivery_order_info($delivery_id);
    } else {
        die('order does not exist');
    }
    /* 查询订单信息 */
    $order = order_info($order_id);
    /* 检查此单发货商品库存缺货情况 */
    $virtual_goods = array();
    $delivery_stock_sql = "SELECT DG.goods_id, DG.is_real, DG.product_id, SUM(DG.send_number) AS sums, IF(DG.product_id > 0, P.product_number, G.goods_number) AS storage, G.goods_name, DG.send_number\r\n        FROM " . $GLOBALS['ecs']->table('delivery_goods') . " AS DG, " . $GLOBALS['ecs']->table('goods') . " AS G, " . $GLOBALS['ecs']->table('products') . " AS P\r\n        WHERE DG.goods_id = G.goods_id\r\n        AND DG.delivery_id = '{$delivery_id}'\r\n        AND DG.product_id = P.product_id\r\n        GROUP BY DG.product_id ";
    $delivery_stock_result = $GLOBALS['db']->getAll($delivery_stock_sql);
    /* 如果商品存在规格就查询规格,如果不存在规格按商品库存查询 */
    if (!empty($delivery_stock_result)) {
        foreach ($delivery_stock_result as $value) {
            if (($value['sums'] > $value['storage'] || $value['storage'] <= 0) && ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_SHIP || $_CFG['use_storage'] == '0' && $value['is_real'] == 0)) {
                /* 操作失败 */
                $links[] = array('text' => $GLOBALS['_LANG']['order_info'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
                sys_msg(sprintf($GLOBALS['_LANG']['act_good_vacancy'], $value['goods_name']), 1, $links);
                break;
            }
            /* 虚拟商品列表 virtual_card*/
            if ($value['is_real'] == 0) {
                $virtual_goods[] = array('goods_id' => $value['goods_id'], 'goods_name' => $value['goods_name'], 'num' => $value['send_number']);
            }
        }
    } else {
        $delivery_stock_sql = "SELECT DG.goods_id, DG.is_real, SUM(DG.send_number) AS sums, G.goods_number, G.goods_name, DG.send_number\r\n        FROM " . $GLOBALS['ecs']->table('delivery_goods') . " AS DG, " . $GLOBALS['ecs']->table('goods') . " AS G\r\n        WHERE DG.goods_id = G.goods_id\r\n        AND DG.delivery_id = '{$delivery_id}'\r\n        GROUP BY DG.goods_id ";
        $delivery_stock_result = $GLOBALS['db']->getAll($delivery_stock_sql);
        foreach ($delivery_stock_result as $value) {
            if (($value['sums'] > $value['goods_number'] || $value['goods_number'] <= 0) && ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_SHIP || $_CFG['use_storage'] == '0' && $value['is_real'] == 0)) {
                /* 操作失败 */
                $links[] = array('text' => $GLOBALS['_LANG']['order_info'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
                sys_msg(sprintf($GLOBALS['_LANG']['act_good_vacancy'], $value['goods_name']), 1, $links);
                break;
            }
            /* 虚拟商品列表 virtual_card*/
            if ($value['is_real'] == 0) {
                $virtual_goods[] = array('goods_id' => $value['goods_id'], 'goods_name' => $value['goods_name'], 'num' => $value['send_number']);
            }
        }
    }
    /* 发货 */
    /* 处理虚拟卡 商品(虚货) */
    if (is_array($virtual_goods) && count($virtual_goods) > 0) {
        foreach ($virtual_goods as $virtual_value) {
            virtual_card_shipping($virtual_value, $order['order_sn'], $msg, 'split');
        }
    }
    /* 如果使用库存,且发货时减库存,则修改库存 */
    if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_SHIP) {
        foreach ($delivery_stock_result as $value) {
            /* 商品(实货)、超级礼包(实货) */
            if ($value['is_real'] != 0) {
                //(货品)
                if (!empty($value['product_id'])) {
                    $minus_stock_sql = "UPDATE " . $GLOBALS['ecs']->table('products') . "\r\n                                        SET product_number = product_number - " . $value['sums'] . "\r\n                                        WHERE product_id = " . $value['product_id'];
                    $GLOBALS['db']->query($minus_stock_sql, 'SILENT');
                }
                $minus_stock_sql = "UPDATE " . $GLOBALS['ecs']->table('goods') . "\r\n                                    SET goods_number = goods_number - " . $value['sums'] . "\r\n                                    WHERE goods_id = " . $value['goods_id'];
                $GLOBALS['db']->query($minus_stock_sql, 'SILENT');
            }
        }
    }
    /* 修改发货单信息 */
    $invoice_no = str_replace(',', '<br>', $delivery['invoice_no']);
    $invoice_no = trim($invoice_no, '<br>');
    $_delivery['invoice_no'] = $invoice_no;
    $_delivery['status'] = 0;
    // 0,为已发货
    $query = $db->autoExecute($ecs->table('delivery_order'), $_delivery, 'UPDATE', "delivery_id = {$delivery_id}", 'SILENT');
    if (!$query) {
        /* 操作失败 */
        $links[] = array('text' => $GLOBALS['_LANG']['delivery_sn'] . $GLOBALS['_LANG']['detail'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
        sys_msg($GLOBALS['_LANG']['act_false'], 1, $links);
    }
    /* 标记订单为已确认 “已发货” */
    /* 更新发货时间 */
    $order_finish = get_all_delivery_finish($order_id);
    $shipping_status = $order_finish == 1 ? SS_SHIPPED : SS_SHIPPED_PART;
    $arr['shipping_status'] = $shipping_status;
    $arr['shipping_time'] = GMTIME_UTC;
    // 发货时间
    $arr['invoice_no'] = trim($order['invoice_no'] . '<br>' . $invoice_no, '<br>');
    update_order($order_id, $arr);
    /* 发货单发货记录log */
    order_action($order['order_sn'], OS_CONFIRMED, $shipping_status, $order['pay_status'], $action_note, null, 1);
    /* 如果当前订单已经全部发货 */
    if ($order_finish) {
        /* 如果订单用户不为空,计算积分,并发给用户;发红包 */
        if ($order['user_id'] > 0) {
            /* 取得用户信息 */
            $user = user_info($order['user_id']);
            /* 计算并发放积分 */
            $integral = integral_to_give($order);
            log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf($GLOBALS['_LANG']['order_gift_integral'], $order['order_sn']));
            /* 发放红包 */
            send_order_bonus($order_id, $order['supplier_id']);
        }
        /* 发送邮件 */
        $cfg = $_CFG['send_ship_email'];
        if ($cfg == '1') {
            $order['invoice_no'] = $invoice_no;
            $tpl = get_mail_template('deliver_notice');
            $smarty->assign('order', $order);
            $smarty->assign('send_time', local_date($_CFG['time_format']));
            $smarty->assign('shop_name', $_CFG['shop_name']);
            $smarty->assign('send_date', local_date($_CFG['date_format']));
            $smarty->assign('sent_date', local_date($_CFG['date_format']));
            $smarty->assign('confirm_url', $ecs->url() . 'receive.php?id=' . $order['order_id'] . '&con=' . rawurlencode($order['consignee']));
            $smarty->assign('send_msg_url', $ecs->url() . 'user.php?act=message_list&order_id=' . $order['order_id']);
            $content = $smarty->fetch('str:' . $tpl['template_content']);
            if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html'])) {
                $msg = $GLOBALS['_LANG']['send_mail_fail'];
            }
        }
        /* 如果需要,发短信 */
        if ($GLOBALS['_CFG']['sms_order_shipped'] == '1' && $order['mobile'] != '') {
            include_once '../send.php';
            $content = '您的订单已发货,订单号为' . $order['order_sn'] . '收货人为' . $order['consignee'] . '收货地址为' . $order['address'] . ',请注意查收【' . $GLOBALS['_CFG']['shop_name'] . '】';
            sendSMS($order['mobile'], $content);
        }
    }
    /* 清除缓存 */
    clear_cache_files();
    /* 操作成功 */
    $links[] = array('text' => $GLOBALS['_LANG']['09_delivery_order'], 'href' => 'order.php?act=delivery_list');
    $links[] = array('text' => $GLOBALS['_LANG']['delivery_sn'] . $GLOBALS['_LANG']['detail'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
    sys_msg($GLOBALS['_LANG']['act_ok'], 0, $links);
}
Exemple #17
0
/**
 * 发短信方法
 * @param array $supplierinfo   eg: array('商家id1'=>订单号)
 * @param string $content 短信内容
 * @param int    $position 调用位置   1,下订单;2,付款
 * 
 */
function send_sms($supplierinfo = '', $content = '', $position = 1)
{
    if (empty($supplierinfo) || empty($position)) {
        return;
    }
    $supplier_ids = array_keys($supplierinfo);
    global $_CFG;
    if (array_search(0, $supplier_ids) !== false) {
        if ($position == 1) {
            if ($_CFG['sms_order_placed'] == '1' && $_CFG['sms_shop_mobile'] != '') {
                $phones = explode(',', $_CFG['sms_shop_mobile']);
                array_filter($phones);
                $content1 = str_replace(array('ordersn', 'shopname'), array($supplierinfo[0], $_CFG['shop_name']), $content);
                foreach ($phones as $phone) {
                    sendSMS($phone, $content1);
                }
            }
        } elseif ($position == 2) {
            if ($_CFG['sms_order_payed'] == '1' && $_CFG['sms_shop_mobile'] != '') {
                $phones = explode(',', $_CFG['sms_shop_mobile']);
                array_filter($phones);
                $content1 = str_replace(array('ordersn', 'shopname'), array($supplierinfo[0], $_CFG['shop_name']), $content);
                foreach ($phones as $phone) {
                    sendSMS($phone, $content1);
                }
            }
        }
        array_filter($supplier_ids);
    }
    foreach ($supplier_ids as $val) {
        $info = get_supplier_info($val);
        if ($position == 1) {
            if ($info['sms_order_placed'] == '1' && $info['sms_shop_mobile'] != '') {
                $phones = explode(',', $info['sms_shop_mobile']);
                array_filter($phones);
                $content1 = str_replace(array('ordersn', 'shopname'), array($supplierinfo[$val], $_CFG['shop_name']), $content);
                foreach ($phones as $phone) {
                    sendSMS($phone, $content1);
                }
            }
        } elseif ($position == 2) {
            if ($info['sms_order_payed'] == '1' && $info['sms_shop_mobile'] != '') {
                $phones = explode(',', $info['sms_shop_mobile']);
                array_filter($phones);
                $content1 = str_replace(array('ordersn', 'shopname'), array($supplierinfo[$val], $_CFG['shop_name']), $content);
                foreach ($phones as $phone) {
                    sendSMS($phone, $content1);
                }
            }
        }
    }
}
Exemple #18
0
if ($interval < 1) {
    // интервал отправки (сек)
    jsAnswer("error", "c_error", "", "Сообщение уже было отправлено.");
} else {
    //$get_data = gF('os');
    $get_data = $_POST["cs"];
    if (count($get_data) > 1) {
        // data to send
        $os = $_POST["os"];
        $cs = $_POST["cs"];
        $ip = $_SERVER["REMOTE_ADDR"];
        $title = "Новый клиент с сайта soapland";
        $title = "=?UTF-8?B?" . base64_encode($title) . "?=";
        $mess = "";
        $mess .= getOptions(1);
        $mess = $mess . "<div style=\"background:#bfd4ac;border:1px solid #999;padding:10px;margin: 10px 0;\">IP: " . $ip . " / <a href='http://dedushka.org/whois/#" . $ip . "'>Определить город</a></div>";
        $headers = "Content-type: text/html; charset=utf-8\r\n";
        $headers .= "From: soapland <" . $from . ">\r\n";
        $sms['msg'] = translit(getOptions(0));
        $sms['msg'] = substr($sms['msg'], 0, 160);
        if ($to != '*****@*****.**') {
            mail($to, $title, $mess, $headers);
        }
        if ($sms['id'] != '' || $sms['key'] != '' || $sms['log'] != '') {
            @sendSMS($num, $sms['msg']);
        }
        jsAnswer('success', 'c_success', '', 'Спасибо, мы свяжемся с Вами в течении 30 минут!');
    } else {
        jsAnswer('error', 'c_error', '', 'Ошибка');
    }
}
 public function password_find_send_sms()
 {
     if ($_SESSION['find_password_user']) {
         $phone = $_SESSION['find_password_user']['user_phone'];
     } else {
         $this->error("错误");
     }
     $code = generateCode();
     if (sendSMS($phone, $code)) {
         $this->success('发送成功,请注意查收短信');
     } else {
         $this->error('未知错误,短信发送失败,请联系hmv客服');
     }
 }
Exemple #20
0
}
$result = mysqli_query($db_handle, "Update users set md5_id = MD5(" . $input->root->user_id . ") where id = " . $input->root->user_id);
$sql = "INSERT INTO `bluenet_v3`.`user_documents` (`id`,  `user_id`, `adhar_card`, `voter_id`, `driving_license`, `pan_card`)\n\t\t\t\tVALUES (NULL,\n\t\t\t\t\t'" . $input->root->user_id . "',\n\t\t\t\t\t '" . $input->root->adhar_card . "',\n\t\t\t\t\t  '" . $input->root->voter_card . "',\n\t\t\t\t\t   '" . $input->root->driving_license . "',\n\t\t\t\t\t\t'" . $input->root->pan_card . "');";
$result = mysqli_query($db_handle, $sql);
/*INSERT INTO `bluenet_v3`.`workers` (`id`, `ref_id`, `user_id`, `status`, `emergency_no`, `native_place`, `native_add`, `dob`, `education`, `experience`, `gender`, `remark`, `salary`, `bonus`) VALUES
	(NULL, '1', '3', 'new', '9090909090', 'delhi', 'asdf', '2016-04-05', '10', '5', 'M', 'afsdv', '1000', '2');*/
$sql = "INSERT INTO `bluenet_v3`.`workers` (`id`, `ref_id`, `user_id`, `status`, `emergency_no`, `native_place`,\n\t\t\t\t\t\t\t\t`native_add`, `dob`, `education`, `experience`, `gender`, `remark`, `salary`, `bonus`)\n\t\t\t\tVALUES (NULL,\n\t\t\t\t\t'" . $input->root->ref_id . "',\n\t\t\t\t\t'" . $input->root->user_id . "',\n\t\t\t\t\t 'new',\n\t\t\t\t\t '" . $input->root->emergency_no . "',\n\t\t\t\t\t  '" . $input->root->native_place . "',\n\t\t\t\t\t   '" . $input->root->native_add . "',\n\t\t\t\t\t\t'" . $input->root->dob . "',\n\t\t\t\t\t\t '" . $input->root->education . "',\n\t\t\t\t\t\t '" . $input->root->experience . "',\n\t\t\t\t\t\t  '" . $input->root->gender . "',\n\t\t\t\t\t\t   '" . $input->root->remark . "',\n\t\t\t\t\t\t\t'" . $input->root->salary . "',\n\t\t\t\t\t\t\t '" . $input->root->bonus . "');";
$result = mysqli_query($db_handle, $sql);
$input->root->id = mysqli_insert_id($db_handle);
/*
 * INSERT INTO `bluenet_v3`.`worker_working_timings`
 * (`id`, `worker_id`, `start_time`, `end_time`, `creation`, `last_update`, `status`, `gps_location`, `device_id`)
 * VALUES
 * (NULL, '1', '12:10:38', '09:37:42', CURRENT_TIME(), '2016-04-12 00:00:00', '1', '123.123,321.123', '2asfd');*/
foreach ($input->root->timings as $timing) {
    $sql = "INSERT INTO `bluenet_v3`.`worker_working_timings`\n\t\t\t\t\t(`id`, `worker_id`, `start_time`, `end_time`, `creation`,  `status`, `gps_location`, `device_id`)\n\t\t\t\t\tVALUES (NULL,\n\t\t\t\t\t'" . $input->root->id . "',\n\t\t\t\t\t '" . $timing->start_time . "',\n\t\t\t\t\t '" . $timing->end_time . "',\n\t\t\t\t\t '" . date("Y-m-d H:i:s") . "',\n\t\t\t\t\t '1',\n\t\t\t\t\t '" . $input->root->gps_location . "',\n\t\t\t\t'" . $input->root->device_id . "'\n\t\t\t\t);";
    $result = mysqli_query($db_handle, $sql);
}
/*
 *
 * INSERT INTO `bluenet_v3`.`service_worker_mappings`
 * 	(`id`, `worker_id`, `service_id`, `creation`) VALUES ('', '1', '2', CURRENT_TIMESTAMP);
 * */
foreach ($input->root->services as $service) {
    $sql = "INSERT INTO `bluenet_v3`.`service_worker_mappings`\n\t\t\t\t(`id`, `worker_id`, `service_id`)\n\t\t\t\t\tVALUES ('',\n\t\t\t\t\t'" . $input->root->id . "',\n\t\t\t\t\t '" . $service . "'\n\t\t\t\t\t );";
    $result = mysqli_query($db_handle, $sql);
}
print json_encode($input);
$message = "Dear " . $input->root->name . ", we have received your registration request. Your username:  "******" , Password: "******" at " . date("Y-m-d H:i:s");
sendSMS($input->root->mobile, $message);
    $data['phoneNumber'] = $phone;
    $data['amount'] = "KES " . $latest_order_amount;
    array_push($recipients, $data);
    //sending the airtime
    sendAirtime($recipients);
    //reduce the user balance by the sent airtime amount
    $balance = $new_balance - $latest_order_amount;
    // and update user balance
    updateUserBalance($user['id'], $balance);
    updateOrderStatus($order['id']);
    echo "your airtime is on its way";
    exit;
} else {
    //send SMS telling the user that he doesn't have sufficient money for the order
    $message = "Hey you, your have insufficient funds to proceed with this transaction";
    sendSMS($phone, $message);
    echo "Check your phone for an SMS";
    exit;
}
//top up the users account
//from the users account, remove amount equal to the airtime ordered
///send airtime
//nouns orders, users, account, airtime,
//verbs top up, store, make payments, send airtime
//users - phone, balance,
//order - user_id, amount, status
//transaction_log
//update order status
function updateOrderStatus($order_id)
{
    return mysql_query("UPDATE airtime_orders SET status=1 WHERE id='{$order_id}'");
Exemple #22
0
function action_send_mobile_code()
{
    // 获取全局变量
    $user = $GLOBALS['user'];
    $_CFG = $GLOBALS['_CFG'];
    $_LANG = $GLOBALS['_LANG'];
    $smarty = $GLOBALS['smarty'];
    $db = $GLOBALS['db'];
    $ecs = $GLOBALS['ecs'];
    $user_id = $_SESSION['user_id'];
    /* 载入语言文件 */
    require_once ROOT_PATH . 'languages/' . $_CFG['lang'] . '/user.php';
    require_once ROOT_PATH . 'includes/lib_validate_record.php';
    $mobile_phone = trim($_REQUEST['mobile_phone']);
    if (empty($mobile_phone)) {
        exit("手机号不能为空");
        return;
    } else {
        if (!is_mobile_phone($mobile_phone)) {
            exit("手机号格式不正确");
            return;
        } else {
            if (check_validate_record_exist($mobile_phone)) {
                // 获取数据库中的验证记录
                $record = get_validate_record($mobile_phone);
                /**
                 * 检查是过了限制发送短信的时间
                 */
                $last_send_time = $record['last_send_time'];
                $expired_time = $record['expired_time'];
                $create_time = $record['create_time'];
                $count = $record['count'];
                // 每天每个手机号最多发送的验证码数量
                $max_sms_count = 10;
                // 发送最多验证码数量的限制时间,默认为24小时
                $max_sms_count_time = 60 * 60 * 24;
                if (time() - $last_send_time < 60) {
                    echo "每60秒内只能发送一次短信验证码,请稍候重试";
                    return;
                } else {
                    if (time() - $create_time < $max_sms_count_time && $record['count'] > $max_sms_count) {
                        echo "您发送验证码太过于频繁,请稍后重试!";
                        return;
                    } else {
                        $count++;
                    }
                }
            }
        }
    }
    require_once ROOT_PATH . 'includes/lib_passport.php';
    // 设置为空
    $_SESSION['mobile_register'] = array();
    require_once ROOT_PATH . 'sms/sms.php';
    // 生成6位短信验证码
    $mobile_code = rand_number(6);
    // 短信内容
    $content = sprintf($_LANG['mobile_code_template'], $GLOBALS['_CFG']['shop_name'], $mobile_code, $GLOBALS['_CFG']['shop_name']);
    /* 发送激活验证邮件 */
    // $result = true;
    $result = sendSMS($mobile_phone, $content);
    if ($result) {
        if (!isset($count)) {
            $ext_info = array("count" => 1);
        } else {
            $ext_info = array("count" => $count);
        }
        // 保存手机号码到SESSION中
        $_SESSION[VT_MOBILE_REGISTER] = $mobile_phone;
        // 保存验证信息
        save_validate_record($mobile_phone, $mobile_code, VT_MOBILE_REGISTER, time(), time() + 30 * 60, $ext_info);
        echo 'ok';
    } else {
        echo '短信验证码发送失败';
    }
}
Exemple #23
0
    if (empty($mobile)) {
        exit(json_encode(array('msg' => '手机号码不能为空')));
    }
    $preg = '/^1[0-9]{10}$/';
    // 简单的方法
    if (!preg_match($preg, $mobile)) {
        exit(json_encode(array('msg' => '手机号码格式不正确')));
    }
    $mobile_code = random(6, 1);
    $content = sprintf($GLOBALS['_CFG']['sms_register_tpl'], $mobile_code, $GLOBALS['_CFG']['sms_sign']);
    if ($_SESSION['mobile']) {
        if (strtotime(read_file($mobile)) > time() - 60) {
            exit(json_encode(array('msg' => '获取验证码太过频繁,一分钟之内只能获取一次。')));
        }
    }
    $num = sendSMS($mobile, $content);
    if ($num == true) {
        $_SESSION['mobile'] = $mobile;
        $_SESSION['mobile_code'] = $mobile_code;
        $_SESSION['time'] = time();
        exit(json_encode(array('code' => 2)));
    } else {
        exit(json_encode(array('msg' => '手机验证码发送失败。')));
    }
}
function sendSMS($mobile, $content, $time = '', $mid = '')
{
    $content = iconv('utf-8', 'gbk', $content);
    $http = 'http://http.yunsms.cn/tx/';
    // 短信接口
    $uid = '57137';
Exemple #24
0
$proxyport = false;
$proxyusername = false;
$proxypassword = false;
$client = new Client($gwUrl, $serialNumber, $password, $sessionKey, $proxyhost, $proxyport, $proxyusername, $proxypassword, $connectTimeOut, $readTimeOut);
/**
 * 发送向服务端的编码,如果本页面的编码为GBK,请使用GBK
 */
$client->setOutgoingEncoding("UTF-8");
// login();   //激活序列号
// updatePassword();  //修改密码
// logout();          //注销序列号
// registDetailInfo();//注册企业信息
// getEachFee();      //得到单价
// getMO();           //接收短信
// getVersion();      //得到版本号
sendSMS();
//发送短信
// getBalance();      //得到余额
// chargeUp();        //充值
//----------------------------------------------------------------------
// 注:
// 1. 下面是各接口的使用用例,Client.php 还有每一个接口更详细的参数说明
// 2. 凡是返回 $statusCode 的, 都是相关操作的状态码
// 3. 由于php是弱类型语言,当服务端没返回时,也会等同认为 $statusCode=='0', 所以在判断时应该使用 if ($statusCode!=null && $statusCode==0)
//----------------------------------------------------------------------
/**
 * 接口调用错误查看 用例
 */
function chkError()
{
    global $client;
 function confirmBuyOrderForVirtualBank($TradingDate, $BankID)
 {
     $function_name = 'confirmBuyOrderForVirtualBank';
     $struct = '{urn:' . $this->class_name . '}' . $function_name . 'Struct';
     if (authenUser(func_get_args(), $this, $function_name) > 0) {
         return returnXML(func_get_args(), $this->class_name, $function_name, $this->_ERROR_CODE, $this->items, $this);
     }
     if (!required($TradingDate) || !required($BankID)) {
         if (!required($TradingDate)) {
             $this->_ERROR_CODE = 34440;
         }
         if (!required($BankID)) {
             $this->_ERROR_CODE = 34441;
         }
     } else {
         $query = sprintf("CALL sp_VirtualBank_Auction('%s', %u)", $TradingDate, $BankID);
         $rs = $this->_MDB2_WRITE->extended->getRow($query);
         if (empty($rs)) {
             $this->_ERROR_CODE = 34442;
         } else {
             $result = $rs['varerror'];
             if ($result < 0) {
                 switch ($result) {
                     case '-1':
                         $this->_ERROR_CODE = 34443;
                         break;
                     case '-2':
                         $this->_ERROR_CODE = 34444;
                         break;
                 }
             } else {
                 $query = sprintf("CALL sp_VirtualBank_getInfoForSMS('%s',4)", date('Y-m-d'));
                 $this->_MDB2->connect();
                 $result = $this->_MDB2->extended->getAll($query);
                 $this->_MDB2->disconnect();
                 $count = count($result);
                 $log = sprintf("Query: %s => Count: %s\n", $query, $count);
                 for ($i = 0; $i < $count; $i++) {
                     $mbnumber = $result[$i]['mobilephone'];
                     $amount = $result[$i]['amount'];
                     $usableamount = $result[$i]['currentbalance'];
                     if (!empty($mbnumber)) {
                         $message = 'Tai khoan cua quy khach tai KIS da thay doi: -' . number_format($amount, 0, '.', ',') . '. Thanh toan tien mua ck';
                         $message .= '. So du hien tai la: ' . number_format($usableamount, 0, '.', ',');
                         sendSMS(array('Phone' => $mbnumber, 'Content' => $message));
                     }
                     $log .= sprintf("\tMB: %s;Amount: %s;UsableAmount: %s\n", $mbnumber, $amount, $usableamount);
                 }
                 write_log($function_name, $log, 'bank/virtual/function/');
             }
         }
     }
     return returnXML(func_get_args(), $this->class_name, $function_name, $this->_ERROR_CODE, $this->items, $this);
 }
Exemple #26
0
             $res = sendSMS($message, $phonename, $userid);
             $array[] = array('url' => $url, "postdata" => "phone={$phone}");
             if ($res['error'] == 0) {
                 $flag = 1;
                 $sendresult = "发送成功";
             } else {
                 $flag = 0;
                 $sendresult = "发送失败" . $res['message'];
             }
             //saveSmsLog($userid,$membername,$phone,$message,$flag,$sendresult,$nowdatetime);
         }
     }
     if ($smstouser == 'on') {
         if (!empty($phone_mobile)) {
             $phonename = array('phone' => $phone_mobile, 'name' => '自己');
             $res = sendSMS($message, $phonename, $userid);
             $array[] = array('url' => $url, "postdata" => "phone={$phone_mobile}");
             if ($res == '') {
                 $flag = 1;
                 $sendresult = "发送成功";
             } else {
                 $flag = 0;
                 $sendresult = "发送失败" . $res['message'];
             }
             //saveSmsLog($userid,"自己",$phone_mobile,$message,$flag,$sendresult,$nowdatetime);
         }
     }
 }
 //on
 if ($email_type == 'on') {
     $email_bt = explode('$', $autoact_email_bt);
Exemple #27
0
                 $content = $smarty->fetch('str:' . $tpl['template_content']);
                 if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html'])) {
                     $msg = $_LANG['send_mail_fail'];
                 }
             }
             /* 如果需要,发短信 */
             if ($GLOBALS['_CFG']['sms_order_shipped'] == '1' && ($order['mobile'] != '' || $order['tel'] != '')) {
                 $arrse = $_SESSION;
                 include_once '../sms/sms.php';
                 if ($order['mobile'] != '') {
                     $mobi = $order['mobile'];
                 } else {
                     $mobi = $order['tel'];
                 }
                 $content = "您的订单" . $order['order_sn'] . "已于" . local_date("Y-m-d H:i:s", time()) . "发货。【68ecshop】";
                 sendSMS($mobi, $content);
                 foreach ($arrse as $key => $asei) {
                     $_SESSION[$key] = $asei;
                 }
             }
         }
         /* 清除缓存 */
         clear_cache_files();
         /* 操作成功 */
         $links[] = array('text' => $_LANG['03_delivery_order'], 'href' => 'order.php?act=delivery_list');
         $links[] = array('text' => $_LANG['delivery_sn'] . $_LANG['detail'], 'href' => 'order.php?act=delivery_info&delivery_id=' . $delivery_id);
         sys_msg($_LANG['act_ok'], 0, $links);
     }
 } elseif (isset($_POST['pay'])) {
     /* 检查权限 */
     admin_priv('order_ps_edit');
Exemple #28
0
function tratarDados($dados)
{
    $con = mysql_connect("cloudservice.cgejdsdl842e.sa-east-1.rds.amazonaws.com", "gpstracker", "d1\$1793689");
    if ($con !== false) {
        mysql_select_db('tracker', $con);
        $gpsSignalIndicator = 'F';
        $latitudeDecimalDegrees = $dados[1];
        $longitudeDecimalDegrees = $dados[2];
        $latitudeHemisphere = $dados[3];
        $longitudeHemisphere = $dados[4];
        $speed = $dados[5];
        $imei = $dados[6];
        $satelliteFixStatus = 'A';
        $phone = '';
        $infotext = $dados[8];
        $dataBem = null;
        $dataCliente = null;
        $ligado = count($dados) > 9 ? $dados[9] : 'N';
        $ativo = count($dados) > 10 ? $dados[10] : 'N';
        $realTime = count($dados) > 11 ? $dados[11] : '';
        //D para diferencial
        $gpsSignalIndicator = $dados[0] == 'S' ? 'F' : 'L';
        //Otavio Gomes - 200120152137
        // Estava aqui o problema do crx1 so enviar o sinal S.
        if ($realTime == 'D') {
            $gpsSignalIndicator = 'D';
        } else {
            $gpsSignalIndicator = 'R';
        }
        $resBem = mysql_query("SELECT id, cliente, envia_sms, name, hodometro, alerta_hodometro, alerta_hodometro_saldo, limite_velocidade FROM bem WHERE imei = '{$imei}'", $con);
        //echo 'Ligado: '.$ligado;
        $dataBem = mysql_fetch_assoc($resBem);
        if ($resBem !== false) {
            $resCliente = mysql_query("SELECT id, celular, dt_ultm_sms, envia_sms, sms_acada, hour(TIMEDIFF(now(), dt_ultm_sms)) horas, minute(TIMEDIFF(now(), dt_ultm_sms)) minutos, nome, email FROM cliente WHERE id = " . $dataBem['cliente'], $con);
            if ($resCliente !== false) {
                $dataCliente = mysql_fetch_assoc($resCliente);
                $texto_sms_localiza = "";
                $texto_sms_alerta_hodometro = "";
                $texto_sms_alerta = "";
                $result = mysql_query("SELECT * FROM preferencias", $con);
                if (mysql_num_rows($result) > 0) {
                    while ($dataPref = mysql_fetch_assoc($result)) {
                        if ($dataPref['nome'] == 'texto_sms_localiza') {
                            $texto_sms_localiza = $dataPref['valor'];
                        }
                        if ($dataPref['nome'] == 'texto_sms_alerta_hodometro') {
                            $texto_sms_alerta_hodometro = $dataPref['valor'];
                        }
                        if ($dataPref['nome'] == 'texto_sms_alerta') {
                            $texto_sms_alerta = $dataPref['valor'];
                        }
                    }
                }
                $movimento = '';
                if ($speed > 0) {
                    $movimento = 'S';
                    if ($dataBem['limite_velocidade'] != "0" && $dataBem['limite_velocidade'] != null && $speed > $dataBem['limite_velocidade']) {
                        if (!checkAlerta($imei, 'Limite Velocidade')) {
                            mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Limite Velocidade')", $con);
                            $msgEmail = "<p><b>Alerta de Limite de Velocidade: </b></p><br><p>O veículo " . $dataBem['name'] . " está trafegando com velocidade de " . $speed . " Km/h, ultrapassando o limite de velocidade definido (" . $dataBem['limite_velocidade'] . " Km/h) em " . date("d/m/Y") . " às " . date("H:i:s") . ".</p><br><i>Equipe InovarSat</i>";
                            enviaEmail($dataCliente['email'], "Alerta de Limite de Velocidade", $msgEmail);
                        }
                    }
                } else {
                    $movimento = 'N';
                }
                // CERCA VIRTUAL
                if ($imei != "") {
                    $consulta = mysql_query("SELECT * FROM geo_fence WHERE imei = '{$imei}'", $con);
                    while ($data = mysql_fetch_assoc($consulta)) {
                        $idCerca = $data['id'];
                        $imeiCerca = $data['imei'];
                        $nomeCerca = $data['nome'];
                        $coordenadasCerca = $data['coordenadas'];
                        $resultCerca = $data['tipo'];
                        $tipoEnvio = $data['tipoEnvio'];
                        $lat_point = $latitudeDecimalDegrees;
                        $lng_point = $longitudeDecimalDegrees;
                        $exp = explode("|", $coordenadasCerca);
                        if (count($exp) < 5) {
                            $strExp = explode(",", $exp[0]);
                            $strExp1 = explode(",", $exp[2]);
                        } else {
                            $int = count($exp) / 2;
                            $strExp = explode(",", $exp[0]);
                            $strExp1 = explode(",", $exp[$int]);
                        }
                        $lat_vertice_1 = $strExp[0];
                        $lng_vertice_1 = $strExp[1];
                        $lat_vertice_2 = $strExp1[0];
                        $lng_vertice_2 = $strExp1[1];
                        if ($lat_vertice_1 < $lat_point or $lat_point < $lat_vertice_2 and $lng_point < $lng_vertice_1 or $lng_vertice_2 < $lng_point) {
                            $result = '0';
                            $situacao = 'fora';
                        } else {
                            $result = '1';
                            $situacao = 'dentro';
                        }
                        if ($result == 0 and $movimento == 'S') {
                            if (!checkAlerta($imei, 'Cerca Violada')) {
                                mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca Violada')", $con);
                                if ($tipoEnvio == 0) {
                                    # Convert the GPS coordinates to a human readable address
                                    /*$tempstr = "http://maps.google.com/maps/geo?q=$lat_point,$lng_point&oe=utf-8&sensor=true&key=ABQIAAAAFd56B-wCWVpooPPO7LR3ihTz-K-sFZ2BISbybur6B4OYOOGbdRShvXwdlYvbnwC38zgCx2up86CqEg&output=csv"; //output = csv, xml, kml, json
                                    		$rev_geo_str = file_get_contents($tempstr);
                                    		$rev_geo_str = preg_replace("/\"/","", $rev_geo_str);
                                    		$rev_geo = explode(',', $rev_geo_str);
                                    		$logradouro = $rev_geo[2] .",". $rev_geo[3] ;*/
                                    /*$consulta1 = mysql_query("SELECT a.*, b.* FROM cliente a INNER JOIN bem b ON a.id = b.cliente WHERE b.imei = '$imei'", $con);
                                    		
                                    		while($data = mysql_fetch_assoc($consulta1)) {
                                    			$emailDestino = $data['email'];
                                    			$nameBem = $data['name'];
                                    			$msgEmail = "<p><b>Alerta de Violação de Perímetro:</b></p><br><p>O veículo ". $nameBem .", está ". $situacao ." do perímetro ". $nomeCerca .", as ". date("H:i:s") ." do dia ". date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>";
                                    			enviaEmail($emailDestino, "Alerta de Violação de Perímetro", $msgEmail);
                                    		}*/
                                    $json = json_decode(file_get_contents("http://maps.googleapis.com/maps/api/geocode/json?latlng=" . $lat_point . "," . $lng_point . "&sensor=false"));
                                    if (isset($json->status) && $json->status == 'OK') {
                                        $address = $json->results[0]->formatted_address;
                                        $address = utf8_decode($address);
                                    }
                                    //else echo $json->status;
                                    $emailDestino = $dataCliente['email'];
                                    $nameBem = $dataBem['name'];
                                    $msgEmail = "<p><b>Alerta de Violação de Perímetro: </b></p><br><p>O veículo " . $nameBem . ", está " . $situacao . " do perímetro " . $nomeCerca . ", transitando na " . $address . " às " . date("H:i:s") . " do dia " . date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>";
                                    enviaEmail($emailDestino, "Alerta de Violação de Perímetro", $msgEmail);
                                }
                            }
                        }
                    }
                }
                //FIM CERCA VIRTUAL
                # Write it to the database...
                if ($gpsSignalIndicator != 'L' && !empty($latitudeDecimalDegrees)) {
                    $gpsLat = $latitudeDecimalDegrees;
                    //gprsToGps($latitudeDecimalDegrees, $latitudeHemisphere)
                    $gpsLon = $longitudeDecimalDegrees;
                    //gprsToGps($longitudeDecimalDegrees, $longitudeHemisphere)
                    $gpsLatAnt = 0;
                    $gpsLatHemAnt = '';
                    $gpsLonAnt = 0;
                    $gpsLonHemAnt = '';
                    $alertaACadaSaldo = 0;
                    $resLocAtual = mysql_query("SELECT id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM loc_atual WHERE imei = '{$imei}' LIMIT 1", $con);
                    $numRows = mysql_num_rows($resLocAtual);
                    if ($numRows == 0) {
                        mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 0, '{$ligado}')", $con);
                    } else {
                        mysql_query("UPDATE loc_atual SET date = now(), phone = '{$phone}', satelliteFixStatus = '{$satelliteFixStatus}', latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', speed = '{$speed}', infotext = '{$infotext}', gpsSignalIndicator = '{$gpsSignalIndicator}', converte = 0, ligado = '{$ligado}' WHERE imei = '{$imei}'", $con);
                    }
                    $distance = 0;
                    try {
                        $bemId = $dataBem['id'];
                        $countGeoDistance = mysql_query("SELECT bem FROM geo_distance WHERE bem = {$bemId}", $con);
                        if ($countGeoDistance === false || mysql_num_rows($countGeoDistance) == 0) {
                            mysql_query("INSERT INTO geo_distance (bem, tipo) VALUES({$bemId}, 'I')", $con);
                            mysql_query("INSERT INTO geo_distance (bem, tipo) VALUES({$bemId}, 'F')", $con);
                        }
                        /*envio de sms*/
                        if ($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && !empty($dataCliente['celular']) && !empty($dataCliente['sms_acada'])) {
                            if (empty($dataCliente['dt_ultm_sms'])) {
                                mysql_query("UPDATE cliente SET dt_ultm_sms = convert_tz(now(), 'GMT', 'Brazil/East') WHERE id = " . $dataCliente['id'], $con);
                            } else {
                                $horas = $dataCliente['horas'];
                                $minutos = $dataCliente['minutos'];
                                if (!empty($horas)) {
                                    $horas = $horas * 60;
                                }
                                $tempoTotal = $horas + $minutos;
                                if ($tempoTotal > $dataCliente['sms_acada']) {
                                    $json = json_decode(file_get_contents("http://maps.google.com/maps/api/geocode/json?sensor=false&latlng={$gpsLat},{$gpsLon}&language=es-ES"));
                                    if (isset($json->status) && $json->status == 'OK' && isset($json->results[0]->formatted_address)) {
                                        $address = $json->results[0]->formatted_address;
                                        $address = utf8_decode($address);
                                        $aDataCliente = split(' ', $dataCliente['nome']);
                                        $msg = $texto_sms_localiza;
                                        $msg = str_replace("#CLIENTE", $aDataCliente[0], $msg);
                                        $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                                        $msg = str_replace("#LOCALIZACAO", $address, $msg);
                                        $msg = str_replace(' ', '+', $msg);
                                        sendSMS($dataCliente['celular'], $msg, '');
                                        if ($retorno < 0) {
                                            mysql_query("INSERT INTO controle(texto) VALUES('envio de sms retorno: {$retorno}')", $con);
                                        } else {
                                            mysql_query("UPDATE cliente SET dt_ultm_sms = convert_tz(now(), 'GMT', 'Brazil/East') WHERE id = " . $dataCliente['id'], $con);
                                        }
                                    }
                                }
                            }
                        }
                        if ($movimento == 'S') {
                            $resGeoDistance = mysql_query("SELECT parou FROM geo_distance WHERE bem = {$bemId} AND tipo = 'I'", $con);
                            if ($resGeoDistance !== false) {
                                $dataGeoDistance = mysql_fetch_assoc($resGeoDistance);
                                if ($dataGeoDistance['parou'] == 'S' || empty($dataGeoDistance['parou'])) {
                                    mysql_query("UPDATE geo_distance SET latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', parou = 'N' WHERE bem = {$bemId} AND tipo = 'I'", $con);
                                }
                            }
                        } else {
                            $resGeoDistance = mysql_query("SELECT latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM geo_distance WHERE bem = {$bemId} AND tipo = 'I'", $con);
                            if (mysql_num_rows($resGeoDistance) > 0) {
                                $update = mysql_query("UPDATE geo_distance SET latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', parou = 'S' WHERE bem =  {$bemId} AND tipo = 'I'", $con);
                                $dataGeoDistance = mysql_fetch_assoc($resGeoDistance);
                                $gpsLatAnt = !strstr($dataGeoDistance['latitudeDecimalDegrees'], "-") ? gprsToGps($dataGeoDistance['latitudeDecimalDegrees'], $dataGeoDistance['latitudeHemisphere']) : $dataGeoDistance['latitudeDecimalDegrees'];
                                $gpsLonAnt = !strstr($dataGeoDistance['longitudeDecimalDegrees'], "-") ? gprsToGps($dataGeoDistance['longitudeDecimalDegrees'], $dataGeoDistance['longitudeHemisphere']) : $dataGeoDistance['longitudeDecimalDegrees'];
                                // $gpsLatAnt = gprsToGps($dataGeoDistance['latitudeDecimalDegrees'], $dataGeoDistance['latitudeHemisphere']);	//$dataGeoDistance['latitudeDecimalDegrees'];
                                // $gpsLonAnt = gprsToGps($dataGeoDistance['longitudeDecimalDegrees'], $dataGeoDistance['longitudeHemisphere']);	//$dataGeoDistance['longitudeDecimalDegrees'];
                                if ($gpsLatAnt != $gpsLat) {
                                    if ($gpsLatAnt != 0 && $gpsLonAnt != 0) {
                                        $geoDistance = distance($gpsLatAnt, $gpsLonAnt, $gpsLat, $gpsLon);
                                        //$strDistance = $json->rows[0]->elements[0]->distance->value;
                                        $distance = (int) $geoDistance;
                                        //(int)($geoDistance*1000)
                                        //echo "******************************IMEI: ". $imei ." | Lat/Long Antiga: ". $gpsLatAnt . ", ". $gpsLonAnt ." | Lat/Long Atual: ". $gpsLat .", ". $gpsLon ." | Geodistance : ". $geoDistance ." | Inteiro: ". $distance ."<br>";
                                        $alertaACada = $dataBem['alerta_hodometro'];
                                        $alertaACadaSaldo = $dataBem['alerta_hodometro_saldo'];
                                        $alertaACadaSaldo = $alertaACadaSaldo - $distance;
                                        if ($alertaACadaSaldo <= 0 && $alertaACada > 0) {
                                            $msg = $texto_sms_alerta_hodometro;
                                            $msg = str_replace("#CLIENTE", $dataCliente['nome'], $msg);
                                            $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                                            $msg = str_replace("#HODOMETRO", $alertaACada, $msg);
                                            $msg = str_replace(' ', '+', $msg);
                                            //sendSMS($dataCliente['celular'], $msg, '');
                                            $msgEmail = "<p><b>Quilometragem atingida: </b></p><br><p>O veículo " . $dataBem['name'] . " atingiu a quilometragem de " . $dataBem['hodometro'] . "Km rodados às " . date("H:i:s") . " do dia " . date("d/m/Y") . ".</p><br><i>Equipe InovarSat</i>";
                                            //echo $msgEmail;
                                            // enviaEmail($dataCliente['email'], 'Hodômetro - Quilometragem Atingida', $msgEmail);
                                            $alertaACadaSaldo = $alertaACada;
                                        }
                                        // $alertaACadaSaldo = (int)$alertaACadaSaldo;//(int)$alertaACadaSaldo/1000
                                    }
                                }
                            }
                        }
                    } catch (Exception $e) {
                        mysql_query("INSERT INTO controle (texto) VALUES ({$e->getMessage}())", $con);
                    }
                    if (!empty($latitudeDecimalDegrees)) {
                        mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, converte, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', {$distance}, 0, '{$ligado}')", $con);
                    }
                    if ($alertaACadaSaldo == 0) {
                        mysql_query("UPDATE bem set date = now(), status_sinal = 'R', movimento = '{$movimento}', hodometro = hodometro+{$distance} WHERE imei = '{$imei}'", $con);
                    } else {
                        mysql_query("UPDATE bem set date = now(), status_sinal = 'R', movimento = '{$movimento}', hodometro = hodometro+{$distance}, alerta_hodometro_saldo = {$alertaACadaSaldo} WHERE imei = '{$imei}'", $con);
                    }
                    /*
                    if($numRows == 0){
                    mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator) VALUES (now(), '$imei', '$phone', '$satelliteFixStatus', '$latitudeDecimalDegrees', '$latitudeHemisphere', '$longitudeDecimalDegrees', '$longitudeHemisphere', '$speed', '$infotext', '$gpsSignalIndicator')", $cnx);
                    } else {
                    mysql_query("UPDATE loc_atual set date = now(), phone = '$phone', satelliteFixStatus = '$satelliteFixStatus', latitudeDecimalDegrees = '$latitudeDecimalDegrees', latitudeHemisphere = '$latitudeHemisphere', longitudeDecimalDegrees = '$longitudeDecimalDegrees', longitudeHemisphere = '$longitudeHemisphere', speed = '$speed', infotext = '$infotext', gpsSignalIndicator = '$gpsSignalIndicator' where imei = '$imei'", $cnx);
                    }
                    */
                } else {
                    $resLocAtual = mysql_query("SELECT id, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere FROM loc_atual WHERE imei = '{$imei}' LIMIT 1", $con);
                    $numRows = mysql_num_rows($resLocAtual);
                    if ($numRows == 0) {
                        mysql_query("INSERT INTO loc_atual (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, converte, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 0, '{$ligado}')", $con);
                    } else {
                        mysql_query("UPDATE loc_atual SET date = now(), phone = '{$phone}', satelliteFixStatus = '{$satelliteFixStatus}', latitudeDecimalDegrees = '{$latitudeDecimalDegrees}', latitudeHemisphere = '{$latitudeHemisphere}', longitudeDecimalDegrees = '{$longitudeDecimalDegrees}', longitudeHemisphere = '{$longitudeHemisphere}', speed = '{$speed}', infotext = '{$infotext}', gpsSignalIndicator = '{$gpsSignalIndicator}', converte = 0, ligado = '{$ligado}' WHERE imei = '{$imei}'", $con);
                    }
                    if (!empty($latitudeDecimalDegrees)) {
                        mysql_query("INSERT INTO gprmc (date, imei, phone, satelliteFixStatus, latitudeDecimalDegrees, latitudeHemisphere, longitudeDecimalDegrees, longitudeHemisphere, speed, infotext, gpsSignalIndicator, km_rodado, converte, ligado) VALUES (now(), '{$imei}', '{$phone}', '{$satelliteFixStatus}', '{$latitudeDecimalDegrees}', '{$latitudeHemisphere}', '{$longitudeDecimalDegrees}', '{$longitudeHemisphere}', '{$speed}', '{$infotext}', '{$gpsSignalIndicator}', 0, 0, '{$ligado}')", $con);
                    }
                    mysql_query("UPDATE bem set date = now(), status_sinal = 'S' WHERE imei = '{$imei}'", $con);
                }
                if (!empty($ligado)) {
                    mysql_query("UPDATE bem SET ligado = '{$ligado}' where imei = '{$imei}'", $con);
                }
                # Now check to see if we need to send any alerts.
                if ($infotext != "tracker") {
                    $msg = $texto_sms_alerta;
                    $msg = str_replace("#CLIENTE", $dataCliente['nome'], $msg);
                    $msg = str_replace("#VEICULO", $dataBem['name'], $msg);
                    $res = mysql_query("SELECT responsible FROM bem WHERE imei='{$imei}'", $con);
                    while ($data = mysql_fetch_assoc($res)) {
                        switch ($infotext) {
                            case "dt":
                                if (!checkAlerta($imei, 'Rastreador Desat.')) {
                                    $body = "Disable Track OK";
                                    $msg = str_replace("#TIPOALERTA", "Rastreador Desabilitado", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Rastreador Desat.')", $con);
                                }
                                break;
                            case "et":
                                if (!checkAlerta($imei, 'Alarme Parado')) {
                                    $body = "Stop Alarm OK";
                                    $msg = str_replace("#TIPOALERTA", "Alarme parado", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Parado')", $con);
                                }
                                break;
                            case "gt":
                                if (!checkAlerta($imei, 'Alarme Movimento')) {
                                    $body = "Move Alarm set OK";
                                    $msg = str_replace("#TIPOALERTA", "Alarme de Movimento ativado", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Movimento')", $con);
                                }
                                break;
                            case "help me":
                                if (!checkAlerta($imei, 'SOS!')) {
                                    $body = "Help!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'SOS!')", $con);
                                    $msg = str_replace("#TIPOALERTA", "SOS", $msg);
                                }
                                //Envia comando de resposta: alerta recebido
                                //$send_cmd = "**,imei:". $conn_imei .",E";
                                //socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (help me): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                            case "ht":
                                if (!checkAlerta($imei, 'Alarme Velocidade')) {
                                    $body = "Speed alarm set OK";
                                    $msg = str_replace("#TIPOALERTA", "Alarme de velocidade ativado", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Velocidade')", $con);
                                }
                                break;
                            case "it":
                                $body = "Timezone set OK";
                                break;
                            case "low battery":
                                if (!checkAlerta($imei, 'Bateria Fraca')) {
                                    $body = "Low battery!\nYou have about 2 minutes...";
                                    $msg = str_replace("#TIPOALERTA", "Bateria fraca, voce tem 2 minutos", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Bateria Fraca')", $con);
                                }
                                //Envia comando de resposta: alerta recebido
                                $send_cmd = "**,imei:" . $conn_imei . ",E";
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (low battery): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                            case "move":
                                if (!checkAlerta($imei, 'Movimento')) {
                                    $body = "Move Alarm!";
                                    $msg = str_replace("#TIPOALERTA", "Seu veiculo esta em movimento", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Movimento')", $con);
                                }
                                //Envia comando de resposta: alerta recebido
                                $send_cmd = "**,imei:" . $conn_imei . ",E";
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (move): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                            case "nt":
                                $body = "Returned to SMS mode OK";
                                break;
                            case "speed":
                                if (!checkAlerta($imei, 'Velocidade')) {
                                    $body = "Speed alarm!";
                                    $msg = str_replace("#TIPOALERTA", "Seu veiculo ultrapassou o limite de velocidade", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Velocidade')", $con);
                                }
                                //Envia comando de resposta: alerta recebido
                                $send_cmd = "**,imei:" . $conn_imei . ",E";
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (speed): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                            case "stockade":
                                if (!checkAlerta($imei, 'Cerca')) {
                                    $body = "Geofence Violation!";
                                    $msg = str_replace("#TIPOALERTA", "Seu veiculo saiu da cerca virtual", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Cerca')", $con);
                                }
                                //Envia comando de resposta: alerta recebido
                                $send_cmd = "**,imei:" . $conn_imei . ",E";
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (stockade): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                            case "door alarm":
                                if (!checkAlerta($imei, 'Porta')) {
                                    $body = "Open door!";
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Porta')", $con);
                                }
                                //Envia comando de resposta: alerta recebido
                                $send_cmd = "**,imei:" . $conn_imei . ",E";
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (door alarm): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                            case "acc alarm":
                                if (!checkAlerta($imei, 'Alarme Disparado')) {
                                    $body = "ACC alarm!";
                                    $msg = str_replace("#TIPOALERTA", "Alarme disparado", $msg);
                                    mysql_query("INSERT INTO message (imei, message) VALUES ('{$imei}', 'Alarme Disparado')", $con);
                                }
                                //Envia comando de resposta: alerta recebido
                                $send_cmd = "**,imei:" . $conn_imei . ",E";
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                            case "acc off":
                                $body = "Ignicao Desligada!";
                                $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave desligada", $msg);
                                //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx);
                                mysql_query("UPDATE bem SET ligado = 'N' where imei = '{$imei}'", $con);
                                //Envia comando de resposta: alerta recebido
                                $send_cmd = "**,imei:" . $conn_imei . ",E";
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                            case "acc on":
                                $body = "Ignicao Ligada!";
                                $msg = str_replace("#TIPOALERTA", "Seu veiculo esta com a chave ligada", $msg);
                                //mysql_query("INSERT INTO message (imei, message) VALUES ('$imei', 'Ignição')", $cnx);
                                mysql_query("UPDATE bem SET ligado = 'S' where imei = '{$imei}'", $cnx);
                                //Envia comando de resposta: alerta recebido
                                $send_cmd = "**,imei:" . $conn_imei . ",E";
                                socket_send($socket, $send_cmd, strlen($send_cmd), 0);
                                //printLog($fh, "Comando de resposta (acc alarm): " . $send_cmd . " imei: " . $conn_imei);
                                break;
                        }
                        //switch
                        $msg = str_replace(' ', '+', $msg);
                        //if($dataCliente['envia_sms'] == 'S' && $dataBem['envia_sms'] == 'S' && $infotext != 'acc on'&& $infotext != 'acc off' && $infotext != 'et')
                        //	sendSMS($dataCliente['celular'], $msg, '');
                        //Enviando e-mail de alerta
                        /*$headers = "From: $email_from" . "\r\n" . "Reply-To: $email_from" . "\r\n";
                        		$responsible = $data['responsible'];
                        		$rv = mail($responsible, "Tracker - $imei", $body, $headers);*/
                        if (isset($body)) {
                            enviaEmail($dataCliente['email'], "Rastreador - {$imei}", $body);
                        }
                    }
                    //while
                }
            } else {
                echo 'Cliente não encontrado. Erro: ' . mysql_error($con);
            }
        } else {
            echo 'Veículo não encontrado. Erro: ' . mysql_error($con);
        }
        mysql_close($con);
    } else {
        echo 'Não foi possivel conectar ao banco. Erro: ' . mysql_error();
    }
}
Exemple #29
0
function action_get_verify_code()
{
    $user = $GLOBALS['user'];
    $_CFG = $GLOBALS['_CFG'];
    $_LANG = $GLOBALS['_LANG'];
    $smarty = $GLOBALS['smarty'];
    $db = $GLOBALS['db'];
    $ecs = $GLOBALS['ecs'];
    $user_id = $_SESSION['user_id'];
    include_once 'includes/cls_json.php';
    require dirname(__FILE__) . '/send.php';
    $json = new JSON();
    $result = array();
    $phone = trim($_REQUEST['phone']);
    $sql = 'SELECT COUNT(*) FROM ' . $GLOBALS['ecs']->table('users') . ' WHERE `user_id` = \'' . $user_id . '\' AND `mobile_phone` = \'' . $phone . '\'';
    $count = $GLOBALS['db']->getOne($sql);
    if ($count == 0) {
        $result['result'] = 'fail';
        $result['message'] = '手机号跟用户不匹配';
        echo $json->encode($result);
    } else {
        $seed = "0123456789";
        $verifycode = mc_random(6, $seed);
        $content = '您的验证码为' . $verifycode;
        $ret = sendSMS($phone, $content);
        $sql = 'INSERT INTO ' . $ecs->table('verifycode') . '(`mobile`, `getip`, `verifycode`, `dateline`) VALUES (\'' . $phone . '\',\'' . real_ip() . '\',\'' . $verifycode . '\',\'' . gmtime() . '\')';
        $db->query($sql);
        if ($ret == '发送成功!' && $db->affected_rows() == 1) {
            $result['result'] = 'success';
            $result['message'] = '短信发送成功';
            echo $json->encode($result);
        } else {
            $result['result'] = 'fail';
            $result['message'] = '短信发送失败!';
            echo $json->encode($result);
        }
    }
}
Exemple #30
0
function sendsms_pricecut($goods_id)
{
    include_once '../send.php';
    $min_price_arr = get_min_price($goods_id);
    if ($min_price_arr['goods_name'] != '') {
        $min_price = $min_price_arr['min_price'];
        $goods_name = $min_price_arr['goods_name'];
        $goods_url = build_uri('goods', array('gid' => $goods_id), $goods_name);
        $goods_url = $GLOBALS['ecs']->url() . $goods_url;
        $sql = "select pricecut_id, mobile,email from " . $GLOBALS['ecs']->table('pricecut') . " where goods_id='{$goods_id}' and price >= '{$min_price}' and status=0 ";
        $list = $GLOBALS['db']->getAll($sql);
        if ($list) {
            for ($i = 0; $i < count($list); $i++) {
                if ($list[$i]['email'] != '') {
                    $content1 = '您关注的商品 ' . $goods_name . ' 已经降价,您可点击下面链接直接进入商品页面浏览或购买!<br><a href="' . $goods_url . '">' . $goods_url . '</a>';
                    send_mail($_CFG['shop_name'], $list[$i]['email'], '您关注的商品' . $goods_name . '已经降价', $content1, 1);
                }
                //开启降价给客户发短信
                if ($GLOBALS['_CFG']['sms_pricecut'] == 1) {
                    //降价通知短信内容
                    $pricecut_content = sprintf($GLOBALS['_CFG']['sms_pricecut_tpl'], $goods_name, $goods_url, $GLOBALS['_CFG']['sms_sign']);
                    if ($list[$i]['mobile'] != '') {
                        $res = sendSMS($list[$i]['mobile'], $pricecut_content);
                        if ($res == true) {
                            $sql = "UPDATE " . $GLOBALS['ecs']->table('pricecut') . " SET status = 2 WHERE pricecut_id = '" . $list[$i]['pricecut_id'] . "'";
                            $GLOBALS['db']->query($sql);
                        } else {
                            $sql = "UPDATE " . $GLOBALS['ecs']->table('pricecut') . " SET status = 1 WHERE pricecut_id = '" . $list[$i]['pricecut_id'] . "'";
                            $GLOBALS['db']->query($sql);
                        }
                    }
                }
            }
        }
    }
}