This commit is contained in:
knowpia
2022-09-08 15:23:13 +08:00
commit 96a49d1bd6
26 changed files with 1597 additions and 0 deletions

1
app/.htaccess Normal file
View File

@@ -0,0 +1 @@
deny from all

22
app/AppService.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
declare (strict_types = 1);
namespace app;
use think\Service;
/**
* 应用服务类
*/
class AppService extends Service
{
public function register()
{
// 服务注册
}
public function boot()
{
// 服务启动
}
}

94
app/BaseController.php Normal file
View File

@@ -0,0 +1,94 @@
<?php
declare (strict_types = 1);
namespace app;
use think\App;
use think\exception\ValidateException;
use think\Validate;
/**
* 控制器基础类
*/
abstract class BaseController
{
/**
* Request实例
* @var \think\Request
*/
protected $request;
/**
* 应用实例
* @var \think\App
*/
protected $app;
/**
* 是否批量验证
* @var bool
*/
protected $batchValidate = false;
/**
* 控制器中间件
* @var array
*/
protected $middleware = [];
/**
* 构造方法
* @access public
* @param App $app 应用对象
*/
public function __construct(App $app)
{
$this->app = $app;
$this->request = $this->app->request;
// 控制器初始化
$this->initialize();
}
// 初始化
protected function initialize()
{}
/**
* 验证数据
* @access protected
* @param array $data 数据
* @param string|array $validate 验证器名或者验证规则数组
* @param array $message 提示信息
* @param bool $batch 是否批量验证
* @return array|string|true
* @throws ValidateException
*/
protected function validate(array $data, $validate, array $message = [], bool $batch = false)
{
if (is_array($validate)) {
$v = new Validate();
$v->rule($validate);
} else {
if (strpos($validate, '.')) {
// 支持场景
[$validate, $scene] = explode('.', $validate);
}
$class = false !== strpos($validate, '\\') ? $validate : $this->app->parseClass('validate', $validate);
$v = new $class();
if (!empty($scene)) {
$v->scene($scene);
}
}
$v->message($message);
// 是否批量验证
if ($batch || $this->batchValidate) {
$v->batch(true);
}
return $v->failException(true)->check($data);
}
}

30
app/CodeAndMessage.php Normal file
View File

@@ -0,0 +1,30 @@
<?php
//系统或是代码错误
const SYSTEM_ERROR_CODE = 999999;
const SYSTEM_ERROR_MESSAGE = "系统繁忙";
const SUCCESS_CODE = 0;
const SUCCESS_MESSAGE = "操作成功";
const ERROR_CODE = 1;
const ERROR_MESSAGE = "具体提示";
const NEED_LOGIN = 20000;
const NEED_LOGIN_MESSAGE = "需要登录后再操作";
const MISSING_PARAMETER = 30000;
const MISSING_PARAMETER_MESSAGE = "缺少参数";
const TYPE_PARAMETER = 30001;
const TYPE_PARAMETER_MESSAGE = "参数类型错误";
const TOKEN_ERROR = 40001;
const TOKEN_ERROR_MESSAGE = "token错误";
const SIGN_ERROR = 40002;
const SIGN_ERROR_MESSAGE = "签名错误";
const TIMEOUT_ERROR = 40004;
const TIMEOUT_ERROR_MESSAGE = "数据超时";

63
app/ExceptionHandle.php Normal file
View File

@@ -0,0 +1,63 @@
<?php
namespace app;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use Throwable;
/**
* 应用异常处理类
*/
class ExceptionHandle extends Handle
{
/**
* 不需要记录信息(日志)的异常类列表
* @var array
*/
protected $ignoreReport = [
HttpException::class,
HttpResponseException::class,
ModelNotFoundException::class,
DataNotFoundException::class,
ValidateException::class,
];
/**
* 记录异常信息(包括日志或者其它方式记录)
*
* @access public
* @param Throwable $exception
* @return void
*/
public function report(Throwable $exception): void
{
// 使用内置的方式记录异常日志
parent::report($exception);
}
/**
* Render an exception into an HTTP response.
*
* @access public
* @param \think\Request $request
* @param Throwable $e
* @return Response
*/
public function render($request, Throwable $e): Response
{
// 添加自定义异常处理机制
$data = [
'file'=>$e->getFile(),
'line'=>$e->getLine(),
'message'=>$e->getMessage()
];
return show(SYSTEM_ERROR_MESSAGE,SYSTEM_ERROR_CODE,$data,$GLOBALS['appKey']);
// 其他错误交给系统处理
// return parent::render($request, $e);
}
}

8
app/Request.php Normal file
View File

@@ -0,0 +1,8 @@
<?php
namespace app;
// 应用请求对象类
class Request extends \think\Request
{
}

254
app/common.php Normal file
View File

