Upload 17 files
Browse filesFiles changed (17)
- .gitignoreAdded+8
- .htaccessAdded+17
- .nginxAdded+14
- DockerfileAdded+72
- FileShare.phpAdded+240
- LICENSEAdded+674
- api.phpAdded+93
- css/marked.cssAdded+132
- css/style.cssAdded+892
- docker-compose.ymlAdded+11
- favicon.pngAdded
- file_api.phpAdded+112
- index.phpAdded+814
- init.phpAdded+70
- router.phpAdded+72
- settings.phpAdded+116
- upload.phpAdded+118
12345678/data/*.db/data/*.sqlite/uploads/files/*/uploads/images/*!uploads/files/.htaccess!uploads/images/.htaccess!uploads/files/index.html!uploads/images/index.html1234567891011121314151617AddType application/x-httpd-php83 .php
RewriteEngine On
RewriteCond %{REQUEST_URI} ^/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$RewriteRule ^(.*)$ /index.php?id=%1 [L]
<FilesMatch "\.(db|bak|sql)$"> Require all denied</FilesMatch>
# 添加默认文档类型DirectoryIndex index.php
# 添加错误处理php_flag display_errors onphp_value error_reporting E_ALL1234567891011121314location ~* \.(db|bak|sql)$ { deny all; return 403;}
location / { try_files $uri $uri/ @rewrite;}
location @rewrite { if ($uri ~* "^/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$") { rewrite ^/(.*)$ /index.php?id=$1 last; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172FROM ubuntu:22.04
# 设置非交互模式和时区ENV DEBIAN_FRONTEND=noninteractiveENV TZ=Asia/Shanghai
# 更新包列表并安装基础依赖RUN apt-get update && apt-get install -y \ software-properties-common \ curl \ wget \ git \ unzip \ libsqlite3-dev \ && rm -rf /var/lib/apt/lists/*
# 添加 PHP 仓库并安装 PHPRUN add-apt-repository ppa:ondrej/php && \ apt-get update && \ apt-get install -y \ php8.3-cli \ php8.3-fpm \ php8.3-common \ php8.3-sqlite3 \ php8.3-xml \ php8.3-curl \ php8.3-mbstring \ && rm -rf /var/lib/apt/lists/*
# 设置工作目录WORKDIR /var/www/html
# 复制项目文件COPY . /var/www/html/
# 创建必要的目录和文件RUN mkdir -p /var/www/html/data \ /var/www/html/uploads/images \ /var/www/html/uploads/files \ && touch /var/www/html/data/notes.db \ && chown -R www-data:www-data /var/www/html \ && find /var/www/html -type d -exec chmod 755 {} \; \ && find /var/www/html -type f -exec chmod 644 {} \; \ && chmod -R 777 /var/www/html/data \ && chmod -R 777 /var/www/html/uploads \ && chmod 666 /var/www/html/data/notes.db
# 配置 PHPRUN echo "display_errors = On" >> /etc/php/8.3/cli/conf.d/error-reporting.ini && \ echo "error_reporting = E_ALL" >> /etc/php/8.3/cli/conf.d/error-reporting.ini && \ echo "log_errors = On" >> /etc/php/8.3/cli/conf.d/error-reporting.ini && \ echo "error_log = /dev/stderr" >> /etc/php/8.3/cli/conf.d/error-reporting.ini && \ echo "upload_max_filesize = 10G" >> /etc/php/8.3/cli/conf.d/uploads.ini && \ echo "post_max_size = 10G" >> /etc/php/8.3/cli/conf.d/uploads.ini && \ echo "memory_limit = 12G" >> /etc/php/8.3/cli/conf.d/uploads.ini && \ echo "max_execution_time = 3600" >> /etc/php/8.3/cli/conf.d/uploads.ini && \ echo "max_input_time = 3600" >> /etc/php/8.3/cli/conf.d/uploads.ini
# 创建启动脚本RUN echo '#!/bin/bash\n\# 启动 PHP 服务器\n\exec php -d upload_max_filesize=10G -d post_max_size=10G -d memory_limit=12G -d max_execution_time=3600 -d max_input_time=3600 -S 0.0.0.0:7860 -t /var/www/html /var/www/html/router.php 2>&1 | grep -v "Accepted\|Closing\|preconnection"' > /usr/local/bin/docker-entrypoint.sh \ && chmod +x /usr/local/bin/docker-entrypoint.sh
# 暴露端口EXPOSE 7860
# 切换到 www-data 用户USER www-data
# 启动 PHP 内置服务器CMD ["/usr/local/bin/docker-entrypoint.sh"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240<?phpclass FileShare { private $db; private $settings; private $upload_dir; private $cleanup_interval = 3600; // 清理间隔:1小时 public function __construct() { $this->settings = new Settings(); $this->db = new SQLite3($this->settings->getSetting('db_path')); $this->upload_dir = __DIR__ . '/uploads/files/'; // 确保上传目录存在并创建必要的保护文件 $this->initializeUploadDirectory(); // 检查是否需要清理过期文件 $this->checkAndCleanup(); } // 初始化上传目录和保护文件 private function initializeUploadDirectory() { // 创建上传目录 if (!is_dir($this->upload_dir)) { if (!mkdir($this->upload_dir, 0755, true)) { throw new Exception('无法创建上传目录,请检查权限'); } // 创建 .htaccess 文件来保护上传目录 $htaccess = $this->upload_dir . '.htaccess'; if (!file_exists($htaccess)) { $htaccess_content = "Options -Indexes\n"; $htaccess_content .= "DirectoryIndex 403.html\n"; $htaccess_content .= "AddType text/plain .php\n"; $htaccess_content .= "AddType text/plain .html\n"; $htaccess_content .= "AddType text/plain .htm\n"; $htaccess_content .= "AddType text/plain .htaccess\n"; file_put_contents($htaccess, $htaccess_content); } // 创建 index.html 文件来防止目录列表 $index_html = $this->upload_dir . 'index.html'; if (!file_exists($index_html)) { file_put_contents($index_html, '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1></body></html>'); } // 创建 403.html 文件 $forbidden_page = $this->upload_dir . '403.html'; if (!file_exists($forbidden_page)) { file_put_contents($forbidden_page, '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1><p>Access to this directory is forbidden.</p></body></html>'); } } // 设置目录权限 chmod($this->upload_dir, 0755); } // 检查并清理过期文件 private function checkAndCleanup() { $lastCleanup = $this->settings->getSetting('last_cleanup', 0); // 使用中国时间 date_default_timezone_set('Asia/Shanghai'); $currentTime = time(); if ($currentTime - $lastCleanup > $this->cleanup_interval) { $this->settings->setSetting('last_cleanup', $currentTime); $stmt = $this->db->prepare(' SELECT code, type, filepath FROM files WHERE expires_at < :current_time OR (max_downloads > 0 AND current_downloads >= max_downloads) '); $stmt->bindValue(':current_time', $currentTime, SQLITE3_INTEGER); $result = $stmt->execute(); // 删除过期的文件和记录 while ($row = $result->fetchArray(SQLITE3_ASSOC)) { if ($row['type'] === 'file' && $row['filepath'] && file_exists($row['filepath'])) { unlink($row['filepath']); } $deleteStmt = $this->db->prepare('DELETE FROM files WHERE code = :code'); $deleteStmt->bindValue(':code', $row['code'], SQLITE3_TEXT); $deleteStmt->execute(); } // 清理空目录 $this->cleanEmptyDirectories($this->upload_dir); } } // 清理空目录 private function cleanEmptyDirectories($dir) { if (!is_dir($dir)) { return; } $files = scandir($dir); foreach ($files as $file) { if ($file === '.' || $file === '..' || $file === '.htaccess' || $file === 'index.html' || $file === '403.html') { continue; } $path = $dir . '/' . $file; if (is_dir($path)) { $this->cleanEmptyDirectories($path); // 如果目录为空(只包含 . 和 ..),则删除 $subFiles = scandir($path); if (count($subFiles) <= 2) { // 只有 . 和 .. rmdir($path); } } } } // 生成随机提取码 private function generateCode($length = 6) { $chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'; $code = ''; for ($i = 0; $i < $length; $i++) { $code .= $chars[random_int(0, strlen($chars) - 1)]; } return $code; } // 保存文件或文��� public function save($data) { $this->checkAndCleanup(); $code = $this->generateCode(); // 使用中国时间 date_default_timezone_set('Asia/Shanghai'); $created_at = time(); // 当前中国时间 $expires_at = $created_at + intval($data['expire_time']); // 过期时间也是中国时间 if (isset($_FILES['file'])) { // 处理文件上传 $file = $_FILES['file']; $filename = $file['name']; $filepath = $this->upload_dir . uniqid() . '_' . bin2hex(random_bytes(4)) . '_' . $filename; if (!move_uploaded_file($file['tmp_name'], $filepath)) { throw new Exception('文件上传失败'); } $type = 'file'; $content = null; } else { // 处理文本内容 $filename = null; $filepath = null; $type = 'text'; $content = $data['content']; } $stmt = $this->db->prepare(' INSERT INTO files (code, filename, filepath, content, type, created_at, expires_at, max_downloads) VALUES (:code, :filename, :filepath, :content, :type, :created_at, :expires_at, :max_downloads) '); $stmt->bindValue(':code', $code, SQLITE3_TEXT); $stmt->bindValue(':filename', $filename, SQLITE3_TEXT); $stmt->bindValue(':filepath', $filepath, SQLITE3_TEXT); $stmt->bindValue(':content', $content, SQLITE3_TEXT); $stmt->bindValue(':type', $type, SQLITE3_TEXT); $stmt->bindValue(':created_at', $created_at, SQLITE3_INTEGER); $stmt->bindValue(':expires_at', $expires_at, SQLITE3_INTEGER); $stmt->bindValue(':max_downloads', intval($data['max_downloads']), SQLITE3_INTEGER); if ($stmt->execute()) { return $code; } throw new Exception('保存失败'); } // 获取文件或文本 public function get($code) { $this->checkAndCleanup(); $stmt = $this->db->prepare('SELECT * FROM files WHERE code = :code'); $stmt->bindValue(':code', $code, SQLITE3_TEXT); $result = $stmt->execute(); if ($row = $result->fetchArray(SQLITE3_ASSOC)) { // 使用中国时间进行比较 date_default_timezone_set('Asia/Shanghai'); if (time() > $row['expires_at']) { $this->delete($code); return null; } // 检查下载次数 if ($row['max_downloads'] > 0 && $row['current_downloads'] >= $row['max_downloads']) { $this->delete($code); return null; } // 更新下载次数 $stmt = $this->db->prepare(' UPDATE files SET current_downloads = current_downloads + 1 WHERE code = :code '); $stmt->bindValue(':code', $code, SQLITE3_TEXT); $stmt->execute(); // 返回更多文件信息 return [ 'type' => $row['type'], 'content' => $row['content'], 'filename' => $row['filename'], 'filepath' => $row['filepath'], 'current_downloads' => $row['current_downloads'], 'max_downloads' => $row['max_downloads'], 'expires_at' => $row['expires_at'] ]; } return null; } // 删除文件或文本 private function delete($code) { $stmt = $this->db->prepare('SELECT * FROM files WHERE code = :code'); $stmt->bindValue(':code', $code, SQLITE3_TEXT); $result = $stmt->execute(); if ($row = $result->fetchArray(SQLITE3_ASSOC)) { if ($row['type'] === 'file' && $row['filepath'] && file_exists($row['filepath'])) { unlink($row['filepath']); } } $stmt = $this->db->prepare('DELETE FROM files WHERE code = :code'); $stmt->bindValue(':code', $code, SQLITE3_TEXT); $stmt->execute(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293<?php// api.phpheader('Content-Type: application/json');
require_once 'settings.php';
class PasteAPI { private $db; private $settings; public function __construct() { $this->settings = new Settings(); $this->db = new SQLite3($this->settings->getSetting('db_path')); } public function createPaste($data) { // 验证输入 if (empty($data['content'])) { return ['status' => 'error', 'message' => 'Content is required']; } // 验证和规范化参数 $expire_time = isset($data['expire_time']) ? (int)$data['expire_time'] : 2592000; // 默认1个月 $max_expire_time = (int)$this->settings->getSetting('max_expire_time', 31536000); if ($expire_time > $max_expire_time) { $expire_time = $max_expire_time; } $max_views = isset($data['max_views']) ? (int)$data['max_views'] : 0; if ($max_views > 25565) { $max_views = 25565; } $is_markdown = isset($data['is_markdown']) && $data['is_markdown'] ? 1 : 0; $is_encrypted = isset($data['is_encrypted']) && $data['is_encrypted'] ? 1 : 0; // 生成UUID $uuid = $this->generateUUID(); // 准备数据 $now = time(); $expires_at = $now + $expire_time; // 插入数据 $stmt = $this->db->prepare('INSERT INTO notes ( uuid, content, created_at, expires_at, max_views, current_views, is_encrypted, is_markdown ) VALUES ( :uuid, :content, :created_at, :expires_at, :max_views, 0, :is_encrypted, :is_markdown )'); $stmt->bindValue(':uuid', $uuid, SQLITE3_TEXT); $stmt->bindValue(':content', $data['content'], SQLITE3_TEXT); $stmt->bindValue(':created_at', $now, SQLITE3_INTEGER); $stmt->bindValue(':expires_at', $expires_at, SQLITE3_INTEGER); $stmt->bindValue(':max_views', $max_views, SQLITE3_INTEGER); $stmt->bindValue(':is_encrypted', $is_encrypted, SQLITE3_INTEGER); $stmt->bindValue(':is_markdown', $is_markdown, SQLITE3_INTEGER); if ($stmt->execute()) { $response = ['status' => 'success', 'uuid' => $uuid]; if ($is_encrypted && isset($data['encryption_key'])) { $response['encryption_key'] = $data['encryption_key']; } return $response; } return ['status' => 'error', 'message' => 'Failed to create paste']; } private function generateUUID() { return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x', mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0x0fff) | 0x4000, mt_rand(0, 0x3fff) | 0x8000, mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff) ); }}
// 处理请求$method = $_SERVER['REQUEST_METHOD'];$api = new PasteAPI();
if ($method === 'POST') { $data = json_decode(file_get_contents('php://input'), true); echo json_encode($api->createPaste($data));} else { http_response_code(405); echo json_encode(['status' => 'error', 'message' => 'Method not allowed']);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132/* Markdown styling */#markdown-content { line-height: 1.8; color: var(--text-color);}
#markdown-content h1,#markdown-content h2,#markdown-content h3,#markdown-content h4,#markdown-content h5,#markdown-content h6 { margin: 1.5rem 0 1rem; line-height: 1.25; font-weight: 600;}
#markdown-content h1 { font-size: 2em; }#markdown-content h2 { font-size: 1.5em; }#markdown-content h3 { font-size: 1.25em; }#markdown-content h4 { font-size: 1em; }#markdown-content h5 { font-size: 0.875em; }#markdown-content h6 { font-size: 0.85em; }
#markdown-content p { margin-bottom: 1rem;}
#markdown-content strong { font-weight: 600;}
#markdown-content em { font-style: italic;}
#markdown-content blockquote { padding: 0.5rem 1rem; margin: 1rem 0; border-left: 4px solid var(--primary-color); background: rgba(0, 0, 0, 0.05);}
#markdown-content code { background: rgba(0, 0, 0, 0.05); padding: 0.2rem 0.4rem; border-radius: 4px; font-family: 'Monaco', 'Consolas', monospace; font-size: 0.9em;}
#markdown-content pre { background: rgba(0, 0, 0, 0.05); padding: 1rem; border-radius: 8px; overflow-x: auto; margin: 1rem 0;}
#markdown-content pre code { background: none; padding: 0; border-radius: 0;}
#markdown-content ul,#markdown-content ol { margin: 1rem 0; padding-left: 2rem;}
#markdown-content li { margin: 0.5rem 0;}
#markdown-content table { border-collapse: collapse; width: 100%; margin: 1rem 0;}
#markdown-content table th,#markdown-content table td { border: 1px solid var(--border-color); padding: 0.5rem;}
#markdown-content table th { background: rgba(0, 0, 0, 0.05); font-weight: 600;}
#markdown-content hr { border: none; border-top: 2px solid var(--border-color); margin: 2rem 0;}
#markdown-content img { max-width: 100%; height: auto; border-radius: 8px; margin: 1rem 0;}
#markdown-content a { color: var(--primary-color); text-decoration: none;}
#markdown-content a:hover { text-decoration: underline;}
/* Dark mode adjustments for markdown */@media (prefers-color-scheme: dark) { #markdown-content blockquote { background: rgba(255, 255, 255, 0.05); }
#markdown-content code { background: rgba(255, 255, 255, 0.1); }
#markdown-content pre { background: rgba(255, 255, 255, 0.05); }
#markdown-content table th { background: rgba(255, 255, 255, 0.05); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892/* Reset and base styles */:root { --primary-color: #3498db; --primary-hover: #2980b9; --text-color: #2c3e50; /* 更深的默认文本颜色 */ --text-content: #1a1a1a; /* 新增:笔记内容的颜色 */ --bg-color: #f9f9f9; --container-bg: #ffffff; --border-color: #ddd; /* 修改为更明显的边框颜色 */ --success-color: #2ecc71; --shadow: 0 2px 15px rgba(0, 0, 0, 0.1);}
* { margin: 0; padding: 0; box-sizing: border-box;}
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; line-height: 1.6; color: var(--text-color); background: var(--bg-color) url('https://image.ulaara.xyz/file/1729940342977_pFyErOU.png') no-repeat center center fixed; background-size: cover; min-height: 100vh; padding: 20px;}
/* Container styling */.container { max-width: 1200px; margin: 0 auto; background: var(--container-bg); padding: 2rem; border-radius: 12px; box-shadow: var(--shadow); backdrop-filter: blur(10px); background-color: rgba(255, 255, 255, 0.9); /* 添加半透明背景 */}
/* 深色模式下的调整 */@media (prefers-color-scheme: dark) { .container { background-color: rgba(45, 45, 45, 0.9); /* 深色模式下的半透明背景 */ }}
/* Header styling */h1 { color: var(--text-color); font-size: 2.5rem; font-weight: 700; margin-bottom: 0.5rem;}
p { color: #666; margin-bottom: 2rem;}
/* Form elements */#pasteForm { display: flex; flex-direction: column; gap: 1.5rem; width: 100%;}
textarea { width: 100%; min-height: 400px; padding: 1rem; border: 2px solid var(--border-color); border-radius: 8px; font-family: 'Monaco', 'Consolas', monospace; font-size: 1rem; line-height: 1.5; color: var(--text-content); font-weight: 500; /* 略微加粗 */ resize: vertical; transition: border-color 0.3s ease;}
textarea:focus { outline: none; border-color: var(--primary-color);}
/* Options grid */.options { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1.5rem; width: 100%; margin: 1rem 0; padding: 1rem; border: 2px solid var(--border-color); border-radius: 8px; background: var(--container-bg);}
.option { display: flex; flex-direction: column; gap: 0.5rem;}
/* Form controls */label { font-weight: 500; color: var(--text-color); display: flex; align-items: center; gap: 0.5rem;}
select,input[type="number"] { padding: 0.75rem; border: 2px solid var(--border-color); border-radius: 6px; font-size: 1rem; width: 100%; background: white; transition: border-color 0.3s ease;}
select:focus,input[type="number"]:focus { outline: none; border-color: var(--primary-color);}
input[type="checkbox"] { width: 1.2rem; height: 1.2rem; border-radius: 4px; accent-color: var(--primary-color);}
/* Button container */.form-actions { display: flex; justify-content: flex-end; width: 100%; margin-top: 1rem;}
/* Button styling */.form-actions button { background: var(--primary-color); color: white; border: none; padding: 1rem 2rem; border-radius: 8px; font-size: 1rem; font-weight: 600; cursor: pointer; transition: all 0.3s ease; width: auto; min-width: 150px; max-width: 200px;}
.form-actions button:hover { background: var(--primary-hover); transform: translateY(-1px);}
/* Dark mode adjustments */@media (prefers-color-scheme: dark) { select, input[type="number"] { background: #333; color: var(--text-color); border-color: var(--border-color); }
.options { background: var(--container-bg); border-color: var(--border-color); }}
/* Mobile adjustments */@media screen and (max-width: 768px) { .options { grid-template-columns: 1fr; padding: 0.75rem; }
.form-actions button { width: 100%; max-width: none; }}
/* Content display */#content { background: white; padding: 2rem; border-radius: 8px; border: 2px solid var(--border-color); margin-top: 1rem; overflow-x: auto; color: var(--text-content); font-weight: 500;}
pre { font-family: 'Monaco', 'Consolas', monospace; white-space: pre-wrap; word-wrap: break-word; color: var(--text-content); font-weight: 500;}
/* Info section */.info { background: #f8f9fa; padding: 1rem; border-radius: 6px; color: #666; font-size: 0.9rem; margin-bottom: 1rem; display: flex; gap: 1rem; flex-wrap: wrap;}
/* Decrypt section */#decrypt-section { background: #fff3cd; color: #856404; padding: 1rem; border-radius: 6px; margin: 1rem 0;}
#decryption-error { background: #f8d7da; color: #721c24; padding: 1rem; border-radius: 6px; margin-top: 1rem;}
/* Mobile Responsive Design */@media screen and (max-width: 768px) { body { padding: 10px; } .container { padding: 1rem; } h1 { font-size: 2rem; } textarea { min-height: 300px; } .options { grid-template-columns: 1fr; padding: 0.75rem; } button[type="submit"] { width: 100%; max-width: none; } #content { padding: 1rem; }}
/* Dark mode support */@media (prefers-color-scheme: dark) { :root { --bg-color: #1a1a1a; --container-bg: #2d2d2d; --text-color: #e0e0e0; --text-content: #ffffff; /* 深色模式下的内容颜色 */ --border-color: #555; /* 深色模式下更明显的边框颜色 */ --primary-color: #4dabf7; --primary-hover: #339af0; } select, input[type="number"], textarea { background: #333; color: var(--text-color); border-color: var(--border-color); } #content { background: #333; } #decrypt-section { background: #2c2c1d; color: #ffd700; } #decryption-error { background: #2c1d1d; color: #ff7070; } .info { background: #333; color: #999; } textarea, #content, pre { color: var(--text-content); } #markdown-content { color: var(--text-content); } .options { background: var(--container-bg); border-color: var(--border-color); }}
#markdown-content { color: var(--text-content); font-weight: 500;}
/* 编辑器容器 */.editor-container { margin-bottom: 1.5rem; width: 100%;}
/* Markdown split view */.split-view { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; width: 100%; position: relative; margin-bottom: 1.5rem;}
.split-view textarea { min-height: 500px; height: 500px; resize: none; width: 100%; overflow-y: auto;}
/* 修改预览窗口的选择器 */.split-view .markdown-preview { border: 2px solid var(--border-color); border-radius: 8px; padding: 1rem; overflow-y: auto; background: var(--container-bg); /* 使用容器背景色 */ height: 500px; width: 100%; line-height: 1.5; font-size: 1rem; color: var(--text-color); /* 确保文字颜色正确 */}
/* 深色模式下的预览窗 */@media (prefers-color-scheme: dark) { .split-view .markdown-preview { background: #333; color: var(--text-color); }}
/* 确保滚动条在深色模式下可见 */.split-view textarea::-webkit-scrollbar,.split-view .markdown-preview::-webkit-scrollbar { width: 8px; background: transparent;}
.split-view textarea::-webkit-scrollbar-track,.split-view .markdown-preview::-webkit-scrollbar-track { background: var(--bg-color); border-radius: 4px;}
.split-view textarea::-webkit-scrollbar-thumb,.split-view .markdown-preview::-webkit-scrollbar-thumb { background: #888; border-radius: 4px;}
.split-view textarea::-webkit-scrollbar-thumb:hover,.split-view .markdown-preview::-webkit-scrollbar-thumb:hover { background: #666;}
/* 修改预览窗口中图片的样 */.markdown-preview img { max-width: 80% !important; height: auto !important; display: block; margin: 0.5rem auto; /* 减小图片上下间距 */ max-height: 300px !important; /* 稍微降低最大高度 */ object-fit: contain; border: 1px solid var(--border-color); border-radius: 4px; transition: all 0.3s ease;}
/* 图片悬停效果 */.markdown-preview img:hover { cursor: zoom-in; opacity: 0.95; box-shadow: 0 0 12px rgba(0, 0, 0, 0.15);}
/* 移动端的图片样式调整 */@media screen and (max-width: 768px) { .markdown-preview img { max-width: 90% !important; /* 增加到90% */ max-height: 250px !important; }}
/* 表单选项区域 */#pasteForm { display: flex; flex-direction: column; gap: 1.5rem; width: 100%; margin-bottom: 2rem;}
.options { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 1.5rem; width: 100%; margin: 1rem 0; padding: 1rem; border: 2px solid var(--border-color); border-radius: 8px; background: var(--container-bg);}
/* 确按钮区域正确定位 */.form-actions { display: flex; justify-content: flex-end; width: 100%; margin-top: 1rem;}
/* 移动端的图片尺寸 */@media screen and (max-width: 768px) { .split-view .preview img { max-width: 70% !important; max-height: 150px !important; }}
/* 调整图片悬停效果 */.split-view .preview img:hover { cursor: pointer; opacity: 0.9;}
/* 调整预览窗口中的段落间距 */.markdown-preview p { margin: 0 0 1rem 0; /* 减小段落间距 */ line-height: 1.5; /* 确保与textarea一致 */}
/* 调整预览窗口中的图片布局 */.markdown-preview img { max-width: 80% !important; height: auto !important; display: block; margin: 0.5rem auto; /* 减小图片上下间距 */ max-height: 300px !important; /* 稍微降低最大高度 */ object-fit: contain; border: 1px solid var(--border-color); border-radius: 4px;}
/* 调整预览窗口中的标题间距 */.markdown-preview h1,.markdown-preview h2,.markdown-preview h3,.markdown-preview h4,.markdown-preview h5,.markdown-preview h6 { margin: 0.5rem 0; /* 减小标题的上下间距 */ line-height: 1.5;}
/* 调整预览窗口中的列表间距 */.markdown-preview ul,.markdown-preview ol { margin: 0.5rem 0; padding-left: 1.5rem;}
.markdown-preview li { margin: 0; line-height: 1.5;}
/* 调整预览窗口中的代码块间距 */.markdown-preview pre,.markdown-preview code { margin: 0.5rem 0; line-height: 1.5;}
/* 调整预览窗口中的引用块间距 */.markdown-preview blockquote { margin: 0.5rem 0; padding: 0.5rem 1rem; line-height: 1.5;}
/* 确保表单控件有明显的边框 */textarea,select,input[type="number"] { border: 2px solid var(--border-color); background: #ffffff;}
/* 深色模式下的边框和背景调整 */@media (prefers-color-scheme: dark) { :root { --bg-color: #1a1a1a; --container-bg: #2d2d2d; --text-color: #e0e0e0; --text-content: #ffffff; --border-color: #555; /* 深色模式下更明显的边框颜色 */ --primary-color: #4dabf7; --primary-hover: #339af0; }
textarea, select, input[type="number"] { background: #333; border-color: var(--border-color); color: var(--text-color); }}
/* 删除滚动提示样式 */.editor-container::after { display: none; /* 或直接删除这个样式块 */}
/* 调整编辑器容器的边距 */.editor-container { position: relative; margin-bottom: 1.5rem; /* 恢复原来的边距 */}
/* 修改 split-view 相关样式 */.split-view { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; width: 100%; position: relative; margin-bottom: 1.5rem;}
/* 修改 textarea 和预览窗口的样式 */.split-view textarea,.split-view .markdown-preview { height: 100%; /* 改为相对高度 */ min-height: 500px; resize: vertical; /* 允许垂直调整大小 */ width: 100%; overflow-y: auto;}
/* 添加新的容器样式来同步高度 */.editor-container { display: flex; flex-direction: column;}
.editor-container.split-view { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;}
/* 确保预览窗口跟随 textarea 的高度 */.markdown-preview { height: 100%; border: 2px solid var(--border-color); border-radius: 8px; padding: 1rem; overflow-y: auto; background: var(--container-bg); line-height: 1.5; font-size: 1rem; color: var(--text-color);}
/* 添加加密内容的样式规则 */#content #markdown-content img { max-width: 80% !important; height: auto !important; display: block; margin: 0.5rem auto; max-height: 300px !important; object-fit: contain; border: 1px solid var(--border-color); border-radius: 4px; transition: all 0.3s ease;}
#content #markdown-content { color: var(--text-content); font-weight: 500; line-height: 1.5;}
/* 确保加密内容的容器样式正确 */#content { background: var(--container-bg); padding: 2rem; border-radius: 8px; border: 2px solid var(--border-color); margin-top: 1rem; overflow-x: auto; color: var(--text-content); font-weight: 500; width: 100%;}
/* 修改预览窗口中图片的样式 */.markdown-preview img,#content #markdown-content img { max-width: 100% !important; /* 改为100% */ height: auto !important; display: block; margin: 0.5rem auto; max-height: 600px !important; /* 增加最大高度 */ object-fit: contain; border: 1px solid var(--border-color); border-radius: 4px; transition: all 0.3s ease;}
/* 移动端的图片样式调整 */@media screen and (max-width: 768px) { .markdown-preview img, #content #markdown-content img { max-width: 100% !important; max-height: 400px !important; /* 移动端也适当增加高度 */ }}
/* 文件分享相关样式 */.tab-buttons { display: flex; gap: 1rem; margin-bottom: 1rem;}
.tab-button { padding: 0.5rem 1rem; border: 2px solid var(--border-color); border-radius: 4px; background: none; cursor: pointer; transition: all 0.3s ease;}
.tab-button.active { background: var(--primary-color); color: white; border-color: var(--primary-color);}
.file-upload-container { border: 2px dashed var(--border-color); padding: 2rem; text-align: center; margin-bottom: 1rem; border-radius: 8px; transition: border-color 0.3s ease;}
.file-upload-container:hover { border-color: var(--primary-color);}
.file-upload-container input[type="file"] { margin-bottom: 1rem;}
.file-info { margin-top: 1rem; font-size: 0.9rem; color: #666;}
.code-input-container { display: flex; gap: 1rem; margin-top: 2rem; padding-top: 2rem; border-top: 1px solid var(--border-color);}
.code-input-container input { flex: 1; padding: 0.75rem; border: 2px solid var(--border-color); border-radius: 6px; font-size: 1rem;}
.code-input-container button { padding: 0.75rem 1.5rem; background: var(--primary-color); color: white; border: none; border-radius: 6px; cursor: pointer; transition: all 0.3s ease;}
.code-input-container button:hover { background: var(--primary-hover);}
/* 上传进度条样式 */.upload-progress { margin-top: 1rem; width: 100%;}
.progress-bar { width: 100%; height: 20px; background-color: var(--border-color); border-radius: 10px; overflow: hidden;}
.progress-bar-fill { height: 100%; background-color: var(--primary-color); width: 0; transition: width 0.3s ease;}
.progress-text { text-align: center; margin-top: 0.5rem; font-size: 0.9rem; color: var(--text-color);}
/* 文件上传容器样式优化 */.file-upload-container { border: 2px dashed var(--border-color); padding: 2rem; text-align: center; margin-bottom: 1rem; border-radius: 8px; transition: border-color 0.3s ease;}
.file-upload-container:hover { border-color: var(--primary-color);}
.file-upload-container input[type="file"] { margin-bottom: 1rem;}
/* 添加加载动画样式 */.loading-spinner { width: 40px; height: 40px; margin: 20px auto; border: 4px solid var(--border-color); border-top: 4px solid var(--primary-color); border-radius: 50%; animation: spin 1s linear infinite;}
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); }}
/* 添加提取码和分享链接的样式 */.share-info { margin: 1.5rem 0;}
.copy-group { display: flex; align-items: center; gap: 0.5rem; margin: 0.5rem 0; padding: 0.5rem; background: var(--bg-color); border-radius: 4px;}
.copy-group label { font-weight: 500; color: var(--text-color); white-space: nowrap;}
.copy-text { flex: 1; padding: 0.5rem; background: var(--container-bg); border: 1px solid var(--border-color); border-radius: 4px; font-family: monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}
.copy-btn { padding: 0.5rem 1rem; background: var(--primary-color); color: white; border: none; border-radius: 4px; cursor: pointer; transition: background 0.3s ease;}
.copy-btn:hover { background: var(--primary-hover);}
.close-btn { margin-top: 1rem; padding: 0.5rem 1.5rem; background: var(--border-color); color: var(--text-color); border: none; border-radius: 4px; cursor: pointer; transition: background 0.3s ease;}
.close-btn:hover { background: #ccc;}
/* 深色模式适配 */@media (prefers-color-scheme: dark) { .copy-group { background: rgba(255, 255, 255, 0.1); } .copy-text { background: var(--container-bg); color: var(--text-color); } .close-btn { background: #444; color: #fff; } .close-btn:hover { background: #555; }}1234567891011version: '3'services: web: build: . ports: - "7860:7860" volumes: - ./data:/var/www/html/data - ./uploads:/var/www/html/uploads environment: - APACHE_DOCUMENT_ROOT=/var/www/html123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112<?phpheader('Content-Type: application/json');
require_once 'settings.php';require_once 'FileShare.php';
$fileShare = new FileShare();
try { if ($_SERVER['REQUEST_METHOD'] === 'POST') { // 处理上传 $data = [ 'expire_time' => $_POST['expire_time'] ?? 86400, 'max_downloads' => $_POST['max_downloads'] ?? 0 ]; if (isset($_FILES['file']) || isset($_POST['content'])) { if (isset($_POST['content'])) { $data['content'] = $_POST['content']; } $code = $fileShare->save($data); echo json_encode([ 'status' => 'success', 'code' => $code ]); } else { throw new Exception('未收到文件或文本内容'); } } else if ($_SERVER['REQUEST_METHOD'] === 'GET') { // 处理下载/获取 if (isset($_GET['download'])) { $code = $_GET['download']; $file = $fileShare->get($code); if (!$file || $file['type'] !== 'file') { throw new Exception('文件不存在或已过期'); } // 获取文件 MIME 类型 $finfo = finfo_open(FILEINFO_MIME_TYPE); $mime_type = finfo_file($finfo, $file['filepath']); finfo_close($finfo); // 清除之前的输出缓冲和头信息 ob_clean(); header('Content-Type: ' . $mime_type); header('Content-Transfer-Encoding: binary'); header('Content-Disposition: attachment; filename="' . rawurlencode($file['filename']) . '"'); header('Content-Length: ' . filesize($file['filepath'])); header('Accept-Ranges: bytes'); // 处理断点续传 if (isset($_SERVER['HTTP_RANGE'])) { list($start, $end) = sscanf($_SERVER['HTTP_RANGE'], 'bytes=%d-%d'); $filesize = filesize($file['filepath']); if (!isset($end)) { $end = $filesize - 1; } $length = $end - $start + 1; header('HTTP/1.1 206 Partial Content'); header("Content-Range: bytes $start-$end/$filesize"); header('Content-Length: ' . $length); $fp = fopen($file['filepath'], 'rb'); fseek($fp, $start); $buffer = 1024 * 8; while ($length > 0) { $read = min($buffer, $length); echo fread($fp, $read); flush(); $length -= $read; } fclose($fp); } else { readfile($file['filepath']); } exit; } else { $code = $_GET['code'] ?? null; if (!$code) { throw new Exception('未提供提取码'); } $file = $fileShare->get($code); if (!$file) { throw new Exception('文件不存在或已过期'); } // 返回文件信息或文本内容 echo json_encode([ 'status' => 'success', 'type' => $file['type'], 'content' => $file['content'], 'filename' => $file['filename'], 'current_downloads' => $file['current_downloads'], 'max_downloads' => $file['max_downloads'], 'expires_at' => $file['expires_at'], 'expires_at_formatted' => date('Y-m-d H:i:s', $file['expires_at']) // 添加格式化的时间 ]); } }} catch (Exception $e) { http_response_code(400); echo json_encode([ 'status' => 'error', 'message' => $e->getMessage() ]);}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814<?php// index.phprequire_once 'settings.php';
class PasteBoard { private $db; private $settings; public function __construct() { $this->settings = new Settings(); $this->db = new SQLite3($this->settings->getSetting('db_path')); } private function getChineseTime($timestamp) { date_default_timezone_set('Asia/Shanghai'); return $timestamp; } public function getPaste($uuid) { $stmt = $this->db->prepare('SELECT * FROM notes WHERE uuid = :uuid'); $stmt->bindValue(':uuid', $uuid, SQLITE3_TEXT); $result = $stmt->execute(); if ($row = $result->fetchArray(SQLITE3_ASSOC)) { // 检查是否过期(使用中国时间) date_default_timezone_set('Asia/Shanghai'); if (time() > $row['expires_at']) { $this->deletePaste($uuid); return null; } // 检查访问次数 if ($row['max_views'] > 0 && $row['current_views'] >= $row['max_views']) { $this->deletePaste($uuid); return null; } // 更新访问次数 $stmt = $this->db->prepare('UPDATE notes SET current_views = current_views + 1 WHERE uuid = :uuid'); $stmt->bindValue(':uuid', $uuid, SQLITE3_TEXT); $stmt->execute(); return $row; } return null; } private function deletePaste($uuid) { $stmt = $this->db->prepare('DELETE FROM notes WHERE uuid = :uuid'); $stmt->bindValue(':uuid', $uuid, SQLITE3_TEXT); $stmt->execute(); }}
$pasteboard = new PasteBoard();$settings = new Settings();$paste = null;$uuid = isset($_GET['id']) ? $_GET['id'] : null;
if ($uuid) { $paste = $pasteboard->getPaste($uuid); if (!$paste) { header("HTTP/1.0 404 Not Found"); echo "Paste not found or expired"; exit; }}?>
<!DOCTYPE html><html lang="zh-CN"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title><?php echo htmlspecialchars($settings->getSetting('site_name')); ?></title> <link rel="icon" href="<?php echo htmlspecialchars($settings->getSetting('favicon_path')); ?>"> <link rel="stylesheet" href="/css/marked.css"> <link rel="stylesheet" href="/css/style.css"></head><body> <div class="container"> <h1><?php echo htmlspecialchars($settings->getSetting('site_name')); ?></h1> <p><?php echo htmlspecialchars($settings->getSetting('site_description')); ?></p> <?php if ($paste): ?> <div class="info"> 浏览次数: <?php echo $paste['current_views']; ?>/<?php echo $paste['max_views'] ? $paste['max_views'] : '∞'; ?> | 过期时间: <?php date_default_timezone_set('Asia/Shanghai'); echo date('Y-m-d H:i:s', $paste['expires_at']); ?> </div> <div id="content" <?php echo $paste['is_encrypted'] ? 'style="display:none;"' : ''; ?>> <?php if ($paste['is_markdown']): ?> <div id="markdown-content"></div> <?php else: ?> <pre><?php echo htmlspecialchars($paste['content']); ?></pre> <?php endif; ?> </div> <?php if ($paste['is_encrypted']): ?> <div id="decrypt-section"> <p>此内容已加密。解密密钥应该在URL的#后面。</p> <div id="decryption-error" style="color: red; display: none;"> 解密失败。请检查解密密钥。 </div> </div> <?php endif; ?> <?php else: ?> <div class="tab-buttons"> <button class="tab-button active" data-tab="paste">URL分享</button> <button class="tab-button" data-tab="code">提取码分享</button> <button class="tab-button" data-tab="file">文件分享</button> </div> <!-- 原有的文本分享表单 --> <form id="pasteForm" style="display: block;"> <div class="editor-container"> <textarea name="content" placeholder="在此粘贴您要分享的内容"></textarea> <div class="markdown-preview" style="display: none;"></div> </div> <div class="options"> <div class="option"> <label>过期时间:</label> <select name="expire_time"> <option value="3600">1小时</option> <option value="86400">1天</option> <option value="604800">1周</option> <option value="2592000" selected>1个月</option> <option value="31536000">1年</option> </select> </div> <div class="option"> <label>最大浏览次数 (0表示无限制):</label> <input type="number" name="max_views" value="0" min="0" max="25565"> </div> <div class="option"> <label> <input type="checkbox" name="is_markdown"> 启用Markdown </label> </div> <div class="option"> <label> <input type="checkbox" name="is_encrypted"> 启用加密 </label> </div> </div> <div class="form-actions"> <button type="submit">创建笔记</button> </div> </form> <!-- 提取码分享表单 --> <form id="textShareForm" style="display: none;"> <div class="editor-container"> <textarea name="content" placeholder="在此输入您要分享的文本内容..."></textarea> </div> <div class="options"> <div class="option"> <label>过期时间:</label> <select name="expire_time"> <option value="3600">1小时</option> <option value="86400">1天</option> <option value="604800">1周</option> <option value="2592000" selected>1个月</option> <option value="31536000">1年</option> </select> </div> <div class="option"> <label>最大查看次数 (0表示无限制):</label> <input type="number" name="max_downloads" value="0" min="0"> </div> </div> <div class="form-actions"> <button type="submit">生成提取码</button> </div> </form> <!-- 文件上传表单 --> <form id="fileForm" style="display: none;"> <div class="file-upload-container"> <input type="file" name="file" id="fileInput"> <div class="file-info"></div> <div class="upload-progress" style="display: none;"> <div class="progress-bar"> <div class="progress-bar-fill"></div> </div> <div class="progress-text">0%</div> </div> </div> <div class="options"> <div class="option"> <label>过期时间:</label> <select name="expire_time"> <option value="3600">1小时</option> <option value="86400">1天</option> <option value="604800">1周</option> <option value="2592000" selected>1个月</option> <option value="31536000">1年</option> </select> </div> <div class="option"> <label>最大下载次数 (0表示无限制):</label> <input type="number" name="max_downloads" value="0" min="0"> </div> </div> <div class="form-actions"> <button type="submit">上传文件</button> </div> </form> <!-- 提取码输入区域 --> <div class="code-input-container"> <input type="text" id="codeInput" placeholder="输入提取码"> <button onclick="getFile()">获取内容</button> </div> <!-- 文件信息显示区域 --> <div id="fileInfo" style="display: none;"> <div class="info"> <span class="downloads"></span> <span class="expires"></span> </div> <div class="content"></div> </div> <?php endif; ?> </div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script> <script> // 修改获取网站域名的方法 const siteUrl = (() => { // 优使用 X-Forwarded-Host 和 X-Forwarded-Proto const forwardedHost = '<?php echo isset($_SERVER["HTTP_X_FORWARDED_HOST"]) ? $_SERVER["HTTP_X_FORWARDED_HOST"] : ""; ?>'; const forwardedProto = '<?php echo isset($_SERVER["HTTP_X_FORWARDED_PROTO"]) ? $_SERVER["HTTP_X_FORWARDED_PROTO"] : ""; ?>'; if (forwardedHost && forwardedProto) { return `${forwardedProto}://${forwardedHost}`; } // 如果没有转发的头部信息,则使用当前请求的 Host const protocol = window.location.protocol; const host = window.location.host; return `${protocol}//${host}`; })(); <?php if ($paste && $paste['is_markdown']): ?> document.getElementById('markdown-content').innerHTML = marked.parse(<?php echo json_encode($paste['content']); ?>); <?php endif; ?>
<?php if ($paste && $paste['is_encrypted']): ?> const encryptedContent = <?php echo json_encode($paste['content']); ?>; const decryptionKey = window.location.hash.substring(1); if (decryptionKey) { try { const decryptedBytes = CryptoJS.AES.decrypt(encryptedContent, decryptionKey); const decryptedContent = decryptedBytes.toString(CryptoJS.enc.Utf8); if (decryptedContent) { const content = document.getElementById('content'); content.style.display = 'block'; if (<?php echo $paste['is_markdown'] ? 'true' : 'false'; ?>) { // 修改这里:使用 markdown-content div const markdownContent = document.getElementById('markdown-content'); markdownContent.innerHTML = marked.parse(decryptedContent); // 确保图片样式一致 markdownContent.querySelectorAll('img').forEach(img => { img.style.maxWidth = '100%'; // 改为100% img.style.height = 'auto'; img.style.maxHeight = '600px'; // 增加最大高度 img.style.margin = '0.5rem auto'; img.style.display = 'block'; // 添加点击放大功能 img.addEventListener('click', function(e) { e.preventDefault(); const modal = document.createElement('div'); modal.style.cssText = ` position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.9); display: flex; justify-content: center; align-items: center; z-index: 1000; cursor: zoom-out; `; const modalImg = document.createElement('img'); modalImg.src = this.src; modalImg.style.cssText = ` max-width: 90%; max-height: 90vh; object-fit: contain; border-radius: 4px; `; modal.appendChild(modalImg); document.body.appendChild(modal); modal.addEventListener('click', function() { document.body.removeChild(modal); }); }); }); } else { content.innerHTML = `<pre>${decryptedContent}</pre>`; } document.getElementById('decrypt-section').style.display = 'none'; } else { document.getElementById('decryption-error').style.display = 'block'; } } catch (e) { document.getElementById('decryption-error').style.display = 'block'; } } <?php endif; ?>
if (document.getElementById('pasteForm')) { document.getElementById('pasteForm').onsubmit = async (e) => { e.preventDefault(); const formData = new FormData(e.target); const data = Object.fromEntries(formData.entries()); if (data.is_encrypted) { const key = CryptoJS.lib.WordArray.random(32).toString(); data.content = CryptoJS.AES.encrypt(data.content, key).toString(); data.encryption_key = key; } try { const response = await fetch('api.php', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data) }); const result = await response.json(); if (result.status === 'success') { let url = `${window.location.origin}/${result.uuid}`; // let url = `${window.location.origin}${window.location.pathname}?id=${result.uuid}`; if (data.is_encrypted) { url += '#' + result.encryption_key; } window.location.href = url; } else { alert('Error creating paste: ' + result.message); } } catch (error) { alert('Error creating paste: ' + error.message); } }; } document.addEventListener('DOMContentLoaded', function() { const markdownCheckbox = document.querySelector('input[name="is_markdown"]'); const editorContainer = document.querySelector('.editor-container'); const textarea = document.querySelector('textarea[name="content"]'); const markdownPreview = document.querySelector('.markdown-preview');
let isPreviewScrolling = false; let isEditorScrolling = false; let lastEditorScrollTop = 0; let lastPreviewScrollTop = 0;
// 只保留输入窗口的滚动同步 textarea.addEventListener('scroll', function() { if (!isPreviewScrolling && markdownPreview.style.display !== 'none') { isEditorScrolling = true; // 计算输入窗口的滚动百分比变化 const editorScrollPercentage = this.scrollTop / (this.scrollHeight - this.clientHeight); const previewMaxScroll = markdownPreview.scrollHeight - markdownPreview.clientHeight; // 根据输入窗口的滚动百比设置预览窗口的位置 markdownPreview.scrollTop = previewMaxScroll * editorScrollPercentage; setTimeout(() => isEditorScrolling = false, 50); } });
// 删除 markdownPreview 的滚动监听器 // 移除这代码: // markdownPreview.addEventListener('scroll', function() { ... });
markdownCheckbox.addEventListener('change', function() { if (this.checked) { editorContainer.classList.add('split-view'); markdownPreview.style.display = 'block'; // 立即同步高度 markdownPreview.style.height = `${textarea.offsetHeight}px`; updatePreview(markdownPreview, textarea); } else { editorContainer.classList.remove('split-view'); markdownPreview.style.display = 'none'; } });
// 在每次入内容更新时更新预览 textarea.addEventListener('input', function() { updatePreview(markdownPreview, textarea); });
// 添加粘贴事件处理 textarea.addEventListener('paste', async function(e) { const items = (e.clipboardData || e.originalEvent.clipboardData).items; for (let item of items) { if (item.type.indexOf('image') === 0) { e.preventDefault(); const blob = item.getAsFile(); const formData = new FormData(); formData.append('image', blob); try { // 显示上传进度提示 const uploadingText = `![Uploading...]()\n`; const startPos = this.selectionStart; this.value = this.value.substring(0, startPos) + uploadingText + this.value.substring(this.selectionEnd); // 发送图片到服务器 const response = await fetch('upload.php', { method: 'POST', body: formData }); const result = await response.json(); if (result.success) { // 使用完整的URL路径 const imageMarkdown = `\n`; const currentContent = this.value; const uploadingIndex = currentContent.indexOf(uploadingText); if (uploadingIndex !== -1) { this.value = currentContent.substring(0, uploadingIndex) + imageMarkdown + currentContent.substring(uploadingIndex + uploadingText.length); // 触发预览更新 updatePreview(markdownPreview, textarea); } } else { // 处理上传失败 alert('图片上传失败: ' + result.message); } } catch (error) { alert('图片上传出错: ' + error.message); } } } }); });
function updatePreview(markdownPreview, textarea) { if (markdownPreview && markdownPreview.style.display !== 'none') { try { const content = textarea.value || ''; const parsedContent = marked.parse(content); markdownPreview.innerHTML = parsedContent; // 为预览窗口中的图片添加点击事件 markdownPreview.querySelectorAll('img').forEach(img => { img.addEventListener('click', function(e) { e.preventDefault(); // 创建模态框显示大图 const modal = document.createElement('div'); modal.style.cssText = ` position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.9); display: flex; justify-content: center; align-items: center; z-index: 1000; cursor: zoom-out; `; const modalImg = document.createElement('img'); modalImg.src = this.src; modalImg.style.cssText = ` max-width: 90%; max-height: 90vh; object-fit: contain; border-radius: 4px; `; modal.appendChild(modalImg); document.body.appendChild(modal); // 点击模态框关闭 modal.addEventListener('click', function() { document.body.removeChild(modal); }); }); }); } catch (error) { console.error('Markdown parsing error:', error); markdownPreview.innerHTML = '<p style="color: red;">Error parsing markdown content</p>'; } } }
// 在原有的 script 标中添加/修改 document.addEventListener('DOMContentLoaded', function() { // 标签切换 const tabButtons = document.querySelectorAll('.tab-button'); const pasteForm = document.getElementById('pasteForm'); const textShareForm = document.getElementById('textShareForm'); const fileForm = document.getElementById('fileForm'); tabButtons.forEach(button => { button.addEventListener('click', function() { const tab = this.dataset.tab; // 更新按钮状态 tabButtons.forEach(btn => btn.classList.remove('active')); this.classList.add('active'); // 显示/隐藏表单 pasteForm.style.display = tab === 'paste' ? 'block' : 'none'; textShareForm.style.display = tab === 'code' ? 'block' : 'none'; fileForm.style.display = tab === 'file' ? 'block' : 'none'; }); }); // 文本分享表单处理 if (textShareForm) { textShareForm.onsubmit = async (e) => { e.preventDefault(); const formData = new FormData(e.target); try { const response = await fetch('file_api.php', { method: 'POST', body: formData }); const result = await response.json(); if (result.status === 'success') { // 显示提取码和分享链接 const shareUrl = `${window.location.origin}?code=${result.code}`; const modal = document.createElement('div'); modal.className = 'modal'; modal.innerHTML = ` <div class="modal-content"> <h3>分享成功!</h3> <div class="share-info"> <div class="copy-group"> <label>提取码:</label> <span class="copy-text" data-clipboard="${result.code}">${result.code}</span> <button class="copy-btn" onclick="copyText(this.previousElementSibling)">复制</button> </div> <div class="copy-group"> <label>分享链接:</label> <span class="copy-text" data-clipboard="${shareUrl}">${shareUrl}</span> <button class="copy-btn" onclick="copyText(this.previousElementSibling)">复制</button> </div> </div> <button class="close-btn" onclick="this.parentElement.parentElement.remove()">关闭</button> </div> `; document.body.appendChild(modal); } else { alert('分享失败:' + result.message); } } catch (error) { alert('分享出错:' + error.message); } }; } // 文件上传表单处理 if (fileForm) { const fileInput = document.getElementById('fileInput'); const fileInfo = document.querySelector('.file-info'); const progressBar = document.querySelector('.progress-bar-fill'); const progressText = document.querySelector('.progress-text'); const uploadProgress = document.querySelector('.upload-progress'); fileInput.addEventListener('change', function() { if (this.files[0]) { const file = this.files[0]; const size = (file.size / 1024 / 1024).toFixed(2); fileInfo.textContent = `文件名: ${file.name}, 大小: ${size}MB`; } }); fileForm.onsubmit = async (e) => { e.preventDefault(); const formData = new FormData(e.target); try { uploadProgress.style.display = 'block'; const xhr = new XMLHttpRequest(); xhr.upload.onprogress = (e) => { if (e.lengthComputable) { const percentComplete = Math.round((e.loaded / e.total) * 100); progressBar.style.width = percentComplete + '%'; progressText.textContent = percentComplete + '%'; } }; // 使用 Promise 包装 XHR 请求 const response = await new Promise((resolve, reject) => { xhr.onload = () => { if (xhr.status === 200) { try { resolve(JSON.parse(xhr.responseText)); } catch (e) { reject(new Error('解析响应失败')); } } else { reject(new Error('上传失败')); } }; xhr.onerror = () => reject(new Error('网络错误')); xhr.open('POST', 'file_api.php', true); xhr.send(formData); }); if (response.status === 'success') { const shareUrl = `${window.location.origin}?code=${response.code}`; const modal = document.createElement('div'); modal.className = 'modal'; modal.innerHTML = ` <div class="modal-content"> <h3>上传成功!</h3> <div class="share-info"> <div class="copy-group"> <label>提取码:</label> <span class="copy-text" data-clipboard="${response.code}">${response.code}</span> <button class="copy-btn" onclick="copyText(this.previousElementSibling)">复制</button> </div> <div class="copy-group"> <label>分享链接:</label> <span class="copy-text" data-clipboard="${shareUrl}">${shareUrl}</span> <button class="copy-btn" onclick="copyText(this.previousElementSibling)">复制</button> </div> </div> <button class="close-btn" onclick="this.parentElement.parentElement.remove()">关闭</button> </div> `; document.body.appendChild(modal); // 重置进度条 setTimeout(() => { uploadProgress.style.display = 'none'; progressBar.style.width = '0%'; progressText.textContent = '0%'; }, 1000); } else { alert('上传失败:' + response.message); } } catch (error) { alert('上传出错:' + error.message); } }; } });
// 修改获取文件函数 async function getFile() { const code = document.getElementById('codeInput').value.trim(); if (!code) { alert('请输入提取码'); return; } // 显示加载动画 const loadingModal = document.createElement('div'); loadingModal.className = 'modal'; loadingModal.innerHTML = ` <div class="modal-content"> <h3>正在获取内容...</h3> <div class="loading-spinner"></div> </div> `; document.body.appendChild(loadingModal); try { const response = await fetch(`file_api.php?code=${code}`); const result = await response.json(); if (result.status === 'success') { if (result.content) { // 文本内容 const fileInfo = document.getElementById('fileInfo'); fileInfo.style.display = 'block'; fileInfo.querySelector('.content').innerHTML = `<pre>${result.content}</pre>`; // 添加过期时间显示 const info = fileInfo.querySelector('.info'); if (info) { info.innerHTML = ` 下载次数: ${result.current_downloads}/${result.max_downloads ? result.max_downloads : '∞'} | 过期时间: ${result.expires_at_formatted} `; } } else { // 文件下载 - 创建下载链接 const downloadUrl = `${siteUrl}/file_api.php?download=${code}&filename=${encodeURIComponent(result.filename)}`; window.location.href = downloadUrl; } } else { alert(result.message || '获取内容失败'); } } catch (error) { alert('获取文件失败:' + error.message); } finally { // 移除加载动画 loadingModal.remove(); } }
// 添加复制功能 function copyText(element) { const text = element.getAttribute('data-clipboard'); navigator.clipboard.writeText(text).then(() => { // 显示复制成功提示 const originalText = element.nextElementSibling.textContent; element.nextElementSibling.textContent = '已复制!'; setTimeout(() => { element.nextElementSibling.textContent = originalText; }, 1000); }).catch(err => { console.error('复制失败:', err); }); }
// 在 DOMContentLoaded 事件中添加自动填充提取码的功能 document.addEventListener('DOMContentLoaded', function() { // 检查 URL 中是否有提取码 const urlParams = new URLSearchParams(window.location.search); const code = urlParams.get('code'); if (code) { // 自动填充提取码并触发获取 const codeInput = document.getElementById('codeInput'); if (codeInput) { codeInput.value = code; getFile(); // 自动获取文件 } } // ... 其他现有的 DOMContentLoaded 代码 ... }); </script>
<!-- 添加模态框样式 --> <style> .modal { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); display: flex; justify-content: center; align-items: center; z-index: 1000; }
.modal-content { background: var(--container-bg); padding: 2rem; border-radius: 8px; box-shadow: var(--shadow); text-align: center; }
.modal-content h3 { margin-bottom: 1rem; }
.modal-content strong { font-size: 1.2rem; color: var(--primary-color); }
.modal-content button { margin-top: 1rem; padding: 0.5rem 1rem; background: var(--primary-color); color: white; border: none; border-radius: 4px; cursor: pointer; }
.modal-content button:hover { background: var(--primary-hover); } </style></body></html>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970<?php// init.php
// 定义基础配置$CONFIG = [ 'data_dir' => './data-ekdvbq/', 'db_path' => './data-ekdvbq/notes.db',];
// 创建数据目录if (!file_exists($CONFIG['data_dir'])) { if (!mkdir($CONFIG['data_dir'], 0755, true)) { die("无法创建数据目录:" . $CONFIG['data_dir'] . "\n"); } echo "已创建数据目录:" . $CONFIG['data_dir'] . "\n";} else { echo "数据目录已存在:" . $CONFIG['data_dir'] . "\n";}
// 检查目录权限if (!is_writable($CONFIG['data_dir'])) { die("数据目录不可写:" . $CONFIG['data_dir'] . "\n");}
// 初始化数据库if (file_exists($CONFIG['db_path'])) { echo "数据库文件已存在。是否重新初始化?(y/N): "; $handle = fopen("php://stdin", "r"); $line = trim(fgets($handle)); fclose($handle); if (strtolower($line) !== 'y') { die("操作取消\n"); } unlink($CONFIG['db_path']);}
try { $db = new SQLite3($CONFIG['db_path']); // 创建笔记表 $db->exec('CREATE TABLE IF NOT EXISTS notes ( id INTEGER PRIMARY KEY AUTOINCREMENT, uuid TEXT UNIQUE NOT NULL, content TEXT NOT NULL, created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL, max_views INTEGER NOT NULL DEFAULT 0, current_views INTEGER NOT NULL DEFAULT 0, is_encrypted INTEGER NOT NULL DEFAULT 0, is_markdown INTEGER NOT NULL DEFAULT 0 )'); // 创建设置表 $db->exec('CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT NOT NULL )'); // 创建索引 $db->exec('CREATE INDEX IF NOT EXISTS idx_uuid ON notes (uuid)'); $db->exec('CREATE INDEX IF NOT EXISTS idx_expires_at ON notes (expires_at)'); // 设置文件权限 chmod($CONFIG['db_path'], 0644); echo "数据库初始化完成\n"; } catch (Exception $e) { die("数据库初始化失败:" . $e->getMessage() . "\n");}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172<?php
// 设置时区
date_default_timezone_set('Asia/Shanghai');
// 处理错误输出
ini_set('display_errors', 'Off');
error_reporting(E_ALL);
ini_set('log_errors', 'On');
ini_set('error_log', '/dev/stderr');
// 确保输出正确的 Content-Type
if (strpos($_SERVER['REQUEST_URI'], '/api.php') === 0 ||
strpos($_SERVER['REQUEST_URI'], '/file_api.php') === 0 ||
strpos($_SERVER['REQUEST_URI'], '/upload.php') === 0) {
header('Content-Type: application/json');
}
// 处理 UUID 格式的 URL
if (preg_match('/^\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$/', $_SERVER['REQUEST_URI'], $matches)) {
$_GET['id'] = $matches[1];
require __DIR__ . '/index.php';
return true;
}
// 处理静态文件
if (preg_match('/\.(css|js|png|jpg|jpeg|gif|ico|webp)$/', $_SERVER['REQUEST_URI'])) {
return false; // 让 PHP 内置服务器处理静态文件
}
// 处理 API 请求
if (strpos($_SERVER['REQUEST_URI'], '/api.php') === 0) {
ob_start(); // 开始输出缓冲
require __DIR__ . '/api.php';
$output = ob_get_clean(); // 获取并清除缓冲
if (json_decode($output) === null) {
// 如果不是有效的 JSON,返回错误
echo json_encode(['status' => 'error', 'message' => 'Invalid response']);
} else {
echo $output;
}
return true;
}
if (strpos($_SERVER['REQUEST_URI'], '/file_api.php') === 0) {
ob_start(); // 开始输出缓冲
require __DIR__ . '/file_api.php';
$output = ob_get_clean(); // 获取并清除缓冲
if (json_decode($output) === null && !headers_sent()) {
// 如果不是有效的 JSON 且头部未发送,返回错误
echo json_encode(['status' => 'error', 'message' => 'Invalid response']);
} else {
echo $output;
}
return true;
}
if (strpos($_SERVER['REQUEST_URI'], '/upload.php') === 0) {
ob_start(); // 开始输出缓冲
require __DIR__ . '/upload.php';
$output = ob_get_clean(); // 获取并清除缓冲
if (json_decode($output) === null) {
// 如果不是有效的 JSON,返回错误
echo json_encode(['status' => 'error', 'message' => 'Invalid response']);
} else {
echo $output;
}
return true;
}
// 默认路由到 index.php
require __DIR__ . '/index.php';
return true;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116<?php// settings.php
class Settings { private $db = null; private $defaultSettings = [ 'site_name' => 'MoeNote', 'site_description' => 'A simple online note that focuses on safe sharing.', 'data_directory' => '/var/www/html/data/', 'db_path' => '/var/www/html/data/notes.db', 'favicon_path' => '/favicon.png', 'max_expire_time' => 31536000, // 1yr ]; public function __construct() { $this->initializeDatabase(); } private function initializeDatabase() { // 确保数据目录存在 $dataDir = dirname($this->defaultSettings['db_path']); if (!file_exists($dataDir)) { if (!mkdir($dataDir, 0777, true)) { throw new Exception('无法创建数据目录,请检查权限'); } // 创建 .htaccess 文件来保护数据目录 $htaccess = $dataDir . '/.htaccess'; if (!file_exists($htaccess)) { $htaccess_content = "Require all denied\n"; $htaccess_content .= "Options -Indexes\n"; file_put_contents($htaccess, $htaccess_content); } // 创建 index.html $index_html = $dataDir . '/index.html'; if (!file_exists($index_html)) { file_put_contents($index_html, '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1></body></html>'); } } // 连接或创建数据库 $this->db = new SQLite3($this->defaultSettings['db_path']); // 创建必要的表 $this->db->exec(' CREATE TABLE IF NOT EXISTS settings ( key TEXT PRIMARY KEY, value TEXT ) '); $this->db->exec(' CREATE TABLE IF NOT EXISTS notes ( uuid TEXT PRIMARY KEY, content TEXT, created_at INTEGER, expires_at INTEGER, max_views INTEGER DEFAULT 0, current_views INTEGER DEFAULT 0, is_markdown INTEGER DEFAULT 0, is_encrypted INTEGER DEFAULT 0 ) '); // 在 initializeDatabase 方法中添加新表 $this->db->exec(' CREATE TABLE IF NOT EXISTS files ( code TEXT PRIMARY KEY, -- 提取码 filename TEXT, -- 原始文件名 filepath TEXT, -- 存储路径 content TEXT, -- 文本内容(如果是文本类型) type TEXT, -- 类型:file 或 text created_at INTEGER, -- 创建时间 expires_at INTEGER, -- 过期时间 max_downloads INTEGER DEFAULT 0, -- 最大下载/查看次数 current_downloads INTEGER DEFAULT 0 -- 当前下载/查看次数 ) '); // 初始化默认设置 foreach ($this->defaultSettings as $key => $value) { $stmt = $this->db->prepare('INSERT OR IGNORE INTO settings (key, value) VALUES (:key, :value)'); $stmt->bindValue(':key', $key, SQLITE3_TEXT); $stmt->bindValue(':value', $value, SQLITE3_TEXT); $stmt->execute(); } } public function getSetting($key, $default = null) { try { $stmt = $this->db->prepare('SELECT value FROM settings WHERE key = :key'); $stmt->bindValue(':key', $key, SQLITE3_TEXT); $result = $stmt->execute(); if ($row = $result->fetchArray(SQLITE3_ASSOC)) { return $row['value']; } } catch (Exception $e) { // 如果发生错误,返回默认值 } return isset($this->defaultSettings[$key]) ? $this->defaultSettings[$key] : $default; } public function setSetting($key, $value) { $stmt = $this->db->prepare('INSERT OR REPLACE INTO settings (key, value) VALUES (:key, :value)'); $stmt->bindValue(':key', $key, SQLITE3_TEXT); $stmt->bindValue(':value', $value, SQLITE3_TEXT); return $stmt->execute(); } public function getDefaultSettings() { return $this->defaultSettings; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118<?phpheader('Content-Type: application/json');
// 设置允许的图片类型$allowed_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];$max_size = 20 * 1024 * 1024; // 20MB
try { // 确保上传目录存在 $upload_dir = __DIR__ . '/uploads/images/'; if (!is_dir($upload_dir)) { // 尝试创建目录 if (!mkdir($upload_dir, 0755, true)) { throw new Exception('无法创建上传目录,请检查权限'); } // 创建 .htaccess 文件来保护上传目录 $htaccess = $upload_dir . '.htaccess'; if (!file_exists($htaccess)) { $htaccess_content = "Options -Indexes\n"; $htaccess_content .= "DirectoryIndex 403.html\n"; // 使用 403.html 作为目录默认页 $htaccess_content .= "AddType text/plain .php\n"; $htaccess_content .= "AddType text/plain .html\n"; $htaccess_content .= "AddType text/plain .htm\n"; $htaccess_content .= "AddType text/plain .htaccess\n"; file_put_contents($htaccess, $htaccess_content); } // 创建 index.html 文件来防止目录列表 $index_html = $upload_dir . 'index.html'; if (!file_exists($index_html)) { file_put_contents($index_html, '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1></body></html>'); } // 创建 403.html 文件来防止目录列表 $forbidden_page = $upload_dir . '403.html'; if (!file_exists($forbidden_page)) { file_put_contents($forbidden_page, '<!DOCTYPE html><html><head><title>403 Forbidden</title></head><body><h1>403 Forbidden</h1><p>Access to this directory is forbidden.</p></body></html>'); } }
if (!isset($_FILES['image'])) { throw new Exception('没有收到图片文件'); }
$file = $_FILES['image']; // 检查错误 if ($file['error'] !== UPLOAD_ERR_OK) { throw new Exception('文件上传错误: ' . $file['error']); } // 检查文件类型 if (!in_array($file['type'], $allowed_types)) { throw new Exception('不支持的文件类型'); } // 检查文件大小 if ($file['size'] > $max_size) { throw new Exception('文件大小超过限制'); } // 生成唯一文件名 $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION)); $filename = uniqid() . '_' . bin2hex(random_bytes(8)) . '.' . $extension; // 移动文件到目标位置 $filepath = $upload_dir . $filename; if (!move_uploaded_file($file['tmp_name'], $filepath)) { throw new Exception('文件保存失败'); } // 设置文件权限 chmod($filepath, 0644); // 在成功上传后添加 .htaccess 文件来设置图片缓存 $images_htaccess = $upload_dir . '.htaccess'; if (!file_exists($images_htaccess)) { $cache_rules = "<IfModule mod_expires.c> ExpiresActive On ExpiresByType image/jpg \"access plus 1 year\" ExpiresByType image/jpeg \"access plus 1 year\" ExpiresByType image/gif \"access plus 1 year\" ExpiresByType image/png \"access plus 1 year\" ExpiresByType image/webp \"access plus 1 year\"</IfModule>
<IfModule mod_headers.c> <FilesMatch \"\.(jpg|jpeg|png|gif|webp)$\"> Header set Cache-Control \"public, max-age=31536000\" </FilesMatch></IfModule>
Options -IndexesDirectoryIndex 403.htmlAddType text/plain .phpAddType text/plain .htmlAddType text/plain .htmAddType text/plain .htaccess"; file_put_contents($images_htaccess, $cache_rules); } // 返回成功响应 echo json_encode([ 'success' => true, 'url' => '/uploads/images/' . $filename ]); } catch (Exception $e) { error_log('Image upload error: ' . $e->getMessage()); http_response_code(400); echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]);}.gitignoreAdded+8
.htaccessAdded+17
.nginxAdded+14
DockerfileAdded+72
FileShare.phpAdded+240
LICENSEAdded+674
api.phpAdded+93
css/marked.cssAdded+132
css/style.cssAdded+892
docker-compose.ymlAdded+11
favicon.pngAdded
file_api.phpAdded+112
index.phpAdded+814
init.phpAdded+70
router.phpAdded+72
settings.phpAdded+116
upload.phpAdded+118