CController.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  1. <?php
  2. namespace app\common\controllers;
  3. use app\modules\cms\models\CategoryPriv;
  4. use Yii;
  5. use yii\web\Controller;
  6. use yii\helpers\Url;
  7. use app\common\helpers\Cookie;
  8. /**
  9. * 基类
  10. */
  11. class CController extends Controller
  12. {
  13. public $imgcodeUrl;
  14. public $moduleName;
  15. public $controllerName;
  16. public $actionName;
  17. public $adminHomeUrl;
  18. public $waterMarkPos;//水印位置
  19. public $mediaTimeTypes;//多媒体时长类型
  20. public $transferPageTypes;//转换页数类型
  21. public $loginWays;//登录方式
  22. public $breadcrumbs;//面包屑
  23. public function init()
  24. {
  25. parent::init();
  26. error_reporting(0);
  27. $this->adminHomeUrl = APP_URL."index.php";
  28. $this->imgcodeUrl = Url::to(['/site/imgcode','width'=>120,'height'=>40]);
  29. }
  30. public function behaviors()
  31. {
  32. $this->moduleName = Yii::$app->controller->module->id;
  33. $this->controllerName = Yii::$app->controller->id;
  34. $this->actionName = Yii::$app->controller->action->id;
  35. }
  36. public function render($view, $params = [])
  37. {
  38. $content = $this->getView()->render($view, $params, $this);
  39. if (strpos(Yii::$app->urlManager->createAbsoluteUrl('/car'), '10.170.42')) {
  40. return str_replace(['/assets/','action="/'],['/house-car/car/assets/','action="/house-car/car/'],$this->renderContent($content));
  41. }
  42. return $this->renderContent($content);
  43. }
  44. public function renderAjax($view, $params = [])
  45. {
  46. ob_start();
  47. ob_implicit_flush(false);
  48. $this->getView()->beginPage();
  49. $this->getView()->head();
  50. $this->getView()->beginBody();
  51. echo $this->getView()->render($view, $params, $this);
  52. $this->getView()->endBody();
  53. $this->getView()->endPage(true);
  54. $content = ob_get_clean();
  55. if (strpos(Yii::$app->urlManager->createAbsoluteUrl('/car'), '10.170.42')) {
  56. $content = str_replace(['/assets/','action="/'],['/house-car/car/assets/','action="/house-car/car/'],$content);
  57. }
  58. echo $content;
  59. return ob_get_clean();
  60. }
  61. /**
  62. * 返回后台身份状态信息
  63. * @param string $key
  64. * @return array or string;
  65. *
  66. */
  67. public function getIdentityInfo($key='')
  68. {
  69. $cookieName = defined('IN_ADMIN')?'adminCookieName':'userCookieName';
  70. $identityInfo = Cookie::getCookie(Yii::$app->params[$cookieName]);
  71. if(empty($identityInfo)) $identityInfo = Yii::$app->session['adminInfo'];
  72. $identityInfo = string2array(sys_auth($identityInfo,'DECODE'));
  73. $dataStr = !empty($_GET['data'])?$_GET['data']:Cookie::getCookie('data_str');
  74. if(empty($identityInfo) && $dataStr){
  75. $identityInfo = $this->getIdentityInfoByToken($dataStr);
  76. }
  77. return $result = isset($key)&&isset($identityInfo[$key])?$identityInfo[$key]:$identityInfo;
  78. }
  79. //判断是否登录
  80. public function hasLogined()
  81. {
  82. $cookieName = defined('IN_ADMIN')?'adminCookieName':'userCookieName';
  83. $identityInfo = $this->getIdentityInfo(Yii::$app->params[$cookieName]);
  84. if(!empty($identityInfo)&&is_array($identityInfo))
  85. {
  86. if(sys_auth($identityInfo['cookieHash'],'DECODE')!=$identityInfo['user_name'])
  87. {
  88. return false;
  89. }
  90. else
  91. {
  92. return true;
  93. }
  94. }
  95. else
  96. {
  97. return false;
  98. }
  99. }
  100. //Modal框中的提示信息
  101. public function showAlertInModal($msg,$class='danger')
  102. {
  103. echo '<div class="alert alert-'.$class.'" >'.$msg.'</div>';
  104. }
  105. /**
  106. * 页面提示信息
  107. * @parame array $data array('message'=>$message,'arguments'=>$arguments,'url'=>$url,'title'=>$title,'time'=>$time,'target'=>$target)
  108. * @param string $message 错误信息
  109. * @parame string $url 页面跳转路径
  110. * @parame int $time 页面延迟跳转时间
  111. * @parame string $target 目标窗口
  112. */
  113. public function showMessage($data,$exit=0)
  114. {
  115. if(is_array($data)) extract($data);
  116. if(empty($time)) $time =0;//毫秒
  117. if(empty($target)) $target = 'self';
  118. if(empty($class))$class='info';//可选类别:danger,success,info,warning
  119. //获取返回页面
  120. if(empty($url))
  121. {
  122. $url = Yii::$app->request->referrer;
  123. $tempUrl = explode("/",ltrim($url,SITE_PROTOCOL));
  124. if(strpos($tempUrl[0],COOKIE_DOMAIN)===false)//其他网站入口,返回首页
  125. {
  126. if(defined('IN_WAP')&&IN_WAP==true)//如果是手机端
  127. {
  128. $url = WAP_URL;
  129. }
  130. else
  131. {
  132. $url = WEB_URL;
  133. }
  134. }
  135. }
  136. if(empty($title))
  137. $title = Yii::t('admin','system alert');
  138. if(!isset($message))
  139. $message = '';
  140. if($time>0)
  141. {
  142. echo Yii::$app->view->renderFile('@app/views/alert/info.php', array('message'=>$message,'url'=>$url,'title'=>$title,'time'=>$time,'target'=>$target,'class'=>$class));
  143. }
  144. else
  145. {
  146. echo "<script>";
  147. echo "window.location.href='".$url."'";
  148. echo "</script>";
  149. }
  150. if($exit)exit();
  151. }
  152. //生成含入口脚本的URL地址
  153. public function createRealUrl($params)
  154. {
  155. if(!empty($_GET['data']) && is_array($params)){
  156. $params['data'] = $_GET['data'];
  157. }
  158. $url = urldecode(Yii::$app->urlManager->createAbsoluteUrl($params));
  159. if (strpos($url, '10.170.42')) {
  160. $url = str_replace(['http:','/car/','/ajax/'],['https:','/house-car/car/car/','/house-car/car/ajax/'],$url);
  161. }
  162. //$url = str_replace(['/car/'],['/house-car/car/car/'],$url);
  163. return $url;
  164. }
  165. //获取URL中传递的ID值(可以自定义参数名)
  166. protected function getKeyId($keyField='id')
  167. {
  168. if(isset($_GET[$keyField]))
  169. {
  170. if(is_numeric($_GET[$keyField]))return intval($_GET[$keyField]);
  171. else return safe_replace($_GET[$keyField]);
  172. }
  173. else
  174. {
  175. throw new \Exception($keyField.' is required');
  176. }
  177. }
  178. //格式化树结构数据
  179. public function serializeTreeData($resultList,$keyId,$parentKeyId,$nameKey='name',$langFile='resource')
  180. {
  181. $datas = array();
  182. $results = array();
  183. $i=0;
  184. if(!empty($resultList))
  185. {
  186. foreach($resultList as $o)
  187. {
  188. $results[$i][$keyId] = $o->$keyId;
  189. $results[$i]['parent_id'] = $o->$parentKeyId;
  190. $results[$i]['name'] = Yii::t($langFile,$o->$nameKey);
  191. $i++;
  192. }
  193. }
  194. if (is_array($results)) {
  195. foreach($results as $r) {
  196. $datas[$r[$keyId]] = array('id'=>$r[$keyId], 'parent_id'=>$r['parent_id'], 'name'=>$r['name']);
  197. }
  198. }
  199. return $datas;
  200. }
  201. //写配置文件
  202. public static function setConfig($config, $filename="params") {
  203. if(defined('SITE_MODE'))
  204. {
  205. $configfile = BASE_PATH.'config'.DIRECTORY_SEPARATOR.SITE_MODE.DIRECTORY_SEPARATOR.$filename.'.php';
  206. }
  207. else
  208. {
  209. $configfile = BASE_PATH.'config'.DIRECTORY_SEPARATOR.$filename.'.php';
  210. }
  211. if(!is_writable($configfile)) exit('Please chmod '.$configfile.' to 0777 !');
  212. $pattern = $replacement = array();
  213. foreach($config as $k=>$v) {
  214. //if(in_array($k,array('OSS_ACCESS_ID','OSS_ACCESS_KEY','OSS_ENDPOINT','OSS_BUCKET','OPEN_ALIOSS'))) {
  215. $v = trim($v);
  216. $configs[$k] = $v;
  217. $pattern[$k] = "/'".$k."'\s*=>\s*([']?)[^']*([']?)(\s*),/is";
  218. $replacement[$k] = "'".$k."' => \${1}".$v."\${2}\${3},";
  219. //}
  220. }
  221. $str = file_get_contents($configfile);
  222. $str = preg_replace($pattern, $replacement, $str);
  223. return Yii::$app->params['lockEx'] ? file_put_contents($configfile, $str, LOCK_EX) : file_put_contents($configfile, $str);
  224. }
  225. //写单个配置文件
  226. public static function writeConfigFile($config, $filename="params") {
  227. if(defined('SITE_MODE'))
  228. {
  229. $configfile = BASE_PATH.'config'.DIRECTORY_SEPARATOR.SITE_MODE.DIRECTORY_SEPARATOR.$filename.'.php';
  230. }
  231. else
  232. {
  233. $configfile = BASE_PATH.'config'.DIRECTORY_SEPARATOR.$filename.'.php';
  234. }
  235. if(!is_writable($configfile)) exit('Please chmod '.$configfile.' to 0777 !');
  236. $configStr = "<?php".PHP_EOL;
  237. $configStr .= "return array(".PHP_EOL;
  238. $configStr .= "\t'params'=>array(".PHP_EOL;
  239. $configStr .= "\t\t'$filename'=>array(".PHP_EOL;
  240. if(is_array($config))foreach($config as $k=>$v)
  241. {
  242. $configStr .= "\t\t\t'$k'=>'$v',".PHP_EOL;
  243. }
  244. $configStr .= "\t\t),".PHP_EOL;
  245. $configStr .= "\t),".PHP_EOL;
  246. $configStr .= ");".PHP_EOL;
  247. $configStr .= "?>";
  248. return Yii::$app->params['lockEx'] ? file_put_contents($configfile, $configStr, LOCK_EX) : file_put_contents($configfile, $configStr);
  249. }
  250. //判断栏目权限
  251. public static function hasCategoryPirv($obj)
  252. {
  253. if($obj->is_admin&&$obj->role_id==1)
  254. {
  255. return true;
  256. }
  257. else
  258. {
  259. $priv_obj = CategoryPriv::find()->where("cat_id=".$obj->cat_id." and role_id=".$obj->role_id." and is_admin=".$obj->is_admin." and action='".$obj->action."'")->one();
  260. if(!empty($priv_obj))
  261. {
  262. return true;
  263. }
  264. else
  265. {
  266. return false;
  267. }
  268. }
  269. }
  270. //美化目录树显示
  271. function beautifulTree($arr, $preview=0,$l = '-|')
  272. {
  273. if(Yii::$app->controller->module->transferconfig['previewpack']==1)$preview=1;
  274. $attConfigInfo = \app\modules\admin\models\Config::find()->where("name='attachment'")->one();
  275. $attConfig = string2array($attConfigInfo->value);
  276. $fileTypeList = explode("|",$attConfig['file_type']);
  277. static $l = '';
  278. static $str = '<ul class="file-tree">';
  279. //遍历刚才得到的目录树
  280. foreach($arr as $key=>$val) {
  281. //如果是个数组,也就代表它是个目录,那么就在它的子文件中加入-|来表示是下一级吧
  282. if(is_array($arr[$key])) {
  283. $valInfo = explode('/',strval($key));
  284. $str.="<li data-jstree='{\"opened\":true,\"icon\":\"iconfont icon-wenjianjia1\"}'>&nbsp;".$valInfo[count($valInfo)-1]."<ul>";
  285. $this->beautifulTree($arr[$key], $preview, $l);
  286. $str.= "</ul>";
  287. }else {
  288. $valInfo = explode('/',strval($val));
  289. $ext = in_array(fileext($val),$fileTypeList)?fileext($val):'file';
  290. if($preview>=1)
  291. {
  292. $str.="<li data-jstree='{\"opened\":true,\"icon\":\"iconfont icon-".$ext."\"}' data-md5='".md5($val)."' class='previewpackfile".$preview."' >&nbsp;".$l.$valInfo[count($valInfo)-1]."<span style='margin-left:15px;'>--点击预览</span></li>";
  293. }
  294. else
  295. {
  296. $str.="<li data-jstree='{\"opened\":true,\"icon\":\"iconfont icon-".$ext."\"}'>&nbsp;".$l.$valInfo[count($valInfo)-1]."</li>";
  297. }
  298. }
  299. }
  300. $l = '';
  301. return $str;
  302. }
  303. //压缩包文件数量
  304. function packFileNum($arr)
  305. {
  306. static $num = 0;
  307. //遍历刚才得到的目录树
  308. if(is_array($arr))foreach($arr as $key=>$val) {
  309. //如果是个数组,也就代表它是个目录,那么就在它的子文件中加入-|来表示是下一级吧
  310. if(is_array($arr[$key])) {
  311. $this->packFileNum($arr[$key]);
  312. }else {
  313. $num++;
  314. }
  315. }
  316. return $num;
  317. }
  318. //头像
  319. public function makeAvatar($imagePath,$width,$height)
  320. {
  321. $hash = $imagePath?md5($imagePath):'noavatar';
  322. $img = \app\modules\admin\models\Attachment::find()->where("hash='".$hash."'")->limit(1)->one();
  323. if(!$img&&is_net_file($imagePath))
  324. {
  325. return $imagePath;
  326. }
  327. else
  328. {
  329. return APP_URL.'avt/'.$width.'/'.$height.'/'.$hash.'.jpg';
  330. }
  331. }
  332. //缩略图
  333. public function makeThumb($imagePath,$width,$height)
  334. {
  335. if(Yii::$app->params['oss']['OPEN_OSS']&&Yii::$app->params['oss']['OSS_THUMB'])
  336. {
  337. $fileUrl = getFileUrl($imagePath);
  338. if(Yii::$app->params['oss']['OSS_TYPE']=='tencent')
  339. {
  340. return $fileUrl.'?imageMogr2/thumbnail/'.$width.'x'.$height;
  341. }
  342. if(Yii::$app->params['oss']['OSS_TYPE']=='ali')
  343. {
  344. return $fileUrl.'?x-oss-process=image/resize,m_fill,h_'.$height.',w_'.$width;
  345. }
  346. if(Yii::$app->params['oss']['OSS_TYPE']=='baidu')
  347. {
  348. return $fileUrl.'?x-bce-process=image/resize,m_fill,w_'.$width.',h_'.$height;
  349. }
  350. else
  351. {
  352. return $fileUrl;
  353. }
  354. }
  355. else
  356. {
  357. $hash = $imagePath?md5($imagePath):'noimage';
  358. return APP_URL.'p/'.$width.'/'.$height.'/'.$hash.'.jpg';
  359. }
  360. }
  361. //当前用户是否有权限访问和操作所请求的资源
  362. public function checkRights($user_id,$model,$fild_name='user_id')
  363. {
  364. if ($model->$fild_name != $user_id){
  365. if (Yii::$app->request->isAjax) {
  366. $msgdata = ['error' => 1,'msg' => '没有操作权限'];
  367. echo_json($msgdata);
  368. }
  369. else
  370. {
  371. throw new \yii\web\ForbiddenHttpException('你只能操作你自己创作的数据');
  372. }
  373. }
  374. else
  375. {
  376. return true;
  377. }
  378. }
  379. //解密价值平台字串
  380. public function getIdentityInfoByToken($str){
  381. if ($str == null) {
  382. return false;
  383. }
  384. //Cookie::setCookie('data_str',$str);
  385. $str = str_replace("\\\\n", "", $str);
  386. $str = str_replace("/add/", "+", $str);
  387. // 解密
  388. $decrypted = json_decode(openssl_decrypt(base64_decode($str),"AES-128-ECB", '2na$$PdV9AW8b#CS',OPENSSL_RAW_DATA),true);
  389. //var_dump($decrypted);
  390. if(!empty($decrypted) && is_array($decrypted) && isset($decrypted['LOGIN_ID']) && isset($decrypted['APP_ID']) && isset($decrypted['TIME_STAMP']) && isset($decrypted['REQUEST_URL'])){
  391. //if(time()-5*60 > strtotime($decrypted['TIME_STAMP']) || time() + 5*60 < strtotime($decrypted['TIME_STAMP'])) return 'token';
  392. $identityInfo = array();
  393. $identityInfo['admin_id']=1;
  394. $identityInfo['user_name']=$decrypted['LOGIN_ID'];
  395. $identityInfo['role_id']=1;
  396. $identityInfo['real_name']='管理员';
  397. $identityInfo['role_name']='超级管理员';
  398. $identityInfo['cookieHash'] = sys_auth($decrypted['LOGIN_ID']);
  399. $identityInfo['login_type'] = 'token';
  400. $info = sys_auth(array2string($identityInfo));
  401. Yii::$app->session['adminInfo']=$info;
  402. Cookie::setCookie(Yii::$app->params['adminCookieName'],$info);//使用COOKIE记录用户身份信息
  403. //为锁屏功能设置的一个开关变量
  404. Cookie::setCookie('lockscreen',0);
  405. return $identityInfo;
  406. }
  407. return 'token';
  408. }
  409. }