@@ -0,0 +1,254 @@
<?php
// 应用公共文件
include "../app/CodeAndMessage.php";
use think\facade\Db;
// 获取客户端IP
if(!function_exists('get_client_ip')){
function get_client_ip(){
if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown"))
$ip = getenv("HTTP_CLIENT_IP");
else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown"))
$ip = getenv("REMOTE_ADDR");
else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown"))
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = "unknown";
return($ip);
}
}
if(!function_exists('show')){
function show($message = '',$code = ERROR_CODE,$data = [],$appKey="",$httpStatus = 200){
if($appKey == "" && !empty($GLOBALS['appkey'])){
$appKey = $GLOBALS['appkey'];
}
$result = ["code" => $code,"message"=>$message,"data"=>$data];
if(env("APP_DEBUG")){
return json($result,$httpStatus);
}
return json(["RD"=>app\tools\Aes::encrypt(json_encode($result),$appKey)],$httpStatus);
}
}
/**
* 验证手机号是否正确
* @author honfei
* @param number $mobile
*/
if(!function_exists('is_mobile_number')) {
function is_mobile_number($mobile)
{
if (!is_numeric($mobile)) return false;
return (bool)preg_match('#^1[3,4,5,7,8,9]{1}[\d]{9}$#', $mobile);
}
}
/**
* 生成随机字符串
* @param int $length 生成随机字符串的长度
* @param string $char 组成随机字符串的字符串
* @return string $string 生成的随机字符串
*/
if(!function_exists('strRand')) {
function strRand(int $length = 32, string $char = '0123456789&abcdefghijklmnopqrstuvwxyz@ABCDEFGHIJKLMNOPQRSTUVWXYZ$')
{
if (!is_int($length) || $length < 0) {
return false;
}
$string = '';
for ($i = $length; $i > 0; $i--) {
$string .= $char[mt_rand(0, strlen($char) - 1)];
}
return $string;
}
}
/**
* Discuz 经典双向加密/解密
* @param string $string 明文 或 密文
* @param string $operation DECODE表示解密,其它表示加密
* @param string $key 密匙
* @param string $expiry 密文有效期
*/
if(!function_exists('authcode')) {
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0)
{
if ($operation == 'DECODE') {
$string = str_replace(' ', '+', $string);
}
$ckey_length = 4;
$key = md5($key ? $key : env('data_auth_key'));
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya . md5($keya . $keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = [];
for ($i = 0; $i <= 255; $i++) {
$rndkey[$i] = ord($cryptkey[$i % $key_length]);
}
for ($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
for ($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if ($operation == 'DECODE') {
if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
return substr($result, 26);
} else {
return '';
}
} else {
return $keyc . str_replace('=', '', base64_encode($result));
}
}
}
use OSS\Core\OssException;
use OSS\OssClient;
//阿里云OSS
/*
if (!function_exists('aliyun')) {
function aliyun($savePath, $category = '', $isunlink = false, $bucket = "hphb-storage")
{
$accessKeyId = env('aliyunsms.accessKeyId');//去阿里云后台获取秘钥
$accessKeySecret = env('aliyunsms.accesskey');//去阿里云后台获取秘钥
$endpoint = env('aliyunsms.oss_endpoint');//你的阿里云OSS地址
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
// 判断bucketname是否存在不存在就去创建
if (!$ossClient->doesBucketExist($bucket)) {
$ossClient->createBucket($bucket);
}
$category = empty($category) ? $bucket : $category;
$savePath = str_replace("\\", "/", $savePath);
$object = '/' . $savePath;//想要保存文件的名称
$file = env("upload_directory").'\\' . $savePath;//文件路径,必须是本地的。
try {
echo 'bc';
$obj = $ossClient->uploadFile($bucket, $object, $file);
echo 'abc';
if ($isunlink == true) {
unlink($file);
}
print_r($obj);
} catch (OssException $e) {
echo $e->getErrorMessage();
}
$web = "https://hphb-storage.".env('aliyunsms.oss_endpoint').'/'.$object;//这里是你阿里云oss外网访问的Bucket域名
return $web;
}
}
*/
if (!function_exists('aliyun')) {
function aliyun($localfile = '', $path = '')
{
$config = [
'access' => env('aliyunsms.accessKeyId'),
'access_key' => env('aliyunsms.accesskey'),
'bucket' => 'hphb-storage',
'url' => 'https://oss-cn-beijing.aliyuncs.com'
];
$path = "r/".$localfile;
$localfile = env("upload_directory").'/' . $localfile;//文件路径,必须是本地的。
if (!file_exists($localfile)) {
return ('Not found file');
}
if ($path == "") {
return ['code' => 1, 'message' => "远程文件名不能为空"];
}
$accessKeyId = $config['access'];
$accessKeySecret = $config['access_key'];
$endpoint = $config['url'];
try {
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$info = $ossClient->uploadFile($config['bucket'], $path, $localfile);
if(empty($info['info']['url'])){
return ['code' => 1, 'message' => "上传失败"];
}
return ['code' => 0, 'message' => "", 'url' => $info['info']['url']];
} catch (OssException $e) {
return ['code' => 1, 'message' => $e->getMessage()];
}
}
}
function getExt($filename)
{
$arr = explode('.',$filename);
return array_pop($arr);
}
function StudentToArray($list = []) : array {
$result = [];
$result['lastIndex'] = 0;
$result['list']=[];
foreach($list as $key => $vo){
if($vo['id']>$result['lastIndex']){
$result['lastIndex'] = $vo['id'];
}
$result["list"][] = [
"id"=>$vo['id'],
"hot"=>$vo['hot'],
"avatar"=>$vo['avatar'],
"nickname"=>$vo['nickname'],
"is_disabled"=>$vo['disabled'],
"type"=>$vo["type"],
"identifier"=>$vo['identifier'],
"article_count"=>$vo['article_count'],
"city"=>$vo['city'],
"school"=>$vo['school'],
"age"=>$vo['age'],
];
}
if(count($list)<env("page_count")){
$result["lastIndex"] = 0;
}
return $result;
}
function lastindex(){
return empty($GLOBALS['data']['data']["lastindex"])?0:$GLOBALS['data']['data']["lastindex"];
}
if(!function_exists('getAllUsersMessage')) {
function getAllUsersMessage($list = [], $userIdField = "", $getFieldString = "")
{
if (empty($list)) return;
$UserIds = [];
foreach ($list as $vo) $UserIds[] = $vo[$userIdField];
if (empty($UserIds)) return;
$UserIds = array_unique($UserIds);
$getAllUsersMessage = [];
$UserLists = Db::name("app_users")->where("id", "IN", $UserIds)->field($getFieldString)->select()->toArray();
foreach ($UserLists as $vo) {
$getAllUsersMessage[$vo['id']] = $vo;
}
return $getAllUsersMessage;
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace app\controller;
use think\facade\Db;
class Address
{
//地址管理
public function lists(){
$userid = $GLOBALS['data']['userid'];
if (empty($userid)) {
return show("请登录后再发布!");
}
$list = Db::name("app_address")->where("userid",$userid)->select()->toArray();
return show("获取成功!",SUCCESS_CODE,$list);
}
//地址详细信息
public function getaddress(){
$userid = $GLOBALS['data']['userid'];
if (empty($userid)) {
return show("请登录后再发布!");
}
$address_id = $GLOBALS['data']['data']['address_id'];
if (empty($address_id)) {
return show("请输入地址编号!");
}
$info = Db::name("app_address")->where("id",$address_id)->find();
if(empty($info) || $info['userid']!=$userid){
return show("找不到该地址信息!");
}
return show("获取成功!",SUCCESS_CODE,$info);
}
//添加地址
public function plus()
{
$post = $GLOBALS['data']['data'];
$userid = $GLOBALS['data']['userid'];
if (empty($userid)) {
return show("请登录后再发布!");
}
if(empty($post['name'])) return show("请输入收货人收件人姓名!");
if(empty($post['mobile'])) return show("请输入收货人电话!");
if(empty($post['province'])) return show("请输入省份!");
if(empty($post['city'])) return show("请输入城市!");
if(empty($post['area'])) return show("请输入区!");
if(empty($post['detail'])) return show("请输入详细地址!");
$default = $post['is_default'];
if(!in_array($default, [0,1])){
return show("默认地址值超出范围!");
}else{
if($default == 1){
Db::name("app_address")->where("userid",$userid)->update(["is_default"=>0]);
}
}
Db::name("app_address")->insert([
"userid"=>$userid,
"name"=>$post['name'],
"mobile"=>$post['mobile'],
"province"=>$post['province'],
"city"=>$post['city'],
"area"=>$post['area'],
"detail"=>$post['detail'],
"is_default"=>$post['is_default'],
]);
return show("添加成功!", SUCCESS_CODE, []);
}
}

116
app/controller/Article.php Normal file
View File

@@ -0,0 +1,116 @@
<?php
namespace app\controller;
use think\facade\Db;
class Article
{
public function plus()
{
$post = $GLOBALS['data']['data'];
$userid = $GLOBALS['data']['userid'];
if(empty($userid)){
return show("请登录后再发布!");
}
if(empty($post['content'])){
return show("内容不能为空!");
}
if(empty($post['imgs'])){
return show("图片不能为空!");
}
Db::name("app_article")->insert([
"text"=>$post['content'],
"imgs"=>$post['imgs'],
"userid"=>$userid,
"createtime"=>time(),
"click"=>0
]);
Db::name("student")->inc("article_count",1)->where("id",$userid)->update();
return show("发布成功!",SUCCESS_CODE,[]);
}
public function delete(){
$userid = $GLOBALS['data']['userid'];
if(empty($userid)){
return show("请登录后操作!");
}
$article_id = $GLOBALS['data']['data']["article_id"];
if(empty($article_id)){
return show("请上输入动态ID");
}
$info = Db::name("app_article")->where("id",$article_id)->find();
if(empty($info) || $info['userid']!=$userid){
return show("找不到该动态信息!");
}
Db::name("app_article")->where("id",$article_id)->delete();
return show("删除成功!",SUCCESS_CODE,[]);
}
public function lists(){
$userid = $GLOBALS['data']['userid'];
if(empty($userid)){
return show("请登录后操作!");
}
$lastIndex = empty($GLOBALS['data']['data']["lastindex"])?0:$GLOBALS['data']['data']["lastindex"];
if($lastIndex == 0){
$where = "userid={$userid} and id>0";
}else{
$where = "userid={$userid} and id<".$lastIndex;
}
$result["lastIndex"] = 0;
$list = Db::name("app_article")->where($where)->order("id desc")->order('id desc')->limit(env("page_count"))->select()->toArray();
foreach($list as $vo){
$result['lastIndex'] = $vo['id'];
$result["list"][] = $vo;
}
if(count($list)<env("page_count")){
$result["lastIndex"] = 0;
}
return show(SUCCESS_MESSAGE,SUCCESS_CODE,$result);
}
public function detail(){
if(empty($GLOBALS['data']['data']['article_id'])){
return show("请上传动态ID");
}
$article_id = $GLOBALS['data']['data']['article_id'];
$info = Db::name('app_article')->where("id",$article_id)->find();
if(empty($info)) return show("找不到该动态信息!");
return show(SUCCESS_MESSAGE,SUCCESS_CODE,$info);
}
public function getlists(){
$userid = $GLOBALS['data']['userid'];
if(empty($userid)){
return show("请登录后操作!");
}
if(empty($GLOBALS['data']['data']['student_userid'])){
return show("请输入用户ID");
}
$student_userid = $GLOBALS['data']['data']['student_userid'];
$student = Db::name("student")->field("id")->where("id",$student_userid)->find();
if(empty($student)) return show("找不到用户信息!");
$lastIndex = empty($GLOBALS['data']['data']["lastindex"])?0:$GLOBALS['data']['data']["lastindex"];
if($lastIndex == 0){
$where = "userid={$student_userid} and id>0";
}else{
$where = "userid={$student_userid} and id<".$lastIndex;
}
$result["lastIndex"] = 0;
$list = Db::name("app_article")->where($where)->order("id desc")->order('id desc')->limit(env("page_count"))->select()->toArray();
foreach($list as $vo){
$result['lastIndex'] = $vo['id'];
$result["list"][] = $vo;
}
if(count($list)<env("page_count")){
$result["lastIndex"] = 0;
}
return show(SUCCESS_MESSAGE,SUCCESS_CODE,$result);
}
}

103
app/controller/Help.php Normal file
View File

@@ -0,0 +1,103 @@
<?php
namespace app\controller;
use think\facade\Db;
class Help
{
//为用户助力
public function me()
{
$userid = $GLOBALS['data']['userid'];
if(empty($userid)){
return show("请登录后再助力!");
}
if(empty($GLOBALS['data']['data']['student_id'])){
return show("请输入要助力的用户id");
}
$student_id = $GLOBALS['data']['data']['student_id'];
$info = Db::name("student")->where("id",$student_id)->field("id")->find();
if(empty($info)){
return show("找不到该学生信息!");
}
$data = [
"userid"=>$userid,
"student_id"=>$student_id,
"createtime"=>date("Y-m-d",time())
];
$data['sha'] = sha1(json_encode($data));
Db::startTrans();
try {
$info = Db::name("app_help_log")->where("sha", $data['sha'])->find();
if (!empty($info)) {
return show("你今天已经为他助力过,谢谢!");
} else {
Db::name("app_help_log")->insert($data);
}
$appHelp = Db::name("app_help")->where(["userid" => $userid, "student_id" => $student_id])->find();
if (empty($appHelp)) {
Db::name("app_help")->insert([
"userid" => $userid,
"student_id" => $student_id,
"count" => 1
]);
} else {
Db::name("app_help")->where(["id" => $appHelp['id']])->inc("count", 1)->update();
}
Db::commit();
return show("助力成功!", SUCCESS_CODE, []);
}catch (\Exception $e) {
Db::rollback();
return show("助力失败!");
}
}
public function lists(){
if(empty($GLOBALS['data']['data']['student_id'])){
return show("请输入要助力的用户id");
}
$student_id = $GLOBALS['data']['data']['student_id'];
$info = Db::name("student")->where("id",$student_id)->field("id")->find();
if(empty($info)){
return show("找不到该学生信息!");
}
$lastIndex = lastindex();
if($lastIndex == 0) {
$lastIndex = 1;
}
$result = [];
$list = Db::name("appHelp")->where("student_id",$student_id)->limit(env("page_count"))->order('count desc')->paginate([
"list_rows"=>env("page_count"),
"page"=>$lastIndex
]);
if(empty($list)) return show("获取成功", SUCCESS_CODE,$result);
if($list->currentPage() < $list->lastPage()){
$result['lastIndex'] = $lastIndex +1;
}else{
$result['lastIndex'] = 0;
}
$users = getAllUsersMessage($list,'userid','id,nickname,avatar');
foreach($list as $vo){
$result['list'][] = [
"id"=>$vo['id'],
"userid"=>$vo['userid'],
"username"=>empty($users[$vo['userid']]['nickname'])?'':$users[$vo['userid']]['nickname'],
"count"=>$vo['count']
];
}
return show("获取成功!", SUCCESS_CODE, $result);
}
}

145
app/controller/Main.php Normal file
View File

@@ -0,0 +1,145 @@
<?php
namespace app\controller;
//use app\model\AppToken;
class Main
{
public function index()
{
// $j = ["userid"=>1];
// echo authcode(json_encode($j),'f');
$GLOBALS['data'] = []; // 全局变量
$api_version = ''; //当前版本号
$timeout = env('APP_DEBUG')?1000000:20; //处理超时时间
$userid = 0; //默认用户ID是0
$appKey = env('app.DEFAULT_KEY');
$GLOBALS['appKey'] = env('app.DEFAULT_KEY');//定义全局变量,报错时使用
$startTime = microtime(true); //开始时间时间
$LogArray = []; //记录日志数组
$message = [
'token_error' => 'Token验证失败',
'token_Illegal' => 'Token非法',
'data_Illegal' => '非法数据',
'logout_success' => '退出成功',
'sign_error' => '数据签名错误',
'data_timeout' => '请求数据超时',
'cmd_error' => '没有CMD信息',
];
// $independent = ["user.logout"];
try {
//获取访问者IP
$LogArray['ip'] = get_client_ip();
//获取用户上传的token
$clientToken = request()->post('tk');
//如果TOKEN不存在则设置为空
$clientToken = !empty($clientToken)?$clientToken:'';
//记录日志开始记录token和开始时间
$LogArray['token'] = $clientToken;
$LogArray['start_time'] = $startTime;
//如果存在TOKEN则需要解析token
$appToken = "";
if ($clientToken) {
$tk = json_decode(authcode($clientToken),true);
$userid = $tk['userid'];
}
//解密数据
$data = request()->post();
//定义常量
define('PLATFORM', $data['RequestBody']['Platform'] ?? ''); //手机系统平台 IOS、ANDROID
define('DEVICE', $data['RequestBody']['Device'] ?? ''); //手机型号
define('IM_NUMBER', $data['RequestBody']['IM'] ?? ''); //设备码
define('APP_VERSION', $data['RequestBody']['APPVersion'] ?? ''); //版本号
$LogArray['userid'] = $userid;
$LogArray['platform'] = PLATFORM;
$LogArray['device'] = DEVICE;
$LogArray['im_number'] = IM_NUMBER;
$LogArray['app_version'] = APP_VERSION;
$LogArray['api_version'] = $api_version;
$LogArray['cmd'] = !empty($data['RequestBody']['CMD'])?$data['RequestBody']['CMD']:'';
$LogArray['data'] = json_encode($data);
if(empty($data['cmd'])) {
return show($message['cmd_error'],MISSING_PARAMETER);
}
/**********
* start 调用退出 *************
* 把apptoken表数据清空只退出当前设置
* 其它设置信息保留
*/
if (strtolower($data['cmd']) == "sign.logout") {
if(!empty($appToken['id'])) {
$this->logout($appToken['id']);
$LogArray['return_data'] = $message['logout_success'];
$this->log($LogArray);
}
return show("退出成功!",SUCCESS_CODE);
}
if (($data['cmd'])) {
$action = explode('.', $data['cmd']);
if (is_array($action)) {
$ClassName = '\\app\\controller\\' . ucfirst($action[0]);
$FunctionName = $action[1];
$class = new $ClassName();
$GLOBALS['data'] = [
'data' => $data,
'userid' => $userid
];
if(!empty($_FILES['file'])){
$GLOBALS['data']['file'] = $_FILES['file'];
}
$backdata = $class->$FunctionName();
$LogArray['return_data'] = !empty($GLOBALS['data']['returnData'])?$GLOBALS['data']['returnData']:'';
$this->log($LogArray);
unset($data);
return $backdata;
}
}
} catch (\Exception $e) {
if(env("APP_DEBUG")){$msg = $e->getMessage();}else{$msg = "服务器故障!";}
return show($msg,SYSTEM_ERROR_CODE);
}
}
private function logout($userid)
{
(new \app\model\AppToken)->where('id', $userid)->delete();
}
private function log($data)
{
$addData = [
'ip' => !empty($data['ip'])?$data['ip']:'',
'token' => !empty($data['token'])?$data['token']:'',
'start_time' => !empty($data['start_time'])?$data['start_time']:'',
'userid' => !empty($data['userid'])?$data['userid']:'',
'platform' => !empty($data['platform'])?$data['platform']:'',
'device' => !empty($data['device'])?$data['device']:'',
'im_number' => !empty($data['im_number'])?$data['im_number']:'',
'app_version' => !empty($data['app_version'])?$data['app_version']:'',
'api_version' => !empty($data['api_version'])?$data['api_version']:'',
'cmd' => !empty($data['cmd'])?$data['cmd']:'',
'data' => !empty($data['data'])?$data['data']:'',
'return_data' => !empty($data['return_data'])?$data['return_data']:'',
'end_time' => microtime(true),
'usetime' => microtime(true) - $data['start_time']
];
$applog = (new \app\model\AppLog)->insertGetId($addData);
return $applog;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace app\controller;
use think\facade\Db;
class Ranking
{
public function lists()
{
$post = $GLOBALS['data']['data'];
if(empty($post['type'])){
return show("请选择传类型");
}
$type = $post['type'];
$typeArray = [1,2,3,4];
if(!in_array($type,$typeArray)){
return show("不支持当前类型!");
}
$where = [];
//1=未来之星;2=适龄儿童;3=残联儿童;4=全部
if($type == 1) $where = "type=1";
if($type == 2) $where = "type=2";
if($type == 3) $where = "disabled=1";
if($type == 4) $where = "";
$lastIndex = lastindex();
if($lastIndex == 0) {
$lastIndex = 1;
}
$result = [];
$list = Db::name("student")->where($where)->limit(env("page_count"))->order('hot desc')->paginate([
"list_rows"=>env("page_count"),
"page"=>$lastIndex
]);
if(empty($list)) return show("获取成功", SUCCESS_CODE,$result);
if($list->currentPage() < $list->lastPage()){
$result['lastIndex'] = $lastIndex +1;
}else{
$result['lastIndex'] = 0;
}
$result = StudentToArray($list);
return show(SUCCESS_MESSAGE,SUCCESS_CODE,$result);
}
}

28
app/controller/Search.php Normal file
View File

@@ -0,0 +1,28 @@
<?php
namespace app\controller;
use think\facade\Db;
class Search
{
public function keywords()
{
$post = $GLOBALS['data']['data'];
if(empty($post['keywords'])){
return show("请输入搜索关键字");
}
$lastIndex = $GLOBALS['data']['data']["lastindex"]??0;
if($lastIndex == 0){
$where = "id > 0";
}else{
$where = "id < ".$lastIndex;
}
$KEY = $post['keywords'];
$list = Db::name("student")->where("nickname like '{$KEY}%' or city like '{$KEY}%' or school like '{$KEY}%'")->order('hot desc')->limit(env("page_count"))->where($where)->select()->toArray();
$result = StudentToArray($list);
return show(SUCCESS_MESSAGE,SUCCESS_CODE,$result);
}
}

111
app/controller/Sign.php Normal file
View File

@@ -0,0 +1,111 @@
<?php
namespace app\controller;
use app\v1\model\AppToken;
use think\facade\Db;
class Sign
{
public function password(){
if(empty($GLOBALS['data']['data']['mobile'])){
return show("手机号不能为空!");
}
if(empty($GLOBALS['data']['data']['password'])){
return show("密码不能为空!");
}
$password = md5($GLOBALS['data']['data']['password']);
$info = Db::name("student")->where("mobile",$GLOBALS['data']['data']['mobile'])->find();
if(empty($info)){
return show("找不到家长信息!");
}
if($info['password']!=$password){
return show("密码不正确,请重试!");
}
$tokenData = ['userid' => $info['id'],'loginTime' => time(),'rankStr' => strRand(5)];
$tk = authcode(json_encode($tokenData), 'ENCODE');
unset($info['password']);
$res = [
'TK' => $tk,
'user' => [
"userid"=>$info['id'],
"identifier"=>$info['identifier'],
"nickname"=>$info['nickname'],
"mobile"=>$info['mobile'],
"avatar"=> env("admin_pannel_address") . $info['avatar'],
"gender"=>$info['gender'],
"birthday"=>$info['birthday'],
"age"=>$info['age'],
"createtime"=>$info['createtime'],
"is_disabled"=>$info['disabled'],
"type"=>$info["type"],
"hot"=>$info['hot']
]
];
return show("验证成功!",SUCCESS_CODE,$res);
}
public function getuser(){
if(empty($GLOBALS['data']['userid'])){
return show("请上传TOKEN");
}
$info = Db::name("student")->where("id",$GLOBALS['data']['userid'])->find();
if(empty($info)){
return show("找不到家长信息!");
}
$res = [
'user' => [
"userid"=>$info['id'],
"identifier"=>$info['identifier'],
"nickname"=>$info['nickname'],
"mobile"=>$info['mobile'],
"avatar"=> env("admin_pannel_address") . $info['avatar'],
"gender"=>$info['gender'],
"birthday"=>$info['birthday'],
"age"=>$info['age'],
"createtime"=>$info['createtime'],
"is_disabled"=>$info['disabled'],
"type"=>$info["type"],
"hot"=>$info['hot']
]
];
return show("操作成功!",SUCCESS_CODE,$res);
}
public function repass(){
if(empty($GLOBALS['data']['data']['mobile'])){
return show("手机号不能为空!");
}
$mobile = $GLOBALS['data']['data']['mobile'];
$info = Db::name("student")->where("mobile",$mobile)->find();
if(empty($info)){
return show("找不到用户信息!");
}
if(empty($GLOBALS['data']['data']['code'])){
return show("验证码不能为空!");
}
$code = $GLOBALS['data']['data']['code'];
if(empty($GLOBALS['data']['data']['password'])){
return show("请输入密码!");
}
$password = $GLOBALS['data']['data']['password'];
$code = Db::name("app_sms")->order("id desc")->where("mobile", $mobile)->find();
if(empty($code)){
return show("请发送短信后再试!");
}
Db::name("app_sms")->where("id",$code['id'])->inc("count",1)->update();
if((time() - $code['create_time'])>15*60){
return show("短信已经失效,请重新发送!");
}
Db::name("student")->where("id",$info['id'])->update([
"password" => md5($password)
]);
return show(SUCCESS_MESSAGE,SUCCESS_CODE,[]);
}
}

44
app/controller/Sms.php Normal file
View File

@@ -0,0 +1,44 @@
<?php
namespace app\controller;
use think\facade\Db;
class Sms
{
public function send(){
if(empty($GLOBALS['data']['data']['mobile'])){
return show("手机号不能为空!");
}
$mobileNumber = $GLOBALS['data']['data']['mobile'];
if(!is_mobile_number($mobileNumber)){
return show("手机号不正确!");
}
$timeOut = 60;
$info = Db::name("app_sms")->order("id desc")->where("mobile",$mobileNumber)->find();
if(!empty($info) && (time() - $info['create_time'])<$timeOut){
return show("请在". ($timeOut-(time()-$info['create_time'])) ."后重新发送!");
}
$code = rand(111111,999999);
try {
if(!env("APP_DEBUG")){
$result = \app\tools\Sms::sendmsg($mobileNumber,$code);
if($result['code'] != 1){
return show("运营商接口无法返回!");
}
}else{
$code = "000000";
}
Db::name("app_sms")->insert([
"ipaddress"=>get_client_ip(),
"mobile"=>$mobileNumber,
"code"=>$code,
"create_time"=>time(),
"count"=>0
]);
return show("发送成功!",SUCCESS_CODE);
}catch(\Exception $e){
return show("发送失败,请联系客服人员!");
}
}
}

View File

@@ -0,0 +1,47 @@
<?php
namespace app\controller;
use think\facade\Db;
class Student
{
public function lists()
{
$post = $GLOBALS['data']['data'];
if(empty($post['type'])){
return show("请选择传类型");
}
$type = $post['type'];
$typeArray = [1,2,3,4];
if(!in_array($type,$typeArray)){
return show("不支持当前类型!");
}
//1=未来之星;2=适龄儿童;3=残联儿童;4=全部
if($type == 1) $where = "type=1";
if($type == 2) $where = "type=2";
if($type == 3) $where = "disabled=1";
if($type == 4) $where = "";
$lastIndex = lastindex();
if($lastIndex == 0) {
$lastIndex = 1;
}
$result = [];
$list = Db::name("student")->where($where)->limit(env("page_count"))->order('hot desc')->paginate([
"list_rows"=>env("page_count"),
"page"=>$lastIndex
]);
if(empty($list)) return show("获取成功", SUCCESS_CODE,$result);
if($list->currentPage() < $list->lastPage()){
$result['lastIndex'] = $lastIndex +1;
}else{
$result['lastIndex'] = 0;
}
$result = StudentToArray($list);
return show(SUCCESS_MESSAGE,SUCCESS_CODE,$result);
}
}

34
app/controller/Upload.php Normal file
View File

@@ -0,0 +1,34 @@
<?php
namespace app\controller;
use think\facade\Db;
class Upload
{
public function image()
{
if(empty($GLOBALS['data']['userid'])){
return show("请上传TOKEN");
}
if(empty($GLOBALS['data']['file'])){
return show("请选择图片!");
}
$file = $GLOBALS['data']['file'];
$dir = env('upload_directory');
if(!is_dir($dir)){
mkdir($dir, 0777, true);
}
$ext = getExt($file['name']);
$newfilename = uniqid().rand(10000,99999).'.'.$ext;
if(move_uploaded_file($file['tmp_name'], $dir.'/'.$newfilename)){
$but = aliyun($newfilename);
if(empty($but["url"])){
return show('服务器繁忙,请联系管理员');
}
return show('上传成功',SUCCESS_CODE,['url'=>$but['url']]);
}else{
return show('服务器繁忙,请联系管理员');
}
}
}

128
app/controller/User.php Normal file
View File

@@ -0,0 +1,128 @@
<?php
namespace app\controller;
use think\facade\Db;
class User
{
//获取用户信息
public function info()
{
if(empty($GLOBALS['data']['userid'])){
return show("请上传TOKEN");
}
$userid = $GLOBALS['data']['userid'];
$info = Db::name("app_users")->where("id",$userid)->find();
if(empty($info)) return show("无此用户信息");
unset($info['openid']);
return show(SUCCESS_MESSAGE,SUCCESS_CODE,$info);
}
//修改头像
public function modify_avatar(){
if(empty($GLOBALS['data']['userid'])){
return show("请上传TOKEN");
}
$userid = $GLOBALS['data']['userid'];
$avatarUrl = $GLOBALS['data']['data']['avatar_url'];
if(empty($avatarUrl)){
return show("请上传头像!");
}
Db::name("app_users")->where("id",$userid)->update(['avatar'=>$avatarUrl]);
return show("头像修改成功!",SUCCESS_CODE,[]);
}
//修改昵称
public function modify_nickname(){
if(empty($GLOBALS['data']['userid'])){
return show("请上传TOKEN");
}
$userid = $GLOBALS['data']['userid'];
$nickname = $GLOBALS['data']['data']['nickname'];
if(empty(nickname)){
return show("请输入昵称!");
}
Db::name("app_users")->where("id",$userid)->update(['nickname'=>$nickname]);
return show("昵称修改成功!",SUCCESS_CODE,[]);
}
//狮友认证
public function verify(){
if(empty($GLOBALS['data']['userid'])){
return show("请上传TOKEN");
}
$userid = $GLOBALS['data']['userid'];
$mobileNumber = $GLOBALS['data']['data']['mobile'];
if(!is_mobile_number($mobileNumber)){
return show("手机号不正确!");
}
$res = Db::name("shiyou")->where("mobile",$mobileNumber)->find();
if(empty($res)) {
return show("未找到狮友信息!");
}
$code = Db::name("app_sms")->order("id desc")->where("mobile", $mobileNumber)->find();
if(empty($code)){
return show("请发送短信后再试!");
}
Db::name("app_sms")->where("id",$code['id'])->inc("count",1)->update();
if((time() - $code['create_time'])>15*60){
return show("短信已经失效,请重新发送!");
}
if($GLOBALS['data']['data']['code'] != $code["code"]){
return show("验证码不正确!");
}
Db::name("app_users")->where("id",$userid)->update(['identity'=>1]);
return show("狮友认证成功!",SUCCESS_CODE,[]);
}
//发送验证码
public function getcode(){
if(empty($GLOBALS['data']['data']['mobile'])){
return show("手机号不能为空!");
}
$mobileNumber = $GLOBALS['data']['data']['mobile'];
if(!is_mobile_number($mobileNumber)){
return show("手机号不正确!");
}
$user = Db::name("shiyou")->where("mobile",$mobileNumber)->find();
if(empty($user)) return show("手机号狮友库中未找到,请核对!");
$timeOut = 60;
$info = Db::name("app_sms")->order("id desc")->where("mobile",$mobileNumber)->find();
if(!empty($info) && (time() - $info['create_time'])<$timeOut){
return show("请在". ($timeOut-(time()-$info['create_time'])) ."后重新发送!");
}
$code = rand(111111,999999);
try {
if(!env("APP_DEBUG")){
$result = \app\tools\Sms::sendmsg($mobileNumber,$code);
if($result['code'] != 1){
return show("运营商接口无法返回!");
}
}else{
$code = "000000";
}
Db::name("app_sms")->insert([
"ipaddress"=>get_client_ip(),
"mobile"=>$mobileNumber,
"code"=>$code,
"create_time"=>time(),
"count"=>0
]);
return show("发送成功!",SUCCESS_CODE);
}catch(\Exception $e){
return show("发送失败,请联系客服人员!");
}
}
}

17
app/event.php Normal file
View File

@@ -0,0 +1,17 @@
<?php
// 事件定义文件
return [
'bind' => [
],
'listen' => [
'AppInit' => [],
'HttpRun' => [],
'HttpEnd' => [],
'LogLevel' => [],
'LogWrite' => [],
],
'subscribe' => [
],
];

10
app/middleware.php Normal file
View File

@@ -0,0 +1,10 @@
<?php
// 全局中间件定义文件
return [
// 全局请求缓存
// \think\middleware\CheckRequestCache::class,
// 多语言加载
// \think\middleware\LoadLangPack::class,
// Session初始化
// \think\middleware\SessionInit::class
];

9
app/model/AppLog.php Normal file
View File

@@ -0,0 +1,9 @@
<?php
namespace app\model;
use think\Model;
class AppLog extends Model
{
protected $name = 'AppLog';
}

7
app/model/AppToken.php Normal file
View File

@@ -0,0 +1,7 @@
<?php
namespace app\model;
class AppToken extends BaseModel
{
protected $name = 'AppToken';
}

9
app/provider.php Normal file
View File

@@ -0,0 +1,9 @@
<?php
use app\ExceptionHandle;
use app\Request;
// 容器Provider定义文件
return [
'think\Request' => Request::class,
'think\exception\Handle' => ExceptionHandle::class,
];

9
app/service.php Normal file
View File

@@ -0,0 +1,9 @@
<?php
use app\AppService;
// 系统服务定义文件
// 服务在完成全局初始化之后执行
return [
AppService::class,
];

57
app/tools/Aes.php Normal file
View File

@@ -0,0 +1,57 @@
<?php
// +------------------------------------------------+
// |http://www.vsyo.com |
// +------------------------------------------------+
// | 修复BUG不是一朝一夕的事情等我喝醉了再说吧 |
// +------------------------------------------------+
// | Author: 林义满 <steven.lin> |
// +------------------------------------------------+
namespace app\tools;
class Aes
{
/**
*
* @param string $string 需要加密的字符串
* @param string $key 密钥
* @return string
*/
/*
public static function encrypt($string, $key)
{
$data = openssl_encrypt($string, 'AES-256-ECB', $key, OPENSSL_RAW_DATA, null);
return base64_encode($data);
}
*/
/**
* @param string $string 需要解密的字符串
* @param string $key 密钥
* @return string
*/
/*
public static function decrypt($string, $key)
{
$string = base64_decode($string);
$data = openssl_decrypt($string, 'AES-256-ECB', $key, OPENSSL_RAW_DATA, null);
return $data;
}
*/
/**
* aes加密
* AES加密(PHP+FLUTTER)
*/
public static function encrypt($string ,$key)
{
return openssl_encrypt($string,"AES-256-CBC",$key,0 ,"0000000000000000");
}
/**
* aes解密
*/
public static function decrypt($string ,$key)
{
return openssl_decrypt($string,"AES-256-CBC",$key,0,"0000000000000000");
}
}

127
app/tools/Sms.php Normal file
View File

@@ -0,0 +1,127 @@
<?php
namespace app\tools;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
// Downloadhttps://github.com/aliyun/openapi-sdk-php
// Usagehttps://github.com/aliyun/openapi-sdk-php/blob/master/README.md
class Sms
{
/**
* 发送短信验证码,本接只适合发送单个验证码
*
* @param integer $number 目标用户手机号
* @param int $code 短信验证码
* @param string $signName 签名如Knowpia
* @param string $template 使用的短信模板
* @return array
*/
public static function sendmsg($number, $code, $signName='', $template='')
{
if(empty($signName)) $signName = env('aliyunsms.signName');
if(empty($template)) $template = env('aliyunsms.TemplateCode');
if (intval($number) == 0 || $code == "" || $signName == "" || $template == "") {
return ['code' => 0, 'message' => '参数不全'];
}
AlibabaCloud::accessKeyClient(env('aliyunsms.accessKeyId'), env('aliyunsms.accesskey'))
->regionId(env('aliyunsms.regionid'))
->asDefaultClient();
try {
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host('dysmsapi.aliyuncs.com')
->options([
'query' => [
'RegionId' => env('aliyunsms.regionid'),
'PhoneNumbers' => $number,
'SignName' => $signName,
'TemplateCode' => $template,
'TemplateParam' => "{\"code\":\"" . $code . "\"}",
],
])
->request();
$result = $result->toArray();
return ['code' => 1, 'info' => $result];
} catch (ClientException $e) {
return ['code' => 0, 'message' => $e->getErrorMessage()];
} catch (ServerException $e) {
return ['code' => 0, 'message' => $e->getErrorMessage()];
}
}
/**
* 获得用户的短信验证码
*
* @param string $mobile [手机号]
* @return array
*/
public static function getMobileCode($mobile)
{
$smsExpiration = env('system.smsExpiration');
$codeInfo = \app\tools\model\MobileCode::where('state=0 and mobile="'.$mobile.'"')->order('id desc')->find();
$notMessage = '请先发送短信再验证';
if ($codeInfo) {
if ((time() - $codeInfo['create_at']) <= $smsExpiration) {
return ['code' => 1, 'MobileCode' => $codeInfo['code'],'check_id'=>$codeInfo['id']];
}
if ((time() - $codeInfo['create_at']) > $smsExpiration && (time() - $codeInfo['create_at']) <= 60 * 30) {
return ['code' => 0, 'message' => '验证码已过期'];
}
return ['code' => 0, 'message' => $notMessage];
}
return ['code' => 0, 'message' => $notMessage];
}
/**
* 号码认证服务利用一键登录TOKEN获取手机号
*
* @param string $token
* @return array
*/
public static function getMobileNumber($token = ''): array
{
/** back array
* {
* "GetMobileResultDTO": {
* "Mobile": "18620725473"
* },
* "Message": "OK",
* "RequestId": "098CC43B-8006-4127-9DC5-2B30CA741745",
* "Code": "OK"
* }
*/
if ($token == '') {
return ['code' => 0, 'message' => '参数不全'];
}
AlibabaCloud::accessKeyClient(env('aliyunsms.accessKeyId'), env('aliyunsms.accesskey'))
->regionId('cn-hangzhou')
->asDefaultClient();
try {
$result = AlibabaCloud::rpc()
->product('Dypnsapi')
->scheme('https')
->version('2017-05-25')
->action('GetMobile')
->method('POST')
->host('dypnsapi.aliyuncs.com')
->options([
'query' => [
'RegionId' => "cn-hangzhou",
'AccessToken' => $token,
],
])->request();
return ['code' => 1, 'info' => $result->toArray()];
} catch (ClientException $e) {
return ['code' => 0, 'message' => $e->getErrorMessage()];
} catch (ServerException $e) {
return ['code' => 0, 'message' => $e->getErrorMessage()];
}
}
}