support plugin

This commit is contained in:
xiaomlove
2022-06-03 03:42:53 +08:00
parent 29d414ce0a
commit 44c750234a
21 changed files with 333 additions and 68 deletions

1
.gitignore vendored
View File

@@ -25,3 +25,4 @@ yarn-error.log
/imdb/images
/resources/geoip
.DS_Store
/plugins

View File

@@ -0,0 +1,51 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class Plugin extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'plugin {action} {name}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Plugin management, arguments: action plugin';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$plugin = new \Nexus\Plugin\Plugin();
$action = $this->argument('action');
$name = $this->argument('name');
$mainClass = $plugin->getMainClass($name);
if (!$mainClass) {
$this->error("Can not find plugin: $name");
return 1;
}
if ($action == 'install') {
call_user_func([$mainClass, 'install']);
} elseif ($action == 'uninstall') {
call_user_func([$mainClass, 'uninstall']);
} else {
$this->error("Not support action: $action");
return 1;
}
$log = sprintf("[%s], %s plugin: %s successfully !", nexus()->getRequestId(), $action, $name);
$this->info($log);
do_log($log);
return 0;
}
}

View File

@@ -39,6 +39,7 @@ use JeroenG\Explorer\Infrastructure\Scout\ElasticEngine;
use League\Flysystem\StorageAttributes;
use Nexus\Database\NexusDB;
use Nexus\Imdb\Imdb;
use NexusPlugin\PostLike\PostLike;
use Rhilip\Bencode\Bencode;
class Test extends Command
@@ -74,62 +75,9 @@ class Test extends Command
*/
public function handle()
{
// $searchRep = new SearchRepository();
// $r = $searchRep->deleteIndex();
// $r = $searchRep->createIndex();
// $r = $searchRep->import();
// dd($r);
//
// $arr = [
// 'cat' => 'category',
// 'source' => 'source',
// 'medium' => 'medium',
// 'codec' => 'codec',
// 'audiocodec' => 'audiocodec',
// 'standard' => 'standard',
// 'processing' => 'processing',
// 'team' => 'team',
// ];
$queryString = 'cat401=1&cat404=1&source2=1&medium2=1&medium3=1&codec3=1&audiocodec3=1&standard2=1&standard3=1&processing2=1&team3=1&team4=1&incldead=1&spstate=0&inclbookmarked=0&search=&search_area=0&search_mode=0';
$userSetting = '[cat401][cat404][sou1][med1][cod1][sta2][sta3][pro2][tea2][aud2][incldead=0][spstate=3][inclbookmarked=2]';
// foreach ($arr as $queryField => $value) {
//// $pattern = sprintf("/\[%s([\d]+)\]/", substr($queryField, 0, 3));
// $pattern = "/{$queryField}([\d]+)=/";
// if (preg_match_all($pattern, $queryString, $matches)) {
// dump($matches);
// echo '----------------------' . PHP_EOL;
// }
// }
// $r = preg_match("/\[incldead=([\d]+)\]/", $userSetting, $matches);
// dump($matches);
$params = [
'tag_id' => 1,
// 'incldead' => 0,
// 'spstate' => 0,
// 'inclbookmarked' => 0,
// 'search' => '5034',
// 'search_area' => 4,
// 'search_mode' => 0,
];
$queryString = "cat401=1&cat404=1&cat405=1&cat402=1&cat403=1&cat406=1&cat407=1&cat409=1&cat408=1&incldead=0&spstate=0&inclbookmarked=0&search=5034838&search_area=4&search_mode=0";
// $r = $searchRep->listTorrentFromEs($params, 1, '');
// $r = $searchRep->updateTorrent(1);
// $r = $searchRep->updateUser(1);
// $r = $searchRep->addTorrent(1);
// $r = $searchRep->deleteBookmark(1);
// $r = $searchRep->addBookmark(1);
// $rep = new AttendanceRepository();
// $uid = 1;
// $attendance = $rep->getAttendance($uid);
// $r = $rep->migrateAttendanceLogs($uid);
// $r = $rep->getContinuousDays($attendance);
// $r = $rep->getContinuousPoints(11);
$r = trim(exec('command -v 7z.exe'));
dd($r);
$postLike = new PostLike();
$postLike->install();
// $postLike->uninstall();
}

