Initial commit

main
liutk 2024-03-12 14:38:01 +08:00
commit 5e8037666a
360 changed files with 23629 additions and 0 deletions

18
.editorconfig 100644
View File

@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[docker-compose.yml]
indent_size = 4

59
.env.example 100644
View File

@ -0,0 +1,59 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
LOG_CHANNEL=stack
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
BROADCAST_DRIVER=log
CACHE_DRIVER=file
FILESYSTEM_DISK=local
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120
MEMCACHED_HOST=127.0.0.1
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=
PUSHER_HOST=
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=mt1
VITE_APP_NAME="${APP_NAME}"
VITE_PUSHER_APP_KEY="${PUSHER_APP_KEY}"
VITE_PUSHER_HOST="${PUSHER_HOST}"
VITE_PUSHER_PORT="${PUSHER_PORT}"
VITE_PUSHER_SCHEME="${PUSHER_SCHEME}"
VITE_PUSHER_APP_CLUSTER="${PUSHER_APP_CLUSTER}"

11
.gitattributes vendored 100644
View File

@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore

19
.gitignore vendored 100644
View File

@ -0,0 +1,19 @@
/.phpunit.cache
/node_modules
/public/build
/public/hot
/public/storage
/storage/*.key
/vendor
.env
.env.backup
.env.production
.phpunit.result.cache
Homestead.json
Homestead.yaml
auth.json
npm-debug.log
yarn-error.log
/.fleet
/.idea
/.vscode

66
README.md 100644
View File

@ -0,0 +1,66 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
## About Laravel
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
You may also try the [Laravel Bootcamp](https://bootcamp.laravel.com), where you will be guided through building a modern Laravel application from scratch.
If you don't feel like reading, [Laracasts](https://laracasts.com) can help. Laracasts contains over 2000 video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
## Laravel Sponsors
We would like to extend our thanks to the following sponsors for funding Laravel development. If you are interested in becoming a sponsor, please visit the [Laravel Partners program](https://partners.laravel.com).
### Premium Partners
- **[Vehikl](https://vehikl.com/)**
- **[Tighten Co.](https://tighten.co)**
- **[WebReinvent](https://webreinvent.com/)**
- **[Kirschbaum Development Group](https://kirschbaumdevelopment.com)**
- **[64 Robots](https://64robots.com)**
- **[Curotec](https://www.curotec.com/services/technologies/laravel/)**
- **[Cyber-Duck](https://cyber-duck.co.uk)**
- **[DevSquad](https://devsquad.com/hire-laravel-developers)**
- **[Jump24](https://jump24.co.uk)**
- **[Redberry](https://redberry.international/laravel/)**
- **[Active Logic](https://activelogic.com)**
- **[byte5](https://byte5.de)**
- **[OP.GG](https://op.gg)**
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).

View File

@ -0,0 +1,281 @@
<?php
namespace App\Admin;
use App\Models\Keyword;
use Slowlyo\OwlAdmin\Renderers\BaseRenderer;
use Slowlyo\OwlAdmin\Renderers\WangEditor;
class Components extends BaseRenderer {
/**
* 父级选择器
*/
public function parentControl($apiUrl = null, $name ='parent_id', $label = null, $labelField = 'name', $valueField = 'id')
{
return amisMake()->TreeSelectControl()->source($apiUrl)
->name($name)->label($label ?? __('admin.components.parent_select'))
->showIcon(false)
->labelField($labelField)
->valueField($valueField);
}
/**
* 排序字段
*/
public function sortControl($name ='sort', $label = null){
return amisMake()->NumberControl()
->name($name)->label($label ?? __('admin.components.order'))
->displayMode('enhance')
->value(0)
->min(0);
}
/**
* 2位小数输入框
*/
public function decimalControl($name ='decimal', $label = null){
return amisMake()->NumberControl()
->name($name)->label($label ?? __('admin.components.decimal'))
->kilobitSeparator(true)
->percision(2)
->step(0.01)
->value(0.00)
->min(0);
}
/**
* 富文本编辑器
*/
public function fuEditorControl($name ='content', $label = null, $height = 530)
{
return WangEditor::make()
->name($name)->label($label ?? __('admin.components.content'))
->height($height)
->excludeKeys(['group-video']);
}
/**
* 开关
*/
public function enableControl($name = 'is_enable', $label= null, $mode = 'horizontal'){
return amisMake()->SwitchControl()
->name($name)->label($label ?? __('admin.components.status'))
->mode($mode)
->onText(__('admin.components.status_map.enabled'))->offText(__('admin.components.status_map.disabled'));
}
/**
* 图片上传
*/
public function imageControl($name, $label){
return amis()->ImageControl($name, $label)
->joinValues(false)
->autoUpload(true)->maxSize('5*1024*1024');//不能大于5M
}
/**
* 图片上传,带裁剪
*/
public function cropImageControl($name, $label, $aspectRatio = null){
$cropImage = amis()->ImageControl($name, $label)->joinValues(false);
// if($aspectRatio){
$cropImage->crop([
'aspectRatio' => $aspectRatio ?? 1
]);
// }
$cropImage->autoUpload(true);
return $cropImage;
}
/**
* 普通文件上传
*/
public function fileControl($name, $label, $accept = '.txt', $multiple = false){
return amis()->FileControl($name, $label ?? __('admin.components.files'))
->multiple($multiple)
->joinValues(false)
->useChunk(false)
->maxSize(20*1024*1024)
->accept($accept);
}
public function chunkFileControl($name, $label, $accept = '*', $multiple = false){
return amis()->FileControl($name, $label ?? __('admin.components.files'))
->multiple($multiple)
->joinValues(false)
->useChunk(true)
->accept($accept)
->startChunkApi(admin_url('start_chunk_upload_file'))
->chunkApi(admin_url('save_chunk_upload_file'))
->finishChunkApi(admin_url('finish_chunk_upload_file'));
}
/**
* 标签选择
*/
public function keywordsTagControl($name = 'tags', $label= null, $pKey = null){
return amisMake()->TagControl()
->name($name)->label($label ?? __('admin.components.tag'))
->maxTagLength(0)
->options(Keyword::where('parent_key', $pKey)->pluck('name', 'id')->toArray());
}
public function keywordsTag($label = null, $color = null){
if($color){
$tag = amisMake()->Tag()->label($label ?? __('admin.components.tag'))
->displayMode('rounded')->style([
'color' => '#fff',
'backgroundColor' =>$color,
'borderColor' => $color
]);
}else{
$tag = amisMake()->Tag()->label($label ?? __('admin.components.tag'))
->displayMode('rounded')->color('inactive');
}
return $tag;
}
/**
* 生成统计图config
* 折线图或者柱状图
*/
public function chartLineBarConfig($title = null, array $x , array $y){
$yAxisData = [];
$seriesData = [];
$color = [];
if(!isset($y[0])){
$_y = $y;
$y = [0=>$_y];
}
$i = 0;
$tips = '{b0}';
foreach($y as $item) {
//调色盘
$color[] = $item['color'];
//tips
$tips.= '<br/> {a'.$i.'}: {c'.$i.'}'.($item['unit'] ?? '');
//纵坐标
$yAxisData[] = [
'name'=>($item['unit'] ?? ''),
'type' =>'value',
'axisTick' => true,
'alignTicks' => true,
'axisLine' => [
'show' => true,
'lineStyle' => [
'color' => $item['color'] ?? ''
]
],
'axisLabel'=> [
'formatter'=>'{value} '
]
];
//数据
$_series = [
'name' => $item['name'] ?? '',
'data' => $item['data'] ?? [],
'type' => $item['type'] ?? 'line',
'yAxisIndex' => $i,
];
switch($item['type']){
case 'line':
$_series = array_merge($_series, [
'smooth'=> true,
'symbol'=> 'none',
'lineStyle' => [
'color' => $item['color'] ?? ''
],
'areaStyle' => [
'color' => $item['color'] ?? ''
],
]);
break;
case 'bar':
$_series = array_merge($_series, [
]);
break;
}
$seriesData[] = $_series;
$i++;
}
return [
'color' => $color,
'title' => [
'text' => $title,
],
"tooltip" => [//提示
'trigger'=>'axis',//坐标轴触发
'axisPointer' => [
'type' => 'cross'
],
// 'formatter' => $tips
],
'grid' => [
'left' => '8%',
'right' => '8%',
],
'xAxis' => [
'type' => 'category',
'data' => $x,
],
'yAxis' => $yAxisData,
'series' => $seriesData
];
}
/**
* 散点图
*/
public function chartScatterConfig($title = null, array $x , array $y, array $yData = null){
$yAxisData = [];
$seriesData = [];
$color = [];
if($yData){
$yAxisData = [
'type' =>'category',
// 'splitLine'=>[
// 'show'=>true,
// 'lineStyle'=>[
// 'type'=>'dashed'
// ]
// ],
'axisTick' => [
'alignWithLabel'=>true
],
'data'=> $yData
];
}
$seriesData = $y;
return [
'color' => $color,
'title' => [
'text' => $title,
],
"tooltip" => [//提示
'trigger'=>'axis',//坐标轴触发
'axisPointer' => [
'type' => 'cross'
],
],
'xAxis' => [
'type' => 'category',
'data' => $x,
],
'yAxis' => $yAxisData,
'series' => $seriesData
];
}
/**
* 生成饼状图config
* -todo
*/
public function chartPieConfig(){
return ;
}
}

View File

