|
- <?php
-
- namespace backend\common;
-
- use Yii;
- use yii\base\Model;
- use yii\db\Exception;
- use common\components\zHttp;
-
-
- /**
- * Created by PhpStorm.
- * User: wangxj
- * Date: 2017/4/12
- * Time: 16:21
- */
- class Utils
- {
- /**
- * User:Steven
- *
- * Desc:发生soap请求
- * @param $request_fun
- * @param $param
- * @param $url
- * @return Exception | string
- */
- public function soapRequest($request_fun, $param, $url)
- {
- ini_set("soap.wsdl_cache_enabled", "0");
- $soap = new SoapClient($url, array(array('soap_version' => SOAP_1_2, 'trace' => true, 'exceptions' => true)));
- try {
- $response = $soap->{$request_fun}(['requestXml' => $param]);
- return $response;
- } catch (Exception $sf) {
- return $sf;
- /*print ($soap->__getLastRequest());
- print ($soap->__getLastResponse());*/
- }
- }
-
- /**
- * User:Steven
- *
- * Desc:发送post请求(xml)
- * @param $url
- * @param $xmlData
- * @return mixed
- */
- public function xml_post_request($url, $xmlData)
- {
- $header[] = "Content-type: text/xml"; //定义content-type为xml,注意是数组
- $ch = curl_init($url);
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $xmlData);
- $response = curl_exec($ch);
- if (curl_errno($ch)) {
- print curl_error($ch);
- }
- curl_close($ch);
- return $response;
- }
-
- public function execute($request, $session = null)
- {
- $this->data = $this->format == 'json' ? json_encode($request) : $this->xml_encode($request);
- $this->Url = 'http://' . str_replace(array('http://', 'https://'), '', $this->Url);
- $postUrl = $this->Url . "?method={$this->requestMethod}&data=" . urlencode($this->data);
- return $this->request_by_curl($postUrl);
- }
-
- /**
- * User:Steven
- *
- * Desc:编辑符合携程需要的XML格式
- * @param $data array 请求体
- * @param $RequestTypeName string 请求方法名称
- * @return string
- */
- public static function xml_encode($data, $RequestTypeName)
- {
- $params = Yii::$app->params['ctrip']['soap'];
- $timeStamp = date("Y-m-d H:i:s", time());
- $xml = "<Request>";
- $xml .= "<HeaderInfo UserID=\"" . $params['UserID'] . "\" RequestorId=\"" . $params['RequestorId'] .
- "\" AsyncRequest=\"" . $params['AsyncRequest'] . "\" TimeStamp=\"$timeStamp\"><Authentication UserName=\"" .
- $params['UserName'] . "\" Password=\"" . $params['Password'] . "\" /><RequestType Name=\"$RequestTypeName\" Version=\"" . $params['Version'] . "\" /></HeaderInfo>";
- $xml .= self::data_to_xml($data);
- $xml .= "</Request>";
- return $xml;
- }
-
-
- /**
- * User:Steven
- *
- * Desc:编辑符合携程需要的XML格式
- * @param $data array 请求体
- * @param $RequestTypeName string 请求方法名称
- * @return string
- */
- public static function xml_encode_remain($data, $RequestTypeName)
- {
- $params = Yii::$app->params['ctrip']['soap'];
- $timeStamp = date("Y-m-d H:i:s", time());
- $xml = "<![CDATA[<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
- $xml .= "<q1:Request xmlns:q1=\"http://soa.ctrip.com/hotel/vendor/RoomQuantity/v1\">";
- $xml .= "<q1:HeaderInfo UserID=\"" . $params['UserID'] . "\" RequestorId=\"" . $params['RequestorId'] .
- "\" AsyncRequest=\"" . $params['AsyncRequest'] . "\" TimeStamp=\"$timeStamp\"><q1:Authentication UserName=\"" .
- $params['UserNameRemain'] . "\" Password=\"" . $params['PasswordRemain'] . "\" /><q1:RequestType Name=\"$RequestTypeName\" Version=\"" . $params['VersionRemain'] . "\" /></q1:HeaderInfo>";
- $xml .= self::data_to_xml_ns($data, 'q1:');
- $xml .= "</q1:Request>]]>";
- return $xml;
- }
-
- /**
- * User: wangxj
- *
- * 格式化返回的soap字符串
- *
- * @param $str
- */
- public static function formatResult($str)
- {
- $result = "<RequestResponse><RequestResult>{$str}</RequestResult></RequestResponse>";
- return $result;
- }
-
- /**
- * User:Steven
- *
- * Desc:将xml转换为数组
- * @param $xml
- * @return mixed
- */
- public static function xml_to_array($xml)
- {
- $ob = simplexml_load_string($xml);
- $json = json_encode($ob);
- $array = json_decode($json, true);
- return $array;
- }
-
- /**
- * User:Steven
- *
- * Desc:将数组转化成xml
- * @param $data
- * @return string
- */
- public static function data_to_xml($data)
- {
- if (is_object($data)) {
- $data = get_object_vars($data);
- }
- $xml = '';
- foreach ($data as $key => $val) {
- if (is_null($val) || $val === '') {
- // $xml .= "<$key/>\n";
- $xml .= "<$key>$val</$key>";
- } else {
- if (!is_numeric($key)) {
- $xml .= "<$key>";
- }
- $xml .= (is_array($val) || is_object($val)) ? self::data_to_xml($val) : $val;
- if (!is_numeric($key)) {
- $xml .= "</$key>";
- }
- }
- }
- return $xml;
- }
-
- /**
- * User:Steven
- * Desc:拼接带有命名空间的XML
- * @param $data
- * @param $namespace
- * @return string
- */
- public static function data_to_xml_ns($data, $namespace)
- {
- if (is_object($data)) {
- $data = get_object_vars($data);
- }
- $xml = '';
- foreach ($data as $key => $val) {
- if (is_null($val) || $val === '') {
- // $xml .= "<$namespace$key/>\n";
- $xml .= "<$namespace$key>$val</$namespace$key>";
- } else {
- if (!is_numeric($key)) {
- $xml .= "<$namespace$key>";
- }
- $xml .= (is_array($val) || is_object($val)) ? self::data_to_xml_ns($val, $namespace) : $val;
- if (!is_numeric($key)) {
- $xml .= "</$namespace$key>";
- }
- }
- }
- return $xml;
- }
-
- /**
- * User:Steven
- * Desc:格式化时间字符串 (适用于Ctrip)
- * @param $dataTime
- * @param $type 1: 去掉T 2:拼接T
- */
- public static function formatDataTime($dataTime, $type)
- {
- if ($type == 1) {
- $dateTime_arr = explode('T', $dataTime);
- $DataTime = $dateTime_arr[0] . ' ' . $dateTime_arr[1];
- } else {
- $DataTime = date('Y-m-d\TH:i:s', strtotime($dataTime));
- }
- return $DataTime;
- }
-
- /**
- * User: wangxj
- *
- * 获取错误信息到字符串
- *
- * @param $model Model
- * @return string
- */
- public static function getModelError($model)
- {
- $tmp = $model->getErrors();
- if (!empty($tmp)) {
- $str = '';
- foreach ($tmp as $item) {
- if (is_array($item)) {
- foreach ($item as $value) {
- $str .= $value . ' ';
- }
- } else {
- $str .= $item;
- }
- }
- return trim($str);
- } else {
- return '';
- }
- }
-
- /**
- * User: wangxj
- *
- * 把时间转换为
- *
- * @param $time
- * @param $type string 不需要返回 23988
- */
- public static function timeHour($time, $type = '')
- {
- if ($time != '-1' && $time != '-2' || $type == '') {
- $data = explode(',', $time);
- if (count($data) > 1) {
- $tmp = explode(':', $data[1]);
- return (int)($data[0]) * 24 + (24 - (int)($tmp[0]));
- } else {
- $tmp = explode(':', $data[0]);
- return (24 - (int)($tmp[0]));
- }
- } else {
- return '23988';
- }
- }
-
-
- /**
- * User:Stevem
- *
- * 求两个日期之间相差的天数
- * (针对1970年1月1日之后,求之前可以采用泰勒公式)
- * @param string $day1
- * @param string $day2
- * @return number
- */
- static function diffBetweenTwoDays($day1, $day2)
- {
- $second1 = strtotime($day1);
- $second2 = strtotime($day2);
-
- if ($second1 < $second2) {
- $tmp = $second2;
- $second2 = $second1;
- $second1 = $tmp;
- }
- return ($second1 - $second2) / 86400;
- }
-
- /**
- * User:Steven
- * Desc:计算两个日期范围内的所有日期 ,不包括期限的结束日期
- * @param $strDateFrom
- * @param $strDateTo
- * @return array
- */
- static function createDateRangeArray($strDateFrom, $strDateTo)
- {
- $aryRange = array();
-
- $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
- $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));
-
- if ($iDateTo >= $iDateFrom) {
- array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
- while ($iDateFrom + 86400 < $iDateTo) {
- $iDateFrom += 86400; // add 24 hours
- array_push($aryRange, date('Y-m-d', $iDateFrom));
- }
- }
- return $aryRange;
- }
-
- /**
- * User:Steven
- *
- * 想RTX发送推送消息
- * 使用企业微信 zOfficeWechat::sendMsg($arr)
- *
- * $title 通知标题
- * $msg 通知内容
- */
- static function sendMessageToRTX($title, $msg, $user = 'shifp,wangxj,yuw')
- {
- //生产环境才发送RTX
- if (Yii::$app->params['sendRTX']) {
- $cuntomer_list = $user;
- $arr = array(
- 'title' => $title . '【' . date('Y-m-d H:i:s', time()) . '】' . '[' . microtime() . ']',
- 'receiver' => $cuntomer_list,
- 'msg' => substr($msg, 0, 1024),
- );
- self::httpsPost('http://180.168.4.58:8012/SendNotify.cgi', $arr);
- }
- }
-
- /**
- * User:Steven
- * Desc:
- * @param $url
- * @param array $param
- * @return mixed
- * @throws Exception
- */
- static function httpsPost($url, $param = array())
- {
- $ch = curl_init(); // 初始化一个 cURL 对象
- curl_setopt($ch, CURLOPT_URL, $url); // 设置需要抓取的URL
- curl_setopt($ch, CURLOPT_HEADER, 0); // // 设置header
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 设置cURL 参数,要求结果保存到字符串中还是输出到屏幕上。
- // 如果你想PHP去做一个正规的HTTP POST,设置这个选项为一个非零值。这个POST是普通的 application/x-www-from-urlencoded 类型,多数被HTML表单使用。
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param)); // 传递一个作为HTTP “POST”操作的所有数据的字符串。//http_build_query:生成 URL-encode 之后的请求字符串
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array(
- 'Content-type:application/x-www-form-urlencoded;charset=utf-8'
- ));
- $rtn = curl_exec($ch); // 运行cURL,请求网页
- if ($errno = curl_errno($ch)) {
- throw new Exception ('Curl Error(' . $errno . '):' . curl_error($ch));
- }
- curl_close($ch); // 关闭URL请求
- return $rtn; // 返回获取的数据
- }
-
-
- /**
- * User:Steven
- * Desc:GET 请求
- * @param $url
- * @return mixed
- */
- static function http_get($url)
- {
- $oCurl = curl_init();
- if (stripos($url, "https://") !== FALSE) {
- curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
- curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
- }
- curl_setopt($oCurl, CURLOPT_URL, $url);
- curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
- curl_setopt($oCurl, CURLOPT_HEADER, 1);
-
- // $sContent = curl_exec($oCurl);
- // $aStatus = curl_getinfo($oCurl);
- $sContent = self::execCURL($oCurl);
- curl_close($oCurl);
-
- return $sContent;
- }
-
- /**
- * User:Steven
- * POST 请求(新)
- * @param string $url
- * @param array $param
- * @param boolean $post_file 是否文件上传
- * @return string content
- */
- static function http_post($url, $param, $post_file = false)
- {
- $oCurl = curl_init();
-
- if (stripos($url, "https://") !== FALSE) {
- curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
- curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
- curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
- }
- if (PHP_VERSION_ID >= 50500 && class_exists('\CURLFile')) {
- $is_curlFile = true;
- } else {
- $is_curlFile = false;
- if (defined('CURLOPT_SAFE_UPLOAD')) {
- curl_setopt($oCurl, CURLOPT_SAFE_UPLOAD, false);
- }
- }
-
- if ($post_file) {
- if ($is_curlFile) {
- foreach ($param as $key => $val) {
- if (isset($val["tmp_name"])) {
- $param[$key] = new \CURLFile(realpath($val["tmp_name"]), $val["type"], $val["name"]);
- } else if (substr($val, 0, 1) == '@') {
- $param[$key] = new \CURLFile(realpath(substr($val, 1)));
- }
- }
- }
- $strPOST = $param;
- } else {
- $strPOST = urldecode(json_encode($param));
- }
-
- curl_setopt($oCurl, CURLOPT_URL, $url);
- curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($oCurl, CURLOPT_POST, true);
- curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
- curl_setopt($oCurl, CURLOPT_VERBOSE, 1);
- curl_setopt($oCurl, CURLOPT_HEADER, 1);
-
- // $sContent = curl_exec($oCurl);
- // $aStatus = curl_getinfo($oCurl);
-
- $sContent = self::execCURL($oCurl);
- curl_close($oCurl);
-
- return $sContent;
- }
-
- /**
- * User:Steven
- * Desc:执行CURL请求,并封装返回对象
- * @param $ch
- * @return array
- */
- static function execCURL($ch)
- {
- $response = curl_exec($ch);
- $error = curl_error($ch);
- $result = array('header' => '',
- 'content' => '',
- 'curl_error' => '',
- 'http_code' => '',
- 'last_url' => '');
-
- if ($error != "") {
- $result['curl_error'] = $error;
- return $result;
- }
-
- $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
- $result['header'] = str_replace(array("\r\n", "\r", "\n"), "<br/>", substr($response, 0, $header_size));
- $result['content'] = substr($response, $header_size);
- $result['http_code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
- $result['last_url'] = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
- $result["base_resp"] = array();
- $result["base_resp"]["ret"] = $result['http_code'] == 200 ? 0 : $result['http_code'];
- $result["base_resp"]["err_msg"] = $result['http_code'] == 200 ? "ok" : $result["curl_error"];
-
- return $result;
- }
-
- /**
- * User: wangxj
- *
- * 保存日志
- *
- * @param $action
- * @param $string
- */
- static function writeLog($action, $string)
- {
- $string = date('Y-m-d H:i:s') . " $action " . PHP_EOL . $string . PHP_EOL;
- if (!file_exists(__DIR__ . '/../runtime/logs/soap/receive')) {
- mkdir(__DIR__ . '/../runtime/logs/soap/receive', 0777, true);
- }
- file_put_contents(__DIR__ . '/../runtime/logs/soap/receive/' . date('Y-m-d') . '.log', $string, FILE_APPEND);
- }
-
- /**
- * 根据时间戳,返回后七天的时间戳
- * @param $time
- * @return array
- */
- static function getWeekTime($time)
- {
- $times[] = strtotime('+0 days', $time);
- $times[] = strtotime('+1 days', $time);
- $times[] = strtotime('+2 days', $time);
- $times[] = strtotime('+3 days', $time);
- $times[] = strtotime('+4 days', $time);
- $times[] = strtotime('+5 days', $time);
- $times[] = strtotime('+6 days', $time);
- $times[] = strtotime('+7 days', $time);
- $times[] = strtotime('+8 days', $time);
- $times[] = strtotime('+9 days', $time);
- $times[] = strtotime('+10 days', $time);
- $times[] = strtotime('+11 days', $time);
- $times[] = strtotime('+12 days', $time);
- $times[] = strtotime('+13 days', $time);
- return $times;
- }
-
- /**
- * User:Steven
- * Desc:获取日期label
- * @param $number
- * @param string $tag
- * @return string
- */
- static function getWeekLabel($number, $tag = '周')
- {
- $week = ['日', '一', '二', '三', '四', '五', '六'];
- return isset($week[$number]) ? $tag . $week[$number] : '';
- }
-
- /**
- * 获取日期区间的所有日期
- *
- * @param $start_date string 2017-07-01
- * @param $end_date string 2017-07-31
- * @param $type bool 是否包含结束日期
- *
- * @author wangxj
- */
- static function getRangeDate($start_date, $end_date, $type=false){
- $start = new \DateTime($start_date);
- $end = new \DateTime($end_date);
- $interval = new \DateInterval('P1D'); // 1 day interval
- $period = new \DatePeriod($start, $interval, $end);
-
- $result = [];
- foreach ($period as $day) {
- // Do stuff with each $day...
- /* @var $day /DatePeriod */
- $result[] = $day->format('Y-m-d');
- }
-
- if($type=== true){
- $result[] = $end_date;
- }
- return $result;
- }
-
- /**
- * Function Description:发送邮件
- * Function Name: send_mail
- * @param $user
- * @param $pwd
- * @param $toemail
- * @param $title
- * @param $content
- *
- * @return mixed
- *
- * @author 冒炎
- */
- static function send_mail($user, $pwd, $toemail, $title, $content)
- {
- $currentDir = dirname(__FILE__);
- include_once $currentDir .'/Smtp.class.php';
- //******************** 配置信息 ********************************
- $smtpserver = "smtp.exmail.qq.com";//SMTP服务器
- $smtpserverport = 25;//SMTP服务器端口
- $smtpusermail = $user;//SMTP服务器的用户邮箱
- $smtpemailto = $toemail;//发送给谁
- $smtpuser = $user;//SMTP服务器的用户帐号,注:部分邮箱只需@前面的用户名
- $smtppass = $pwd;//SMTP服务器的用户密码
- $mailtitle = $title;//邮件主题
- $mailcontent = "<h1>" . $content . "</h1>";//邮件内容
- $mailtype = "HTML";//邮件格式(HTML/TXT),TXT为文本邮件
- //************************ 配置信息 ****************************
- set_time_limit(0);
- $smtp = new \Smtp($smtpserver, $smtpserverport, true, $smtpuser, $smtppass);//这里面的一个true是表示使用身份验证,否则不使用身份验证.
- $smtp->debug = false;//是否显示发送的调试信息
- $state = $smtp->sendmail($smtpemailto, $smtpusermail, $mailtitle, $mailcontent, $mailtype);
- if ($state == "") {
- $data['code'] = '1';
- $data['info'] = '邮件发送失败,请联系管理员';
- } else {
- $data['code'] = '0';
- $data['info'] = '邮件发送成功';
- }
- return $data;
- }
-
-
- /**
- * User:Steven
- * Desc:计算早餐级别
- * @param $breakfast
- * @return int
- */
- static function calBreakfastLevel($breakfast)
- {
- switch ($breakfast) {
- case 0:
- $breakfast_desc = '无早';
- break;
- case 1:
- $breakfast_desc ='单早';
- break;
- case 2:
- $breakfast_desc = '双早';
- break;
- case 3:
- $breakfast_desc = '三早';
- break;
- case 4:
- $breakfast_desc = '四早';
- break;
- case 5:
- $breakfast_desc = '五早';
- break;
- case 6:
- $breakfast_desc = '六早';
- break;
- case 7:
- $breakfast_desc = '七早';
- break;
- case 8:
- $breakfast_desc ='八早';
- break;
- case 9:
- $breakfast_desc = '九早';
- break;
- case 10:
- $breakfast_desc = '十早';
- break;
- default:
- $breakfast_desc = '多早';
- break;
- }
- return $breakfast_desc;
- }
-
- /**
- * Notes:过滤所选日期中符合星期的日期
- * User: Steven
- * Date: 2018/2/2
- * Time: 14:33
- * @param $strDateFrom
- * @param $strDateTo
- * @param $week_arr
- * @return array
- */
- static function createDateByWeek($strDateFrom, $strDateTo, $week_arr)
- {
- $aryRange = array();
- $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
- $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));
- if ($iDateTo >= $iDateFrom) {
- if (in_array(date("w", $iDateFrom), $week_arr)) {
- array_push($aryRange, date('Y-m-d', $iDateFrom));//first entry
- }
- while ($iDateFrom < $iDateTo) {
- $iDateFrom += 86400;//add 24 hours
- $number_wk = date("w", $iDateFrom);
- if (in_array($number_wk, $week_arr)) {
- array_push($aryRange, date('Y-m-d', $iDateFrom));
- }
- }
- }
- return $aryRange;
- }
- }
-
- ?>
|