View File

@@ -41,6 +41,10 @@ class Handler extends ExceptionHandler
*/
public function register()
{
if (!request()->expectsJson()) {
return;
}
$this->reportable(function (Throwable $e) {
//
});

View File

@@ -57,6 +57,7 @@ class Kernel extends HttpKernel
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.nexus' => \App\Http\Middleware\NexusAuth::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,

View File

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

View File

@@ -2,7 +2,10 @@
namespace App\Providers;
use App\Models\User;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
class AuthServiceProvider extends ServiceProvider
@@ -25,6 +28,34 @@ class AuthServiceProvider extends ServiceProvider
{
$this->registerPolicies();
//
Auth::viaRequest('nexus-cookie', function (Request $request) {
return $this->getUserByCookie($request->cookie());
});
}
private function getUserByCookie($cookie)
{
if (empty($cookie["c_secure_pass"]) || empty($cookie["c_secure_uid"]) || empty($cookie["c_secure_login"])) {
return null;
}
$b_id = base64($cookie["c_secure_uid"],false);
$id = intval($b_id ?? 0);
if (!$id || !is_valid_id($id) || strlen($cookie["c_secure_pass"]) != 32) {
return null;
}
$user = User::query()->find($id);
if (!$user) {
return null;
}
if ($cookie["c_secure_login"] == base64("yeah")) {
if ($cookie["c_secure_pass"] != md5($user->passhash . $_SERVER["REMOTE_ADDR"])) {
return null;
}
} else {
if ($cookie["c_secure_pass"] !== md5($user->passhash)) {
return null;
}
}
return $user;
}
}

View File

@@ -84,7 +84,8 @@
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true
"sort-packages": true,
"secure-http": false
},
"minimum-stability": "dev",
"prefer-stable": true

2
composer.lock generated
View File