@ -0,0 +1,97 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Admin;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use Slowlyo\OwlAdmin\Renderers\Operation;
use App\Services\Admin\AdService;
use App\Admin\Components;
use App\Models\Keyword;
use App\Models\Ad;
/**
* 广告管理
*
* @property AdService $service
*/
class AdController extends AdminController
{
protected string $serviceName = AdService::class;
public function list(): Page
{
$crud = $this->baseCRUD()->tableLayout('fixed')
->headerToolbar([
$this->createButton(),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->labelWidth('80px')->body([
amis()->GroupControl()->mode('horizontal')->body([
amis()->TextControl('id', __('admin.ads.id'))
->placeholder(__('admin.id')),
amis()->TextControl('remark', __('admin.ads.remark'))
->placeholder(__('admin.ads.remark')),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=banner_address&has_owner=0'), 'address', __('admin.ads.address'), 'name', 'key'),
amis()->SelectControl('enable', __('admin.ads.is_enable'))
->options([
1=>'开启',0=>'关闭'
]),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->InputDatetimeRange()->label(__('admin.ads.published_at'))->name('published_at'),
amis()->InputDatetimeRange()->label(__('admin.created_at'))->name('created_at'),
]),
]))
->columns([
amis()->TableColumn('id', __('admin.ads.id'))->width('50px')->sortable(),
amis()->TableColumn('address', __('admin.ads.address'))->type('mapping')
->map(Keyword::allChildrenOfKey('banner_address')->pluck('name', 'key')->toArray())
->itemSchema(amis()->Tag()->label('${item}')->color(Admin::setting()->get('system_theme_setting')['theme_color'] ?? '#1677ff')),
amis()->TableColumn('sort', __('admin.ads.sort'))->quickEdit(
amis()->NumberControl()->min(0)->saveImmediately(true)
),
amis()->TableColumn('resource', __('admin.ads.resource'))->type('image')->height('50px')->width('150px')->enlargeAble(true),
amis()->TableColumn('remark', __('admin.ads.remark')),
amis()->TableColumn('published_at', __('admin.ads.published_at'))->remark(__('admin.ads.published_at_remark')),
amis()->TableColumn('is_enable', __('admin.ads.is_enable'))->type('switch'),
amis()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
Operation::make()->label(__('admin.actions'))->buttons([
$this->rowEditButton(),
$this->rowDeleteButton(),
])
]);
return $this->baseList($crud);
}
public function form($isEdit = false): Form
{
return $this->baseForm()->body([
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=banner_address&has_owner=0'), 'address', __('admin.ads.address'), 'name', 'key')->required(true),
Components::make()->imageControl('resource', __('admin.ads.resource'))->required(true),
amis()->TextControl('remark', __('admin.ads.remark')),
Components::make()->sortControl('sort', __('admin.ads.sort')),
amis()->DateTimeControl('published_at', __('admin.ads.published_at'))->format('YYYY-MM-DD HH:mm:ss')->description(__('admin.ads.published_at_remark')),
amis()->SwitchControl('is_enable', __('admin.ads.is_enable'))->value(false),
amis()->RadiosControl('jump_type', __('admin.ads.jump_type'))->selectFirst(true)->options(Ad::jumpTypeMap())->required(true),
amis()->TextControl('jump_config.web_link', __('admin.ads.jump_config_arr.web_link'))->visibleOn('this.jump_type == '.Ad::TYPE_WEB)->required(true),
amis()->TextControl('jump_config.app_link', __('admin.ads.jump_config_arr.app_link'))->visibleOn('this.jump_type == '.Ad::TYPE_APP)->required(true),
amis()->GroupControl()->body([
amis()->TextControl('jump_config.mini_id', __('admin.ads.jump_config_arr.mini_id'))->visibleOn('this.jump_type == '.Ad::TYPE_MINI)->required(true),
amis()->TextControl('jump_config.mini_link', __('admin.ads.jump_config_arr.mini_link'))->visibleOn('this.jump_type == '.Ad::TYPE_MINI)->required(true),
]),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([
amis()->TextControl('id', 'ID')->static(),
amis()->TextControl('created_at', __('admin.created_at'))->static(),
amis()->TextControl('updated_at', __('admin.updated_at'))->static()
]);
}
}

View File

@ -0,0 +1,50 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Controllers\AdminRoleController as AdminRoleBaseController;
class AdminRoleController extends AdminRoleBaseController
{
public function list(): Page
{
$crud = $this->baseCRUD()
->headerToolbar([
$this->createButton(true),
...$this->baseHeaderToolBar(),
])
->filterTogglable(false)
->itemCheckableOn('${id !== 1}')
->columns([
amis()->TableColumn()->label('ID')->name('id')->sortable(),
amis()->TableColumn()->label(__('admin.admin_role.name'))->name('name'),
amis()->TableColumn()->label(__('admin.admin_role.slug'))->name('slug')->type('tag'),
amis()->TableColumn()
->label(__('admin.created_at'))
->name('created_at')
->type('datetime')
->sortable(true),
amis()->TableColumn()
->label(__('admin.updated_at'))
->name('updated_at')
->type('datetime')
->sortable(true),
amis()->Operation()->label(__('admin.actions'))->buttons([
$this->setPermission()->visibleOn('${slug != "administrator"}'),
$this->rowEditButton(true)->visibleOn('${slug != "administrator"}'),
$this->rowDeleteButton()->visibleOn('${slug != "administrator"}'),
]),
]);
return $this->baseList($crud)->css([
'.tree-full' => [
'overflow' => 'hidden !important',
],
'.cxd-TreeControl > .cxd-Tree' => [
'height' => '100% !important',
'max-height' => '100% !important',
],
]);
}
}

View File

@ -0,0 +1,99 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Renderers\Operation;
use Slowlyo\OwlAdmin\Renderers\SwitchControl;
use Slowlyo\OwlAdmin\Renderers\TableColumn;
use App\Services\Admin\AdminUserService;
use Slowlyo\OwlAdmin\Services\AdminRoleService;
use Slowlyo\OwlAdmin\Controllers\AdminController;
/**
* @property AdminUserService $service
*/
class AdminUserController extends AdminController
{
protected string $serviceName = AdminUserService::class;
public function list(): Page
{
$crud = $this->baseCRUD()
->headerToolbar([
$this->createButton(true),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->body(
amisMake()->TextControl('keyword', __('admin.keyword'))
->size('md')
->placeholder(__('admin.admin_user.search_username'))
))
->quickSaveItemApi(admin_url('quick-edit/admin_users/$id'))
->itemCheckableOn('${id !== 1}')
->columns([
amisMake()->TableColumn('id', 'ID')->sortable(),
amisMake()->TableColumn('avatar', __('admin.admin_user.avatar'))->type('avatar')->src('${avatar}'),
amisMake()->TableColumn('username', __('admin.username')),
amisMake()->TableColumn('name', __('admin.admin_user.name')),
amisMake()->TableColumn('roles', __('admin.admin_user.roles'))->type('each')->items(
amisMake()->Tag()->label('${name}')->className('my-1')
),
amisMake()->TableColumn('lock', __('admin.admin_user.lock'))->quickEdit(SwitchControl::make()->saveImmediately(true)->mode('inline')->disabledOn('${id === 1}')),
amisMake()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
Operation::make()->label(__('admin.actions'))->buttons([
$this->rowEditButton(true)->visibleOn('${id != 1}'),
//单独修改密码
$this->editPassword()->visibleOn('${id != 1}'),
$this->rowDeleteButton()->visibleOn('${id != 1}'),
]),
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->body([
amisMake()->ImageControl('avatar', __('admin.admin_user.avatar'))->receiver($this->uploadImagePath()),
amisMake()->TextControl('name', __('admin.admin_user.name'))->required(),
amisMake()->TextControl('username', __('admin.username'))->required(),
amisMake()->TextControl('password', __('admin.password'))->type('input-password')->required()->validations(['minLength' => 6])->hiddenOn('${id > 0}'),
amisMake()->TextControl('confirm_password', __('admin.confirm_password'))->type('input-password')->required()->validations(['minLength' => 6])->hiddenOn('${id > 0}'),
amisMake()->SelectControl('roles', __('admin.admin_user.roles'))
->searchable()
->multiple()
->labelField('name')
->valueField('id')
->joinValues(false)
->extractValue()
->options(AdminRoleService::make()->query()->get(['id', 'name'])),
SwitchControl::make()->name('lock')->label(__('admin.admin_user.lock'))->value(false),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([]);
}
public function editPassword()
{
return amisMake()->DialogAction()->icon('fa-regular fa-lightbulb')->label(__('admin.admin_user.edit_password'))->level('link')->dialog(
amisMake()->Dialog()->title(__('admin.admin_user.edit_password'))->body([
amisMake()->Form()->title('')
->api([
'method'=>'PUT',
'url'=> admin_url('system/admin_users/$id')
])
->body([
amisMake()->TextControl('id')->value('${id}')->hidden(true),
amisMake()->TextControl('username')->value('${username}')->hidden(true),
amisMake()->TextControl('password', __('admin.password'))->type('input-password')->required()->validations(['minLength' => 6]),
amisMake()->TextControl('confirm_password', __('admin.confirm_password'))->type('input-password')->required()->validations(['minLength' => 6]),
]),
])->size('md')
);
}
}

View File

@ -0,0 +1,107 @@
<?php
namespace App\Admin\Controllers;
use App\Casts\Storage;
use Slowlyo\OwlAdmin\Admin;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Services\Admin\ArticleService;
use App\Admin\Components;
use App\Models\Keyword;
class ArticleController extends AdminController
{
protected string $serviceName = ArticleService::class;
public function list():Page
{
$crud = $this->baseCRUD()->tableLayout('fixed')
->headerToolbar([
$this->createButton(),
...$this->baseHeaderToolBar(),
])
->filter($this->baseFilter()->body([
amis()->GroupControl()->mode('horizontal')->body([
amis()->TextControl('id', __('admin.articles.id'))
->placeholder(__('admin.id')),
amis()->TextControl('title', __('admin.articles.title'))
->placeholder(__('admin.articles.title')),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=article_category&has_owner=0'), 'category', __('admin.articles.category'), 'name', 'key'),
Components::make()->keywordsTagControl('t_ids', __('admin.articles.tags'), 'article_tag'),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->SelectControl('enable', __('admin.articles.is_enable'))
->columnRatio(3)
->options([
1=>'开启',0=>'关闭'
]),
amis()->SelectControl('recommend', __('admin.articles.is_recommend'))
->columnRatio(3)
->options([
1=>'开启',0=>'关闭'
]),
amis()->InputDatetimeRange()->label(__('admin.articles.published_at'))->name('published_at'),
]),
amis()->GroupControl()->mode('horizontal')->body([
amis()->InputDatetimeRange()->label(__('admin.created_at'))->name('created_at')->columnRatio(6),
]),
]))
->itemBadge([//行角标
'text' => __('admin.articles.is_recommend'),
'mode' => 'ribbon',
'position' => 'top-left',
'badgeLevel' => 'danger',
'visibleOn' => '${is_recommend > 0}',
'size' => 15
])
->columns([
amis()->TableColumn('id', __('admin.id'))->sortable(true),
amis()->TableColumn('title', __('admin.articles.title'))->width('300px'),
amis()->TableColumn('category', __('admin.articles.category'))->type('mapping')
->map(Keyword::allChildrenOfKey('article_category')->pluck('name', 'key')->toArray())
->itemSchema(amis()->Tag()->label('${item}')->color(Admin::setting()->get('system_theme_setting')['theme_color'] ?? '#1677ff')),
amis()->TableColumn('tags', __('admin.articles.tags'))->type('mapping')->map(Keyword::tagsMap('article_tag')),
amis()->TableColumn('cover', __('admin.articles.cover'))->type('image')->height('50px')->width('50px')->enlargeAble(true),
amis()->TableColumn('published_at', __('admin.articles.published_at'))->remark(__('admin.articles.published_at_remark')),
amis()->TableColumn('is_enable', __('admin.articles.is_enable'))->type('switch'),
amis()->TableColumn('is_recommend', __('admin.articles.is_recommend'))->type('switch'),
amis()->TableColumn('created_at', __('admin.created_at'))->type('datetime')->sortable(true),
amis()->Operation()->label(__('admin.actions'))->buttons([
$this->rowEditButton(),
$this->rowDeleteButton(),
])
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->panelClassName('px-0')->body([
amis()->Grid()->columns([
amis()->Wrapper()->body([
amis()->TextControl('title', __('admin.articles.title'))->required(true),
Components::make()->parentControl(admin_url('api/keywords/tree-list?parent_name=article_category&has_owner=0'), 'category', __('admin.articles.category'), 'name', 'key'),
Components::make()->keywordsTagControl('t_ids', __('admin.articles.tags'), 'article_tag'),
Components::make()->cropImageControl('cover', __('admin.articles.cover')),
Components::make()->sortControl('sort', __('admin.articles.sort')),
amis()->DateTimeControl('published_at', __('admin.articles.published_at'))->format('YYYY-MM-DD HH:mm:ss')->description(__('admin.articles.published_at_remark')),
amis()->SwitchControl('is_enable', __('admin.articles.is_enable'))->value(false),
amis()->SwitchControl('is_recommend', __('admin.articles.is_recommend'))->value(false),
Components::make()->fileControl('appendixes', __('admin.articles.appendixes'), '.xsl,.xlsx,.txt,.doc,.docx,.pdf,.pptx'),
])->md(4),
amis()->Wrapper()->body([
Components::make()->fuEditorControl('content', __('admin.articles.content')),
])->md(8)
]),
]);
}
public function detail(): Form
{
return $this->baseDetail()->body([]);
}
}

View File

@ -0,0 +1,57 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Symfony\Component\HttpFoundation\Response;
use Slowlyo\OwlAdmin\Models\AdminUser;
use Slowlyo\OwlAdmin\Controllers\AuthController as AdminAuthController;
use Illuminate\Support\Facades\Hash;
class AuthController extends AdminAuthController
{
public function login(Request $request)
{
if (Admin::config('admin.auth.login_captcha')) {
if (!$request->has('captcha')) {
return $this->response()->fail(__('admin.required', ['attribute' => __('admin.captcha')]));
}
if (strtolower(admin_decode($request->sys_captcha)) != strtolower($request->captcha)) {
return $this->response()->fail(__('admin.captcha_error'));
}
}
try {
$validator = Validator::make($request->all(), [
'username' => 'required',
'password' => 'required',
], [
'username' . '.required' => __('admin.required', ['attribute' => __('admin.username')]),
'password.required' => __('admin.required', ['attribute' => __('admin.password')]),
]);
if ($validator->fails()) {
abort(Response::HTTP_BAD_REQUEST, $validator->errors()->first());
}
$adminModel = Admin::config("admin.auth.model", AdminUser::class);
$user = $adminModel::query()->where('username', $request->username)->first();
if($user && $user->lock){
abort(Response::HTTP_BAD_REQUEST, '您的账号已被锁定,需要联系超级管理员解锁。');
}else{
if ($user && Hash::check($request->password, $user->password)) {
$module = Admin::currentModule(true);
$prefix = $module ? $module . '.' : '';
$token = $user->createToken($prefix . 'admin')->plainTextToken;
return $this->response()->success(compact('token'), __('admin.login_successful'));
}
abort(Response::HTTP_BAD_REQUEST, __('admin.login_failed'));
}
} catch (\Exception $e) {
return $this->response()->fail($e->getMessage());
}
}
}

View File

@ -0,0 +1,282 @@
<?php
namespace App\Admin\Controllers;
use Illuminate\Http\JsonResponse;
use Slowlyo\OwlAdmin\Renderers\Card;
use Slowlyo\OwlAdmin\Renderers\Flex;
use Slowlyo\OwlAdmin\Renderers\Html;
use Slowlyo\OwlAdmin\Renderers\Grid;
use Slowlyo\OwlAdmin\Renderers\Chart;
use Slowlyo\OwlAdmin\Renderers\Image;
use Slowlyo\OwlAdmin\Renderers\Action;
use Slowlyo\OwlAdmin\Renderers\Custom;
use Slowlyo\OwlAdmin\Renderers\Wrapper;
use Illuminate\Http\Resources\Json\JsonResource;
use Slowlyo\OwlAdmin\Controllers\AdminController;
class HomeController extends AdminController
{
public function index(): JsonResponse|JsonResource
{
$page = $this->basePage()->css($this->css())->body([
Grid::make()->columns([
$this->frameworkInfo()->md(5),
Flex::make()->items([
$this->pieChart(),
$this->cube(),
]),
]),
Grid::make()->columns([
$this->lineChart()->md(8),
Flex::make()->className('h-full')->items([
$this->clock(),
$this->hitokoto(),
])->direction('column'),
]),
]);
return $this->response()->success($page);
}
/**
* 一言
*/
public function hitokoto()
{
return Card::make()
->className('h-full clear-card-mb')
->body(
Custom::make()->html(<<<HTML
<div class="h-full flex flex-col mt-5 py-5 px-7">
<div></div>
<div class="flex flex-1 items-center w-full justify-center" id="hitokoto">
<a class="text-dark" href="#" id="hitokoto_text" target="_blank"></a>
</div>
<div class="flex justify-end"></div>
</div>
<div class="flex justify-end mt-3">
——&nbsp;
<span id="hitokoto_from_who"></span>
<span></span>
<span id="hitokoto_from"></span>
<span></span>
</div>
HTML
)->onMount(<<<JS
fetch('https://v1.hitokoto.cn?c=i')
.then(response => response.json())
.then(data => {
const hitokoto = document.querySelector('#hitokoto_text')
hitokoto.href = `https://hitokoto.cn/?uuid=\${data.uuid}`
hitokoto.innerText = data.hitokoto
document.querySelector('#hitokoto_from_who').innerText = data.from_who
document.querySelector('#hitokoto_from').innerText = data.from
})
.catch(console.error)
JS
)
);
}
public function clock(): Card
{
return Card::make()->className('h-full bg-blingbling')->header([
'title' => '时钟',
])->body([
Custom::make()
->name('clock')
->html('<div id="clock" class="text-4xl"></div><div id="clock-date" class="mt-5"></div>')
->onMount(<<<JS
const clock = document.getElementById('clock');
const tick = () => {
clock.innerHTML = (new Date()).toLocaleTimeString();
requestAnimationFrame(tick);
};
tick();
const clockDate = document.getElementById('clock-date');
clockDate.innerHTML = (new Date()).toLocaleDateString();
JS
),
]);
}
public function frameworkInfo(): Card
{
return Card::make()->className('h-96')->body(
Wrapper::make()->className('h-full')->body([
Flex::make()->className('h-full')->direction('column')->justify('center')->alignItems('center')->items([
Image::make()->src(url(config('admin.logo'))),
Wrapper::make()->className('text-3xl mt-9')->body(config('admin.name')),
Flex::make()->className('w-64 mt-5')->justify('space-around')->items([
Action::make()
->level('link')
->label('GitHub')
->blank(true)
->actionType('url')
->blank(true)
->link('https://github.com/slowlyo/owl-admin'),
Action::make()
->level('link')
->label('OwlAdmin 文档')
->blank(true)
->actionType('url')
->link('http://doc.owladmin.com'),
Action::make()
->level('link')
->label('Amis 文档')
->blank(true)
->actionType('url')
->link('https://aisuda.bce.baidu.com/amis/zh-CN/docs/index'),
]),
]),
])
);
}
public function pieChart(): Card
{
return Card::make()->className('h-96')->body(
Chart::make()->height(350)->config("{
backgroundColor:'',
tooltip: { trigger: 'item' },
legend: { bottom: 0, left: 'center' },
series: [
{
name: 'Access From',
type: 'pie',
radius: ['40%', '70%'],
avoidLabelOverlap: false,
itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 },
label: { show: false, position: 'center' },
emphasis: {
label: { show: true, fontSize: '40', fontWeight: 'bold' }
},
labelLine: { show: false },
data: [
{ value: 1048, name: 'Search Engine' },
{ value: 735, name: 'Direct' },
{ value: 580, name: 'Email' },
{ value: 484, name: 'Union Ads' },
{ value: 300, name: 'Video Ads' }
]
}
]
}")
);
}
public function lineChart(): Card
{
$randArr = function () {
$_arr = [];
for ($i = 0; $i < 7; $i++) {
$_arr[] = random_int(10, 200);
}
return '[' . implode(',', $_arr) . ']';
};
$random1 = $randArr();
$random2 = $randArr();
$chart = Chart::make()->height(380)->className('h-96')->config("{
backgroundColor:'',
title:{ text: '会员增长情况', },
tooltip: { trigger: 'axis' },
xAxis: { type: 'category', boundaryGap: false, data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] },
yAxis: { type: 'value' },
grid:{ left: '7%', right:'3%', top: 60, bottom: 30, },
legend: { data: ['访问量','注册量'] },
series: [
{ name: '访问量', data: {$random1}, type: 'line', areaStyle: {}, smooth: true, symbol: 'none', },
{ name:'注册量', data: {$random2}, type: 'line', areaStyle: {}, smooth: true, symbol: 'none', },
]}");
return Card::make()->className('clear-card-mb')->body($chart);
}
public function cube(): Card
{
return Card::make()->className('h-96 ml-4 w-8/12')->body(
Html::make()->html(<<<HTML
<style>
.cube-box{ height: 300px; display: flex; align-items: center; justify-content: center; }
.cube { width: 100px; height: 100px; position: relative; transform-style: preserve-3d; animation: rotate 10s linear infinite; }
.cube:after {
content: '';
width: 100%;
height: 100%;
box-shadow: 0 0 50px rgba(0, 0, 0, 0.2);
position: absolute;
transform-origin: bottom;
transform-style: preserve-3d;
transform: rotateX(90deg) translateY(50px) translateZ(-50px);
background-color: rgba(0, 0, 0, 0.1);
}
.cube div {
background-color: rgba(64, 158, 255, 0.7);
position: absolute;
width: 100%;
height: 100%;
border: 1px solid rgb(27, 99, 170);
box-shadow: 0 0 60px rgba(64, 158, 255, 0.7);
}
.cube div:nth-child(1) { transform: translateZ(-50px); animation: shade 10s -5s linear infinite; }
.cube div:nth-child(2) { transform: translateZ(50px) rotateY(180deg); animation: shade 10s linear infinite; }
.cube div:nth-child(3) { transform-origin: right; transform: translateZ(50px) rotateY(270deg); animation: shade 10s -2.5s linear infinite; }
.cube div:nth-child(4) { transform-origin: left; transform: translateZ(50px) rotateY(90deg); animation: shade 10s -7.5s linear infinite; }
.cube div:nth-child(5) { transform-origin: bottom; transform: translateZ(50px) rotateX(90deg); background-color: rgba(0, 0, 0, 0.7); }
.cube div:nth-child(6) { transform-origin: top; transform: translateZ(50px) rotateX(270deg); }
@keyframes rotate {
0% { transform: rotateX(-15deg) rotateY(0deg); }
100% { transform: rotateX(-15deg) rotateY(360deg); }
}
@keyframes shade { 50% { background-color: rgba(0, 0, 0, 0.7); } }
</style>
<div class="cube-box">
<div class="cube">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
HTML
)
);
}
private function css(): array
{
return [
'.clear-card-mb' => [
'margin-bottom' => '0 !important',
],
'.cxd-Image' => [
'border' => '0',
],
'.bg-blingbling' => [
'color' => '#fff',
'background' => 'linear-gradient(to bottom right, #2C3E50, #FD746C, #FF8235, #ffff1c, #92FE9D, #00C9FF, #a044ff, #e73827)',
'background-repeat' => 'no-repeat',
'background-size' => '1000% 1000%',
'animation' => 'gradient 60s ease infinite',
],
'@keyframes gradient' => [
'0%{background-position:0% 0%}
50%{background-position:100% 100%}
100%{background-position:0% 0%}',
],
'.bg-blingbling .cxd-Card-title' => [
'color' => '#fff',
],
];
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Traits\UploadTrait;
class IndexController extends AdminController
{
use UploadTrait;
}

View File

@ -0,0 +1,69 @@
<?php
namespace App\Admin\Controllers;
use Slowlyo\OwlAdmin\Renderers\Page;
use Slowlyo\OwlAdmin\Renderers\Form;
use Slowlyo\OwlAdmin\Renderers\TableColumn;
use Slowlyo\OwlAdmin\Renderers\TextControl;
use Slowlyo\OwlAdmin\Controllers\AdminController;
use App\Services\Admin\KeywordService;
use App\Admin\Components;
use Illuminate\Http\Request;
class KeywordController extends AdminController
{
protected string $serviceName = KeywordService::class;
public function list(): Page
{
$crud = $this->baseCRUD()
//去掉分页-start
->loadDataOnce(true)
->footerToolbar([])
//去掉分页-end
->headerToolbar([
$this->createButton(true),
amis('reload')->align('right'),
amis('filter-toggler')->align('right'),
])
->filter($this->baseFilter()->body([
amis()->TextControl('name', __('admin.keyword'))
->size('md')
->placeholder(__('admin.keywords.search_name')),
amis()->TextControl('parent_name', __('admin.keywords.parent_keyword'))
->size('md')
->placeholder(__('admin.keywords.search_name'))
]
))
->columns([
// TableColumn::make()->name('id')->label('ID')->sortable(true),
TableColumn::make()->name('name')->label('名称'),
TableColumn::make()->name('key')->label('KEY')->copyable(true),
TableColumn::make()->name('value')->label('值'),
TableColumn::make()->name('sort')->label('排序'),
TableColumn::make()->name('created_at')->label('创建时间')->type('datetime')->sortable(true),
amisMake()->Operation()->label(__('admin.actions'))->buttons([
$this->rowEditButton(true),
$this->rowDeleteButton(),
]),
]);
return $this->baseList($crud);
}
public function form(): Form
{
return $this->baseForm()->body([
Components::make()->parentControl(admin_url('api/keywords/tree-list')),
TextControl::make()->name('name')->label('名称')->required(true),
TextControl::make()->name('key')->label('KEY')->required(true),
TextControl::make()->name('value')->label('值'),
amisMake()->NumberControl()->name('sort')->value(0)->min()->label('排序'),
]);
}
public function getTreeList(Request $request){
return $this->service->getTree();
}
}

View File

@ -0,0 +1,91 @@
<?php
namespace App\Admin\Controllers;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Slowlyo\OwlAdmin\Renderers\Tab;
use Slowlyo\OwlAdmin\Renderers\Tabs;
use Slowlyo\OwlAdmin\Renderers\Alert;
use Slowlyo\OwlAdmin\Renderers\InputKV;
use Slowlyo\OwlAdmin\Renderers\TextControl;
use Slowlyo\OwlAdmin\Controllers\AdminController;
class SettingController extends AdminController
{
public function index()
{
$page = $this->basePage()->body([
$this->form(),
]);
return $this->response()->success($page);
}
public function form()
{
return $this->baseForm(false)
->redirect('')->labelWidth('200px')
->api($this->getStorePath())
->data(settings()->all())
->body(
Tabs::make()->tabs([
Tab::make()->title('上传设置')->body([
amis()->RadiosControl('upload_disk', '上传驱动')->options([
'public'=>'本地存储',
'oss' => '阿里云OSS',
])->value('public')->required(true),
amis()->TextControl('oss_config.access_key_id', '阿里云AccessKeyId')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}'),
amis()->TextControl('oss_config.access_key_secret', '阿里云AccessKeySecret')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}'),
amis()->TextControl('oss_config.bucket', '对象存储Bucket')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('示例: my-bucket'),
amis()->TextControl('oss_config.endpoint', '对象存储endpoint')->required(true)->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('示例: oss-cn-shanghai.aliyuncs.com'),
amis()->TextControl('oss_config.domain', '自有域名')->size('lg')->visibleOn('${upload_disk == "oss"}')->remark('填写即启用 示例: my-domain.com'),
amis()->SwitchControl('oss_config.use_ssl', '开启SSL')->value(false)->visibleOn('${upload_disk == "oss"}'),
]),
])
);
}
public function store(Request $request)
{
$data = $request->only([
'upload_disk',
'oss_config'
]);
//上传设置-修改env文件内配置
if(!empty($data['upload_disk'])){
$envData['FILESYSTEM_DISK'] = $data['upload_disk'];
if($envData['FILESYSTEM_DISK'] == 'oss'){//如果设置为OSS驱动则配置env变量
$envData['OSS_ACCESS_KEY_ID'] = Arr::get($data['oss_config'], 'access_key_id');
$envData['OSS_ACCESS_KEY_SECRET'] = Arr::get($data['oss_config'], 'access_key_secret');
$envData['OSS_BUCKET'] = Arr::get($data['oss_config'], 'bucket');
$envData['OSS_ENDPOINT'] = Arr::get($data['oss_config'], 'endpoint');
$envData['OSS_DOMAIN'] = Arr::get($data['oss_config'], 'domain');
if(!empty($envData['OSS_DOMAIN'])){
$envData['OSS_CNAME'] = 'true';
}else{
$envData['OSS_CNAME'] = 'false';
}
$envData['OSS_SSL'] = Arr::get($data['oss_config'], 'use_ssl') ? 'true':'false';
}
$envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
$contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));
$contentArray->transform(function ($item) use ($envData){
foreach ($envData as $key => $value){
if(str_contains($item, $key)){
return $key . '=' . $value;
}
}
return $item;
});
$content = implode("\n", $contentArray->toArray());
\File::put($envPath, $content);
}
return settings()->adminSetMany($data);
}
}

View File

@ -0,0 +1,9 @@
<?php
use Slowlyo\OwlAdmin\Admin;
// Admin::styles([
// '.cxd-Panel-heading { border-width: 0; background: #4080ffc7 !important; }',
// // '.cxd-Panel {box-shadow: none; }',
// '.cxd-Panel-title { color:white;font-size: 16px; }'
// ]);

View File

@ -0,0 +1,43 @@
<?php
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Route;
Route::group([
'domain' => config('admin.route.domain'),
'prefix' => config('admin.route.prefix'),
'middleware' => config('admin.route.middleware'),
], function (Router $router) {
$router->group([
'prefix' => 'api',
], function (Router $router) {
$router->get('keywords/tree-list', '\App\Admin\Controllers\KeywordController@getTreeList')->name('api.keywords.tree-list');
});
$router->resource('index', \App\Admin\Controllers\HomeController::class);
$router->post('login', [App\Admin\Controllers\AuthController::class, 'login']);
$router->resource('system/admin_users', App\Admin\Controllers\AdminUserController::class);
$router->post('quick-edit/admin_users/{admin_user}',[\App\Admin\Controllers\AdminUserController::class, 'update']);
$router->get('system/admin_roles', [App\Admin\Controllers\AdminRoleController::class, 'index']);
$router->resource('system/settings', \App\Admin\Controllers\SettingController::class);
$router->resource('system/keywords', \App\Admin\Controllers\KeywordController::class);
$router->resource('articles', \App\Admin\Controllers\ArticleController::class);
$router->resource('ads', \App\Admin\Controllers\AdController::class);
//修改上传
$router->post('upload_file', [\App\Admin\Controllers\IndexController::class, 'uploadFile']);
$router->post('upload_image', [\App\Admin\Controllers\IndexController::class, 'uploadImage']);
$router->post('upload_rich', [\App\Admin\Controllers\IndexController::class, 'uploadRich']);
$router->post('start_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'startChunk']);
$router->post('save_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'saveChunk']);
$router->post('finish_chunk_upload_file', [\App\Admin\Controllers\IndexController::class, 'finishChunk']);
});

View File

@ -0,0 +1,45 @@
<?php
namespace App\Casts;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage as StorageFacades;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
/**
* 转换文件存储路径
*
* get: 返回全路径
* set: 原样保存
*/
class Storage implements CastsAttributes
{
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
* @return array
*/
public function get($model, $key, $value, $attributes)
{
return $value ? (Str::startsWith($value, ['http://', 'https://']) ? $value : StorageFacades::disk(Admin::config('admin.upload.disk'))->url($value)) : '';
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
* @return string
*/
public function set($model, $key, $value, $attributes)
{
return $value;
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
class Kernel extends ConsoleKernel
{
/**
* Define the application's command schedule.
*/
protected function schedule(Schedule $schedule): void
{
// $schedule->command('inspire')->hourly();
}
/**
* Register the commands for the application.
*/
protected function commands(): void
{
$this->load(__DIR__.'/Commands');
require base_path('routes/console.php');
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Exceptions;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Throwable;
class Handler extends ExceptionHandler
{
/**
* The list of the inputs that are never flashed to the session on validation exceptions.
*
* @var array<int, string>
*/
protected $dontFlash = [
'current_password',
'password',
'password_confirmation',
];
/**
* Register the exception handling callbacks for the application.
*/
public function register(): void
{
$this->reportable(function (Throwable $e) {
//
});
}
}

View File

@ -0,0 +1,12 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests;
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array<int, class-string|string>
*/
protected $middleware = [
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\TrustProxies::class,
\Illuminate\Http\Middleware\HandleCors::class,
\App\Http\Middleware\PreventRequestsDuringMaintenance::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\App\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
\Illuminate\Routing\Middleware\ThrottleRequests::class.':api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
];
/**
* The application's middleware aliases.
*
* Aliases may be used instead of class names to conveniently assign middleware to routes and groups.
*
* @var array<string, class-string|string>
*/
protected $middlewareAliases = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'precognitive' => \Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests::class,
'signed' => \App\Http\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
use Illuminate\Http\Request;
class Authenticate extends Middleware
{
/**
* Get the path the user should be redirected to when they are not authenticated.
*/
protected function redirectTo(Request $request): ?string
{
return $request->expectsJson() ? null : route('login');
}
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
class EncryptCookies extends Middleware
{
/**
* The names of the cookies that should not be encrypted.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance as Middleware;
class PreventRequestsDuringMaintenance extends Middleware
{
/**
* The URIs that should be reachable while maintenance mode is enabled.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Http\Middleware;
use App\Providers\RouteServiceProvider;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class RedirectIfAuthenticated
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next, string ...$guards): Response
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
class TrimStrings extends Middleware
{
/**
* The names of the attributes that should not be trimmed.
*
* @var array<int, string>
*/
protected $except = [
'current_password',
'password',
'password_confirmation',
];
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustHosts as Middleware;
class TrustHosts extends Middleware
{
/**
* Get the host patterns that should be trusted.
*
* @return array<int, string|null>
*/
public function hosts(): array
{
return [
$this->allSubdomainsOfApplicationUrl(),
];
}
}

View File

@ -0,0 +1,28 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Middleware\TrustProxies as Middleware;
use Illuminate\Http\Request;
class TrustProxies extends Middleware
{
/**
* The trusted proxies for this application.
*
* @var array<int, string>|string|null
*/
protected $proxies;
/**
* The headers that should be used to detect proxies.
*
* @var int
*/
protected $headers =
Request::HEADER_X_FORWARDED_FOR |
Request::HEADER_X_FORWARDED_HOST |
Request::HEADER_X_FORWARDED_PORT |
Request::HEADER_X_FORWARDED_PROTO |
Request::HEADER_X_FORWARDED_AWS_ELB;
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Routing\Middleware\ValidateSignature as Middleware;
class ValidateSignature extends Middleware
{
/**
* The names of the query string parameters that should be ignored.
*
* @var array<int, string>
*/
protected $except = [
// 'fbclid',
// 'utm_campaign',
// 'utm_content',
// 'utm_medium',
// 'utm_source',
// 'utm_term',
];
}

View File

@ -0,0 +1,17 @@
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array<int, string>
*/
protected $except = [
//
];
}

85
app/Models/Ad.php 100644
View File

@ -0,0 +1,85 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Casts\Storage;
class Ad extends Model
{
use HasFactory;
use Filterable;
public const TYPE_OFF = 0; //无跳转
public const TYPE_WEB = 1; //网页跳转
public const TYPE_APP = 2; //应用跳转
public const TYPE_MINI = 3;//小程序跳转
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'published_at' => 'datetime',
'is_enable' => 'boolean',
'jump_config' => 'array',
];
protected $fillable = [
'resource',
'address',
'remark',
'published_at',
'is_enable',
'sort',
'jump_type',
'jump_config',
];
public static function jumpTypeMap() :array
{
return [
self::TYPE_WEB => '网页跳转',
self::TYPE_APP => '应用跳转',
self::TYPE_MINI => '小程序跳转',
self::TYPE_OFF => '无跳转',
];
}
public static function jumpTypeMapLabel()
{
return [
self::TYPE_OFF => "<span class='label'>无跳转</span>",
self::TYPE_WEB => "<span class='label label-info'>网页跳转</span>",
self::TYPE_APP => "<span class='label label-warning'>应用跳转</span>",
self::TYPE_MINI => "<span class='label label-green'>小程序跳转</span>",
'*'=>'其他:${jump_type}'
];
}
public static function typeMapLabel()
{
return [
self::TYPE_IN => "<span class='label label-info'>入住缴费</span>",
self::TYPE_CONTINUE => "<span class='label label-warning'>续住缴费</span>",
self::TYPE_EXIT => "<span class='label label-danger'>离开结算</span>",
'*'=>'其他:${live_in}'
];
}
public function scopeShow(){
$q->where('is_enable', true)->where('published_at', '>=', now());
}
public function scopeSort($q)
{
$q->orderBy('sort', 'asc')
->orderBy('published_at', 'desc')
->orderBy('created_at', 'desc');
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Casts\Storage;
class Article extends Model
{
use HasFactory;
use Filterable;
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected $appends = ['tags'];
protected $casts = [
'created_at' => 'datetime:Y-m-d H:i:s',
'updated_at' => 'datetime:Y-m-d H:i:s',
'published_at' => 'datetime:Y-m-d H:i:s',
'is_enable' => 'boolean',
'is_recommend' => 'boolean',
'appendixes' => 'array',
];
protected $fillable = [
'title',
'content',
'cover',
'category',
't_ids',
'published_at',
'is_enable',
'is_recommend',
'sort',
'appendixes',
];
public function scopeShow(){
$q->where('is_enable', true)->where('published_at', '>=', now());
}
public function scopeSort($q)
{
$q->orderBy('is_recommend', 'desc')
->orderBy('sort', 'asc')
->orderBy('published_at', 'desc')
->orderBy('created_at', 'desc');
}
protected function tags():Attribute
{
return Attribute::make(
get: fn($value) => $this->t_ids ? explode(',', $this->t_ids) : [],
);
}
}

View File

@ -0,0 +1,63 @@
<?php
namespace App\Models\Filters;
use Illuminate\Support\Arr;
use EloquentFilter\ModelFilter;
class AdFilter extends ModelFilter
{
/**
* 主键
*/
public function id($id)
{
return $this->where('id', $id);
}
/**
* 备注
*/
public function remark($remark)
{
return $this->where('remark','like', '%'.$remark.'%');
}
/**
* 位置
*/
public function address($address)
{
return $this->where('address', $address);
}
public function publishedAt($publishedAt){
$publishedAt = explode(',',$publishedAt);
return $this->where(function($q) use ($publishedAt) {
$startAt = Arr::get($publishedAt, 0) ?? null;
$endAt = Arr::get($publishedAt, 1) ?? null;
if(!empty($startAt)){
$q->where('published_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('published_at', '<=', $endAt);
}
});
}
public function createdAt($createdAt){
$createdAt = explode(',',$createdAt);
return $this->where(function($q) use ($createdAt) {
$startAt = Arr::get($createdAt, 0) ?? null;
$endAt = Arr::get($createdAt, 1) ?? null;
if(!empty($startAt)){
$q->where('created_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('created_at', '<=', $endAt);
}
});
}
public function enable($enable){
return $this->where('is_enable', $enable);
}
}

View File

@ -0,0 +1,80 @@
<?php
namespace App\Models\Filters;
use EloquentFilter\ModelFilter;
use Illuminate\Support\Arr;
class ArticleFilter extends ModelFilter
{
/**
* 主键
*/
public function id($id)
{
return $this->where('id', $id);
}
/**
* 标题
*/
public function title($title)
{
return $this->where('title','like', '%'.$title.'%');
}
/**
* 获取分类下的文章
*/
public function category($category)
{
return $this->where('category', $category);
}
/**
* 查询带有标签的文章
*/
public function tIds($tIds){
$tIds = explode(',',$tIds);
return $this->where(function($q) use ($tIds) {
foreach ($tIds as $tId) {
$q->whereRaw("FIND_IN_SET('".$tId."',t_ids)");
}
});
}
public function publishedAt($publishedAt){
$publishedAt = explode(',',$publishedAt);
return $this->where(function($q) use ($publishedAt) {
$startAt = Arr::get($publishedAt, 0) ?? null;
$endAt = Arr::get($publishedAt, 1) ?? null;
if(!empty($startAt)){
$q->where('published_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('published_at', '<=', $endAt);
}
});
}
public function createdAt($createdAt){
$createdAt = explode(',',$createdAt);
return $this->where(function($q) use ($createdAt) {
$startAt = Arr::get($createdAt, 0) ?? null;
$endAt = Arr::get($createdAt, 1) ?? null;
if(!empty($startAt)){
$q->where('created_at', '>=', $startAt);
}
if(!empty($endAt)){
$q->where('created_at', '<=', $endAt);
}
});
}
public function enable($enable){
return $this->where('is_enable', $enable);
}
public function recommend($recommend){
return $this->where('is_recommend', $recommend);
}
}

View File

@ -0,0 +1,31 @@
<?php
namespace App\Models\Filters;
use EloquentFilter\ModelFilter;
use App\Models\Keyword;
class KeywordFilter extends ModelFilter
{
/**
* 关键字
*/
public function name($name)
{
return $this->where('name','like', '%'.$name.'%')
->orWhere('key','like', '%'.$name.'%');
}
public function parentName($parent_name)
{
if(request('has_owner', 1)){
$this->where(function($q) use ($parent_name){
$q->where('name','like', '%'.$parent_name.'%')
->orWhere('key','like', '%'.$parent_name.'%');
});
}
return $this->orWhere('path','like', '%-'.
Keyword::where('name','like', '%'.$parent_name.'%')->orWhere('key','like', '%'.$parent_name.'%')->value('id')
. '-%' ?? '');
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Admin\Components;
class Keyword extends Model
{
use HasFactory;
use Filterable;
protected $fillable = ['name', 'key', 'value', 'parent_id', 'parent_key', 'path', 'sort', 'lv'];
protected function serializeDate(\DateTimeInterface $date)
{
return $date->format('Y-m-d H:i:s');
}
protected static function boot()
{
parent::boot();
// 监听 Keyword 的创建事件,用于初始化 path 和 lv 字段值
static::saving(function ($keyword) {
// 如果创建的是一个根类目
if (! $keyword->parent_id) {
// 将层级设为 1
$keyword->lv = 1;
// 将 path 设为 -
$keyword->path = '-';
} else {
// 将层级设为父类目的层级 + 1
$keyword->lv = $keyword->parent->lv +1;
$keyword->parent_key = $keyword->parent->key;
// 将 path 值设为父类目的 path 追加父类目 ID 以及最后跟上一个 - 分隔符
$keyword->path = $keyword->parent->path.$keyword->parent_id.'-';
}
});
}
public function parent()
{
return $this->belongsTo(static::class, 'parent_id');
}
public function children()
{
return $this->hasMany(static::class, 'parent_id');
}
public function scopeAllChildrenOfKey($q, $parentKey)
{
$q->where('path','like', '%-'.
static::where('key', $parentKey)->value('id')
. '-%' ?? '');
}
public static function tagsMap(String $key)
{
$mapArr = [];
self::query()->where('parent_key', $key)->get()->map(function($item) use (&$mapArr){
$mapArr[$item->id] = Components::make()->keywordsTag($item->name, $item->value);
});
return $mapArr;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot()
{
\Schema::defaultStringLength(191);
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace App\Providers;
// use Illuminate\Support\Facades\Gate;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The model to policy mappings for the application.
*
* @var array<class-string, class-string>
*/
protected $policies = [
//
];
/**
* Register any authentication / authorization services.
*/
public function boot(): void
{
//
}
}

View File

@ -0,0 +1,19 @@
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Broadcast;
use Illuminate\Support\ServiceProvider;
class BroadcastServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Broadcast::routes();
require base_path('routes/channels.php');
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace App\Providers;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;
class EventServiceProvider extends ServiceProvider
{
/**
* The event to listener mappings for the application.
*
* @var array<class-string, array<int, class-string>>
*/
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
],
];
/**
* Register any events for your application.
*/
public function boot(): void
{
//
}
/**
* Determine if events and listeners should be automatically discovered.
*/
public function shouldDiscoverEvents(): bool
{
return false;
}
}

View File

@ -0,0 +1,67 @@
<?php
namespace App\Providers;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Database\Events\TransactionBeginning;
use Illuminate\Database\Events\TransactionCommitted;
use Illuminate\Database\Events\TransactionRolledBack;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
class QueryLoggerServiceProvider extends ServiceProvider
{
/**
* {@inheritdoc}
*/
public function boot()
{
if (! config('app.debug')) {
return;
}
$this->app['events']->listen([
QueryExecuted::class,
TransactionBeginning::class,
TransactionCommitted::class,
TransactionRolledBack::class,
], function ($event) {
Log::debug(match (true) {
$event instanceof TransactionBeginning => 'begin transaction',
$event instanceof TransactionCommitted => 'commit transaction',
$event instanceof TransactionRolledBack => 'rollback transaction',
default => $this->prepareSql($event),
});
});
}
/**
* @param \Illuminate\Database\Events\QueryExecuted $query
* @return string
*/
protected function prepareSql(QueryExecuted $query): string
{
$sql = str_replace(['%', '?'], ['%%', '%s'], $query->sql);
$bindings = $query->connection->prepareBindings($query->bindings);
if (count($bindings)) {
$sql = vsprintf($sql, array_map([$query->connection->getPdo(), 'quote'], $bindings));
}
return sprintf('[%s] %s', $this->formatDuration($query->time), $sql);
}
/**
* @param float $milliseconds
* @return string
*/
protected function formatDuration($milliseconds): string
{
return match (true) {
$milliseconds >= 1000 => round($milliseconds / 1000, 2).'s',
$milliseconds < 0.01 => round($milliseconds * 1000).'μs',
default => $milliseconds.'ms',
};
}
}

View File

@ -0,0 +1,40 @@
<?php
namespace App\Providers;
use Illuminate\Cache\RateLimiting\Limit;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
/**
* The path to your application's "home" route.
*
* Typically, users are redirected here after authentication.
*
* @var string
*/
public const HOME = '/home';
/**
* Define your route model bindings, pattern filters, and other route configuration.
*/
public function boot(): void
{
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
$this->routes(function () {
Route::middleware('api')
->prefix('api')
->group(base_path('routes/api.php'));
Route::middleware('web')
->group(base_path('routes/web.php'));
});
}
}

View File

@ -0,0 +1,114 @@
<?php
namespace App\Services\Admin;
use App\Models\Ad;
use App\Models\Filters\AdFilter;
use App\Traits\UploadTrait;
use Illuminate\Support\Arr;
/**
* @method Ad getModel()
* @method Ad|\Illuminate\Database\Query\Builder query()
*/
class AdService extends BaseService
{
use UploadTrait;
protected string $modelName = Ad::class;
protected string $modelFilterName = AdFilter::class;
protected bool $modelSortAble = true;
public function store($data): bool
{
$columns = $this->getTableColumns();
$model = $this->getModel();
$isEnable = Arr::get($data, 'is_enabled');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt)) {
$data['published_at'] = now();
}
if(isset($data['resource'])){
$data['resource'] = $this->saveImage('resource', 'ads/resource')[0];
}
//处理跳转配置
$jumpType = Arr::get($data, 'jump_type');
if($jumpType !== null){
switch($jumpType){
case Ad::TYPE_OFF:
$data['jump_config'] = null;
break;
case Ad::TYPE_WEB:
$data['jump_config'] = Arr::only($data['jump_config'], 'web_link');
break;
case Ad::TYPE_APP:
$data['jump_config'] = Arr::only($data['jump_config'], 'app_link');;
break;
case Ad::TYPE_MINI:
$data['jump_config'] = Arr::only($data['jump_config'], ['mini_id', 'mini_link']);;
break;
}
}
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
public function update($primaryKey, $data): bool
{
$columns = $this->getTableColumns();
$model = $this->query()->whereKey($primaryKey)->first();
$isEnable = Arr::get($data, 'is_enable');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt) && empty($model->published_at)) {
$data['published_at'] = now();
}
if(isset($data['resource'])){
$data['resource'] = $this->saveImage('resource', 'ads/resource')[0];
}
//处理跳转配置
$jumpType = Arr::get($data, 'jump_type');
if($jumpType !== null){
switch($jumpType){
case Ad::TYPE_OFF:
$data['jump_config'] = null;
break;
case Ad::TYPE_WEB:
$data['jump_config'] = Arr::only($data['jump_config'], 'web_link');
break;
case Ad::TYPE_APP:
$data['jump_config'] = Arr::only($data['jump_config'], 'app_link');;
break;
case Ad::TYPE_MINI:
$data['jump_config'] = Arr::only($data['jump_config'], ['mini_id', 'mini_link']);;
break;
}
}
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
}

View File

@ -0,0 +1,166 @@
<?php
namespace App\Services\Admin;
use Illuminate\Support\Arr;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Support\Facades\Hash;
use Slowlyo\OwlAdmin\Models\AdminUser;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
/**
* @method AdminUser getModel()
* @method AdminUser|Builder query()
*/
class AdminUserService extends BaseService
{
protected string $modelName;
public function __construct()
{
$this->modelName = Admin::adminUserModel();
}
public function getEditData($id): Model|\Illuminate\Database\Eloquent\Collection|Builder|array|null
{
$adminUser = parent::getEditData($id)->makeHidden('password');
$adminUser->load('roles');
return $adminUser;
}
public function store($data): bool
{
if ($this->checkUsernameUnique($data['username'])) {
return $this->setError(__('admin.admin_user.username_already_exists'));
}
if (!data_get($data, 'password')) {
return $this->setError(__('admin.required', ['attribute' => __('admin.password')]));
}
if (!$this->passwordHandler($data)) {
return false;
}
$columns = $this->getTableColumns();
$model = $this->getModel();
return $this->saveData($data, $columns, $model);
}
public function update($primaryKey, $data): bool
{
if ($this->checkUsernameUnique($data['username'], $primaryKey)) {
return $this->setError(__('admin.admin_user.username_already_exists'));
}
if (!$this->passwordHandler($data)) {
return false;
}
$columns = $this->getTableColumns();
$model = $this->query()->whereKey($primaryKey)->first();
return $this->saveData($data, $columns, $model);
}
public function checkUsernameUnique($username, $id = 0): bool
{
return $this->query()
->where('username', $username)
->when($id, fn($query) => $query->where('id', '<>', $id))
->exists();
}
public function updateUserSetting($primaryKey, $data): bool
{
if (!$this->passwordHandler($data, $primaryKey)) {
return false;
}
return parent::update($primaryKey, $data);
}
public function passwordHandler(&$data, $id = null): bool
{
$password = Arr::get($data, 'password');
if ($password) {
if ($password !== Arr::get($data, 'confirm_password')) {
return $this->setError(__('admin.admin_user.password_confirmation'));
}
if ($id) {
if (!Arr::get($data, 'old_password')) {
return $this->setError(__('admin.admin_user.old_password_required'));
}
$oldPassword = $this->query()->where('id', $id)->value('password');
if (!Hash::check($data['old_password'], $oldPassword)) {
return $this->setError(__('admin.admin_user.old_password_error'));
}
}
$data['password'] = bcrypt($password);
unset($data['confirm_password']);
unset($data['old_password']);
}
return true;
}
public function list()
{
$keyword = request()->keyword;
$query = $this
->query()
->with('roles')
->select(['id', 'name', 'username', 'avatar', 'created_at', 'lock'])
->when($keyword, function ($query) use ($keyword) {
$query->where('username', 'like', "%{$keyword}%")->orWhere('name', 'like', "%{$keyword}%");
});
$this->sortable($query);
$items = (clone $query)->paginate(request()->input('perPage', 20))->items();
$total = (clone $query)->count();
return compact('items', 'total');
}
/**
* @param $data
* @param array $columns
* @param AdminUser $model
*
* @return bool
*/
protected function saveData($data, array $columns, AdminUser $model): bool
{
$roles = Arr::pull($data, 'roles');
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
if ($model->save()) {
$model->roles()->sync(Arr::has($roles, '0.id') ? Arr::pluck($roles, 'id') : $roles);
return true;
}
return false;
}
}

View File

@ -0,0 +1,79 @@
<?php
namespace App\Services\Admin;
use App\Models\Article;
use App\Models\Filters\ArticleFilter;
use App\Traits\UploadTrait;
use Illuminate\Support\Arr;
/**
* @method Article getModel()
* @method Article|\Illuminate\Database\Query\Builder query()
*/
class ArticleService extends BaseService
{
use UploadTrait;
protected string $modelName = Article::class;
protected string $modelFilterName = ArticleFilter::class;
protected bool $modelSortAble = true;
public function store($data): bool
{
$columns = $this->getTableColumns();
$model = $this->getModel();
$isEnable = Arr::get($data, 'is_enabled');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt)) {
$data['published_at'] = now();
}
$data['cover'] = $this->saveImage('cover', 'articles/cover')[0] ?? '';
$data['appendixes'] = $this->saveFile('appendixes', 'articles/appendixes');
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
public function update($primaryKey, $data): bool
{
$columns = $this->getTableColumns();
$model = $this->query()->whereKey($primaryKey)->first();
$isEnable = Arr::get($data, 'is_enable');
$publishedAt = Arr::get($data, 'published_at');
if ($isEnable && empty($publishedAt) && empty($model->published_at)) {
$data['published_at'] = now();
}
if(isset($data['cover'])){
$data['cover'] = $this->saveImage('cover', 'articles/cover')[0] ?? '';
}
if(isset($data['appendixes'])){
$data['appendixes'] = $this->saveFile('appendixes', 'articles/appendixes');
}
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Services\Admin;
use Slowlyo\OwlAdmin\Services\AdminService;
/**
* @method Region getModel()
* @method Region|\Illuminate\Database\Query\Builder query()
*/
class BaseService extends AdminService
{
protected array $withRelationships = [];
protected string $modelFilterName = '';
protected bool $modelSortAble = false;
public function getTree()
{
$list = $this->query()->orderByDesc('sort')->get();
$minNum = $list->min('parent_id');
return array2tree($list->toArray(), $minNum);
}
public function getModelFilter()
{
return $this->modelFilterName;
}
public function listQuery()
{
$model = $this->getModel();
$filter = $this->getModelFilter();
$query = $this->query();
if($this->withRelationships){
$query->with($this->withRelationships);
}
if ($filter) {
$query->filter(request()->input(), $filter);
}
if($this->modelSortAble){
$query->sort();
}
$this->sortable($query);
return $query;
}
public function getDetail($id)
{
return $this->query()->with($this->withRelationships)->find($id);
}
}

View File

@ -0,0 +1,116 @@
<?php
namespace App\Services\Admin;
use Illuminate\Support\Arr;
use App\Models\Keyword;
use App\Models\Filters\KeywordFilter;
/**
* @method Keyword getModel()
* @method Keyword|\Illuminate\Database\Query\Builder query()
*/
class KeywordService extends BaseService
{
protected string $modelName = Keyword::class;
protected string $modelFilterName = KeywordFilter::class;
public function getTree()
{
$list = $this->query()->filter(request()->all(), $this->modelFilterName)->orderByDesc('sort')->get();
$minNum = $list->min('parent_id');
return !$list->isEmpty() ? array2tree($list->toArray(), $minNum) :[];
}
public function parentIsChild($id, $pid): bool
{
$parent = $this->query()->find($pid);
do {
if ($parent->parent_id == $id) {
return true;
}
// 如果没有parent 则为顶级 退出循环
$parent = $parent->parent;
} while ($parent);
return false;
}
public function list()
{
return ['items' => $this->getTree()];
}
public function store($data): bool
{
if ($this->hasRepeated($data)) {
return false;
}
$columns = $this->getTableColumns();
$model = $this->getModel();
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
public function update($primaryKey, $data): bool
{
if ($this->hasRepeated($data, $primaryKey)) {
return false;
}
$columns = $this->getTableColumns();
$pid = Arr::get($data, 'parent_id');
if ($pid != 0) {
if ($this->parentIsChild($primaryKey, $pid)) {
$this->setError('父级不允许设置为当前子权限');
return false;
}
}
$model = $this->query()->whereKey($primaryKey)->first();
foreach ($data as $k => $v) {
if (!in_array($k, $columns)) {
continue;
}
$model->setAttribute($k, $v);
}
return $model->save();
}
public function hasRepeated($data, $id = 0): bool
{
$query = $this->query()->when($id, fn($query) => $query->where('id', '<>', $id));
if ((clone $query)->where('key', $data['key'])->exists()) {
$this->setError('KEY重复');
return true;
}
return false;
}
public function delete(string $ids): mixed
{
$ids = explode(',', $ids);
if(count($ids) == 1){
$this->query()->where('path', 'like', '%-'.$ids[0].'-%')->delete();
}
return $this->query()->whereIn('id', $ids)->delete();
}
}

View File

@ -0,0 +1,210 @@
<?php
namespace App\Traits;
use Slowlyo\OwlAdmin\Admin;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
trait UploadTrait
{
public function uploadImage()
{
return $this->upload('image');
}
public function uploadFile()
{
return $this->upload();
}
/**
* 富文本内文件上传
*/
public function uploadRich()
{
$fromWangEditor = false;
$file = request()->file('file');
if (!$file) {
$fromWangEditor = true;
$file = request()->file('wangeditor-uploaded-image');
if (!$file) {
$file = request()->file('wangeditor-uploaded-video');
}
}
if (!$file) {
return $this->response()->additional(['errno' => 1])->fail(__('admin.upload_file_error'));
}
$path = $file->store(Admin::config('admin.upload.directory.rich'), Admin::config('admin.upload.disk'));
$link = Storage::disk(Admin::config('admin.upload.disk'))->url($path);
if ($fromWangEditor) {
return $this->response()->additional(['errno' => 0])->success(['url' => $link]);
}
return $this->response()->additional(compact('link'))->success(compact('link'));
}
/**
* 存放临时文件目录,按日期区分;
*/
protected function upload($type = 'file')
{
$file = request()->file('file');
if (!$file) {
return $this->response()->fail(__('admin.upload_file_error'));
}
$path = $file->store(Admin::config('admin.upload.tem_directory.' . $type).'/'.date('Y-m-d'), Admin::config('admin.upload.disk'));
return $this->response()->success(['value' => $path]);
}
public function saveImage($field = 'image', $path)
{
return $this->saveFile($field, $path);
}
/**
* 表单提交时,转存实际目录,并保留上传时文件名称;文件保存全路径
*/
public function saveFile($field = 'file', $path)
{
$file = request()->file($field);
if (!$file) {
$file = request()->get($field);
}
$fileArr = [];
//判断是否多个文件;
if(is_string($file) || isset($file['id'])){
$files = [$file];
}else{
$files = $file;
}
if($files){
foreach($files as $file){
if(is_array($file) && isset($file['state'])){
switch($file['state']){
case 'init':
if(strpos($file['value'], 'temporary') !== false){
$filePath = $path.'/'.$file['name'];
Storage::disk(Admin::config('admin.upload.disk'))->move($file['value'], $filePath);
$fileArr[] = Storage::disk(Admin::config('admin.upload.disk'))->url($filePath);
}else{
$fileArr[] = $file['value'];
}
break;
case 'uploaded':
if(isset($file['name'])){
$filePath = $path.'/'.$file['name'];
if(Str::startsWith($file['value'], ['http://', 'https://'])){
$fileUrl = parse_url($file['value']);
$fileValue = ltrim($fileUrl['path'], '/');
}else{
$fileValue = $file['value'];
}
Storage::disk(Admin::config('admin.upload.disk'))->move($file['value'], $filePath);
$fileArr[] = Storage::disk(Admin::config('admin.upload.disk'))->url($filePath);
}
break;
}
}else{
$fileArr[] = $file;
}
}
}
return $fileArr;
}
/**
* 开始分片上传, 生成唯一ID
*/
public function startChunk()
{
$type = 'file';
$fileName = request()->get('filename', '');
$uploadId = md5(time().$fileName);
//创建临时文件夹
if ( Storage::disk(Admin::config('admin.upload.disk'))->exists(Admin::config('admin.upload.tem_directory.' . $type).'/'.$uploadId) === false ) {
if ( Storage::disk(Admin::config('admin.upload.disk'))->makeDirectory(Admin::config('admin.upload.tem_directory.' . $type).'/'.$uploadId) === false ) {
return false;
}
}
return $this->response()->success(['uploadId' => $uploadId]);
}
/**
* 保存分片
*/
public function saveChunk()
{
$type = 'file';
$file = request()->file('file');
$uploadId = request()->get('uploadId');
$partNumber = request()->get('partNumber');
$partSize = request()->get('partSize');
// dd($file);
$fileName = $file->getClientOriginalName();
//判断该分片是否已存在,
$dirPath = Admin::config('admin.upload.tem_directory.' . $type).'/'.$uploadId;
if(Storage::disk(Admin::config('admin.upload.disk'))->exists($dirPath . '/'.$fileName.'_'.$partNumber)){
return $this->response()->fail(__('admin.upload_file_error'));
}else{
//验证分片大小-todo
$path = $file->storeAs($dirPath, $fileName.'_'.$partNumber, Admin::config('admin.upload.disk'));
$realPath = Storage::disk(Admin::config('admin.upload.disk'))->url($path);
$eTag = md5_file($realPath);
return $this->response()->success(['eTag' => $eTag]);
}
}
/**
* 完成分片
*/
public function finishChunk()
{
$type = 'file';
//合并文件
$fileName = request()->get('filename', '');
$uploadId = request()->get('uploadId', '');
$partList = request()->get('partList', []);
$basePath = Admin::config('admin.upload.tem_directory.' . $type).'/'.$uploadId;
$realPath = 'chunk/'.$fileName;
//获取分片列表中序号,查看分片是否都完成上传
$partNumberList = Arr::pluck($partList, 'partNumber');
if(max($partNumberList) === count($partNumberList)){
//判断是否已存在同名文件,进行删除
if(Storage::disk(Admin::config('admin.upload.disk'))->exists($realPath)){
$realPath = 'chunk/(1)'.$fileName;
}
for($i = 1; $i<=count($partNumberList); $i++){
$_file = Storage::disk(Admin::config('admin.upload.disk'))->get($basePath.'/'.$fileName.'_'.$i);
Storage::disk(Admin::config('admin.upload.disk'))->append($realPath, $_file, null);
}
//删除分片文件夹
Storage::disk(Admin::config('admin.upload.disk'))->deleteDirectory($basePath);
$value = Storage::disk(Admin::config('admin.upload.disk'))->url($realPath);
return $this->response()->success(['value'=>$value]);
}else{
return $this->response()->fail(__('admin.upload_file_error'));
}
}
}

53
artisan 100644
View File

@ -0,0 +1,53 @@
#!/usr/bin/env php
<?php
define('LARAVEL_START', microtime(true));
/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so that we do not have to worry about the
| loading of any of our classes manually. It's great to relax.
|
*/
require __DIR__.'/vendor/autoload.php';
$app = require_once __DIR__.'/bootstrap/app.php';
/*
|--------------------------------------------------------------------------
| Run The Artisan Application
|--------------------------------------------------------------------------
|
| When we run the console application, the current CLI command will be
| executed in this console and the response sent back to a terminal
| or another output device for the developers. Here goes nothing!
|
*/
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$status = $kernel->handle(
$input = new Symfony\Component\Console\Input\ArgvInput,
new Symfony\Component\Console\Output\ConsoleOutput
);
/*
|--------------------------------------------------------------------------
| Shutdown The Application
|--------------------------------------------------------------------------
|
| Once Artisan has finished running, we will fire off the shutdown events
| so that any final work may be done by the application before we shut
| down the process. This is the last thing to happen to the request.
|
*/
$kernel->terminate($input, $status);
exit($status);

55
bootstrap/app.php 100644
View File

@ -0,0 +1,55 @@
<?php
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| The first thing we will do is create a new Laravel application instance
| which serves as the "glue" for all the components of Laravel, and is
| the IoC container for the system binding all of the various parts.
|
*/
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
/*
|--------------------------------------------------------------------------
| Bind Important Interfaces
|--------------------------------------------------------------------------
|
| Next, we need to bind some important interfaces into the container so
| we will be able to resolve them when needed. The kernels serve the
| incoming requests to this application from both the web and CLI.
|
*/
$app->singleton(
Illuminate\Contracts\Http\Kernel::class,
App\Http\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
/*
|--------------------------------------------------------------------------
| Return The Application
|--------------------------------------------------------------------------
|
| This script returns the application instance. The instance is given to
| the calling script so we can separate the building of the instances
| from the actual running of the application and sending responses.
|
*/
return $app;

2
bootstrap/cache/.gitignore vendored 100644
View File

@ -0,0 +1,2 @@
*
!.gitignore

69
composer.json 100644
View File

@ -0,0 +1,69 @@
{
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.1",
"alphasnow/aliyun-oss-laravel": "^4.7",
"guzzlehttp/guzzle": "^7.2",
"laravel/framework": "^10.10",
"laravel/sanctum": "^3.3",
"laravel/tinker": "^2.8",
"slowlyo/owl-admin": "^3.0",
"tucker-eric/eloquentfilter": "^3.2"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
"laravel/pint": "^1.0",
"laravel/sail": "^1.18",
"mockery/mockery": "^1.4.4",
"nunomaduro/collision": "^7.0",
"phpunit/phpunit": "^10.1",
"spatie/laravel-ignition": "^2.0"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}

6408
composer.lock generated 100644

File diff suppressed because it is too large Load Diff

121
config/admin.php 100644
View File

@ -0,0 +1,121 @@
<?php
return [
// 应用名称
'name' => 'Owl Admin',
// 应用 logo
'logo' => '/admin/logo.png',
// 默认头像
'default_avatar' => '/admin/default-avatar.png',
// 应用安装目录
'directory' => app_path('Admin'),
// 引导文件
'bootstrap' => app_path('Admin/bootstrap.php'),
// 应用路由
'route' => [
'prefix' => 'admin-api',
'domain' => null,
'namespace' => 'App\\Admin\\Controllers',
'middleware' => ['admin'],
// 不包含额外路由, 配置后, 不会追加新增/详情/编辑页面路由
'without_extra_routes' => [
'/dashboard',
],
],
'auth' => [
// 是否开启验证码
'login_captcha' => env('ADMIN_LOGIN_CAPTCHA', true),
// 是否开启认证
'enable' => true,
// 是否开启鉴权
'permission' => true,
'guard' => 'admin',
'guards' => [
'admin' => [
'driver' => 'sanctum',
'provider' => 'admin',
],
],
'providers' => [
'admin' => [
'driver' => 'eloquent',
'model' => \Slowlyo\OwlAdmin\Models\AdminUser::class,
],
],
'except' => [
],
],
'upload' => [
'disk' => env("FILESYSTEM_DISK", 'public'),
// 文件上传目录
'directory' => [
'image' => 'images',
'file' => 'files',
'rich' => 'rich',
],
// 临时目录
'tem_directory' => [
'image' => 'temporary/images',
'file' => 'temporary/file',
'rich' => 'temporary/rich',
]
],
'https' => env('ADMIN_HTTPS', false),
// 是否显示 [开发者工具]
'show_development_tools' => env('ADMIN_SHOW_DEVELOPMENT_TOOLS', true),
// 是否显示 [权限] 功能中的自动生成按钮
'show_auto_generate_permission_button' => env('ADMIN_SHOW_AUTO_GENERATE_PERMISSION_BUTTON', true),
// 扩展
'extension' => [
'dir' => base_path('extensions'),
],
'layout' => [
// 浏览器标题, 功能名称使用 %title% 代替
'title' => '%title% | OwlAdmin',
'header' => [
// 是否显示 [刷新] 按钮
'refresh' => true,
// 是否显示 [暗色模式] 按钮
'dark' => true,
// 是否显示 [全屏] 按钮
'full_screen' => true,
// 是否显示 [主题配置] 按钮
'theme_config' => true,
],
/*
* keep_alive 页面缓存黑名单
*
* eg:
* 列表: /user
* 详情: /user/:id
* 编辑: /user/:id/edit
* 新增: /user/create
*/
'keep_alive_exclude' => [],
// 底部信息
'footer' => '<a href="https://github.com/slowlyo/owl-admin" target="_blank">Owl Admin</a>',
],
'models' => [
'admin_user' => \Slowlyo\OwlAdmin\Models\AdminUser::class,
'admin_role' => \Slowlyo\OwlAdmin\Models\AdminRole::class,
'admin_menu' => \Slowlyo\OwlAdmin\Models\AdminMenu::class,
'admin_permission' => \Slowlyo\OwlAdmin\Models\AdminPermission::class,
],
'modules' => [
],
];

190
config/app.php 100644
View File

@ -0,0 +1,190 @@
<?php
use Illuminate\Support\Facades\Facade;
use Illuminate\Support\ServiceProvider;
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application. This value is used when the
| framework needs to place the application's name in a notification or
| any other location as required by the application or its packages.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| your application so that it is used when running Artisan tasks.
|
*/
'url' => env('APP_URL', 'http://localhost'),
'asset_url' => env('ASSET_URL'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/
'timezone' => 'PRC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/
'locale' => 'zh_CN',
/*
|--------------------------------------------------------------------------
| Application Fallback Locale
|--------------------------------------------------------------------------
|
| The fallback locale determines the locale to use when the current one
| is not available. You may change the value to correspond to any of
| the language folders that are provided through your application.
|
*/
'fallback_locale' => 'en',
/*
|--------------------------------------------------------------------------
| Faker Locale
|--------------------------------------------------------------------------
|
| This locale will be used by the Faker PHP library when generating fake
| data for your database seeds. For example, this will be used to get
| localized telephone numbers, street address information and more.
|
*/
'faker_locale' => 'en_US',
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is used by the Illuminate encrypter service and should be set
| to a random, 32 character string, otherwise these encrypted strings
| will not be safe. Please do this before deploying an application!
|
*/
'key' => env('APP_KEY'),
'cipher' => 'AES-256-CBC',
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => 'file',
// 'store' => 'redis',
],
/*
|--------------------------------------------------------------------------
| Autoloaded Service Providers
|--------------------------------------------------------------------------
|
| The service providers listed here will be automatically loaded on the
| request to your application. Feel free to add your own services to
| this array to grant expanded functionality to your applications.
|
*/
'providers' => ServiceProvider::defaultProviders()->merge([
/*
* Package Service Providers...
*/
/*
* Application Service Providers...
*/
App\Providers\AppServiceProvider::class,
App\Providers\AuthServiceProvider::class,
// App\Providers\BroadcastServiceProvider::class,
App\Providers\EventServiceProvider::class,
App\Providers\RouteServiceProvider::class,
App\Providers\QueryLoggerServiceProvider::class,
])->toArray(),
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => Facade::defaultAliases()->merge([
// 'Example' => App\Facades\Example::class,
])->toArray(),
];

115
config/auth.php 100644
View File

@ -0,0 +1,115 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option controls the default authentication "guard" and password
| reset options for your application. You may change these defaults
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| here which uses session storage and the Eloquent user provider.
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication drivers have a user provider. This defines how the
| users are actually retrieved out of your database or other storage
| mechanisms used by this application to persist your user's data.
|
| If you have multiple user tables or models you may configure multiple
| sources which represent each model / table. These sources may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| You may specify multiple password reset configurations if you have more
| than one user table or model in the application and you want to have
| separate password reset settings based on the specific user types.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => 'password_reset_tokens',
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the amount of seconds before a password confirmation
| times out and the user is prompted to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => 10800,
];

View File

@ -0,0 +1,71 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Broadcaster
|--------------------------------------------------------------------------
|
| This option controls the default broadcaster that will be used by the
| framework when an event needs to be broadcast. You may set this to
| any of the connections defined in the "connections" array below.
|
| Supported: "pusher", "ably", "redis", "log", "null"
|
*/
'default' => env('BROADCAST_DRIVER', 'null'),
/*
|--------------------------------------------------------------------------
| Broadcast Connections
|--------------------------------------------------------------------------
|
| Here you may define all of the broadcast connections that will be used
| to broadcast events to other systems or over websockets. Samples of
| each available type of connection are provided inside this array.
|
*/
'connections' => [
'pusher' => [
'driver' => 'pusher',
'key' => env('PUSHER_APP_KEY'),
'secret' => env('PUSHER_APP_SECRET'),
'app_id' => env('PUSHER_APP_ID'),
'options' => [
'cluster' => env('PUSHER_APP_CLUSTER'),
'host' => env('PUSHER_HOST') ?: 'api-'.env('PUSHER_APP_CLUSTER', 'mt1').'.pusher.com',
'port' => env('PUSHER_PORT', 443),
'scheme' => env('PUSHER_SCHEME', 'https'),
'encrypted' => true,
'useTLS' => env('PUSHER_SCHEME', 'https') === 'https',
],
'client_options' => [
// Guzzle client options: https://docs.guzzlephp.org/en/stable/request-options.html
],
],
'ably' => [
'driver' => 'ably',
'key' => env('ABLY_KEY'),
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
],
'log' => [
'driver' => 'log',
],
'null' => [
'driver' => 'null',
],
],
];

111
config/cache.php 100644
View File

@ -0,0 +1,111 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache connection that gets used while
| using this caching library. This connection is used when another is
| not explicitly specified when executing a given caching function.
|
*/
'default' => env('CACHE_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "apc", "array", "database", "file",
| "memcached", "redis", "dynamodb", "octane", "null"
|
*/
'stores' => [
'apc' => [
'driver' => 'apc',
],
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'table' => 'cache',
'connection' => null,
'lock_connection' => null,
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache',
'lock_connection' => 'default',
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, or DynamoDB cache
| stores there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_cache_'),
];

34
config/cors.php 100644
View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,
];

151
config/database.php 100644
View File

@ -0,0 +1,151 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for all database work. Of course
| you may use many connections at once using the Database library.
|
*/
'default' => env('DB_CONNECTION', 'mysql'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Here are each of the database connections setup for your application.
| Of course, examples of configuring each database platform that is
| supported by Laravel is shown below to make development simple.
|
|
| All database work in Laravel is done through the PHP PDO facilities
| so make sure you have the driver for your particular database of
| choice installed on your machine before you begin development.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DATABASE_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => 'prefer',
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run in the database.
|
*/
'migrations' => 'migrations',
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as APC or Memcached. Laravel makes it easy to dig right in.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
],
],
];

View File

@ -0,0 +1,92 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application. Just store away!
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Here you may configure as many filesystem "disks" as you wish, and you
| may even configure multiple disks of the same driver. Defaults have
| been set up for each driver as an example of the required values.
|
| Supported Drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app'),
'throw' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
],
"oss" => [
"driver" => "oss",
"access_key_id" => env("OSS_ACCESS_KEY_ID"), // 必填, 阿里云的AccessKeyId
"access_key_secret" => env("OSS_ACCESS_KEY_SECRET"), // 必填, 阿里云的AccessKeySecret
"bucket" => env("OSS_BUCKET"), // 必填, 对象存储的Bucket, 示例: my-bucket
"endpoint" => env("OSS_ENDPOINT"), // 必填, 对象存储的Endpoint, 示例: oss-cn-shanghai.aliyuncs.com
"internal" => env("OSS_INTERNAL", null), // 选填, 内网上传地址,填写即启用 示例: oss-cn-shanghai-internal.aliyuncs.com
"domain" => env("OSS_DOMAIN", null), // 选填, 绑定域名,填写即启用 示例: oss.my-domain.com
"is_cname" => env("OSS_CNAME", false), // 选填, 若Endpoint为自定义域名此项要为truehttps://github.com/aliyun/aliyun-oss-php-sdk/blob/572d0f8e099e8630ae7139ed3fdedb926c7a760f/src/OSS/OssClient.php#L113C1-L122C78
"prefix" => env("OSS_PREFIX", ""), // 选填, 统一存储地址前缀
"use_ssl" => env("OSS_SSL", false), // 选填, 是否使用HTTPS
"reverse_proxy" => env("OSS_REVERSE_PROXY", false), // 选填, 域名是否使用NGINX代理绑定
"throw" => env("OSS_THROW", true), // 选填, 是否抛出引起错误的异常,默认出现错误时,不抛出异常仅返回false
"options" => [], // 选填, 添加全局配置参数, 示例: [\OSS\OssClient::OSS_CHECK_MD5 => false]
"macros" => [] // 选填, 添加自定义Macro, 示例: [\App\Macros\ListBuckets::class, \App\Macros\CreateBucket::class]
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];

54
config/hashing.php 100644
View File

@ -0,0 +1,54 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Hash Driver
|--------------------------------------------------------------------------
|
| This option controls the default hash driver that will be used to hash
| passwords for your application. By default, the bcrypt algorithm is
| used; however, you remain free to modify this option if you wish.
|
| Supported: "bcrypt", "argon", "argon2id"
|
*/
'driver' => 'bcrypt',
/*
|--------------------------------------------------------------------------
| Bcrypt Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Bcrypt algorithm. This will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 12),
'verify' => true,
],
/*
|--------------------------------------------------------------------------
| Argon Options
|--------------------------------------------------------------------------
|
| Here you may specify the configuration options that should be used when
| passwords are hashed using the Argon algorithm. These will allow you
| to control the amount of time it takes to hash the given password.
|
*/
'argon' => [
'memory' => 65536,
'threads' => 1,
'time' => 4,
'verify' => true,
],
];

131
config/logging.php 100644
View File

@ -0,0 +1,131 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that gets used when writing
| messages to the logs. The name specified in this option should match
| one of the channels defined in the "channels" configuration array.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => false,
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Out of
| the box, Laravel uses the Monolog PHP logging library. This gives
| you a variety of powerful log handlers / formatters to utilize.
|
| Available Drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog",
| "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['single'],
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => 'Laravel Log',
'emoji' => ':boom:',
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'formatter' => env('LOG_STDERR_FORMATTER'),
'with' => [
'stream' => 'php://stderr',
],
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => LOG_USER,
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];

126
config/mail.php 100644
View File

@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send any email
| messages sent by your application. Alternative mailers may be setup
| and used as needed; however, this mailer will be used by default.
|
*/
'default' => env('MAIL_MAILER', 'smtp'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers to be used while
| sending an e-mail. You will specify which one you are using for your
| mailers below. You are free to add additional mailers as required.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "log", "array", "failover"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
'port' => env('MAIL_PORT', 587),
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN'),
],
'ses' => [
'transport' => 'ses',
],
'mailgun' => [
'transport' => 'mailgun',
// 'client' => [
// 'timeout' => 5,
// ],
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => null,
// 'client' => [
// 'timeout' => 5,
// ],
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all e-mails sent by your application to be sent from
| the same address. Here, you may specify a name and address that is
| used globally for all e-mails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', 'Example'),
],
/*
|--------------------------------------------------------------------------
| Markdown Mail Settings
|--------------------------------------------------------------------------
|
| If you are using Markdown based email rendering, you may configure your
| theme and component paths here, allowing you to customize the design
| of the emails. Or, you may simply stick with the Laravel defaults!
|
*/
'markdown' => [
'theme' => 'default',
'paths' => [
resource_path('views/vendor/mail'),
],
],
];

109
config/queue.php 100644
View File

@ -0,0 +1,109 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue API supports an assortment of back-ends via a single
| API, giving you convenient access to each back-end using the same
| syntax for every one. Here you may define a default connection.
|
*/
'default' => env('QUEUE_CONNECTION', 'sync'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection information for each server that
| is used by your application. A default configuration has been added
| for each back-end shipped with Laravel. You are free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'table' => 'jobs',
'queue' => 'default',
'retry_after' => 90,
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => 'localhost',
'queue' => 'default',
'retry_after' => 90,
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => 'default',
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => 90,
'block_for' => null,
'after_commit' => false,
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control which database and table are used to store the jobs that
| have failed. You may change them to any database / table you wish.
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'mysql'),
'table' => 'failed_jobs',
],
];

83
config/sanctum.php 100644
View File

@ -0,0 +1,83 @@
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort()
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => App\Http\Middleware\EncryptCookies::class,
'verify_csrf_token' => App\Http\Middleware\VerifyCsrfToken::class,
],
];

View File

@ -0,0 +1,34 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'mailgun' => [
'domain' => env('MAILGUN_DOMAIN'),
'secret' => env('MAILGUN_SECRET'),
'endpoint' => env('MAILGUN_ENDPOINT', 'api.mailgun.net'),
'scheme' => 'https',
],
'postmark' => [
'token' => env('POSTMARK_TOKEN'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
];

214
config/session.php 100644
View File

@ -0,0 +1,214 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option controls the default session "driver" that will be used on
| requests. By default, we will use the lightweight native driver but
| you may specify any of the other wonderful drivers provided here.
|
| Supported: "file", "cookie", "database", "apc",
| "memcached", "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'file'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to immediately expire on the browser closing, set that option.
|
*/
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => false,
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it is stored. All encryption will be run
| automatically by Laravel and you can use the Session like normal.
|
*/
'encrypt' => false,
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When using the native session driver, we need a location where session
| files may be stored. A default has been set for you but a different
| location may be specified. This is only needed for file sessions.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table we
| should use to manage the sessions. Of course, a sensible default is
| provided for you; however, you are free to change this as needed.
|
*/
'table' => 'sessions',
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| While using one of the framework's cache driven session backends you may
| list a cache store that should be used for these sessions. This value
| must match with one of the application's configured cache "stores".
|
| Affects: "apc", "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the cookie used to identify a session
| instance by ID. The name specified here will get used every time a
| new session cookie is created by the framework for every driver.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug(env('APP_NAME', 'laravel'), '_').'_session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application but you are free to change this when necessary.
|
*/
'path' => '/',
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| Here you may change the domain of the cookie used to identify a session
| in your application. This will determine which domains the cookie is
| available to in your application. A sensible default has been set.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. You are free to modify this option if needed.
|
*/
'http_only' => true,
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" since this is a secure default value.
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => 'lax',
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => false,
];

36
config/view.php 100644
View File

@ -0,0 +1,36 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| View Storage Paths
|--------------------------------------------------------------------------
|
| Most templating systems load templates from disk. Here you may specify
| an array of paths that should be checked for your views. Of course
| the usual Laravel view path has already been registered for you.
|
*/
'paths' => [
resource_path('views'),
],
/*
|--------------------------------------------------------------------------
| Compiled View Path
|--------------------------------------------------------------------------
|
| This option determines where all the compiled Blade templates will be
| stored for your application. Typically, this is within the storage
| directory. However, as usual, you are free to change this value.
|
*/
'compiled' => env(
'VIEW_COMPILED_PATH',
realpath(storage_path('framework/views'))
),
];

1
database/.gitignore vendored 100644
View File

@ -0,0 +1 @@
*.sqlite*

View File

@ -0,0 +1,44 @@
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
}
};

View File

@ -0,0 +1,28 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('password_reset_tokens');
}
};

View File

@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->text('connection');
$table->text('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('failed_jobs');
}
};

View File

@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->string('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('keywords', function (Blueprint $table) {
$table->id();
$table->string('key')->unique();
$table->string('name')->comment('名字');
$table->string('value')->nullable();
$table->unsignedInteger('sort')->default(0)->comment('排序');
$table->unsignedBigInteger('parent_id')->default(0)->comment('上级ID');
$table->string('parent_key')->nullable('上级key');
$table->unsignedInteger('lv')->default(1)->comment('层级');
$table->string('path')->default('-')->comment('所有的父级ID');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('keywords');
}
};

View File

@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('admin_users', function (Blueprint $table) {
$table->unsignedInteger('lock')->default(0)->comment('锁定');
$table->unsignedInteger('error_num')->default(0)->comment('错误次数');
$table->timestamp('last_error_at')->nullable()->comment('上次错误时间');
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('admin_users', function (Blueprint $table) {
$table->dropColumn(['lock', 'error_num', 'last_error_at']);
});
}
};

View File

@ -0,0 +1,42 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->string('title')->comment('标题');
$table->text('content')->nullable()->comment('内容');
$table->string('cover')->nullable()->comment('封面');
$table->string('category')->nullable()->comment('分类');
$table->string('t_ids')->nullable()->comment('标签');
$table->timestamp('published_at')->nullable()->comment('发布时间');
$table->unsignedTinyInteger('is_enable')->default(1)->comment('显示开关');
$table->unsignedTinyInteger('is_recommend')->default(0)->comment('推荐开关');
$table->unsignedInteger('sort')->default(0)->comment('排序');
$table->text('appendixes')->nullable()->comment('附件');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('articles');
}
};

