BaseController.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: Leo
  5. * Date: 2017/9/3
  6. * Time: 下午3:05
  7. */
  8. namespace backendApi\modules\v1\controllers;
  9. use common\helpers\Date;
  10. use common\helpers\Tool;
  11. use common\libs\IpFilter;
  12. use common\models\UserInfo;
  13. use common\models\UserSystem;
  14. use \Yii;
  15. use common\components\ActiveRecord;
  16. use common\helpers\Form;
  17. use yii\db\Exception;
  18. use yii\web\HttpException;
  19. class BaseController extends \yii\rest\ActiveController {
  20. /**
  21. * 不让控制器直接选择model类直接返回数据
  22. * @return array
  23. */
  24. public function actions() {
  25. return [];
  26. }
  27. /**
  28. * 校验管理员权限
  29. * @param $action
  30. * @return bool|mixed
  31. * @throws HttpException
  32. * @throws \yii\web\BadRequestHttpException
  33. */
  34. public function beforeAction($action) {
  35. $parentBeforeAction = parent::beforeAction($action);
  36. $notFilterApi = [
  37. '/v1/oauth/login',
  38. '/v1/site/page-data',
  39. '/v1/oauth/send-email-code',
  40. '/v1/site/days-diff',
  41. '/v1/site/captcha',
  42. '/favicon.ico',
  43. ];
  44. $request = Yii::$app->request;
  45. if (\Yii::$app->redis->get('backend_ip_filter') && !Tool::checkArrayElementSubstringOfString($request->getUrl(), $notFilterApi)) {
  46. if (!(new IpFilter())->checkIp('backend')) {
  47. throw new \Exception('用户名或密码错误');
  48. }
  49. }
  50. // 增加的判断用户登录后未操作后的超时
  51. if (Yii::$app->getUser()->getUserInfo()){
  52. $adminId = Yii::$app->getUser()->getUserInfo()['id'];
  53. $redisKey = 'admin:timeOut';
  54. $lastTime = '';
  55. if (!Yii::$app->tokenRedis->hget($redisKey, $adminId)) {
  56. $lastTime = time();
  57. }else{
  58. $lastTime = Yii::$app->tokenRedis->hget($redisKey, $adminId);
  59. }
  60. $currentTime = time();
  61. $timeOut = Yii::$app->params['operationTimeOut'];
  62. if ($currentTime - $lastTime > $timeOut) {
  63. return self::notice('Connection not operated for too long', 402);
  64. } else {
  65. Yii::$app->tokenRedis->hset($redisKey, $adminId, time());
  66. }
  67. }
  68. // 校验用户权限
  69. if (!Yii::$app->user->validateAdminAction($this->id, $this->action->id)) {
  70. return self::notice('权限不足', 403);
  71. }
  72. return $parentBeforeAction;
  73. }
  74. /**
  75. * 返回结果集
  76. * @param $dataOrErrorMessage
  77. * @param int $code
  78. * @return mixed
  79. * @throws HttpException
  80. */
  81. public static function notice($dataOrErrorMessage, $code = 0) {
  82. if ($code === 0) {
  83. return $dataOrErrorMessage;
  84. } else {
  85. throw new HttpException($code, $dataOrErrorMessage, $code);
  86. }
  87. }
  88. /**
  89. * 编辑方法
  90. * @param $formModelClass
  91. * @param $successMsg
  92. * @param string|null $scenario
  93. * @param array|null $methodAndParam
  94. * [
  95. * 'edit', // form 调用对象的方法名
  96. * 'param1', // form 调用对象的方法的第一个参数
  97. * 'param2', // form 调用对象的方法的第二个参数
  98. * 'param3', // form 调用对象的方法的第三个参数
  99. * ]
  100. * @param callable|null $beforeFun
  101. * @param callable|null $afterFun
  102. * @return mixed
  103. * @throws HttpException
  104. */
  105. public static function edit($formModelClass, $successMsg, string $scenario = null, array $methodAndParam = null, callable $beforeFun = null, callable $afterFun = null) {
  106. $id = Yii::$app->request->get('id', 0);
  107. $formModel = new $formModelClass();
  108. $formModel->scenario = 'add';
  109. if ($id) {
  110. $formModel->scenario = 'edit';
  111. $formModel->id = $id;
  112. }
  113. if ($scenario !== null) {
  114. $formModel->scenario = $scenario;
  115. }
  116. if ($beforeFun) $beforeFun($formModel);
  117. if ($methodAndParam === null) {
  118. $method = 'edit';
  119. $param = [];
  120. } else {
  121. $method = $methodAndParam[0];
  122. $param = $methodAndParam;
  123. unset($param[0]);
  124. }
  125. if ($formModel->load(Yii::$app->request->post(), '') && $result = call_user_func_array([&$formModel, $method], $param)) {
  126. if ($afterFun) $afterFun($formModel, $result);
  127. return static::notice($successMsg);
  128. } else {
  129. return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 422);
  130. }
  131. }
  132. /**
  133. * 删除方法
  134. * @param $modelClass
  135. * @param callable|null $beforeFun
  136. * @param callable|null $afterFun
  137. * @param bool $isDelData
  138. * @return mixed
  139. * @throws Exception
  140. * @throws HttpException
  141. */
  142. public static function delete($modelClass, callable $beforeFun = null, callable $afterFun = null, $isDelData = true) {
  143. $selected = \Yii::$app->request->get('selected');
  144. if (!$selected) {
  145. $selected = \Yii::$app->request->post('selected');
  146. }
  147. if (!$selected) {
  148. return self::notice('必须选择一条删除数据', 500);
  149. }
  150. // 是否存在 DONT_DEL 字段
  151. if (ActiveRecord::isExistsField($modelClass, 'DONT_DEL')) {
  152. $isDontDelField = true;
  153. } else {
  154. $isDontDelField = false;
  155. }
  156. if (is_array($selected)) {
  157. if ($isDontDelField) {
  158. $condition = ['AND', ['IN', 'ID', $selected], ['<>', 'DONT_DEL', 1]];
  159. } else {
  160. $condition = ['AND', ['IN', 'ID', $selected]];
  161. }
  162. // $condition = 'ID IN ('.implode(',', $selected).') AND DONT_DEL<>1';
  163. $params = [];
  164. } else {
  165. if ($isDontDelField) {
  166. $condition = 'ID=:ID AND DONT_DEL<>1';
  167. } else {
  168. $condition = 'ID=:ID';
  169. }
  170. //$condition = ['AND', ['ID'=>$selected], ['<>', 'DONT_DEL', 1]];
  171. $params = [':ID' => $selected];
  172. }
  173. $transaction = \Yii::$app->db->beginTransaction();
  174. try {
  175. if (!is_array($selected)) {
  176. $selected = [$selected];
  177. }
  178. if ($beforeFun) $beforeFun($selected);
  179. if ($isDelData) {
  180. // 真实删除数据
  181. if (!$modelClass::deleteAll($condition, $params)) {
  182. throw new Exception('删除失败');
  183. }
  184. } else {
  185. // 设置IS_DEL字段为1
  186. $modelClass::updateAll(['IS_DEL' => 1, 'DELETED_AT' => Date::nowTime()], $condition, $params);
  187. }
  188. if ($afterFun) $afterFun($selected);
  189. $transaction->commit();
  190. return self::notice('删除成功');
  191. } catch (Exception $e) {
  192. $transaction->rollBack();
  193. return self::notice($e->getMessage(), 500);
  194. }
  195. }
  196. /**
  197. * 筛选条件
  198. * @param array $tableParams
  199. * [
  200. * '筛选提交参数名' => '表名.字段名',
  201. * 'userIds' => 'USER_INFO.USER_ID',
  202. * 'userName' => 'USER_INFO.USER_NAME',
  203. * ]
  204. *
  205. * get提交的值
  206. * [
  207. * 'userIds' => 'in,asdsa,asdsads',
  208. * 'userName' => 'like,test',
  209. * 'createdAt' => '>=,2018-11-26,date'
  210. * ]
  211. * @return array
  212. */
  213. public function filterCondition(array $tableParams = []) {
  214. $allGet = Yii::$app->request->get();
  215. $condition = '';
  216. $params = [];
  217. foreach ($tableParams as $getParam => $tableField) {
  218. if (isset($allGet[$getParam]) && $allGet[$getParam]) {
  219. $getValue = trim($allGet[$getParam], ", \t\n\r\0\x0B");
  220. $bindParam = strtoupper($getParam);
  221. if (strpos($getValue, '|') > 0) {
  222. $condition .= ' AND (';
  223. $chidValueArr = explode('|', $getValue);
  224. foreach ($chidValueArr as $k => $value) {
  225. if ($k == 0) {
  226. $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, '');
  227. } else {
  228. $result = $this->_getConditionAndParams($value, $tableField, $bindParam . $k, 'OR');
  229. }
  230. $condition .= $result['condition'];
  231. $params += $result['params'];
  232. }
  233. $condition .= ')';
  234. } else {
  235. $result = $this->_getConditionAndParams($getValue, $tableField, $bindParam);
  236. $condition .= $result['condition'];
  237. $params += $result['params'];
  238. }
  239. }
  240. }
  241. return [
  242. 'condition' => $condition,
  243. 'params' => $params,
  244. 'request' => $allGet,
  245. ];
  246. }
  247. /**
  248. * 获取条件
  249. * @param $getValue
  250. * @param $tableField
  251. * @param $bindParam
  252. * @param string $relation
  253. * @return array
  254. */
  255. private function _getConditionAndParams($getValue, $tableField, $bindParam, $relation = 'AND') {
  256. $condition = '';
  257. $params = [];
  258. $isDate = false;
  259. $filterModel = '';
  260. if (strpos($getValue, ',') > 0) {
  261. $getValueArr = explode(',', $getValue);
  262. $getSymbol = strtoupper($getValueArr[0]);
  263. if ($getSymbol == 'IN') {
  264. $bindValueArr = $getValueArr;
  265. unset($bindValueArr[0]);
  266. $bindValue = implode("','", $bindValueArr);
  267. $bindValue = "'$bindValue'";
  268. } else {
  269. $bindValue = $getValueArr[1];
  270. $filterModel = end($getValueArr);
  271. reset($getValueArr);
  272. if($filterModel == 'date'){
  273. if( $getSymbol !== '>=' && $getSymbol !== '<=' && $getSymbol !== '>' && $getSymbol !== '<' ) {
  274. throw new \Exception("日期筛选格式不对");
  275. }
  276. $bindValue = strtotime($getValueArr[1]);
  277. $isDate = true;
  278. $relation = $relation ? 'AND' : '';
  279. }
  280. elseif($filterModel == 'area'){
  281. $bindValue = array_slice($getValueArr, 1, 3);
  282. }
  283. }
  284. } else {
  285. $getSymbol = '=';
  286. $bindValue = $getValue;
  287. }
  288. if ($getSymbol == 'LIKE') {
  289. $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')>0';
  290. } elseif ($getSymbol == strtoupper('notLike')) {
  291. $condition .= ' ' . $relation . ' INSTR(' . $tableField . ',:' . $bindParam . ')=0';
  292. } elseif ($getSymbol == 'IN') {
  293. $condition .= ' ' . $relation . ' ' . $tableField . ' IN (' . $bindValue . ')';
  294. } else {
  295. if ($isDate && $getSymbol == '=') {
  296. $condition .= ' ' . $relation . ' ' . $tableField . '>=:' . $bindParam . 's';
  297. $condition .= ' AND ' . $tableField . '<=:' . $bindParam . 'e';
  298. }
  299. elseif($filterModel == 'area'){
  300. if($bindValue[0]){
  301. $condition .= ' AND '.$tableField['FIELD'][0].'=:'.$tableField['BIND'][0];
  302. if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
  303. $condition .= ' AND '.$tableField['FIELD'][1].'=:'.$tableField['BIND'][1];
  304. if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
  305. $condition .= ' AND '.$tableField['FIELD'][2].'=:'.$tableField['BIND'][2];
  306. }
  307. }
  308. }
  309. }
  310. else {
  311. if($getSymbol!=='=' && $relation=='OR'){
  312. $relation = 'AND';
  313. }
  314. $condition .= ' ' . $relation . ' ' . $tableField . $getSymbol . ':' . $bindParam;
  315. }
  316. }
  317. if ($getSymbol != 'IN') {
  318. if ($isDate && $getSymbol == '=') {
  319. $params[':' . $bindParam . 's'] = $bindValue;
  320. $params[':' . $bindParam . 'e'] = $bindValue + 86399;
  321. }
  322. if ($filterModel == 'area') {
  323. if($bindValue[0]){
  324. $params[':'.$tableField['BIND'][0]] = $bindValue[0];
  325. if(isset($bindValue[1])&&$bindValue[1]&&$bindValue[1]!='area'){
  326. $params[':'.$tableField['BIND'][1]] = $bindValue[1];
  327. if(isset($bindValue[2])&&$bindValue[2]&&$bindValue[2]!='area'){
  328. $params[':'.$tableField['BIND'][2]] = $bindValue[2];
  329. }
  330. }
  331. }
  332. }
  333. else {
  334. $params[':' . $bindParam] = $bindValue;
  335. }
  336. }
  337. return ['condition' => $condition, 'params' => $params];
  338. }
  339. /**
  340. * 筛选条件
  341. * @param string $tableName
  342. * @param array $otherParams
  343. * [
  344. * '筛选提交参数名' => '表名.字段名',
  345. * 'userName' => 'USER_INFO.USER_NAME',
  346. * ]
  347. * 或者
  348. * [
  349. * '筛选提交参数名' => ['表名.字段名', '符号'],
  350. * 'userName' => ['USER_INFO.USER_NAME', '<'],
  351. * ]
  352. * @return array
  353. */
  354. public function filterConditionBak($tableName = '', array $otherParams = []) {
  355. $dateRange = Yii::$app->request->get('dateRange', '');
  356. $condition = '';
  357. $params = [];
  358. if ($tableName) {
  359. $tableName = $tableName . '.';
  360. }
  361. if ($dateRange) {
  362. $condition .= " AND {$tableName}CREATED_AT>:CREATED_START AND {$tableName}CREATED_AT<:CREATED_END";
  363. $params[':CREATED_START'] = Date::utcToTime($dateRange[0]);
  364. $params[':CREATED_END'] = Date::utcToTime($dateRange[1]);
  365. }
  366. $requestParams = [];
  367. foreach ($otherParams as $getParam => $field) {
  368. $getValue = Yii::$app->request->get($getParam, '');
  369. $requestParams[$getParam] = $getValue;
  370. if ($getValue === 'all') $getValue = '';
  371. if ($getValue !== '') {
  372. if (is_string($field)) {
  373. $condition .= " AND $field=:" . strtoupper($getParam);
  374. $params[':' . strtoupper($getParam)] = $getValue;
  375. } elseif (is_array($field)) {
  376. if (count($field) == 1) {
  377. $condition .= " AND {$field[0]}=:" . strtoupper($getParam);
  378. $params[':' . strtoupper($getParam)] = $getValue;
  379. } elseif (count($field) == 2) {
  380. if (strtolower($field[1]) == 'in') {
  381. $getValue = Tool::filterSpecialChar($getValue);
  382. if ($getValue) {
  383. $getValue = explode(',', $getValue);
  384. $getValue = implode("','", $getValue);
  385. $getValue = "'$getValue'";
  386. $condition .= " AND {$field[0]} IN ({$getValue})";
  387. }
  388. } else {
  389. $condition .= " AND {$field[0]}{$field[1]}:" . strtoupper($getParam);
  390. $params[':' . strtoupper($getParam)] = $getValue;
  391. }
  392. }
  393. }
  394. }
  395. }
  396. // 请求的参数也一并返回
  397. $request = array_merge([
  398. 'dateRange' => $dateRange,
  399. ], $requestParams);
  400. return [
  401. 'condition' => $condition,
  402. 'params' => $params,
  403. 'request' => $request,
  404. ];
  405. }
  406. }