CommonFn.php 41 KB

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