common.php 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409
  1. <?php
  2. use think\facade\Db;
  3. use cmf\lib\Storage;
  4. // 应用公共文件
  5. error_reporting(E_ERROR | E_WARNING | E_PARSE);
  6. require_once dirname(__FILE__).'/redis.php';
  7. /**
  8. * 获取当前登录的管事员id
  9. * @return int
  10. */
  11. function get_current_admin_id(){
  12. return session('ADMIN_ID');
  13. }
  14. /* 去除NULL 判断空处理 主要针对字符串类型*/
  15. function checkNull($checkstr){
  16. $checkstr=trim($checkstr);
  17. $checkstr=urldecode($checkstr);
  18. if( strstr($checkstr,'null') || (!$checkstr && $checkstr!=0 ) ){
  19. $str='';
  20. }else{
  21. $str=$checkstr;
  22. }
  23. $str=htmlspecialchars($str);
  24. return $str;
  25. }
  26. /* 检验手机号 */
  27. function checkMobile($mobile){
  28. $ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/",$mobile);
  29. if($ismobile){
  30. return 1;
  31. }
  32. return 0;
  33. }
  34. /* 去除emoji表情 */
  35. function filterEmoji($str){
  36. $str = preg_replace_callback(
  37. '/./u',
  38. function (array $match) {
  39. return strlen($match[0]) >= 4 ? '' : $match[0];
  40. },
  41. $str);
  42. return $str;
  43. }
  44. /**
  45. * 转化数据库保存的文件路径,为可以访问的url
  46. */
  47. function get_upload_path($file){
  48. if($file==''){
  49. return $file;
  50. }
  51. $configpri=getConfigPri();
  52. if(strpos($file,"http")===0){
  53. if(strpos($file,'%@%cloudtype=') !== false){
  54. //将字符串分隔
  55. $file_arr=explode('%@%cloudtype=',$file);
  56. $file_url=$file_arr[0];
  57. $cloudtype=$file_arr[1];
  58. if(!isset($cloudtype)){
  59. return html_entity_decode($file);
  60. }
  61. if($cloudtype==1){ //存储方式为七牛
  62. return html_entity_decode($file_url);
  63. }else if($cloudtype==2 && $configpri['tx_private_signature']){
  64. return setTxUrl(html_entity_decode($file_url)); //腾讯云存储为私有读写时需要调用该方法获取签名验证
  65. }else if($cloudtype==3){
  66. return html_entity_decode($file_url);
  67. }else{
  68. return html_entity_decode($file_url);
  69. }
  70. }else{
  71. return html_entity_decode($file);
  72. }
  73. }else if(strpos($file,"/")===0){
  74. $filepath= cmf_get_domain().$file;
  75. return $filepath;
  76. }else{
  77. if(strpos($file,'%@%cloudtype=') !== false){
  78. //将字符串分隔
  79. $file_arr=explode('%@%cloudtype=',$file);
  80. $file_url=$file_arr[0];
  81. $cloudtype=$file_arr[1];
  82. if($cloudtype==1){ //七牛存储
  83. $space_host=$configpri['qiniu_protocol']."://".$configpri['qiniu_domain']."/";
  84. }else if($cloudtype==2){ //腾讯云存储
  85. $space_host=$configpri['tx_domain_url'];
  86. }else if($cloudtype==3){ //亚马逊存储
  87. $space_host=$configpri['aws_hosturl'];
  88. }else{
  89. $space_host="http://";
  90. }
  91. $filepath=$space_host.$file_url;
  92. if(!isset($cloudtype)){
  93. return html_entity_decode($filepath);
  94. }
  95. if($cloudtype==2 && $configpri['tx_private_signature']){ //腾讯云存储 且 需要签名验证
  96. return setTxUrl(html_entity_decode($filepath)); //腾讯云存储为私有读写时需要调用该方法获取签名验证
  97. }else{
  98. return html_entity_decode($filepath);
  99. }
  100. }else{
  101. return html_entity_decode($file);
  102. }
  103. }
  104. }
  105. /* 公共配置 */
  106. function getConfigPub() {
  107. $key='getConfigPub';
  108. $config=getcaches($key);
  109. $config=false;
  110. if(!$config){
  111. $config= cmf_get_option('site_info');
  112. setcaches($key,$config);
  113. }
  114. return $config;
  115. }
  116. /* 获取私密配置 */
  117. function getConfigPri() {
  118. $key='getConfigPri';
  119. $config=getcaches($key);
  120. $config=false;
  121. if(!$config){
  122. $config=cmf_get_option('configpri');
  123. setcaches($key,$config);
  124. }
  125. return $config;
  126. }
  127. /* 判断token */
  128. function checkToken($uid,$token) {
  129. if($uid<1 || $token==''){
  130. return 700;
  131. }
  132. $key="token_".$uid;
  133. $userinfo=getCache($key);
  134. if(!$userinfo){
  135. $userinfo=Db::name('user_token')
  136. ->field('token,expire_time')
  137. ->where(['user_id'=>$uid])
  138. ->find();
  139. if($userinfo){
  140. setCache($key,$userinfo);
  141. }
  142. }
  143. if(!$userinfo || $userinfo['token']!=$token || $userinfo['expire_time']<time()){
  144. return 700;
  145. }
  146. return 0;
  147. }
  148. /* 用户基本信息 */
  149. function getUserInfo($uid) {
  150. $info= Db::name("user")
  151. ->field("id,user_nickname,avatar,avatar_thumb,sex,signature,province,city,birthday,user_status,coin,isrecommend,recommend_time")
  152. ->where("id='{$uid}'")
  153. ->find();
  154. if($info){
  155. $info['avatar']=get_upload_path($info['avatar']);
  156. $info['avatar_thumb']=get_upload_path($info['avatar_thumb']);
  157. }else{
  158. $info=array(
  159. 'id'=>$uid,
  160. 'user_nickname'=>'用户不存在',
  161. 'avatar'=>get_upload_path('/default.png'),
  162. 'avatar_thumb'=>get_upload_path('/default_thumb.png'),
  163. 'sex'=>'0',
  164. 'signature'=>'',
  165. 'province'=>'',
  166. 'city'=>'',
  167. 'birthday'=>'',
  168. 'user_status'=>'1',
  169. 'coin'=>'0',
  170. 'isrecommend'=>'0',
  171. 'recommend_time'=>''
  172. );
  173. }
  174. return $info;
  175. }
  176. /* 腾讯IM签名 */
  177. function setSig($id){
  178. $sig='';
  179. $configpri=getConfigPri();
  180. $appid=$configpri['im_sdkappid'];
  181. //return $sig;
  182. try{
  183. $path= CMF_ROOT.'sdk/txim/';
  184. require_once( $path ."TLSSig.php");
  185. $api = new \TLSSigAPI();
  186. $api->SetAppid($appid);
  187. $private = file_get_contents( $path .'keys/private_key.pem');
  188. $api->SetPrivateKey($private);
  189. $public = file_get_contents( $path .'keys/public_key.pem');
  190. $api->SetPublicKey($public);
  191. $sig = $api->genSig($id);
  192. }catch(Exception $e){
  193. //echo $e->getMessage();
  194. file_put_contents(CMF_ROOT.'log/setSig.txt',date('y-m-d H:i:s').'提交参数信息 :'.$e->getMessage()."\r\n",FILE_APPEND);
  195. }
  196. return $sig;
  197. }
  198. /* 腾讯IM REST API */
  199. function getTxRestApi(){
  200. $configpri=getConfigPri();
  201. $sdkappid=$configpri['im_sdkappid'];
  202. $identifier=$configpri['im_admin'];
  203. $sig=setSig($identifier);
  204. $path= CMF_ROOT.'sdk/txim/';
  205. require_once( $path."restapi/TimRestApi.php");
  206. $api = createRestAPI();
  207. $api->init($sdkappid, $identifier);
  208. //托管模式
  209. $ret = $api->set_user_sig($sig);
  210. if($ret == false){
  211. file_put_contents(CMF_ROOT.'log/RESTAPI.txt',date('y-m-d H:i:s').'提交参数信息 :'.'设置管理员usrsig失败'."\r\n",FILE_APPEND);
  212. }
  213. return $api;
  214. }
  215. /* 时长 */
  216. /*function getLength($cha,$type=0){
  217. $iz=floor($cha/60);
  218. $hz=floor($iz/60);
  219. $dz=floor($hz/24);
  220. // 秒
  221. $s=$cha%60;
  222. // 分
  223. $i=floor($iz%60);
  224. // 时
  225. $h=floor($hz/24);
  226. // 天
  227. if($type==1){
  228. if($s<10){
  229. $s='0'.$s;
  230. }
  231. if($i<10){
  232. $i='0'.$i;
  233. }
  234. if($h<10){
  235. $h='0'.$h;
  236. }
  237. if($hz<10){
  238. $hz='0'.$hz;
  239. }
  240. return $hz.':'.$i.':'.$s;
  241. }
  242. if($type==2){
  243. if($s<10){
  244. $s='0'.$s;
  245. }
  246. if($i<10){
  247. $i='0'.$i;
  248. }
  249. if($hz>0){
  250. if($hz<10){
  251. $hz='0'.$hz;
  252. }
  253. return $hz.':'.$i.':'.$s;
  254. }
  255. return $i.':'.$s;
  256. }
  257. if($cha<60){
  258. return $cha.'秒';
  259. }else if($iz<60){
  260. return $iz.'分'.$s.'秒';
  261. }else if($hz<24){
  262. return $hz.'小时'.$i.'分'.$s.'秒';
  263. }else if($dz<30){
  264. return $dz.'天'.$h.'小时'.$i.'分'.$s.'秒';
  265. }
  266. }*/
  267. function getLength($time,$type=0){
  268. if(!$time){
  269. return (string)$time;
  270. }
  271. $value = array(
  272. "years" => 0,
  273. "days" => 0,
  274. "hours" => 0,
  275. "minutes" => 0,
  276. "seconds" => 0
  277. );
  278. if($time >= 31556926){
  279. $value["years"] = floor($time/31556926);
  280. $time = ($time%31556926);
  281. }
  282. if($time >= 86400){
  283. $value["days"] = floor($time/86400);
  284. $time = ($time%86400);
  285. }
  286. if($time >= 3600){
  287. $value["hours"] = floor($time/3600);
  288. $time = ($time%3600);
  289. }
  290. if($time >= 60){
  291. $value["minutes"] = floor($time/60);
  292. $time = ($time%60);
  293. }
  294. $value["seconds"] = floor($time);
  295. if($value['years']){
  296. if($type==1&&$value['years']<10){
  297. $value['years']='0'.$value['years'];
  298. }
  299. }
  300. if($value['days']){
  301. if($type==1&&$value['days']<10){
  302. $value['days']='0'.$value['days'];
  303. }
  304. }
  305. if($value['hours']){
  306. if($type==1&&$value['hours']<10){
  307. $value['hours']='0'.$value['hours'];
  308. }
  309. }
  310. if($value['minutes']){
  311. if($type==1&&$value['minutes']<10){
  312. $value['minutes']='0'.$value['minutes'];
  313. }
  314. }
  315. if($value['seconds']){
  316. if($type==1&&$value['seconds']<10){
  317. $value['seconds']='0'.$value['seconds'];
  318. }
  319. }
  320. if($value['years']){
  321. $t=$value["years"] ."年".$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
  322. }else if($value['days']){
  323. $t=$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
  324. }else if($value['hours']){
  325. $t=$value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
  326. }else if($value['minutes']){
  327. $t=$value["minutes"] ."分".$value["seconds"]."秒";
  328. }else if($value['seconds']){
  329. $t=$value["seconds"]."秒";
  330. }
  331. return $t;
  332. }
  333. /**
  334. * 导出Excel
  335. * @param string $fileName 文件名称
  336. * @param array $headArr Excel标题头数组
  337. * @param array $data 数据内容
  338. * @param array $cellName Excel标题字母
  339. * @param string $suffix 文件后缀,xlsx 和 xls
  340. * @return bool
  341. */
  342. function exportExcel($fileName = "myData", $headArr = [], $data = [],$cellName = [], $suffix = 'xls'){
  343. @ini_set('memory_limit', '2048M');
  344. @set_time_limit(0);
  345. if (!$headArr || !$data || !is_array($data)) {
  346. return false;
  347. }
  348. require_once( CMF_ROOT."sdk/phpoffice/autoload.php");
  349. $fileName .= "_" . date("YmdHis");// 文件名称连接上相应的时间戳
  350. $spreadsheet = new PhpOffice\PhpSpreadsheet\Spreadsheet();
  351. $sheet = $spreadsheet->getActiveSheet();
  352. $cellNum = count($headArr);
  353. $dataNum = count($data);
  354. for($i=0;$i<$cellNum;$i++){
  355. $sheet->setCellValue($cellName[$i].'1', $headArr[$i][1]);
  356. }
  357. for($i=0;$i<$dataNum;$i++){
  358. for($j=0;$j<$cellNum;$j++){
  359. $sheet->setCellValue($cellName[$j].($i+2), filterEmoji( $data[$i][$headArr[$j][0]] ) );
  360. }
  361. }
  362. // 重命名表(UTF8编码不需要这一步)
  363. $fileName = iconv("utf-8", "gbk//IGNORE", $fileName);
  364. // 清理缓存
  365. ob_end_clean();
  366. if ($suffix == 'xlsx') {
  367. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  368. $class = "\PhpOffice\PhpSpreadsheet\Writer\Xlsx";
  369. } elseif ($suffix == 'xls') {
  370. header('Content-Type:application/vnd.ms-excel');
  371. $class = "\PhpOffice\PhpSpreadsheet\Writer\Xls";
  372. }
  373. header('Content-Disposition: attachment;filename="' . $fileName . '.' . $suffix . '"');
  374. header('Cache-Control: max-age=0');
  375. $writer = new $class($spreadsheet);
  376. $writer->save('php://output');
  377. // 删除清空 释放内存
  378. $spreadsheet->disconnectWorksheets();
  379. unset($spreadsheet);
  380. }
  381. function get_file_suffix($file_name, $allow_type = array()){
  382. $fnarray=explode('.', $file_name);
  383. $file_suffix = strtolower(end($fnarray));
  384. if (empty($allow_type)){
  385. return true;
  386. }else{
  387. if (in_array($file_suffix, $allow_type)){
  388. return true;
  389. }else{
  390. return false;
  391. }
  392. }
  393. }
  394. /*
  395. 单文件云存储
  396. files 单个文件上传信息(包含键值) $files['file']=$_FILES["file"]
  397. type 文件类型 img图片 video视频 music音乐
  398. */
  399. function adminUploadFilesBF($files='',$type="video"){
  400. $rs=array('code'=>1000,'data'=>[],'msg'=>'上传失败');
  401. //获取后台上传配置
  402. $configpri=getConfigPri();
  403. if($configpri['cloudtype']==1){ //七牛云存储
  404. require_once CMF_ROOT.'sdk/qiniu/autoload.php';
  405. // 需要填写你的 Access Key 和 Secret Key
  406. $accessKey = $configpri['qiniu_accesskey'];
  407. $secretKey = $configpri['qiniu_secretkey'];
  408. $bucket = $configpri['qiniu_bucket'];
  409. $qiniu_domain_url = $configpri['qiniu_domain_url'];
  410. // 构建鉴权对象
  411. $auth = new \Qiniu\Auth($accessKey, $secretKey);
  412. // 生成上传 Token
  413. $token = $auth->uploadToken($bucket);
  414. // 要上传文件的本地路径
  415. $filePath = $files['file']['tmp_name'];
  416. // 上传到七牛后保存的文件名
  417. $ext=strtolower(pathinfo($files['file']['name'], PATHINFO_EXTENSION));
  418. $key = date('Ymd').'/'.uniqid().'.'.$ext;
  419. // 初始化 UploadManager 对象并进行文件的上传。
  420. $uploadMgr = new \Qiniu\Storage\UploadManager();
  421. // 调用 UploadManager 的 putFile 方法进行文件的上传。
  422. list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
  423. if($err !== null){
  424. $rs['msg']=$err->getResponse()->error;
  425. return $rs;
  426. }
  427. $url=$key;
  428. $url_p=$qiniu_domain_url.$key;
  429. }else if($configpri['cloudtype']==2){ //腾讯云存储
  430. /* 腾讯云 */
  431. require_once(CMF_ROOT.'sdk/qcloud/autoload.php');
  432. $folder = '/'.$configpri['txvideofolder'];
  433. if($type=='img'){
  434. $folder = '/'.$configpri['tximgfolder'];
  435. }
  436. $file_name = $_FILES["file"]["name"];
  437. $src = $_FILES["file"]["tmp_name"];
  438. if($files){
  439. $file_name = $files["file"]["name"];
  440. $src = $files["file"]["tmp_name"];
  441. }
  442. $fnarray=explode('.', $file_name);
  443. $file_suffix = strtolower(end($fnarray)); //后缀名
  444. $dst = $folder.'/'.date('YmdHis').rand(1,999).'.'.$file_suffix;
  445. $cosClient = new \Qcloud\Cos\Client(array(
  446. 'region' => $configpri['txcloud_region'], #地域,如ap-guangzhou,ap-beijing-1
  447. 'credentials' => array(
  448. 'secretId' => $configpri['txcloud_secret_id'],
  449. 'secretKey' => $configpri['txcloud_secret_key'],
  450. ),
  451. ));
  452. // 若初始化 Client 时未填写 appId,则 bucket 的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
  453. $bucket = $configpri['txcloud_bucket'].'-'.$configpri['txcloud_appid'];
  454. try {
  455. $result = $cosClient->upload(
  456. $bucket = $bucket,
  457. $key = $dst,
  458. $body = fopen($src, 'rb')
  459. );
  460. $url = $result['Location'];
  461. $url_p=$url;
  462. } catch (\Exception $e) {
  463. $rs['msg']=$e->getMessage();
  464. return $rs;
  465. }
  466. }
  467. $rs['code']=0;
  468. $rs['data']['url']=$url;
  469. $rs['data']['url_p']=$url_p;
  470. return $rs;
  471. }
  472. /*
  473. 单文件云存储
  474. files 单个文件上传信息(包含键值) $files['file']=$_FILES["file"]
  475. type 文件类型 img图片 video视频 music音乐
  476. */
  477. function adminUploadFiles($files='',$type="video"){
  478. $name=$files["file"]['name'];
  479. $pathinfo=pathinfo($name);
  480. if(!isset($pathinfo['extension'])){
  481. $files["file"]['name']=$name.'.jpg';
  482. }
  483. $rs=array('code'=>1000,'data'=>[],'msg'=>'上传失败');
  484. //获取后台上传配置
  485. $configpri=getConfigPri();
  486. $cloudtype=$configpri['cloudtype'];
  487. if($cloudtype==1){ //七牛云存储
  488. require_once CMF_ROOT.'sdk/qiniu/autoload.php';
  489. // 需要填写你的 Access Key 和 Secret Key
  490. $accessKey = $configpri['qiniu_accesskey'];
  491. $secretKey = $configpri['qiniu_secretkey'];
  492. $bucket = $configpri['qiniu_bucket'];
  493. /* $qiniu_domain_url = $configpri['qiniu_domain_url']; */
  494. $qiniu_domain_url = $configpri['qiniu_protocol']."://".$configpri['qiniu_domain']."/";
  495. // 构建鉴权对象
  496. $auth = new \Qiniu\Auth($accessKey, $secretKey);
  497. // 生成上传 Token
  498. $token = $auth->uploadToken($bucket);
  499. // 要上传文件的本地路径
  500. $filePath = $files['file']['tmp_name'];
  501. // 上传到七牛后保存的文件名
  502. $ext=strtolower(pathinfo($files['file']['name'], PATHINFO_EXTENSION));
  503. $key = date('Ymd').'/'.uniqid().'.'.$ext;
  504. // 初始化 UploadManager 对象并进行文件的上传。
  505. $uploadMgr = new \Qiniu\Storage\UploadManager();
  506. // 调用 UploadManager 的 putFile 方法进行文件的上传。
  507. list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
  508. if($err !== null){
  509. $rs['msg']=$err->getResponse()->error;
  510. return $rs;
  511. }
  512. $url=$qiniu_domain_url.$key;
  513. $url_p=$key;
  514. }else if($cloudtype==2){ //腾讯云存储
  515. require_once(CMF_ROOT.'sdk/qcloud/autoload.php');
  516. if(isset($_FILES["image"])){
  517. $file_name = $_FILES["image"]["name"];
  518. $src = $_FILES["image"]["tmp_name"];
  519. }
  520. if(isset($_FILES["file"])){
  521. $file_name = $_FILES["file"]["name"];
  522. $src = $_FILES["file"]["tmp_name"];
  523. }
  524. if($files){
  525. $file_name = $files["file"]["name"];
  526. $src = $files["file"]["tmp_name"];
  527. }
  528. $fnarray=explode('.', $file_name);
  529. $file_suffix = strtolower(end($fnarray)); //后缀名
  530. $dst = date('YmdHis').rand(1,999).'.'.$file_suffix;
  531. $cosClient = new \Qcloud\Cos\Client(array(
  532. 'region' => $configpri['txcloud_region'], //地域,如ap-guangzhou,ap-beijing-1
  533. 'credentials' => array(
  534. 'secretId' => $configpri['txcloud_secret_id'],
  535. 'secretKey' => $configpri['txcloud_secret_key'],
  536. ),
  537. ));
  538. // 若初始化 Client 时未填写 appId,则 bucket 的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
  539. $bucket = $configpri['txcloud_bucket'].'-'.$configpri['txcloud_appid'];
  540. try {
  541. //opcache_reset();
  542. $result = $cosClient->upload(
  543. $bucket = $bucket,
  544. $key = $dst,
  545. $body = fopen($src, 'rb')
  546. );
  547. $url = $result['Location'];
  548. //$url_p=str_replace($configpri['tx_domain_url'], '', $url);
  549. $replace_url="http://".$configpri['txcloud_bucket']."-".$configpri['txcloud_appid'].".cos.".$configpri['txcloud_region'].".myqcloud.com/";
  550. $url_p=str_replace($replace_url, '', $url);
  551. $url=$configpri['tx_domain_url'].$url_p;
  552. } catch (\Exception $e) {
  553. $rs['msg']=$e->getMessage();
  554. return $rs;
  555. }
  556. }else if($cloudtype==3){ //亚马逊存储
  557. $name_arr=explode(".", $name);
  558. $suffix=$name_arr[count($name_arr)-1];
  559. $rand=rand(0,100000);
  560. $name=time().$rand.'.'.$suffix;
  561. $path= CMF_ROOT.'sdk/aws/aws-autoloader.php';
  562. require_once($path);
  563. if(!empty($files)){
  564. $configpri=getConfigPri();
  565. $sharedConfig = [
  566. 'profile' => 'default',
  567. 'region' => $configpri['aws_region'], //区域
  568. 'version' => 'latest',
  569. 'Content-Type' => $files["file"]['type'],
  570. //'debug' => true
  571. ];
  572. $sdk = new \Aws\Sdk($sharedConfig);
  573. $s3Client = $sdk->createS3();
  574. $result = $s3Client->putObject([
  575. 'Bucket' => $configpri['aws_bucket'],
  576. 'Key' => $name,
  577. 'ACL' => 'public-read',
  578. 'Content-Type' => $files["file"]['type'],
  579. 'Body' => fopen($files["file"]['tmp_name'], 'r')
  580. ]);
  581. $aws_res=1;
  582. $a = (array)$result;
  583. $n = 0;
  584. foreach($a as $k =>$t){
  585. if($n==0){
  586. $n++;
  587. $info = $t['ObjectURL'];
  588. if($info){
  589. //return $info;
  590. //return $name;
  591. }else{
  592. $aws_res=0;
  593. }
  594. }
  595. }
  596. if($aws_res){
  597. $url_p=$name;
  598. $url=$configpri['aws_hosturl'].$name;
  599. }
  600. }
  601. }
  602. $rs['code']=0;
  603. $rs['data']['url']=$url_p;
  604. $rs['data']['url_p']=setCloudType($url_p); //设置存储方式
  605. $rs['data']['url_c']=$url;
  606. $tx_private_signature=$configpri['tx_private_signature'];
  607. if($cloudtype==2 && $tx_private_signature){ //腾讯存储桶为私有读 需要进行文件验证签名
  608. $rs['data']['url_c']=setTxUrl($url_p); //签名地址
  609. }
  610. //return $rs;
  611. //同步Upload.php返回格式
  612. return [
  613. 'filepath' => $rs['data']['url_p'], //带存储方式的【存储用】
  614. "name" => '',
  615. 'id' => time().rand(1,99),
  616. 'preview_url' =>$rs['data']['url_c'], //带签名的【展示用】
  617. 'url' => $rs['data']['url_c'],
  618. 'code' =>0
  619. ];
  620. }
  621. /* 数字格式化 */
  622. function NumberFormat($num){
  623. if($num<10000){
  624. }else if($num<1000000){
  625. $num=round($num/10000,2).'万';
  626. }else if($num<100000000){
  627. $num=round($num/10000,1).'万';
  628. }else if($num<10000000000){
  629. $num=round($num/100000000,2).'亿';
  630. }else{
  631. $num=round($num/100000000,1).'亿';
  632. }
  633. return $num;
  634. }
  635. /* 生成邀请码 */
  636. function createCode(){
  637. $code = 'ABCDEFGHIJKLMNPQRSTUVWXYZ';
  638. $rand = $code[rand(0,25)]
  639. .strtoupper(dechex(date('m')))
  640. .date('d').substr(time(),-5)
  641. .substr(microtime(),2,5)
  642. .sprintf('%02d',rand(0,99));
  643. for(
  644. $a = md5( $rand, true ),
  645. $s = '123456789ABCDEFGHIJKLMNPQRSTUV',
  646. $d = '',
  647. $f = 0;
  648. $f < 6;
  649. $g = ord( $a[ $f ] ),
  650. $d .= $s[ ( $g ^ ord( $a[ $f + 6 ] ) ) - $g & 0x1F ],
  651. $f++
  652. );
  653. if(mb_strlen($d)==6){
  654. $oneinfo=Db::name("user")->field("id")->where("code='{$d}'")->find();
  655. if(!$oneinfo){
  656. return $d;
  657. }
  658. }
  659. $d=createCode();
  660. return $d;
  661. }
  662. function m_s($a){
  663. return $a;
  664. }
  665. /**
  666. * @desc 获取推拉流地址
  667. * @param string $host 协议,如:http、rtmp
  668. * @param string $stream 流名,如有则包含 .flv、.m3u8
  669. * @param int $type 类型,0表示播流,1表示推流
  670. */
  671. function PrivateKeyA($host,$stream,$type){
  672. $configpri=getConfigPri();
  673. $cdn_switch=$configpri['cdn_switch'];
  674. //$cdn_switch=2;
  675. switch($cdn_switch){
  676. case '1':
  677. $url=PrivateKey_tx($host,$stream,$type);
  678. break;
  679. }
  680. return $url;
  681. }
  682. /**
  683. * @desc 腾讯云推拉流地址
  684. * @param string $host 协议,如:http、rtmp
  685. * @param string $stream 流名,如有则包含 .flv、.m3u8
  686. * @param int $type 类型,0表示播流,1表示推流
  687. */
  688. function PrivateKey_tx($host,$stream,$type){
  689. $configpri=getConfigPri();
  690. $bizid=$configpri['tx_bizid'];
  691. $push_url_key=$configpri['tx_push_key'];
  692. $push=$configpri['tx_push'];
  693. $pull=$configpri['tx_pull'];
  694. $stream_a=explode('.',$stream);
  695. $streamKey = isset($stream_a[0])? $stream_a[0] : '';
  696. $ext = isset($stream_a[1])? $stream_a[1] : '';
  697. //$live_code = $bizid . "_" .$streamKey;
  698. $live_code = $streamKey;
  699. $now_time = time() + 3*60*60;
  700. $txTime = dechex($now_time);
  701. $txSecret = md5($push_url_key . $live_code . $txTime);
  702. $safe_url = "?txSecret=" .$txSecret."&txTime=" .$txTime;
  703. if($type==1){
  704. //$push_url = "rtmp://" . $bizid . ".livepush2.myqcloud.com/live/" . $live_code . "?bizid=" . $bizid . "&record=flv" .$safe_url; 可录像
  705. //$url = "rtmp://" . $bizid .".livepush2.myqcloud.com/live/" . $live_code . "?bizid=" . $bizid . "" .$safe_url;
  706. $url=array(
  707. 'cdn'=>urlencode("rtmp://{$push}/live/"),
  708. 'stream'=>urlencode($live_code.$safe_url),
  709. );
  710. }else{
  711. $url = "http://{$pull}/live/" . $live_code . ".flv";
  712. if($ext){
  713. $url = "http://{$pull}/live/" . $live_code . ".".$ext;
  714. }
  715. $configpub=getConfigPub();
  716. if(strstr($configpub['site'],'https')){
  717. $url=str_replace('http:','https:',$url);
  718. }
  719. if($type==3){ //前台直播间使用
  720. $url_a=explode('/'.$live_code,$url);
  721. $url=array(
  722. 'cdn'=>urlencode("rtmp://{$pull}/live/"),
  723. 'stream'=>urlencode($live_code),
  724. );
  725. }
  726. }
  727. return $url;
  728. }
  729. /************腾讯云存储私有读写的签名验证start*************/
  730. function setTxUrl($url){
  731. /*if(!strstr($url,'myqcloud')){
  732. return $url;
  733. }*/
  734. $url_a=parse_url($url);
  735. // 获取前端过来的参数
  736. $method = isset($_GET['method']) ? $_GET['method'] : 'get';
  737. $pathname = isset($url_a['path']) ? $url_a['path'] : '/';
  738. if($pathname=="/"){
  739. return $url;
  740. }
  741. $signinfo=getcaches($pathname);
  742. if($signinfo){
  743. $now=time();
  744. if($signinfo['endtime']>$now){
  745. return $url."?".$signinfo['sign'];
  746. }
  747. }
  748. // 获取临时密钥,计算签名
  749. $tempKeys = getTempKeys();
  750. if ($tempKeys && isset($tempKeys['credentials'])) {
  751. $data = array(
  752. 'Authorization' => getAuthorization($tempKeys, $method, $pathname),
  753. //'Authorization' => aaa($tempKeys),
  754. 'XCosSecurityToken' => $tempKeys['credentials']['sessionToken'],
  755. );
  756. } else {
  757. //$data = array('error'=> $tempKeys);
  758. return $url;
  759. }
  760. $sign=$data['Authorization']."&x-cos-security-token=".$data['XCosSecurityToken'];
  761. $signArr=array(
  762. "endtime"=>time()-10+600,
  763. "sign"=>$sign
  764. );
  765. setcaches($pathname,$signArr);
  766. $str=$url."?".$sign;
  767. return $str;
  768. }
  769. // 获取临时密钥
  770. function getTempKeys() {
  771. $config=getCosConfig();
  772. // 判断是否修改了 AllowPrefix
  773. if ($config['AllowPrefix'] === '_ALLOW_DIR_/*') {
  774. return array('error'=> '请修改 AllowPrefix 配置项,指定允许上传的路径前缀');
  775. }
  776. $ShortBucketName = substr($config['Bucket'],0, strripos($config['Bucket'], '-'));
  777. $AppId = substr($config['Bucket'], 1 + strripos($config['Bucket'], '-'));
  778. $policy = array(
  779. 'version'=> '2.0',
  780. 'statement'=> array(
  781. array(
  782. 'action'=> array(
  783. // 简单文件操作
  784. 'name/cos:PutObject',
  785. 'name/cos:PostObject',
  786. 'name/cos:AppendObject',
  787. 'name/cos:GetObject',
  788. 'name/cos:HeadObject',
  789. 'name/cos:OptionsObject',
  790. 'name/cos:PutObjectCopy',
  791. 'name/cos:PostObjectRestore',
  792. // 分片上传操作
  793. 'name/cos:InitiateMultipartUpload',
  794. 'name/cos:ListMultipartUploads',
  795. 'name/cos:ListParts',
  796. 'name/cos:UploadPart',
  797. 'name/cos:CompleteMultipartUpload',
  798. 'name/cos:AbortMultipartUpload',
  799. ),
  800. 'effect'=> 'allow',
  801. 'principal'=> array('qcs'=> array('*')),
  802. 'resource'=> array(
  803. 'qcs::cos:' . $config['Region'] . ':uid/' . $AppId . ':prefix//' . $AppId . '/' . $ShortBucketName . '/',
  804. 'qcs::cos:' . $config['Region'] . ':uid/' . $AppId . ':prefix//' . $AppId . '/' . $ShortBucketName . '/' . resourceUrlEncode($config['AllowPrefix'])
  805. )
  806. )
  807. )
  808. );
  809. $policyStr = str_replace('\\/', '/', json_encode($policy));
  810. $Action = 'GetFederationToken';
  811. $Nonce = rand(10000, 20000);
  812. $Timestamp = time() - 1;
  813. $Method = 'GET';
  814. $params = array(
  815. 'Action'=> $Action,
  816. 'Nonce'=> $Nonce,
  817. 'Region'=> '',
  818. 'SecretId'=> $config['SecretId'],
  819. 'Timestamp'=> $Timestamp,
  820. 'durationSeconds'=> 7200,
  821. 'name'=> 'cos',
  822. 'policy'=> urlencode($policyStr)
  823. );
  824. $params['Signature'] = urlencode(getSignature($params, $config['SecretKey'], $Method));
  825. $url = $config['Url'] . '?' . json2str($params);
  826. $ch = curl_init($url);
  827. $config['Proxy'] && curl_setopt($ch, CURLOPT_PROXY, $config['Proxy']);
  828. curl_setopt($ch, CURLOPT_HEADER, 0);
  829. curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,0);
  830. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,0);
  831. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  832. $result = curl_exec($ch);
  833. if(curl_errno($ch)) $result = curl_error($ch);
  834. curl_close($ch);
  835. $result = json_decode($result, 1);
  836. if (isset($result['data'])) $result = $result['data'];
  837. return $result;
  838. }
  839. function getCosConfig(){
  840. $configpri=getConfigPri();
  841. // 配置参数
  842. $config = array(
  843. 'Url' => 'https://sts.api.qcloud.com/v2/index.php',
  844. 'Domain' => 'sts.api.qcloud.com',
  845. 'Proxy' => '',
  846. 'SecretId' => $configpri['txcloud_secret_id'], // 固定密钥
  847. 'SecretKey' => $configpri['txcloud_secret_key'], // 固定密钥
  848. 'Bucket' => $configpri['txcloud_bucket'].'-'.$configpri['txcloud_appid'],//dsp-1257569725,
  849. 'Region' => $configpri['txcloud_region'], //存储桶地域
  850. 'AllowPrefix' => '*', // 这里改成允许的路径前缀,这里可以根据自己网站的用户登录态判断允许上传的目录,例子:* 或者 a/* 或者 a.jpg
  851. );
  852. return $config;
  853. }
  854. // 计算临时密钥用的签名
  855. function resourceUrlEncode($str) {
  856. $str = rawurlencode($str);
  857. //特殊处理字符 !()~
  858. $str = str_replace('%2F', '/', $str);
  859. $str = str_replace('%2A', '*', $str);
  860. $str = str_replace('%21', '!', $str);
  861. $str = str_replace('%28', '(', $str);
  862. $str = str_replace('%29', ')', $str);
  863. $str = str_replace('%7E', '~', $str);
  864. return $str;
  865. }
  866. // 计算 COS API 请求用的签名
  867. function getAuthorization($keys, $method, $pathname){
  868. // 获取个人 API 密钥 https://console.qcloud.com/capi
  869. $SecretId = $keys['credentials']['tmpSecretId'];
  870. $SecretKey = $keys['credentials']['tmpSecretKey'];
  871. // 整理参数
  872. $query = array();
  873. $headers = array();
  874. $method = strtolower($method ? $method : 'get');
  875. $pathname = $pathname ? $pathname : '/';
  876. substr($pathname, 0, 1) != '/' && ($pathname = '/' . $pathname);
  877. // 签名有效起止时间
  878. $now = time() - 1;
  879. $expired = $now + 600; // 签名过期时刻,600 秒后
  880. // 要用到的 Authorization 参数列表
  881. $qSignAlgorithm = 'sha1';
  882. $qAk = $SecretId;
  883. $qSignTime = $now . ';' . $expired;
  884. //$qSignTime = "1554284206;1554287806";
  885. //$qKeyTime = $now . ';' . $expired;
  886. $qKeyTime = $qSignTime;
  887. $qHeaderList = strtolower(implode(';', getObjectKeys($headers)));
  888. $qUrlParamList = strtolower(implode(';', getObjectKeys($query)));
  889. // 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
  890. // 步骤一:计算 SignKey
  891. $signKey = hash_hmac("sha1", $qKeyTime, $SecretKey);
  892. // 步骤二:构成 FormatString
  893. $formatString = implode("\n", array(strtolower($method), $pathname, obj2str($query), obj2str($headers), ''));
  894. //header('x-test-method', $method);
  895. // header('x-test-pathname', $pathname);
  896. // 步骤三:计算 StringToSign
  897. $stringToSign = implode("\n", array('sha1', $qSignTime, sha1($formatString), ''));
  898. // 步骤四:计算 Signature
  899. $qSignature = hash_hmac('sha1', $stringToSign, $signKey);
  900. // 步骤五:构造 Authorization
  901. $authorization = implode('&', array(
  902. 'q-sign-algorithm=' . $qSignAlgorithm,
  903. 'q-ak=' . $qAk,
  904. 'q-sign-time=' . $qSignTime,
  905. 'q-key-time=' . $qKeyTime,
  906. 'q-header-list=' . $qHeaderList,
  907. 'q-url-param-list=' . $qUrlParamList,
  908. 'q-signature=' . $qSignature
  909. ));
  910. return $authorization;
  911. }
  912. // 工具方法
  913. function getObjectKeys($obj){
  914. $list = array_keys($obj);
  915. sort($list);
  916. return $list;
  917. }
  918. function obj2str($obj){
  919. $list = array();
  920. $keyList = getObjectKeys($obj);
  921. $len = count($keyList);
  922. for ($i = 0; $i < $len; $i++) {
  923. $key = $keyList[$i];
  924. $val = isset($obj[$key]) ? $obj[$key] : '';
  925. $key = strtolower($key);
  926. $list[] = rawurlencode($key) . '=' . rawurlencode($val);
  927. }
  928. return implode('&', $list);
  929. }
  930. // 计算临时密钥用的签名
  931. function getSignature($opt, $key, $method) {
  932. $config=getCosConfig();
  933. $formatString = $method . $config['Domain'] . '/v2/index.php?' . json2str($opt);
  934. $formatString = urldecode($formatString);
  935. $sign = hash_hmac('sha1', $formatString, $key);
  936. $sign = base64_encode(hex2bin($sign));
  937. return $sign;
  938. }
  939. // obj 转 query string
  940. function json2str($obj) {
  941. ksort($obj);
  942. $arr = array();
  943. foreach ($obj as $key => $val) {
  944. array_push($arr, $key . '=' . $val);
  945. }
  946. return join('&', $arr);
  947. }
  948. /*************私有读写的签名验证end*****************/
  949. //为文件拼接存储方式,方便get_upload_path做签名处理
  950. function setCloudType($url){
  951. $configpri=getConfigPri();
  952. $cloudtype=$configpri['cloudtype'];
  953. //file_put_contents("zzza.txt", $url);
  954. $url=$url."%@%cloudtype=".$cloudtype;
  955. //file_put_contents("zzz.txt", $url);
  956. return $url;
  957. }
  958. //写入映票收入记录
  959. function setVoteRecord($data){
  960. Db::name("votes_record")->insert($data);
  961. }
  962. //写入钻石消费记录
  963. function setCoinRecord($data){
  964. Db::name("user_coinrecord")->insert($data);
  965. }
  966. //更新用户的映票
  967. function changeUserVotes($uid,$votes,$type){ //type 为0 扣费 type 为1 增加
  968. if(!$type){
  969. $res=Db::name("user")->where("id={$uid} and votes >={$votes}")->dec("votes",$votes)->update();
  970. }else{
  971. $res=Db::name("user")->where("id={$uid}")->inc("votes",$votes)->update();
  972. $res=Db::name("user")->where("id={$uid}")->inc("votestotal",$votes)->update();
  973. }
  974. if(!$res){
  975. return 0;
  976. }
  977. return 1;
  978. }
  979. //更新用户的钻石数
  980. function changeUserCoin($uid,$coin,$type=0){ //type 为0 扣费 type 为1 增加
  981. if(!$type){
  982. $res=Db::name("user")->where("id={$uid} and coin>={$coin}")->dec("coin",$coin)->update();
  983. }else{
  984. $res=Db::name("user")->where("id={$uid}")->inc("coin",$coin)->update();
  985. }
  986. if(!$res){
  987. return 0;
  988. }
  989. if(!$type){
  990. Db::name("user")->where("id={$uid}")->inc("consumption",$coin)->update();
  991. }
  992. return 1;
  993. }
  994. //获取粉丝数量
  995. function getFans($uid){
  996. $count=Db::name("user_attention")->where("touid={$uid}")->count();
  997. return $count;
  998. }
  999. //获取用户的vip信息
  1000. function getUserVipInfo($uid){
  1001. $result=array();
  1002. $now=time();
  1003. $vipInfo=Db::name("user")->where("id={$uid}")->field("vip_endtime")->find();
  1004. if(!$vipInfo){
  1005. $result['isvip']='0';
  1006. $result['vip_endtime']='';
  1007. return $result;
  1008. }
  1009. if($vipInfo['vip_endtime']<=$now){
  1010. $result['isvip']='0';
  1011. $result['vip_endtime']='';
  1012. return $result;
  1013. }
  1014. $result['isvip']='1';
  1015. $result['vip_endtime']=date("Y.m.d",$vipInfo['vip_endtime']);
  1016. return $result;
  1017. }
  1018. /*删除极光用户*/
  1019. /*function delIMUser($uid){
  1020. //获取后台配置的极光推送app_key和master_secret
  1021. $configPri=getConfigPri();
  1022. $appKey = $configPri['jpush_key'];
  1023. $masterSecret = $configPri['jpush_secret'];
  1024. if($appKey&&$masterSecret){
  1025. //极光IM
  1026. require_once CMF_ROOT.'sdk/jmessage/autoload.php'; //导入极光IM类库
  1027. $jm = new \JMessage\JMessage($appKey, $masterSecret);
  1028. $user = new \JMessage\IM\User($jm);
  1029. $before=userSendBefore(); //获取极光用户账号前缀
  1030. $username=$before.$uid;
  1031. $response=$user->delete($username);
  1032. }
  1033. }*/
  1034. /* 房间管理员 */
  1035. function getIsAdmin($uid,$showid){
  1036. if($uid==$showid){
  1037. return 50;
  1038. }
  1039. $isuper=isSuper($uid);
  1040. if($isuper){
  1041. return 60;
  1042. }
  1043. $where['uid']=$uid;
  1044. $where['liveuid']=$showid;
  1045. $id=Db::name("user_livemanager")->where($where)->find();
  1046. if($id) {
  1047. return 40;
  1048. }
  1049. return 30;
  1050. }
  1051. /* 判断账号是否超管 */
  1052. function isSuper($uid){
  1053. $where['uid']=$uid;
  1054. $isexist=Db::name("user_super")->where($where)->find();
  1055. if($isexist){
  1056. return 1;
  1057. }
  1058. return 0;
  1059. }
  1060. //判断用户是否注销
  1061. function checkIsDestroy($uid){
  1062. $user_status=Db::name("user")->where("id={$uid}")->value('user_status');
  1063. if($user_status==3){
  1064. return 1;
  1065. }
  1066. return 0;
  1067. }
  1068. /* 管理员操作日志 */
  1069. function setAdminLog($action){
  1070. $data=array(
  1071. 'adminid'=>session('ADMIN_ID'),
  1072. 'admin'=>session('name'),
  1073. 'action'=>$action,
  1074. 'ip'=>ip2long(get_client_ip(0,true)),
  1075. 'addtime'=>time(),
  1076. );
  1077. Db::name("admin_log")->insert($data);
  1078. return !0;
  1079. }
  1080. //身份证检测
  1081. function checkCardNo($cardno){
  1082. $preg='/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/';
  1083. $isok=preg_match($preg, $cardno);
  1084. if($isok){
  1085. return 1;
  1086. }else{
  1087. return 0;
  1088. }
  1089. }
  1090. // 获取店铺商品订单详情
  1091. function getShopOrderInfo($where,$files='*'){
  1092. $info=Db::name("shop_order")
  1093. ->field($files)
  1094. ->where($where)
  1095. ->find();
  1096. return $info;
  1097. }
  1098. // 获取店铺商品订单退款详情
  1099. function getShopOrderRefundInfo($where,$files='*'){
  1100. $info=Db::name("shop_order_refund")
  1101. ->field($files)
  1102. ->where($where)
  1103. ->find();
  1104. return $info;
  1105. }
  1106. //获取店铺协商历史
  1107. function getShopOrderRefundList($where){
  1108. $list=Db::name("shop_order_refund_list")
  1109. ->where($where)
  1110. ->order("addtime desc")
  1111. ->select();
  1112. return $list;
  1113. }
  1114. ///////////////////////////////////////快递鸟物流信息查询start/////////////////////////////////////////////
  1115. //快递鸟获取物流信息
  1116. function getExpressInfoByKDN($express_code,$express_number,$phone){
  1117. $configpri=getConfigPri();
  1118. $EBusinessID=isset($configpri['express_id'])?$configpri['express_id']:'';
  1119. $AppKey=isset($configpri['express_appkey'])?$configpri['express_appkey']:'';
  1120. $ReqURL='https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx'; //在途监控即时查询
  1121. $requestData=array(
  1122. 'ShipperCode'=>$express_code,
  1123. 'LogisticCode'=>$express_number,
  1124. );
  1125. if($express_code=='SF' || $express_code=='KYSY' ){ //顺丰/跨越 要带上发件人/收件人手机号的后四位
  1126. $requestData['CustomerName']=substr($phone, -4);
  1127. }
  1128. $requestData= json_encode($requestData);
  1129. $datas = array(
  1130. 'EBusinessID' => $EBusinessID,
  1131. 'RequestType' => '8001',
  1132. 'RequestData' => urlencode($requestData) ,
  1133. 'DataType' => '2',
  1134. );
  1135. $datas['DataSign'] = encrypt_kdn($requestData, $AppKey);
  1136. $result=sendPost_KDN($ReqURL, $datas);
  1137. return json_decode($result,true);
  1138. }
  1139. /**
  1140. * 快递鸟电商Sign签名生成
  1141. * @param data 内容
  1142. * @param appkey Appkey
  1143. * @return DataSign签名
  1144. */
  1145. function encrypt_kdn($data, $appkey) {
  1146. return urlencode(base64_encode(md5($data.$appkey)));
  1147. }
  1148. /**
  1149. * post提交数据
  1150. * @param string $url 请求Url
  1151. * @param array $datas 提交的数据
  1152. * @return url响应返回的html
  1153. */
  1154. function sendPost_KDN($url, $datas) {
  1155. $temps = array();
  1156. foreach ($datas as $key => $value) {
  1157. $temps[] = sprintf('%s=%s', $key, $value);
  1158. }
  1159. $post_data = implode('&', $temps);
  1160. $url_info = parse_url($url);
  1161. if(empty($url_info['port']))
  1162. {
  1163. $url_info['port']=80;
  1164. }
  1165. $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
  1166. $httpheader.= "Host:" . $url_info['host'] . "\r\n";
  1167. $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
  1168. $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
  1169. $httpheader.= "Connection:close\r\n\r\n";
  1170. $httpheader.= $post_data;
  1171. $fd = fsockopen($url_info['host'], $url_info['port']);
  1172. fwrite($fd, $httpheader);
  1173. $gets = "";
  1174. $headerFlag = true;
  1175. while (!feof($fd)) {
  1176. if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
  1177. break;
  1178. }
  1179. }
  1180. while (!feof($fd)) {
  1181. $gets.= fread($fd, 128);
  1182. }
  1183. fclose($fd);
  1184. return $gets;
  1185. }
  1186. function is_true($val, $return_null=false){
  1187. $boolval = ( is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : (bool) $val );
  1188. return ( $boolval===null && !$return_null ? false : $boolval );
  1189. }
  1190. ///////////////////////////////////////快递鸟物流信息查询end/////////////////////////////////////////////
  1191. //获取店铺设置的有效时间
  1192. function getShopEffectiveTime(){
  1193. $configpri=getConfigPri();
  1194. $shop_payment_time=$configpri['shop_payment_time']; //付款有效时间(单位:分钟)
  1195. $shop_shipment_time=$configpri['shop_shipment_time']; //发货有效时间(单位:天)
  1196. $shop_receive_time=$configpri['shop_receive_time']; //自动确认收货时间(单位:天)
  1197. $shop_refund_time=$configpri['shop_refund_time']; //买家发起退款,卖家不做处理自动退款时间(单位:天)
  1198. $shop_refund_finish_time=$configpri['shop_refund_finish_time']; //卖家拒绝买家退款后,买家不做任何操作,退款自动完成时间(单位:天)
  1199. $shop_receive_refund_time=$configpri['shop_receive_refund_time']; //订单确认收货后,指定天内可以发起退货退款(单位:天)
  1200. $shop_settlement_time=$configpri['shop_settlement_time']; //订单确认收货后,货款自动打到卖家的时间(单位:天)
  1201. $data['shop_payment_time']=$shop_payment_time;
  1202. $data['shop_shipment_time']=$shop_shipment_time;
  1203. $data['shop_receive_time']=$shop_receive_time;
  1204. $data['shop_refund_time']=$shop_refund_time;
  1205. $data['shop_refund_finish_time']=$shop_refund_finish_time;
  1206. $data['shop_receive_refund_time']=$shop_receive_refund_time;
  1207. $data['shop_settlement_time']=$shop_settlement_time;
  1208. return $data;
  1209. }
  1210. //修改商品订单
  1211. function changeShopOrderStatus($uid,$orderid,$data){
  1212. $res=Db::name('shop_order')
  1213. ->where("id={$orderid}")
  1214. ->update($data);
  1215. return $res;
  1216. }
  1217. //更改商品库存
  1218. function changeShopGoodsSpecNum($goodsid,$spec_id,$nums,$type){
  1219. $goods_info=Db::name("shop_goods")
  1220. ->where("id={$goodsid}")
  1221. ->find();
  1222. if(!$goods_info){
  1223. return 0;
  1224. }
  1225. $spec_arr=json_decode($goods_info['specs'],true);
  1226. $specid_arr=array_column($spec_arr, 'spec_id');
  1227. if(!in_array($spec_id, $specid_arr)){
  1228. return 0;
  1229. }
  1230. foreach ($spec_arr as $k => $v) {
  1231. if($v['spec_id']==$spec_id){
  1232. if($type==1){
  1233. $spec_num=$v['spec_num']+$nums;
  1234. }else{
  1235. $spec_num=$v['spec_num']-$nums;
  1236. }
  1237. if($spec_num<0){
  1238. $spec_num=0;
  1239. }
  1240. $spec_arr[$k]['spec_num']=(string)$spec_num;
  1241. }
  1242. }
  1243. $spec_str=json_encode($spec_arr);
  1244. Db::name("shop_goods")->where("id={$goodsid}")->update(array('specs'=>$spec_str));
  1245. return 1;
  1246. }
  1247. //写入订单操作记录
  1248. function addShopGoodsOrderMessage($data){
  1249. $res=Db::name("shop_order_message")->insert($data);
  1250. return $res;
  1251. }
  1252. //修改用户的余额 type:0 扣除余额 1 增加余额
  1253. function setUserBalance($uid,$type,$balance){
  1254. $res=0;
  1255. if($type==0){ //扣除用户余额,增加用户余额消费总额
  1256. Db::name("user")
  1257. ->where("id={$uid} and balance>={$balance}")
  1258. ->dec('balance',$balance)
  1259. ->update();
  1260. $res=Db::name("user")
  1261. ->where("id={$uid}")
  1262. ->inc('balance_consumption',$balance)
  1263. ->update();
  1264. }else if($type==1){ //增加用户余额
  1265. Db::name("user")
  1266. ->where("id={$uid}")
  1267. ->inc('balance',$balance)
  1268. ->update();
  1269. $res=Db::name("user")
  1270. ->where("id={$uid}")
  1271. ->inc('balance_total',$balance)
  1272. ->update();
  1273. }
  1274. return $res;
  1275. }
  1276. //添加余额操作记录
  1277. function addBalanceRecord($data){
  1278. $res=Db::name("user_balance_record")->insert($data);
  1279. return $res;
  1280. }
  1281. //更新商品的销量 type=0 减 type=1 增
  1282. function changeShopGoodsSaleNums($goodsid,$type,$nums){
  1283. if($type==0){
  1284. $res=Db::name("shop_goods")
  1285. ->where("id={$goodsid} and sale_nums>= {$nums}")
  1286. ->dec('sale_nums',$nums)
  1287. ->update();
  1288. }else{
  1289. $res=Db::name("shop_goods")
  1290. ->where("id={$goodsid}")
  1291. ->inc('sale_nums',$nums)
  1292. ->update();
  1293. }
  1294. return $res;
  1295. }
  1296. //更新店铺的销量 type=0 减 type=1 增
  1297. function changeShopSaleNums($uid,$type,$nums){
  1298. if($type==0){
  1299. $res=Db::name("shop_apply")
  1300. ->where("uid={$uid} and sale_nums>= {$nums}")
  1301. ->dec('sale_nums',$nums)
  1302. ->update();
  1303. }else{
  1304. $res=Db::name("shop_apply")
  1305. ->where("uid={$uid}")
  1306. ->inc('sale_nums',$nums)
  1307. ->update();
  1308. }
  1309. return $res;
  1310. }
  1311. //更改退款详情信息
  1312. function changeGoodsOrderRefund($where,$data){
  1313. $res=Db::name("shop_order_refund")
  1314. ->where($where)
  1315. ->update($data);
  1316. return $res;
  1317. }
  1318. //写入退款协商记录
  1319. function setGoodsOrderRefundList($data){
  1320. $res=Db::name("shop_order_refund_list")->insert($data);
  1321. return $res;
  1322. }
  1323. /* 店铺订单支付时 处理店铺订单支付 */
  1324. function handelShopOrder($where,$data=[]){
  1325. $orderinfo=Db::name("shop_order")->where($where)->find();
  1326. if(!$orderinfo){
  1327. return 0;
  1328. }
  1329. if($orderinfo['status']==-1){ //已关闭
  1330. return -1;
  1331. }
  1332. if($orderinfo['status']!=0){
  1333. return 1;
  1334. }
  1335. $now=time();
  1336. /* 更新 订单状态 */
  1337. $data['status']=1;
  1338. $data['paytime']= $now;
  1339. Db::name("shop_order")->where("id='{$orderinfo['id']}'")->update($data);
  1340. $uid=$orderinfo['uid'];
  1341. $balance_consumption=Db::name("user")->where("id={$uid}")->value("balance_consumption");
  1342. //增加用户的商城累计消费
  1343. Db::name("user")->where("id={$uid}")->inc("balance_consumption",$orderinfo['total'])->update();
  1344. //增加商品销量
  1345. changeShopGoodsSaleNums($orderinfo['goodsid'],1,$orderinfo['nums']);
  1346. //增加店铺销量
  1347. changeShopSaleNums($orderinfo['shop_uid'],1,$orderinfo['nums']);
  1348. //写入订单信息
  1349. $title="你的商品“".$orderinfo['goods_name']."”收到一笔新订单,订单编号:".$orderinfo['orderno'];
  1350. $data1=array(
  1351. 'uid'=>$orderinfo['shop_uid'],
  1352. 'orderid'=>$orderinfo['id'],
  1353. 'title'=>$title,
  1354. 'addtime'=>$now,
  1355. 'type'=>'1'
  1356. );
  1357. addShopGoodsOrderMessage($data1);
  1358. //发送腾讯云IM
  1359. txMessageIM($title,$orderinfo['shop_uid'],'goodsorder_admin');
  1360. return 2;
  1361. }
  1362. //写入系统消息
  1363. function addSysytemInfo($uid,$title,$msg){
  1364. //极光IM
  1365. $aid=session('ADMIN_ID');
  1366. $user=Db::name("user")->where("id='{$aid}'")->find();
  1367. //向系统通知表中写入数据
  1368. $sysInfo=array(
  1369. 'title'=>$title,
  1370. 'addtime'=>time(),
  1371. 'admin'=>$user['user_login'],
  1372. 'ip'=>$_SERVER['REMOTE_ADDR'],
  1373. 'uid'=>$uid,
  1374. 'content'=>$msg,
  1375. );
  1376. $id=Db::name("system_push")->insertGetId($sysInfo);
  1377. return $id;
  1378. }
  1379. //修改代售平台商品记录的信息
  1380. function setOnsalePlatformInfo($where,$data){
  1381. Db::name("seller_platform_goods")
  1382. ->where($where)
  1383. ->update($data);
  1384. }
  1385. /* ip限定 */
  1386. function ip_limit(){
  1387. $configpri=getConfigPri();
  1388. if($configpri['iplimit_switch']==0){
  1389. return 0;
  1390. }
  1391. $date = date("Ymd");
  1392. $ip= ip2long($_SERVER["REMOTE_ADDR"]);
  1393. $isexist=Db::name("getcode_limit_ip")
  1394. ->field("ip,date,times")
  1395. ->where("ip={$ip}")
  1396. ->find();
  1397. if(!$isexist){
  1398. $data=array(
  1399. "ip" => $ip,
  1400. "date" => $date,
  1401. "times" => 1,
  1402. );
  1403. $isexist=Db::name("getcode_limit_ip")->insert($data);
  1404. return 0;
  1405. }elseif($date == $isexist['date'] && $isexist['times'] >= $configpri['iplimit_times'] ){
  1406. return 1;
  1407. }else{
  1408. if($date == $isexist['date']){
  1409. $isexist=Db::name("getcode_limit_ip")
  1410. ->where("ip={$ip}")
  1411. ->inc("times",1)
  1412. ->update();
  1413. return 0;
  1414. }else{
  1415. $isexist=Db::name("getcode_limit_ip")
  1416. ->where("ip={$ip}")
  1417. ->update(array('date'=> $date ,'times'=>1));
  1418. return 0;
  1419. }
  1420. }
  1421. }
  1422. /* 随机数 */
  1423. function random($length = 6 , $numeric = 0) {
  1424. PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
  1425. if($numeric) {
  1426. $hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
  1427. } else {
  1428. $hash = '';
  1429. $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
  1430. $max = strlen($chars) - 1;
  1431. for($i = 0; $i < $length; $i++) {
  1432. $hash .= $chars[mt_rand(0, $max)];
  1433. }
  1434. }
  1435. return $hash;
  1436. }
  1437. /* 发送验证码 -- 阿里云 */
  1438. function sendCode($mobile,$code){
  1439. $rs = array('code' => 0, 'msg' => '', 'info' => array());
  1440. $config = getConfigPri();
  1441. if(!$config['sendcode_switch']){
  1442. $rs['code']=667;
  1443. $rs['msg']='123456';
  1444. return $rs;
  1445. }
  1446. if($config['code_switch']=='1'){//阿里云
  1447. $res=sendCodeByAli($mobile,$code);
  1448. }else{
  1449. $res=sendCodeByRonglian($mobile,$code);//容联云
  1450. }
  1451. return $rs;
  1452. }
  1453. //阿里云短信
  1454. function sendCodeByAli($mobile,$code){
  1455. $rs = array('code' => 0, 'msg' => '', 'info' => array());
  1456. $configpri = getConfigPri();
  1457. require_once CMF_ROOT.'sdk/aliyunsms/AliSmsApi.php';
  1458. $config = array(
  1459. 'accessKeyId' =>$configpri['aly_keydi'],
  1460. 'accessKeySecret' =>$configpri['aly_secret'],
  1461. 'PhoneNumbers' => $mobile,
  1462. 'SignName' => $configpri['aly_signName'],
  1463. 'TemplateCode' => $configpri['aly_templateCode'],
  1464. 'TemplateParam' => array("code"=>$code)
  1465. );
  1466. $go = new \AliSmsApi($config);
  1467. $result = $go->send_sms();
  1468. file_put_contents(CMF_ROOT.'log/sendCode_aly_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 result:'.json_encode($result)."\r\n",FILE_APPEND);
  1469. if($result == NULL ) {
  1470. $rs['code']=1002;
  1471. $rs['msg']="发送失败";
  1472. return $rs;
  1473. }
  1474. if($result['Code']!='OK') {
  1475. //TODO 添加错误处理逻辑
  1476. $rs['code']=1002;
  1477. $rs['msg']="获取失败";
  1478. return $rs;
  1479. }
  1480. return $rs;
  1481. }
  1482. function sendCodeByRonglian($mobile,$code){
  1483. $rs = array('code' => 0, 'msg' => '', 'info' => array());
  1484. $config = getConfigPri();
  1485. require_once CMF_ROOT.'sdk/ronglianyun/CCPRestSDK.php';
  1486. //主帐号
  1487. $accountSid= $config['ccp_sid'];
  1488. //主帐号Token
  1489. $accountToken= $config['ccp_token'];
  1490. //应用Id
  1491. $appId=$config['ccp_appid'];
  1492. //请求地址,格式如下,不需要写https://
  1493. $serverIP='app.cloopen.com';
  1494. //请求端口
  1495. $serverPort='8883';
  1496. //REST版本号
  1497. $softVersion='2013-12-26';
  1498. $tempId=$config['ccp_tempid'];
  1499. //file_put_contents(API_ROOT.'/../data/sendCode_rly_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 post_data: accountSid:'.$accountSid.";accountToken:{$accountToken};appId:{$appId};tempId:{$tempId}\r\n",FILE_APPEND);
  1500. $rest = new REST($serverIP,$serverPort,$softVersion);
  1501. $rest->setAccount($accountSid,$accountToken);
  1502. $rest->setAppId($appId);
  1503. $datas=[];
  1504. $datas[]=$code;
  1505. $result = $rest->sendTemplateSMS($mobile,$datas,$tempId);
  1506. //file_put_contents(API_ROOT.'/../data/sendCode_rly_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 result:'.json_encode($result)."\r\n",FILE_APPEND);
  1507. if($result == NULL ) {
  1508. $rs['code']=1002;
  1509. $rs['msg']="获取失败";
  1510. return $rs;
  1511. }
  1512. if($result->statusCode!=0) {
  1513. $rs['code']=1002;
  1514. $rs['msg']="获取失败";
  1515. return $rs;
  1516. }
  1517. return $rs;
  1518. }
  1519. /* 检测用户是否存在 */
  1520. function checkUser($where){
  1521. if(!$where){
  1522. return 0;
  1523. }
  1524. $isexist=Db::name('user')->field('id')->where($where)->find();
  1525. if($isexist){
  1526. return 1;
  1527. }
  1528. return 0;
  1529. }
  1530. //腾讯云IMUserSign
  1531. function txImUserSign($id){
  1532. $sig='';
  1533. $configpri=getConfigPri();
  1534. $appid=$configpri['tencentIM_appid'];
  1535. $appkey=$configpri['tencentIM_appkey'];
  1536. require_once CMF_ROOT.'sdk/tencentIM/TLSSigAPIv2.php';
  1537. $api = new \Tencent\TLSSigAPIv2($appid,$appkey);
  1538. $sign = $api->genUserSig($id);
  1539. return $sign;
  1540. }
  1541. /**
  1542. * 发送腾讯IM
  1543. * @param string $test 文本消息内容
  1544. * @param int $uid 被通知用户id
  1545. * @param string $adminName 发送消息者
  1546. */
  1547. function txMessageIM($test,$uid,$adminName='dsp_admin_2'){
  1548. $identifier='administrator'; //跟腾讯云控制台即时通讯IM默认管理员保持一致
  1549. $method_name='openim/sendmsg';
  1550. $data=array(
  1551. "SyncOtherMachine"=>2,
  1552. "From_Account"=>(string)$adminName,
  1553. "To_Account"=>(string)$uid,
  1554. "MsgRandom"=>(int)get_str(8),
  1555. "MsgBody"=>array(
  1556. 0=>array(
  1557. "MsgType"=>"TIMTextElem",
  1558. "MsgContent"=>array(
  1559. "Text"=>$test
  1560. )
  1561. ))
  1562. );
  1563. $data=json_encode($data);
  1564. $response=txImPostParam($identifier,$method_name,$data);
  1565. $result=json_decode($response,true);
  1566. //ErrorCode:10001 自定义参数,代表请求失败
  1567. if($result && $result['ActionStatus']=='OK' && $result['ErrorCode']==0){
  1568. }
  1569. }
  1570. //腾讯云IM数据请求 identifier:标识体,method_name:方法名,data:请求消息体【json字符串】
  1571. function txImPostParam($identifier,$method_name,$data){
  1572. $configpri=getConfigPri();
  1573. $appid=$configpri['tencentIM_appid'];
  1574. $user_sign=txImUserSign($identifier);
  1575. $random=get_str(8);
  1576. $area_url='';
  1577. $tencentIM_area = $configpri['tencentIM_area'];
  1578. switch($tencentIM_area){
  1579. case 'china':
  1580. $area_url='console.tim.qq.com';
  1581. break;
  1582. case 'singapore':
  1583. $area_url='adminapisgp.im.qcloud.com';
  1584. break;
  1585. case 'seoul':
  1586. $area_url='adminapikr.im.qcloud.com';
  1587. break;
  1588. case 'frankfurt':
  1589. $area_url='adminapiger.im.qcloud.com';
  1590. break;
  1591. case 'bombay':
  1592. $area_url='adminapiind.im.qcloud.com';
  1593. break;
  1594. case 'silicon-valley':
  1595. $area_url='adminapiusa.im.qcloud.com';
  1596. break;
  1597. case 'jakarta':
  1598. $area_url='adminapiidn.im.qcloud.com';
  1599. break;
  1600. default:
  1601. $area_url='console.tim.qq.com';
  1602. }
  1603. $url='https://'.$area_url.'/v4/'.$method_name;
  1604. $url.='?sdkappid='.$appid.'&identifier='.$identifier.'&usersig='.$user_sign.'&random='.$random.'&contenttype=json';
  1605. $curl = curl_init();
  1606. curl_setopt($curl, CURLOPT_URL, $url);
  1607. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  1608. curl_setopt($curl, CURLOPT_NOBODY, true);
  1609. curl_setopt($curl, CURLOPT_POST, true);
  1610. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  1611. $return_str = curl_exec($curl);
  1612. if (curl_error($curl)) {
  1613. curl_close($curl);
  1614. return json_encode(['ActionStatus'=>'FAIL','ErrorCode'=>'10001']);
  1615. }
  1616. curl_close($curl);
  1617. return $return_str;
  1618. }
  1619. //随机生成存数字字符串
  1620. function get_str($length){
  1621. $str = '0123456789';
  1622. $len = strlen($str)-1;
  1623. $randstr = '';
  1624. for ($i=0;$i<$length;$i++) {
  1625. $num=mt_rand(0,$len);
  1626. $randstr .= $str[$num];
  1627. }
  1628. return $randstr;
  1629. }
  1630. /**
  1631. * 腾讯云TPNS移动推送
  1632. * @param string $title 推送标题
  1633. * @param string $msg 推送消息内容
  1634. * @param string $type 推送类型 all 全员推送 single 单账号推送 account_list 账号列表推送
  1635. * @param integer $uid 单账号用户id
  1636. * @url https://cloud.tencent.com/document/product/548/39064
  1637. */
  1638. function txMessageTpns($title,$msg,$type,$uid=0,$account_list=[],$json_str=''){
  1639. require_once CMF_ROOT.'sdk/tencentTpns/tpns.php';
  1640. $configpri=getConfigPri();
  1641. $area=$configpri['tencentTpns_area'];
  1642. $accessid_android=$configpri['tencentTpns_accessid_android'];
  1643. $secretkey_android=$configpri['tencentTpns_secretkey_android'];
  1644. $accessid_ios=$configpri['tencentTpns_accessid_ios'];
  1645. $secretkey_ios=$configpri['tencentTpns_secretkey_ios'];
  1646. $ios_environment=$configpri['tencentTpns_ios_environment'];
  1647. if(
  1648. !in_array($area,['guangzhou','shanghai','hongkong','singapore']) ||
  1649. !$accessid_android ||
  1650. !$secretkey_android ||
  1651. !$accessid_ios ||
  1652. !$secretkey_ios
  1653. ){
  1654. return;
  1655. }
  1656. if($area=='guangzhou'){
  1657. $stub_android = new tpns\Stub($accessid_android, $secretkey_android, tpns\GUANGZHOU);
  1658. $stub_ios = new tpns\Stub($accessid_ios, $secretkey_ios, tpns\GUANGZHOU);
  1659. }else if($area=='shanghai'){
  1660. $stub_android = new tpns\Stub($accessid_android, $secretkey_android, tpns\SHANGHAI);
  1661. $stub_ios = new tpns\Stub($accessid_ios, $secretkey_ios, tpns\SHANGHAI);
  1662. }else if($area=='hongkong'){
  1663. $stub_android = new tpns\Stub($accessid_android, $secretkey_android, tpns\HONGKONG);
  1664. $stub_ios = new tpns\Stub($accessid_ios, $secretkey_ios, tpns\HONGKONG);
  1665. }else if($area=='singapore'){
  1666. $stub_android = new tpns\Stub($accessid_android, $secretkey_android, tpns\SINGAPORE);
  1667. $stub_ios = new tpns\Stub($accessid_ios, $secretkey_ios, tpns\SINGAPORE);
  1668. }else{
  1669. return;
  1670. }
  1671. if($type=='account_list' && count($account_list)==1){
  1672. $type='single';
  1673. $uid=$account_list[0];
  1674. }
  1675. if($type=='all'){
  1676. //Android推送
  1677. $android = new tpns\AndroidMessage;
  1678. if($json_str){
  1679. $android->custom_content = $json_str;
  1680. }
  1681. //控制通知点击时乱转到指定页面
  1682. $action=[
  1683. "action_type"=> 1,// 动作类型,1,打开activity或app本身;2,打开浏览器;3,打开Intent
  1684. "activity"=> "com.yunbao.im.activity.ImMsgNotifyActivity"
  1685. ];
  1686. $android->action=(object)$action;
  1687. $req_android = tpns\NewRequest(
  1688. tpns\WithAudienceType(tpns\AUDIENCE_ALL),
  1689. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1690. tpns\WithTitle($title),
  1691. tpns\WithContent($msg),
  1692. tpns\WithAndroidMessage($android),
  1693. tpns\WithEnvironment(tpns\ENVIRONMENT_PROD)
  1694. );
  1695. $result_android = $stub_android->Push($req_android);
  1696. //var_dump($result_android);
  1697. //iOS推送
  1698. $ios = new tpns\iOSMessage;
  1699. if($json_str){
  1700. $ios->custom = $json_str;
  1701. }
  1702. $req_ios = tpns\NewRequest(
  1703. tpns\WithAudienceType(tpns\AUDIENCE_ALL),
  1704. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1705. tpns\WithTitle($title),
  1706. tpns\WithContent($msg),
  1707. tpns\WithIOSMessage($ios),
  1708. tpns\WithEnvironment(tpns\ENVIRONMENT_DEV)
  1709. );
  1710. if($ios_environment==0){ //开发
  1711. $req_ios = tpns\NewRequest(
  1712. tpns\WithAudienceType(tpns\AUDIENCE_ALL),
  1713. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1714. tpns\WithTitle($title),
  1715. tpns\WithContent($msg),
  1716. tpns\WithIOSMessage($ios),
  1717. tpns\WithEnvironment(tpns\ENVIRONMENT_DEV)
  1718. );
  1719. }else{
  1720. $req_ios = tpns\NewRequest(
  1721. tpns\WithAudienceType(tpns\AUDIENCE_ALL),
  1722. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1723. tpns\WithTitle($title),
  1724. tpns\WithContent($msg),
  1725. tpns\WithIOSMessage($ios),
  1726. tpns\WithEnvironment(tpns\ENVIRONMENT_PROD)
  1727. );
  1728. }
  1729. $result_ios = $stub_ios->Push($req_ios);
  1730. //var_dump($result_ios);
  1731. }else if($type=='single'){
  1732. if(!$uid){
  1733. return;
  1734. }
  1735. $uid=(string)$uid;
  1736. //Android推送
  1737. $android = new tpns\AndroidMessage;
  1738. if($json_str){
  1739. $android->custom_content = $json_str;
  1740. }
  1741. $action=[
  1742. "action_type"=> 1,// 动作类型,1,打开activity或app本身;2,打开浏览器;3,打开Intent
  1743. "activity"=> "com.yunbao.im.activity.ImMsgNotifyActivity"
  1744. ];
  1745. $android->action=(object)$action;
  1746. $req_android = tpns\NewRequest(
  1747. tpns\WithAudienceType(tpns\AUDIENCE_ACCOUNT),
  1748. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1749. tpns\WithTitle($title),
  1750. tpns\WithContent($msg),
  1751. tpns\WithAndroidMessage($android),
  1752. tpns\WithAccountList(array($uid)),
  1753. tpns\WithEnvironment(tpns\ENVIRONMENT_PROD)
  1754. );
  1755. $result_android = $stub_android->Push($req_android);
  1756. //var_dump($result_android);
  1757. //iOS推送
  1758. $ios = new tpns\iOSMessage;
  1759. if($json_str){
  1760. $ios->custom = $json_str;
  1761. }
  1762. if($ios_environment==0){ //开发
  1763. $req_ios = tpns\NewRequest(
  1764. tpns\WithAudienceType(tpns\AUDIENCE_ACCOUNT),
  1765. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1766. tpns\WithTitle($title),
  1767. tpns\WithContent($msg),
  1768. tpns\WithIOSMessage($ios),
  1769. tpns\WithAccountList(array($uid)),
  1770. tpns\WithEnvironment(tpns\ENVIRONMENT_DEV)
  1771. );
  1772. }else{
  1773. $req_ios = tpns\NewRequest(
  1774. tpns\WithAudienceType(tpns\AUDIENCE_ACCOUNT),
  1775. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1776. tpns\WithTitle($title),
  1777. tpns\WithContent($msg),
  1778. tpns\WithIOSMessage($ios),
  1779. tpns\WithAccountList(array($uid)),
  1780. tpns\WithEnvironment(tpns\ENVIRONMENT_PROD)
  1781. );
  1782. }
  1783. $result_ios = $stub_ios->Push($req_ios);
  1784. //var_dump($result_ios);
  1785. }else if($type=='account_list'){
  1786. if(empty($account_list)){
  1787. return;
  1788. }
  1789. //Android推送
  1790. $android = new tpns\AndroidMessage;
  1791. if($json_str){
  1792. $android->custom_content = $json_str;
  1793. }
  1794. $action=[
  1795. "action_type"=> 1,// 动作类型,1,打开activity或app本身;2,打开浏览器;3,打开Intent
  1796. "activity"=> "com.yunbao.im.activity.ImMsgNotifyActivity"
  1797. ];
  1798. $android->action=(object)$action;
  1799. $req_android = tpns\NewRequest(
  1800. tpns\WithAudienceType(tpns\AUDIENCE_ACCOUNT_LIST),
  1801. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1802. tpns\WithTitle($title),
  1803. tpns\WithContent($msg),
  1804. tpns\WithAndroidMessage($android),
  1805. //tpns\WithIOSMessage($ios),
  1806. tpns\WithAccountList($account_list),
  1807. tpns\WithEnvironment(tpns\ENVIRONMENT_PROD)
  1808. );
  1809. $result_android = $stub_android->Push($req_android);
  1810. //var_dump($result_android);
  1811. //iOS推送
  1812. $ios = new tpns\iOSMessage;
  1813. if($json_str){
  1814. $ios->custom = $json_str;
  1815. }
  1816. if($ios_environment==0){ //开发
  1817. $req_ios = tpns\NewRequest(
  1818. tpns\WithAudienceType(tpns\AUDIENCE_ACCOUNT_LIST),
  1819. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1820. tpns\WithTitle($title),
  1821. tpns\WithContent($msg),
  1822. tpns\WithIOSMessage($ios),
  1823. tpns\WithAccountList($account_list),
  1824. tpns\WithEnvironment(tpns\ENVIRONMENT_DEV)
  1825. );
  1826. }else{
  1827. $req_ios = tpns\NewRequest(
  1828. tpns\WithAudienceType(tpns\AUDIENCE_ACCOUNT_LIST),
  1829. tpns\WithMessageType(tpns\MESSAGE_NOTIFY),
  1830. tpns\WithTitle($title),
  1831. tpns\WithContent($msg),
  1832. tpns\WithIOSMessage($ios),
  1833. tpns\WithAccountList($account_list),
  1834. tpns\WithEnvironment(tpns\ENVIRONMENT_PROD)
  1835. );
  1836. }
  1837. $result_ios = $stub_ios->Push($req_ios);
  1838. //var_dump($result_ios);
  1839. }
  1840. }