@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "1f44d54112683e0d2cd0738ac87d54d6",
"content-hash": "3387b3f52798b9a38c8eb3c895498916",
"packages": [
{
"name": "asm89/stack-cors",

View File

@@ -46,6 +46,9 @@ return [
'provider' => 'users',
'hash' => false,
],
'nexus' => [
'driver' => 'nexus-cookie',
],
],
/*

View File

@@ -1,6 +1,6 @@
<?php
defined('VERSION_NUMBER') || define('VERSION_NUMBER', '1.7.13');
defined('RELEASE_DATE') || define('RELEASE_DATE', '2022-06-01');
defined('VERSION_NUMBER') || define('VERSION_NUMBER', '1.7.14');
defined('RELEASE_DATE') || define('RELEASE_DATE', '2022-06-03');
defined('IN_TRACKER') || define('IN_TRACKER', true);
defined('PROJECTNAME') || define("PROJECTNAME","NexusPHP");
defined('NEXUSPHPURL') || define("NEXUSPHPURL","https://nexusphp.org");

View File

@@ -46,3 +46,6 @@ define ("UC_SYSOP",15);
define ("UC_STAFFLEADER",16);
ignore_user_abort(1);
@set_time_limit(60);
$hook = new \Nexus\Plugin\Hook();
$plugin = new \Nexus\Plugin\Plugin();

View File

@@ -726,3 +726,31 @@ function isIPV6 ($ip)
{
return filter_var($ip,FILTER_VALIDATE_IP, FILTER_FLAG_IPV6);
}
function add_filter($name, $function, $priority = 10, $argc = 1)
{
global $hook;
$hook->addFilter($name, $function, $priority, $argc);
}
function apply_filter($name, $value)
{
global $hook;
do_log("[APPLY_FILTER]: $name");
return $hook->applyFilter($name, func_get_args());
}
function add_action($name, $function, $priority = 10, $argc = 1)
{
global $hook;
$hook->addAction($name, $function, $priority, $argc);
}
function do_action($name, ...$args)
{
global $hook;
do_log("[DO_ACTION]: $name");
return $hook->doAction($name, ...$args);
}

View File

@@ -231,12 +231,11 @@ class Update extends Install
];
$table = 'sysoppanel';
$this->addMenu($table, $menus);
$menuToDel = ['amountupload.php', 'amountattendancecard.php', 'amountbonus.php'];
$menuToDel = ['amountupload.php', 'amountattendancecard.php', 'amountbonus.php', 'deletedisabled.php'];
$this->removeMenu('sysoppanel', $menuToDel);
$this->removeMenu('adminpanel', $menuToDel);
$this->removeMenu('modpanel', $menuToDel);
}
public function runExtraMigrate()

View File

@@ -3,6 +3,7 @@ namespace Nexus;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Nexus\Plugin\Hook;
final class Nexus
{

View File

@@ -0,0 +1,27 @@
<?php
namespace Nexus\Plugin;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Artisan;
abstract class BasePlugin
{
abstract function install();
abstract function boot();
public function runMigrations($dir, $rollback = false)
{
$command = "migrate";
if ($rollback) {
$command .= ":rollback";
}
$command .= " --realpath --force";
foreach (glob("$dir/*.php") as $file) {
$file = str_replace('\\', '/', $file);
$toExecute = "$command --path=$file";
do_log("command: $toExecute");
Artisan::call($toExecute);
}
}
}

71
nexus/Plugin/Hook.php Normal file
View File

@@ -0,0 +1,71 @@
<?php
namespace Nexus\Plugin;
class Hook
{
private static array $callbacks = [];
public function addFilter($name, $function, $priority, $argc)
{
$id = $this->buildUniqueId($function);
$isPriorityExists = isset(self::$callbacks[$priority]);
self::$callbacks[$name][$priority][$id] = ['function' => $function, 'argc' => $argc];
if (!$isPriorityExists && count(self::$callbacks) > 1) {
krsort(self::$callbacks, SORT_NUMERIC);
}
}
private function buildUniqueId($function): string
{
if (is_string($function)) {
return $function;
} elseif (is_object($function) && ($function instanceof \Closure)) {
//Closure
return spl_object_hash($function);
} elseif (is_array($function)) {
if (is_object($function[0])) {
return spl_object_hash($function[0]).$function[1];
} elseif (is_string($function[0])) {
return $function[0].'::'.$function[1];
}
}
throw new \InvalidArgumentException("Invalid function, type: " . gettype($function));
}
public function applyFilter($name, $value = '')
{
if (!isset(self::$callbacks[$name])) {
do_log("No this hook: $name");
return null;
}
$args = func_get_args();
reset(self::$callbacks[$name]);
do_log("name: $name, args: " . json_encode($args));
do {
foreach ((array)current(self::$callbacks[$name]) as $callback) {
$args[1] = $value;
$value = call_user_func_array($callback['function'], array_slice($args, 1, $callback['argc']));
}
}
while (next(self::$callbacks[$name]) !== false);
return $value;
}
public function addAction($name, $function, $priority, $argc)
{
return $this->addFilter($name, $function, $priority, $argc);
}
public function doAction($name, ...$args)
{
$this->applyFilter(...func_get_args());
}
public function dump()
{
echo '<pre>';
var_dump(self::$callbacks);
echo '</pre>';
}
}

57
nexus/Plugin/Plugin.php Normal file
View File

@@ -0,0 +1,57 @@
<?php
namespace Nexus\Plugin;
class Plugin
{
private static mixed $providers = null;
public function __construct()
{
$this->loadProviders();
if (!isRunningInConsole()) {
$this->bootPlugins();
}
}
public function enabled($name): bool
{
return !empty(self::$providers[$name]['providers']);
}
public function getMainClass($name)
{
if (isset(self::$providers[$name]['providers'][0])) {
$className = self::$providers[$name]['providers'][0];
$className = str_replace('ServiceProvider', '', $className);
if (class_exists($className)) {
return new $className;
}
}
}
private function bootPlugins()
{
foreach (self::$providers as $name => $providers) {
$provider = $providers['providers'][0];
$parts = explode('\\', $provider);
if ($parts[0] == 'NexusPlugin') {
$className = str_replace('ServiceProvider', '', $provider);
call_user_func([new $className, 'boot']);
}
}
}
private function loadProviders()
{
if (is_null(self::$providers)) {
$path = ROOT_PATH . 'bootstrap/cache/packages.php';
if (file_exists($path)) {
self::$providers = require $path;
} else {
self::$providers = [];
}
}
}
}

View File

@@ -18,9 +18,25 @@ $arr = mysql_fetch_assoc($res);
$id = $arr['id'];
$name = $arr['username'];
$res = sql_query("DELETE FROM users WHERE id=$id") or sqlerr();
if (mysql_affected_rows() != 1)
stderr("Error", "Unable to delete the account.");
try {
\Nexus\Database\NexusDB::transaction(function () use ($id) {
$affectedRows = \Nexus\Database\NexusDB::table('users')->where('id', $id)->delete();
if ($affectedRows != 1) {
throw new \RuntimeException("Unable to delete the account.");
}
$tables = [
'hit_and_runs' => 'uid',
'claims' => 'uid',
'exam_users' => 'uid',
'exam_progress' => 'uid',
];
foreach ($tables as $table => $key) {
\Nexus\Database\NexusDB::table($table)->where($key, $id)->delete();
}
});
} catch (\Exception $exception) {
stderr("Error", $exception->getMessage());
}
stderr("Success", "The account <b>".htmlspecialchars($name)."</b> was deleted.",false);
}
stdhead("Delete account");

View File

@@ -7,6 +7,7 @@ if (get_user_class() < UC_SYSOP)
permissiondenied();
$shownotice=false;
stderr("Error", "Hard deletion of users is not recommended and can cause many problems.");
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if ($_POST['sure'])

View File

@@ -4,7 +4,6 @@ dbconn();
require_once(get_langfile_path());
loggedinorreturn();
parked();
if ($enableextforum == 'yes') //check whether internal forum is disabled
permissiondenied();
@@ -635,7 +634,6 @@ if ($action == "viewtopic")
$userInfoArr = \App\Models\User::query()->with(['wearing_medals'])->find($uidArr, $neededColumns)->keyBy('id');
$pn = 0;
$lpr = get_last_read_post_id($topicid);
if ($Advertisement->enable_ad())
$forumpostad=$Advertisement->get_ad('forumpost');
foreach ($allPosts as $arr)
@@ -728,6 +726,8 @@ if ($action == "viewtopic")
print("<tr><td class=\"rowfollow\" align=\"center\" valign=\"middle\">".("'".$arr2['last_access']."'">$dt?"<img class=\"f_online\" src=\"pic/trans.gif\" alt=\"Online\" title=\"".$lang_forums['title_online']."\" />":"<img class=\"f_offline\" src=\"pic/trans.gif\" alt=\"Offline\" title=\"".$lang_forums['title_offline']."\" />" )."<a href=\"sendmessage.php?receiver=".htmlspecialchars(trim($arr2["id"]))."\"><img class=\"f_pm\" src=\"pic/trans.gif\" alt=\"PM\" title=\"".$lang_forums['title_send_message_to'].htmlspecialchars($arr2["username"])."\" /></a><a href=\"report.php?forumpost=$postid\"><img class=\"f_report\" src=\"pic/trans.gif\" alt=\"Report\" title=\"".$lang_forums['title_report_this_post']."\" /></a></td>");
print("<td class=\"toolbox\" align=\"right\">");
do_action('post_toolbox', $arr, $allPosts, $CURUSER['id']);
if ($maypost)
print("<a href=\"".htmlspecialchars("?action=quotepost&postid=".$postid)."\"><img class=\"f_quote\" src=\"pic/trans.gif\" alt=\"Quote\" title=\"".$lang_forums['title_reply_with_quote']."\" /></a>");
@@ -833,6 +833,7 @@ if ($action == "viewtopic")
else print($lang_forums['text_unpermitted_posting_here']);
print(key_shortcut($page,$pages-1));
do_action('page_forums_js');
stdfoot();
die;
}