BaseController.php
15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
<?php
namespace app\wx\controllers;
use Yii;
use yii\helpers\Url;
use yii\web\BadRequestHttpException;
use yii\db\Query;
use app\wx\models\Engineer;
use common\helpers\WxHelper;
use common\helpers\ImageManager;
use common\exts\wechat\Log as WxLog;
use common\helpers\Log as AppLog;
use common\models\SysSetting;
use domain\engineer\EngineerRole;
use domain\engineer\EngineerStatus;
use domain\engineer\EngineerSkillTagsRepository;
use domain\user\UserRepository;
use stdClass;
use function header;
use function in_array;
use function md5;
use function str_replace;
use function urlencode;
/**
* 只有通过 微信 OAuth 验证后才能访问整个App,
* 这是所有应用控制器的基类
* Class BaseController
* @package app\wx\controllers
* @author lee.li <34923862@qq.com>
* @date 2015/07/01
*/
class BaseController extends AppController
{
/**
* CSR验证,关闭后可以在不提交CSR验证码的情况下通过POST方式提交数据
* @var bool
*/
public $enableCsrfValidation = false;
/** @var **/
protected $wx;
/** @var **/
protected $site;
/**
* 初始化应用控制器,确保 mall id 的存在,有效启动程序,否则抛出异常。
* @throws yii\web\BadRequestHttpException
* @throws yii\web\BadRequestHttpException
*/
public function init()
{
$this->initTempFilePaths();
//AppLog::DEBUG("BaseController: init()" );
parent::init();
$wxArray = $this->getWxArray();
if (empty($wxArray)) {
throw new BadRequestHttpException(404);
}
//重置应用的名称
Yii::$app->name = $wxArray['name'];
/**
* 微信服务号配置
*/
$this->wx = new stdClass();
$this->site = new stdClass();
$this->formatWx($wxArray);
$this->formatSite($wxArray);
$view = Yii::$app->view;
$view->params['site']= $this->site;
}
/**
* @return array|bool
*/
private function getWxArray()
{
$wxQuery = new Query();
$wxQuery->select(['mp_setting.*']);
$wxQuery->from('mp_setting');
//调用 Active Query 得到一个数组的结果
$wxArray = $wxQuery->one();
return $wxArray;
}
/**
* @param $wxArray
*/
private function formatWx($wxArray)
{
/**
* 工程师微信服务号信息
*/
$this->wx->name = $wxArray['name'];//名称
$this->wx->intro = $wxArray['intro'];//简介
$this->wx->logo_url = $wxArray['logo_path'];//路径
$this->wx->subscribe_title = $wxArray['subscribe_title']; // 公众号关注图文标题
$this->wx->subscribe_desc = $wxArray['subscribe_desc']; // 公众号关注图文描述
$this->wx->subscribe_img = $wxArray['subscribe_img']; // 公众号关注图文消息图片
$this->wx->subscribe_url = $wxArray['subscribe_url']; // 公众号关注图文url
$this->wx->appid = $wxArray['appid'];// APPID
$this->wx->appsecret = $wxArray['appsecret'];//APPSECRET
$this->wx->token = $wxArray['token'];//微信TOKEN
}
/**
* 获取 ID
* @return int|string
*/
public function getUserId()
{
if (isset(Yii::$app->user)) {
return Yii::$app->user->id;
} else {
return 0;
}
}
/**
* @param $wxArray
*/
private function formatSite($wxArray)
{
/**
* 站点信息
*/
$appUser = Yii::$app->getUser();
$url = Yii::$app->request->getHostInfo() . Yii::$app->request->url;
$this->site->url = $url;
if (YII_ENV_DEV) {
$this->site->base_url = Yii::$app->request->getHostInfo() . Yii::$app->request->baseUrl;
} else {
$this->site->base_url = Yii::$app->request->getHostInfo();
}
$am = Yii::$app->view->getAssetManager();
$assets = $am->getBundle('app\wx\assets\AppAsset');
$this->site->is_android = (int)$this->isAndroid();
$this->site->assets_url = $assets->baseUrl;
$this->site->is_login = !$appUser->isGuest;
$this->site->title = $wxArray['name'];
$search = array("\t", "\n", "\r");
$this->site->desc = str_replace($search, '<br/>', $wxArray['intro']);
$this->site->icon = ImageManager::getUrl($wxArray['logo_path']);
$sign = WxHelper::getWxJSSDK()->getSignContext();
$this->site->appid = $sign->appId;
$this->site->timestamp = $sign->timestamp;
$this->site->noncestr = $sign->nonceStr;
$this->site->signature = $sign->signature;
}
/**
* @return yii\web\Response
*/
protected function handleMallAccessCtrl()
{
//AppLog::DEBUG("BaseController: handleMallAccessCtrl()" );
$appUser = Yii::$app->getUser();
if(YII_ENV_DEV && $appUser->isGuest){
$uid = Yii::$app->params['testUID']; // 请在各自的config/params-local.php里配置
$appUser->login(UserRepository::findOne($uid));
$this->goHome();
return ;
}
//test和 prod 环境,进行微信登陆
if ($appUser->isGuest){
$this->handleOAuthRedirect();
} else {
$path = $this->request->get('jumppath');
$model= $this->request->get('jumpmodel');
$paramOne= $this->request->get('paramOne');
if (!empty($path) && !empty($model)) {
$locationUrl = Yii::$app->params["baseUrl"]."/".$model."#".$path;
if (!empty($paramOne)) {
$locationUrl .= "/".urldecode($paramOne);
}
header("Location: $locationUrl");exit;
}
}
}
/**
* @return yii\web\Response
*/
private function handleOAuthRedirect()
{
$redirectUri = WxHelper::getDomain(true) . Url::toRoute(['/wechat/login-proccess', 'dest' => $this->site->url]);
AppLog::DEBUG("BaseController::handleOAuthRedirect() --> 开始重定向跳转 redirectUri={$redirectUri}");
$wechat = WxHelper::getWxPHPSDK();
$OAuthUrl = $wechat->getOAuthRedirect($redirectUri, 'smart', 'snsapi_base');
AppLog::DEBUG("BaseController::handleOAuthRedirect() --> 开始重定向跳转 OAuthUrl={$OAuthUrl}");
Yii::$app->response->redirect($OAuthUrl)->send();
Yii::$app->end();
}
/**
* 是否是IOS端
* 是否通过微信客户端来访问
* LOG 记录时发现,
* 在微信公众号里面第一次访问: $_SERVER ['HTTP_USER_AGENT'] 为 Mozilla/4.0
* 第二次访问: $_SERVER ['HTTP_USER_AGENT'] 为
* 苹果:
* Mozilla/5.0 (iPhone; CPU iPhone OS 9_3_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13E238 MicroMessenger/6.3.16 NetType/WIFI Language/zh_CN
* 安卓(小米NOTE):
* Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9b4) Gecko/2008030317 Firefox/3.0b4
* @return bool
*/
protected function isAndroid()
{
// if(false !== strpos($_SERVER ['HTTP_USER_AGENT'], 'Android') || !isset($_SERVER ['HTTP_USER_AGENT'])){
// return true;
// } else {
// return false;
// }
return true;
}
/** 用来验证签名
* @param $sign
* @param $revFromOpenId
* @param $location
* @param $tt
* @return bool
*/
/*
public function checkSign($sign,$revFromOpenId,$location,$tt){
$mySign = md5('openid='.$revFromOpenId.'&location_x='.$location['x'].'&time='.$tt.'&key='.$this->vKey);
if($sign==$mySign){return true;}else{return false;}
}
*/
/**
* @param $revFromOpenId
* @param $location
* @return string
*/
/*
public function genSign($revFromOpenId,$location){
$tt = time();
$mySign = md5('openid='.$revFromOpenId.'&location_x='.$location['x'].'&time='.$tt.'&key='.$this->vKey);
return $mySign;
}
*/
/**
* 重定向页面
* @param bool $return
*/
private function redirectPage($return = false , $pageUrl = "")
{
$redirect = $this->site->base_url;
$redirect = $redirect . $pageUrl;
if ($return == true) {
return array('success' => true,'redirect_url' => $redirect);
} else {
$this->redirect($redirect);
}
}
/** 判断用户是否被封号或者禁用
* @param $userStatus
* @return array
*/
public function checkEngineerBlockOrDisable($userStatus, $redirect = false)
{
if(EngineerStatus::STATUS_BLOCK == $userStatus){
//封号直接跳转
if (true == $redirect) {
$blockUrl = $this->site->base_url.'/site/block';
$this->redirect($blockUrl);
} else {
$disableUrl = $this->site->base_url.'/site/block';
return array('success' => 0 - $userStatus,'msg' => '您的账号已被封号','redirect_url' => $disableUrl);
}
} elseif (EngineerStatus::STATUS_DISABLE == $userStatus) {
//禁用表示还可以进入,但是要做其他处理
return array('success' => 0-$userStatus,'msg'=>' 您的账号已被禁用!');
} elseif (EngineerStatus::STATUS_SKILL_FAIL != $userStatus) {
//技能审核失败
} else {
}
return array('success'=>0,'msg'=>'null');
}
/* 下面这个作废 */
public function checkUserStatus($userStatus, $redirect = false)
{
if(EngineerStatus::STATUS_BLOCK == $userStatus){
//封号直接跳转
if (true == $redirect) {
$blockUrl = $this->site->base_url.'/site/block';
$this->redirect($blockUrl);
} else {
$disableUrl = $this->site->base_url.'/site/block';
return array('success' => 0 - $userStatus,'msg' => '您的账号已被封号','redirect_url' => $disableUrl);
}
} elseif (EngineerStatus::STATUS_DISABLE == $userStatus) {
//禁用表示还可以进入,但是要做其他处理
return array('success' => 0-$userStatus,'msg'=>' 您的账号已被禁用!');
} elseif (EngineerStatus::STATUS_SKILL_FAIL != $userStatus) {
//技能审核失败
} else {
}
return array('success'=>0,'msg'=>'null');
}
/*
public function authTable($userStatus)
{
$controllerID = Yii::$app->controller->id;
$actionID = Yii::$app->controller->action->id;
$moduleID=$this->module->id;
//echo 'moduleId:'.$moduleID.'_controllerID:'.$controllerID.'_actionID:'.$actionID;
if($userStatus == EngineerStatus::STATUS_NOT_AUTH){
//toDo
}
}
*/
//
public function setPhoneCode($phone, $code)
{
Yii::$app->session['v_'.$phone] = array('create_time' => time(),'vCode' => md5($phone.'_'.$code));
}
public function getPhoneCode($phone)
{
return Yii::$app->session['v_'.$phone];
}
// 默认是300秒
public function validatePhoneCode($phone, $code, $vaTime = 300)
{
$pCode = $this->getPhoneCode($phone);
$cTime = time();
if (empty($pCode)) {
return -3;
}
if ($cTime > ($pCode['create_time'] + $vaTime)) {
$this->unsetPhoneCode($phone);
return -1;
}
if($pCode['vCode'] == md5($phone.'_'.$code)){
return 0;
}else{
return -2;
}
}
public function unsetPhoneCode($phone)
{
unset(Yii::$app->session['v_'.$phone]);
}
public function checkClientStatus()
{
$stop = SysSetting::checkClientSiteStop();
if ($stop) {
$blockUrl = $this->site->base_url.'/error/stop';
//$this->redirect($blockUrl);
header('Location:'.$blockUrl);
exit;
}
return true;
}
/**
* 判断是否是BD成员
*/
public function isBdRole($engineerModel)
{
$bdRoles = EngineerRole::getBdVisitedRoles();
$engineerStatus = EngineerStatus::getBdVisitedStatus();
if (in_array($engineerModel->role, $bdRoles) && in_array($engineerModel->status, $engineerStatus)) {
return true;
} else {
return false;
}
}
public function checkIsBdRoleAndWarning()
{
$appUser = Yii::$app->getUser();
$userId = $appUser->id;
if (empty($userId)) {
$redirectUrl = $this->site->base_url.'/site/no-oauth';
$this->redirect($redirectUrl);
}
$engineerModel = Engineer::findOne($userId);
if (empty($engineerModel)) {
$redirectUrl = $this->site->base_url.'/site/no-oauth';
$this->redirect($redirectUrl);
}
//AppLog::DEBUG('== checkIsBdRoleAndWarning =='.$engineerModel->id);
if (!$this->isBdRole($engineerModel)) {
$redirectUrl = $this->site->base_url.'/site/no-oauth';
$this->redirect($redirectUrl);
}
}
/**
* 判断是否是工程师成员
*/
public function isEngineerRole($engineerModel)
{
$roles = EngineerRole::getVisitedRoles();
$engineerStatus = EngineerStatus::getVisitedStatus();
if (in_array($engineerModel->role, $roles) && in_array($engineerModel->status, $engineerStatus)) {
return true;
} else {
return false;
}
}
public function checkIsEngineerRoleAndWarning()
{
$appUser = Yii::$app->getUser();
$userId = $appUser->id;
if (empty($userId)) {
$redirectUrl = $this->site->base_url.'/site/no-oauth';
$this->redirect($redirectUrl);
}
$engineerModel = Engineer::findOne($userId);
if (empty($engineerModel)) {
$redirectUrl = $this->site->base_url.'/site/no-oauth';
$this->redirect($redirectUrl);
}
if (!$this->isEngineerRole($engineerModel)) {
$redirectUrl = $this->site->base_url.'/site/no-oauth';
$this->redirect($redirectUrl);
}
}
/** 判断用户是否被封号或者禁用
* @param $userStatus
* @return array
*/
public function checkEngineerSubscribe($subscribe)
{
if(EngineerStatus::NOSUBSCRIBE== $subscribe) {
//未关注直接跳转
$subscribeUrl = $this->site->base_url.'/site/subscribe';
$this->redirect($subscribeUrl);
}
}
/**
* 初始化web目录文件夹, 完成自动创建
*/
private function initTempFilePaths()
{
// 临时文件
$webRoot = Yii::getAlias('@webroot');
$tmpFilePath = $webRoot . '/tmp';
if (!is_dir($tmpFilePath)) {
mkdir($tmpFilePath, 0777, true);
}
}
/**检测用户去到哪个状态,根据状态跳转页面
* @param string $view
* @param bool|false $return 标明要直接跳转还是要返回数组
* @return array
*/
public function checkUserlevel($view = '', $return = false, $needPower = "default")
{
// getIdentity 可能要定时更新session 才行,不然审核通过后无法更新这个数据
$user = Yii::$app->getUser()->getIdentity();
switch ($needPower) {
case "none":
// 无需验证
if ($return == true) {
return array('success'=> false, 'redirect_url'=>'');
}
break;
default:
break;
}
}
}