View File

@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('ads', function (Blueprint $table) {
$table->id();
$table->string('address')->comment('位置');
$table->string('resource')->comment('资源');
$table->string('remark')->nullable()->comment('备注');
$table->timestamp('published_at')->nullable()->comment('发布时间');
$table->unsignedTinyInteger('is_enable')->default(1)->comment('显示开关');
$table->unsignedInteger('sort')->default(0)->comment('排序');
$table->unsignedTinyInteger('jump_type')->default(0)->comment('跳转0不跳转。1网页跳转2应用跳转3微信小程序跳转');
$table->text('jump_config')->nullable()->comment('跳转配置');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('ads');
}
};

View File

@ -0,0 +1,71 @@
<?php
namespace Database\Seeders;
use Slowlyo\OwlAdmin\Models\AdminMenu;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Throwable;
class AdminMenuSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
//
$menus = [
['title' => 'index', 'icon' => 'line-md:home-twotone-alt', 'url' => '/index', 'is_home'=>1, 'order'=>1],
['title' => 'admin_system', 'icon' => 'material-symbols:settings-outline', 'url' => '/system', 'order'=>2,
'children' => [
['title' => 'admin_users', 'icon' => 'ph:user-gear', 'url' => '/system/admin_users', 'order'=>1],
['title' => 'admin_roles', 'icon' => 'carbon:user-role', 'url' => '/system/admin_roles', 'order'=>2],
['title' => 'admin_permission', 'icon' => 'carbon:user-role', 'url' => '/system/admin_permissions', 'order'=>3],
['title' => 'admin_menu', 'icon' => 'fluent-mdl2:permissions', 'url' => '/system/admin_menus', 'order'=>4],
['title' => 'admin_setting', 'icon' => 'akar-icons:settings-horizontal', 'url' => '/system/settings', 'order'=>5],
['title' => 'keywords', 'icon' => 'ph:codesandbox-logo-light', 'url' => '/system/keywords', 'order'=>6]
],
],
['title' => 'web_content', 'icon' => 'ic:outline-collections-bookmark', 'url' => '', 'order'=>3,
'children' =>[
['title'=>'articles', 'icon'=>'ic:outline-article','url'=>'/articles', 'order'=>1],
['title'=>'ads', 'icon'=>'lets-icons:img-box','url'=>'/ads', 'order'=>2],
]
]
];
DB::table('admin_menus')->truncate();
try {
DB::begintransaction();
$this->createMenus($menus);
DB::commit();
} catch (Throwable $th) {
DB::rollBack();
report($th);
}
}
public function createMenus(array $menus, $pid = 0)
{
foreach ($menus as $menu) {
$mm = AdminMenu::create([
'title' => $menu['title'],
'icon' => $menu['icon'],
'url' => $menu['url'],
'parent_id' => $pid,
'url_type' => $menu['url_type'] ?? 1,
'visible' => $menu['visible'] ?? 1,
'is_home' => $menu['is_home'] ?? 0,
'order' => $menu['order'] ?? 0,
'is_full' => 0,
]);
if (isset($menu['children'])) {
$this->createMenus($menu['children'], $mm->id);
}
}
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace Database\Seeders;
// use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*/
public function run(): void
{
$this->call(AdminMenuSeeder::class);
$this->call(KeywordSeeder::class);
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace Database\Seeders;
use App\Models\Keyword;
use Illuminate\Database\Seeder;
use Illuminate\Support\Arr;
class KeywordSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
Keyword::truncate();
$list = [
['key' => 'article_category', 'name' => '文章分类', 'list' => [
]],
['key' => 'article_tag', 'name' => '文章标签', 'list' => [//标签value填写色号指定标签颜色
]],
['key' => 'banner_address', 'name' => '广告位置', 'list' => [
]],
];
foreach ($list as $item) {
$type = Keyword::create(Arr::except($item, 'list'));
if (isset($item['list'])) {
$keywords = [];
foreach ($item['list'] as $index => $name) {
$template = [
'key' => $type->key . ($index + 1),
'parent_key' => $type->key,
'lv' => $type->lv + 1,
'sort' => $index + 1
];
if (is_array($name)) {
$template = array_merge($template, $name);
} else {
$template['name'] = $name;
}
array_push($keywords, $template);
}
$type->children()->createMany($keywords);
}
}
}
}

