| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803 |
- <?php
- // +----------------------------------------------------------------------
- // | ThinkPHP [ WE CAN DO IT JUST THINK ]
- // +----------------------------------------------------------------------
- // | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved.
- // +----------------------------------------------------------------------
- // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
- // +----------------------------------------------------------------------
- // | Author: liu21st <liu21st@gmail.com>
- // +----------------------------------------------------------------------
- declare (strict_types=1);
- namespace app;
- /*require "../vendor/cgf/src/Cgf.php";
- require "../vendor/cgf/src/SqlToCgfDefinition.php";
- require "../vendor/cgf/src/TableInfoInterface.php";
- require "../vendor/cgf/src/TableInfo/Mysql.php";
- require "../vendor/cgf/src/CommentParser.php";
- require "../vendor/cgf/src/Definition.php";
- require "../vendor/cgf/src/Form.php";
- require "../vendor/cgf/src/Framework/Thinkphp/Bootstrap.php";
- require "../vendor/cgf/src/validate.php";
- require "../vendor/cgf/src/validate/ThinkphpValidate.php";
- require "../vendor/cgf/src/Template.php";
- require "../vendor/cgf/src/Framework/Thinkphp/ThinkphpTemplate.php";*/
- use app\BaseController;
- //use Cgf\Cgf;
- use Cgf\Cgf;
- use think\App;
- use think\facade\View;
- use think\facade\Db;
- /**
- * 控制器基础类
- */
- class CgfController extends BaseController
- {
- public $cgf; //静态类会不会更好?
- public $m;
- public $moduleName;
- public $controllerName;
- public $actionName;
- function __construct(App $app)
- {
- parent::__construct($app);
- $this->moduleName = \think\facade\Request::app();
- $this->controllerName = \think\facade\Request::controller();
- $this->actionName = \think\facade\Request::action();
- //var_dump($this->moduleName,$this->controllerName,$this->actionName);exit;
- $tableName = APP::parseName($this->controllerName);
- $this->m = Db::name($this->controllerName);
- error_reporting(E_ALL ^ E_NOTICE);
- $appBasePath = __DIR__;
- $dbconfig = include('../config/database.php');
- $dbconfig = $dbconfig['connections']['mysql'];
- //dump(Cgf::$config);exit;
- $dbconfig = Cgf::getDbConfigFromThinkPHP($dbconfig);
- $cgfConf = [];
- $cgfConf['dbConfig'] = $dbconfig;
- $cgfConf['savePath'] = $appBasePath . "/Cgf/definition";//保存cgf生成的定义文件
- $cgfConf['framework'] = 'thinkphp';//使用的框架
- $cgfConf['validate'] = 'thinkphp';//使用验证库
- $cgfConf['form'] = 'bootstrap';//表单使用的框架
- $cgfConf['currentName'] = 'common';//当前模块名
- $cgfConf['tableName'] = $tableName;//表名
- $cgfConf['controllerName'] = $this->controllerName;//控制器名
- $cgfConf['appRootPath'] = $appBasePath;//框架应用程序根目录
- $cgfConf['parentTemplatePath'] = $appBasePath . '/view/public/';//cgf生成模板使用的父模板,cgf会根据这里的模板来生成应用模板
- $cgfConf['templateSavePath'] = $appBasePath . "/view/{$tableName}";//cgf生成的模板保存路径
- $cgfConf['availableModule'] = ['common', 'admin'];//可用模块
- $cgfConf['autoHiddenPrimaryKey'] = false;//是否将主键表单类型设为hidden
- $this->cgf = new Cgf($cgfConf);
- }
- public function index()
- {
- //数据
- $map = $this->_search();
- if (method_exists($this, '_filter')) {
- $this->_filter($map);
- }
- if (!empty ($this->m)) {
- $this->_list($this->m, $map);
- }
- //模板
- $r = $this->cgf->generateListsTemplate();
- return view('');
- }
- public function add()
- {
- $tpl = $this->cgf->generateAddTemplatel();
- //配置select选项和选中值
- $allColumnOptionsDefinition = $this->cgf->getAllColumnOptions();
- foreach ($allColumnOptionsDefinition as $column => $option) {
- $this->assign('opt_' . $column, $option);
- $this->assign($column . '_selected', input($column,''));
- }
- /*if (method_exists($this, '_replacePublic')) {
- $this->_replacePublic($vo);
- }
- $this->pageTitle = $this->getControllerTitle(CONTROLLER_NAME) . "添加";
- $this->cgf = "cgf";*/
- return view();
- }
- function edit()
- {
- $this->cgf->generateAddTemplatel();
- $pk = "id";
- $id = input($pk);
- $where = [];
- $where[$pk] = $id;
- if (MODULE_NAME == 'User') $where['user_id'] = $this->user_id;
- $vo = $this->m->where($where)->find();
- /* if (method_exists($this, '_replacePublic')) {
- $this->_replacePublic($vo);
- }*/
- //$pageTitle = $this->getControllerTitle(CONTROLLER_NAME) . "编辑";
- $pageTitle = '';
- $this->cgf = "cgf";
- $view = ['vo'=>$vo,'action'=>'edit','cgf' => 'cgf', 'pageTitle' => $pageTitle];
- return view('add', $view);
- }
- //保存添加和编辑
- function save()
- {
- if (haveUploadFile()) {
- $uploadInfo = $this->commonUpload();
- if (!empty($uploadInfo)) {
- foreach ($uploadInfo as $k => $v) {
- $_POST[$k] = $v['path'];
- }
- }
- }
- //var_dump($this->isAjax());exit;
- //$id = I($this->m->getPk ());
- $id = I('id');
- //$vo = $this->m->getById ( $id );
- //自动验证
- //$tableInfo = new TableInfo('',$this->dbConnection);
- $validate = new ThinkphpValidate();
- $this->cgf->setValidate($validate);
- $tableName = $this->m->getTableName();
- $rules = $this->cgf->generateValidate($tableName);
- //$auto = $tableInfo->getAutoComplete($tableName);
- $data = $this->m->create();
- if (empty($id)) {
- $isNew = 1;
- unset($_POST['id']);
- //$r = $this->m->validate($rules)->create ();
- /*var_dump($_GET);
- var_dump($_POST);
- var_dump($_REQUEST);
- var_dump($r);eixt;*/
- //$_POST['user_id'] = $this->user_id; //添加时默认加上用户id
- if (false === $this->m->validate($rules)->create()) {
- //$this->error ( $this->m->getError () );
- }
- $r = $this->m->add();
- $id = $r;
- } else {
- if (false === $this->m->validate($rules)->create()) {
- $this->error($this->m->getError());
- }
- $r = $this->m->save();
- }
- //保存当前数据对象
- if (method_exists($this, '_after_save') && $id) $this->_after_save($id);
- //echo $this->m->getLastSql();exit;
- if ($id !== false) { //保存成功
- $ret = [];
- //$this->assign ( 'jumpUrl', cookie( '_currentUrl_' ) );
- if (I('multiple')) { //多图,需要关联图片到对应的主题,
- //注意,不支持一个主题里有两个以上字段都是多图上传。此情况需要在图片表里增加标识,属于哪个字段,
- //或在主题字段里存储用逗号分隔的图片id,如:1,2,3
- //其实不用forech,直接取$uploadInfo[0]即可,反正又不支持多字段多图上传
- if (!empty($uploadInfo)) {
- foreach ($uploadInfo as $k => $v) {
- $ids[$k] = array_column($v, 'id');
- M('File')->where(['id' => ['in', $ids[$k]]])->setField('tid', $id);
- }
- $ret = $uploadInfo;
- }
- }
- if ($this->successRedirectUrl) {
- $redirectUrl = $this->successRedirectUrl . $id;
- } elseif ($isNew && $this->newInfoNextUrl) {
- $redirectUrl = $this->newInfoNextUrl . $id;
- } else {
- //$redirectUrl = cookie( '_currentUrl_' );
- $redirectUrl = "/" . CONTROLLER_NAME;
- }
- C('info_id', $id);
- $ret['id'] = $id;
- $this->success($ret, '成功', $redirectUrl);
- } else {
- //失败提示
- $this->error('失败了!');
- }
- }
- function _initialize() {
- //由于 Think\controller construct 里先调用了_initialize ,
- // 但userBase 验证登录是放在_initialize,导致此类construct 还没执行,就被跳转了
- // 跳转代码获取不到ret_format 导出返回信息仍是html 跳转
- //所以要此代码从construct 移动到此处
- if(IS_AJAX){
- C('ret_format','json');
- }elseif(!empty(I(C('VAR_JSONP_HANDLER')))){
- C('ret_format','jsonp');
- }
- if($this->enableLog && !IS_CLI) $this->requestLog();
- //白名单优先
- if(!empty(C('whitelist'))) {
- //只允许白名单中的controller
- $wl_control = C('whitelist.controller');
- $wl_action = C('whitelist.action');
- $wl_url = C('whitelist.url');
- $wl_url = array_map(
- function($value) {
- return strtolower($value);
- },
- $wl_url
- );
- $current_url = CONTROLLER_NAME . '/' . ACTION_NAME;
- //var_dump(lcfirst($current_url));
- //var_dump($wl_url);exit;
- if (in_array(lcfirst(CONTROLLER_NAME), $wl_control)
- || in_array(lcfirst(ACTION_NAME), $wl_action)
- || in_array(strtolower($current_url), $wl_url)
- ) {
- //通过白名单
- } else {
- $this->error('control 1 非法访问');
- }
- }
- //黑名单
- if(!empty(C('blacklist'))){
- //禁用访问黑名单中的controller
- $bl_control = C('blacklist.controller');
- $bl_action = C('blacklist.action');
- $bl_url = C('blacklist.url');
- $current_url = CONTROLLER_NAME.'/'.ACTION_NAME;
- if( in_array(lcfirst(CONTROLLER_NAME),$bl_control)
- || in_array(lcfirst(ACTION_NAME),$bl_action)
- || in_array(strtolower($current_url),$bl_url)
- ){
- $this->error('control 2 非法访问');
- }
- }
- $referer = empty($_SERVER['HTTP_REFERER']) ? '/' : $_SERVER['HTTP_REFERER'];
- C('referer',$referer);
- $this->platform = $this->getPlatform();
- //$this->referer = $_SERVER['HTTP_REFERER'];
- /*//url带openid 自动写cookie,session等登录标识
- $open_id = I('open_id');
- if($open_id){
- $r = M('User')->where(["open_id" => $open_id,"type" => I('type')])->find();
- if(!empty($r)){
- $r['user_id'] = $r['id'];
- $this->tempStorageOpenidUser = $r;
- setUserAuth($r); //登录前在getAuth 里增加个标识,如果get open_id有值,不必取cookie,直接标识为登录
- }
- }
- //exit('x');exit;
- //用户信息
- if(!empty($this->user_id)){
- $m = M('User');
- $r = $m->find($this->user_id);
- //var_dump($r);
- //echo $m->getLastSql();
- //exit;
- if(empty($r['nickname']) && !empty($r['username'])) $r['nickname'] = $r['username'];
- $this->assign ( 'user', $r );
- }
- if(C('USER_AUTH_ON')){
- import ( '@.ORG.Util.RBAC_WEB' );
- $app = 'USER';
- }else{
- import ( 'ORG.Util.RBAC' );
- $app = APP_NAME;
- }*/
- }
- function getPlatform(){
- $platform = I('server.platform');
- if(empty($platform)){
- if(IS_MOBILE){
- if(is_weixin()){
- $platform = 'wx';
- }else{
- $platform = 'wap';
- }
- }else{
- $platform = 'pc';
- }
- }
- return $platform;
- }
- /**
- * 设置用户id
- * @param $user_id
- */
- protected function setUserId($user_id){
- $_REQUEST['user_id'] = $_POST['user_id'] = $_GET['user_id'] = $user_id;//$this->user_id;
- }
- //有连接表显示列表
- public function indexLink($option=array())
- {
- //列表过滤器,生成查询Map对象
- $map = $this->_search ();
- if (method_exists ( $this, '_filter' )) {
- $this->_filter ( $map );
- }
- $name=CONTROLLER_NAME;
- if (! empty ( $this->m )) {
- if ($option['join']) {
- $this->_listLink($this->m, $map, $option);
- } else {
- $this->_list($this->m, $map);
- }
- }
- if(!IS_AJAX){
- $tplContent = $this->generateListTpl();
- }
- $this->pageTitle = $this->getControllerTitle(CONTROLLER_NAME)."列表";
- $this->cgf="cgf";
- $this->toview();
- }
- public function msg($result,$text = '',$url=''){
- if(false !== $result){
- $this->success($text."成功");
- }else{
- $this->error($text."失败");
- }
- }
- //获取用户登录凭证信息
- function getAuth(){
- $u = getUserAuth();
- if(!ONLINE){
- //$u['user_id'] = 4;
- }
- //===============================================临时代码 所有付费用户绑定完后,就要删除 同时要删除get-weixin-code.html里110行的临时代码 ===============================================
- if(is_weixin() && !empty($u)){
- $code = I('code');
- if(!empty($code)) { //是微信用户,且已经用手机登录过了,而且没有绑定过unionid,且unionid没有被其它用户绑定过,则绑定
- $rU = M('User')->find($u['user_id']);
- if(empty($rU['wx_union_id']) || $rU['wx_union_id']==null ){
- $conf = C('wechat');
- $this->auth = new WechatAuth($conf['appid'], $conf['appSecret']);
- if (empty($token)) {
- $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$conf['appid']}&secret={$conf['appSecret']}&code={$code}&grant_type=authorization_code";
- $accessToken = file_get_contents($url);
- $accessToken = json_decode($accessToken, 1);
- //var_dump($accessToken);
- $token = $accessToken['access_token'];
- $open_id = $accessToken['openid'];
- C('openid',$open_id);
- $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid=$open_id";
- //echo $url;
- $userinfo = file_get_contents($url);
- $wxUserInfo = json_decode($userinfo, true);
- if($wxUserInfo['errcode'] == '41001'){
- tplog("wx_error:".$userinfo['errmsg'],'ERR', '', LOG_PATH.'/wx.log');
- }
- if(!empty($wxUserInfo['unionid'])){
- $rUnionIdUser = M('User')->where(['wx_union_id'=>$wxUserInfo['unionid']])->find();
- if(empty($rUnionIdUser)){
- $mUser = D('User');
- $userInfo = $mUser->wxUserInfoToUser($wxUserInfo);
- $mUser->where(['id' => $rU['id']])->save($userInfo);
- }
- }
- }
- }
- }
- }
- //===============================================临时代码 所有付费用户绑定完后,就要删除 ===============================================
- if(empty($u)){
- $open_id = I('open_id');
- $type = I('type');
- $code = I('code');
- if(!empty($open_id) && in_array($type,['wx','wb','qq','gzh']) ){ //公众号搜索进入
- $field = $type.'_open_id';
- $where[$field] = $open_id;
- $u['user_id'] = M('User')->where($where)->getField('id');
- //微信公众号用户浏览,第一次要设置cookie,相当于登录操作
- if($type=='gzh'){
- setUserAuth($u);
- }
- }elseif(!empty($code)){ //公众号链接进入
- $conf = C('wechat');
- /* $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$conf['appid']}&secret={$conf['appSecret']}&code={$code}&grant_type=authorization_code";
- $r = file_get_contents($url);
- var_dump($r);//exit;*/
- //$this->wechat = new Wechat($conf['token'], $conf['appid'], $conf['crypt']);
- $this->auth = new WechatAuth($conf['appid'], $conf['appSecret']);
- //$token = S('weixin_token');
- if(empty($token)){
- //$accessToken = $this->auth->getAccessToken('code',$code);
- $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$conf['appid']}&secret={$conf['appSecret']}&code={$code}&grant_type=authorization_code";
- $accessToken = file_get_contents($url);
- $accessToken = json_decode($accessToken,1);
- //var_dump($accessToken);
- $token =$accessToken['access_token'];
- $open_id=$accessToken['openid'];
- C('openid',$open_id);
- $url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token}&openid=$open_id";
- //echo $url;
- $userinfo = file_get_contents($url);
- $userinfo = json_decode($userinfo,true);
- //var_dump($userinfo);//exit('x==========');
- if($userinfo['errcode'] == '41001'){
- tplog("wx_error:".$userinfo['errmsg'],'ERR', '', LOG_PATH.'/wx.log');
- }
- if(!empty($userinfo['unionid'])){
- $mUser = M('User');
- $rUser = $mUser->where(['wx_union_id'=>$userinfo['unionid']])->find();
- if(!empty($rUser)){
- $u['user_id'] = $rUser['id'];
- setUserAuth($u);
- }else{
- $id = $this->registerLinkGzh($userinfo);
- $u['user_id'] = M('User')->where(['id'=>$id])->getField('id');
- //微信公众号用户浏览,第一次要设置cookie,相当于登录操作
- setUserAuth($u);
- // var_dump($u);
- // var_dump($userinfo);exit('============');
- //var_dump($userinfo);exit('x');
- //S('weixin_token',$token,$accessToken['expires_in']-120);
- }
- }
- }
- /*$this->auth->setAccessToken($token);
- $this->token = $token;
- $this->openid = $open_id;
- exit('x');
- $info = $this->auth->getUserInfo($this->openid);
- var_dump($info);exit('x');
- $this->registerUser();*/
- }
- if(empty($u)){
- return false;
- }
- }
- //要去数据库验证有没有此id
- $tableInfo = new TableInfo('list');
- $selectFields = $tableInfo->createListSelectFields('user');
- $dbUserInfo = M('User')->field($selectFields)->find($u['user_id']);
- if(empty($dbUserInfo)){
- debug('没有此用户');
- //echo '没有此用户';
- return false;
- }
- $dbUserInfo['nickname'] = !empty($dbUserInfo['nickname']) ? $dbUserInfo['nickname'] : ( !empty($dbUserInfo['username']) ? $dbUserInfo['username'] : '竞拍用户') ;
- $dbUserInfo['avatar'] = img($dbUserInfo['avatar'],'user_avatar');
- $this->user_id = $dbUserInfo['id'];
- $this->user = $dbUserInfo;
- $this->assign('user_id',$this->user_id);
- $this->assign('user',$this->user);
- return $dbUserInfo;
- }
- /**
- * 公众号链接新用户注册,unionid注册
- * @param $info
- */
- function registerLinkGzh($info){
- $userInfo = [];
- $userInfo['unionid'] = $info['unionid'];
- $userInfo['gzh_open_id'] = $info['openid'];
- $userInfo['province'] = $info['province'];
- $userInfo['city'] = $info['city'];
- $userInfo['avatar'] = $info['headimgurl'];
- $userInfo['sex'] = $info['sex'];
- $userInfo['nickname'] = $info['nickname'];
- $sex_map=[0=>2,1=>1,2=>0];
- $userInfo['sex'] = $sex_map[$info['sex']];
- $extra = [];
- $extra['subscribe'] = $info['subscribe'];
- $extra['groupid'] = $info['groupid'];
- $extra['tagid_list'] = $info['tagid_list'];
- $extra['subscribe_time'] = $info['subscribe_time'];
- $userInfo['extra'] = json_encode($extra,JSON_UNESCAPED_UNICODE);
- //wx_open_id
- /** @var \Common\Model\UserModel $mUser */
- $mUser = D('User');
- $r = $mUser->oauthUnionidAdd('wx',$userInfo);
- return $r;
- }
- /**
- * 公众号搜索新用户注册
- */
- function registerUser(){
- /** @var \Common\Model\UserModel $mUser */
- $mUser = D('User');
- $field = 'wx_open_id';
- $r = $mUser->where(['gzh_open_id' => $this->openid ])->find();
- if(empty($r)){
- $info = $this->auth->getUserInfo($this->openid);
- if(empty($info)){
- $message = "token:{$this->token}| open_id: {$this->openid}";
- tplog($message, 'ERR', '', LOG_PATH.'/wx.log');
- }
- $userInfo = [];
- $userInfo['province'] = $info['province'];
- $userInfo['city'] = $info['city'];
- $userInfo['avatar'] = $info['headimgurl'];
- $userInfo['sex'] = $info['sex'];
- $userInfo['nickname'] = $info['nickname'];
- $sex_map=[0=>2,1=>1,2=>0];
- $userInfo['sex'] = $sex_map[$info['sex']];
- $extra = [];
- $extra['subscribe'] = $info['subscribe'];
- $extra['groupid'] = $info['groupid'];
- $extra['tagid_list'] = $info['tagid_list'];
- $extra['subscribe_time'] = $info['subscribe_time'];
- $userInfo['extra'] = json_encode($extra,JSON_UNESCAPED_UNICODE);
- //wx_open_id
- $r = $mUser->oauthAdd($this->openid,'gzh',$userInfo);
- }
- }
- /**
- * 访问日志,记录用户请求的参数
- */
- function requestLog(){
- $data = array();
- $data['url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
- if(IS_POST){
- $params = $_POST;
- }elseif(IS_GET){
- $params = $_GET;
- }
- if(empty($params)) $params['input'] = file_get_contents("php://input");
- $data['params'] = json_encode($params);
- //$data['cookie'] = json_encode($_COOKIE);
- //$data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
- $data['ip'] = get_client_ip();
- $detail = array();
- $detail['request'] = $_REQUEST;
- $header = [];
- $fields = ['HTTP_USER_ID','HTTP_DEVICE_VID','HTTP_DEVICE_ID','HTTP_PLATFORM','HTTP_VERSION']; //'HTTP_USER_AGENT',
- foreach ($fields as $k => $v){
- if(empty($_SERVER[$v])) continue;
- $header[$v] = $_SERVER[$v];
- }
- /*$this->version = I('server.HTTP_VERSION');
- $this->device_id = I('device_id') ?:I('server.HTTP_DEVICE_ID');
- $this->platform = I('server.HTTP_PLATFORM');
- $user_id = I('user_id') ?: I('server.HTTP_USER_ID');
- $detail['server'] = $_SERVER;*/
- //$detail['header'] = $header;
- //$data['detail'] = json_encode($detail);
- $url = $_SERVER['REQUEST_METHOD']." ".$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']." ".$_SERVER['SERVER_PROTOCOL']."\r\n";
- $request = $url.getallheaders(true);
- $raw_post = '';
- if(IS_POST){
- $raw_post = http_build_query($_POST);
- if(empty($raw_post)){
- $raw_post = file_get_contents("php://input");
- }
- }
- $request .= "\r\n".$raw_post;
- $data['detail'] = $request;
- $data['user_agent'] = $_SERVER['HTTP_USER_AGENT'];
- $data['platform'] = I('server.HTTP_PLATFORM');
- $data['user_id'] = cookie('user_id');//cookie可能取出null,要求字段必须可为null
- $data['create_time'] = date("Y-m-d H:i:s");
- $data['method'] = $_SERVER['REQUEST_METHOD'];
- $data['date_int'] = time();
- try{
- $m = M('LogRequest','',C('log_db'));
- //$m->create($data);
- $logId = $m->add($data);
- C('logId',$logId);
- }catch (\Exception $e){
- tplog($e->getMessage());
- }
- //echo $m->getLastSql();exit;
- }
- /**
- * 记录响应,调用的地方有:\Think\Control->ajaxReturn()
- * @param $id
- * @param $response
- */
- function responseLog($id,$response){
- /* $data = [];
- $data['id'] = $id;
- $data['response'] = $response;
- $m = M('LogRequest','',C('log_db'));
- $m->save($data);*/
- }
- public function lists() {
- //列表过滤器,生成查询Map对象
- $map = $this->_search ();
- if (method_exists ( $this, '_filter' )) {
- $this->_filter ( $map );
- }
- $name=CONTROLLER_NAME;
- //$model = D ($name);
- if (! empty ( $this->m )) {
- $this->_list ( $this->m, $map );
- }
- $this->toview ();
- return;
- //exit('lists erorr');
- // $this->display ();
- //return;
- }
- /**
- * 根据表单生成查询条件 进行列表过滤
- * @param string $name
- * @return array
- */
- protected function _search($name = '') {
- $map=[];
- $autoIndistinct = true;
- $fields = Db::name($this->controllerName)->getFields(); //包含字段类型,注释等
- foreach ( $fields as $column => $definition ) {
- $inputValue = input($column);
- if ( $inputValue !== null && $inputValue != '') {
- if($autoIndistinct && $this->columnType($definition['type']) == 'string'){
- $map[] = [$column, 'like', '%'.$inputValue.'%'];
- }
- }
- }
- //配置select选项和选中值
- $options = $this->cgf->getAllColumnOptions();
- foreach ($options as $column => $option) {
- $this->assign('opt_' . $column, $option);
- $this->assign($column . '_selected', input($column,[]));
- //var_dump($column . '_selected');
- }
- /*dump($fields);
- $fields = Db::name($this->controllerName)->getTableFields();
- dump($fields);exit;
- $map = array ();
- foreach ( $fields as $key => $val ) {
- $inputValue = input($val);
- if ( $inputValue !== null && $inputValue != '') {
- $map[] = [$val, 'like', '%'.$inputValue.'%'];
- }
- }*/
- return $map;
- }
- function columnType($type){
- if( strpos($type,'char') !== false || strpos($type,'text') !== false){
- return 'string';
- }elseif (strpos($type,'int') !== false || strpos($type,'decimal') !== false || strpos($type,'numeric') || strpos($type,'double')){
- return 'int';
- }else{
- return '';
- }
- }
- /**
- * 根据表单生成查询条件
- * 进行列表过滤
- * @param $model 模型对象
- * @param $map 过滤条件
- * @param string $sortBy 排序
- * @param bool $asc 是否正序
- */
- protected function _list($model, $map, $sortBy = '', $asc = false) {
-
- //排序字段 默认为主键名
- if (!empty( $_REQUEST ['_order'] )) {
- $order = $_REQUEST ['_order'];
- } else {
- $order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
- }
- //排序方式默认按照倒序排列
- //接受 sost参数 0 表示倒序 非0都 表示正序
- //$setOrder = setOrder(array(array('viewCount', 'a.view_count'), 'a.id'), $orderBy, $orderType, 'a');
- if (!empty( $_REQUEST ['_sort'] )) {
- $sort = $_REQUEST ['_sort'] ;
- } else {
- $sort = $asc ? 'asc' : 'desc';
- }
- //取得满足条件的记录数
- $pk = $model->getPk();
- $count = $model->where ( $map )->count ();
- if ($count > 0) {
- //import ( "ORG.Util.Page" );
- //创建分页对象
- if (! empty ( $_REQUEST ['listRows'] )) {
- $listRows = $_REQUEST ['listRows'];
- } elseif(!empty($this->listRows)){
- $listRows = $this->listRows;
- } else {
- $listRows = '10';
- }
- if(strtolower(MODULE_NAME) == 'user'){
- unset($_GET['user_id']);
- }
- //========================================== cgf start =========================================
- //1.生成查询字段
- $selectFields = $this->cgf->generateListSelectColumn();
- //var_dump($selectFields);exit;
- //if(strpos($order,'`') === false) $order = "`" . $order . "` ";
- //$r = $model->select();
- //var_dump($r);exit;
- $voList = $model->field($selectFields)->where($map)->order($order.' '. $sort)->paginate(5, false, ['query' => []]);
- //去掉前台不显示的字段,与上面$selectFields功能重复
- /*if(C('ret_format') == 'json' || C('ret_format') == 'jsonp'){
- $tableInfo = new TableInfo('list');
- $tableName = $this->m->getTableName();
- $fields = $tableInfo->generateHomeListFields($tableName);
- foreach ($voList as $k => &$v){
- foreach ($v as $column => $value){
- if(!in_array($column,$fields)) unset($v[$column]);
- }
- }
- }*/
- //2.当前表有关联的表字段时,取关联表信息并合并。实现join功能
- $this->cgf->mergeRelatedTableData($voList);
- //3.调用字段显示处理函数
- $this->cgf->executeColumnCallback($voList);
- //与后台管理的list里调用相关显示函数有重复,如|optionValue
- //if (method_exists ( $this, 'dateToViewModel' )) $this->dateToViewModel ( $voList );
- //========================================== cgf end =========================================
- if (method_exists ( $this, '_join' )) $this->_join ( $voList );
- //将导出功能注入到此处
- if(ACTION_NAME == 'exportExcel'){
- $this->realExportExcel($voList);
- }
- //var_dump($voList);exit;
- //echo $model->getlastsql();exit('x');
- //分页跳转的时候保证查询条件
- foreach ( $map as $key => $val ) {
- if (! is_array ( $val ) && !in_array($key,['_logic'])) {
- //$p->parameter .= "$key=" . urlencode ( $val ) . "&";
- if(strtolower(MODULE_NAME) == 'user' && $key =='user_id'){
- continue;
- }
- //$p->parameter[$key] = urlencode ( $val );
- }
- }
- $page = $voList->render();
- $sortImg = $sort == 'desc' ? "glyphicon-arrow-down" : "glyphicon-arrow-up"; //排序图标 glyphicon glyphicon-arrow-up
- if($sort=='desc'){
- $sortImg = 'glyphicon-arrow-down';
- }elseif($sort='asc'){
- $sortImg = 'glyphicon-arrow-up';
- }else{
- $sortImg = 'glyphicon-sort';
- }
- $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
- $sort = $sort == 'desc' ? 'asc' : 'desc'; //页面上显示的下一次排序方式
- //模板赋值显示
- $this->assign ( 'list', $voList );
- $this->assign ( 'sort', $sort );
- $this->assign ( 'order', $order );
- $this->assign ( 'sortImg', $sortImg );
- $this->assign ( 'sortType', $sortAlt );
- $this->assign ( "page", $page );
- $this->assign ( "totalPages", $p->totalPages );
- $this->assign ( "nowPage", $p->nowPage );
- $this->assign ('totalRows',$count);
- //顶部简易分页
- if($this->enableLitePage){
- $nextIndex = $p->nowPage+1;
- if($nextIndex > $p->totalPages) $nextIndex = $p->totalPages;
- $nextPageUrl = $p->url($nextIndex);
- $prevIndex = $p->nowPage-1;
- if($prevIndex < 1) $prevIndex = 1;
- $prevPageUrl = $p->url($prevIndex);
- $this->assign('nextPageUrl',$nextPageUrl);
- $this->assign('prevPageUrl',$prevPageUrl);
- }
- }else{
- $this->assign ( 'list', [] );
- }
- //cookie( '_currentUrl_', __SELF__ );
- return;
- }
- function assign($key,$value){
- View::assign($key,$value);
- }
- /**
- +----------------------------------------------------------
- * 根据表单生成查询条件
- * 进行列表过滤
- * 返回结果,不输出
- +----------------------------------------------------------
- * @access protected
- +----------------------------------------------------------
- * @param Model $model 数据对象
- * @param HashMap $map 过滤条件
- * @param string $sortBy 排序
- * @param boolean $asc 是否正序
- +----------------------------------------------------------
- * @return void
- +----------------------------------------------------------
- * @throws ThinkExecption
- +----------------------------------------------------------
- */
- protected function _getlist($model, $map, $sortBy = '', $asc = false) {
- //排序字段 默认为主键名
- if (isset ( $_REQUEST ['_order'] )) {
- $order = $_REQUEST ['_order'];
- } else {
- $order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
- }
- //排序方式默认按照倒序排列
- //接受 sost参数 0 表示倒序 非0都 表示正序
- //$setOrder = setOrder(array(array('viewCount', 'a.view_count'), 'a.id'), $orderBy, $orderType, 'a');
- if (isset ( $_REQUEST ['_sort'] )) {
- $sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
- } else {
- $sort = $asc ? 'asc' : 'desc';
- }
- //取得满足条件的记录数
- $pk = $model->getPk();
- $count = $model->where ( $map )->count ( $pk );
- if ($count > 0) {
- import ( "ORG.Util.Page" );
- //创建分页对象
- if (! empty ( $_REQUEST ['listRows'] )) {
- $listRows = $_REQUEST ['listRows'];
- } else {
- $listRows = '';
- }
- $p = new Page ( $count, $listRows );
- //echo C('PAGE_STYLE');exit;
- $p->style = C('PAGE_STYLE');//设置风格
- //分页查询数据
- //var_dump($p->listRows);exit;
- $voList = $model->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select ( );
- //echo $model->getlastsql();
- //分页跳转的时候保证查询条件
- foreach ( $map as $key => $val ) {
- if (! is_array ( $val )) {
- $p->parameter .= "$key=" . urlencode ( $val ) . "&";
- }
- }
- //分页显示
- $page = $p->show ();
- //列表排序显示
- $sortImg = $sort; //排序图标
- $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
- $sort = $sort == 'desc' ? 'asc' : 'desc'; //页面上显示的排序方式
- //模板赋值显示
- return array('list' => $voList ,
- 'sort' => $sort,
- 'order' => $order);
- //$this->assign ( 'sortImg', $sortImg );
- //$this->assign ( 'sortType', $sortAlt );
- //$this->assign ( "page", $page );*
- /*$this->assign ( 'list', $voList );
- $this->assign ( 'sort', $sort );
- $this->assign ( 'order', $order );
- $this->assign ( 'sortImg', $sortImg );
- $this->assign ( 'sortType', $sortAlt );
- $this->assign ( "page", $page );*/
- }
- //cookie( '_currentUrl_', __SELF__ );
- return;
- }
- /**
- +----------------------------------------------------------
- * 连接查询列表显示
- * 进行列表过滤
- +----------------------------------------------------------
- * @access protected
- +----------------------------------------------------------
- * @param Model $model 数据对象
- * @param HashMap $map 过滤条件
- * @param string $sortBy 排序
- * @param boolean $asc 是否正序
- +----------------------------------------------------------
- * @return void
- +----------------------------------------------------------
- * @throws ThinkExecption
- +----------------------------------------------------------
- */
- protected function _listLink($model,$map,$option=array(), $sortBy = '', $asc = false,$sql='') {
- extract($option);
- //$option['join'] = $join; //有查询条件,开启连接查询
- $field || $field = "*";
- $table || $table = $model->getTableName();
- //$table = "{$this->trueTableName} j";
- //$r = $this->table($table)->field($field)->join($join)->where($map)->count();
- //dump($r);
- //return $r;
- //排序字段 默认为主键名
- if (isset ( $_REQUEST ['_order'] )) {
- $order = $_REQUEST ['_order'];
- } else {
- $order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
- }
- //排序方式默认按照倒序排列
- //接受 sost参数 0 表示倒序 非0都 表示正序
- //$setOrder = setOrder(array(array('viewCount', 'a.view_count'), 'a.id'), $orderBy, $orderType, 'a');
- if (isset ( $_REQUEST ['_sort'] )) {
- $sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
- } else {
- $sort = $asc ? 'asc' : 'desc';
- }
- //取得满足条件的记录数
- $pk = $model->getPk();
- if ($option['num'] ){ //限制取几条记录,直接返回指定条记录
- if($sql){
- $voList = $model->query($sql);
- }elseif($option['join']){
- if(strpos($order,'`') === false) $order = "`" . $order . "` ";
- $voList = $model->table($table)->alias('a')->field($field)->join($option['join'])->where($map)->order( $order .' '. $sort)->limit($p->firstRow . ',' . $p->listRows)->select ( );
- }else{
- $voList = $model->where($map)->order( "`" . $order . "` " .' '. $sort)->limit($p->firstRow . ',' . $p->listRows)->select ( );
- }
- return $voList;
- }else{ //分页
- if($sql){
- $count = $count = $model->query(getCountSql($sql));
- $count = $count[0];
- }elseif($option['join']){
- //if(strpos($order,'`') === false) $order = "`" . $order . "` ";
- $count = $model->table($table)->alias('a')->field($field)->join($join)->where($map)->count();
- }else{
- $count = $model->where ( $map )->count ( $pk );
- }
- if($count<0) return;
- import ( "ORG.Util.Page" );
- //创建分页对象
- if (! empty ( $_REQUEST ['listRows'] )) {
- $listRows = $_REQUEST ['listRows'];
- } else {
- $listRows = '';
- }
- $p = new \Think\Page ( $count, $listRows );
- //echo C('PAGE_STYLE');exit;
- //$s = rand(1,25);echo $s;
- $p->style = C('PAGE_STYLE');//设置风格
- //分页查询数据
- if($sql){
- $voList = $model->query($sql);
- }elseif($option['join']){
- if(strpos($order,'`') === false) $order = "`" . $order . "` ";
- $voList = $model->table($table)->alias('a')->field($field)->join($join)->where($map)->order( $order .' '. $sort)->limit($p->firstRow . ',' . $p->listRows)->select ( );
- }else{
- $voList = $model->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select ( );
- }
- //高亮关键字
- if(C('highLightKeyword') && $_REQUEST['keyword']){
- $keyword = $_REQUEST['keyword'];
- foreach($voList as $k => $v){
- $voList[$k]['jtitle'] = hightLightKeyword($v['jtitle'],$keyword);
- $voList[$k]['request'] = hightLightKeyword($v['request'],$keyword);
- $voList[$k]['ctitle'] = hightLightKeyword($v['ctitle'],$keyword);
- }
- }
- //分页跳转的时候保证查询条件
- foreach ( $map as $key => $val ) {
- if (! is_array ( $val )) {
- $p->parameter .= "$key=" . urlencode ( $val ) . "&";
- }
- }
- //分页显示
- $page = $p->show ();
- //列表排序显示
- $sortImg = $sort; //排序图标
- $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
- $sort = $sort == 'desc' ? 'asc' : 'desc'; //页面上显示的排序方式
- //模板赋值显示
- $this->assign ( 'list', $voList );
- $this->assign ( 'sort', $sort );
- $this->assign ( 'order', $order );
- $this->assign ( 'sortImg', $sortImg );
- $this->assign ( 'sortType', $sortAlt );
- $this->assign ( "page", $page );
- $this->assign ( "totalPages", $p->totalPages );
- $this->assign ( "nowPage", $p->nowPage );
- $this->assign ('totalRows',$count);
- }
- //cookie( '_currentUrl_', __SELF__ );
- return;
- }
- public function delete() {
- //删除指定记录
- $name=CONTROLLER_NAME;
- //$model = M ($name);
- if (! empty ( $this->m )) {
- $pk = $this->m->getPk ();
- $id = I($pk);
- if (!empty ( $id )) {
- $condition = array ($pk => array ('in', explode ( ',', $id ) ) );
- $list=$this->m->where ( $condition )->setField ( 'status', 0 );
- if ($list!==false) {
- $this->success ('删除成功!',cookie ( '_currentUrl_' ));
- } else {
- $this->error ('删除失败!');
- }
- } else {
- $this->error ( '非法操作' );
- }
- }
- }
- public function foreverdelete() {
- //删除指定记录
- $name=CONTROLLER_NAME;
- //$model = D ($name);
- if (! empty ( $this->m )) {
- $pk = $this->m->getPk ();
- $id = I($pk);
- if (isset ( $id )) {
- $condition = array ($pk => array ('in', explode ( ',', $id ) ) );
- //用户中心增加用户id条件
- if(MODULE_NAME == 'User') $condition['user_id'] = $this->user_id;
- $r = $this->m->where($condition)->select();
- if(empty($r)) $this->error ( '非法操作' );
- if (false !== $this->m->where ( $condition )->delete ()) {
- if (!empty(I(C('VAR_JSONP_HANDLER'))) || IS_AJAX){
- $method_name = '_after_' . ACTION_NAME;
- if(method_exists($this,$method_name)){
- //if(is_callable([$this,$method_name])){
- $this->$method_name($r);
- /* if ($after->isPublic()) {
- $after->invoke($module);
- }*/
- }
- }
- $this->assign ( 'jumpUrl', cookie ( '_currentUrl_' ) );
- $this->success ('删除成功!',cookie ( '_currentUrl_' ));
- } else {
- $this->error ('删除失败!');
- }
- } else {
- $this->error ( '非法操作' );
- }
- }
- $this->forward ();
- }
- public function clear() {
- //删除指定记录
- $name=CONTROLLER_NAME;
- //$this->m = D ($name);
- if (! empty ( $this->m )) {
- if (false !== $this->m->where ( 'status=1' )->delete ()) {
- $this->assign ( "jumpUrl", $this->getReturnUrl () );
- $this->success ( L ( '_DELETE_SUCCESS_' ) );
- } else {
- $this->error ( L ( '_DELETE_FAIL_' ) );
- }
- }
- $this->forward ();
- }
- public function forbid() {
- $name=CONTROLLER_NAME;
- //$model = D ($name);
- $pk = $this->m->getPk ();
- $id = $_REQUEST [$pk];
- $condition = array ($pk => array ('in', $id ) );
- $list=$this->m->forbid ( $condition );
- if ($list!==false) {
- $this->assign ( "jumpUrl", $this->getReturnUrl () );
- $this->success ( '状态禁用成功' );
- } else {
- $this->error ( '状态禁用失败!' );
- }
- }
- public function checkPass() {
- $name=CONTROLLER_NAME;
- //$model = D ($name);
- $pk = $this->m->getPk ();
- $id = $_GET [$pk];
- $condition = array ($pk => array ('in', $id ) );
- if (false !== $this->m->checkPass( $condition )) {
- $this->assign ( "jumpUrl", $this->getReturnUrl () );
- $this->success ( '状态批准成功!' );
- } else {
- $this->error ( '状态批准失败!' );
- }
- }
- public function recycle() {
- $name=CONTROLLER_NAME;
- //$model = D ($name);
- $pk = $this->m->getPk ();
- $id = $_GET [$pk];
- $condition = array ($pk => array ('in', $id ) );
- if (false !== $this->m->recycle ( $condition )) {
- $this->assign ( "jumpUrl", $this->getReturnUrl () );
- $this->success ( '状态还原成功!' );
- } else {
- $this->error ( '状态还原失败!' );
- }
- }
- public function recycleBin() {
- $map = $this->_search ();
- $map ['status'] = - 1;
- $name=CONTROLLER_NAME;
- //$model = D ($name);
- if (! empty ( $this->m )) {
- $this->_list ( $this->m, $map );
- }
- $this->display ();
- }
- /**
- +----------------------------------------------------------
- * 默认恢复操作
- *
- +----------------------------------------------------------
- * @access public
- +----------------------------------------------------------
- * @return string
- +----------------------------------------------------------
- * @throws FcsException
- +----------------------------------------------------------
- */
- function resume() {
- //恢复指定记录
- $name=CONTROLLER_NAME;
- //$model = D ($name);
- $pk = $this->m->getPk ();
- $id = $_GET [$pk];
- $condition = array ($pk => array ('in', $id ) );
- if (false !== $this->m->resume ( $condition )) {
- $this->assign ( "jumpUrl", $this->getReturnUrl () );
- $this->success ( '状态恢复成功!' );
- } else {
- $this->error ( '状态恢复失败!' );
- }
- }
- function saveSort() {
- $seqNoList = $_POST ['seqNoList'];
- if (! empty ( $seqNoList )) {
- //更新数据对象
- $name=CONTROLLER_NAME;
- //$model = D ($name);
- $col = explode ( ',', $seqNoList );
- //启动事务
- $this->m->startTrans ();
- foreach ( $col as $val ) {
- $val = explode ( ':', $val );
- $this->m->id = $val [0];
- $this->m->sort = $val [1];
- $result = $this->m->save ();
- if (! $result) {
- break;
- }
- }
- //提交事务
- $this->m->commit ();
- if ($result!==false) {
- //采用普通方式跳转刷新页面
- $this->success ( '更新成功' );
- } else {
- $this->error ( $this->m->getError () );
- }
- }
- }
- protected function msgText($nextModel,$nextModelText,$id){
- $app = __APP__;
- $url = __CONTROLLER__;
- return "发布成功! <a href='$app/$nextModel/add'>发布{$nextModelText}信息</a> <a href='$url/edit/id/$id'>返回修改信息</a> <a href='$url/'>返回列表</a>";
- }
- public function show($content="",$charset='',$contentType='',$prefix=''){
- $id = I('id');
- $vo = $this->m->getById ( $id );
- if (method_exists ( $this, '_show' )) {
- $this->_show ( $vo );
- }
- $this->vo = $vo;
- $this->toview();
- }
- function upload($stype='file'){
- $uploadInfo = $this->commonUpload($stype);
- $this->upload = $uploadInfo;
- $this->toview();
- }
- /**
- * 通用上传,支持多张上传
- * @param string $moduleDir 模块目录名
- * @return array 上传结果,一张图片,一个array,key为上传控件的名字
- */
- protected function commonUpload($stype='file'){
- $type = I('type','file');
- if(C('UPLOAD_STRORAGE') == 'oss'){
- //传到aliyun
- C('UPLOAD_SITEIMG_OSS.savePath',$stype.'/');
- $setting=C('UPLOAD_SITEIMG_OSS');
- $upload = new \Think\Upload($setting);
- $info = $upload->upload();
- }else{
- $config = array(
- 'subName' => array('date','Ymd'),
- );
- //$modelName = "file/";
- $rootPath = C('SAVE_PATH');
- $upload = new \Think\Upload($config);
- $upload->maxSize = 31457280 ;// 设置附件上传大小
- $upload->exts = array('jpg', 'gif', 'png', 'jpeg','doc','docx','rar','zip','tar','tar.gz','tgz','7z','txt','flv','mp4','mov');// 设置附件上传类型
- $upload->rootPath = $rootPath; // 设置附件上传根目录
- $upload->savePath = $stype.'/'; // 设置附件上传(子)目录
- //传到本地
- $info = $upload->upload();
- }
- if(!$info) {
- $this->error($upload->getError());
- }else{
- $ret = [];
- $f = M('image');
- $multiple = I('multiple');
- //从数组中取出重复的元素
- if(!$multiple){
- $file_names = array_column($info,'key');
- $unique_arr = array_unique ( $file_names );
- //有多个文件的file对象的名称
- $muti_file_key = array_diff_assoc ( $file_names, $unique_arr );
- }
- //var_dump($repeat_arr);
- //exit;
- $goods_id = 1;
- foreach ($info as $k => $fileInfo){
- /* $cropInfo = I('avatar_data');
- $cropInfo = json_decode($cropInfo,1);
- foreach ($cropInfo as &$v){
- $v = round($v);
- }*/
- $filePath = $fileInfo['savepath'].$fileInfo['savename'];
- /* $data = [];
- if( $this->crop($fileInfo,$cropInfo['width'],$cropInfo['height'],$cropInfo['x'],$cropInfo['y'],$cropInfo['rotate'])){
- $filePath .= "_{$cropInfo['width']}x{$cropInfo['height']}.{$fileInfo['ext']}";
- }
- $data['url'] = URL_IMG.'/'.$filePath;*/
- //$data = $info['avatar_file'];
- $data = [];
- $data['res_id'] = $goods_id;
- $data['type'] = 20;
- //$data['user_id'] = $this->user_id;
- $data['hd_url'] = $filePath;
- $data['nhd_url'] = $filePath;
- $data['create_t'] = time();
- /*$data['title'] = I('title');
- $data['content'] = I('content');
- $data['type'] = $type;
- $data['input_name'] = trim(trim($fileInfo['key'],"'"),'_');*/
- $id = $f->add($data);
- if( $multiple
- || !empty($muti_file_key) && in_array($data['input_name'],$muti_file_key)){ //多文件上传,返回数组
- $ret[$data['input_name']][] = ["id" => $id,'path' => $filePath,'url' => img($filePath,'big'), ];
- }else{
- $ret[$data['input_name']] = ["id" => $id,'path' => $filePath,'url' => img($filePath,'big'), ];
- }
- }
- return $ret;
- //$this->success();
- //var_dump($data);exit('x');
- //$this->toview($data);
- }
- }
- function responseFormat(){
- $format = "";
- if(IS_AJAX || C('RETRUN_FORMAT') == "android_json" || I('ret_format') == 'json' || $_SERVER['HTTP_ACCEPT'] == 'application/json'){ //json,app: code,msg,data
- return "json";
- }elseif (!empty(I(C('VAR_JSONP_HANDLER')))){ //jsonp
- return "jsonp";
- }elseif(isMobile()){
- return "wap";
- }else{
- return "web";
- }
- }
- /**
- * @name 根据请求方式,显示对应的格式到页面
- * @param 数据 array $data
- * @param 格式类型 int $type
- * @return member
- */
- public function toview($data = "", $tpl=""){
- if(!APP_DEBUG) {
- //action结束,缓存viewData
- \Think\Hook::listen('setViewData', $this); // //tag('setViewData',$this);
- }
- if(empty($data)) $data = $this->get();
- //var_dump($data);//exit;
- //if(!empty($tpl)) $this->display($tpl);
- //var_dump($_SERVER);exit;
- if(IS_AJAX || C('RETRUN_FORMAT') == "android_json" || I('ret_format') == 'json' || $_SERVER['HTTP_ACCEPT'] == 'application/json'){ //json,app: code,msg,data
- if(empty($data)) $data = (object)$data;
- $this->success($data,"",1);
- }elseif (!empty(I(C('VAR_JSONP_HANDLER')))){ //jsonp
- $this->ajaxReturn(array("code" =>1, "msg" => "","data" => $data),'JSONP');
- }elseif(isMobile()){ //wap
- empty($tpl) && $tpl = RAW_ACTION_NAME;
- $wapTpl = "wap_".$tpl;
- $templateFile = $this->view->parseTemplate($wapTpl);
- //var_dump($templateFile);exit;
- //if()
- $www_host = parse_url(URL_WWW)['host'];
- if($_SERVER['HTTP_HOST'] == $www_host){
- redirect(URL_M.__SELF__);
- }
- /*
- elseif ($_SERVER['HTTP_HOST'] == $news_host){
- //新闻则跳转到wap的新闻模块
- redirect(URL_M.'news/'.__SELF__);
- }*/
- //var_dump(SCHEME.$_SERVER['HTTP_HOST'] ,URL_M, SCHEME.$_SERVER['HTTP_HOST'] , URL_USER,URL_M.__SELF__);exit;
- //if(SCHEME.$_SERVER['HTTP_HOST'] !=URL_M && SCHEME.$_SERVER['HTTP_HOST'] != URL_USER) redirect(URL_M.__SELF__);
- if(is_file($templateFile)) $this->display($wapTpl);
- else $this->display($tpl);
- }else{ //web
- $this->display($tpl);
- }
- /* if(!empty(I(C('VAR_JSONP_HANDLER')))){ //ajax返回,默认json格式
- $this->ajaxReturn($data,$type);
- }elseif(IS_AJAX){ //jsonp格式
- //var_dump($data);exit;
- $this->success($data,"成功!",1);
- }elseif(C('RETRUN_FORMAT') == "android_json" || I('ret_format') == 'json'){
- $this->ajaxReturn($data); //android格式数据必须有个[]
- }elseif(isMobile()){
- $this->display("wap".__ACTION__);
- }else{ //html
- $this->display($tpl);
- } */
- }
- /*function success($data,$msg = 'success',$code = 1,$jumpUrl = ''){
- $this->dispatchJump2($data,$msg,$code,$jumpUrl);
- }*/
- /**
- * @param string $firstParam
- * @param string $secondParam
- * @param string $jumpUrl
- * @param bool $ajax
- */
- function success($firstParam='成功',$secondParam='',$jumpUrl='',$ajax=false){
- //第一个参数是数组或对象,说明是app返回,则第二个参数是msg
- if(is_array($firstParam) || is_object($firstParam)){ //api返回
- $data = $firstParam;
- $msg = $secondParam;
- }else{ //pc返回,第一个参数做msg,第二个参数做跳转url
- $data = '';
- $msg = $firstParam;
- $jumpUrl = $secondParam;
- }
- $this->dispatchJump2($data,$msg,1,$jumpUrl,$ajax);
- }
- function error($message='',$jumpUrl='',$ajax=false,$status=0){
- $ret_format = $this->responseFormat();
- if(in_array($ret_format,['json','jsonp']) ){
- $data = [];
- $data['code'] = $status;
- $data['msg'] = $message;
- $data['data'] = (object)array();
- if($jumpUrl) $data['jumpUrl'] = $jumpUrl;
- $this->ajaxReturn($data,$ret_format);
- }
- /*if("json" == $this->responseFormat() || "jsonp" == $this->responseFormat()) $ajax = 1;
- if($ajax || IS_AJAX) {// AJAX提交
- $data = is_array($ajax)?$ajax:array();
- $data['code'] = $status;
- $data['msg'] = $message;
- $data['data'] = (object)array();
- $type = C('ret_format');
- if($type != 'json' && $type != 'jsonp') $type = 'json';
- $this->ajaxReturn($data,$type);
- }*/
- if(is_int($ajax)) $this->assign('waitSecond',$ajax);
- if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl);
- // 提示标题
- $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));
- //如果设置了关闭窗口,则提示完毕后自动关闭窗口
- if($this->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();');
- $this->assign('status',$status); // 状态
- //保证输出不受静态缓存影响
- C('HTML_CACHE_ON',false);
- if($status) { //发送成功信息
- $this->assign('message',$message);// 提示信息
- // 成功操作后默认停留1秒
- if(!isset($this->waitSecond)) $this->assign('waitSecond','1');
- // 默认操作成功自动返回操作前页面
- if(!isset($this->jumpUrl)) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]);
- if(isMobile()){
- $this->display(C('TMPL_ACTION_SUCCESS_WAP'));
- }else{
- $this->display(C('TMPL_ACTION_SUCCESS'));
- }
- }else{
- $this->assign('error',$message);// 提示信息
- //发生错误时候默认停留3秒
- if(!isset($this->waitSecond)) $this->assign('waitSecond','3');
- // 默认发生错误的话自动返回上页
- if(!isset($this->jumpUrl)) $this->assign('jumpUrl',"javascript:history.back(-1);");
- if(isMobile()){
- $this->display(C('TMPL_ACTION_ERROR_WAP'));
- }else{
- $this->display(C('TMPL_ACTION_ERROR'));
- }
- // 中止执行 避免出错后继续执行
- exit ;
- }
- }
- // $this->dispatchJump2($message,1,$jumpUrl,$ajax);
- function dispatchJump2($data, $msg='', $status = 1, $jumpUrl='', $ajax=false){
- if (!empty(I(C('VAR_JSONP_HANDLER')))){ //jsonp
- if(empty($data)) $data = (object)[];
- $this->ajaxReturn(array("code" =>$status, "msg" => $msg,"data" => $data),'JSONP');
- }
- if(IS_AJAX) {// AJAX和ret_format=json
- if(empty($data)) $data = (object)[];
- $ret = [];
- $ret['code'] = $status;
- $ret['msg'] = $msg;
- $ret['data'] = $data;
- $ret['jumpUrl'] = $jumpUrl;
- $this->ajaxReturn($ret);
- }
- if(is_int($ajax)) $this->assign('waitSecond',$ajax);
- if(!empty($jumpUrl)) $this->assign('jumpUrl',$jumpUrl);
- // 提示标题
- $this->assign('msgTitle',$status? L('_OPERATION_SUCCESS_') : L('_OPERATION_FAIL_'));
- //如果设置了关闭窗口,则提示完毕后自动关闭窗口
- if($this->get('closeWin')) $this->assign('jumpUrl','javascript:window.close();');
- $this->assign('status',$status); // 状态
- //保证输出不受静态缓存影响
- C('HTML_CACHE_ON',false);
- if($status) { //发送成功信息
- $this->assign('message',$msg);// 提示信息
- if($this->jumpMenu){
- $this->jumpMenu = str_replace('{$info_id}', C('info_id'),$this->jumpMenu);
- $this->assign('jumpMenu',$this->jumpMenu);
- }
- // 成功操作后默认停留1秒
- if(!isset($this->waitSecond)) $this->assign('waitSecond','1');
- // 默认操作成功自动返回操作前页面
- if(!isset($this->jumpUrl)) $this->assign("jumpUrl",$_SERVER["HTTP_REFERER"]);
- if(isMobile()){
- $this->display(C('TMPL_ACTION_SUCCESS_WAP'));
- }else{
- $this->display(C('TMPL_ACTION_SUCCESS'));
- }
- }else{
- $this->assign('error',$msg);// 提示信息
- //发生错误时候默认停留3秒
- if(!isset($this->waitSecond)) $this->assign('waitSecond','3');
- // 默认发生错误的话自动返回上页
- if(!isset($this->jumpUrl)) $this->assign('jumpUrl',"javascript:history.back(-1);");
- if(isMobile()){
- $this->display(C('TMPL_ACTION_ERROR_WAP'));
- }else{
- $this->display(C('TMPL_ACTION_ERROR'));
- }
- // 中止执行 避免出错后继续执行
- exit ;
- }
- }
- /**
- * @param string $firstParam data | msg
- * @param string $secondParam msg | jumpUrl
- * @param string $jumpUrl
- * @param bool $ajax
- */
- //function response($firstParam='',$secondParam='',$jumpUrl=''){
- function error_new($msg='',$jumpUrl='',$ajax=false){
- /* //第一个参数是数组或对象,说明是app返回,则第二个参数是msg
- if(is_array($firstParam) || is_object($firstParam)){ //api返回
- $data = $firstParam;
- $msg = $secondParam;
- }else{ //pc返回,第一个参数做msg,第二个参数做跳转url
- $data = '';
- $msg = $firstParam;
- $jumpUrl = $secondParam;
- }*/
- $status = 0;
- $ret_format = $this->responseFormat();
- if(in_array($ret_format,['josn','jsonp']) ){
- $data = [];
- $data['code'] = $status;
- $data['msg'] = $msg;
- $data['data'] = (object)array();
- $this->ajaxReturn($data,$ret_format);
- }
- //保证输出不受静态缓存影响
- C('HTML_CACHE_ON',false);
- $this->assign('error',$msg);// 提示信息
- //发生错误时候默认停留3秒
- if(!isset($this->waitSecond)) $this->assign('waitSecond','3');
- // 默认发生错误的话自动返回上页
- if(!isset($this->jumpUrl)) $this->assign('jumpUrl',"javascript:history.back(-1);");
- if(isMobile()){
- $this->display(C('TMPL_ACTION_ERROR_WAP'));
- }else{
- $this->display(C('TMPL_ACTION_ERROR'));
- }
- // 中止执行 避免出错后继续执行
- exit ;
- }
- //用户信息
- function userinfo(){
- if(empty($this->user_id)) return;
- $u = M('User');
- $userinfo = $u->find($this->user_id);
- unset($userinfo['id']);
- unset($userinfo['pwd']);
- unset($userinfo['open_id']);
- unset($userinfo['bind']);
- $userinfo = json_encode($userinfo);
- $this->userinfo = $userinfo;
- }
- //设置标题
- function setTitle($title){
- $this->pageTitle = empty($title) ? C('SITE_TITLE') : $title.'_'.C('SITE_TITLE');
- //$title && $title = $title."_";
- //$this->pageTitle = $title.C('SITE_TITLE');
- }
- //验证码
- public function createVerifyCode(){
- $Verify = new \Think\Verify();
- $Verify->entry();
- }
- function setParam($key,$value){
- $_REQUEST[$key] = $_POST[$key] = $_GET[$key] = $value;
- }
- }
|