作者 郭盛
1 个管道 的构建 通过 耗费 6 秒

后台老师模块,前台老师接口

<?php
namespace addons\loginbg;
use think\Addons;
/**
* 登录背景图插件
*/
class Loginbg extends Addons
{
/**
* 插件安装方法
* @return bool
*/
public function install()
{
return true;
}
/**
* 插件卸载方法
* @return bool
*/
public function uninstall()
{
return true;
}
public function adminLoginInit(\think\Request &$request)
{
$config = $this->getConfig();
if ($config['mode'] == 'random' || $config['mode'] == 'daily')
{
$index = $config['mode'] == 'random' ? mt_rand(1, 4000) : date("Ymd") % 4000;
$background = "http://img.infinitynewtab.com/wallpaper/" . $index . ".jpg";
}
else
{
$background = cdnurl($config['image']);
}
\think\View::instance()->assign('background', $background);
}
}
... ...
<?php
return array (
0 =>
array (
'name' => 'mode',
'title' => '模式',
'type' => 'radio',
'content' =>
array (
'fixed' => '固定',
'random' => '每次随机',
'daily' => '每日切换',
),
'value' => 'daily',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
1 =>
array (
'name' => 'image',
'title' => '固定背景图',
'type' => 'image',
'content' =>
array (
),
'value' => '/assets/img/loginbg.jpg',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
);
... ...
<?php
namespace addons\loginbg\controller;
use think\addons\Controller;
class Index extends Controller
{
public function index()
{
$this->error("当前插件暂无前台页面");
}
}
... ...
name = loginbg
title = 登录背景图
intro = 可自定义后台登录背景图
author = Karson
website = http://www.fastadmin.net
version = 1.0.1
state = 1
url = /addons/loginbg
... ...
<?php
namespace addons\qiniu;
use addons\qiniu\library\Auth;
use fast\Http;
use think\Addons;
/**
* 七牛上传插件
*/
class Qiniu extends Addons
{
/**
* 插件安装方法
* @return bool
*/
public function install()
{
return true;
}
/**
* 插件卸载方法
* @return bool
*/
public function uninstall()
{
return true;
}
/**
* 上传初始化时
*/
public function uploadConfigInit(&$upload)
{
$config = $this->getConfig();
$policy = array(
'saveKey' => ltrim($config['savekey'], '/'),
);
//如果启用服务端回调
if ($config['notifyenabled']) {
$policy = array_merge($policy, [
'callbackUrl' => $config['notifyurl'],
'callbackBody' => 'filename=$(fname)&key=$(key)&imageInfo=$(imageInfo)&filesize=$(fsize)&admin=$(x:admin)&user=$(x:user)'
]);
}
if ($config['uploadmode'] == 'client') {
$auth = new Auth($config['app_key'], $config['secret_key']);
$multipart['token'] = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
$multipart['x:admin'] = (int)session('admin.id');
$multipart['x:user'] = (int)cookie('uid');
$upload = [
'cdnurl' => $config['cdnurl'],
'uploadurl' => $config['uploadurl'],
'bucket' => $config['bucket'],
'maxsize' => $config['maxsize'],
'mimetype' => $config['mimetype'],
'multipart' => $multipart,
'multiple' => $config['multiple'] ? true : false,
];
} else {
$upload = array_merge($upload, [
'cdnurl' => $config['cdnurl'],
'uploadurl' => addon_url('qiniu/index/upload'),
'maxsize' => $config['maxsize'],
'mimetype' => $config['mimetype'],
'multiple' => $config['multiple'] ? true : false,
]);
}
}
/**
* 附件删除后
*/
public function uploadDelete($attachment)
{
$config = $this->getConfig();
if ($attachment['storage'] == 'qiniu' && isset($config['syncdelete']) && $config['syncdelete']) {
$auth = new Auth($config['app_key'], $config['secret_key']);
$entry = $config['bucket'] . ':' . ltrim($attachment->url, '/');
$encodedEntryURI = $auth->base64_urlSafeEncode($entry);
$url = 'http://rs.qiniu.com/delete/' . $encodedEntryURI;
$headers = $auth->authorization($url);
//删除云储存文件
$ret = Http::sendRequest($url, [], 'POST', [CURLOPT_HTTPHEADER => ['Authorization: ' . $headers['Authorization']]]);
//如果是服务端中转,还需要删除本地文件
if ($config['uploadmode'] == 'server') {
$filePath = ROOT_PATH . 'public' . str_replace('/', DS, $attachment->url);
if ($filePath) {
@unlink($filePath);
}
}
}
return true;
}
}
... ...
//修改上传的接口调用
require(['upload'], function (Upload) {
var _onUploadResponse = Upload.events.onUploadResponse;
Upload.events.onUploadResponse = function (response) {
try {
var ret = typeof response === 'object' ? response : JSON.parse(response);
if (ret.hasOwnProperty("code") && ret.hasOwnProperty("data")) {
return _onUploadResponse.call(this, response);
} else if (ret.hasOwnProperty("key") && !ret.hasOwnProperty("err_code")) {
ret.code = 1;
ret.data = {
url: '/' + ret.key
};
return _onUploadResponse.call(this, JSON.stringify(ret));
}
} catch (e) {
}
return _onUploadResponse.call(this, response);
};
});
\ No newline at end of file
... ...
<?php
return array (
0 =>
array (
'name' => 'app_key',
'title' => 'app_key',
'type' => 'string',
'content' =>
array (
),
'value' => '-5ozVJMiyjFqls8LWSXNciKa6rkedQBAxLyPazuJ',
'rule' => 'required',
'msg' => '',
'tip' => '请在个人中心 > 密钥管理中获取 > AK',
'ok' => '',
'extend' => '',
),
1 =>
array (
'name' => 'secret_key',
'title' => 'secret_key',
'type' => 'string',
'content' =>
array (
),
'value' => 'nztK57AGUF6TKhfftSviQdakMK0VCsPYwRwjBJDg',
'rule' => 'required',
'msg' => '',
'tip' => '请在个人中心 > 密钥管理中获取 > SK',
'ok' => '',
'extend' => '',
),
2 =>
array (
'name' => 'bucket',
'title' => 'bucket',
'type' => 'string',
'content' =>
array (
),
'value' => 'guoquestions',
'rule' => 'required',
'msg' => '',
'tip' => '存储空间名称',
'ok' => '',
'extend' => '',
),
3 =>
array (
'name' => 'uploadurl',
'title' => '上传接口地址',
'type' => 'select',
'content' =>
array (
'https://upload-z0.qiniup.com' => '华东 https://upload-z0.qiniup.com',
'https://upload-z1.qiniup.com' => '华北 https://upload-z1.qiniup.com',
'https://upload-z2.qiniup.com' => '华南 https://upload-z2.qiniup.com',
'https://upload-na0.qiniup.com' => '北美 https://upload-na0.qiniup.com',
'https://upload-as0.qiniup.com' => '东南亚 https://upload-as0.qiniup.com',
),
'value' => 'https://upload-z0.qiniup.com',
'rule' => 'required',
'msg' => '',
'tip' => '推荐选择最近的地址',
'ok' => '',
'extend' => '',
),
4 =>
array (
'name' => 'cdnurl',
'title' => 'CDN地址',
'type' => 'string',
'content' =>
array (
),
'value' => 'http://q3veqhmi6.bkt.clouddn.com',
'rule' => 'required',
'msg' => '',
'tip' => '未绑定CDN的话可使用七牛分配的测试域名',
'ok' => '',
'extend' => '',
),
5 =>
array (
'name' => 'notifyenabled',
'title' => '启用服务端回调',
'type' => 'bool',
'content' =>
array (
),
'value' => '0',
'rule' => '',
'msg' => '',
'tip' => '本地开发请禁用服务端回调',
'ok' => '',
'extend' => '',
),
6 =>
array (
'name' => 'notifyurl',
'title' => '回调通知地址',
'type' => 'string',
'content' =>
array (
),
'value' => 'http://www.yoursite.com/addons/qiniu/index/notify',
'rule' => '',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
7 =>
array (
'name' => 'uploadmode',
'title' => '上传模式',
'type' => 'select',
'content' =>
array (
'client' => '客户端直传(速度快,无备份)',
'server' => '服务器中转(占用服务器带宽,有备份)',
),
'value' => 'server',
'rule' => '',
'msg' => '',
'tip' => '启用服务器中转时务必配置操作员和密码',
'ok' => '',
'extend' => '',
),
8 =>
array (
'name' => 'savekey',
'title' => '保存文件名',
'type' => 'string',
'content' =>
array (
),
'value' => '/uploads/$(year)$(mon)$(day)/$(etag)$(ext)',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
9 =>
array (
'name' => 'expire',
'title' => '上传有效时长',
'type' => 'string',
'content' =>
array (
),
'value' => '600',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
10 =>
array (
'name' => 'maxsize',
'title' => '最大可上传',
'type' => 'string',
'content' =>
array (
),
'value' => '200M',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
11 =>
array (
'name' => 'mimetype',
'title' => '可上传后缀格式',
'type' => 'string',
'content' =>
array (
),
'value' => 'jpg,png,bmp,jpeg,gif,zip,rar,xls,xlsx',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
12 =>
array (
'name' => 'multiple',
'title' => '多文件上传',
'type' => 'bool',
'content' =>
array (
),
'value' => '1',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
13 =>
array (
'name' => 'syncdelete',
'title' => '附件删除时是否同步删除文件',
'type' => 'bool',
'content' =>
array (
),
'value' => '1',
'rule' => 'required',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
14 =>
array (
'name' => '__tips__',
'title' => '温馨提示',
'type' => '',
'content' =>
array (
),
'value' => '在使用之前请注册七牛账号并进行认证,注册链接:<a href="https://portal.qiniu.com/signup?code=3l79xtos9w9qq" target="_blank">https://portal.qiniu.com/signup?code=3l79xtos9w9qq</a>',
'rule' => '',
'msg' => '',
'tip' => '',
'ok' => '',
'extend' => '',
),
);
... ...
<?php
namespace addons\qiniu\controller;
use addons\qiniu\library\Auth;
use app\common\model\Attachment;
use think\addons\Controller;
use think\Config;
/**
* 七牛管理
*
*/
class Index extends Controller
{
public function index()
{
$this->error("当前插件暂无前台页面");
}
/**
* 上传接口
*/
public function upload()
{
Config::set('default_return_type', 'json');
if (!session('admin') && !$this->auth->id) {
$this->error("请登录后再进行操作");
}
$config = get_addon_config('qiniu');
$file = $this->request->file('file');
if (!$file || !$file->isValid()) {
$this->error("请上传有效的文件");
}
$fileInfo = $file->getInfo();
$filePath = $file->getRealPath() ?: $file->getPathname();
preg_match('/(\d+)(\w+)/', $config['maxsize'], $matches);
$type = strtolower($matches[2]);
$typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
$size = (int)$config['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
$suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
$suffix = $suffix ? $suffix : 'file';
$md5 = md5_file($filePath);
$search = ['$(year)', '$(mon)', '$(day)', '$(etag)', '$(ext)'];
$replace = [date("Y"), date("m"), date("d"), $md5, '.' . $suffix];
$object = ltrim(str_replace($search, $replace, $config['savekey']), '/');
$mimetypeArr = explode(',', strtolower($config['mimetype']));
$typeArr = explode('/', $fileInfo['type']);
//检查文件大小
if (!$file->checkSize($size)) {
$this->error("起过最大可上传文件限制");
}
//验证文件后缀
if ($config['mimetype'] !== '*' &&
(
!in_array($suffix, $mimetypeArr)
|| (stripos($typeArr[0] . '/', $config['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
)
) {
$this->error(__('上传格式限制'));
}
$savekey = '/' . $object;
$uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
$fileName = substr($savekey, strripos($savekey, '/') + 1);
//先上传到本地
$splInfo = $file->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
if ($splInfo) {
$extparam = $this->request->post();
$filePath = $splInfo->getRealPath() ?: $splInfo->getPathname();
$sha1 = sha1_file($filePath);
$imagewidth = $imageheight = 0;
if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
$imgInfo = getimagesize($splInfo->getPathname());
$imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
$imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
}
$params = array(
'admin_id' => session('admin.id'),
'user_id' => $this->auth->id,
'filesize' => $fileInfo['size'],
'imagewidth' => $imagewidth,
'imageheight' => $imageheight,
'imagetype' => $suffix,
'imageframes' => 0,
'mimetype' => $fileInfo['type'],
'url' => $uploadDir . $splInfo->getSaveName(),
'uploadtime' => time(),
'storage' => 'local',
'sha1' => $sha1,
'extparam' => json_encode($extparam),
);
$attachment = Attachment::create(array_filter($params), true);
$policy = array(
'saveKey' => ltrim($savekey, '/'),
);
$auth = new Auth($config['app_key'], $config['secret_key']);
$token = $auth->uploadToken($config['bucket'], null, $config['expire'], $policy);
$multipart = [
['name' => 'token', 'contents' => $token],
[
'name' => 'file',
'contents' => fopen($filePath, 'r'),
'filename' => $fileName,
]
];
try {
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', $config['uploadurl'], [
'multipart' => $multipart
]);
$code = $res->getStatusCode();
//成功不做任何操作
} catch (\GuzzleHttp\Exception\ClientException $e) {
$attachment->delete();
unlink($filePath);
$this->error("上传失败");
}
$url = '/' . $object;
//上传成功后将存储变更为qiniu
$attachment->storage = 'qiniu';
$attachment->save();
$this->success("上传成功", null, ['url' => $url]);
} else {
$this->error('上传失败');
}
return;
}
/**
* 通知回调
*/
public function notify()
{
$config = get_addon_config('qiniu');
$auth = new Auth($config['app_key'], $config['secret_key']);
$contentType = 'application/x-www-form-urlencoded';
$authorization = isset($_SERVER['HTTP_AUTHORIZATION']) ? $_SERVER['HTTP_AUTHORIZATION'] : '';
if (!$authorization && function_exists('apache_request_headers')) {
$headers = apache_request_headers();
$authorization = isset($headers['Authorization']) ? $headers['Authorization'] : '';
}
$url = $config['notifyurl'];
$body = file_get_contents('php://input');
$ret = $auth->verifyCallback($contentType, $authorization, $url, $body);
if ($ret) {
parse_str($body, $arr);
$admin_id = isset($arr['admin']) ? $arr['admin'] : 0;
$user_id = isset($arr['user']) ? $arr['user'] : 0;
$imageInfo = json_decode($arr['imageInfo'], true);
$params = array(
'admin_id' => (int)$admin_id,
'user_id' => (int)$user_id,
'filesize' => $arr['filesize'],
'imagewidth' => isset($imageInfo['width']) ? $imageInfo['width'] : 0,
'imageheight' => isset($imageInfo['height']) ? $imageInfo['height'] : 0,
'imagetype' => isset($imageInfo['format']) ? $imageInfo['format'] : '',
'imageframes' => 1,
'mimetype' => "image/" . (isset($imageInfo['format']) ? $imageInfo['format'] : ''),
'extparam' => '',
'url' => '/' . $arr['key'],
'uploadtime' => time(),
'storage' => 'qiniu'
);
Attachment::create($params);
return json(['ret' => 'success', 'code' => 1, 'data' => ['url' => $params['url']]]);
}
return json(['ret' => 'failed']);
}
}
... ...
name = qiniu
title = 七牛上传
intro = 使用七牛云存储,上传时直传七牛
author = Karson
website = https://www.fastadmin.net
version = 1.0.5
state = 1
url = /addons/qiniu.html
... ...
<?php
namespace addons\qiniu\library;
final class Auth
{
private $accessKey;
private $secretKey;
public function __construct($accessKey, $secretKey)
{
$this->accessKey = $accessKey;
$this->secretKey = $secretKey;
}
public function getAccessKey()
{
return $this->accessKey;
}
public function sign($data)
{
$hmac = hash_hmac('sha1', $data, $this->secretKey, true);
return $this->accessKey . ':' . $this->base64_urlSafeEncode($hmac);
}
public function signWithData($data)
{
$encodedData = $this->base64_urlSafeEncode($data);
return $this->sign($encodedData) . ':' . $encodedData;
}
public function signRequest($urlString, $body, $contentType = null)
{
$url = parse_url($urlString);
$data = '';
if (array_key_exists('path', $url)) {
$data = $url['path'];
}
if (array_key_exists('query', $url)) {
$data .= '?' . $url['query'];
}
$data .= "\n";
if ($body !== null && $contentType === 'application/x-www-form-urlencoded') {
$data .= $body;
}
return $this->sign($data);
}
public function verifyCallback($contentType, $originAuthorization, $url, $body)
{
$authorization = 'QBox ' . $this->signRequest($url, $body, $contentType);
return $originAuthorization === $authorization;
}
public function privateDownloadUrl($baseUrl, $expires = 3600)
{
$deadline = time() + $expires;
$pos = strpos($baseUrl, '?');
if ($pos !== false) {
$baseUrl .= '&e=';
} else {
$baseUrl .= '?e=';
}
$baseUrl .= $deadline;
$token = $this->sign($baseUrl);
return "$baseUrl&token=$token";
}
public function uploadToken($bucket, $key = null, $expires = 3600, $policy = null, $strictPolicy = true)
{
$deadline = time() + $expires;
$scope = $bucket;
if ($key !== null) {
$scope .= ':' . $key;
}
$args = self::copyPolicy($args, $policy, $strictPolicy);
$args['scope'] = $scope;
$args['deadline'] = $deadline;
$b = json_encode($args);
return $this->signWithData($b);
}
/**
* 上传策略,参数规格详见
* http://developer.qiniu.com/docs/v6/api/reference/security/put-policy.html
*/
private static $policyFields = array(
'callbackUrl',
'callbackBody',
'callbackHost',
'callbackBodyType',
'callbackFetchKey',
'returnUrl',
'returnBody',
'endUser',
'saveKey',
'insertOnly',
'detectMime',
'mimeLimit',
'fsizeMin',
'fsizeLimit',
'persistentOps',
'persistentNotifyUrl',
'persistentPipeline',
'deleteAfterDays',
'fileType',
'upHosts',
);
private static function copyPolicy(&$policy, $originPolicy, $strictPolicy)
{
if ($originPolicy === null) {
return array();
}
foreach ($originPolicy as $key => $value) {
if (!$strictPolicy || in_array((string)$key, self::$policyFields, true)) {
$policy[$key] = $value;
}
}
return $policy;
}
public function authorization($url, $body = null, $contentType = null)
{
$authorization = 'QBox ' . $this->signRequest($url, $body, $contentType);
return array('Authorization' => $authorization);
}
/**
* 对提供的数据进行urlsafe的base64编码。
*
* @param string $data 待编码的数据,一般为字符串
*
* @return string 编码后的字符串
* @link http://developer.qiniu.com/docs/v6/api/overview/appendix.html#urlsafe-base64
*/
function base64_urlSafeEncode($data)
{
$find = array('+', '/');
$replace = array('-', '_');
return str_replace($find, $replace, base64_encode($data));
}
/**
* 对提供的urlsafe的base64编码的数据进行解码
*
* @param string $str 待解码的数据,一般为字符串
*
* @return string 解码后的字符串
*/
function base64_urlSafeDecode($str)
{
$find = array('-', '_');
$replace = array('+', '/');
return base64_decode(str_replace($find, $replace, $str));
}
}
... ...
<?php
namespace app\admin\controller;
use app\common\controller\Backend;
use think\Db;
/**
* 老师管理
*
* @icon fa fa-circle-o
*/
class Teacher extends Backend
{
/**
* Teacher模型对象
* @var \app\admin\model\Teacher
*/
protected $model = null;
public function _initialize()
{
parent::_initialize();
$this->model = new \app\admin\model\Teacher;
}
/**
* 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
* 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
* 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
*/
/**
* 查看
*/
public function index()
{
//当前是否为关联查询
$this->relationSearch = true;
//设置过滤方法
$this->request->filter(['strip_tags', 'trim']);
if ($this->request->isAjax())
{
//如果发送的来源是Selectpage,则转发到Selectpage
if ($this->request->request('keyField'))
{
return $this->selectpage();
}
list($where, $sort, $order, $offset, $limit) = $this->buildparams();
$total = $this->model
->with(['user'])
->where($where)
->order($sort, $order)
->count();
$list = $this->model
->with(['user'])
->where($where)
->order($sort, $order)
->limit($offset, $limit)
->select();
foreach ($list as $row) {
$row->territory_id = explode(',',$row['territory_id']);
$row->getRelation('user')->visible(['nickname']);
}
$list = collection($list)->toArray();
foreach ($list as &$v){
$v['territory_id'] = Db::name('territory')
->alias('a')
->join('contype c','a.contype_id = c.id')
->whereIn('a.id',$v['territory_id'])
->column('c.title');
}
$result = array("total" => $total, "rows" => $list);
return json($result);
}
return $this->view->fetch();
}
/**
* 编辑
*/
public function edit($ids = null)
{
$row = $this->model->get($ids);
if (!$row) {
$this->error(__('No Results were found'));
}
$adminIds = $this->getDataLimitAdminIds();
if (is_array($adminIds)) {
if (!in_array($row[$this->dataLimitField], $adminIds)) {
$this->error(__('You have no permission'));
}
}
if ($this->request->isPost()) {
$params = $this->request->post("row/a");
if ($params) {
$params = $this->preExcludeFields($params);
$result = false;
Db::startTrans();
try {
//是否采用模型验证
if ($this->modelValidate) {
$name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
$validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
$row->validateFailException(true)->validate($validate);
}
$result = $row->allowField(true)->save($params);
Db::commit();
} catch (ValidateException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (PDOException $e) {
Db::rollback();
$this->error($e->getMessage());
} catch (Exception $e) {
Db::rollback();
$this->error($e->getMessage());
}
if ($result !== false) {
$this->success();
} else {
$this->error(__('No rows were updated'));
}
}
$this->error(__('Parameter %s can not be empty', ''));
}
$this->view->assign("row", $row);
return $this->view->fetch();
}
}
... ...
<?php
return [
'Id' => 'ID',
'User_id' => '用户ID',
'Name' => '真实姓名',
'Sex' => '性别',
'Birth' => '出生日期',
'Idcard' => '身份证号',
'Before' => '身份证正面',
'Behind' => '身份证反面',
'Phone' => '手机号',
'Thumbnail' => '头像',
'Address' => '常住地',
'Honor' => '头衔',
'Content' => '个人履历',
'Show' => '展示在最前',
'Desc' => '个人简历',
'Online' => '在线时段',
'Status' => '状态',
'Territory_id' => '擅长领域ID',
'Help_num' => '帮助人数',
'Level' => '星级',
'Createtime' => '创建时间',
'Updatetime' => '修改时间',
'User.nickname' => '昵称'
];
... ...
<?php
namespace app\admin\model;
use think\Model;
class Teacher extends Model
{
// 表名
protected $name = 'teacher';
// 自动写入时间戳字段
protected $autoWriteTimestamp = 'int';
// 定义时间戳字段名
protected $createTime = 'createtime';
protected $updateTime = 'updatetime';
protected $deleteTime = false;
// 追加属性
protected $append = [
'onlinetime_text'
];
public function getOnlinetimeTextAttr($value, $data)
{
$value = $value ? $value : (isset($data['onlinetime']) ? $data['onlinetime'] : '');
return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
}
protected function setOnlinetimeAttr($value)
{
return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
}
public function user()
{
return $this->belongsTo('User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
}
}
... ...
<?php
namespace app\admin\validate;
use think\Validate;
class Teacher extends Validate
{
/**
* 验证规则
*/
protected $rule = [
];
/**
* 提示消息
*/
protected $message = [
];
/**
* 验证场景
*/
protected $scene = [
'add' => [],
'edit' => [],
];
}
... ...
<form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('User_id')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-user_id" data-rule="required" data-source="user/user/index" data-field="nickname" class="form-control selectpage" name="row[user_id]" type="text" value="">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Name')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-name" class="form-control" name="row[name]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Sex')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-sex" class="form-control" name="row[sex]" type="number" value="1">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Birth')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-birth" class="form-control" name="row[birth]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Idcard')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-idcard" class="form-control" name="row[idcard]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Before')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-before" class="form-control" name="row[before]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Behind')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-behind" class="form-control" name="row[behind]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Phone')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-phone" class="form-control" name="row[phone]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Thumbnail')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-thumbnail" class="form-control" name="row[thumbnail]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Address')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-address" class="form-control" name="row[address]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Honor')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-honor" class="form-control" name="row[honor]" type="text">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Content')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-content" class="form-control editor" rows="5" name="row[content]" cols="50"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Show')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-show" class="form-control " rows="5" name="row[show]" cols="50"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Desc')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-desc" class="form-control " rows="5" name="row[desc]" cols="50"></textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Onlinetime')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-onlinetime" class="form-control datetimepicker" data-date-format="YYYY-MM-DD HH:mm:ss" data-use-current="true" name="row[onlinetime]" type="text" value="{:date('Y-m-d H:i:s')}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Status')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-status" class="form-control" name="row[status]" type="number" value="0">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Territory_id')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-territory_id" data-rule="required" data-source="territory/index" class="form-control selectpage" name="row[territory_id]" type="text" value="">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Help_num')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-help_num" class="form-control" name="row[help_num]" type="number" value="0">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Level')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-level" class="form-control" name="row[level]" type="number" value="0">
</div>
</div>
<div class="form-group layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
... ...
<form id="edit-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Name')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-name" class="form-control" name="row[name]" type="text" value="{$row.name|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Sex')}:</label>
<div class="col-xs-12 col-sm-8">
{:build_radios('row[sex]', ['1'=>__('男'), '2'=>__('女')], $row['sex'])}
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Birth')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-birth" class="form-control" name="row[birth]" type="text" value="{$row.birth|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Idcard')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-idcard" class="form-control" name="row[idcard]" type="text" value="{$row.idcard|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Before')}:</label>
<div class="col-xs-12 col-sm-8">
<div class="input-group">
<input id="c-before" data-rule="required" class="form-control" size="35" name="row[before]" type="text" value="{$row.before}">
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="plupload-before" class="btn btn-danger plupload" data-input-id="c-before" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="false" data-preview-id="p-before"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
<span><button type="button" id="fachoose-before" class="btn btn-primary fachoose" data-input-id="c-before" data-mimetype="image/*" data-multiple="false"><i class="fa fa-list"></i> {:__('Choose')}</button></span>
</div>
<span class="msg-box n-right"></span>
</div>
<ul class="row list-inline plupload-preview" id="p-before"></ul>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Behind')}:</label>
<div class="col-xs-12 col-sm-8">
<div class="input-group">
<input id="c-behind" data-rule="required" class="form-control" size="35" name="row[behind]" type="text" value="{$row.behind}">
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="plupload-behind" class="btn btn-danger plupload" data-input-id="c-behind" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="false" data-preview-id="p-behind"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
<span><button type="button" id="fachoose-behind" class="btn btn-primary fachoose" data-input-id="c-behind" data-mimetype="image/*" data-multiple="false"><i class="fa fa-list"></i> {:__('Choose')}</button></span>
</div>
<span class="msg-box n-right"></span>
</div>
<ul class="row list-inline plupload-preview" id="p-behind"></ul>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Phone')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-phone" class="form-control" name="row[phone]" type="text" value="{$row.phone|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Thumbnail')}:</label>
<div class="col-xs-12 col-sm-8">
<div class="input-group">
<input id="c-thumbnail" data-rule="required" class="form-control" size="35" name="row[thumbnail]" type="text" value="{$row.thumbnail}">
<div class="input-group-addon no-border no-padding">
<span><button type="button" id="plupload-thumbnail" class="btn btn-danger plupload" data-input-id="c-thumbnail" data-mimetype="image/gif,image/jpeg,image/png,image/jpg,image/bmp" data-multiple="false" data-preview-id="p-thumbnail"><i class="fa fa-upload"></i> {:__('Upload')}</button></span>
<span><button type="button" id="fachoose-thumbnail" class="btn btn-primary fachoose" data-input-id="c-thumbnail" data-mimetype="image/*" data-multiple="false"><i class="fa fa-list"></i> {:__('Choose')}</button></span>
</div>
<span class="msg-box n-right"></span>
</div>
<ul class="row list-inline plupload-preview" id="p-thumbnail"></ul>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Address')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-address" class="form-control" name="row[address]" type="text" value="{$row.address|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Honor')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-honor" class="form-control" name="row[honor]" type="text" value="{$row.honor|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Content')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-content" class="form-control editor" rows="5" name="row[content]" cols="50">{$row.content|htmlentities}</textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Show')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-show" class="form-control " rows="5" name="row[show]" cols="50">{$row.show|htmlentities}</textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Desc')}:</label>
<div class="col-xs-12 col-sm-8">
<textarea id="c-desc" class="form-control " rows="5" name="row[desc]" cols="50">{$row.desc|htmlentities}</textarea>
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Online')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-online" class="form-control" name="row[online]" type="text" value="{$row.online|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Status')}:</label>
<div class="col-xs-12 col-sm-8">
{:build_radios('row[status]', ['1'=>__('审核通过'), '2'=>__('审核未通过')], $row['status'])}
</div>
</div>
<!--<div class="form-group">-->
<!--<label class="control-label col-xs-12 col-sm-2">{:__('Territory_id')}:</label>-->
<!--<div class="col-xs-12 col-sm-8">-->
<!--<input id="c-territory_id" data-rule="required" data-source="territory/index" class="form-control selectpage" name="row[territory_id]" type="text" value="{$row.territory_id|htmlentities}">-->
<!--</div>-->
<!--</div>-->
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Help_num')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-help_num" class="form-control" name="row[help_num]" type="number" value="{$row.help_num|htmlentities}">
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-12 col-sm-2">{:__('Level')}:</label>
<div class="col-xs-12 col-sm-8">
<input id="c-level" class="form-control" name="row[level]" type="number" value="{$row.level|htmlentities}">
</div>
</div>
<div class="form-group layer-footer">
<label class="control-label col-xs-12 col-sm-2"></label>
<div class="col-xs-12 col-sm-8">
<button type="submit" class="btn btn-success btn-embossed disabled">{:__('OK')}</button>
<button type="reset" class="btn btn-default btn-embossed">{:__('Reset')}</button>
</div>
</div>
</form>
... ...
<div class="panel panel-default panel-intro">
{:build_heading()}
<div class="panel-body">
<div id="myTabContent" class="tab-content">
<div class="tab-pane fade active in" id="one">
<div class="widget-body no-padding">
<div id="toolbar" class="toolbar">
<a href="javascript:;" class="btn btn-primary btn-refresh" title="{:__('Refresh')}" ><i class="fa fa-refresh"></i> </a>
<!--<a href="javascript:;" class="btn btn-success btn-add {:$auth->check('teacher/add')?'':'hide'}" title="{:__('Add')}" ><i class="fa fa-plus"></i> {:__('Add')}</a>-->
<a href="javascript:;" class="btn btn-success btn-edit btn-disabled disabled {:$auth->check('teacher/edit')?'':'hide'}" title="{:__('Edit')}" ><i class="fa fa-pencil"></i> {:__('Edit')}</a>
<a href="javascript:;" class="btn btn-danger btn-del btn-disabled disabled {:$auth->check('teacher/del')?'':'hide'}" title="{:__('Delete')}" ><i class="fa fa-trash"></i> {:__('Delete')}</a>
<a href="javascript:;" class="btn btn-danger btn-import {:$auth->check('teacher/import')?'':'hide'}" title="{:__('Import')}" id="btn-import-file" data-url="ajax/upload" data-mimetype="csv,xls,xlsx" data-multiple="false"><i class="fa fa-upload"></i> {:__('Import')}</a>
<div class="dropdown btn-group {:$auth->check('teacher/multi')?'':'hide'}">
<a class="btn btn-primary btn-more dropdown-toggle btn-disabled disabled" data-toggle="dropdown"><i class="fa fa-cog"></i> {:__('More')}</a>
<ul class="dropdown-menu text-left" role="menu">
<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=normal"><i class="fa fa-eye"></i> {:__('Set to normal')}</a></li>
<li><a class="btn btn-link btn-multi btn-disabled disabled" href="javascript:;" data-params="status=hidden"><i class="fa fa-eye-slash"></i> {:__('Set to hidden')}</a></li>
</ul>
</div>
</div>
<table id="table" class="table table-striped table-bordered table-hover table-nowrap"
data-operate-edit="{:$auth->check('teacher/edit')}"
data-operate-del="{:$auth->check('teacher/del')}"
width="100%">
</table>
</div>
</div>
</div>
</div>
</div>
... ...
... ... @@ -155,12 +155,12 @@ function generateCode($length = 6) {
*/
function send_sms($data){
//todo 短信账号密码
require_once EXTEND_PATH . 'nsms/nsms.php';
// require_once EXTEND_PATH . 'nsms/nsms.php';
$url = "http://www.ztsms.cn/sendNSms.do";
$username = '';
$password = '';
$username = 'xiaoweiwenwen';
$password = 'Cxz307312';
$sendAPI = new nsms($url, $username, $password);
$sendAPI->data = $data;/*初始化数据包*/
$return = $sendAPI->sendSMS('GET');
$return = $sendAPI->sendSMS('POST');
return $return;
}
\ No newline at end of file
... ...
... ... @@ -9,13 +9,15 @@ use fast\Random;
use think\Config;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;
use think\Cache;
use think\Validate;
/**
* 公共接口
*/
class Common extends Api
{
protected $noNeedLogin = ['init'];
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
/**
... ... @@ -66,11 +68,12 @@ class Common extends Api
$this->error('未检出文件上传');
}
$countFile = count($files);
if($countFile > 5) {
if($countFile > 9) {
$this->error('最多上传5张图片');
}
$url2 = '';
$host = "http://q3fjhcx63.bkt.clouddn.com"; //七牛云地址
// $fan = '';
$host = "http://q3veqhmi6.bkt.clouddn.com";
foreach ($files as $file){
//移动到框架应用根目录/public/uploads/ 目录下
$moveUrl = ROOT_PATH . 'public' . DS . 'uploads';
... ... @@ -122,4 +125,87 @@ class Common extends Api
}
return $os_str;
}
/**
* @ApiTitle (获取验证码)
* @ApiSummary (获取验证码)
* @ApiMethod (POST)
* @ApiRoute (/api/common/getcode)
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
*
* @ApiParams (name="phone", type="string", required=false, description="手机号")
*
* @ApiReturn({
"code": 1,
"msg": "SUCCESS",
"time": "1553839125",
"data": {
}
})
*/
public function getcode()
{
$phone = $this->request->param('phone');
if (empty($phone)) {
$this->error(['code' => 40005, 'msg' => '手机号不能为空']);
}
if (!preg_match('/^1[0-9]{10}$/', $phone)) {
$this->error(['code' => 40005, 'msg' => "请输入正确的手机格式!"]);
}
//生成验证码
$number = generateCode();
//发送验证码
$data = array(
'content' => "【小微问问】提醒您,您的验证码是:" .$number.",十分钟之内有效,请勿向他人泄漏您的验证码",//短信内容
'mobile' => $phone,//手机号码
'productid' => '676767',//产品id
'xh' => ''//小号
);
$result = send_sms($data);
if (substr($result, 0, strpos($result, ',')) != "1") {
$this->error(['code' => 42001, 'msg' => $result]);
}
Cache::set($phone,$number,600);
$this->success('SUCCESS');
}
/**
* @ApiTitle (验证验证码)
* @ApiSummary (验证验证码)
* @ApiMethod (POST)
* @ApiRoute (/api/common/verify)
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
*
* @ApiParams (name="phone", type="string", required=true, description="手机号")
* @ApiParams (name="code", type="string", required=true, description="验证码")
*
* @ApiReturn({
"code": 1,
"msg": "SUCCESS",
"time": "1553839125",
"data": {
}
})
*/
public function verify()
{
$param = $this->request->param();
$validate = new Validate([
'phone' => 'require|max:11',
'code'=>'require'
]);
if (!$validate->check($param)) {
$this->error(['code'=>40005,'msg'=>$validate->getError()]);
}
$code = Cache::get($param['phone']);
if($param['code'] == $code){
$this->success('SUCCESS');
}else{
$this->error('验证码错误或者失效,请重新发送');
}
}
}
... ...
<?php
namespace app\api\controller;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\common\model\User;
use think\Hook;
/**
* 手机短信接口
*/
class Sms extends Api
{
protected $noNeedLogin = '*';
protected $noNeedRight = '*';
/**
* 发送验证码
*
* @param string $mobile 手机号
* @param string $event 事件名称
*/
public function send()
{
$mobile = $this->request->request("mobile");
$event = $this->request->request("event");
$event = $event ? $event : 'register';
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
$last = Smslib::get($mobile, $event);
if ($last && time() - $last['createtime'] < 60) {
$this->error(__('发送频繁'));
}
$ipSendTotal = \app\common\model\Sms::where(['ip' => $this->request->ip()])->whereTime('createtime', '-1 hours')->count();
if ($ipSendTotal >= 5) {
$this->error(__('发送频繁'));
}
if ($event) {
$userinfo = User::getByMobile($mobile);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changemobile']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
if (!Hook::get('sms_send')) {
$this->error(__('请在后台插件管理安装短信验证插件'));
}
$ret = Smslib::send($mobile, null, $event);
if ($ret) {
$this->success(__('发送成功'));
} else {
$this->error(__('发送失败,请检查短信配置是否正确'));
}
}
/**
* 检测验证码
*
* @param string $mobile 手机号
* @param string $event 事件名称
* @param string $captcha 验证码
*/
public function check()
{
$mobile = $this->request->request("mobile");
$event = $this->request->request("event");
$event = $event ? $event : 'register';
$captcha = $this->request->request("captcha");
if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
$this->error(__('手机号不正确'));
}
if ($event) {
$userinfo = User::getByMobile($mobile);
if ($event == 'register' && $userinfo) {
//已被注册
$this->error(__('已被注册'));
} elseif (in_array($event, ['changemobile']) && $userinfo) {
//被占用
$this->error(__('已被占用'));
} elseif (in_array($event, ['changepwd', 'resetpwd']) && !$userinfo) {
//未注册
$this->error(__('未注册'));
}
}
$ret = Smslib::check($mobile, $captcha, $event);
if ($ret) {
$this->success(__('成功'));
} else {
$this->error(__('验证码不正确'));
}
}
}
... ... @@ -19,6 +19,75 @@ use think\Validate;
class Teacher extends Api
{
/**
* @ApiTitle (成为老师表单提交)
* @ApiSummary (成为老师表单提交)
* @ApiMethod (POST)
* @ApiRoute (/api/teacher/become)
*
* @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
*
* @ApiParams (name="name", type="string", required=true, description="真实姓名")
* @ApiParams (name="sex", type="int", required=true, description="性别(1男2女)")
* @ApiParams (name="birth", type="string", required=true, description="出生日期")
* @ApiParams (name="idcard", type="string", required=true, description="身份证号")
* @ApiParams (name="before", type="string", required=true, description="身份证正面")
* @ApiParams (name="behind", type="string", required=true, description="身份证反面")
* @ApiParams (name="phone", type="string", required=true, description="手机号")
* @ApiParams (name="thumbnail", type="string", required=true, description="头像")
* @ApiParams (name="address", type="string", required=true, description="常住地")
* @ApiParams (name="honor", type="string", required=true, description="头衔")
* @ApiParams (name="content", type="string", required=true, description="个人履历")
* @ApiParams (name="show", type="string", required=true, description="展示在最前")
* @ApiParams (name="desc", type="string", required=true, description="个人简历")
* @ApiParams (name="online", type="string", required=true, description="在线时段")
* @ApiParams (name="territory_id", type="string", required=true, description="擅长领域ID")
*
*
* @ApiReturn({
"code": 1,
"msg": "成功",
"time": "1571492001",
"data": {
}
})
*/
public function become()
{
$param = $this->request->param();
$param['user_id'] = $this->getUserId();
$validate = new Validate([
'name' => 'require',
'sex' => 'require',
'birth' => 'require',
'idcard'=>'require',
'before'=>'require',
'behind'=>'require',
'phone'=>'require',
'thumbnail'=>'require',
'address'=>'require',
'honor'=>'require',
'content'=>'require',
'show'=>'require',
'desc'=>'require',
'online'=>'require',
'territory_id'=>"require"
]);
if (!$validate->check($param)) {
$this->error($validate->getError());
}
$param['createtime'] = time();
$data = Db::name('teacher')->insertGetId($param);
if(empty($data)){
$this->error('提交失败');
}else{
$this->success('提交成功');
}
}
/**
* @ApiTitle (新赠擅长领域)
* @ApiSummary (新赠擅长领域)
* @ApiMethod (POST)
... ...
... ... @@ -4,6 +4,18 @@ return array (
'autoload' => false,
'hooks' =>
array (
'admin_login_init' =>
array (
0 => 'loginbg',
),
'upload_config_init' =>
array (
0 => 'qiniu',
),
'upload_delete' =>
array (
0 => 'qiniu',
),
),
'route' =>
array (
... ...
<?php
namespace app\nsms;
date_default_timezone_set('PRC');//设置时区
/**
* 发送API
* demo仅供参考,demo最低运行环境PHP5.3
* 请确认开启PHP CURL 扩展
*/
class nsms {
public $data; //发送数据
public $timeout = 30; //超时
private $apiUrl; //发送地址
private $username; //用户名
private $password; //密码
function __construct($url, $username, $password) {
$this->apiUrl = $url;
$this->username = $username;
$this->password = $password;
}
private function httpGet() {
$url = $this->apiUrl . '?' . http_build_query($this->data);
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_URL, $url);
$res = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Error GET '.curl_error($curl);
}
curl_close($curl);
return $res;
}
private function httpPost(){ // 模拟提交数据函数
$curl = curl_init(); // 启动一个CURL会话
curl_setopt($curl, CURLOPT_URL, $this->apiUrl); // 要访问的地址
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 对认证证书来源的检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); // 从证书中检查SSL加密算法是否存在
curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
curl_setopt($curl, CURLOPT_POST, true); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($this->data)); // Post提交的数据包
curl_setopt($curl, CURLOPT_TIMEOUT, $this->timeout); // 设置超时限制防止死循环
curl_setopt($curl, CURLOPT_HEADER, false); // 显示返回的Header区域内容
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); // 获取的信息以文件流的形式返回
$result = curl_exec($curl); // 执行操作
if (curl_errno($curl)) {
echo 'Error POST'.curl_error($curl);
}
curl_close($curl); // 关键CURL会话
return $result; // 返回数据
}
/**
* @param $type|提交类型 POST/GET
* @param $isTranscoding|是否需要转 $isTranscoding 是否需要转utf-8 默认 false
* @return mixed
*/
public function sendSMS($type, $isTranscoding = false) {
$this->data['content'] = $isTranscoding === true ? mb_convert_encoding($this->data['content'], "UTF-8") : $this->data['content'];
$this->data['username'] = $this->username;
$this->data['tkey'] = date('YmdHis');
$this->data['password'] = md5(md5($this->password) . $this->data['tkey']);
return $type == "POST" ? $this->httpPost() : $this->httpGet();
}
}
\ No newline at end of file
... ...
此 diff 太大无法显示。
define([], function () {
//修改上传的接口调用
require(['upload'], function (Upload) {
var _onUploadResponse = Upload.events.onUploadResponse;
Upload.events.onUploadResponse = function (response) {
try {
var ret = typeof response === 'object' ? response : JSON.parse(response);
if (ret.hasOwnProperty("code") && ret.hasOwnProperty("data")) {
return _onUploadResponse.call(this, response);
} else if (ret.hasOwnProperty("key") && !ret.hasOwnProperty("err_code")) {
ret.code = 1;
ret.data = {
url: '/' + ret.key
};
return _onUploadResponse.call(this, JSON.stringify(ret));
}
} catch (e) {
}
return _onUploadResponse.call(this, response);
};
});
});
\ No newline at end of file
... ...
define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {
var Controller = {
index: function () {
// 初始化表格参数配置
Table.api.init({
extend: {
index_url: 'teacher/index' + location.search,
add_url: 'teacher/add',
edit_url: 'teacher/edit',
del_url: 'teacher/del',
multi_url: 'teacher/multi',
table: 'teacher',
}
});
var table = $("#table");
// 初始化表格
table.bootstrapTable({
url: $.fn.bootstrapTable.defaults.extend.index_url,
pk: 'id',
sortName: 'id',
columns: [
[
{checkbox: true},
{field: 'id', title: __('Id'), operate:false},
{field: 'user.nickname', title: __('User.nickname'), operate:false},
{field: 'name', title: __('Name'), operate:false},
{field: 'sex', title: __('Sex'),formatter: Table.api.formatter.label,searchList:{'1': '男','2':'女'}},
{field: 'birth', title: __('Birth'), operate:false},
{field: 'idcard', title: __('Idcard'), operate:false},
{field: 'before', title: __('Before'), operate:false, events: Table.api.events.image, formatter: Table.api.formatter.image},
{field: 'behind', title: __('Behind'), operate:false, events: Table.api.events.image, formatter: Table.api.formatter.image},
{field: 'phone', title: __('Phone'), operate:false},
{field: 'thumbnail', title: __('Thumbnail'), operate:false, events: Table.api.events.image, formatter: Table.api.formatter.image},
{field: 'address', title: __('Address'), operate:false},
{field: 'honor', title: __('Honor'), operate:false},
{field: 'online', title: __('Online'), operate:false},
{field: 'status', title: __('Status'),formatter: Table.api.formatter.status,custom: {1:'success', 2:'error'},searchList:{'0':'待审核','1': '审核通过','2':'审核未通过'}},
{field: 'territory_id', title: __('Territory_id'), operate:false},
{field: 'help_num', title: __('Help_num'), operate:false},
{field: 'level', title: __('Level'), operate:false},
{field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
{field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
{field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate}
]
]
});
// 为表格绑定事件
Table.api.bindevent(table);
},
add: function () {
Controller.api.bindevent();
},
edit: function () {
Controller.api.bindevent();
},
api: {
bindevent: function () {
Form.api.bindevent($("form[role=form]"));
}
}
};
return Controller;
});
\ No newline at end of file
... ...