255
lang/en/admin.php 100644
View File

@ -0,0 +1,255 @@
<?php
return [
'remember_me' => 'Remember me',
'login' => 'Login',
'logout' => 'Logout',
'username' => 'Username',
'password' => 'Password',
'old_password' => 'Old Password',
'confirm_password' => 'Confirm Password',
'captcha' => 'Captcha',
'captcha_error' => 'Captcha Error',
'required' => ':attribute is required',
'login_successful' => 'Login Success',
'login_failed' => 'Username Or Password Error',
'user_setting' => 'User Settings',
'created_at' => 'Created At',
'updated_at' => 'Updated At',
'deleted_at' => 'Deleted At',
'actions' => 'Actions',
'create' => 'Create',
'edit' => 'Edit',
'show' => 'Show',
'delete' => 'Delete',
'copy' => 'Copy',
'confirm_delete' => 'Confirm Delete Selected Items?',
'back' => 'Back',
'reset' => 'Reset',
'search' => 'Search',
'list' => 'List',
'add' => 'Add',
'save' => 'Save',
'detail' => 'Detail',
'developer' => 'Developer',
'code_generator' => 'Code Generator',
'visual_editor' => 'Visual Editor',
'terminal' => 'Terminal',
'administrator' => 'Administrator',
'soft_delete' => 'Soft Delete',
'keyword' => 'Keyword',
'unknown_error' => 'Unknown Error',
'upload_file_error' => 'Upload File Error',
'parent' => 'Parent',
'order' => 'Order',
'order_desc' => 'Order Desc',
'order_asc' => 'Order Asc',
'menus' => 'Menus',
'successfully' => 'Successfully',
'failed' => 'Failed',
'successfully_message' => ':attribute Successfully',
'failed_message' => ':attribute Failed',
'action_success' => 'Action Success',
'action_failed' => 'Action Failed',
'save_success' => 'Save Success',
'save_failed' => 'Save Failed',
'yes' => 'Yes',
'no' => 'No',
'need_start_with_slash' => 'Need Start With /',
'cancel' => 'Cancel',
'please_login' => 'Please Login',
'unauthorized' => 'Unauthorized',
'code_generators' => [
'remark1' => 'For more parameters, please refer to',
'remark2' => 'Database Migration',
'remark3' => 'Multiple parameters are separated by English commas',
'table_name' => 'Table Name',
'model_name' => 'Model',
'controller_name' => 'Controller',
'service_name' => 'Service',
'primary_key' => 'Primary Key',
'primary_key_description' => 'Use increments method',
'options' => 'Options',
'create_database_migration' => 'Create Database Migration File',
'create_table' => 'Create Table',
'create_model' => 'Create Model',
'create_controller' => 'Create Controller',
'create_service' => 'Create Service',
'app_title' => 'App Title',
'column_name' => 'Column Name',
'type' => 'Type',
'extra_params' => 'Extra Params',
'nullable' => 'Nullable',
'index' => 'Index',
'default_value' => 'Default Value',
'comment' => 'Comment',
'exists_table' => 'Exists Table',
'generate_code' => 'Generate Code',
'expand_more_settings' => 'More Settings',
'collapse_settings' => 'Collapse Settings',
'confirm_generate_code' => 'Confirm Generate Code?',
'preview' => 'Preview',
'base_info' => 'Base Info',
'column_info' => 'Column Info',
'route_config' => 'Route Config',
'page_config' => 'Page Config',
'gen_route_menu' => 'Generate Route And Menu',
'route' => 'Route',
'menu_name' => 'Menu Name',
'parent_menu' => 'Parent Menu',
'menu_icon' => 'Menu Icon',
'name_label_desc' => 'Name And Label Attribute Take Field Name And Comment',
'column_warning' => 'If the field name exists (no / status) will cause the form to fail to echo back!',
'add_column' => 'Add Column',
'scope' => 'Scope',
'list_component' => 'List Component',
'list_component_desc' => 'List Component, Default Is TableColumn',
'form_component' => 'Form Component',
'form_component_desc' => 'Form Component, Default Is TextControl',
'detail_component' => 'Detail Component',
'detail_component_desc' => 'Detail Component, Default Is TextControl',
'model_config' => 'Model Config',
'file_column' => 'File Column',
'file_column_desc' => 'File Column, Automatically Add Attribute Methods In The Model',
'preview_code' => 'Preview Code',
'property' => 'Property',
'property_name' => 'Property Name',
'value' => 'Value',
'dialog_form' => 'Dialog Form',
'dialog_size' => 'Dialog Size',
'copy_record' => 'Copy Record',
'copy_record_description' => 'You can copy and share to <a href="https://github.com/Slowlyo/owl-admin/discussions/categories/%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E8%AE%B0%E5%BD%95" target="_blank">Github</a>',
'import_record' => 'Import Record',
'import_record_placeholder' => 'Please enter the imported json record',
'import_record_desc' => 'You can find some records shared by others on <a href="https://github.com/Slowlyo/owl-admin/discussions/categories/%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E8%AE%B0%E5%BD%95" target="_blank">Github</a>',
'load_config' => 'Load Config',
'load_component_config' => 'Load :c Config',
'fill' => 'Fill',
'save_current_config' => 'Save Current Config',
'input_config_name' => 'Please Input Config Name',
'same_name_tips' => 'Configurations with the same name will be overwritten',
],
'admin_users' => 'Admin Users',
'admin_user' => [
'avatar' => 'Avatar',
'name' => 'Name',
'roles' => 'Roles',
'search_username' => 'Search Username/Name',
'password_confirmation' => 'Password Not Match',
'old_password_required' => 'Old Password Required',
'old_password_error' => 'Old Password Error',
'username_already_exists' => 'Username Already Exists',
],
'admin_roles' => 'Admin Roles',
'admin_role' => [
'name' => 'Name',
'slug' => 'Slug',
'permissions' => 'Permissions',
'slug_description' => 'unique identifier of a role',
'name_already_exists' => 'Role Name Already Exists',
'slug_already_exists' => 'Role Slug Already Exists',
'set_permissions' => 'Set Permissions',
],
'admin_permissions' => 'Permissions',
'admin_permission' => [
'name' => 'Name',
'slug' => 'Slug',
'http_method' => 'Http Method',
'http_method_description' => 'if you do not select the value is ANY',
'http_path' => 'Http Path',
'auto_generate' => 'Auto Generate',
'auto_generate_confirm' => 'The permission information will be generated after the permission table and permission menu association table are truncated. Do you want to continue?',
'parent_id_not_allow' => 'Parent Id Not Allow',
'name_already_exists' => 'Permission Name Already Exists',
'slug_already_exists' => 'Permission Slug Already Exists',
],
'admin_menus' => 'Menus',
'admin_menu' => [
'parent_id' => 'Parent',
'order' => 'Order',
'title' => 'Title',
'icon' => 'Icon',
'icon_description' => 'Please refer to ',
'url' => 'Url',
'visible' => 'Visible',
'type' => 'Type',
'api' => 'Page API',
'api_description' => 'schemaApi, the api for page initialization requests, needs to be consistent with queryPath in Controller',
'route' => 'Route',
'link' => 'Link',
'class_name' => 'Class Name',
'class_name_description' => 'The CSS class name of the menu, which is typically used to customize styles',
'show' => 'Show',
'hide' => 'Hide',
'is_home' => 'Is Home',
'is_home_description' => 'In multi-tab mode, the page label is fixed on the left',
'is_full' => 'Is Full',
'is_full_description' => 'When enabled, the menu bar portion of the page is hidden',
'parent_id_not_allow' => 'The parent menu cannot be set to the current submenu',
'component' => 'Component',
'component_desc' => 'amis by default. Not a custom front-end page, please do not modify it',
],
'extensions' => [
'name_invalid' => 'Name Invalid',
'exists' => 'This extension already exists: ',
'menu' => 'Extensions',
'page_title' => 'Extensions',
'create' => 'Create',
'install' => 'Install',
'create_extension' => 'Create Extension',
'create_tips' => 'After the directory is created, a basic extended directory structure is created under the <br><b>:dir</b><br> directory',
'local_install' => 'Local Install',
'more_extensions' => 'More Extensions',
'setting' => 'Setting',
'enable' => 'Enable',
'enable_confirm' => 'Are you sure to enable the extension?',
'disable' => 'Disable',
'disable_confirm' => 'Are you sure to disable the extension?',
'uninstall' => 'Uninstall',
'uninstall_confirm' => '
<div class="text-danger">
Confirm to uninstall the extension?<br>
Uninstallation will delete all files and databases published after the extension is enabled and cannot be retrieved!!!<br>
Backup important data before performing operations!!!<br>
<span class="text-info">Extension package files will not be deleted, please manually delete them!!!</span>
</div>
',
'filter_placeholder' => 'Search by extension name',
'form' => [
'create_extension' => 'Create Extension',
'name' => 'Name',
'namespace' => 'Namespace',
'create_description' => 'It will be created in :dir Directory to create a basic extended directory structure',
],
'card' => [
'author' => 'Author',
'version' => 'Version',
'homepage' => 'Home',
'status' => 'Status',
],
'status_map' => [
'enabled' => 'Enabled',
'disabled' => 'Disabled',
],
'validation' => [
'file' => 'Please select file',
'invalid_package' => 'Invalid extension package',
],
],
'export' => [
'title' => 'Export',
'all' => 'All',
'page' => 'Current Page',
'selected_rows' => 'Selected Rows',
'page_no_data' => 'Current page has no data',
'selected_rows_no_data' => 'No data is selected',
'please_install_laravel_excel' => 'Please install the package "maatwebsite/excel" first',
],
];

