common.php 64 KB

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