Commit 04620bf2 authored by clone's avatar clone

Merge branch 'chat_0818' into test

# Conflicts: # application/model/Agents.php
parents e74505b7 8657770f
...@@ -93,14 +93,14 @@ class Shop extends Basic ...@@ -93,14 +93,14 @@ class Shop extends Basic
//面积 room_area最小面积 room_area2最大面积 参考老版本 //面积 room_area最小面积 room_area2最大面积 参考老版本
//面积 room_area最小面积 room_area2最大面积 参考老版本 //面积 room_area最小面积 room_area2最大面积 参考老版本
if (isset($params['area_start']) && isset($params['area_end'])) { if (isset($params['area_start']) && isset($params['area_end'])) {
$conditions['a.room_area'] = array( 'between', array( $params['area_start'], $params['area_end'] ) ); $conditions['a.room_area'] = array( 'between', array( $params['area_start'], $params['area_end'] ) );
//街铺只有一个room_area //街铺只有一个room_area
if($params['shangpu_type'] == 0){ if ($params['shangpu_type'] == 0) {
$conditions['a.room_area2'] = array( 'between', array( $params['area_start'], $params['area_end'] ) ); $conditions['a.room_area2'] = array( 'between', array( $params['area_start'], $params['area_end'] ) );
} }
} else if (isset($params['area_start']) && !isset($params['area_end'])) { //100米以上不用传结束面积 } else if (isset($params['area_start']) && !isset($params['area_end'])) { //100米以上不用传结束面积
$conditions['a.room_area'] = array( 'egt', $params['area_start'] ); $conditions['a.room_area'] = array( 'egt', $params['area_start'] );
if($params['shangpu_type'] == 0){ if ($params['shangpu_type'] == 0) {
$conditions['a.room_area2'] = array( 'egt', $params['area_start'] ); $conditions['a.room_area2'] = array( 'egt', $params['area_start'] );
} }
} }
...@@ -178,7 +178,7 @@ class Shop extends Basic ...@@ -178,7 +178,7 @@ class Shop extends Basic
$result["api_path"] = IMG_PATH; $result["api_path"] = IMG_PATH;
$param["house_id"] = $params['id']; $param["house_id"] = $params['id'];
//todo 这里的是否要更改成b端后台上传的类型 //todo 这里的是否要更改成b端后台上传的类型
$param["imgtype"] = 2; $param["imgtype"] = 2;
$result["images"] = $this->dbImg->getHouseImages($param, 15); $result["images"] = $this->dbImg->getHouseImages($param, 15);
$param["imgtype"] = 4;//图片类型:1效果图,2实景图,3样板图,4户型图,5交通图 $param["imgtype"] = 4;//图片类型:1效果图,2实景图,3样板图,4户型图,5交通图
$result["plan_images"] = $this->dbImg->getHouseImages($param, 4); $result["plan_images"] = $this->dbImg->getHouseImages($param, 4);
......
<?php
use app\api_broker\extend\Basic;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/24
* Time : 14:24
* Intro:
*/
class FollowUp extends Basic{
public function __construct($request = null)
{
parent::__construct($request);
}
/**
* 报备
*/
public function report(){
$params = $this->params;
$params = array(
"user_id" => 1,
"shop_ids"=> "1,2,3",
""
);
$this->response("200","request success",[]);
}
}
\ No newline at end of file
<?php
namespace app\api_broker\controller;
class Index
{
public function index()
{
return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:)</h1><p> ThinkPHP V5<br/><span style="font-size:30px">十年磨一剑 - 为API开发设计的高性能框架</span></p><span style="font-size:22px;">[ V5.0 版本由 <a href="http://www.qiniu.com" target="qiniu">七牛云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="http://tajs.qq.com/stats?sId=9347272" charset="UTF-8"></script><script type="text/javascript" src="http://ad.topthink.com/Public/static/client.js"></script><thinkad id="ad_bd568ce7058a1091"></thinkad>';
}
}
<?php
namespace app\api_broker\extend;
/**
* Created by PhpStorm.
* User: zw
* Date: 2018/1/24
* Time: 9:35
* 基类
*/
use app\model\Users;
use think\Controller;
use think\Request;
use think\Response;
use Qiniu;
class Basic extends Controller
{
/**
* 访问请求对象
* @var Request
*/
public $request;
public $params;
protected $authToken;
/**
* @var int userId
*/
protected $userId;
protected $userNick;
protected $phone;
protected $timeStamp_;
protected $filterVerify = array(
);
/**
* 基础接口SDK
* @param Request|null $request
*/
public function __construct(Request $request = null)
{
// CORS 跨域 Options 检测响应
$this->corsOptionsHandler();
// 输入对象
$this->request = is_null($request) ? Request::instance() : $request;
if (strtoupper($this->request->method()) === "GET") {
$this->params = $this->request->param();
} elseif (strtoupper($this->request->method()) === "POST") {
$this->params = $this->request->param() != null ? $this->request->param() : null;
}
/* if (isset($this->params['AuthToken']) && $this->params['AuthToken'] != 'null' && !empty($this->params['AuthToken'])) {
$jwt = new \Firebase\JWT\JWT();
$this->authToken = $this->params['AuthToken'];
$result = $jwt->decode($this->authToken, config('jwt_key'), array( 'HS256' )); //解码token
$this->userId = $result->data->id;
$this->phone = $result->data->phone;
$this->userNick = $result->data->userNick;
$this->timeStamp_ = $result->timeStamp_;
}
$requestPath = $this->request->routeInfo()["rule"][0] . "/" . $this->request->routeInfo()["rule"][1];
//过滤掉不需要验证token的接口
if (!in_array(trim($requestPath), $this->filterVerify)) {
$this->tokenVerify();
}*/
}
/**
* token 验证
*/
public function tokenVerify()
{
if (!isset($this->params['AuthToken'])) {
echo json_encode(array( "code" => "300", "msg" => "AuthToken不能为空!", "data" => [], "type" => "json" ));
exit;
}
$this->verifyUserInfo();
$this->verifyTime();
}
public function verifyTime()
{
//authToken有效期为30天
if ((time() - $this->timeStamp_) > 2592000) {
echo json_encode(array( "code" => "300", "msg" => "AuthToken失效,请重新登录!", "data" => [], "type" => "json" ));
exit;
}
}
public function verifyUserInfo()
{
$userModel = new Users();
$userArr = $userModel->selectUser($this->userId);
if (count($userArr) > 0 && ($userArr["id"] != $this->userId || $userArr["user_phone"] != $this->phone)) {
echo json_encode(array( "code" => "300", "msg" => "用户验证失败,重新登录!", "data" => [], "type" => "json" ));
exit;
}
return true;
}
/**
* 输出返回数据
* @param string $msg 提示消息内容
* @param string $code 业务状态码
* @param mixed $data 要返回的数据
* @param string $type 返回类型 JSON XML
* @return Response
*/
public function response($code = 'SUCCESS', $msg, $data = [], $type = 'json')
{
$result = [ 'code' => $code, 'msg' => $msg, 'data' => $data, 'type' => strtolower($type) ];
return Response::create($result, $type);
}
/**
* 一维数据数组生成数据树
* @param array $list 数据列表
* @param string $id 父ID Key
* @param string $pid ID Key
* @param string $son 定义子数据Key
* @return array
*/
public static function arr2tree($list, $id = 'id', $pid = 'pid', $son = 'sub')
{
list($tree, $map) = [ [], [] ];
foreach ($list as $item) {
$map[$item[$id]] = $item;
}
foreach ($list as $item) {
if (isset($item[$pid]) && isset($map[$item[$pid]])) {
$map[$item[$pid]][$son][] = &$map[$item[$id]];
} else {
$tree[] = &$map[$item[$id]];
}
}
unset($map);
return $tree;
}
/**
* 一维数据数组生成数据树
* @param array $list 数据列表
* @param string $id ID Key
* @param string $pid 父ID Key
* @param string $path
* @param string $ppath
* @return array
*/
public static function arr2table(array $list, $id = 'id', $pid = 'pid', $path = 'path', $ppath = '')
{
$tree = [];
foreach (self::arr2tree($list, $id, $pid) as $attr) {
$attr[$path] = "{$ppath}-{$attr[$id]}";
$attr['sub'] = isset($attr['sub']) ? $attr['sub'] : [];
$attr['spl'] = str_repeat("&nbsp;&nbsp;&nbsp;├&nbsp;&nbsp;", substr_count($ppath, '-'));
$sub = $attr['sub'];
unset($attr['sub']);
$tree[] = $attr;
if (!empty($sub)) {
$tree = array_merge($tree, (array)self::arr2table($sub, $id, $pid, $path, $attr[$path]));
}
}
return $tree;
}
/**
* 获取数据树子ID
* @param array $list 数据列表
* @param int $id 起始ID
* @param string $key 子Key
* @param string $pkey 父Key
* @return array
*/
public static function getArrSubIds($list, $id = 0, $key = 'id', $pkey = 'pid')
{
$ids = [ intval($id) ];
foreach ($list as $vo) {
if (intval($vo[$pkey]) > 0 && intval($vo[$pkey]) === intval($id)) {
$ids = array_merge($ids, self::getArrSubIds($list, intval($vo[$key]), $key, $pkey));
}
}
return $ids;
}
/**
* Cors Options 授权处理
*/
public static function corsOptionsHandler()
{
if (request()->isOptions()) {
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
header('Access-Control-Allow-Credentials:true');
header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
header('Access-Control-Max-Age:1728000');
header('Content-Type:text/plain charset=UTF-8');
header('Content-Length: 0', true);
header('status: 204');
header('HTTP/1.0 204 No Content');
exit;
}
}
/**
* Cors Request Header信息
* @return array
*/
public static function corsRequestHander()
{
return [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Credentials' => true,
'Access-Control-Allow-Methods' => 'GET,POST,OPTIONS',
'Access-Defined-X-Support' => 'service@cuci.cc',
'Access-Defined-X-Servers' => 'Guangzhou Cuci Technology Co. Ltd',
];
}
}
<?php
//配置文件
return [
];
\ No newline at end of file
<?php
namespace app\chat\consts;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/9
* Time : 13:27
* Intro:
*/
class ConfigConst
{
const CLIENT_ID = "YXA6hqlTwLr0EeeNFrlhHiI-Xg";
const CLIENT_SECRET = "YXA6BkraoPZqZYJoLce4sCyRebXMC48";
const API_PATH = "https://a1.easemob.com/";
const ORG_NAME = "1157170531115254";
const APP_NAME = "tonglianjituan";
}
\ No newline at end of file
<?php
namespace app\chat\consts;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/9
* Time : 16:54
* Intro:
*/
class ErrorCodeConst
{
//聊天
const ERROR_CODE_PARAM_NOT_EXIST = 110001;
const ERROR_CODE_TARGET_TYPE_ERROR = 110002;
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
<?php
namespace app\chat\extend;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/8
* Time : 16:54
* Intro:
*/
use app\chat\consts\ConfigConst;
use app\chat\utils\CurlUtil;
use http\Exception;
use think\Cache;
use think\Controller;
use Think\Log;
use think\Request;
use think\Response;
class Basic extends Controller
{
/**
* 访问请求对象
* @var Request
*/
public $request;
/**
* 请求参数
* @var mixed|null
*/
public $params;
/**
* app通讯接口授权token
* @var
*/
public $accessToken;
/**
* 基础接口SDK
* @param Request|null $request
*/
public function __construct(Request $request = null)
{
// CORS 跨域 Options 检测响应
$this->corsOptionsHandler();
// 输入对象
$this->request = is_null($request) ? Request::instance() : $request;
if (strtoupper($this->request->method()) === "GET") {
$this->params = $this->request->param();
} elseif (strtoupper($this->request->method()) === "POST") {
$this->params = $this->request->param() != null ? $this->request->param() : null;
}
$this->accessToken = Cache::get('access_token');
$expires_in = Cache::get('expires_in');
$application = Cache::get('application');
$accredit_time = Cache::get('accredit_time');
if (!$this->accessToken || !$expires_in || !$application || !$accredit_time || (time() - $accredit_time) > $expires_in) {
//todo 这里加个验证 多少时间内不能重复请求
$this->getToken();
if (Cache::get('access_token')) {
$this->accessToken = Cache::get('access_token');
} else {
echo json_encode(array( "code" => "300", "msg" => "accessToken拉取失败,请稍后再试!", "data" => [], "type" => "json" ));
exit;
}
}
}
/**
* 输出返回数据
* @param string $msg 提示消息内容
* @param string $code 业务状态码
* @param mixed $data 要返回的数据
* @param string $type 返回类型 JSON XML
* @return Response
*/
public function response($code = 'SUCCESS', $msg, $data = [], $type = 'json')
{
$result = [ 'code' => $code, 'msg' => $msg, 'data' => $data, 'type' => strtolower($type) ];
return Response::create($result, $type);
}
public function getApiPath()
{
return ConfigConst::API_PATH . ConfigConst::ORG_NAME . "/" . ConfigConst::APP_NAME;
}
/**
* Cors Options 授权处理
*/
public static function corsOptionsHandler()
{
if (request()->isOptions()) {
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Headers:Accept,Referer,Host,Keep-Alive,User-Agent,X-Requested-With,Cache-Control,Content-Type,Cookie,token');
header('Access-Control-Allow-Credentials:true');
header('Access-Control-Allow-Methods:GET,POST,OPTIONS');
header('Access-Control-Max-Age:1728000');
header('Content-Type:text/plain charset=UTF-8');
header('Content-Length: 0', true);
header('status: 204');
header('HTTP/1.0 204 No Content');
exit;
}
}
/**
* 获取调取接口的access_token
*/
public function getToken()
{
$url = "/token";
$data = [
"grant_type" => "client_credentials",
"client_id" => ConfigConst::CLIENT_ID,
"client_secret" => ConfigConst::CLIENT_SECRET
];
$curl = new CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$apiUrl = $this->getApiPath() . $url;
try {
$response = $curl->post($apiUrl, json_encode($data));
$response = json_decode($response,true);
if ($response) {
Cache::set('access_token', $response["access_token"]);
Cache::set('expires_in', $response["expires_in"]);
Cache::set('application', $response["application"]);
Cache::set('accredit_time', time());
}
} catch (Exception $e) {
Log::record('class:Basic,function:getToken get token ,Exception :' . $e, "error");
}
Log::record('class:Basic,function:getToken get token' , "info");
}
}
This diff is collapsed.
<?php
namespace app\chat\service;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/23
* Time : 14:15
* Intro:
*/
class GroupService
{
//todo
}
\ No newline at end of file
<?php
namespace app\chat\utils;
/**
* Parses the response from a Curl request into an object containing
* the response body and an associative array of headers
*
* @author qianfunian <qianfunian@51jk.com>
**/
class CurlResponse {
/**
* The body of the response without the headers block
*
* @var string
**/
public $body = '';
/**
* An associative array containing the response's headers
*
* @var array
**/
public $headers = array();
/**
* Accepts the result of a curl request as a string
*
* <code>
* $response = new CurlResponse(curl_exec($curl_handle));
* echo $response->body;
* echo $response->headers['Status'];
* </code>
*
* @param string $response
**/
function __construct($response) {
# Headers regex
$pattern = '#HTTP/\d\.\d.*?$.*?\r\n\r\n#ims';
# Extract headers from response
preg_match_all($pattern, $response, $matches);
$headers_string = array_pop($matches[0]);
$headers = explode("\r\n", str_replace("\r\n\r\n", '', $headers_string));
# Remove headers from the response body
$this->body = str_replace($headers_string, '', $response);
# Extract the version and status from the first header
$version_and_status = array_shift($headers);
preg_match('#HTTP/(\d\.\d)\s(\d\d\d)\s(.*)#', $version_and_status, $matches);
$this->headers['Http-Version'] = $matches[1];
$this->headers['Status-Code'] = $matches[2];
$this->headers['Status'] = $matches[2].' '.$matches[3];
# Convert headers into an associative array
foreach ($headers as $header) {
preg_match('#(.*?)\:\s(.*)#', $header, $matches);
$this->headers[$matches[1]] = $matches[2];
}
}
/**
* Returns the response body
*
* <code>
* $curl = new Curl;
* $response = $curl->get('google.com');
* echo $response; # => echo $response->body;
* </code>
*
* @return string
**/
function __toString() {
return $this->body;
}
}
\ No newline at end of file
<?php
namespace app\chat\utils;
/**
* A basic CURL wrapper
*
* @author qianfunian <qianfunian@51jk.com>
**/
class CurlUtil {
/**
* The file to read and write cookies to for requests
*
* @var string
**/
public $cookie_file;
/**
* Determines whether or not requests should follow redirects
*
* @var boolean
**/
public $follow_redirects = true;
/**
* An associative array of headers to send along with requests
*
* @var array
**/
public $headers = array();
/**
* An associative array of CURLOPT options to send along with requests
*
* @var array
**/
public $options = array();
/**
* The referer header to send along with requests
*
* @var string
**/
public $referer;
/**
* The user agent to send along with requests
*
* @var string
**/
public $user_agent;
/**
* Stores an error string for the last request if one occurred
*
* @var string
* @access protected
**/
protected $error = '';
/**
* Stores resource handle for the current CURL request
*
* @var resource
* @access protected
**/
protected $request;
/**
* Initializes a Curl object
*
* Sets the $cookie_file to "curl_cookie.txt" in the current directory
* Also sets the $user_agent to $_SERVER['HTTP_USER_AGENT'] if it exists, 'Curl/PHP '.PHP_VERSION.' (http://github.com/shuber/curl)' otherwise
**/
function __construct() {
$this->cookie_file = dirname(__FILE__).DIRECTORY_SEPARATOR.'curl_cookie.txt';
$this->user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'Curl/PHP ' . PHP_VERSION;
}
/**
* Makes an HTTP DELETE request to the specified $url with an optional array or string of $vars
*
* Returns a CurlResponse object if the request was successful, false otherwise
*
* @param string $url
* @param array|string $vars
* @return CurlResponse object
**/
function delete($url, $vars = array()) {
return $this->request('DELETE', $url, $vars);
}
/**
* Returns the error string of the current request if one occurred
*
* @return string
**/
function error() {
return $this->error;
}
/**
* Makes an HTTP GET request to the specified $url with an optional array or string of $vars
*
* Returns a CurlResponse object if the request was successful, false otherwise
*
* @param string $url
* @param array|string $vars
* @return CurlResponse
**/
function get($url, $vars = array()) {
$vars['platform_type'] = 130;
if (!empty($vars)) {
$url .= (stripos($url, '?') !== false) ? '&' : '?';
$url .= (is_string($vars)) ? $vars : http_build_query($vars, '', '&');
}
$file = new LogsService(LOGS_PATH.'/curl_get/' . date('Y-m-d'));
$file->info($url);
return $this->request('GET', $url);
}
/**
* Makes an HTTP HEAD request to the specified $url with an optional array or string of $vars
*
* Returns a CurlResponse object if the request was successful, false otherwise
*
* @param string $url
* @param array|string $vars
* @return CurlResponse
**/
function head($url, $vars = array()) {
return $this->request('HEAD', $url, $vars);
}
/**
* Makes an HTTP POST request to the specified $url with an optional array or string of $vars
*
* @param string $url
* @param array|string $vars
* @return CurlResponse|boolean
**/
function post($url, $vars = array()) {
if (!is_string($vars)) {
$vars['platform_type'] = 130;
}
return $this->request('POST', $url, $vars);
}
/**
* Makes an HTTP PUT request to the specified $url with an optional array or string of $vars
*
* Returns a CurlResponse object if the request was successful, false otherwise
*
* @param string $url
* @param array|string $vars
* @return CurlResponse|boolean
**/
function put($url, $vars = array()) {
return $this->request('PUT', $url, $vars);
}
/**
* Makes an HTTP request of the specified $method to a $url with an optional array or string of $vars
*
* Returns a CurlResponse object if the request was successful, false otherwise
*
* @param string $method
* @param string $url
* @param array|string $vars
* @return CurlResponse|boolean
**/
function request($method, $url, $vars = array()) {
$this->error = '';
$this->request = curl_init();
if (is_array($vars)) $vars = http_build_query($vars, '', '&');
$this->set_request_method($method);
$this->set_request_options($url, $vars);
$this->set_request_headers();
$response = curl_exec($this->request);
if ($response) {
$response = new CurlResponse($response);
} else {
$this->error = curl_errno($this->request).' - '.curl_error($this->request);
}
curl_close($this->request);
return $response;
}
/**
* Formats and adds custom headers to the current request
*
* @return void
* @access protected
**/
protected function set_request_headers() {
$headers = array();
foreach ($this->headers as $key => $value) {
$headers[] = $key.': '.$value;
}
curl_setopt($this->request, CURLOPT_HTTPHEADER, $headers);
}
/**
* Set the associated CURL options for a request method
*
* @param string $method
* @return void
* @access protected
**/
protected function set_request_method($method) {
switch (strtoupper($method)) {
case 'HEAD':
curl_setopt($this->request, CURLOPT_NOBODY, true);
break;
case 'GET':
curl_setopt($this->request, CURLOPT_HTTPGET, true);
break;
case 'POST':
curl_setopt($this->request, CURLOPT_POST, true);
break;
default:
curl_setopt($this->request, CURLOPT_CUSTOMREQUEST, $method);
}
}
/**
* Sets the CURLOPT options for the current request
*
* @param string $url
* @param string $vars
* @return void
* @access protected
**/
protected function set_request_options($url, $vars) {
/* echo $url;
dump($vars);
dump($this->options);
echo $this->request;
exit;*/
curl_setopt($this->request, CURLOPT_URL, $url);
if (!empty($vars)) curl_setopt($this->request, CURLOPT_POSTFIELDS, $vars);
# Set some default CURL options
curl_setopt($this->request, CURLOPT_HEADER, true);
curl_setopt($this->request, CURLOPT_RETURNTRANSFER, true);
curl_setopt($this->request, CURLOPT_USERAGENT, $this->user_agent);
if ($this->cookie_file) {
curl_setopt($this->request, CURLOPT_COOKIEFILE, $this->cookie_file);
curl_setopt($this->request, CURLOPT_COOKIEJAR, $this->cookie_file);
}
if ($this->follow_redirects) curl_setopt($this->request, CURLOPT_FOLLOWLOCATION, true);
if ($this->referer) curl_setopt($this->request, CURLOPT_REFERER, $this->referer);
# Set any custom CURL options
foreach ($this->options as $option => $value) {
curl_setopt($this->request, constant('CURLOPT_'.str_replace('CURLOPT_', '', strtoupper($option))), $value);
}
}
}
\ No newline at end of file
<?php
namespace app\chat\utils;
use app\chat\consts\ConfigConst;
use Think\Log;
use think\Cache;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/8
* Time : 17:17
* Intro: 发送消息类
*/
class RPush
{
/**
* 发送消息
* @param $user_name
* @param $target_type
* @param $target
* @param $msg_content
* @param $from
* @param $type
* @param $access_token
* @param $callback
*/
public function send($user_name,$target_type, $target, $msg_content, $from, $type, $access_token, $callback)
{
//todo
if(Cache::get('save_message_num')){
$save_message_num=Cache::get('save_message_num');
if($save_message_num>10){
sleep(1);
Cache::set('save_message_num', 0);
}else{
$save_message_num=$save_message_num+1;
Cache::set('save_message_num', $save_message_num);
}
}else{
Cache::set('save_message_num', 0);
}
$response = $this->sendRequestByCurl($user_name,$target_type, $target, $msg_content, $from, $type, $access_token);
call_user_func_array([ $callback[0], $callback[1] ], [ $response, $target, $from, $msg_content ]);
}
/** curl参数拼凑
* @param $user_name
* @param $target_type users 给用户发消息。chatgroups: 给群发消息,chatrooms: 给聊天室发消息
* @param $target 注意这里需要用数组,数组长度建议不大于20,即使只有一个用户,也要用数组 ['u1'],给用户发送时数组元素是用户名,
* 给群组发送时数组元素是groupid
* @param $type //目前只有文本的消息
* @param $msg_content
* @param $from
* @param $type
* @param $access_token
* @return \app\chat\utils\CurlResponse|bool
*/
public function sendRequestByCurl($user_name,$target_type, $target, $msg_content, $from, $type, $access_token)
{
$arr = array(
'target_type' => $target_type,
'target' => $target,
'msg' => [ "type" => "txt", "msg" => $msg_content ],
'from' => $from,
'ext' => [ "msg_type" => $type ,"user_name"=>$user_name]
);
$data = json_encode($arr);
$curl = new \app\chat\utils\CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => "Bearer " . $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$url = $this->buildSendUrl();
$response = $curl->post($url, $data);
Log::record('info -------------' . json_encode($response), "info");
return $response;
}
/**
* 请求api
* @return string
*/
private function buildSendUrl()
{
return ConfigConst::API_PATH . ConfigConst::ORG_NAME . "/" . ConfigConst::APP_NAME . "/messages";
}
}
\ No newline at end of file
<?php
namespace app\chat\utils;
use app\chat\consts\ConfigConst;
use app\chat\utils;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/18
* Time : 14:47
* Intro: 注册环信用户
*/
class RegisterUtil
{
const IM_REGISTER_USER = "/users";
const IM_DELETE_USER = "/users";
/**
* @param $username
* @param $password
* @return CurlResponse|bool
*/
public function registerByCurl($username, $password)
{
$arr = array(
'username' => $username,
'password' => $password,
);
$data = json_encode($arr);
$curl = new CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$url = $this->buildSendUrl() . self::IM_REGISTER_USER;
$response = $curl->post($url, $data);
return $response;
}
/**
* @param $username
* @param $access_token
* @return CurlResponse|bool
*/
public function deleteByCurl($username, $access_token)
{
$arr = array(
'username' => $username,
);
$data = json_encode($arr);
$curl = new CurlUtil();
$curl->delete();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$url = $this->buildSendUrl() . self::IM_DELETE_USER;
$response = $curl->post($url, $data);
return $response;
}
/**
* 请求api
* @return string
*/
private function buildSendUrl()
{
return ConfigConst::API_PATH . ConfigConst::ORG_NAME . "/" . ConfigConst::APP_NAME;
}
}
\ No newline at end of file
<?php
namespace app\chat\utils;
use app\chat\consts\ConfigConst;
use Think\Log;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/8
* Time : 17:17
* Intro: 发送消息类
*/
class UGroup
{
/** 创建一个群
* 朱伟 2018年01月25日
*/
public function createGroup($group_name, $group_users, $group_users_admin='admin',$access_token)
{
$arr= array(
"groupname"=>$group_name, //群组名称,此属性为必须的
"desc"=>"good", //群组描述,此属性为必须的
"public"=>true, //是否是公开群,此属性为必须的
"maxusers"=>300, //群组成员最大数(包括群主),值为数值类型,默认值200,最大值2000,此属性为可选的
"members_only"=>true, // 加入群是否需要群主或者群管理员审批,默认是false
"allowinvites"=> true, //是否允许群成员邀请别人加入此群。 true:允许群成员邀请人加入此群,false:只有群主或者管理员才可以往群里加人。
"owner"=>$group_users_admin, //群组的管理员,此属性为必须的
"members"=>$group_users //群组成员,此属性为可选的,但是如果加了此项,数组元素至少一个(注:群主jma1不需要写入到members里面)
);
$data = json_encode($arr);
$curl = new \app\chat\utils\CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => "Bearer " . $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$url = $this->buildSendUrl();
$response = $curl->post($url, $data);
Log::record('------createGroup-------' . json_encode($response), "info");
return $response;
}
/** del一个群
* 朱伟 2018年01月25日
*/
public function deleteGroup($group_id,$access_token)
{
$arr= array();
$data = json_encode($arr);
$curl = new \app\chat\utils\CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => "Bearer " . $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$url = $this->buildSendUrl().$group_id;
$response = $curl->delete($url, $data);
Log::record('-------deleteGroup------' . json_encode($response), "info");
return $response;
}
/** 获取群成员
* 朱伟 2018年01月26日
*/
public function getGroupUser($group_id,$pagenum,$pagesize,$access_token)
{
$arr= array();
$data = json_encode($arr);
$curl = new \app\chat\utils\CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => "Bearer " . $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$url = $this->buildSendUrl().$group_id.'users?pagenum='.$pagenum.'&pagesize='.$pagesize;
$response = $curl->get($url, $data);
Log::record('-------deleteGroup------' . json_encode($response), "info");
return $response;
}
/** 添加群组成员
* 朱伟 2018年01月26日
*/
public function addGroupUserByIds($group_id,$username,$access_token)
{
$arr= array();
$data = json_encode($arr);
$curl = new \app\chat\utils\CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => "Bearer " . $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$url = $this->buildSendUrl().$group_id.'/users/'.$username;
$response = $curl->post($url, $data);
Log::record('-------addGroupUserByIds------' . json_encode($response), "info");
return $response;
}
/**
* 移除群组成员
* 朱伟 2018年01月29日
* @param $group_id
* @param $username
* @param $access_token
* @return CurlResponse|bool
*/
public function delGroupUserByIds($group_id,$username,$access_token)
{
$arr= array();
$data = json_encode($arr);
$curl = new \app\chat\utils\CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => "Bearer " . $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
$url = $this->buildSendUrl().$group_id.'/users/'.$username;
$response = $curl->post($url, $data);
Log::record('-------delGroupUserByIds------' . json_encode($response), "info");
return $response;
}
/**
* 添加群组管理员
* 朱伟 2018年01月29日
* @param $group_id
* @param $username
* @param $access_token
* @return CurlResponse|bool
*/
public function addGroupManage($group_id,$username,$access_token)
{
$arr= array("newadmin"=>$username);
$data = json_encode($arr);
$curl = new \app\chat\utils\CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => "Bearer " . $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
//Path: /{org_name}/{app_name}/chatgroups/{group_id}/admin
$url = $this->buildSendUrl().$group_id.'/admin';
$response = $curl->delete($url, $data);
Log::record('-------delGroupUserByIds------' . json_encode($response), "info");
return $response;
}
/**
* 移除群组管理员
* 朱伟 2018年01月29日
* @param $group_id
* @param $username
* @param $access_token
* @return CurlResponse|bool
*/
public function delGroupManage($group_id,$username,$access_token)
{
$arr= array();
$data = json_encode($arr);
$curl = new \app\chat\utils\CurlUtil();
$curl->headers = [
"Accept" => "application/json",
"Content-Type" => "application/json;charset=utf-8",
'Authorization' => "Bearer " . $access_token,
];
$curl->options = [
"CURLOPT_SSL_VERIFYPEER" => 0,
"CURLOPT_SSL_VERIFYHOST" => 2,
];
//
$url = $this->buildSendUrl().$group_id.'/admin/'.$username;
$response = $curl->delete($url, $data);
Log::record('-------delGroupUserByIds------' . json_encode($response), "info");
return $response;
}
/**
* 请求api
* @return string
*/
private function buildSendUrl()
{
return ConfigConst::API_PATH . ConfigConst::ORG_NAME . "/" . ConfigConst::APP_NAME.'/chatgroups/' ;
}
}
\ No newline at end of file
# Netscape HTTP Cookie File
# http://curl.haxx.se/docs/http-cookies.html
# This file was generated by libcurl! Edit at your own risk.
a1.easemob.com FALSE / FALSE 1517538110 rememberMe deleteMe
...@@ -13,8 +13,10 @@ define('IMG_PATH','https://admin.tonglianjituan.com/houseImg/'); ...@@ -13,8 +13,10 @@ define('IMG_PATH','https://admin.tonglianjituan.com/houseImg/');
define('LOCAL_IMG_HOST','/resource/lib/Attachments/'); define('LOCAL_IMG_HOST','/resource/lib/Attachments/');
define('PAGESIZE', 15); //分页每页条数 define('PAGESIZE', 15); //分页每页条数
define('ADMIN_URL_TL','https://admin.tonglianjituan.com/'); //B端网址 define('ADMIN_URL_TL','https://admin.tonglianjituan.com/'); //B端网址
define('TEST_ADMIN_URL_TL','https://dev.tonglianjituan.com/'); //B端网址
define('CURRENT_URL', 'http://'.$_SERVER['HTTP_HOST'].DS); //取当前域名地址 define('CURRENT_URL', 'http://'.$_SERVER['HTTP_HOST'].DS); //取当前域名地址
define('HEADERIMGURL', CURRENT_URL . 'static'. DS . 'head_portrait/'); //头像地址 define('HEADERIMGURL', CURRENT_URL . 'static'. DS . 'head_portrait/'); //头像地址
define('CHAT_IMG_URL', CURRENT_URL . 'static'. DS . 'chat_image/'); //聊天图片地址
define('CK_IMG_URL', CURRENT_URL . '/resource/lib/Attachments/'); //ck 资源文件 define('CK_IMG_URL', CURRENT_URL . '/resource/lib/Attachments/'); //ck 资源文件
return [ return [
// +---------------------------------------------------------------------- // +----------------------------------------------------------------------
......
<?php
namespace app\extra;
/**
* Created by PhpStorm.
* User : zw
* Date : 2018/1/9
* Time : 15:20
* Intro: redis connect class
*/
class RedisPackage
{
protected static $handler = null;
protected $options = [
'host' => '101.132.186.250',
'port' => 6379,
'password' => '',
'select' => 0,
'timeout' => 0,
'expire' => 0,
'persistent' => false,
'prefix' => '',
];
public function __construct($options = [])
{
if (!extension_loaded('redis')) { //判断是否有扩展(如果你的apache没reids扩展就会抛出这个异常)
throw new \BadFunctionCallException('not support: redis');
}
if (!empty($options)) {
$this->options = array_merge($this->options, $options);
}
$func = $this->options['persistent'] ? 'pconnect' : 'connect'; //判断是否长连接
self::$handler = new \Redis;
self::$handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']);
if ('' != $this->options['password']) {
self::$handler->auth($this->options['password']);
}
if (0 != $this->options['select']) {
self::$handler->select($this->options['select']);
}
}
/**
* 写入缓存
* @param string $key 键名
* @param string $value 键值
* @param int $exprie 过期时间 0:永不过期
* @return bool
*/
public static function set($key, $value, $exprie = 0)
{
if ($exprie == 0) {
$set = self::$handler->set($key, $value);
} else {
$set = self::$handler->setex($key, $exprie, $value);
}
return $set;
}
/**
* 读取缓存
* @param string $key 键值
* @return mixed
*/
public static function get($key)
{
$fun = is_array($key) ? 'Mget' : 'get';
return self::$handler->{$fun}($key);
}
/**
* 获取值长度
* @param string $key
* @return int
*/
public static function lLen($key)
{
return self::$handler->lLen($key);
}
/**
* 将一个或多个值插入到列表头部
* @param $key
* @param $value
* @return int
*/
public static function LPush($key, $value, $value2 = null, $valueN = null)
{
return self::$handler->lPush($key, $value, $value2, $valueN);
}
/**
* 移出并获取列表的第一个元素
* @param string $key
* @return string
*/
public static function lPop($key)
{
return self::$handler->lPop($key);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: hujun
* Date: 2018/1/16
* Time: 13:51
*/
namespace app\index\controller;
use app\index\extend\Basic;
use app\model\AuthGroup;
use app\model\AuthRule;
use think\Db;
class Auth extends Basic
{
protected $authGroupModel;
protected $authRuleModel;
function _initialize()
{
}
/**
* 权限列表页
*
* @return type
*/
public function index(){
return view('index');
}
/**
* 权限分配
*
* @param type $group_id
*/
public function access($group_id = 0) {
return view('access');
}
/**
* 用户组授权用户列表
*
* @param type $group_id
*/
public function accessUser($group_id = 0) {
return view('accessUser');
}
public function getAuth() {
$data['status'] = 200;
$data['msg'] = '';
$params = $this->request->param();
$pageNo = empty($params['pageNo']) ? 1 : $params['pageNo'];
$pageSize = empty($params['pageSize']) ? 15 : $params['pageSize'];
$auth_group = New AuthGroup();
$where = 'status <> 0';
$data['list'] = $auth_group->getList($pageNo, $pageSize, '','*', $where);
$data['total'] = $auth_group->getTotal($where);
return $this->response(200, '', $data);
}
/**
* 角色编辑
*/
public function roleEdit() {
//$this->assign('type','1');
// return $this->display();
return view('role_edit');
}
/**
* 验证数据
* @param string $validate 验证器名或者验证规则数组
* @param array $data [description]
* @return [type] [description]
*/
protected function validateData($data,$validate)
{
if (!$validate || empty($data)) return false;
$result = $this->validate($data,$validate);
if(true !== $result){
// 验证失败 输出错误信息
return $result;
}
return 1;
}
//添加角色
public function addAuth($group_id=0){
$data['status'] = 200;
$data['msg'] = '';
$title = $group_id ? '编辑':'新增';
$table= New AuthGroup();
$info= $table->find();
if (empty($group_id)) {
$data = input('post.');
$err=$this->validateData($data,
[
['title','require|chsAlpha','用户组名称不能为空|用户组名称只能是汉字和字母'],
['description','chsAlphaNum','描述只能是汉字字母数字']
]
);
if($err!=1){
return $this->response(100, $err);
}
$id = isset($data['id']) && $data['id']>0 ? $data['id']:false;
if ($table->editData($data,$id)) {
return $this->response(200, '成功');
} else {
return $this->response(101, '失败');
}
} else {
return $this->response(200, $title, $info);
}
}
public function test(){
// $this->authRuleModel = new AuthRule();
// dump($this->authRuleModel);die;
// $list= $this->authRuleModel->find();
// return $this->response(200, '', $list);
}
/**
* 权限分配
* @param integer $group_id 组ID
* @return [type] [description]
* @date 2018-01-22
* @author zfc
*/
public function accessLook($group_id=0){
$table= New AuthGroup();
$table2= New AuthRule();
$data['title']='权限分配';
// echo $group_id;
// exit;
if (IS_POST && $group_id=0) {
//添加or修改
$data['id'] = $group_id;
$menu_auth = input('post.menu_auth/a','');//获取所有授权菜单id
$data['rules'] = implode(',',$menu_auth);//拼接
$id = isset($data['id']) && $data['id']>0 ? $data['id']:false;
//开发过程中先关闭这个限制
//if($group_id==1){
//$this->error('不能修改超级管理员'.$title);
// }else{
if ( $table->editData($data,$id)) {
cache('admin_sidebar_menus_'.$this->currentUser['uid'],null);
return $this->response(200, '成功');
}else{
return $this->response(100, '失败');
}
//}
} else{
//查看
$role_auth_rule = $table->where(['id'=>intval($group_id)])->value('rules');
$data['menu_auth_rules']=explode(',',$role_auth_rule);//获取指定获取到的权限
}
$menu = $table2->where(['pid'=>0,'status'=>1])->order('sort asc')->select();
foreach($menu as $k=>$v){
$menu[$k]['_child']=$table2->where(['pid'=>$v['id']])->order('sort asc')->select();
}
$data['all_auth_rules']=$menu;//所以规则
return $this->response(200,'可以查看',$data);
}
/**
* 设置角色的状态
*/
public function setStatus($model ='auth_rule',$script = false){
$ids = input('request.ids/a');
if ($model =='AuthGroup') {
if (is_array($ids)) {
if(in_array(1, $ids)) {
$this->error('超级管理员不允许操作');
}
} else{
if($ids === 1) {
$this->error('超级管理员不允许操作');
}
}
} else{
//cache('admin_sidebar_menus_'.$this->currentUser['uid'],null);//清空后台菜单缓存
}
parent::setStatus($model);
}
//权限列表
public function authList(){
$data['status'] = 200;
$data['msg'] = '';
$params = $this->request->param();
$pageNo = empty($params['pageNo']) ? 1 : $params['pageNo'];
$pageSize = empty($params['pageSize']) ? 20 : $params['pageSize'];
$table= new authRule;
//条件
$field='a.id,a.name,a.title,a.depend_flag,a.type,a.pid,a.icon,a.sort,a.is_menu,a.status,b.name as name2';
$where='a.status=1';
$order='a.pid asc,a.sort asc';
$join=[['auth_rule b', ' a.pid=b.id','left']];
$list=$table->authList($pageNo, $pageSize,$order,$field,$join, $where);
// prt($list);//转化arr
//prt(collection($list)->toArray());//转化arr
return $this->response(200,'成功',$list);
}
}
\ No newline at end of file
<?php
/**
* Created by PhpStorm.
* User: hujun
* Date: 2018/1/17
* Time: 13:26
*/
namespace app\index\controller;
use app\index\extend\Basic;
use app\model\GBusinessDistrict;
use app\model\Regions;
class BusinessDistrict extends Basic
{
public function index() {
return view('business_district/index');
}
public function edit() {
if ($this->request->isPost()) {
$result['code'] = 200;
$result['msg'] = '';
$params = $this->request->param();
$business = new GBusinessDistrict();
if ($params['type'] == NULL) {
$data['province'] = $params['province'];
$data['city'] = $params['city'];
$data['disc'] = $params['disc'];
$data['province_code'] = $params['province_code'];
$data['city_code'] = $params['city_code'];
$data['disc_code'] = $params['disc_code'];
$data['name'] = $params['business'];
$data['create_time'] = date('Y-m-d H:i:s');
} else {
$data['status'] = $params['type'];
}
if ($params['id']) {
$num = $business->save($data, ['id' => $params['id']]);
} else {
$business->save($data);
$num = $business->id;
}
if ($num) {
$result['code'] = 200;
$result['msg'] = '添加成功';
} else {
$result['code'] = 101;
$result['msg'] = '添加失败';
}
return $this->response( $result['code'], $result['msg'], $result['data']);
} elseif ($this->request->param('id')) {
$business = new GBusinessDistrict();
$result['data'] = $business->get($this->request->param('id'));
return $this->response( 200, '', $result['data']);
} else{
return view('business_district/edit');
}
}
/**
* 删除商圈
*
* @return \think\Response
*/
public function del() {
$result['code'] = 200;
$result['msg'] = '';
$id = $this->request->param('id');
$business = new GBusinessDistrict();
$num = $business->save(['is_del' => 1],['id'=>$id]);
if ($num != 1) {
$result['code'] = 101;
}
return $this->response( $result['code'], '');
}
/**
* 获取商圈列表
*
* @return mixed
*/
public function getBusiness() {
$data['status'] = 200;
$data['msg'] = '';
$params = $this->request->param();
$pageNo = empty($params['pageNo']) ? 1 : $params['pageNo'];
$pageSize = empty($params['pageSize']) ? 15 : $params['pageSize'];
$auth_group = New GBusinessDistrict();
$where = 'is_del = 0';
if ($params['name'] != NULL) {
$where .= ' and name like "'.$params['name'].'%"';
}
$fields = 'id,name,province,city,disc,status,create_time';
$data['list'] = $auth_group->getList($pageNo, $pageSize, 'id desc',$fields, $where);
$data['total'] = $auth_group->getTotal($where);
return $this->response(200, '', $data);
}
/**
* 获取省市区数据
*
* @return \think\Response
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function regions() {
$code = $this->request->get('code');
$parent_code = $this->request->get('parent_code');
$regions = new Regions();
if ($code) {
$where = 'code = '.$code;
} elseif ($parent_code) {
$where = 'parentCode = '.$parent_code;
} else {
$type = $this->request->get('type') ? $this->request->get('type') : 1;
$where = 'type = '.$type;
}
$fields = 'code,parentCode,name';
$data = $regions->field($fields)->where($where)->select();
return $this->response(200, '', $data);
}
}
\ No newline at end of file
<?php
namespace app\index\controller;
use app\index\extend\Basic;
use app\model\HouseInfos;
/**
* Description of HouseInfo
*
* @author : fuju
* @date : 2018-1-15 11:09:56
* @internal : description
*/
class HouseInfo extends Basic{
protected $house_infos;
public function __construct() {
parent::__construct($request);
$this->house_infos = new HouseInfos();
}
public function index() {
return $this->house_infos->select();
}
}
<?php
/**
* Created by PhpStorm.
* User: fuju
* Date: 2018/1/17
* Time: 13:46
*/
namespace app\index\controller;
use app\index\extend\Basic;
use app\model\GHouses;
use app\model\GHousesExt;
use app\model\GHousesImgs;
use think\Request;
class Houses extends Basic
{
protected $house;
public function __construct(Request $request = null)
{
parent::__construct($request);
$this->house = new GHouses();
}
public function index() {
return view('houseList');
}
/**
* 新增和编辑商铺
*
* @return \think\response\View
* @throws \Exception
* @throws \think\exception\PDOException
*/
public function edit() {
$result['code'] = 200;
$result['msg'] = '';
$params = $this->request->param();
if ($this->request->isPost()) {
$date = date('Y-m-d H:i:s');
if ($params['id']) {
$params['update_time'] = $date;
}
$this->house->startTrans();
//新增或编辑
if ($params['id'] == '') {
$house_id = $this->house->allowField(true)->save($params);
} else {
$house_id = $this->house->allowField(true)->isUpdate(true)->save($params, ['id' => $params['id']]);
}
$params['house_id'] = $house_id;
$house_ext = new GHousesExt();
if ($params['start_business_date']) {
$params['start_business_date'] = date('Y-m-d H:i:s' , strtotime($params['start_business_date']));
}
//新增或编辑根据id
if ($params['id'] == '') {
$house_ext->allowField(true)->save($params);
} else {
$house_ext_data = $house_ext->field('id')->where('house_id',$params['id'])->find();
$house_ext->allowField(true)->isUpdate(true)->save($params, ['id' => $house_ext_data['id']]);
}
/***保存图片 hujun 2018.1.19 start***/
$house_img = new GHousesImgs();
if ($params['id'] == '') {
$house_img->add($params, $house_id);
} else {
$house_img->edit($params, $house_id);
}
/***保存图片 hujun 2018.1.19 end***/
if ($house_id) {
$this->house->commit();
$return = $this->response($result['code'], $result['msg']);
} else {
$this->house->rollback();
$return = $this->response(101, $result['msg']);
}
} elseif ($params['id']){
//获取商铺详情
$house = new GHouses();
$result['data'] = $house->getHouseById($params['id']);
$return = $this->response($result['code'], $result['msg'], $result['data']);
} else {
//商铺添加页面
$return = view('edit');
}
return $return;
}
/**
* 楼盘列表
*
* @return \think\Response
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/
public function getHouseList() {
$data['status'] = 200;
$data['msg'] = '';
$params = $this->request->param();
$pageNo = empty($params['pageNo']) ? 1 : $params['pageNo'];
$pageSize = empty($params['pageSize']) ? 15 : $params['pageSize'];
$fields = '';
/*精选商铺--0是1否*/
if ($params['is_carefully_chosen'] != NULL) {
$where['is_carefully_chosen'] = $params['is_carefully_chosen'];
}
/*0是1否显示在c端用户*/
if ($params['is_show'] != NULL) {
$where['is_show'] = $params['is_show'];
}
/*商铺类型(0商场,1街铺)*/
if ($params['shop_type'] != NULL) {
$where['shop_type'] = $params['shop_type'];
}
/*所在城市*/
if ($params['city'] != NULL) {
$where['city'] = $params['city'];
}
/*所在区*/
if ($params['disc'] != NULL) {
$where['disc'] = $params['disc'];
}
/*状态 0待审批 1上架 2下架 3回收*/
if ($params['status'] != NULL) {
$where['status'] = $params['status'];
}
/*价格 -1表示营业额扣点 存分*/
if ($params['rent_price'] != NULL) {
switch ($params['rent_price']) {
case 1:
$where['rent_price'] = ['>',10000];break;
case 2:
$where['rent_price'] = ['between','10000,30000'];break;
default :
$where['rent_price'] = ['>', '30000'];
}
}
/*对内楼盘名*/
if ($params['internal_title'] != NULL) {
$where['internal_title'] = ['LIKE', $params['internal_title'].'%'];
}
/*是否独家0否1是*/
if ($params['is_exclusive_type'] != NULL) {
$where['is_exclusive_type'] = ['LIKE', $params['is_exclusive_type'].'%'];
}
/*开始时间*/
if ($params['start_date'] != NULL) {
$where['create_time'] = ['> time', $params['start_date']. ' 00:00:00'];
}
/*结束时间*/
if ($params['end_date'] != NULL) {
$where['create_time'] = ['< time',$params['end_date']. ' 23:59:59'];
}
/*开始结束时间*/
if ($params['start_date'] != NULL && $params['end_date'] != NULL) {
$where['create_time'] = ['between time',[$params['start_date'].' 00:00:00'],$params['end_date']. ' 23:59:59'];
}
/*根据库存判断是否已租*/
if ($params['leased'] != NULL) {
if ($params['leased'] == 0) {
$where['residue_num'] = 0;
} else {
$where['residue_num'] = ['<>',0];
}
}
/*业态*/
if ($params['industry_type'] != NULL) {
$where['industry_type'] = ['LIKE',$params['industry_type'].'%'];
}
//案场权限人搜索
if (empty($params['dish'])) {
/*楼盘编号*/
if ($params['id'] != NULL) {
$where['id'] = $params['id'];
}
$where['status'] = ['<>',2];
$data['data']['list'] = $this->house->getHouseList($pageNo, $pageSize, 'id DESC', $fields, $where);
$data['data']['total'] = $this->house->getTotal($where);
} else {
//盘方人搜索
/*楼盘编号*/
if ($params['id'] != NULL) {
$where['a.id'] = $params['id'];
}
$where['a.status'] = ['<>',2];
$where['c.name'] = ['LIKE',$params['dish'].'%'];
$where['b.type'] = ['=',1];
$data['data']['list'] = $this->house->getHouseListDish($pageNo, $pageSize, 'a.id DESC', $fields, $where);
$data['data']['total'] = $this->house->getHouseListDishTotal($where);
}
return $this->response($data['status'], $data['msg'], $data['data']);
}
/**
* 伪删除商铺
*
* @return \think\Response
*/
public function del() {
$data['status'] = 200;
$data['msg'] = '';
$params = $this->request->param();
if ($params['id']) {
$this->house->isUpdate(true)->save(['status'=>3],['id'=>$params['id']]);
$data['msg'] = 'successfully deleted';
} else {
$data['status'] = 101;
$data['msg'] = 'id is null';
}
return $this->response($data['status'], $data['msg'], $data['data']);
}
}
\ No newline at end of file
This diff is collapsed.
{layout name="global/frame_tpl" /}
<input type="hidden" class="page-load" id="business_district" /><!--关联js文件-->
<div id="page-content-wrapper">
<div class="container">
<div class="col-lg-10 col-lg-offset-0">
<div class="builder-tabs builder-form-tabs">
<ul class="nav nav-tabs">
<li class=""><a href="/admin.php/index/roleedit/1.html">角色信息</a></li>
<li class="active"><a href="/admin.php/index/access/1.html">权限分配</a></li>
<li class=""><a href="/admin.php/index/accessUser/1.html">成员授权</a></li>
</ul>
<div class="form-group"></div>
</div>
<div class="builder formbuilder-box panel-body bg-color-fff">
<div class="row">
<div class="col-md-7 col-md-offset-1">
<div id="tab2" class="tab-pane">
<form action="" method="post" class="form-builder form-horizontal responsive">
<div class="form-group">
<div class="auth" id="access_box">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 tc">
<div class="col-md-3"><button class="btn btn-block btn-primary submit ajax-post" type="submit" target-form="form-builder">确认</button></div> &nbsp;
<div class="col-md-3"><button class="btn bg-aqua btn-block return" onclick="javascript:history.back(-1);return false;"><i class="fa fa-mail-reply"></i> 返回</button></div>
</div>
</div>
</form>
</div>
</div>
</div><!--row-->
</div>
</div>
</div>
</div>
\ No newline at end of file
{layout name="global/frame_tpl" /}
<div id="page-content-wrapper">
<div class="container">
<div class="col-lg-10 col-lg-offset-0">
<div class="builder-tabs builder-form-tabs">
<ul class="nav nav-tabs">
<li class=""><a href="/admin.php/index/roleedit/1.html">角色信息</a></li>
<li class=""><a href="/admin.php/index/access/1.html">权限分配</a></li>
<li class="active"><a href="/admin.php/index/accessUser/1.html">成员授权</a></li>
</ul>
<div class="form-group"></div>
</div>
<div class="builder formbuilder-box panel-body bg-color-fff">
<div class="row">
<div class="builder-table">
<!-- 数据列表 -->
<div class="col-sm-12">
<table class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr>
<th class="">UID</th>
<th class="">昵称</th>
<th class="">最后登录时间</th>
<th class="">最后登录IP</th>
<th class="">状态</th>
<th class="">操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>1 </td>
<td>创始人</td>
<td><span>2018-01-16 16:49</span></td>
<td><span>127.0.0.1</span></td>
<td>正常</td>
<td><a href="/admin.php/admin/auth/removefromgroup/uid/1/group_id/1.html" class="ajax-get">解除授权</a>
</td>
</tr>
<tr>
<td>2 </td>
<td>心灵旅行</td>
<td><span>2016-09-18 22:18</span></td>
<td><span>1928388295</span></td>
<td>正常</td>
<td><a href="/admin.php/admin/auth/removefromgroup/uid/2/group_id/1.html" class="ajax-get">解除授权</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="main-title">
<div class="page_nav col-md-8">
</div>
<div id="add-to-group" class="tools col-md-4">
<form class="add-user" action="/admin.php/admin/auth/addtogroup.html" method="post" enctype="application/x-www-form-urlencoded">
<div class="form-group">
<div class="col-md-10">
<input class="form-control" type="text" name="uid" placeholder="请输入uid,多个用英文逗号分隔">
</div>
<input type="hidden" name="group_id" value="1">
<button type="submit" class="btn btn-info btn-raised btn-sm ajax-post col-md-2" target-form="add-user">新 增</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{layout name="global/frame_tpl" /}
<h4>权限管理</h4>
<a href="/index/roleedit">添加角色</a>
<input type="hidden" class="page-load" id="auth" />
<div id="page-content-wrapper">
<div class="container">
<div class="col-lg-10 col-lg-offset-0">
<table class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center">角色名</th>
<th class="text-center">描述</th>
<th class="text-center">状态</th>
<th class="text-center">操作</th>
</tr>
</thead>
<tbody id="auth_list">
</tbody>
</table>
</div>
<!-- /#page-content-wrapper -->
<div class="text-right pageinfo" id="pagediv">
</div>
</div>
</div>
\ No newline at end of file
{layout name="global/frame_tpl" /}
<input type="hidden" class="page-load" id="role_edit"/>
<div id="page-content-wrapper">
<div class="container">
<div class="col-lg-10 col-lg-offset-0">
<div class="builder-tabs builder-form-tabs">
<ul class="nav nav-tabs">
<li class="active"><a href="/admin.php/index/roleedit/1.html">角色信息</a></li>
<li class=""><a href="/admin.php/index/access/1.html">权限分配</a></li>
<li class=""><a href="/admin.php/index/accessUser/1.html">成员授权</a></li>
</ul>
<div class="form-group"></div>
</div>
<div class="builder formbuilder-box panel-body bg-color-fff">
<div class="row">
<div class="col-md-7">
<form action="/index/addAUth" method="post" class="form-builder form-horizontal">
<fieldset>
<!-- <input type="hidden" name="id" value="3">-->
<div class="form-group">
<label for="title" class="col-md-2 control-label">名称:</label>
<div class="col-md-10">
<input type="text" class="form-control" name="title" placeholder="创建的角色名称" value="普通用户">
<span class="material-input"></span>
</div>
</div>
<div class="form-group item_description">
<label for="description" class="col-md-2 control-label">描述:</label>
<div class="col-md-10">
<textarea name="description" class="form-control" length="120" rows="5">这是普通用户的权限</textarea>
<span class="material-input"></span>
</div>
</div>
<div class="form-group">
<div class="col-md-12 col-md-offset-2">
<div class="col-md-3"><button class="btn btn-block btn-primary submit ajax-post" type="submit" target-form="form-builder">确定</button></div>
<div class="col-md-3"><button class="btn btn-block btn-default return" onclick="javascript:history.back(-1);return false;">返回</button></div>
</div>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
{layout name="global/frame_tpl" /}
<input type="hidden" class="page-load" id="business_district" />
<!--导航star-->
<!-- Sidebar -->
<!-- /#sidebar-wrapper -->
<!-- Page Content -->
<div id="page-content-wrapper">
<div class="container">
<div class="row">
<div class="col-lg-10 col-lg-offset-0">
<div class="panel panel-default">
<div class="panel-heading breadcrumb">
<li><a href="#">商铺管理</a></li>
<li class="active">添加商圈</li>
<div class="pull-right">
<ul class="bread_btn">
<li>
<a href="#modal_business" data-toggle="modal" class="btn btn-default" id="modal_add"><i class="icon-plus"></i>
添加商圈</a>
</li>
</ul>
</div>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover table-condensed">
<thead>
<tr>
<td colspan="8">
<form action="" method="get" id="form_search">
<input class="form-control btn2" data-rule-phoneus="false" data-rule-required="false" id="name" name="name" placeholder="商圈名" type="text" value="">
<span class="btn btn-default btn3" id="search">搜索</span>
<span class="btn btn-default btn3" id="reset">重置</span>
</form>
</td>
</tr>
<tr>
<th class="text-center">编号</th>
<th class="text-center">商圈名</th>
<th class="text-center"></th>
<th class="text-center"></th>
<th class="text-center"></th>
<th class="text-center">状态</th>
<th class="text-center">创建时间</th>
<th class="text-center">操作</th>
</tr>
</thead>
<tbody id="business_list" class="text-center">
</tbody>
</table>
</div>
<!-- /#page-content-wrapper -->
<div class="text-right" id="pagediv">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /#wrapper -->
<!-- /#新增用户模态框 -->
<div class="modal fade" id="modal_business" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
&times;
</button>
<h4 class="modal-title" id="title">
添加商圈
</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" action="/index/editBusinessDistrict" method="POST" id="add_business_form">
<div class="form-group">
<label for="province" class="col-md-3 control-label">省:</label>
<div class="col-md-7">
<select name="province" id="province" class="form-control btn6">
<option>请选择</option>
</select>
<span class="use-span text-danger">(必填)</span>
</div>
</div>
<div class="form-group">
<label for="city" class="col-md-3 control-label">市:</label>
<div class="col-md-7">
<select name="city" id="city" class="form-control btn6">
<option>请选择</option>
</select>
<span class="use-span text-danger">(必填)</span>
</div>
</div>
<div class="form-group">
<label for="disc" class="col-md-3 control-label">区:</label>
<div class="col-md-7">
<select name="disc" id="disc" class="form-control btn6">
<option>请选择</option>
</select>
<span class="use-span text-danger">(必填)</span>
</div>
</div>
<div class="form-group">
<label for="business" class="col-md-3 control-label">商圈:</label>
<div class="col-md-7">
<input type="text" id="business" name="business" class="form-control btn6">
<span class="use-span text-danger">(必填)</span>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="close">关闭
</button>
<button type="button" class="btn btn-primary" id="add_business">
提交
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
<!-- /#wrapper -->
<!-- /#删除模态框 -->
<div class="modal fade" id="modal-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
&times;
</button>
<h4 class="modal-title">
删除
</h4>
</div>
<div class="modal-body">
<div class="modal-body" id="del_msg">
确认删除吗?
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭
</button>
<button type="button" class="btn btn-primary" id="confirm_delete">
删除
</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal -->
</div>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
<?php
/**
* Created by PhpStorm.
* User: fuju
* Date: 2018/1/20
* Time: 17:52
*/
namespace app\model;
class AAgents extends BaseModel
{
}
\ No newline at end of file
...@@ -7,9 +7,12 @@ use think\Db; ...@@ -7,9 +7,12 @@ use think\Db;
class Agents extends Model class Agents extends Model
{ {
protected $table = 'agents';
/** /**
* 查询经纪人 * 查询经纪人
* *
* @param type $pageNo * @param type $pageNo
* @param type $pageSize * @param type $pageSize
* @param type $order_ * @param type $order_
...@@ -18,28 +21,29 @@ class Agents extends Model ...@@ -18,28 +21,29 @@ class Agents extends Model
* @param type $house_id 查询该街铺和商铺的经纪人评论信息 * @param type $house_id 查询该街铺和商铺的经纪人评论信息
* @return type * @return type
*/ */
public function getUser($pageNo = 1, $pageSize = 15, $order_ = 'id desc', $field, $params, $house_id = '') { public function getUser($pageNo = 1, $pageSize = 15, $order_ = 'id desc', $field, $params, $house_id = '')
{
if ($house_id == '') { if ($house_id == '') {
$data = $this->field($field)->alias('a') $data = $this->field($field)->alias('a')
->join('u_evaluate b', 'a.id = b.agents_id', 'left') ->join('u_evaluate b', 'a.id = b.agents_id', 'left')
->where($params) ->where($params)
->where('level=2 or level=5') ->where('level=2 or level=5')
->group('a.id') ->group('a.id')
->order($order_) ->order($order_)
->limit($pageSize) ->limit($pageSize)
->page($pageNo) ->page($pageNo)
->select(); ->select();
} else { } else {
$data = $this->field($field)->alias('a') $data = $this->field($field)->alias('a')
->join('u_evaluate b','a.id = b.agents_id','left') ->join('u_evaluate b', 'a.id = b.agents_id', 'left')
->where('find_in_set('.$house_id.', house_ids) or find_in_set('.$house_id.', house_ids2)') ->where('find_in_set(' . $house_id . ', house_ids) or find_in_set(' . $house_id . ', house_ids2)')
->where($params) ->where($params)
->where('level=2 or level=5') ->where('level=2 or level=5')
->group('a.id') ->group('a.id')
->order($order_) ->order($order_)
->limit($pageSize) ->limit($pageSize)
->page($pageNo) ->page($pageNo)
->select(); ->select();
} }
return $data; return $data;
...@@ -47,25 +51,20 @@ class Agents extends Model ...@@ -47,25 +51,20 @@ class Agents extends Model
/** /**
* 经纪人详情 * 经纪人详情
*
* @param $id
* @return array|bool|false|\PDOStatement|string|Model
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException
*/ */
public function agentsDetail($id) { public function agentsDetail($id)
{
if ($id) { if ($id) {
$result = $this->field('id,realname,created,sub_shopname,head_portrait') $result = $this->field('id,realname,created,sub_shopname,head_portrait')
->where('level=2 or level=5') ->where('level=2 or level=5')
->where('id',$id)->find(); ->where('id', $id)->find();
$result['head_portrait'] = 'user_header/'.$result['head_portrait']; //头像 $result['head_portrait'] = 'user_header/' . $result['head_portrait']; //头像
$evaluate_grade = Db::table('u_evaluate') $evaluate_grade = Db::table('u_evaluate')
->field('sum(evaluate_grade) as evaluate_grade, count(*) as evaluate_num') ->field('sum(evaluate_grade) as evaluate_grade, count(*) as evaluate_num')
->where('agents_id',$id)->where('is_show',0)->find(); ->where('agents_id', $id)->where('is_show', 0)->find();
if ($evaluate_grade['evaluate_grade']) { if ($evaluate_grade['evaluate_grade']) {
$grade = floor(($evaluate_grade['evaluate_grade']/2)/$evaluate_grade['evaluate_num']); $grade = floor(($evaluate_grade['evaluate_grade'] / 2) / $evaluate_grade['evaluate_num']);
} else { } else {
$grade = 0; $grade = 0;
} }
...@@ -73,7 +72,7 @@ class Agents extends Model ...@@ -73,7 +72,7 @@ class Agents extends Model
$result['evaluate_grade'] = $grade; //评分等级 $result['evaluate_grade'] = $grade; //评分等级
$result['evaluate_num'] = $evaluate_grade['evaluate_num']; //评论数量 $result['evaluate_num'] = $evaluate_grade['evaluate_num']; //评论数量
$result['watch_shop'] = Db::table('u_appoint_watch_shop') $result['watch_shop'] = Db::table('u_appoint_watch_shop')
->where('agents_id',$id)->count(); //看铺 ->where('agents_id', $id)->count(); //看铺
$result['head_portrait'] = ADMIN_URL_TL.$result['head_portrait']; $result['head_portrait'] = ADMIN_URL_TL.$result['head_portrait'];
$remarks = new Remarks(); $remarks = new Remarks();
...@@ -85,24 +84,40 @@ class Agents extends Model ...@@ -85,24 +84,40 @@ class Agents extends Model
$current_time = time(); $current_time = time();
$user_time = strtotime($result['created']); $user_time = strtotime($result['created']);
$year = date('Y', $current_time) - date('Y', $user_time); $year = date('Y', $current_time) - date('Y', $user_time);
//入职年限 //入职年限
if ($year == 0) { if ($year == 0) {
$result['created'] = $year .'个月以上'; $result['created'] = $year . '个月以上';
} else { } else {
$result['created'] = $year . '年以上'; $result['created'] = $year . '年以上';
} }
$result['label'] = array(0=>'待定标签数据',1=>'待定标签数据'); $result['label'] = array( 0 => '待定标签数据', 1 => '待定标签数据' );
$data = $result; $data = $result;
} else { } else {
$data = false; $data = false;
} }
return $data; return $data;
} }
/**
* 获取经纪人 by zw
* @param $field
* @param $where_
* @return array|false|\PDOStatement|string|Model
*/
public function getAgentsById($field, $where_)
{
$data = $this
->field($field)
->where($where_)
->select();
return $data;
}
/** /**
* 查询经纪人列表 * 查询经纪人列表
* *
...@@ -117,7 +132,8 @@ class Agents extends Model ...@@ -117,7 +132,8 @@ class Agents extends Model
* @throws \think\db\exception\ModelNotFoundException * @throws \think\db\exception\ModelNotFoundException
* @throws \think\exception\DbException * @throws \think\exception\DbException
*/ */
public function getAgents($pageNo = 1, $pageSize = 15, $order_ = 'id desc', $field, $params, $house_id = '') { public function getAgents($pageNo = 1, $pageSize = 15, $order_ = 'id desc', $field, $params, $house_id = '')
{
if ($house_id == '') { if ($house_id == '') {
$data = $this->field($field) $data = $this->field($field)
->where($params) ->where($params)
...@@ -128,7 +144,7 @@ class Agents extends Model ...@@ -128,7 +144,7 @@ class Agents extends Model
->select(); ->select();
} else { } else {
$data = $this->field($field) $data = $this->field($field)
->where('find_in_set('.$house_id.', house_ids) or find_in_set('.$house_id.', house_ids2)') ->where('find_in_set(' . $house_id . ', house_ids) or find_in_set(' . $house_id . ', house_ids2)')
->where($params) ->where($params)
->where('level=2 or level=5') ->where('level=2 or level=5')
->order($order_) ->order($order_)
......
<?php
// 权限模型
namespace app\model;
class AuthGroup extends BaseModel
{
const TYPE_ADMIN = 1; // 管理员用户组类型标识
const MEMBER = 'agents';
const AUTH_GROUP_ACCESS = 'auth_group_access'; // 关系表表名
const AUTH_GROUP = 'auth_group'; // 用户组表名
const AUTH_EXTEND_CATEGORY_TYPE = 1; // 分类权限标识
const AUTH_EXTEND_MODEL_TYPE = 2; //分类权限标识
protected $insert =['status'=>1];
/**
* 返回用户组列表
* 默认返回正常状态的管理员用户组列表
* @param array $where 查询条件,供where()方法使用
*
*/
public function getGroups($where=array()){
$map = array('status'=>1);
$map = array_merge($map,$where);
return $this->where($map)->select();
}
/**
* 把用户添加到用户组,支持批量添加用户到用户组
*
* 示例: 把uid=1的用户添加到group_id为1,2的组 `AuthGroupModel->addToGroup(1,'1,2');`
*/
public function addToGroup($uid, $gid){
$uid = is_array($uid)? implode(',',$uid) : trim($uid,',');
$gid = is_array($gid)? $gid:explode( ',',trim($gid,',') );
$Access = model(self::AUTH_GROUP_ACCESS);
$del = true;
if( isset($_REQUEST['batch']) ){
//为单个用户批量添加用户组时,先删除旧数据
$del = $Access->where(['uid'=>['in',$uid]])->delete();
}
$uid_arr = explode(',',$uid);
$uid_arr = array_diff($uid_arr,get_administrators());
$add = [];
if( $del!==false ){
foreach ($uid_arr as $u){
foreach ($gid as $g){
if( is_numeric($u) && is_numeric($g) ){
//防止重复添加
if (!$Access->where(['group_id'=>$g,'uid'=>$u])->count()) {
$add[] = ['group_id'=>$g,'uid'=>$u];
}
}
}
}
if (!empty($add) && is_array($add)) {
$Access->saveAll($add);
} else{
$this->error = "添加失败,可能有重复添加操作";
return false;
}
}
if ($Access->getError()) {
if( count($uid_arr)==1 && count($gid)==1 ){
//单个添加时定制错误提示
$this->error = "不能重复添加";
}
return false;
}
return true;
}
/**
* 返回用户所属用户组信息
* @param int $uid 用户id
* @return array 用户所属的用户组 array(
* array('uid'=>'用户id','group_id'=>'用户组id','title'=>'用户组名称','rules'=>'用户组拥有的规则id,多个,号隔开'),
* ...)
*/
static public function getUserGroup($uid){
static $groups = array();
if (isset($groups[$uid]))
return $groups[$uid];
$prefix = config('database.prefix');
$user_groups = model()
->field('uid,group_id,title,description,rules')
->table($prefix.self::AUTH_GROUP_ACCESS.' a')
->join ($prefix.self::AUTH_GROUP." g on a.group_id=g.id")
->where("a.uid='$uid' and g.status='1'")
->select();
$groups[$uid]=$user_groups?$user_groups:array();
return $groups[$uid];
}
/**
* 将用户从用户组中移除
* @param int|string|array $gid 用户组id
* @param int|string|array $cid 分类id
*/
public function removeFromGroup($uid,$gid){
$del_result = model(self::AUTH_GROUP_ACCESS)->where( array( 'uid'=>$uid,'group_id'=>$gid) )->delete();
if ($del_result) {
$user_auth_role = db('users')->where(array('uid'=>$uid))->value('auth_groups');
if ($user_auth_role) {
$user_auth_role=array_merge(array_diff(explode(',', $user_auth_role), array($gid)));
model('user')->where(array('uid'=>$uid))->setField('auth_groups',$user_auth_role);//同时将用户角色关联删除
}
}
return $del_result;
}
/**
* 获取某个用户组的用户列表
*
* @param int $group_id 用户组id
*/
static public function userInGroup($group_id){
$prefix = config('database.prefix');
$l_table = $prefix.self::MEMBER;
$r_table = $prefix.self::AUTH_GROUP_ACCESS;
$list = model() ->field('m.uid,u.username,m.last_login_time,m.last_login_ip,m.status')
->table($l_table.' m')
->join($r_table.' a ON m.uid=a.uid')
->where(array('a.group_id'=>$group_id))
->select();
return $list;
}
/**
* 检查id是否全部存在
* @param array|string $gid 用户组id列表
*/
public function checkId($modelname,$mid,$msg = '以下id不存在:'){
if(is_array($mid)){
$count = count($mid);
$ids = implode(',',$mid);
}else{
$mid = explode(',',$mid);
$count = count($mid);
$ids = $mid;
}
$s = model($modelname)->where(array('id'=>array('in',$ids)))->column('id');
if(count($s)===$count){
return true;
}else{
$diff = implode(',',array_diff($mid,$s));
$this->error = $msg.$diff;
return false;
}
}
/**
* 检查用户组是否全部存在
* @param array|string $gid 用户组id列表
*/
public function checkGroupId($gid){
return $this->checkId('AuthGroup',$gid, '以下用户组id不存在:');
}
/**
* 返回角色分组
*
* @param type $pageNo
* @param type $pageSize
* @param type $order_
* @param type $field
* @param type $params
* @return type
*/
public function getList($pageNo = 1, $pageSize = 15, $order_ = 'id desc', $field = '', $params = '') {
return $this->field($field)
->where($params)
->order($order_)
->limit($pageSize)
->page($pageNo)
->select();
}
}
<?php
// 权限模型
namespace app\admin\model;
class AuthGroupAccess extends Base
{
// 设置完整的数据表(包含前缀)
// protected $table = 'think_access';
// 设置数据表(不含前缀)
// protected $name = 'auth_rule';
// 定义时间戳字段名
protected $createTime = false;
protected $updateTime = false;
/**
* 用户组信息
* @param integer $uid [description]
* @return [type] [description]
*/
public function userGroupInfo($uid = 0)
{
if (!$uid) return false;
$result = $this->alias('a')->join('__AUTH_GROUP__ b','a.group_id = b.id')->where(['a.uid'=>$uid,'a.status'=>1])->field('a.group_id,b.title')->select();
if ($result) {
foreach ($result as $key => $row) {
$return[$row['group_id']] = $row['title'];
}
return $return;
}
return false;
}
/**
* 获取组对应的用户Uids
* @param string $group_id [description]
* @return [type] [description]
* @date 2017-10-17
* @author 心云间、凝听 <981248356@qq.com>
*/
public static function groupUserUids($group_id)
{
return $return = self::where('group_id',$group_id)->column('uid');
}
}
\ No newline at end of file
<?php
//权限规则模型
namespace app\model;
use think\Model;
class AuthRule extends Model
{
// 设置完整的数据表(包含前缀)
// protected $table = 'think_access';
// 设置数据表(不含前缀)
// protected $name = 'auth_rule';
// 设置birthday为时间戳类型(整型)
// protected $type = [
// 'birthday' => 'timestamp',
// ];
// 定义时间戳字段名
protected $createTime = '';
//protected $updateTime = '';
/**
*返回功能权限列表
*
*
*/
public function authList($p = 1, $pageSize = 20, $order_ = '', $field = '',$join='', $where = ''){
$data = $this->field($field)
->alias('a')
->join($join)
->where($where)
->order($order_)
->limit($pageSize)
->page($p)
->select();
return $data;
}
}
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment