BaseController.php 15 KB

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