Files
wordpress-theme-aksrt/inc/helpers/aksrt-user-center.php
T
kate522 8e0f9d989d feat(user-center): add cash wallet balance separate from credits
Introduce AKSRT_Balance (user_meta aksrt_balance + balance_log) for
Zibll-like pay_balance wallet. User center assets panel shows wallet
and points; balance gateway/card-pass/refunds credit cash when enabled.
2026-07-16 13:44:37 +08:00

490 lines
19 KiB
PHP

<?php
/**
* User center helpers.
*
* @package AKSRT
*/
defined('ABSPATH') || exit;
if (!function_exists('aksrt_normalize_user_contacts')) {
/**
* Sanitize the editable public contact list.
*
* @param mixed $raw_contacts Submitted contact rows.
* @return array<int, array{name:string,url:string,icon:string}>
*/
function aksrt_normalize_user_contacts($raw_contacts): array {
$contacts = [];
if (!is_array($raw_contacts)) {
return $contacts;
}
foreach ($raw_contacts as $contact) {
if (!is_array($contact)) {
continue;
}
$url = isset($contact['url']) ? esc_url_raw(wp_unslash($contact['url'])) : '';
$icon = isset($contact['icon']) ? sanitize_key(wp_unslash($contact['icon'])) : '';
$icon = preg_replace('/^(fab|fas|far)[\s-]*/', '', $icon);
$icon = preg_replace('/^fa[\s-]*/', '', (string) $icon);
$icon = trim(preg_replace('/^[\s-]+/', '', (string) $icon), '- ');
if (!$url || !$icon) {
continue;
}
$contacts[] = [
'name' => aksrt_icon_key_to_name($icon),
'url' => $url,
'icon' => $icon,
];
}
return $contacts;
}
}
if (!function_exists('aksrt_save_user_center_profile')) {
/**
* Save the user-center profile form for both AJAX and no-JS requests.
*
* @param int $user_id User being updated.
* @param array $input Untrusted request data.
* @return true|WP_Error
*/
function aksrt_save_user_center_profile(int $user_id, array $input) {
if (!$user_id || $user_id !== get_current_user_id()) {
return new WP_Error('aksrt_profile_forbidden', __('无权操作', 'aksrt'));
}
$errors = [];
$update = ['ID' => $user_id];
if (isset($input['nickname'])) {
$name = sanitize_text_field(wp_unslash($input['nickname']));
if (mb_strlen($name) < 1 || mb_strlen($name) > 50) {
$errors[] = __('昵称长度需在 1-50 字之间', 'aksrt');
} else {
$update['display_name'] = $name;
}
}
if (isset($input['description'])) {
$description = sanitize_textarea_field(wp_unslash($input['description']));
if (mb_strlen($description) > 500) {
$errors[] = __('个人简介不能超过 500 字', 'aksrt');
} else {
$update['description'] = $description;
}
}
if ($errors) {
return new WP_Error('aksrt_profile_invalid', implode('<br>', $errors));
}
if (count($update) > 1) {
$result = wp_update_user($update);
if (is_wp_error($result)) {
return $result;
}
}
update_user_meta($user_id, 'aksrt_user_contacts', aksrt_normalize_user_contacts($input['contacts'] ?? []));
return true;
}
}
if (!function_exists('aksrt_get_user_center_tab_url')) {
/**
* Build a canonical full-page user-center tab URL.
*/
function aksrt_get_user_center_tab_url(string $tab): string {
$url = remove_query_arg([
'tab', 'posts_page', 'comments_page', 'favorites_page', 'credits_page',
'post_status', 'saved', 'profile_error',
], aksrt_get_user_center_url());
return add_query_arg('tab', sanitize_key($tab), $url);
}
}
if (!function_exists('aksrt_normalize_user_center_tabs')) {
/**
* Normalize the dashboard tab contract.
*/
function aksrt_normalize_user_center_tabs(array $tabs): array {
$normalized = [];
foreach ($tabs as $key => $tab) {
$key = sanitize_key((string) $key);
if (!$key || !is_array($tab)) {
continue;
}
$normalized[$key] = [
'label' => (string) ($tab['label'] ?? $key),
'icon' => sanitize_html_class((string) ($tab['icon'] ?? 'circle')),
'template' => isset($tab['template']) ? (string) $tab['template'] : '',
'context_callback' => $tab['context_callback'] ?? null,
];
}
return $normalized;
}
}
if (!function_exists('aksrt_capture_user_center_view')) {
/**
* Render an internal user-center view into an inert HTML payload.
*/
function aksrt_capture_user_center_view(string $view, array $context): string {
// Built-in panels map to renderer files; "profile" content lives in profile-form.php.
$map = [
'profile' => 'form',
'posts' => 'posts',
'comments' => 'comments',
'favorites' => 'favorites',
'credits' => 'credits',
'settings' => 'settings',
'header' => 'header',
'sidebar' => 'sidebar',
'account-modals' => 'account-modals',
];
$view = sanitize_file_name($view);
$renderer = $map[$view] ?? $view;
$path = AKSRT_DIR . '/inc/helpers/user-center-renderers/profile-' . $renderer . '.php';
if (!is_file($path)) {
return '';
}
ob_start();
$args = ['context' => $context];
require $path;
return (string) ob_get_clean();
}
}
if (!function_exists('aksrt_capture_user_center_panel')) {
/**
* Capture a built-in or registered user-center panel body.
*/
function aksrt_capture_user_center_panel(string $tab_key, array $tab, array $context): string {
$built_in_tabs = ['profile', 'posts', 'comments', 'favorites', 'credits', 'settings'];
if (in_array($tab_key, $built_in_tabs, true)) {
return aksrt_capture_user_center_view($tab_key, $context);
}
$panel_context = $context;
if (is_callable($tab['context_callback'] ?? null)) {
$custom_context = call_user_func($tab['context_callback'], $context, $tab_key);
if (is_array($custom_context)) {
$panel_context = array_merge($panel_context, $custom_context);
}
}
$template = ltrim((string) ($tab['template'] ?? ''), '/');
if ($template === '') {
return '';
}
$template_path = locate_template([$template . '.php', $template], false, false);
if (!$template_path) {
return '';
}
ob_start();
load_template($template_path, false, ['context' => $panel_context]);
return (string) ob_get_clean();
}
}
if (!function_exists('aksrt_build_user_center_render_context')) {
/**
* Assemble all runtime data before template parts are entered.
*/
function aksrt_build_user_center_render_context(array $context): array {
$active_tab = (string) ($context['active_tab'] ?? 'profile');
$context['header_html'] = aksrt_capture_user_center_view('header', $context);
$context['sidebar_html'] = aksrt_capture_user_center_view('sidebar', $context);
$context['mobile_tabs'] = [];
foreach ((array) ($context['dashboard_tabs'] ?? []) as $tab_key => $tab) {
$context['mobile_tabs'][] = [
'key' => (string) $tab_key,
'label' => (string) ($tab['label'] ?? $tab_key),
'url' => aksrt_get_user_center_tab_url((string) $tab_key),
'is_active' => $active_tab === $tab_key,
];
}
$context['panels'] = [];
foreach ((array) ($context['dashboard_tabs'] ?? []) as $tab_key => $tab) {
$context['panels'][$tab_key] = [
'key' => (string) $tab_key,
'url' => aksrt_get_user_center_tab_url((string) $tab_key),
'is_active' => $active_tab === $tab_key,
'is_loaded' => $active_tab === $tab_key,
'html' => $active_tab === $tab_key
? aksrt_capture_user_center_panel((string) $tab_key, (array) $tab, $context)
: '',
];
}
$context['account_modals_html'] = 'settings' === $active_tab
? aksrt_capture_user_center_view('account-modals', $context)
: '';
return $context;
}
}
if (!function_exists('aksrt_user_center_empty_svgs')) {
/**
* Shared empty-state icons for user-center panels.
*
* @return array{post:string,comment:string,favorite:string}
*/
function aksrt_user_center_empty_svgs(): array {
return [
'post' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><path d="M14 2v6h6"/></svg>',
'comment' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>',
'favorite' => '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>',
];
}
}
if (!function_exists('aksrt_user_center_resolve_tabs')) {
/**
* Resolve dashboard tabs + active tab for the private user center.
*
* @return array{tabs:array,keys:array<int,string>,default:string,active:string,urls:array<string,string>}
*/
function aksrt_user_center_resolve_tabs(): array {
$tabs = class_exists('AKSRT_User_Center')
? AKSRT_User_Center::get_instance()->get_dashboard_tabs()
: [
'profile' => ['label' => __('个人信息', 'aksrt'), 'icon' => 'user'],
'posts' => ['label' => __('我的文章', 'aksrt'), 'icon' => 'file-alt'],
'comments' => ['label' => __('我的评论', 'aksrt'), 'icon' => 'comment'],
'favorites' => ['label' => __('我的收藏', 'aksrt'), 'icon' => 'star'],
'settings' => ['label' => __('账号设置', 'aksrt'), 'icon' => 'cog'],
];
$tabs = aksrt_normalize_user_center_tabs($tabs);
$keys = array_keys($tabs);
$default = in_array('profile', $keys, true) ? 'profile' : ($keys[0] ?? 'profile');
$active = isset($_GET['tab']) ? sanitize_key(wp_unslash($_GET['tab'])) : $default;
if ('signin' === $active) {
$active = 'credits';
} elseif ('invite' === $active) {
$active = 'settings';
}
if (!in_array($active, $keys, true)) {
$active = $default;
}
$urls = [];
foreach ($keys as $key) {
$urls[$key] = aksrt_get_user_center_tab_url($key);
}
return [
'tabs' => $tabs,
'keys' => $keys,
'default' => $default,
'active' => $active,
'urls' => $urls,
];
}
}
if (!function_exists('aksrt_user_center_post_status_counts')) {
/**
* Count the current user's posts by status (posts tab only).
*
* @return array{counts:array<string,int>,total:int}
*/
function aksrt_user_center_post_status_counts(int $user_id): array {
global $wpdb;
$counts = ['publish' => 0, 'draft' => 0, 'pending' => 0, 'private' => 0];
$rows = $wpdb->get_results($wpdb->prepare(
"SELECT post_status, COUNT(*) AS num FROM {$wpdb->posts} WHERE post_author = %d AND post_type = 'post' AND post_status IN ('publish','draft','pending','private') GROUP BY post_status",
$user_id
));
foreach ((array) $rows as $row) {
$counts[$row->post_status] = (int) $row->num;
}
return [
'counts' => $counts,
'total' => (int) array_sum($counts),
];
}
}
if (!function_exists('aksrt_user_center_runtime_config')) {
/**
* Frontend runtime config injected into the private user center page.
*/
function aksrt_user_center_runtime_config(int $user_id, string $default_tab, string $active_tab, array $tab_urls): array {
return [
'ajaxUrl' => admin_url('admin-ajax.php'),
'publicNonce' => wp_create_nonce('aksrt_public_nonce'),
'settingsNonce' => wp_create_nonce('aksrt_account_settings'),
'userId' => $user_id,
'defaultTab' => $default_tab,
'activeTab' => $active_tab,
'tabAliases' => ['signin' => 'credits', 'invite' => 'settings'],
'tabUrls' => $tab_urls,
'i18n' => [
'contactUrlPlaceholder' => __('链接 URL', 'aksrt'),
'deleteLabel' => __('删除', 'aksrt'),
'saving' => __('保存中…', 'aksrt'),
'saveBtn' => __('保存修改', 'aksrt'),
'saved' => __('已保存', 'aksrt'),
'saveFailed' => __('保存失败', 'aksrt'),
'networkError' => __('网络错误,请重试', 'aksrt'),
'confirmUnfavorite' => __('确定取消收藏这篇文章?', 'aksrt'),
'unfavorited' => __('已取消收藏', 'aksrt'),
'operationFailed' => __('操作失败', 'aksrt'),
'confirmUnbind' => __('确定解除绑定?', 'aksrt'),
'unbinding' => __('解除中...', 'aksrt'),
'unbindSuccess' => __('解除成功', 'aksrt'),
'unbindFailed' => __('解除失败', 'aksrt'),
'unbind' => __('解除', 'aksrt'),
],
];
}
}
if (!function_exists('aksrt_user_center_cover_upload_config')) {
/**
* Cover upload config for the private user-center hero.
*/
function aksrt_user_center_cover_upload_config(bool $allow_bg_upload): array {
if (!$allow_bg_upload) {
return [];
}
return [
'enabled' => true,
'restUrl' => rest_url('aksrt/v1/user/background'),
'restNonce' => wp_create_nonce('wp_rest'),
'buttonId' => 'aksrt-upload-bg-btn',
'inputId' => 'aksrt-bg-file-input',
'imageId' => 'aksrt-cover-img',
'fieldName' => 'background',
'maxSize' => 2097152,
'fallbackImage' => AKSRT_URI . '/assets/img/person_background.png',
'idleText' => __('编辑', 'aksrt'),
'loadingText' => __('上传中…', 'aksrt'),
'tooLargeText' => __('图片大小不能超过 2MB', 'aksrt'),
'successText' => __('背景图已更新', 'aksrt'),
'errorText' => __('上传失败', 'aksrt'),
'networkErrorText' => __('网络错误,请重试', 'aksrt'),
];
}
}
if (!function_exists('aksrt_get_user_center_render_context')) {
/**
* Resolve the current user's complete render context outside template files.
*/
function aksrt_get_user_center_render_context(WP_User $current_user): array {
$user_id = (int) $current_user->ID;
$user_center_settings = class_exists('AKSRT_Settings')
? AKSRT_Settings::get_user_center_settings()
: [
'tabs' => ['profile', 'posts', 'comments', 'favorites'],
'avatar_upload' => true,
'cover_upload' => true,
'social_links' => true,
];
$tabs = aksrt_user_center_resolve_tabs();
$active_tab = $tabs['active'];
$dashboard = function_exists('aksrt_get_user_dashboard_view')
? aksrt_get_user_dashboard_view($user_id, [
'viewer_id' => $user_id,
'include_recent_posts' => false,
'include_governance' => true,
])
: [];
$post_count = (int) ($dashboard['post_count'] ?? count_user_posts($user_id, 'post', true));
$comment_count = (int) ($dashboard['comment_count'] ?? get_comments(['user_id' => $user_id, 'count' => true, 'status' => 'approve']));
$favorite_post_ids = $dashboard['favorite_post_ids'] ?? [];
$favorite_count = (int) ($dashboard['favorite_count'] ?? count($favorite_post_ids));
$user_contacts = $dashboard['user_contacts'] ?? get_user_meta($user_id, 'aksrt_user_contacts', true);
$user_contacts = is_array($user_contacts) ? $user_contacts : [];
$user_background_url = (string) ($dashboard['background_url'] ?? get_user_meta($user_id, 'aksrt_background_image', true));
$allow_bg_upload = !empty($user_center_settings['cover_upload']) && class_exists('AKSRT_Settings') && aksrt_get_setting('allow_background_upload', false);
$post_status_filter = isset($_GET['post_status']) ? sanitize_key(wp_unslash($_GET['post_status'])) : 'publish';
if (!in_array($post_status_filter, ['all', 'publish', 'draft', 'pending', 'private'], true)) {
$post_status_filter = 'publish';
}
$user_status_counts = ['publish' => 0, 'draft' => 0, 'pending' => 0, 'private' => 0];
if ('posts' === $active_tab) {
$status = aksrt_user_center_post_status_counts($user_id);
$user_status_counts = $status['counts'];
$post_count = $status['total'];
}
$svgs = aksrt_user_center_empty_svgs();
require_once AKSRT_DIR . '/templates/parts/user-shared-helpers.php';
$vip_settings = class_exists('AKSRT_Settings') ? AKSRT_Settings::get_payment_vip_settings() : [];
$affiliate_settings = class_exists('AKSRT_Settings') ? AKSRT_Settings::get_payment_affiliate_settings() : [];
$show_credit_tabs = (bool) ($dashboard['credits_enabled'] ?? false);
$currency_name = (string) ($dashboard['currency_name'] ?? __('积分', 'aksrt'));
$balance_enabled = (bool) ($dashboard['balance_enabled'] ?? false);
$wallet_balance = (float) ($dashboard['wallet_balance'] ?? 0.0);
$render_context = [
'user_center_settings' => $user_center_settings,
'dashboard_tabs' => $tabs['tabs'],
'dashboard_tab_keys' => $tabs['keys'],
'default_dashboard_tab' => $tabs['default'],
'active_tab' => $active_tab,
'dashboard' => $dashboard,
'target_user' => $current_user,
'user_id' => $user_id,
'post_count' => $post_count,
'comment_count' => $comment_count,
'favorite_post_ids' => $favorite_post_ids,
'favorite_count' => $favorite_count,
'user_contacts' => $user_contacts,
'profile_signals' => $dashboard['profile_signals'] ?? [],
'user_background_url' => $user_background_url,
'allow_bg_upload' => $allow_bg_upload,
'show_avatar_edit' => !empty($user_center_settings['avatar_upload']),
'avatar_settings_url' => admin_url('profile.php'),
'notification_unread_count' => function_exists('aksrt_get_user_unread_notification_count') ? aksrt_get_user_unread_notification_count($user_id) : 0,
'messages_url' => function_exists('aksrt_get_messages_page_url') ? aksrt_get_messages_page_url() : '',
'per_page' => 10,
'posts_page' => max(1, isset($_GET['posts_page']) ? (int) $_GET['posts_page'] : 1),
'comments_page' => max(1, isset($_GET['comments_page']) ? (int) $_GET['comments_page'] : 1),
'favorites_page' => max(1, isset($_GET['favorites_page']) ? (int) $_GET['favorites_page'] : 1),
'post_status_filter' => $post_status_filter,
'user_status_counts' => $user_status_counts,
'svg_empty_post' => $svgs['post'],
'svg_empty_comment' => $svgs['comment'],
'svg_empty_favorite' => $svgs['favorite'],
'orders_url' => function_exists('aksrt_get_orders_page_url') ? aksrt_get_orders_page_url() : '',
'show_vip' => !empty($vip_settings['enabled']),
'show_credit_tabs' => $show_credit_tabs,
'affiliate_enabled' => $show_credit_tabs && !empty($affiliate_settings['enabled']),
'currency_name' => $currency_name,
'credit_balance' => (float) ($dashboard['credit_balance'] ?? 0.0),
'credits_enabled' => $show_credit_tabs,
'balance_enabled' => $balance_enabled,
'wallet_balance' => $wallet_balance,
'vip_settings' => $vip_settings,
'show_invite_section' => $show_credit_tabs
&& class_exists('AKSRT_Settings')
&& AKSRT_Settings::invite_enabled()
&& AKSRT_Settings::invite_registration_enabled(),
'user_email' => (string) $current_user->user_email,
'runtime_config' => aksrt_user_center_runtime_config($user_id, $tabs['default'], $active_tab, $tabs['urls']),
'cover_upload_config' => aksrt_user_center_cover_upload_config($allow_bg_upload),
];
return aksrt_build_user_center_render_context($render_context);
}
}