Merge branch '1.7' into php8

This commit is contained in:
xiaomlove
2022-03-31 16:43:51 +08:00
140 changed files with 21731 additions and 273 deletions

View File

@@ -1,9 +1,11 @@
<?php
define('NEXUS_START', microtime(true));
define('IN_NEXUS', true);
$rootpath = dirname(__DIR__) . '/';
set_include_path(get_include_path() . PATH_SEPARATOR . $rootpath);
require $rootpath . 'include/globalfunctions.php';
require $rootpath . 'include/functions.php';
require $rootpath . 'include/core.php';
require $rootpath . 'classes/class_advertisement.php';
require $rootpath . 'classes/class_attendance.php';

View File

@@ -1,7 +1,11 @@
<?php
define('NEXUS_START', microtime(true));
define('IN_NEXUS', true);
defined('IN_NEXUS') || define('IN_NEXUS', true);
defined('IN_TRACKER') || define('IN_TRACKER', true);
$rootpath= dirname(__DIR__) . '/';
require $rootpath . 'include/core.php';
require $rootpath . 'include/functions_announce.php';
require_once $rootpath . 'include/constants.php';
require_once $rootpath . 'include/globalfunctions.php';
require_once $rootpath . 'include/functions_announce.php';
require_once $rootpath . 'vendor/autoload.php';
\Nexus\Nexus::boot();

View File

