杂七杂八的清理工作

This commit is contained in:
Chenx221 2024-02-16 13:59:54 +08:00
parent b09d2e6c36
commit 7154ee9ce1
Signed by: chenx221
GPG Key ID: D7A9EC07024C3021
9 changed files with 140 additions and 47 deletions

View File

@ -7,6 +7,9 @@ use app\models\RenameForm;
use app\models\UploadForm; use app\models\UploadForm;
use app\models\ZipForm; use app\models\ZipForm;
use app\utils\FileTypeDetector; use app\utils\FileTypeDetector;
use Exception;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use wapmorgan\UnifiedArchive\Exceptions\ArchiveExtractionException; use wapmorgan\UnifiedArchive\Exceptions\ArchiveExtractionException;
use wapmorgan\UnifiedArchive\Exceptions\FileAlreadyExistsException; use wapmorgan\UnifiedArchive\Exceptions\FileAlreadyExistsException;
use wapmorgan\UnifiedArchive\Exceptions\UnsupportedOperationException; use wapmorgan\UnifiedArchive\Exceptions\UnsupportedOperationException;
@ -25,7 +28,7 @@ class HomeController extends Controller
{ {
protected string $pattern = '/^[^\p{C}:*?"<>|\\\\]+$/u'; protected string $pattern = '/^[^\p{C}:*?"<>|\\\\]+$/u';
public function behaviors() public function behaviors(): array
{ {
return array_merge( return array_merge(
parent::behaviors(), parent::behaviors(),
@ -51,13 +54,14 @@ class HomeController extends Controller
} }
/** /**
* diplay the page of the file manager (accepts a directory parameter like cd command) * display the page of the file manager (accepts a directory parameter like cd command)
* visit it via https://devs.chenx221.cyou:8081/index.php?r=home * visit it via https://devs.chenx221.cyou:8081/index.php?r=home
* *
* @param null $directory
* @return string|Response * @return string|Response
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionIndex($directory = null) public function actionIndex($directory = null): Response|string
{ {
if (Yii::$app->user->isGuest) { if (Yii::$app->user->isGuest) {
return $this->redirect(Yii::$app->user->loginUrl); return $this->redirect(Yii::$app->user->loginUrl);
@ -94,7 +98,7 @@ class HomeController extends Controller
* @return array 文件和文件夹内容数组 * @return array 文件和文件夹内容数组
* @throws NotFoundHttpException 如果路径不存在 * @throws NotFoundHttpException 如果路径不存在
*/ */
protected function getDirectoryContents($path) protected function getDirectoryContents(string $path): array
{ {
// 确定路径是否存在 // 确定路径是否存在
if (!is_dir($path)) { if (!is_dir($path)) {
@ -127,7 +131,7 @@ class HomeController extends Controller
* @param string $relativePath 文件的相对路径 * @param string $relativePath 文件的相对路径
* @throws NotFoundHttpException 如果文件不存在 * @throws NotFoundHttpException 如果文件不存在
*/ */
public function actionDownload($relativePath) public function actionDownload(string $relativePath): void
{ {
// 对相对路径进行解码 // 对相对路径进行解码
$relativePath = rawurldecode($relativePath); $relativePath = rawurldecode($relativePath);
@ -161,7 +165,7 @@ class HomeController extends Controller
* @return string|Response|null * @return string|Response|null
* @throws NotFoundHttpException 如果文件或文件夹不存在 * @throws NotFoundHttpException 如果文件或文件夹不存在
*/ */
public function actionRename() public function actionRename(): Response|string|null
{ {
$relativePath = Yii::$app->request->post('relativePath'); $relativePath = Yii::$app->request->post('relativePath');
@ -183,7 +187,11 @@ class HomeController extends Controller
$model = new RenameForm(); $model = new RenameForm();
$model->newName = ArrayHelper::getValue(Yii::$app->request->post('RenameForm'), 'newName'); try {
$model->newName = ArrayHelper::getValue(Yii::$app->request->post('RenameForm'), 'newName');
} catch (Exception) {
throw new NotFoundHttpException('Invalid request.');
}
if (!$model->validate()) { if (!$model->validate()) {
Yii::$app->response->statusCode = 400; Yii::$app->response->statusCode = 400;
@ -209,7 +217,7 @@ class HomeController extends Controller
* 删除文件或文件夹 * 删除文件或文件夹
* @throws NotFoundHttpException 如果文件或文件夹不存在 * @throws NotFoundHttpException 如果文件或文件夹不存在
*/ */
public function actionDelete() public function actionDelete(): Response
{ {
$relativePaths = Yii::$app->request->post('relativePath'); $relativePaths = Yii::$app->request->post('relativePath');
if (!is_array($relativePaths)) { if (!is_array($relativePaths)) {
@ -253,7 +261,7 @@ class HomeController extends Controller
* 递归删除目录及其内容 * 递归删除目录及其内容
* @param string $dir 目录路径 * @param string $dir 目录路径
*/ */
protected function deleteDirectory($dir): bool protected function deleteDirectory(string $dir): bool
{ {
if (!is_dir($dir)) { if (!is_dir($dir)) {
return false; return false;
@ -282,9 +290,9 @@ class HomeController extends Controller
* 注意,已存在的同名文件会被覆盖 * 注意,已存在的同名文件会被覆盖
* https://devs.chenx221.cyou:8081/index.php?r=home%2Fupload * https://devs.chenx221.cyou:8081/index.php?r=home%2Fupload
* *
* @return string|Response * @return int
*/ */
public function actionUpload() public function actionUpload(): int
{ {
$model = new UploadForm(); $model = new UploadForm();
$model->targetDir = Yii::$app->request->post('targetDir', '.'); $model->targetDir = Yii::$app->request->post('targetDir', '.');
@ -316,9 +324,9 @@ class HomeController extends Controller
/** /**
* 新建文件夹 * 新建文件夹
* *
* @return array|string|Response * @return array|Response
*/ */
public function actionNewFolder() public function actionNewFolder(): Response|array
{ {
$relativePath = Yii::$app->request->post('relativePath'); $relativePath = Yii::$app->request->post('relativePath');
@ -354,10 +362,10 @@ class HomeController extends Controller
* @param string $directory 目录路径 * @param string $directory 目录路径
* @return int 目录的大小(字节) * @return int 目录的大小(字节)
*/ */
protected function getDirectorySize($directory) protected function getDirectorySize(string $directory): int
{ {
$size = 0; $size = 0;
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory)); $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));
foreach ($files as $file) { foreach ($files as $file) {
if ($file->isFile()) { if ($file->isFile()) {
$size += $file->getSize(); $size += $file->getSize();
@ -369,7 +377,7 @@ class HomeController extends Controller
/** /**
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionDownloadFolder($relativePath) public function actionDownloadFolder($relativePath): Response|\yii\console\Response
{ {
$relativePath = rawurldecode($relativePath); $relativePath = rawurldecode($relativePath);
if (!preg_match($this->pattern, $relativePath) || str_contains($relativePath, '..')) { if (!preg_match($this->pattern, $relativePath) || str_contains($relativePath, '..')) {
@ -391,12 +399,12 @@ class HomeController extends Controller
$zipPath = $tempDir . basename($absolutePath) . '.zip'; $zipPath = $tempDir . basename($absolutePath) . '.zip';
if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE)) { if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE)) {
$files = new \RecursiveIteratorIterator( $files = new RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($absolutePath), new RecursiveDirectoryIterator($absolutePath),
\RecursiveIteratorIterator::LEAVES_ONLY RecursiveIteratorIterator::LEAVES_ONLY
); );
foreach ($files as $name => $file) { foreach ($files as $file) {
if (!$file->isDir()) { if (!$file->isDir()) {
$filePath = $file->getRealPath(); $filePath = $file->getRealPath();
$relativePath = substr($filePath, strlen($absolutePath) + 1); $relativePath = substr($filePath, strlen($absolutePath) + 1);
@ -415,7 +423,7 @@ class HomeController extends Controller
* @return \yii\console\Response|Response * @return \yii\console\Response|Response
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionMultiFfZipDl() public function actionMultiFfZipDl(): Response|\yii\console\Response
{ {
// 获取请求中的文件和文件夹的相对路径 // 获取请求中的文件和文件夹的相对路径
$relativePaths = Yii::$app->request->post('relativePaths'); $relativePaths = Yii::$app->request->post('relativePaths');
@ -465,11 +473,11 @@ class HomeController extends Controller
if (is_file($absolutePath)) { if (is_file($absolutePath)) {
$zip->addFile($absolutePath, $relativePath); $zip->addFile($absolutePath, $relativePath);
} else if (is_dir($absolutePath)) { } else if (is_dir($absolutePath)) {
$files = new \RecursiveIteratorIterator( $files = new RecursiveIteratorIterator(
new \RecursiveDirectoryIterator($absolutePath), new RecursiveDirectoryIterator($absolutePath),
\RecursiveIteratorIterator::LEAVES_ONLY RecursiveIteratorIterator::LEAVES_ONLY
); );
foreach ($files as $name => $file) { foreach ($files as $file) {
if (!$file->isDir()) { if (!$file->isDir()) {
$filePath = $file->getRealPath(); $filePath = $file->getRealPath();
$relativePathInZip = $relativePath . '/' . substr($filePath, strlen($absolutePath) + 1); $relativePathInZip = $relativePath . '/' . substr($filePath, strlen($absolutePath) + 1);
@ -488,7 +496,7 @@ class HomeController extends Controller
* @return Response * @return Response
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionZip() public function actionZip(): Response
{ {
$model = new ZipForm(); $model = new ZipForm();
$relativePaths = json_decode(Yii::$app->request->post('relativePath'), true); $relativePaths = json_decode(Yii::$app->request->post('relativePath'), true);
@ -514,9 +522,9 @@ class HomeController extends Controller
try { try {
UnifiedArchive::create($absolutePaths, $zipPath); UnifiedArchive::create($absolutePaths, $zipPath);
Yii::$app->session->setFlash('success', '打包成功'); Yii::$app->session->setFlash('success', '打包成功');
} catch (FileAlreadyExistsException $e) { } catch (FileAlreadyExistsException) {
Yii::$app->session->setFlash('error', '目标文件夹已存在同名压缩档案'); Yii::$app->session->setFlash('error', '目标文件夹已存在同名压缩档案');
} catch (UnsupportedOperationException $e) { } catch (UnsupportedOperationException) {
Yii::$app->session->setFlash('error', '不支持的操作'); Yii::$app->session->setFlash('error', '不支持的操作');
} }
} }
@ -526,7 +534,7 @@ class HomeController extends Controller
/** /**
* @throws NotFoundHttpException * @throws NotFoundHttpException
*/ */
public function actionUnzip() public function actionUnzip(): array
{ {
$relativePath = Yii::$app->request->post('relativePath'); $relativePath = Yii::$app->request->post('relativePath');
if (!preg_match($this->pattern, $relativePath) || str_contains($relativePath, '..')) { if (!preg_match($this->pattern, $relativePath) || str_contains($relativePath, '..')) {
@ -550,15 +558,15 @@ class HomeController extends Controller
try { try {
$archive->extract($targetDirectory); $archive->extract($targetDirectory);
Yii::$app->session->setFlash('success', 'Folder created successfully.'); Yii::$app->session->setFlash('success', 'Folder created successfully.');
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; Yii::$app->response->format = Response::FORMAT_JSON;
return [ return [
'status' => 200, 'status' => 200,
'directory' => pathinfo($relativePath, PATHINFO_FILENAME) . '_' . time(), 'directory' => pathinfo($relativePath, PATHINFO_FILENAME) . '_' . time(),
]; ];
} catch (ArchiveExtractionException $e) { } catch (ArchiveExtractionException) {
$this->deleteDirectory($targetDirectory); $this->deleteDirectory($targetDirectory);
Yii::$app->session->setFlash('error', 'Failed to extract the archive.'); Yii::$app->session->setFlash('error', 'Failed to extract the archive.');
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; Yii::$app->response->format = Response::FORMAT_JSON;
return [ return [
'status' => 500, 'status' => 500,
'directory' => pathinfo($relativePath, PATHINFO_FILENAME) . '_' . time(), 'directory' => pathinfo($relativePath, PATHINFO_FILENAME) . '_' . time(),
@ -572,7 +580,7 @@ class HomeController extends Controller
* *
* @return Response * @return Response
*/ */
public function actionPaste() public function actionPaste(): Response
{ {
// 获取请求中的操作类型、相对路径和目标目录 // 获取请求中的操作类型、相对路径和目标目录
$operation = Yii::$app->request->post('operation'); $operation = Yii::$app->request->post('operation');
@ -650,7 +658,7 @@ class HomeController extends Controller
* @param string $destination 目标目录路径 * @param string $destination 目标目录路径
* @return bool 操作是否成功 * @return bool 操作是否成功
*/ */
protected function copyDirectory($source, $destination) protected function copyDirectory(string $source, string $destination): bool
{ {
// 创建目标目录 // 创建目标目录
if (!mkdir($destination)) { if (!mkdir($destination)) {
@ -695,7 +703,7 @@ class HomeController extends Controller
* @param string $destination 目标目录路径 * @param string $destination 目标目录路径
* @return bool 操作是否成功 * @return bool 操作是否成功
*/ */
protected function moveDirectory($source, $destination) protected function moveDirectory(string $source, string $destination): bool
{ {
// 创建目标目录 // 创建目标目录
if (!mkdir($destination)) { if (!mkdir($destination)) {
@ -739,4 +747,30 @@ class HomeController extends Controller
return true; return true;
} }
/**
* @return array
* @throws NotFoundHttpException
*/
public function actionChecksum(): array
{
$relativePath = Yii::$app->request->post('relativePath');
if (!preg_match($this->pattern, $relativePath) || str_contains($relativePath, '..')) {
throw new NotFoundHttpException('Invalid file path.');
}
$absolutePath = Yii::getAlias(Yii::$app->params['dataDirectory']) . '/' . Yii::$app->user->id . '/' . $relativePath;
if (!is_file($absolutePath)) {
throw new NotFoundHttpException('The specified path does not point to a file.');
}
// 计算文件的校验值
$crc32b = hash_file('crc32b', $absolutePath);
$sha256 = hash_file('sha256', $absolutePath);
// 将校验值返回给客户端
Yii::$app->response->format = Response::FORMAT_JSON;
return [
'crc32b' => strtoupper($crc32b),
'sha256' => strtoupper($sha256),
];
}
} }

View File

@ -66,7 +66,7 @@ class UserController extends Controller
/** /**
* Creates a new User model. * Creates a new User model.
* If creation is successful, the browser will be redirected to the 'view' page. * If creation is successful, the browser will be redirected to the 'view' page.
* @return string|\yii\web\Response * @return string|Response
*/ */
public function actionCreate() public function actionCreate()
{ {
@ -89,7 +89,7 @@ class UserController extends Controller
* Updates an existing User model. * Updates an existing User model.
* If update is successful, the browser will be redirected to the 'view' page. * If update is successful, the browser will be redirected to the 'view' page.
* @param int $id ID * @param int $id ID
* @return string|\yii\web\Response * @return string|Response
* @throws NotFoundHttpException if the model cannot be found * @throws NotFoundHttpException if the model cannot be found
*/ */
public function actionUpdate($id) public function actionUpdate($id)
@ -109,7 +109,7 @@ class UserController extends Controller
* Deletes an existing User model. * Deletes an existing User model.
* If deletion is successful, the browser will be redirected to the 'index' page. * If deletion is successful, the browser will be redirected to the 'index' page.
* @param int $id ID * @param int $id ID
* @return \yii\web\Response * @return Response
* @throws NotFoundHttpException if the model cannot be found * @throws NotFoundHttpException if the model cannot be found
*/ */
public function actionDelete($id) public function actionDelete($id)
@ -139,7 +139,7 @@ class UserController extends Controller
* Displays the login page. * Displays the login page.
* visit via https://devs.chenx221.cyou:8081/index.php?r=user%2Flogin * visit via https://devs.chenx221.cyou:8081/index.php?r=user%2Flogin
* *
* @return string|\yii\web\Response * @return string|Response
*/ */
public function actionLogin() public function actionLogin()
{ {
@ -163,7 +163,7 @@ class UserController extends Controller
/** /**
* Logs out the current user. * Logs out the current user.
* @return \yii\web\Response * @return Response
*/ */
public function actionLogout() public function actionLogout()
{ {

View File

@ -43,6 +43,6 @@ class NewFolderForm extends Model
$userHomeDir = Yii::getAlias(Yii::$app->params['dataDirectory']) . '/' . Yii::$app->user->id; $userHomeDir = Yii::getAlias(Yii::$app->params['dataDirectory']) . '/' . Yii::$app->user->id;
$absolutePath = $userHomeDir . '/' . $this->relativePath . '/' . $this->folderName; $absolutePath = $userHomeDir . '/' . $this->relativePath . '/' . $this->folderName;
return mkdir($absolutePath, 0777); return mkdir($absolutePath);
} }
} }

View File

@ -3,6 +3,7 @@
namespace app\models; namespace app\models;
use Yii; use Yii;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface; use yii\web\IdentityInterface;
/** /**
@ -15,7 +16,7 @@ use yii\web\IdentityInterface;
* @property string|null $email 邮箱 * @property string|null $email 邮箱
* @property int|null $status 用户状态 * @property int|null $status 用户状态
*/ */
class User extends \yii\db\ActiveRecord implements IdentityInterface class User extends ActiveRecord implements IdentityInterface
{ {
public $password2; // 重复密码 public $password2; // 重复密码
public $rememberMe; // 记住我 public $rememberMe; // 记住我

32
qodana.yaml Normal file
View File

@ -0,0 +1,32 @@
#-------------------------------------------------------------------------------#
# Qodana analysis is configured by qodana.yaml file #
# https://www.jetbrains.com/help/qodana/qodana-yaml.html #
#-------------------------------------------------------------------------------#
version: "1.0"
#Specify inspection profile for code analysis
profile:
name: qodana.starter
#Enable inspections
#include:
# - name: <SomeEnabledInspectionId>
#Disable inspections
#exclude:
# - name: <SomeDisabledInspectionId>
# paths:
# - <path/where/not/run/inspection>
php:
version: 8.2 #(Applied in CI/CD pipeline)
#Execute shell command before Qodana execution (Applied in CI/CD pipeline)
#bootstrap: sh ./prepare-qodana.sh
#Install IDE plugins before Qodana execution (Applied in CI/CD pipeline)
#plugins:
# - id: <plugin.id> #(plugin id can be found at https://plugins.jetbrains.com)
#Specify Qodana linter for analysis (Applied in CI/CD pipeline)
linter: jetbrains/qodana-php:latest

View File

@ -76,8 +76,7 @@ $this->registerCssFile('@web/css/home_style.css');
]); ]);
?> ?>
<nav style="--bs-breadcrumb-divider: url(&#34;data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Cpath d='M2.5 0L1 1.5 3.5 4 1 6.5 2.5 8l4-4-4-4z' fill='%236c757d'/%3E%3C/svg%3E&#34;);" <nav aria-label="breadcrumb">
aria-label="breadcrumb">
<ol class="breadcrumb"> <ol class="breadcrumb">
<?= Html::a('<i class="fa-solid fa-house"></i> HOME', ['home/index'], ['class' => 'breadcrumb-item']) ?> <?= Html::a('<i class="fa-solid fa-house"></i> HOME', ['home/index'], ['class' => 'breadcrumb-item']) ?>
<?php if ($directory !== null): ?> <?php if ($directory !== null): ?>
@ -228,6 +227,15 @@ echo Html::submitButton('创建', ['class' => 'btn btn-primary']);
ActiveForm::end(); ActiveForm::end();
Modal::end(); Modal::end();
Modal::begin([
'id' => 'checksumModal',
'title' => '文件校验信息',
'size' => 'modal-lg',
]);
echo Html::tag('p', '', ['id' => 'crc32b']);
echo Html::tag('p', '', ['id' => 'sha256']);
Modal::end();
$this->registerJsFile('@web/js/home_script.js', ['depends' => [JqueryAsset::class], 'position' => View::POS_END]); $this->registerJsFile('@web/js/home_script.js', ['depends' => [JqueryAsset::class], 'position' => View::POS_END]);
?> ?>

View File

@ -78,7 +78,7 @@ $this->registerLinkTag(['rel' => 'icon', 'type' => 'image/x-icon', 'href' => Yii
<div class="row text-muted"> <div class="row text-muted">
<div class="col-md-6 text-center text-md-start"><?php echo '&copy; Created & Design by ' . '<a href="https://blog.chenx221.cyou" rel="external">Chenx221</a> | 2024 - ' . date('Y') ?></div> <div class="col-md-6 text-center text-md-start"><?php echo '&copy; Created & Design by ' . '<a href="https://blog.chenx221.cyou" rel="external">Chenx221</a> | 2024 - ' . date('Y') ?></div>
<div class="col-md-6 text-center text-md-end"><?= Yii::t('yii', 'Powered by {yii}', [ <div class="col-md-6 text-center text-md-end"><?= Yii::t('yii', 'Powered by {yii}', [
'yii' => '<a href="https://www.yiiframework.com/" rel="external">' . \Yii::t('yii', 'yii' => '<a href="https://www.yiiframework.com/" rel="external">' . Yii::t('yii',
'Yii Framework') . '</a>', 'Yii Framework') . '</a>',
]) ?></div> ]) ?></div>
</div> </div>

View File

@ -1,3 +1,6 @@
nav {
--bs-breadcrumb-divider: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='8' height='8'%3E%3Cpath d='M2.5 0L1 1.5 3.5 4 1 6.5 2.5 8l4-4-4-4z' fill='%236c757d'/%3E%3C/svg%3E");
}
table a { table a {
text-decoration-line: none; text-decoration-line: none;
color: black; color: black;

View File

@ -168,8 +168,23 @@ $(document).on('click', '.batch-paste-btn', function () {
}); });
$(document).on('click', '.calc-sum-btn', function () { $(document).on('click', '.calc-sum-btn', function () {
console.log('计算文件校验值按钮被点击'); var relativePath = $('.select-item:checked').first().data('relativePath');
// 在这里添加你的代码 $.ajax({
type: "POST",
url: "index.php?r=home%2Fchecksum",
data: { relativePath: relativePath },
dataType: "json",
success: function(response) {
// 更新模态框中的内容
$('#crc32b').text('CRC32B: ' + response.crc32b);
$('#sha256').text('SHA256: ' + response.sha256);
// 显示模态框
$('#checksumModal').modal('show');
},
error: function() {
console.error('AJAX request failed.');
}
});
}); });
$(document).on('click', '.single-share-btn', function () { $(document).on('click', '.single-share-btn', function () {