11
lang/en/menu.php 100644
View File

@ -0,0 +1,11 @@
<?php
return [
'dashboard' => 'Dashboard',
'admin_system' => 'Admin',
'admin_users' => 'Users',
'admin_roles' => 'Roles',
'admin_permission' => 'Permissions',
'admin_menu' => 'Menus',
'admin_setting' => 'Settings',
];

View File

@ -0,0 +1,311 @@
<?php
return [
'remember_me' => '记住我',
'login' => '登 录',
'logout' => '退出登录',
'username' => '用户名',
'password' => '密码',
'old_password' => '旧密码',
'confirm_password' => '确认密码',
'captcha' => '验证码',
'captcha_error' => '验证码有误',
'required' => '请填写:attribute',
'login_successful' => '登录成功',
'login_failed' => '用户名或密码错误',
'user_setting' => '个人设置',
'created_at' => '创建时间',
'updated_at' => '更新时间',
'deleted_at' => '删除时间',
'actions' => '操作',
'create' => '新增',
'edit' => '编辑',
'show' => '查看',
'delete' => '删除',
'copy' => '复制',
'confirm_delete' => '确认删除选中项?',
'back' => '返回',
'reset' => '重置',
'search' => '搜索',
'list' => '列表',
'add' => '新增',
'save' => '保存',
'detail' => '详情',
'developer' => '开发',
'code_generator' => '代码生成器',
'visual_editor' => '可视化编辑器',
'terminal' => '终端',
'administrator' => '管理员',
'soft_delete' => '软删除',
'keyword' => '关键字',
'unknown_error' => '未知错误',
'upload_file_error' => '上传文件错误',
'parent' => '父级',
'order' => '排序',
'order_desc' => '降序排序',
'order_asc' => '升序排序',
'menus' => '菜单',
'successfully' => '成功',
'failed' => '失败',
'successfully_message' => ':attribute成功',
'failed_message' => ':attribute失败',
'action_success' => '操作成功',
'action_failed' => '操作失败',
'save_success' => '保存成功',
'save_failed' => '保存失败',
'yes' => '是',
'no' => '否',
'need_start_with_slash' => '需要以 / 开头',
'cancel' => '取消',
'please_login' => '请先登录',
'unauthorized' => '无权访问',
'id' => 'ID',
'components' => [
'content' => '内容',
'parent_select' => '父级',
'order' => '排序',
'decimal' => '金额',
'status' => '状态',
'status_map' => [
'enabled' => '已启用',
'disabled' => '已禁用',
],
'tag' => '标签',
'files' => '文件'
],
'code_generators' => [
'remark1' => '额外参数请参考',
'remark2' => '数据库迁移',
'remark3' => '多个参数使用英文逗号分割',
'table_name' => '表名',
'model_name' => '模型',
'controller_name' => '控制器',
'service_name' => 'Service',
'primary_key' => '主键名称',
'primary_key_description' => '使用 increments 方法',
'options' => '可选项',
'create_database_migration' => '创建数据库迁移文件',
'create_table' => '创建数据表',
'create_model' => '创建模型',
'create_controller' => '创建控制器',
'create_service' => '创建Service',
'app_title' => '功能名称',
'column_name' => '字段名',
'type' => '类型',
'extra_params' => '额外参数',
'nullable' => '允许空值',
'index' => '索引',
'default_value' => '默认值',
'comment' => '注释',
'exists_table' => '已有数据表',
'generate_code' => '生成代码',
'expand_more_settings' => '更多设置',
'collapse_settings' => '收起设置',
'confirm_generate_code' => '确认生成代码?',
'preview' => '预览',
'base_info' => '基本信息',
'column_info' => '字段信息',
'route_config' => '路由配置',
'page_config' => '页面配置',
'gen_route_menu' => '生成路由&菜单',
'route' => '路由',
'menu_name' => '菜单名称',
'parent_menu' => '父级菜单',
'menu_icon' => '菜单图标',
'name_label_desc' => 'name和label属性取字段名和注释',
'column_warning' => '如果字段名存在 no、status 会导致 form 回显失败!',
'add_column' => '添加字段',
'scope' => '作用域',
'list_component' => '列表组件',
'list_component_desc' => '列表组件, 默认为 TableColumn',
'form_component' => '表单组件',
'form_component_desc' => '表单组件, 默认为 TextControl',
'detail_component' => '详情组件',
'detail_component_desc' => '详情组件, 默认为 TextControl',
'model_config' => '模型配置',
'file_column' => '文件字段',
'file_column_desc' => '文件字段会自动在模型中添加 获取/修改器 方法',
'preview_code' => '预览代码',
'property' => '属性',
'property_name' => '属性名称',
'value' => '值',
'dialog_form' => '弹窗表单',
'dialog_size' => '弹窗大小',
'copy_record' => '复制记录',
'copy_record_description' => '你可以复制后分享到 <a href="https://github.com/Slowlyo/owl-admin/discussions/categories/%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E8%AE%B0%E5%BD%95" target="_blank">Github</a>',
'import_record' => '导入记录',
'import_record_placeholder' => '请输入导入的json记录',
'import_record_desc' => '你可以在 <a href="https://github.com/Slowlyo/owl-admin/discussions/categories/%E4%BB%A3%E7%A0%81%E7%94%9F%E6%88%90%E8%AE%B0%E5%BD%95" target="_blank">Github</a> 找到一些其他人分享的记录',
'load_config' => '加载配置',
'load_component_config' => '加载 :c 配置',
'fill' => '填充',
'save_current_config' => '保存当前配置',
'input_config_name' => '请填写配置名称',
'same_name_tips' => '相同名称的配置将会被覆盖'
],
'admin_users' => '管理员',
'admin_user' => [
'avatar' => '头像',
'name' => '姓名',
'roles' => '角色',
'search_username' => '搜索用户名/名称',
'password_confirmation' => '两次输入密码不一致',
'old_password_required' => '请输入原密码',
'old_password_error' => '原密码错误',
'username_already_exists' => '用户名已存在',
'lock' => '锁定',
'edit_password' => '修改密码'
],
'admin_roles' => '角色',
'admin_role' => [
'name' => '名称',
'slug' => '标识',
'permissions' => '权限',
'slug_description' => '角色的唯一标识, 不可重复',
'name_already_exists' => '角色名称已存在',
'slug_already_exists' => '角色标识已存在',
'set_permissions' => '设置权限',
],
'admin_permissions' => '权限',
'admin_permission' => [
'name' => '名称',
'slug' => '标识',
'http_method' => '请求方式',
'http_method_description' => '不选则为ANY',
'http_path' => '路由',
'auto_generate' => '自动生成',
'auto_generate_confirm' => '权限信息会在 截断权限表&权限菜单关联表 后重新生成, 是否继续操作 ?',
'parent_id_not_allow' => '父级不允许设置为当前子权限',
'name_already_exists' => '权限名称已存在',
'slug_already_exists' => '权限标识已存在',
],
'admin_menus' => '菜单',
'admin_menu' => [
'parent_id' => '父级',
'order' => '排序',
'title' => '名称',
'icon' => '图标',
'icon_description' => '请参考',
'url' => '链接',
'visible' => '可见',
'type' => '类型',
'api' => '页面Api',
'api_description' => 'schemaApi, 页面初始化请求的api, 需要与Controller中的queryPath一致',
'route' => '路由',
'link' => '外链',
'class_name' => '类名',
'class_name_description' => '菜单的CSS类名, 一般用于自定义样式',
'show' => '可见',
'hide' => '隐藏',
'is_home' => '首页',
'is_home_description' => '在多页签卡模式下,页面标签将固定在左侧',
'is_full' => '全屏',
'is_full_description' => '开启后将隐藏该页面的菜单栏部分',
'parent_id_not_allow' => '父级菜单不允许设置为当前子菜单',
'component' => '组件',
'component_desc' => '默认为 amis , 非自定义前端页面请勿修改',
],
'extensions' => [
'name_invalid' => '无效的扩展名称',
'exists' => '该扩展已存在:',
'menu' => '扩展',
'page_title' => '扩展',
'create' => '创建',
'install' => '安装',
'create_extension' => '创建扩展',
'create_tips' => '创建成功后会在<br><b>:dir</b><br>目录下创建基础的扩展目录结构',
'local_install' => '本地安装',
'more_extensions' => '更多扩展',
'setting' => '设置',
'enable' => '启用',
'enable_confirm' => '确定要启用该扩展吗?',
'disable' => '禁用',
'disable_confirm' => '确定要禁用该扩展吗?',
'uninstall' => '卸载',
'uninstall_confirm' => '
<div class="text-danger">
确认卸载该扩展?<br>
卸载将会删除启用扩展后发布的所有文件及数据库, 且不可找回!!!<br>
如有重要数据请备份后再操作!!!<br>
<span class="text-info">扩展包文件将不会被删除, 请手动删除!!!</span>
</div>
',
'filter_placeholder' => '输入扩展名称',
'form' => [
'create_extension' => '创建扩展',
'name' => '名称',
'namespace' => '命名空间',
'create_description' => '创建成功后会在 :dir 目录下创建基础的扩展目录结构',
],
'card' => [
'author' => '作者',
'version' => '版本',
'homepage' => '主页',
'status' => '状态',
],
'status_map' => [
'enabled' => '已启用',
'disabled' => '已禁用',
],
'validation' => [
'file' => '请选择文件',
'invalid_package' => '无效的扩展包',
],
],
'export' => [
'title' => '导出',
'all' => '全部',
'page' => '本页',
'selected_rows' => '选中行',
'page_no_data' => '本页无数据',
'selected_rows_no_data' => '请选择要导出的数据',
'please_install_laravel_excel' => '请先安装 laravel-excel 扩展',
],
'keywords' => [
'search_name' => '名称/KEY',
'parent_keyword' => '父级关键字',
],
'articles' => [
'id' => '主键ID',
'title' => '标题',
'content' => '内容',
'cover' =>'封面',
'category' => '分类',
'tags' => '标签',
't_ids' => '标签',
'published_at' => '定时发布',
'published_at_g' => '发布时间',
'is_enable' => '显示',
'is_recommend' => '推荐',
'sort' => '排序',
'appendixes' => '附件',
'published_at_remark' => '*若未设置发布时间且操作设置为显示,则默认生成发布时间',
],
'ads' => [
'id' => 'ID',
'address' => '位置',
'resource' =>'内容',
'published_at' => '定时发布',
'published_at_g' => '发布时间',
'is_enable' => '显示',
'remark' => '备注',
'sort' => '排序',
'published_at_remark' => '*若未设置发布时间且操作设置为显示,则默认生成发布时间',
'jump_type' => '跳转类型',
'jump_config'=>'跳转配置',
'jump_config_arr'=>[
'web_link' => '网页地址',
'app_link' => '应用路径',
'mini_id' => '小程序ID',
'mini_link'=> '小程序路径'
],
]
];

View File

@ -0,0 +1,16 @@
<?php
return [
'dashboard' => '控制台',
'index' => '主页',
'admin_system' => '系统管理',
'admin_users' => '管理员',
'admin_roles' => '角色',
'admin_permission' => '权限',
'admin_menu' => '菜单',
'admin_setting' => '设置',
'keywords' => '数据字典',
'web_content' => '内容管理',
'articles' => '文章管理',
'ads' => '广告管理',
];

13
package.json 100644
View File

@ -0,0 +1,13 @@
{
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vite build"
},
"devDependencies": {
"axios": "^1.6.1",
"laravel-vite-plugin": "^0.8.0",
"vite": "^4.0.0"
}
}

31
phpunit.xml 100644
View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="CACHE_DRIVER" value="array"/>
<!-- <env name="DB_CONNECTION" value="sqlite"/> -->
<!-- <env name="DB_DATABASE" value=":memory:"/> -->
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>

21
public/.htaccess 100644
View File

@ -0,0 +1,21 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Binary file not shown.

File diff suppressed because one or more lines are too long

Some files were not shown because too many files have changed in this diff Show More