@@ -6,7 +6,7 @@ die('Hacking attempt!');
function printProgress($msg) {
$br = php_sapi_name() == 'cli' ? "\n" : "<br />";
echo sprintf("[%s] [%s] %s ... done!%s", date('Y-m-d H:i:s'), REQUEST_ID, $msg, $br);
echo sprintf("[%s] [%s] %s ... done!%s", date('Y-m-d H:i:s'), nexus()->getRequestId(), $msg, $br);
}
function torrent_promotion_expire($days, $type = 2, $targettype = 1){

View File

@@ -7,31 +7,38 @@ defined('NEXUSPHPURL') || define("NEXUSPHPURL","https://nexusphp.org");
defined('NEXUSWIKIURL') || define("NEXUSWIKIURL","https://doc.nexusphp.org");
defined('VERSION') || define("VERSION","Powered by <a href=\"aboutnexus.php\">".PROJECTNAME."</a>");
defined('THISTRACKER') || define("THISTRACKER","General");
$showversion = " - Powered by ".PROJECTNAME;
defined('ROOT_PATH') || define('ROOT_PATH', dirname(__DIR__) . '/');
defined('CURRENT_SCRIPT') || define('CURRENT_SCRIPT', strstr(basename($_SERVER['SCRIPT_FILENAME']), '.', true));
defined('IS_ANNOUNCE') || define('IS_ANNOUNCE', CURRENT_SCRIPT == 'announce');
defined('PLATFORM_ADMIN') || define('PLATFORM_ADMIN', 'admin');
defined('PLATFORM_USER') || define('PLATFORM_USER', 'user');
defined('PLATFORMS') || define('PLATFORMS', [PLATFORM_ADMIN, PLATFORM_USER]);
defined('CURRENT_PLATFORM') || define('CURRENT_PLATFORM', $_SERVER['HTTP_PLATFORM'] ?? '');
defined('IS_PLATFORM_ADMIN') || define('IS_PLATFORM_ADMIN', CURRENT_PLATFORM == PLATFORM_ADMIN);
defined('IS_PLATFORM_USER') || define('IS_PLATFORM_USER', CURRENT_PLATFORM == PLATFORM_USER);
//define the REQUEST_ID
if (!defined('REQUEST_ID')) {
if (!empty($_SERVER['HTTP_X_REQUEST_ID'])) {
$requestId = $_SERVER['HTTP_X_REQUEST_ID'];
} elseif (!empty($_SERVER['REQUEST_ID'])) {
$requestId = $_SERVER['REQUEST_ID'];
if (!defined('RUNNING_IN_OCTANE')) {
if (!empty($_SERVER['PWD']) && str_contains($_SERVER['PWD'], 'vendor/laravel/octane/bin')) {
define('RUNNING_IN_OCTANE', true);
} else {
$prefix = ($_SERVER['SCRIPT_FILENAME'] ?? '') . implode('', $_SERVER['argv'] ?? []);
$prefix = substr(md5($prefix), 0, 4);
// 4 + 23 = 27 characters, after replace '.', 26
$requestId = str_replace('.', '', uniqid($prefix, true));
$requestId .= bin2hex(random_bytes(3));
define('RUNNING_IN_OCTANE', false);
}
define('REQUEST_ID', $requestId);
}
//defined('CURRENT_SCRIPT') || define('CURRENT_SCRIPT', strstr(basename($_SERVER['SCRIPT_FILENAME']), '.', true));
//defined('IS_ANNOUNCE') || define('IS_ANNOUNCE', CURRENT_SCRIPT == 'announce');
//
//defined('PLATFORM_ADMIN') || define('PLATFORM_ADMIN', 'admin');
//defined('PLATFORM_USER') || define('PLATFORM_USER', 'user');
//defined('PLATFORMS') || define('PLATFORMS', [PLATFORM_ADMIN, PLATFORM_USER]);
//defined('CURRENT_PLATFORM') || define('CURRENT_PLATFORM', $_SERVER['HTTP_PLATFORM'] ?? '');
//defined('IS_PLATFORM_ADMIN') || define('IS_PLATFORM_ADMIN', CURRENT_PLATFORM == PLATFORM_ADMIN);
//defined('IS_PLATFORM_USER') || define('IS_PLATFORM_USER', CURRENT_PLATFORM == PLATFORM_USER);
//
//
////define the REQUEST_ID
//if (!defined('REQUEST_ID')) {
// if (!empty($_SERVER['HTTP_X_REQUEST_ID'])) {
// $requestId = $_SERVER['HTTP_X_REQUEST_ID'];
// } elseif (!empty($_SERVER['REQUEST_ID'])) {
// $requestId = $_SERVER['REQUEST_ID'];
// } else {
// $prefix = ($_SERVER['SCRIPT_FILENAME'] ?? '') . implode('', $_SERVER['argv'] ?? []);
// $prefix = substr(md5($prefix), 0, 4);
// // 4 + 23 = 27 characters, after replace '.', 26
// $requestId = str_replace('.', '', uniqid($prefix, true));
// $requestId .= bin2hex(random_bytes(3));
// }
// define('REQUEST_ID', $requestId);
//}

View File

@@ -1,6 +1,7 @@
<?php
require __DIR__ . '/constants.php';
require $rootpath . 'vendor/autoload.php';
require_once __DIR__ . '/constants.php';
require_once $rootpath . 'vendor/autoload.php';
\Nexus\Nexus::boot();
if (!file_exists($rootpath . '.env')) {
$installScriptRelativePath = 'install/install.php';
$installScriptFile = $rootpath . "public/$installScriptRelativePath";
@@ -11,18 +12,18 @@ if (!file_exists($rootpath . '.env')) {
require $rootpath . 'nexus/Database/helpers.php';
require $rootpath . 'classes/class_cache_redis.php';
require $rootpath . 'include/eloquent.php';
require $rootpath . 'include/config.php';
ini_set('date.timezone', nexus_config('nexus.timezone'));
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 0);
if (!isRunningInConsole() && !in_array(CURRENT_SCRIPT, ['announce', 'scrape', 'torrentrss', 'download'])) {
$Cache = new class_cache_redis(); //Load the caching class
$Cache->setLanguageFolderArray(get_langfolder_list());
require $rootpath . 'include/config.php';
if (!in_array(nexus()->getScript(), ['announce', 'scrape', 'torrentrss', 'download'])) {
require $rootpath . get_langfile_path("functions.php");
checkGuestVisit();
}
$Cache = new class_cache_redis(); //Load the caching class
$Cache->setLanguageFolderArray(get_langfolder_list());
define('TIMENOW', time());
$USERUPDATESET = array();
$query_name=array();

View File

@@ -2274,7 +2274,7 @@ function get_style_highlight()
function stdhead($title = "", $msgalert = true, $script = "", $place = "")
{
global $lang_functions;
global $CURUSER, $CURLANGDIR, $USERUPDATESET, $iplog1, $oldip, $SITE_ONLINE, $FUNDS, $SITENAME, $SLOGAN, $logo_main, $BASEURL, $offlinemsg, $showversion,$enabledonation, $staffmem_class, $titlekeywords_tweak, $metakeywords_tweak, $metadescription_tweak, $cssdate_tweak, $deletenotransfertwo_account, $neverdelete_account, $iniupload_main;
global $CURUSER, $CURLANGDIR, $USERUPDATESET, $iplog1, $oldip, $SITE_ONLINE, $FUNDS, $SITENAME, $SLOGAN, $logo_main, $BASEURL, $offlinemsg,$enabledonation, $staffmem_class, $titlekeywords_tweak, $metakeywords_tweak, $metadescription_tweak, $cssdate_tweak, $deletenotransfertwo_account, $neverdelete_account, $iniupload_main;
global $tstart;
global $Cache;
global $Advertisement;
@@ -2302,7 +2302,7 @@ function stdhead($title = "", $msgalert = true, $script = "", $place = "")
$title = $SITENAME." :: " . htmlspecialchars($title);
if ($titlekeywords_tweak)
$title .= " ".htmlspecialchars($titlekeywords_tweak);
$title .= $showversion;
$title .= " - Powered by ".PROJECTNAME;
if ($SITE_ONLINE == "no") {
if (get_user_class() < UC_ADMINISTRATOR) {
die($lang_functions['std_site_down_for_maintenance']);
@@ -2660,7 +2660,7 @@ function stdfoot() {
}
// Variables for End Time
$tend = microtime(true);
$totaltime = ($tend - NEXUS_START);
$totaltime = ($tend - nexus()->getStartTimestamp());
$year = substr($datefounded, 0, 4);
$yearfounded = ($year ? $year : 2007);
print(" (c) "." <a href=\"" . get_protocol_prefix() . $BASEURL."\" target=\"_self\">".$SITENAME."</a> ".($icplicense_main ? " ".$icplicense_main." " : "").(date("Y") != $yearfounded ? $yearfounded."-" : "").date("Y")." ".VERSION."<br /><br />");
@@ -2812,6 +2812,9 @@ function base64 ($string, $encode=true) {
function loggedinorreturn($mainpage = false) {
global $CURUSER,$BASEURL;
if (!$CURUSER) {
if (nexus()->getScript() == 'ajax') {
exit(fail('Not login!', $_POST));
}
if ($mainpage)
header("Location: " . get_protocol_prefix() . "$BASEURL/login.php");
else {
@@ -2929,7 +2932,7 @@ function commenttable($rows, $type, $parent_id, $review = false)
$uidArr = array_unique(array_column($rows, 'user'));
$neededColumns = array('id', 'noad', 'class', 'enabled', 'privacy', 'avatar', 'signature', 'uploaded', 'downloaded', 'last_access', 'username', 'donor', 'leechwarn', 'warned', 'title');
$userInfoArr = \App\Models\User::query()->with(['valid_medals'])->find($uidArr, $neededColumns)->keyBy('id');
$userInfoArr = \App\Models\User::query()->with(['wearing_medals'])->find($uidArr, $neededColumns)->keyBy('id');
foreach ($rows as $row)
{
@@ -2944,7 +2947,7 @@ function commenttable($rows, $type, $parent_id, $review = false)
}
}
print("<div style=\"margin-top: 8pt; margin-bottom: 8pt;\"><table id=\"cid".$row["id"]."\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" width=\"100%\"><tr><td class=\"embedded\" width=\"99%\">#" . $row["id"] . "&nbsp;&nbsp;<font color=\"gray\">".$lang_functions['text_by']."</font>");
print(build_medal_image($userInfo->valid_medals, 20) . get_username($row["user"],false,true,true,false,false,true));
print(build_medal_image($userInfo->wearing_medals, 20) . get_username($row["user"],false,true,true,false,false,true));
print("&nbsp;&nbsp;<font color=\"gray\">".$lang_functions['text_at']."</font>".gettime($row["added"]).
($row["editedby"] && get_user_class() >= $commanage_class ? " - [<a href=\"comment.php?action=vieworiginal&amp;cid=".$row['id']."&amp;type=".$type."\">".$lang_functions['text_view_original']."</a>]" : "") . "</td><td class=\"embedded nowrap\" width=\"1%\"><a href=\"#top\"><img class=\"top\" src=\"pic/trans.gif\" alt=\"Top\" title=\"Top\" /></a>&nbsp;&nbsp;</td></tr></table></div>");
$avatar = ($CURUSER["avatars"] == "yes" ? htmlspecialchars(trim($userRow["avatar"])) : "");
@@ -4838,7 +4841,7 @@ function checkGuestVisit()
if (empty($guestVisitType) || $guestVisitType == 'normal') {
return;
}
if (in_array(CURRENT_SCRIPT, ['login', 'takelogin', 'image']) && canDoLogin()) {
if (in_array(nexus()->getScript(), ['login', 'takelogin', 'image']) && canDoLogin()) {
return;
}
@@ -5223,7 +5226,7 @@ function list_require_search_box_id()
'userdetails' => [$setting['browsecat'], $setting['specialcat']],
'offers' => [$setting['browsecat'], $setting['specialcat']],
];
return $maps[CURRENT_SCRIPT] ?? [];
return $maps[nexus()->getScript()] ?? [];
}
function can_access_torrent($torrent)
@@ -5297,13 +5300,24 @@ function msgalert($url, $text, $bgcolor = "red")
print("</td></tr></table></p><br />");
}
function build_medal_image(\Illuminate\Support\Collection $medals, $maxHeight = 200): string
function build_medal_image(\Illuminate\Support\Collection $medals, $maxHeight = 200, $withActions = false): string
{
$medalImages = [];
$wrapBefore = '<div style="display: inline;">';
$wrapAfter = '</div>';
foreach ($medals as $medal) {
$medalImages[] = sprintf('<img src="%s" title="%s" style="max-height: %spx"/>', $medal->image_large, $medal->name, $maxHeight);
$html = sprintf('<div style="display: inline"><img src="%s" title="%s" style="max-height: %spx"/>', $medal->image_large, $medal->name, $maxHeight);
if ($withActions) {
$checked = '';
if ($medal->pivot->status == \App\Models\UserMedal::STATUS_WEARING) {
$checked = ' checked';
}
$html .= sprintf('<label>%s<input type="checkbox" name="medal_wearing_status" value="%s"%s></label>', '佩戴', $medal->id, $checked);
}
$html .= '</div>';
$medalImages[] = $html;
}
return implode('', $medalImages);
return $wrapBefore . implode('', $medalImages) . $wrapAfter;
}
function insert_torrent_tags($torrentId, $tagIdArr, $sync = false)

View File

@@ -336,4 +336,27 @@ function check_client($peer_id, $agent, &$agent_familyid)
return "Banned Client, Please goto $BASEURL/faq.php#id29 for a list of acceptable clients";
}
}
function request_local_api($api)
{
$start = microtime(true);
$ch = curl_init();
$options = [
CURLOPT_URL => sprintf('%s?%s', trim($api, '/'), $_SERVER['QUERY_STRING']),
CURLOPT_USERAGENT => $_SERVER["HTTP_USER_AGENT"],
CURLOPT_HTTPHEADER => ['REQUEST_ID: ' . nexus()->getRequestId(), 'Platform: tracker'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_TIMEOUT => 60,
];
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$log = sprintf(
"[LOCAL_ANNOUNCE_API] [%s] options: %s, response(%s): %s",
number_format(microtime(true) - $start, 3), nexus_json_encode($options), gettype($response), $response
);
do_log($log);
return $response;
}
?>

View File

@@ -1,4 +1,7 @@
<?php
use JetBrains\PhpStorm\Pure;
function get_global_sp_state()
{
global $Cache;
@@ -153,26 +156,20 @@ function nexus_dd($vars)
* @param $log
* @param string $level
*/
function do_log($log, $level = 'info')
function do_log($log, $level = 'info', $echo = false)
{
static $uid, $passkey, $env, $sequence, $setLogLevel;
static $env, $setLogLevel;
if (is_null($setLogLevel)) {
$setLogLevel = nexus_env('LOG_LEVEL', 'debug');
}
$logLevels = [
\Psr\Log\LogLevel::DEBUG,
\Psr\Log\LogLevel::INFO,
\Psr\Log\LogLevel::NOTICE,
\Psr\Log\LogLevel::WARNING,
\Psr\Log\LogLevel::ERROR,
\Psr\Log\LogLevel::CRITICAL,
\Psr\Log\LogLevel::ALERT,
\Psr\Log\LogLevel::EMERGENCY,
];
if (is_null($env)) {
$env = nexus_env('APP_ENV', 'production');
}
$logLevels = ['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency'];
$setLogLevelKey = array_search($setLogLevel, $logLevels);
$currentLogLevelKey = array_search($level, $logLevels);
if ($currentLogLevelKey === false) {
$level = \Psr\log\LogLevel::ERROR;
$level = 'error';
$log = "[ERROR_LOG_LEVEL] $log";
$currentLogLevelKey = array_search($level, $logLevels);
}
@@ -184,32 +181,25 @@ function do_log($log, $level = 'info')
if (($fd = fopen($logFile, 'a')) === false) {
$fd = fopen(sys_get_temp_dir() . '/nexus.log', 'a');
}
if (is_null($uid)) {
$sequence = 0;
if (IN_NEXUS) {
global $CURUSER;
$user = $CURUSER;
$uid = $user['id'] ?? 0;
$passkey = $user['passkey'] ?? $_REQUEST['passkey'] ?? $_REQUEST['authkey'] ?? '';
$env = nexus_env('APP_ENV');
} else {
$user = \Illuminate\Support\Facades\Auth::user();
$uid = $user->id ?? 0;
$passkey = $user->passkey ?? $_REQUEST['passkey'] ?? $_REQUEST['authkey'] ?? '';
$env = env('APP_ENV');
}
if (IN_NEXUS) {
global $CURUSER;
$user = $CURUSER;
$uid = $user['id'] ?? 0;
$passkey = $user['passkey'] ?? $_REQUEST['passkey'] ?? $_REQUEST['authkey'] ?? '';
} else {
$sequence++;
$user = \Illuminate\Support\Facades\Auth::user();
$uid = $user->id ?? 0;
$passkey = $user->passkey ?? request('passkey', request('authkey', ''));
}
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 2);
$content = sprintf(
"[%s] [%s] [%s] [%s] [%s] [%s] %s.%s %s:%s %s%s%s %s%s",
date('Y-m-d H:i:s'),
defined('REQUEST_ID') ? REQUEST_ID : '',
nexus() ? nexus()->getRequestId() : 'NO_REQUEST_ID',
nexus() ? nexus()->getLogSequence() : 0,
sprintf('%.3f', microtime(true) - (nexus() ? nexus()->getStartTimestamp() : 0)),
$uid,
$passkey,
$sequence,
sprintf('%.3f', microtime(true) - NEXUS_START),
$env, $level,
$backtrace[0]['file'] ?? '',
$backtrace[0]['line'] ?? '',
@@ -221,6 +211,12 @@ function do_log($log, $level = 'info')
);
fwrite($fd, $content);
fclose($fd);
if (is_bool($echo) && $echo) {
echo $content . PHP_EOL;
}
if (nexus()) {
nexus()->incrementLogSequence();
}
}
function getLogFile()
@@ -286,19 +282,23 @@ function get_setting($name = null)
{
static $settings;
if (is_null($settings)) {
//get all settings from database
$sql = "select name, value from settings";
$result = sql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
$value = $row['value'];
if (!is_null($value)) {
$arr = json_decode($value, true);
if (is_array($arr)) {
$value = $arr;
$settings = \Nexus\Database\NexusDB::remember("nexus_settings_in_nexus" . __METHOD__, 10, function () {
//get all settings from database
$sql = "select name, value from settings";
$result = sql_query($sql);
$final = [];
while ($row = mysql_fetch_assoc($result)) {
$value = $row['value'];
if (!is_null($value)) {
$arr = json_decode($value, true);
if (is_array($arr)) {
$value = $arr;
}
}
arr_set($final, $row['name'], $value);
}
arr_set($settings, $row['name'], $value);
}
return $final;
});
}
if (is_null($name)) {
return $settings;
@@ -310,7 +310,7 @@ function nexus_env($key = null, $default = null)
{
static $env;
if (is_null($env)) {
$envFile = defined('ROOT_PATH') ? ROOT_PATH . '.env' : base_path('.env');
$envFile = dirname(__DIR__) . '/.env';
$env = readEnvFile($envFile);
}
if (is_null($key)) {
@@ -492,26 +492,19 @@ function api(...$args)
$msg = $args[1];
$data = $args[2];
}
if (defined('LARAVEL_START')) {
$start = LARAVEL_START;
if ($data instanceof \Illuminate\Http\Resources\Json\ResourceCollection || $data instanceof \Illuminate\Http\Resources\Json\JsonResource) {
$data = $data->response()->getData(true);
if (isset($data['data']) && count($data) == 1) {
//单纯的集合,无分页等其数据
$data = $data['data'];
}
if ($data instanceof \Illuminate\Http\Resources\Json\ResourceCollection || $data instanceof \Illuminate\Http\Resources\Json\JsonResource) {
$data = $data->response()->getData(true);
if (isset($data['data']) && count($data) == 1) {
//单纯的集合,无分页等其数据
$data = $data['data'];
}
} elseif (defined('NEXUS_START')) {
$start = NEXUS_START;
} else {
throw new \RuntimeException("no constant START is defined.");
}
return [
'ret' => (int)$ret,
'msg' => (string)$msg,
'data' => $data,
'time' => (float)number_format(microtime(true) - $start, 3),
'rid' => REQUEST_ID,
'time' => (float)number_format(microtime(true) - nexus()->getStartTimestamp(), 3),
'rid' => nexus()->getRequestId(),
];
}
@@ -678,3 +671,18 @@ function get_hr_ratio($uped, $downed)
return $ratio;
}
function nexus()
{
return \Nexus\Nexus::instance();
}
function site_info()
{
$setting = \App\Models\Setting::get('basic');
$siteInfo = [
'site_name' => $setting['SITENAME'],
'base_url' => getSchemeAndHttpHost(),
];
return $siteInfo;
}