| Server IP : 43.141.50.122 / Your IP : 113.219.202.44 Web Server : Apache System : Linux VM-8-5-opencloudos 6.6.34-9.oc9.x86_64 #1 SMP PREEMPT_DYNAMIC Wed Jun 19 19:35:45 CST 2024 x86_64 User : www ( 1000) PHP Version : 8.1.27 Disable Function : passthru,exec,system,putenv,chroot,chgrp,chown,shell_exec,popen,proc_open,pcntl_exec,ini_alter,ini_restore,dl,openlog,syslog,readlink,symlink,popepassthru,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,imap_open,apache_setenv MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /www/wwwroot/www.ucppt.com/wp-content/plugins/wpcom-member-pro/includes/ |
Upload File : |
<?php
namespace WPCOM\Member;
use WPCOM\Themer\Session;
defined('ABSPATH') || exit;
class Affiliate{
protected static $_logs_table = 'wpcom_aff_logs';
protected static $_payouts_table = 'wpcom_payouts';
function __construct() {
add_action('admin_menu', array($this, 'admin_menu'));
add_action('show_user_profile', array($this, 'edit_user_aff' ) );
add_action('edit_user_profile', array($this, 'edit_user_aff' ) );
add_action('personal_options_update', array($this, 'save_user_aff' ) );
add_action('edit_user_profile_update', array($this, 'save_user_aff' ) );
add_action('template_redirect', array($this, 'set_aff_cookie'));
add_action('user_register', array( $this, 'set_user_aff' ) );
add_action('wpcom_after_insert_order', array( $this, 'set_order_aff' ), 20 ,2);
add_action('wpcom_order_payment_complete', array($this, 'check_order_aff'));
add_action('wpcom_themer_maybe_updated', function(){ self::init_database(); });
add_action('wp_ajax_wpcom_payout_modal', array($this, 'payout_modal'));
add_action('wp_ajax_nopriv_wpcom_payout_modal', array($this, 'payout_modal'));
add_action('wp_ajax_wpcom_payout_form', array($this, 'payout_form'));
add_action('wp_ajax_nopriv_wpcom_payout_form', array($this, 'payout_form'));
add_action('wpcom_order_status_changed', array($this, 'order_status_changed'), 10, 3);
add_action('wpcom_order_deleted', array($this, 'order_deleted'), 10, 2);
add_action('wpcom_payout_status_changed', array($this, 'payout_status_changed'), 10, 3);
add_filter('send_auth_cookies', array($this, 'remove_aff_cookie'), 999999 );
add_filter('wpcom_is_login', array($this, 'set_aff_cookie_by_ajax'), 5);
add_filter('wpcom_account_tabs', array($this, 'account_tab'), 20 );
}
function admin_menu(){
$payout_logs = $this->get_payout_logs(['status' => '0']);
$menu_title = '推广佣金';
if($payout_logs && is_array($payout_logs) && !empty($payout_logs)) $menu_title .= '<span class="awaiting-mod">'.count($payout_logs).'</span>';
add_submenu_page('wpcom-member-pro', '推广佣金', $menu_title, 'manage_options', 'wpcom-affiliate-logs', array(&$this, 'affiliate_list'));
}
function account_tab($tabs){
$tabs[30] = array(
'slug' => 'affiliate',
'title' => __('推广佣金', WPCMP_TD),
'shadow' => 1,
'icon' => 'income'
);
add_action('wpcom_account_tabs_affiliate', array($this, 'account_tabs_affiliate'));
return $tabs;
}
function account_tabs_affiliate(){
global $wpcom_member;
$user = wp_get_current_user();
$options = $GLOBALS['wpmx_options'];
$aff_arg_name = $options && isset($options['aff_arg_name']) && trim($options['aff_arg_name']) ? trim($options['aff_arg_name']) : 'aff';
$paged = get_query_var('pageid') ? get_query_var('pageid') : 1;
$tab = isset($_GET['tab']) && $_GET['tab'] ? $_GET['tab'] : 'aff-logs';
$per_page = 20;
$pages = 1;
if($tab === 'aff-logs' || $tab === 'payout-logs' ){
$logs = $tab === 'aff-logs' ? $this->get_aff_logs(['ref_id' => $user->ID, 'per_page' => -1]) : $this->get_payout_logs(['user_id' => $user->ID, 'per_page' => -1]);
if($logs && is_array($logs)) $pages = ceil(count($logs) / $per_page);
}
$args = [
'current' => $tab,
'user_id' => $user->ID,
'aff_arg_name' => $aff_arg_name,
'incomes' => $this->get_aff_incomes($user->ID),
'payouts' => $this->get_aff_payouts($user->ID),
'can_payouts' => $this->get_aff_can_payouts($user->ID),
'pedding_payouts' => $this->get_aff_cannot_payouts($user->ID),
'aff_logs' => $tab === 'aff-logs' ? $this->get_aff_logs(['ref_id' => $user->ID, 'per_page' => $per_page, 'paged' => $paged]) : [],
'payout_logs' => $tab === 'payout-logs' ? $this->get_payout_logs(['user_id' => $user->ID, 'per_page' => $per_page, 'paged' => $paged]) : [],
'rules' => isset($options['aff_rules']) && trim($options['aff_rules']) !== '' ? $options['aff_rules'] : '',
'aff_rate' => self::get_rate($user->ID),
'paged' => $paged,
'pages' => $pages
];
echo $wpcom_member->load_template('affiliate', $args);
}
function payout_modal(){
global $wpcom_member, $wpmx_options;
$res = array('result' => 0);
$user_id = get_current_user_id();
if($user_id){
$last_log = $this->get_payout_logs(['user_id' => $user_id, 'per_page' => 1, 'status' => 2, 'orderby' => 'ID', 'order' => 'DESC']);
$args = array(
'can_payouts' => $this->get_aff_can_payouts($user_id),
'payout_type' => $wpmx_options && isset($wpmx_options['payout_type']) && $wpmx_options['payout_type'] !== '' ? $wpmx_options['payout_type'] : 0,
'payout_alipay_type' => $wpmx_options && isset($wpmx_options['payout_alipay_type']) && $wpmx_options['payout_alipay_type'] !== '' ? $wpmx_options['payout_alipay_type'] : 0,
'payout_realname' => $wpmx_options && isset($wpmx_options['payout_realname']) && $wpmx_options['payout_realname'] == '1',
'last_log' => $last_log && isset($last_log[0]) ? json_decode($last_log[0]->data, true) : ''
);
$res['tpl'] = $wpcom_member->load_template('payout-modal', $args);
}else{
$res['result'] = -1;
}
wp_send_json($res);
}
function payout_form(){
global $wpmx_options;
$res = array('result' => 0);
$nonce = isset($_POST['payout_form_nonce']) ? sanitize_text_field($_POST['payout_form_nonce']) : '';
$check = $nonce && wp_verify_nonce($nonce, 'payout_form');
$user_id = get_current_user_id();
$user = wp_get_current_user();
if($check && $user_id){
$payouts = isset($_POST['payouts']) ? (float)sanitize_text_field($_POST['payouts']) : 0;
$realname = $wpmx_options && isset($wpmx_options['payout_realname']) && $wpmx_options['payout_realname'] == '1';
$payout_type = $wpmx_options && isset($wpmx_options['payout_type']) && $wpmx_options['payout_type'] !== '' ? $wpmx_options['payout_type'] : 0;
$can_payouts = $this->get_aff_can_payouts($user_id);
$min = $this->get_min_payouts($user_id);
if($payouts != $can_payouts){
$res['result'] = -2;
$res['msg'] = '提现金额与未提现余额不匹配,建议刷新页面后重试';
}else if($can_payouts <= 0 || $can_payouts < $min){
$res['result'] = -3;
$res['msg'] = '当前提现金额低于最低提现限制';
}else{
$data = [];
$name = isset($_POST['name']) ? trim(sanitize_text_field($_POST['name'])) : '';
$data['payout_type'] = $payout_type;
$data['name'] = $name;
if(!($name && preg_match('/^[^0-9a-zA-Z-_]{2,}$/', $name) && mb_strlen($name) > 1)){
$res['result'] = -9;
$res['msg'] = '收款人姓名填写错误';
}
if($res['result'] == 0 && $realname){
$idcard_num = isset($_POST['idcard_num']) ? trim(sanitize_text_field($_POST['idcard_num'])) : '';
$idcard_z = isset($_POST['idcard_z']) ? sanitize_text_field($_POST['idcard_z']) : '';
$idcard_f = isset($_POST['idcard_f']) ? sanitize_text_field($_POST['idcard_f']) : '';
$data['idcard_num'] = $idcard_num;
$data['idcard_z'] = $idcard_z;
$data['idcard_f'] = $idcard_f;
if(!($idcard_num && preg_match('/^([1-9]\d{5})(\d{4})(\d{2})(\d{2})(\d{3})(\d|X)$/i', $idcard_num))){
$res['result'] = -9;
$res['msg'] = '身份证号输入错误';
}else if(!($idcard_z && preg_match('/^data:image\//i', $idcard_z)) || !($idcard_f && preg_match('/^data:image\//i', $idcard_f))){
$res['result'] = -9;
$res['msg'] = '身份证照片错误,请重新上传';
}
}
if($res['result'] == 0){
if($payout_type == 1){
$payout_qrcode = isset($_POST['qrcode']) ? sanitize_text_field($_POST['qrcode']) : '';
$data['qrcode'] = $payout_qrcode;
if(!($payout_qrcode && preg_match('/^data:image\//i', $payout_qrcode))){
$res['result'] = -9;
$res['msg'] = '收款码图片错误,请重新上传';
}
}else if($payout_type == 2){
$bank_name = isset($_POST['bank_name']) ? trim(sanitize_text_field($_POST['bank_name'])) : '';
$bank_number = isset($_POST['bank_number']) ? trim(sanitize_text_field($_POST['bank_number'])) : '';
$data['bank_name'] = $bank_name;
$data['bank_number'] = $bank_number;
if(!($bank_name && preg_match('/^[^0-9a-zA-Z-_]{4,}/', $bank_name) && mb_strlen($bank_name) > 3)){
$res['result'] = -9;
$res['msg'] = '收款开户银行输入错误';
}else if(!($bank_number && preg_match('/[1-9][\d]{11,18}/', $bank_number))){
$res['result'] = -9;
$res['msg'] = '收款银行账号输入错误';
}
}else{
$payout_alipay_type = $wpmx_options && isset($wpmx_options['payout_alipay_type']) ? $wpmx_options['payout_alipay_type'] : 0;
if($payout_alipay_type){
$payout_qrcode = isset($_POST['qrcode']) ? sanitize_text_field($_POST['qrcode']) : '';
$data['qrcode'] = $payout_qrcode;
if(!($payout_qrcode && preg_match('/^data:image\//i', $payout_qrcode))){
$res['result'] = -9;
$res['msg'] = '收款码图片错误,请重新上传';
}
}else{
$alipay = isset($_POST['alipay']) ? trim(sanitize_text_field($_POST['alipay'])) : '';
$data['alipay'] = $alipay;
if(!($alipay && (preg_match('/^1[\d]{10}$/i', $alipay) || is_email($alipay)))){
$res['result'] = -9;
$res['msg'] = '支付宝账号输入错误';
}
}
}
}
// 验证通过
if($res['result'] == 0){
$log = [
'user_id' => $user_id,
'total' => $can_payouts,
'data' => wp_json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
];
if($this->add_payout_log($log)){
// 发送通知给管理员
$admin_email = get_option('admin_email');
if ( is_multisite() ) {
$site_name = get_network()->site_name;
} else {
$site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
}
$title = sprintf( __( '【%s】收到用户佣金提现申请', WPCMP_TD ), $site_name );
$headers = array('Content-Type: text/html; charset=UTF-8');
$message = '<p>收到新的用户推广佣金提现申请,以下是申请信息:</p>';
$message .= '<p>申请用户:' . $user->display_name . '</p>';
$message .= '<p>提现金额:' . number_format($can_payouts, 2, '.', '') . ' 元</p>';
@wp_mail($admin_email, wp_specialchars_decode( $title ), $message, $headers);
}else{
$res['result'] == -4;
$res['msg'] = '提交失败,请稍候再试!';
}
}
}
}else{
$res['result'] = -1;
}
wp_send_json($res);
}
function affiliate_list(){
$tab = isset($_REQUEST['tab']) && $_REQUEST['tab'] ? $_REQUEST['tab'] : 'logs';
$payout_logs = $this->get_payout_logs(['status' => '0']);
?>
<div class="wrap">
<h1 class="wp-heading-inline">推广佣金</h1>
<nav class="nav-tab-wrapper">
<a href="<?php echo esc_url(add_query_arg('tab', 'logs'));?>" class="nav-tab<?php echo $tab === 'logs' ? ' nav-tab-active' : '';?>">
佣金记录
</a>
<a href="<?php echo esc_url(add_query_arg('tab', 'payouts'));?>" class="nav-tab<?php echo $tab === 'payouts' ? ' nav-tab-active' : '';?>">
提现记录
<?php if($payout_logs && is_array($payout_logs) && !empty($payout_logs)) echo '<span class="awaiting-num">'.count($payout_logs).'</span>';?>
</a>
</nav>
<?php if($tab === 'logs'){?>
<h2>佣金记录</h2>
<form method="post">
<?php
if (!class_exists('Affiliate_List')) require_once WPCOM_MP_DIR . '/includes/affiliate-list.php';
$list = new Affiliate_List();
$list->prepare_items();
$list->display();
?>
</form>
<?php } else if($tab === 'payouts'){
wp_enqueue_script( 'jquery-ui-dialog' );
wp_enqueue_style( 'wp-jquery-ui-dialog' );
if (!class_exists('Payouts_List')) require_once WPCOM_MP_DIR . '/includes/payouts-list.php';
$list = new Payouts_List();
$list->prepare_items(); ?>
<h2>提现记录</h2>
<?php $list->views();?>
<form method="post">
<?php $list->display(); ?>
</form>
<div id="payouts-image-view"></div>
<script>
jQuery(function($){
jQuery('#payouts-image-view').dialog({
title: '图片预览',
dialogClass: 'wp-dialog',
autoOpen: false,
width: '680',
modal: true,
focus: false,
position: {
my: "center top",
at: "center top+60",
of: window
}
});
jQuery(document).on('click', '.payout-data-item a', function(){
var $el = jQuery(this);
if($el.data('src')){
$('#payouts-image-view').html('<img style="max-width:100%;height:auto;display:block;margin:0 auto;" src="'+$el.data('src')+'">');
$('#payouts-image-view').dialog('open');
return false;
}
}).on('click', '.j-payout-reject', function(){
var content = prompt('可输入拒绝理由,可留空');
if(content === null) return false;
var $el = $(this);
window.location.href = $el.attr('href') + '&prompt='+content;
return false;
});
});
</script>
<?php } ?>
</div>
<?php }
function order_status_changed($new_status, $old_status, $order_id){
global $wpdb;
if($old_status === 'paid' && $new_status !== 'paid'){
$order = Order::get_order($order_id);
if($order && isset($order->status) && $order->status !== 'paid'){
$log = self::get_aff_logs(['order_id' => $order_id]);
// 订单变更为未支付,删除推广记录
if($log && !empty($log) && isset($log[0])&& isset($log[0]->ID)){
$table = $wpdb->prefix . self::$_logs_table;
$wpdb->delete($table, array('ID' => $log[0]->ID));
}
}
}
}
function order_deleted($order_id, $order){
global $wpdb;
if($order_id && $order && isset($order->status) && $order->status === 'paid'){
$log = self::get_aff_logs(['order_id' => $order_id]);
// 订单删除,同步删除推广记录
if($log && !empty($log) && isset($log[0])&& isset($log[0]->ID)){
$table = $wpdb->prefix . self::$_logs_table;
$wpdb->delete($table, array('ID' => $log[0]->ID));
}
}
}
function payout_status_changed($new_status, $old_status, $payout){
if($new_status != $old_status && $new_status != '0' && $payout->user_id){
// 发送通知给用户
$user = get_user_by( 'ID', $payout->user_id );
if(wpcom_is_empty_mail($user->user_email)) return false;
if ( is_multisite() ) {
$site_name = get_network()->site_name;
} else {
$site_name = wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES );
}
$_title = '推广佣金提现处理进度通知';
$title = '【'.$site_name.'】' . $_title;
$headers = array('Content-Type: text/html; charset=UTF-8');
$message = '<p>' . sprintf( __( 'Hi, %s!', WPCMP_TD ), $user->display_name ) . '</p>';
$message .= '<p>您的推广佣金提现申请有新处理进度更新:</p>';
$message .= '<p>提现金额:' . number_format($payout->total, 2, '.', '') . ' 元</p>';
$message .= '<p>处理状态:' . $this->get_payout_status($new_status) . '</p>';
if($new_status == '-1' && $payout->note && trim($payout->note) !== ''){
$message .= '<p>未通过原因:' . $payout->note . '</p>';
}
@wp_mail($user->user_email, wp_specialchars_decode( $title ), $message, $headers);
do_action('wpcom_add_notification', $payout->user_id, $_title, $message);
}
}
function check_order_aff($order){
if($order && $order->ID && $order->status === 'paid' && $order->payment_gateway !== 'points'){ // 积分订单无佣金
$aff_type = self::get_aff_type(); // 0:按订单,1:按用户
if($aff_type == 1){
$aff_from = (int)Session::get('_aff_from_by_user_'.$order->user);
}else if($aff_type == 0){
$aff_from = (int)Session::get('_aff_from_by_order_'.$order->ID);
}
$rate = isset($aff_from) && $aff_from ? self::get_rate($aff_from) : 0; // 佣金比例
if($aff_type == 1 && $order->user && $rate && $rate > 0 && $rate < 1){ // 推荐用户
// 检查用户是否已有订单
$orders = Order::get_orders(array('user' => $order->user, 'status' => 'paid', 'per_page' => 2));
// 有且仅有当前这一个订单
if($orders && is_array($orders) && count($orders) === 1 && isset($orders[0]->ID) && $orders[0]->ID === $order->ID){
$income = $order->price * $rate;
if(is_numeric($income) && $income > 0){
$log = [
'ref_id' => $aff_from,
'user_id' => $order->user,
'order_id' => $order->ID,
'income' => number_format($income, 2, '.', '')
];
self::add_aff_log($log);
}
}
}else if($aff_type == 0 && $rate && $rate > 0 && $rate < 1){ // 推荐订单
$income = $order->price * $rate;
if(is_numeric($income) && $income > 0){
// 不能自己推荐自己
if($order->user && $order->user == $aff_from) return false;
$log = [
'ref_id' => $aff_from,
'user_id' => $order->user,
'order_id' => $order->ID,
'income' => number_format($income, 2, '.', '')
];
self::add_aff_log($log);
@setcookie('_aff_from', '', time(), COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true); // 删除原有cookie
}
}
}
}
public static function add_aff_log($log){
global $wpdb;
if($log && isset($log['ref_id']) && $log['ref_id'] && isset($log['order_id']) && $log['order_id'] && isset($log['income']) && $log['income']){
// 避免重复插入,检查订单号是否已有推荐记录
$logs = self::get_aff_logs(['order_id' => $log['order_id']]);
if(is_array($logs) && count($logs) > 0){
return new \WP_Error('aff_log_exists', '当前订单已经有推荐记录');
}else{
$table = $wpdb->prefix . self::$_logs_table;
$data = [
'ref_id' => $log['ref_id'],
'user_id' => isset($log['user_id']) ? $log['user_id'] : 0,
'order_id' => $log['order_id'],
'income' => $log['income'],
'time' => current_time('mysql')
];
$format = ['%d', '%d', '%d', '%f', '%s'];
return $wpdb->insert($table, $data, $format);
}
}
}
public static function get_aff_logs($args){
global $wpdb;
$table = $wpdb->prefix . self::$_logs_table;
$where = '';
if($args && isset($args['ref_id'])) $where .= ($where ? ' AND' : ' WHERE') . $wpdb->prepare(" `ref_id` = %s", $args['ref_id']);
if($args && isset($args['user_id'])) $where .= ($where ? ' AND' : ' WHERE') . $wpdb->prepare(" `user_id` = %s", $args['user_id']);
if($args && isset($args['order_id'])) $where .= ($where ? ' AND' : ' WHERE') . $wpdb->prepare(" `order_id` = %s", $args['order_id']);
$per_page = $args && isset($args['per_page']) ? (int)$args['per_page'] : 0;
$limit = '';
if($per_page && $per_page > 0){
$paged = $args && isset($args['paged']) ? $args['paged'] : 1;
$offset = ($paged-1) * $per_page;
$limit = $wpdb->prepare(" LIMIT %d, %d", $offset, $per_page);
}
$_orderby = $args && isset($args['orderby']) ? esc_sql($args['orderby']) : 'ID';
$orderby = '';
if($_orderby !== ''){
$order = $args && isset($args['order']) ? esc_sql($args['order']) : ' DESC';
$orderby = " ORDER BY $_orderby $order";
}
$logs = $wpdb->get_results("SELECT * FROM $table $where $orderby $limit");
if($logs && !is_wp_error($logs)) return $logs;
}
public static function add_payout_log($log){
global $wpdb;
if($log && isset($log['user_id']) && $log['user_id'] && isset($log['total']) && $log['total'] && isset($log['data']) && $log['data']){
$table = $wpdb->prefix . self::$_payouts_table;
$data = [
'user_id' => $log['user_id'],
'total' => $log['total'],
'time' => isset($log['time']) ? $log['time'] : current_time('mysql'),
'data' => $log['data'],
'status' => isset($log['status']) ? $log['status'] : '0'
];
$format = ['%d', '%f', '%s', '%s', '%s'];
return $wpdb->insert($table, $data, $format);
}
}
public static function get_payout_logs($args){
global $wpdb;
$table = $wpdb->prefix . self::$_payouts_table;
$where = '';
if($args && isset($args['user_id'])) $where .= ($where ? ' AND' : ' WHERE') . $wpdb->prepare(" `user_id` = %s", $args['user_id']);
if($args && isset($args['status'])) $where .= ($where ? ' AND' : ' WHERE') . $wpdb->prepare(" `status` = %s", $args['status']);
$per_page = $args && isset($args['per_page']) ? (int)$args['per_page'] : 0;
$limit = '';
if($per_page && $per_page > 0){
$paged = $args && isset($args['paged']) ? $args['paged'] : 1;
$offset = ($paged-1) * $per_page;
$limit = $wpdb->prepare(" LIMIT %d, %d", $offset, $per_page);
}
$_orderby = $args && isset($args['orderby']) ? esc_sql($args['orderby']) : 'ID';
$orderby = '';
if($_orderby !== ''){
$order = $args && isset($args['order']) ? esc_sql($args['order']) : ' DESC';
$orderby = " ORDER BY $_orderby $order";
}
$logs = $wpdb->get_results("SELECT * FROM $table" . $where . $orderby . $limit);
if($logs && !is_wp_error($logs)) return $logs;
}
function set_user_aff($user_id){
$aff_from = isset($_COOKIE['_aff_from']) ? sanitize_text_field($_COOKIE['_aff_from']) : '';
if($user_id && $aff_from){
$aff_type = self::get_aff_type(); // 0:按订单,1:按用户
if($aff_type == 1 && $user = get_user_by('id', $aff_from)){ // 按用户返佣则需要记录注册时的推荐用户
if($user && isset($user->ID) && $user->ID){
update_user_meta($user_id, 'aff_user', $user->ID); // 保存推荐人信息
Session::set('_aff_from_by_user_'.$user_id, $user->ID, 30*24*60*60); // 由cookie保存改为session保存,30天有效期
@setcookie('_aff_from', '', time(), COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true); // 删除原有cookie
}
}
}
}
function set_order_aff($order_id, $inserted){
if($order_id && $inserted){
$aff_from = isset($_COOKIE['_aff_from']) ? sanitize_text_field($_COOKIE['_aff_from']) : '';
if($aff_from && self::get_aff_type() == 0){ // 按订单,则基于订单保存session
Session::set('_aff_from_by_order_' . $order_id, $aff_from);
}
}
}
function set_aff_cookie(){
$options = $GLOBALS['wpmx_options'];
$aff_arg_name = $options && isset($options['aff_arg_name']) && trim($options['aff_arg_name']) ? trim($options['aff_arg_name']) : 'aff';
if($aff_arg_name && isset($_GET[$aff_arg_name]) && $ref = sanitize_text_field($_GET[$aff_arg_name])){
$aff_type = self::get_aff_type(); // 0:按订单,1:按用户
$user_id = get_current_user_id();
if($ref != $user_id && ($aff_type == 0 || $user_id == 0)){
$user = get_user_by('id', $ref);
if($user && isset($user->ID) && $user->ID){
@setcookie('_aff_from', $ref, time()+30*24*60*60, COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
}
}
}
}
// 通过ajax的方式可以避免页面缓存导致添加cookie失败的问题
function set_aff_cookie_by_ajax($res){
$referer = isset( $_SERVER['HTTP_REFERER'] ) && $_SERVER['HTTP_REFERER'] ? sanitize_text_field($_SERVER['HTTP_REFERER']) : '';
if($referer && $parse_url = parse_url($referer)){
if(isset($parse_url['query']) && $parse_url['query']){
$options = $GLOBALS['wpmx_options'];
$aff_arg_name = $options && isset($options['aff_arg_name']) && trim($options['aff_arg_name']) ? trim($options['aff_arg_name']) : 'aff';
parse_str($parse_url['query'], $query);
if($query && isset($query[$aff_arg_name])){
$_GET[$aff_arg_name] = $query[$aff_arg_name];
$this->set_aff_cookie();
}
}
}
return $res;
}
function remove_aff_cookie($send){
if($send && isset($_COOKIE['_aff_from']) && self::get_aff_type() == 1){ // 按用户推荐的方式用户登录登出操作需要移除推荐cookie
@setcookie('_aff_from', '', time(), COOKIEPATH, COOKIE_DOMAIN, is_ssl(), true);
}
return $send;
}
public static function get_aff_type(){
$options = $GLOBALS['wpmx_options'];
return isset($options['aff_type']) && $options['aff_type'] == '1' ? 1 : 0; // 0:按订单,1:按用户
}
public static function get_rate($user_id){
$options = $GLOBALS['wpmx_options'];
$rate = 0;
if(isset($options['aff']) && $options['aff'] == '1'){
$rate = $options['aff_rate'] && trim($options['aff_rate']) !== '' ? (float)$options['aff_rate'] : 0;
$aff_rate = get_user_meta($user_id, '_wpcom_aff_rate', true);
$aff_rate = trim($aff_rate) === '' ? '' : (float)$aff_rate;
if($aff_rate || $aff_rate === 0){
$rate = $aff_rate;
}else if($vip = VIP::get_user_vip($user_id)){
if(isset($vip['aff_rate']) && $vip['aff_rate'] || $vip['aff_rate'] === 0){
$rate = $vip['aff_rate'];
}
}
$rate = is_numeric($rate) && $rate > 0 ? $rate / 100 : 0;
}
return apply_filters('wpcom_affiliate_rate', $rate, $user_id);
}
function edit_user_aff($user){
$options = $GLOBALS['wpmx_options'];
if (!current_user_can('edit_user')) return;
if(isset($options['aff']) && $options['aff'] == '1'){
$aff_rate = get_user_meta($user->ID, '_wpcom_aff_rate', true);
$incomes = $this->get_aff_incomes($user->ID);
$payouts = $this->get_aff_payouts($user->ID); ?>
<h3>推广佣金</h3>
<table class="form-table">
<tr>
<th><label for="vip_type">佣金比例</label></th>
<td>
<input type="number" name="user_aff_rate" class="regular-text" value="<?php echo $aff_rate !== '' ? $aff_rate : '';?>">
<p class="description">可选,针对当前用户的佣金比例,<b>单位:%,无需带单位</b>,留空则按默认佣金比例;<br>默认佣金比例在<b>用户中心-高级功能-佣金比例</b>选项设置</p>
</td>
</tr>
<tr>
<th><label for="vip_type">佣金收入</label></th>
<td>
<p><b><?php echo number_format($incomes, 2, '.', '');?></b> 元</p>
<p class="description">历史累计佣金收入</p>
</td>
</tr>
<tr>
<th><label for="vip_type">已提现佣金</label></th>
<td>
<p><b><?php echo number_format($payouts, 2, '.', '');?></b> 元</p>
<p class="description">已经提现并完成处理的佣金收入</p>
</td>
</tr>
</table>
<?php }
}
public static function get_aff_incomes($user_id = ''){
global $wpdb;
$user_id = $user_id ?: get_current_user_id();
$incomes = 0;
if($user_id){
$logs_table = $wpdb->prefix . self::$_logs_table;
$incomes = $wpdb->get_var( $wpdb->prepare("SELECT SUM(income) FROM $logs_table WHERE ref_id = %s", $user_id) );
}
return (float)$incomes;
}
public static function get_aff_payouts($user_id = '', $status = '2'){
global $wpdb;
$user_id = $user_id ?: get_current_user_id();
$total = 0;
if($user_id){
$payouts_table = $wpdb->prefix . self::$_payouts_table;
if (is_array($status)) {
$placeholders = implode(',', array_fill(0, count($status), '%s'));
$status_sql = $wpdb->prepare("status IN ($placeholders)", $status);
} else {
$status_sql = $wpdb->prepare('status = %s', $status);
}
$total = $wpdb->get_var( $wpdb->prepare("SELECT SUM(total) FROM $payouts_table WHERE user_id = %s AND $status_sql", $user_id) );
}
return (float)$total;
}
function get_aff_can_payouts($user_id = ''){
$user_id = $user_id ?: get_current_user_id();
$can_payouts = 0;
if($user_id){
$total = $this->get_aff_incomes($user_id); // 累计收益
$payouts = $this->get_aff_payouts($user_id, ['0', '1', '2']); // 已提现收益,包含审核中
$pay = $total - $payouts; // 理论可提现余额
// 检查扣除结算期余额
$pedding = $this->get_aff_cannot_payouts($user_id);
if($pedding) $pay -= $pedding;
$can_payouts = $pay;
}
return (float)$can_payouts;
}
function get_aff_cannot_payouts($user_id = ''){
global $wpdb;
$options = $GLOBALS['wpmx_options'];
$incomes = 0;
if(isset($options['payout_pedding']) && $options['payout_pedding'] > 0){
$user_id = $user_id ?: get_current_user_id();
$days = (int)$options['payout_pedding'];
if($days > 0 && $user_id){
$logs_table = $wpdb->prefix . self::$_logs_table;
$incomes = $wpdb->get_var( $wpdb->prepare("SELECT SUM(income) FROM $logs_table WHERE ref_id = %s AND time >= DATE_SUB(NOW(), INTERVAL %d DAY)", $user_id, $days) );
}
}
return (float)$incomes;
}
function get_min_payouts($user_id = ''){
$options = $GLOBALS['wpmx_options'];
$user_id = $user_id ?: get_current_user_id();
$min = 0;
if($user_id){
$payout_limit = isset($options['payout_limit']) ? $options['payout_limit'] : 0;
$payout_limit_min = isset($options['payout_limit_min']) ? (float)$options['payout_limit_min'] : 0;
if($payout_limit == 1){ // 首次限制
// 检查是否有成功处理的提现记录
$logs = self::get_payout_logs(['user_id' => $user_id, 'status' => '2']);
if($logs && !empty($logs) && isset($logs[0])){ // 有记录,则无门槛
$min = 0;
}else{ // 无记录,有最低门槛
$min = $payout_limit_min;
}
}else if($payout_limit == 2){ // 每次限制
$min = $payout_limit_min;
}
}
return (float)$min;
}
function save_user_aff($user_id){
if (!current_user_can('edit_user', $user_id)) return false;
if (isset($_POST['user_aff_rate'])) {
$aff_rate = trim($_POST['user_aff_rate']) === '' ? '' : (float)sanitize_text_field(trim($_POST['user_aff_rate']));
if(is_numeric($aff_rate) || $aff_rate === ''){
update_user_meta($user_id, '_wpcom_aff_rate', $aff_rate);
}
}
}
public static function get_payout_status($status){
$statuses = ['0' => '等待审核', '1' => '审核通过', '2' => '提现成功', '-1' => '审核未通过'];
if($status !== '' && isset($statuses[$status])) {
return $statuses[$status];
}else{
return $status;
}
}
private static function init_database() {
global $wpdb;
$logs_table = $wpdb->prefix . self::$_logs_table;
$payouts_table = $wpdb->prefix . self::$_payouts_table;
if ($wpdb->get_var("SHOW TABLES LIKE '$logs_table'") != $logs_table) {
$charset_collate = $wpdb->get_charset_collate();
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$create_log_table_sql = "CREATE TABLE $logs_table (" .
"ID BIGINT(20) NOT NULL auto_increment," .
"ref_id BIGINT(20) NOT NULL," . // 推荐人
"user_id BIGINT(20) NOT NULL," . // 被推荐人
"order_id BIGINT(20) NOT NULL," . // 推荐订单
"income decimal(10,2) NOT NULL," . // 推荐佣金
"time datetime NOT NULL," . // 推荐时间
"PRIMARY KEY (ID)) $charset_collate;";
dbDelta($create_log_table_sql);
}
if ($wpdb->get_var("SHOW TABLES LIKE '$payouts_table'") != $payouts_table) {
$charset_collate = $wpdb->get_charset_collate();
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
$create_log_table_sql = "CREATE TABLE $payouts_table (" .
"ID BIGINT(20) NOT NULL auto_increment," .
"user_id BIGINT(20) NOT NULL," . // 提现用户
"total decimal(10,2) NOT NULL," . // 提现金额
"time datetime NOT NULL," . // 提现时间
"data longtext NOT NULL," . // 提现信息,比如提现收款信息
"status varchar(20) NOT NULL," . // 提现状态: 0 => 刚提交 1 => 审核通过待处理 2 => 已完成提现 -1 => 审核未通过
"note longtext," . // 备注说明,比如审核未通过原因
"PRIMARY KEY (ID)) $charset_collate;";
dbDelta($create_log_table_sql);
}
}
}
new Affiliate();