BaseController.php 15 KB

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