CommonFn.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303
  1. <?php
  2. /**
  3. * Created on 2012-6-20
  4. * add by wangyang
  5. * 全局公共函数
  6. */
  7. use Green\Request\V20170112 as Green;
  8. class CommonFn
  9. {
  10. // 生成密码
  11. public static function generateRandomString($length = 10) {
  12. $characters = '0123456789';//ABCDEFGHIJKLMNOPQRSTUVWXYZ
  13. $randomString = '';
  14. for ($i = 0; $i < $length/2; $i++) {
  15. $randomString .= $characters[rand(0, strlen($characters) - 1)];
  16. }
  17. $characters = 'abcdefghijklmnopqrstuvwxyz';
  18. for ($i = 0; $i < $length/2; $i++) {
  19. $randomString .= $characters[rand(0, strlen($characters) - 1)];
  20. }
  21. return $randomString;
  22. }
  23. //替换爬虫中的url
  24. public static function replaceUrl($tmp_str){
  25. $_tmp_str = str_replace('pics.wozhua.mobi','wozhua-pics.qiniudn.com',$tmp_str);
  26. $_tmp_str = str_replace('wozhua-video.qiniudn.com','7rfl3z.com2.z0.glb.qiniucdn.com',$_tmp_str);
  27. $_tmp_str = str_replace('7o52dq.com2.z0.glb.clouddn.com','wozhua-avatars.qiniudn.com',$_tmp_str);
  28. $_tmp_str = str_replace('avatars.wozhua.mobi','wozhua-avatars.qiniudn.com',$_tmp_str);
  29. $_tmp_str = str_replace('7oxep6.com2.z0.glb.clouddn.com','avatars.maiyizhi.cn',$_tmp_str);
  30. $_tmp_str = str_replace('7oxer3.com2.z0.glb.qiniucdn.com','icons.maiyizhi.cn',$_tmp_str);
  31. $_tmp_str = str_replace('wozhua-pics.qiniudn.com','pics.maiyizhi.cn',$_tmp_str);
  32. $_tmp_str = str_replace('7rfl3z.com2.z0.glb.qiniucdn.com','video.maiyizhi.cn',$_tmp_str);
  33. $_tmp_str = str_replace('wozhua-avatars.qiniudn.com','others.maiyizhi.cn',$_tmp_str);
  34. $_tmp_str = str_replace('7oxep5.com2.z0.glb.clouddn.com','static.maiyizhi.cn',$_tmp_str);
  35. $_tmp_str = str_replace('files.appcute.im','cwsc-files.maiyizhi.cn',$_tmp_str);
  36. return $_tmp_str;
  37. }
  38. //替换七牛的ssl url
  39. public static function replaceSshUrl($tmp_str){
  40. $_tmp_str = str_replace('ogbtdokqr.qnssl.com','avatars.maiyizhi.cn',$tmp_str);
  41. $_tmp_str = str_replace('ogrzjw8in.qnssl.com','icons.maiyizhi.cn',$_tmp_str);
  42. $_tmp_str = str_replace('oi02dsdsh.qnssl.com','others.maiyizhi.cn',$_tmp_str);
  43. $_tmp_str = str_replace('ogrzx2jit.qnssl.com','pics.maiyizhi.cn',$_tmp_str);
  44. $_tmp_str = str_replace('ogrz13ent.qnssl.com','video.maiyizhi.cn',$_tmp_str);
  45. $_tmp_str = str_replace('ogrzaxwjy.qnssl.com','test.maiyizhi.cn',$_tmp_str);
  46. $_tmp_str = str_replace('oi0318gy3.qnssl.com','static.maiyizhi.cn',$_tmp_str);
  47. return $_tmp_str;
  48. }
  49. //生成水印签名
  50. public static function buildSign($name){
  51. return base64_encode($name.'@买一只');
  52. }
  53. //获得七牛图片的尺寸
  54. public static function getPicSize($url){
  55. $resources = self::simple_http($url."?imageInfo");
  56. return json_decode($resources, true);
  57. }
  58. /**
  59. * 获取easyui datagrid分页参数 返回 limit, offset, order 如果no_page=1 不分页
  60. */
  61. public static function getPageParams(){
  62. $page = Yii::app()->request->getParam('page');
  63. $rows = Yii::app()->request->getParam('rows');
  64. $sort = Yii::app()->request->getParam('sort');
  65. $order = Yii::app()->request->getParam('order');
  66. $no_page = 0;
  67. if ($page == null){
  68. $page = 1;
  69. $no_page = 1;
  70. }
  71. if ($rows == null){
  72. $rows = 20;
  73. }
  74. $new_sort = array();
  75. if ($sort){
  76. $sorts = explode(',', $sort);
  77. $orders = explode(',', $order);
  78. for ($i = 0;$i < count($sorts);$i ++){
  79. if ($orders[$i] == 'asc'){
  80. $temp = EMongoCriteria::SORT_ASC;
  81. } else {
  82. $temp = EMongoCriteria::SORT_DESC;
  83. }
  84. $new_sort[$sorts[$i]] = $temp;
  85. }
  86. }
  87. $offset = ($page - 1) * $rows;
  88. $result = array('offset' => $offset, 'sort' => $new_sort);
  89. if ($no_page == 0){
  90. $result['limit'] = $rows;
  91. }
  92. return $result;
  93. }
  94. //提升效率,简化数据读取操作
  95. public static function getRows($e_cursor){
  96. $rows = array();
  97. $e_cursor->next();
  98. while($row = $e_cursor->current()){
  99. $t = $row->attributes;
  100. $rows[] = $t;
  101. $e_cursor->next();
  102. }
  103. return $rows;
  104. }
  105. /**
  106. * 从cursor游标得到数组
  107. * 同时获取该记录的操作者
  108. */
  109. public static function getRowsFromCursor($e_cursor){
  110. $rows = array();
  111. $e_cursor->next();
  112. $_ids = array();
  113. $user_ids = array();
  114. while($row = $e_cursor->current()){
  115. $t = $row->attributes;
  116. $rows[] = $t;
  117. $_ids[] = $t['_id'];
  118. if (isset($t['user'])){
  119. if (!is_numeric($t['user'])){ //不是管理员用户
  120. $user_ids[] = $t['user'];
  121. }
  122. }
  123. $e_cursor->next();
  124. }
  125. $total = count($rows);
  126. if ($total > 0){
  127. $model = $e_cursor->getModel();
  128. $db_name = $model->getMongoDBComponent()->dbName;
  129. $c_name = $model->getCollectionName();
  130. $criteria = new EMongoCriteria();
  131. $criteria->db_name('==', $db_name);
  132. $criteria->c_name('==', $c_name);
  133. $criteria->r_id('in', $_ids);
  134. $criteria->limit($total);
  135. $cursor = DbAction::model()->findAll($criteria);
  136. if ($cursor->count() > 0){
  137. $action_info = array();
  138. $admin_user_ids = array();
  139. foreach ($cursor as $v){
  140. $_id = (string)$v->r_id;
  141. $action = $v->action;
  142. $last = count($action) - 1;
  143. $admin_user_ids[] = $action[$last]['user'];
  144. $action_info[$_id] = array(
  145. 'action_time' => date("Y-m-d H:i", $action[$last]['time']),
  146. 'admin_id' => $action[$last]['user'],
  147. 'action_log' => isset($action[$last]['action_log']) ? $action[$last]['action_log'] : ''
  148. );
  149. }
  150. $criteria = new EMongoCriteria();
  151. $criteria->_id('in', $admin_user_ids);
  152. $user_cursor = User::model()->findAll($criteria);
  153. $ruser_cursor = RUser::model()->findAll($criteria);
  154. $admin_names = array();
  155. foreach ($user_cursor as $v){
  156. $admin_names[$v->_id] = $v->name;
  157. }
  158. foreach ($ruser_cursor as $v) {
  159. $admin_names[(string)$v->_id] = $v->user_name;
  160. }
  161. foreach ($rows as $k => $v){
  162. $_id = (string)$v['_id'];
  163. if (isset($action_info[$_id])){
  164. $admin_id = (string)$action_info[$_id]['admin_id'];
  165. $admin_user = $admin_names[$admin_id];
  166. $rows[$k]['action_user'] = $admin_user;
  167. $rows[$k]['action_time'] = $action_info[$_id]['action_time'];
  168. $rows[$k]['action_log'] = $action_info[$_id]['action_log'];
  169. } else {
  170. $rows[$k]['action_user'] = '';
  171. $rows[$k]['action_time'] = '';
  172. $rows[$k]['action_log'] = '';
  173. }
  174. }
  175. } else {
  176. foreach ($rows as $k => $v){
  177. $rows[$k]['action_user'] = '';
  178. $rows[$k]['action_time'] = '';
  179. $rows[$k]['action_log'] = '';
  180. }
  181. }
  182. }
  183. return $rows;
  184. }
  185. /**
  186. * 组合easyui datagrid json数据
  187. * 当参数里面不包含数量时
  188. */
  189. public static function composeDatagridData($rows, $total="", $more=""){
  190. $result = array();
  191. if ($total === ""){
  192. $result = $rows;
  193. } else {
  194. $result['rows'] = $rows;
  195. $result['total'] = $total;
  196. $result['more'] = $more;
  197. if (is_array($more) && isset($more['footer'])){
  198. $result['footer'] = $more['footer'];
  199. }
  200. }
  201. $debug = Yii::app()->request->getParam('debug');
  202. if ($debug !== null){
  203. $result['exec_time'] = Yii::getLogger()->getExecutionTime();
  204. }
  205. return json_encode($result);
  206. }
  207. /**
  208. * 根据$response 返回 json
  209. */
  210. public static function requestAjax($response=true, $message="", $data=array(),$error_code=200,$special_data = array())
  211. {
  212. if($response){
  213. $res = array('success' => $response, 'message' => $message,'data' =>$data);
  214. //当错误码为203时,response为false,但依然需要返回数据
  215. }elseif($error_code==203){
  216. $res = array('success' => $response, 'message' => $message,'data' =>$data);
  217. }else{
  218. if(!empty($data)){
  219. $res = array('success' => $response, 'message' => $message,'data' =>$data);
  220. }else{
  221. $res = array('success' => $response, 'message' => $message);
  222. }
  223. }
  224. if(!empty($special_data)&&is_array($special_data)){
  225. foreach ($special_data as $key => $value) {
  226. $res[$key] = $value;
  227. }
  228. }
  229. $callback = Yii::app()->getRequest()->getParam("callback");
  230. if($error_code && is_numeric($error_code)){
  231. $res['error_code'] = $error_code;
  232. }else{
  233. $res['error_code'] = 200;
  234. }
  235. // if (YII_DEBUG){
  236. $res['exec_time'] = Yii::getLogger()->getExecutionTime();
  237. $res['memory_usage'] = number_format(Yii::getLogger()->getMemoryUsage()/1024)."KB";
  238. // }
  239. header('Content-type: application/json');
  240. if ($callback && $callback != '') {
  241. $tmp_str = $callback . '(' . json_encode($res) . ')';
  242. } else {
  243. $tmp_str = json_encode($res);
  244. }
  245. echo $tmp_str;
  246. exit();
  247. }
  248. /**
  249. * 将配置数组转为combobox数据列表
  250. * $config = array(value1 => 'text1', value2 => 'text2' ...) or array(value1 => array('name' => 'text1') ...);
  251. * $specified 指定的初始值
  252. * $all 是否添加全部选项
  253. * $all_value 全部选项的值
  254. */
  255. public static function getComboboxData($config, $specified='', $all=true, $all_value = ''){
  256. $data = array();
  257. if ($all){
  258. $temp = array('value' => $all_value, 'text' => '全部');
  259. if ($specified == $all_value){
  260. $temp['selected'] = true;
  261. }
  262. $data[] = $temp;
  263. }
  264. foreach ($config as $k => $v){
  265. if (is_array($v)){
  266. $name = $v['name'];
  267. } else {
  268. $name = $v;
  269. }
  270. $temp = array('value' => $k, 'text' => $name, 'attributes' => $v);
  271. if ($specified == $k){
  272. $temp['selected'] = true;
  273. }
  274. $data[] = $temp;
  275. }
  276. return $data;
  277. }
  278. /**
  279. * 将数据库取出的二维数组生成easyui combotree所需要的json数据
  280. * params: $datas 数据库取出二维数组, $key 每个item的唯一id, $value 每个item的描述, $level 用来区分组的数据列名
  281. * 注意: 改函数只针对特定表类型的二级目录
  282. */
  283. public static function composeCombotreeData($datas, $key, $value, $level){
  284. $type_list = array();
  285. $temp_array = array();
  286. //按组名重组数组
  287. foreach ($datas as $k => $v){
  288. $temp_array[$v[$level]][] = $v;
  289. }
  290. foreach ($temp_array as $k => $v){
  291. $temp_array1 = array(); //缓存一级目录
  292. $temp_array1['text'] = $k;
  293. $temp_array1['children'] = array();
  294. foreach ($v as $k1 => $v1){
  295. $temp_array2 = array(); //缓存二级目录
  296. $temp_array2['id'] = $v1[$key];
  297. $temp_array2['text'] = $v1[$value];
  298. array_push($temp_array1['children'], $temp_array2);
  299. }
  300. array_push($type_list, $temp_array1);
  301. }
  302. return $type_list;
  303. }
  304. public static function composeTreeData($rows, $key='_id', $value='name', $parent='parent', $level='level'){
  305. $tree_data = array();
  306. $level_array = array();
  307. //按组名重组数组
  308. $max_level = 0;
  309. foreach ($rows as $k => $v){
  310. $level_array[$v[$level]][] = $v;
  311. if ($max_level < $v[$level]){
  312. $max_level = $v[$level];
  313. }
  314. }
  315. $child_data = array();
  316. for ($i = $max_level;$i >= 1;$i --){
  317. $level_data = $level_array[$i];
  318. foreach ($level_data as $k => $v){
  319. $v[$key] = (string)$v[$key];
  320. $v[$parent] = (string)$v[$parent];
  321. $temp = array('id' => $v[$key], 'text' => (string)$v[$value], 'attributes' => $v);
  322. if (isset($child_data[$v[$key]])){
  323. $temp['children'] = $child_data[$v[$key]];
  324. } else {
  325. $temp['children'] = array();
  326. }
  327. if ($i == 1){
  328. $tree_data[] = $temp;
  329. } else {
  330. $child_data[$v[$parent]][] = $temp;
  331. }
  332. }
  333. }
  334. return $tree_data;
  335. }
  336. public static function getLevelCode($code_len, $now_code=1){
  337. $now_code = (string)$now_code;
  338. $t_len = strlen($now_code);
  339. if ($t_len < $code_len){
  340. for ($i = 0;$i < ($code_len - $t_len);$i ++){
  341. $now_code = '0' . $now_code;
  342. }
  343. }
  344. return $now_code;
  345. }
  346. /**
  347. * 返回指定场景下的选项
  348. */
  349. public static function getScenarioOption($all_option, $scenario=''){
  350. $options = array();
  351. foreach ($all_option as $k => $v){
  352. if ($scenario == '' || (isset($v[$scenario]) && $v[$scenario])){
  353. $options[$k] = $v;
  354. }
  355. }
  356. return $options;
  357. }
  358. /**
  359. * 除了超级管理员或者指定的角色只获取自己的数据
  360. * 用于需要进行过滤user_id的查询
  361. * 返回 array(
  362. * 'user_id' => $user_id,
  363. * 'filter' => 1 需要过滤 0 不需要过滤
  364. * );
  365. */
  366. public static function filterByUserId($role='')
  367. {
  368. $user_id = Yii::app()->user->id;
  369. $filter = 1;
  370. $result = array();
  371. $result['user_id'] = $user_id;
  372. $result['filter'] = 0;
  373. if ($user_id == ''){ //未登录
  374. return $result;
  375. }
  376. if (Yii::app()->user->checkAccess(Helper::findModule('srbac')->superUser)){ //超级管理员
  377. $filter = 0;
  378. }
  379. if ($role != '' && Yii::app()->user->checkAccess($role)){ //指定的角色
  380. $filter = 0;
  381. }
  382. $result['filter'] = $filter;
  383. return $result;
  384. }
  385. /**
  386. * 将unicode转化为utf-8编码
  387. */
  388. public static function unescape($str)
  389. {
  390. $str = rawurldecode($str);
  391. preg_match_all("/(?:%u.{4})|&#x.{4};|&#\d+;|.+/U",$str,$r);
  392. $ar = $r[0];
  393. //print_r($ar);
  394. foreach($ar as $k=>$v) {
  395. if(substr($v,0,2) == "%u")
  396. $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,-4)));
  397. elseif(substr($v,0,3) == "&#x")
  398. $ar[$k] = iconv("UCS-2","UTF-8",pack("H4",substr($v,3,-1)));
  399. elseif(substr($v,0,2) == "&#") {
  400. //echo substr($v,2,-1)."\n";
  401. $ar[$k] = iconv("UCS-2","UTF-8",pack("n",substr($v,2,-1)));
  402. }
  403. }
  404. return join("",$ar);
  405. }
  406. public static function get_val_if_isset($var, $key, $defaul_val=''){
  407. return (isset($var) && isset($var[$key]) && $var[$key]!==null)? $var[$key] : $defaul_val;
  408. }
  409. public static function parse_break($str){
  410. return str_replace("\r\n", "\n", $str);
  411. }
  412. public static function parse_break_web($str){
  413. return preg_replace("/\r\n|\n/","<br />",$str);
  414. }
  415. public static $empty = array();
  416. /**
  417. * 简单获取远程文件数据
  418. *
  419. * curl方式获取远程文件信息
  420. * @param string $url 要获取的网址
  421. * @return string 获取的链接内容
  422. */
  423. public static function simple_http($url) {
  424. $ch = curl_init();
  425. curl_setopt($ch, CURLOPT_URL, $url);
  426. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  427. $res = curl_exec($ch);
  428. curl_close($ch);
  429. return $res;
  430. }
  431. /*去除url requset部分*/
  432. public static function clearUrl($url){
  433. $rstr='';
  434. $tmparr=parse_url($url);
  435. $rstr=empty($tmparr['scheme'])?'http://':$tmparr['scheme'].'://';
  436. $rstr.=$tmparr['host'].$tmparr['path'];
  437. return $rstr;
  438. }
  439. /**
  440. * 将数组总的MongoId转为字符串
  441. */
  442. public static function formatDataForJS($row){
  443. foreach ($row as $k => $v){
  444. if (is_a($v, 'MongoId')){
  445. $row[$k] = (string)$v;
  446. }
  447. if ($v === null){
  448. $row[$k] = '';
  449. }
  450. }
  451. return $row;
  452. }
  453. public static function microtime_float(){
  454. list($s1, $s2) = explode(' ', microtime());
  455. return (float)sprintf('%.0f', (floatval($s1) + floatval($s2)) * 1000);
  456. }
  457. /**
  458. * 是否是mongoid
  459. * 当前驱动不支持判断mongoid,先自定义
  460. */
  461. public static function isMongoId($char){
  462. if (method_exists(new MongoId(), 'isValid')){
  463. return MongoId::isValid($char);
  464. } else {
  465. return !preg_match('/[\x80-\xff]./', $char) && strlen($char) == 24;
  466. }
  467. }
  468. //检查图标和图片的格式
  469. public static function checkPicFormat($pic){
  470. $pattern = "/^http:\/\/.*?\/.*?\.(jpg|png|gif|jpeg)/i";
  471. if (!preg_match( $pattern, strtolower($pic))){
  472. return false;
  473. }else{
  474. return true;
  475. }
  476. }
  477. //检查音频的格式
  478. public static function checkVoiceFormat($voice){
  479. $pattern = "/^http:\/\/.*?(.qiniudn.com)\/.*?/i";
  480. if (!preg_match( $pattern, strtolower($voice))){
  481. return false;
  482. }else{
  483. return true;
  484. }
  485. }
  486. //检查视频的格式
  487. public static function checkVideoFormat($video){
  488. $pattern = "/^http:\/\/.*?(.qiniudn.com)\/.*?/i";
  489. if (!preg_match( $pattern, strtolower($video))){
  490. return false;
  491. }else{
  492. return true;
  493. }
  494. }
  495. //时间格式化
  496. public static function sgmdate($dateformat, $timestamp='', $format=0) {
  497. if(empty($timestamp)) {
  498. $timestamp = time();
  499. }
  500. $timeoffset = 8;
  501. $result = '';
  502. if($format) {
  503. $time = time() - $timestamp;
  504. if($time > 12*30*24*3600) {
  505. $result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
  506. //$result = intval($time/31104000).'年前';
  507. }elseif($time > 30*24*3600) {
  508. $result = intval($time/2592000).'个月前';
  509. }elseif($time > 24*3600) {
  510. $result = intval($time/86400).'天前';
  511. } elseif ($time > 3600) {
  512. $result = intval($time/3600).'小时前';
  513. } elseif ($time > 60) {
  514. $result = intval($time/60).'分钟前';
  515. } elseif ($time > 0) {
  516. $result = $time.'秒前';
  517. } else {
  518. $result = '刚刚';
  519. }
  520. } else {
  521. $result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
  522. }
  523. return $result;
  524. }
  525. //时间格式化 格式化未来的时间 如1天之后
  526. public static function bgmdate($dateformat, $timestamp='', $format=0){
  527. if(empty($timestamp)) {
  528. $timestamp = time();
  529. }
  530. $timeoffset = 8;
  531. $result = '';
  532. if($format) {
  533. $time = $timestamp-time();
  534. if($time > 24*3600) {
  535. $result = intval($time/86400).'天后';
  536. } elseif ($time > 3600) {
  537. $result = intval($time/3600).'小时后';
  538. } elseif ($time > 60) {
  539. $result = intval($time/60).'分钟后';
  540. } elseif ($time > 0) {
  541. $result = $time.'秒后';
  542. }elseif ($time < 0) {
  543. $result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
  544. } else {
  545. $result = '马上';
  546. }
  547. } else {
  548. $result = gmdate($dateformat, $timestamp + $timeoffset * 3600);
  549. }
  550. return $result;
  551. }
  552. public static function formatTimestamp($timestamp,$format="Y-n-d"){
  553. $timeoffset = 8; //时区
  554. return gmdate($format, $timestamp + $timeoffset * 3600);
  555. }
  556. /**
  557. *returnInfo 格式化返回信息
  558. *@author >
  559. *@param bool $status 执行状态
  560. *@param string $info 提示信息
  561. *@param array $data 需要时返回数据
  562. */
  563. public static function returnInfo($status = true,$info = '',$data = array(),$special_data = array()){
  564. return array('status'=>$status,'info'=>$info,'data'=>$data,'special_data' => $special_data);
  565. }
  566. /**
  567. * getFirstTime 获得客户端首次请求时间戳
  568. * @param string $device_id 机器码
  569. *@param int $page 分页页码
  570. *@param string $order 排序方式
  571. */
  572. public static function getFirstTime($actiontype,$device_id,$page,$order='time'){
  573. $cache = new ARedisCache();
  574. $key = $actiontype.$device_id.$order;
  575. if($page==1){
  576. $cache->set($key,time());
  577. $res = $cache->get($key);
  578. }else{
  579. $res = $cache->get($key);
  580. if(empty($res)){
  581. $cache->set($key,time());
  582. $res = $cache->get($key);
  583. }
  584. }
  585. return intval($res);
  586. }
  587. /**
  588. * getPagedata 获取分页数据
  589. * @author >
  590. * @param string $model 要获取数据的model
  591. * @param string $page 具体第几页
  592. * @param int $pagesize 分页大小
  593. * @param string $conditions 查询条件
  594. * 使用示例:$conditions = array(
  595. * 'group'=>array('==',$group_id),
  596. * 'status'=>array('==',1),
  597. * 'time'=>array('<=',$actiontime)
  598. * );
  599. *@param string $order 排序方式
  600. * 使用示例: $order = array(
  601. * 'time'=>'desc',
  602. * );
  603. *@return array
  604. */
  605. public static function getPagedata($model,$page,$pagesize,$conditions = array(),$order = array(),$need_parse = true,$sum_page = true,$parse_data = array()){
  606. $customer_pagesize = intval(Yii::app()->getRequest()->getParam("page_size",0));
  607. if($customer_pagesize>0){
  608. $pagesize = $customer_pagesize;
  609. }
  610. $criteria = new EMongoCriteria();
  611. foreach ($conditions as $key => $value) {
  612. $criteria->$key($value[0],$value[1]);
  613. }
  614. if($sum_page&&$pagesize){
  615. $sum_count = $model->count($criteria);
  616. $sum_page = ceil($sum_count/$pagesize);
  617. }else{
  618. $sum_count = 9999;
  619. $sum_page = 99;
  620. }
  621. if($page<1){
  622. $res = array();
  623. $result['sum_count'] = $sum_count;
  624. $result['sum_page'] = $sum_page;
  625. $result['current_page'] = $page;
  626. $result['page_size'] = $pagesize;
  627. $result['res'] = $res;
  628. return $result;
  629. }
  630. if($order){
  631. foreach ($order as $key => $value) {
  632. $orderparam = 'EMongoCriteria::SORT_'.strtoupper($value);
  633. $criteria->sort($key,constant($orderparam));
  634. }
  635. }
  636. $criteria->limit($pagesize);
  637. $offset = $page*$pagesize-$pagesize;
  638. $criteria->offset($offset);
  639. $cursor = $model->findAll($criteria);
  640. $rows = self::getRows($cursor);
  641. if($need_parse){
  642. if($parse_data){
  643. $res = $model->parse($rows,true,$parse_data);
  644. }else{
  645. $res = $model->parse($rows);
  646. }
  647. }else{
  648. $res = $rows;
  649. }
  650. $result['sum_count'] = $sum_count;
  651. $result['sum_page'] = $sum_page>1?$sum_page:1;
  652. $result['current_page'] = $page;
  653. $result['page_size'] = $pagesize;
  654. $result['res'] = $res;
  655. return $result;
  656. }
  657. /**
  658. * getPagedatabyID 获取分页数据
  659. * @author >
  660. * @param string $model 要获取数据的model
  661. * @param int $pagesize 分页大小
  662. * @param string $conditions 查询条件
  663. * 使用示例:$conditions = array(
  664. * 'group'=>array('==',$group_id),
  665. * 'status'=>array('==',1),
  666. * 'time'=>array('<=',$actiontime)
  667. * );
  668. *@param string $order 排序方式
  669. * 使用示例: $order = array(
  670. * 'time'=>'desc',
  671. * );
  672. *@return array
  673. */
  674. public static function getPagedataById($model,$pagesize,$conditions = array(),$order = array(),$need_parse = true,$sum_page = true,$parse_data = array()){
  675. $customer_pagesize = intval(Yii::app()->getRequest()->getParam("page_size",0));
  676. if($customer_pagesize>0){
  677. $pagesize = $customer_pagesize;
  678. }
  679. $criteria = new EMongoCriteria();
  680. foreach ($conditions as $key => $value) {
  681. $criteria->$key($value[0],$value[1]);
  682. }
  683. if($sum_page){
  684. $sum_count = $model->count($criteria);
  685. }else{
  686. $sum_count = 9999;
  687. }
  688. if($order){
  689. foreach ($order as $key => $value) {
  690. $orderparam = 'EMongoCriteria::SORT_'.strtoupper($value);
  691. $criteria->sort($key,constant($orderparam));
  692. }
  693. }
  694. $rows = array();
  695. if($sum_count){
  696. $criteria->limit($pagesize);
  697. $cursor = $model->findAll($criteria);
  698. $rows = self::getRows($cursor);
  699. }
  700. if($need_parse){
  701. if($parse_data){
  702. $res = $model->parse($rows,true,$parse_data);
  703. }else{
  704. $res = $model->parse($rows);
  705. }
  706. }else{
  707. $res = $rows;
  708. }
  709. $result['has_more'] = $sum_count>$pagesize?1:0;
  710. $result['page_size'] = $pagesize;
  711. $result['res'] = $res;
  712. return $result;
  713. }
  714. /**
  715. * formatSolrResult 将solr搜索结果格式化为标准分页格式
  716. * @author >
  717. * @param array $model 要获取数据的model
  718. * @return array
  719. */
  720. public static function formatSearchResult($search_res,$pagesize,$page){
  721. $result['sum_count'] = $search_res['result']['total'];
  722. $result['sum_page'] = ceil($search_res['result']['total']/$pagesize);
  723. $result['current_page'] = intval($page);
  724. $result['page_size'] = $pagesize;
  725. $result['res'] = $search_res['result']['items'];
  726. return $result;
  727. }
  728. /**
  729. * 判断对象在model内是否已存在,存在时返回此对象,为api模块控制器封装,不建议在ApiBaseControllers外的地方使用
  730. * @author >
  731. *@param string $id 要查询对象id
  732. *@param string $Zmodel 要查询的model的Z组件如:ZTopic
  733. *@param string $errorinfo 当对象不存在时向客户端返回的错误信息
  734. *@return object 如存在则返回此对象对象
  735. */
  736. public static function apigetObJ($id,$model,$errorinfo = '此id不存在',$errorcode = ''){
  737. if(CommonFn::isMongoId($id)){
  738. $_id = new MongoId($id);
  739. $obj = new $model();
  740. $_obj = $obj->get($_id);
  741. if($_obj&&isset($_obj->attributes)&&!empty($_obj->attributes)){
  742. return $_obj;
  743. }else{
  744. if ($errorcode) {
  745. CommonFn::requestAjax(false,$errorinfo,array(),$errorcode);
  746. }else{
  747. CommonFn::requestAjax(false,$errorinfo);
  748. }
  749. }
  750. }else{
  751. if ($errorcode) {
  752. CommonFn::requestAjax(false,$errorinfo,array(),$errorcode);
  753. }else{
  754. CommonFn::requestAjax(false,$errorinfo);
  755. }
  756. }
  757. }
  758. /**
  759. * 获取对象
  760. *@param string $id 要查询的id
  761. *@param string $Zmodel 要查询的model的Z组件如:ZTopic
  762. *@return object model存在的这个对象
  763. */
  764. public static function getObj($id,$Zmodel){
  765. if(CommonFn::isMongoId($id)){
  766. $_id = new MongoId($id);
  767. $obj = new $Zmodel();
  768. $_obj = $obj->get($_id);
  769. if($_obj&&isset($_obj->attributes)&&!empty($_obj->attributes)){
  770. return $_obj;
  771. }else{
  772. return false;
  773. }
  774. }else{
  775. return false;
  776. }
  777. }
  778. /**
  779. * 返回系统消息提示信息
  780. * 按照不同的模块分别读取预定义数据
  781. * @param string $type
  782. * @param $key
  783. * @author guoqiang.zhang
  784. * @date 2014-10-27
  785. */
  786. public static function getMessage($type = 'user',$key){
  787. /**
  788. * 消息类型分为coreMessage和message
  789. * type='zii' 和 'yii' 为coreMessage ,对应的message文件为protected/messages/{LOCALID}/yii.php
  790. * type 对应其他值时。对应message文件为protected/messages/{LOCALID}/$type.php
  791. * @link http://www.yiiframework.com/doc/guide/1.1/zh_cn/topics.i18n
  792. */
  793. return Yii::t($type,$key);
  794. }
  795. /**
  796. * 通过curl方式获取制定的图片到本地
  797. * @param string $url 完整的图片地址
  798. * @param string $filename 要存储的文件名
  799. */
  800. public static function getImageByUrl($url,$filename){
  801. if(is_dir(basename($filename))) {
  802. return false;
  803. }
  804. //去除URL连接上面可能的引号
  805. $url = preg_replace( '/(?:^[\'"]+|[\'"\/]+$)/','',$url);
  806. $hander = curl_init();
  807. $fp = fopen($filename,'wb');
  808. curl_setopt($hander,CURLOPT_URL,$url);
  809. curl_setopt($hander,CURLOPT_FILE,$fp);
  810. curl_setopt($hander,CURLOPT_HEADER,0);
  811. curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
  812. //curl_setopt($hander,CURLOPT_RETURNTRANSFER,false);//以数据流的方式返回数据,当为false是直接显示出来
  813. curl_setopt($hander,CURLOPT_TIMEOUT,60);
  814. curl_exec($hander);
  815. curl_close($hander);
  816. fclose($fp);
  817. return true;
  818. }
  819. /**
  820. * 上传文件到七牛
  821. * @param string $file 源文件
  822. * @param string $upname 上传后的文件名
  823. * @param string $bucket 七牛上传的位置
  824. */
  825. public static function upFiletoQiniu($file,$upname,$bucket){
  826. $path = Yii::getPathOfAlias('application');
  827. require_once($path."/vendors/qiniu/rs.php");
  828. require_once($path."/vendors/qiniu/io.php");
  829. $qiniu_config = Yii::app()->params['qiniuConfig'];
  830. $accessKey = $qiniu_config['ak'];
  831. $secretKey = $qiniu_config['sk'];
  832. Qiniu_SetKeys($accessKey, $secretKey);
  833. $putPolicy = new Qiniu_RS_PutPolicy($bucket);
  834. $upToken = $putPolicy->Token(null);
  835. $putExtra = new Qiniu_PutExtra();
  836. $putExtra->Crc32 = 1;
  837. list($ret,$err) = Qiniu_PutFile($upToken,$upname,$file,$putExtra);
  838. if ($err !== null) {
  839. return false;
  840. } else {
  841. return true;
  842. }
  843. }
  844. //根据总记录数和每页显示数来生成最大页,并检查请求的页码是否合法
  845. public static function getMaxPage($total,$items_per_page){
  846. $max_pages = ceil($total / $items_per_page );
  847. if($max_pages==0){
  848. $max_pages=1;
  849. }
  850. return $max_pages;
  851. }
  852. /**
  853. * 根据系统环境配置变量来获取对应的后台发送私信的客服id
  854. * 环境变量设定参照/index.php
  855. * @return bool
  856. */
  857. public static function getMsgAdminID(){
  858. return Yii::app()->params['kefu_user'];
  859. }
  860. //float型的数字比较 比如版本的比较
  861. public static function isBigger($now, $latest)
  862. {
  863. //纯数字比较
  864. if (is_numeric($now) && is_numeric($latest)) {
  865. if ($latest > $now) {
  866. return true;
  867. } else {
  868. return false;
  869. }
  870. }
  871. //x.x.x.x比较
  872. if (stripos($latest, '.') !== false) {
  873. $f = explode('.', $now);
  874. $s = explode('.', $latest);
  875. $count = count($f);
  876. foreach ($f as $k => $v) {
  877. //比如1.0比2.0
  878. if ($s[$k] > $v) {
  879. return true;
  880. }
  881. //前面几位相等没关系,最后一位必须大于
  882. //比如1.0.5比1.0.8
  883. if (($count == $k + 1) && ($s[$k] > $v)) {
  884. return true;
  885. }
  886. }
  887. }
  888. return false;
  889. }
  890. //新增
  891. public static function inc($db, $collection, $_id, $field, $key=null, $inc=1){
  892. $mongo = new MongoClient(DB_CONNETC);
  893. if($key){
  894. $field2=$field.'.'.$key;
  895. }else{
  896. $field2=$field;
  897. }
  898. $res=$mongo->$db->command(array("findandmodify" => $collection, "query" => array('_id'=>$_id), 'update'=>array('$inc'=>array($field2=>$inc)), 'fields'=>array('_id'=>1, $field2=>1), 'upsert'=>true));
  899. if(!$res || !isset($res['value']) || !isset($res['value'][$field]) || ($key && !isset($res['value'][$field][$key]) )){
  900. return 1;
  901. }
  902. if($key) return $res['value'][$field][$key]+1;
  903. return $res['value'][$field]+1;
  904. }
  905. //获得用户自上次访问后的天数
  906. public static function get_user_last_visit_days($last_vt){
  907. $all_days=array(1, 3, 7, 30);
  908. $days=ceil((strtotime(intval(date("Ymd"))+1)-$last_vt)/86400);
  909. foreach($all_days as $day){
  910. if($days<=$day){
  911. return $day;
  912. }
  913. }
  914. return 30;
  915. }
  916. //获得用户自上次访问后的小时数
  917. public static function get_user_last_visit_hours($last_vt){
  918. $hours=floor((time()-$last_vt)/3600);
  919. if($hours<12){
  920. return 3;
  921. }elseif ($hours<24) {
  922. return 24;
  923. }elseif ($hours < 72) {
  924. return 72;
  925. }elseif ($hours < 168) {
  926. return 168;
  927. }else{
  928. return 720;
  929. }
  930. }
  931. //去掉描述末尾的符号,加上省略号
  932. public static function add_more_to_str($str){
  933. return preg_replace("/(。|?|!|~|,|,|…|\!|\.|\?|;|;|~|~|、){1,6}$/", "", $str)."...";
  934. }
  935. //判断是否是微信浏览器
  936. public static function is_weixin(){
  937. if(!isset($_SERVER['HTTP_USER_AGENT'])){
  938. return false;
  939. }
  940. if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger')!==false){
  941. return true;
  942. }
  943. return false;
  944. }
  945. //URL安全的Base64编码
  946. public static function urlsafe_base64_encode($str){
  947. $find = array('+', '/');
  948. $replace = array('-', '_');
  949. $encodedSign = str_replace($find, $replace, base64_encode($str));
  950. return $encodedSign;
  951. }
  952. public static function array_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
  953. if(is_array($arrays)){
  954. foreach ($arrays as $array){
  955. if(is_array($array)){
  956. $key_arrays[] = $array[$sort_key];
  957. }else{
  958. return false;
  959. }
  960. }
  961. }else{
  962. return false;
  963. }
  964. array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
  965. return $arrays;
  966. }
  967. public static function generate_token($access_key, $secret_key, $data){
  968. $digest = hash_hmac("sha1", $data, $secret_key, true);
  969. // var_dump(bin2hex($digest));die();
  970. // var_dump($this->urlsafe_base64_encode($digest));die();
  971. // var_dump($access_key.':'.$this->urlsafe_base64_encode($digest));die();
  972. return $access_key.':'.self::urlsafe_base64_encode($digest);
  973. }
  974. public static function dstrpos($string, $arr, $returnvalue = false) {
  975. if(empty($string)) return false;
  976. foreach((array)$arr as $v) {
  977. if(strpos($string, $v) !== false) {
  978. $return = $returnvalue ? $v : true;
  979. return $return;
  980. }
  981. }
  982. return false;
  983. }
  984. public static function getQiniuImage($url,$width,$height){
  985. return "$url?imageView2/1/w/{$width}/h/{$height}";
  986. }
  987. //火星系坐标转化成百度坐标
  988. public static function GCJTobaidu($lat, $lng){
  989. $v = M_PI * 3000.0 / 180.0;
  990. $x = $lng;
  991. $y = $lat;
  992. $z = sqrt($x * $x + $y * $y) + 0.00002 * sin($y * $v);
  993. $t = atan2($y, $x) + 0.000003 * cos($x * $v);
  994. return array(
  995. 'lat' => $z * sin($t) + 0.006,
  996. 'lng' => $z * cos($t) + 0.0065
  997. );
  998. }
  999. //百度坐标转换成火星系坐标
  1000. public static function baiduToGCJ($lat, $lng){
  1001. $v = M_PI * 3000.0 / 180.0;
  1002. $x = $lng - 0.0065;
  1003. $y = $lat - 0.006;
  1004. $z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $v);
  1005. $t = atan2($y, $x) - 0.000003 * cos($x * $v);
  1006. return array(
  1007. 'lat' => $z * sin($t),
  1008. 'lng' => $z * cos($t)
  1009. );
  1010. }
  1011. //格式化距离 1公里以内 都显示多少米 一公里以上 都显示整数公里
  1012. public static function parseDistance($dis){
  1013. if($dis<1){
  1014. $distance = $dis*10;
  1015. if($distance<1){
  1016. return '附近';
  1017. }else{
  1018. return (string)(floor($distance)*100).'米';
  1019. }
  1020. }else{
  1021. return floor($dis).'公里';
  1022. }
  1023. }
  1024. public static function setInteraction($from_user,$to_user,$type){
  1025. if(!CommonFn::isMongoId($from_user) || !CommonFn::isMongoId($to_user) || !in_array($type,array('at','message','like'))){
  1026. return false;
  1027. }
  1028. $model = new UserInteraction();
  1029. $model->from_user = $from_user;
  1030. $model->to_user = $to_user;
  1031. $model->type = $type;
  1032. $model->time = time();
  1033. if($model->save()){
  1034. return true;
  1035. }else{
  1036. return false;
  1037. }
  1038. }
  1039. public static function sendOrderSms($order,$id){
  1040. $key = $id.'_send_sms';
  1041. $cache = new ARedisCache();
  1042. $have_send = $cache->get($key);
  1043. if(!$have_send){
  1044. $order_info = $order->parseRow($order);
  1045. $month = date('m');
  1046. $day = date('d');
  1047. $address = $order_info['address']['poi']['name'].$order_info['address']['detail'];
  1048. if(date('w') == 0 || date('w') == 6){
  1049. $info = '我们将在工作时间为您安排';
  1050. }else{
  1051. $info = '我们正在为您安排';
  1052. }
  1053. $master = '保洁师';//
  1054. CommonSMS::send('order_pay_success',array('month'=>$month,'day'=>$day,'address'=>$address,'info'=>$info,'master'=>$master,'mobile'=>$order_info['address']['mobile']));
  1055. $cache->set($key,1,86400);
  1056. }
  1057. }
  1058. public static function httpPost($url,$param,$post_file=false){
  1059. $oCurl = curl_init();
  1060. if(stripos($url,"https://")!==FALSE){
  1061. curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
  1062. curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
  1063. curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
  1064. }
  1065. if (is_string($param)) {
  1066. $strPOST = $param;
  1067. } else {
  1068. $aPOST = array();
  1069. foreach($param as $key=>$val){
  1070. //$aPOST[] = $key."=".urlencode($val);
  1071. }
  1072. $strPOST = join("&", $aPOST);
  1073. }
  1074. $this_header = array(
  1075. "content-type: application/x-www-form-urlencoded;
  1076. charset=UTF-8"
  1077. );
  1078. curl_setopt($oCurl,CURLOPT_HTTPHEADER,$this_header);
  1079. curl_setopt($oCurl, CURLOPT_URL, $url);
  1080. curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1 );
  1081. curl_setopt($oCurl, CURLOPT_POST,true);
  1082. curl_setopt($oCurl, CURLOPT_POSTFIELDS,$strPOST);
  1083. $sContent = curl_exec($oCurl);
  1084. $aStatus = curl_getinfo($oCurl);
  1085. curl_close($oCurl);
  1086. if(intval($aStatus["http_code"])==200){
  1087. return $sContent;
  1088. }else{
  1089. return false;
  1090. }
  1091. }
  1092. public static function sendWxMessage($data){
  1093. // 环境检查
  1094. $res = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx9a632fd8918d1a48&secret=1d21b873c19a36b200cf1d0bb1e9aa26');
  1095. $access_token = json_decode($res,true)['access_token'];
  1096. $result = self::httpPost('https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$access_token,$data);
  1097. if ($result)
  1098. {
  1099. $json = json_decode($result,true);
  1100. if (!$json || !empty($json['errcode']) || $json['errcode']!=0) {
  1101. return false;
  1102. }
  1103. return $json;
  1104. }
  1105. return false;
  1106. }
  1107. public static function browser_export($type, $filename){
  1108. if($type == "Excel5"){
  1109. header('Content-Type: application/vnd.ms-excel'); //excel2003
  1110. }else{
  1111. header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); //excel2007
  1112. }
  1113. header('Content-Disposition: attachment;filename="'.$filename.'"');
  1114. header('Cache-Control: max-age=0');
  1115. }
  1116. //解决Excel2007不能导出
  1117. public static function SaveViaTempFile($objWriter){
  1118. $filePath = dirname(__FILE__) . rand(0, getrandmax()) . rand(0, getrandmax()) . ".tmp";
  1119. $objWriter->save($filePath);
  1120. readfile($filePath);
  1121. unlink($filePath);
  1122. }
  1123. public static function getExcelCeilIndex($row, $col) {
  1124. if($row > 0 && $col > 0 )
  1125. {
  1126. $str ="ZABCDEFGHIGKLMNOPQRSTUVWXY";
  1127. $col_str ="";
  1128. do
  1129. {
  1130. $col_tmp = $col % 26;
  1131. $col = $col_tmp == 0 ? intval($col / 26) - 1 : intval($col / 26);
  1132. $col_str = $str[$col_tmp].$col_str;
  1133. }while( $col );
  1134. return $col_str.'$'.$row;
  1135. }
  1136. return false;
  1137. }
  1138. /**
  1139. * 图片鉴黄
  1140. * 同步图片检测样例,调用会实时返回检测结果
  1141. * http://oscmpgu1a.bkt.clouddn.com/o_1bjrul60t1o4g1n6egb4sse1icl9.jpg
  1142. */
  1143. public static function isSex ($url){
  1144. //return false;
  1145. /*if(strpos($url,'?')===false){
  1146. $_info = self::simple_http($url."?qpulp");
  1147. }else{
  1148. $_info = self::simple_http($url."|qpulp");
  1149. }
  1150. $info_array = json_decode($_info, true);
  1151. if(isset($info_array['result'])&&$info_array['result']){
  1152. $rate = floatval(self::get_val_if_isset($info_array['result'],'score',0));
  1153. $label = intval(self::get_val_if_isset($info_array['result'],'label',2));
  1154. if($label==0&&$rate>0.6){
  1155. return true;
  1156. }else{
  1157. return false;
  1158. }
  1159. }else{
  1160. return false;
  1161. }*/
  1162. Yii::$enableIncludePath = false;
  1163. Yii::import('ext.aliyuncs.aliyun-php-sdk-core.Config',1);
  1164. date_default_timezone_set("PRC");
  1165. //请替换成你自己的accessKeyId、accessKeySecret
  1166. $ak['accessKeyId']='LTAIsUUDuVvAmDMP';
  1167. $ak['accessKeySecret']='d8gz2BkKVWGQg77sjShH7TAhei6qIP';
  1168. DefaultProfile::addEndpoint("cn-hangzhou", "cn-hangzhou", "Green", "green.cn-hangzhou.aliyuncs.com");
  1169. $iClientProfile = DefaultProfile::getProfile("cn-hangzhou", $ak["accessKeyId"], $ak["accessKeySecret"]);
  1170. $request = new Green\ImageSyncScanRequest();
  1171. $task1 = array('dataId' => uniqid(),
  1172. 'url' => $url,
  1173. 'time' => round(microtime(true)*1000)
  1174. );
  1175. $client = new DefaultAcsClient($iClientProfile);
  1176. $request->setMethod("POST");
  1177. $request->setAcceptFormat("JSON");
  1178. $request->setContent(json_encode(array("tasks" => $task1,"scenes" => array("porn"))));
  1179. $response = $client->getAcsResponse($request);
  1180. var_dump($response);exit;
  1181. if(isset($response->data[0]->results[0]->suggestion) && $response->data[0]->results[0]->suggestion != 'pass'){
  1182. if (intval($response->data[0]->results[0]->rate) >= 60) {//分数越大 越趋于该分类
  1183. return true;
  1184. }
  1185. }
  1186. return false;
  1187. }
  1188. }