Example #1
0
function xfac_edit_user_profile_update($wpUserId)
{
    $config = xfac_option_getConfig();
    if (empty($config)) {
        return;
    }
    if (!empty($_POST['xfac_disconnect'])) {
        foreach ($_POST['xfac_disconnect'] as $recordId => $confirmed) {
            if ($confirmed) {
                $record = xfac_user_getRecordById($recordId);
                if ($record->user_id == $wpUserId) {
                    xfac_user_deleteRecord($record);
                }
            }
        }
    }
    if (!empty($_POST['xfac_connect'])) {
        $xfUserId = intval($_POST['xfac_connect']);
        if ($xfUserId > 0) {
            $adminAccessToken = xfac_user_getAdminAccessToken($config);
            if (!empty($adminAccessToken)) {
                $userAccessToken = xfac_api_postOauthTokenAdmin($config, $adminAccessToken, $xfUserId);
                if (!empty($userAccessToken)) {
                    $result = xfac_api_getUsersMe($config, $userAccessToken['access_token']);
                    if (!empty($result['user']['user_id'])) {
                        xfac_syncLogin_syncRole($config, get_user_by('id', $wpUserId), $result['user']);
                        if (isset($_POST['role'])) {
                            // because we have already sync'd role, ignore role submitted via POST
                            unset($_POST['role']);
                        }
                        xfac_user_updateRecord($wpUserId, $config['root'], $xfUserId, $result['user'], $userAccessToken);
                    }
                }
            }
        }
    }
}
Example #2
0
function xfac_set_user_role($wpUserId, $newRole, $oldRoles)
{
    if (!empty($GLOBALS['XFAC_SKIP_xfac_set_user_role'])) {
        return;
    }
    $config = xfac_option_getConfig();
    $accessToken = xfac_user_getAccessToken($wpUserId);
    if (empty($accessToken)) {
        return;
    }
    $me = xfac_api_getUsersMe($config, $accessToken);
    if (empty($me['user'])) {
        return;
    }
    $xfUser = $me['user'];
    $wpUser = new WP_User($wpUserId);
    xfac_syncLogin_syncRole($config, $wpUser, $xfUser, false);
}
Example #3
0
function xfac_tools_connect()
{
    /** @var wpdb $wpdb */
    global $wpdb;
    $config = xfac_option_getConfig();
    if (empty($config)) {
        wp_die(__('XenForo API configuration is missing.', 'xenforo-api-consumer'));
    }
    $adminAccessToken = xfac_user_getAdminAccessToken($config);
    if (empty($adminAccessToken)) {
        wp_die(__('Admin Account\'s access token cannot be obtained.', 'xenforo-api-consumer'));
    }
    if (!xfac_api_hasModuleVersion($config, 'forum', 2015030901) || !xfac_api_hasModuleVersion($config, 'oauth2', 2015030902)) {
        wp_die(__('Please update XenForo API to run this tool.', 'xenforo-api-consumer'));
    }
    $optionFilters = array('position' => array('filter' => FILTER_VALIDATE_INT, 'default' => 0), 'limit' => array('filter' => FILTER_VALIDATE_INT, 'default' => 10), 'associate' => array('filter' => FILTER_VALIDATE_INT, 'default' => 0), 'push' => array('filter' => FILTER_VALIDATE_INT, 'default' => 0));
    $options = array();
    foreach ($optionFilters as $optionKey => $optionFilter) {
        $optionValue = filter_input(INPUT_GET, $optionKey, $optionFilter['filter']);
        if (!empty($optionValue)) {
            $options[$optionKey] = $optionValue;
        } else {
            $options[$optionKey] = $optionFilter['default'];
        }
    }
    if (empty($options['associate']) && empty($options['push'])) {
        wp_die(__('At least one action must be selected: either associate or push', 'xenforo-api-consumer'));
    }
    $maxWpUserIds = $wpdb->get_var('SELECT MAX(ID) FROM ' . $wpdb->prefix . 'users');
    if ($options['position'] >= $maxWpUserIds) {
        die(__('Done.', 'xenforo-api-consumer'));
    }
    $dbUsers = $wpdb->get_results('
        SELECT *
        FROM ' . $wpdb->prefix . 'users
        WHERE ID > ' . $options['position'] . '
        LIMIT ' . $options['limit']);
    foreach ($dbUsers as $dbUser) {
        $user = new WP_User($dbUser);
        $options['position'] = max($options['position'], $user->ID);
        $records = xfac_user_getRecordsByUserId($user->ID);
        if (!empty($records)) {
            // this user has connected
            continue;
        }
        printf(__('Processing user #%d (%s)', 'xenforo-api-consumer'), $user->ID, $user->user_login);
        echo "<br />\n";
        $candidates = array();
        $userLoginUsers = xfac_api_getUsersFind($config, $user->user_login);
        if (!empty($userLoginUsers['users'])) {
            foreach ($userLoginUsers['users'] as $userLoginUser) {
                // similar logic with includes/dashboard/profile.php
                if (strlen($userLoginUser['username']) == strlen($user->user_login)) {
                    $candidates[$userLoginUser['user_id']] = $userLoginUser;
                }
            }
        }
        $emailUsers = xfac_api_getUsersFind($config, '', $user->user_email, $adminAccessToken);
        if (!empty($emailUsers['users'])) {
            foreach ($emailUsers['users'] as $emailUser) {
                $candidates[$emailUser['user_id']] = $emailUser;
            }
        }
        if (!empty($candidates) && !empty($options['associate'])) {
            foreach ($candidates as $candidate) {
                $userAccessToken = xfac_api_postOauthTokenAdmin($config, $adminAccessToken, $candidate['user_id']);
                if (!empty($userAccessToken)) {
                    xfac_syncLogin_syncRole($config, $user, $candidate, false);
                    xfac_user_updateRecord($user->ID, $config['root'], $candidate['user_id'], $candidate, $userAccessToken);
                    xfac_log('xfac_tools_connect associated $wpUser (#%d) vs. $xfUser (#%d)', $user->ID, $candidate['user_id']);
                } else {
                    $errors = xfac_api_getLastErrors();
                    if (!is_array($errors)) {
                        $errors = array(__('Unknown error', 'xenforo-api-consumer'));
                    }
                    xfac_log('xfac_tools_connect failed to associate $wpUser (#%d) vs. $xfUser (#%d): %s', $user->ID, $candidate['user_id'], implode(', ', $errors));
                }
            }
        }
        if (empty($candidates) && !empty($options['push'])) {
            $result = xfac_api_postUser($config, $user->user_email, $user->user_login, '', array('oauth_token' => $adminAccessToken));
            if (!empty($result)) {
                $xfUser = $result['user'];
                $token = $result['token'];
                xfac_syncLogin_syncRole($config, $user, $xfUser, false);
                xfac_user_updateRecord($user->ID, $config['root'], $xfUser['user_id'], $xfUser, $token);
                xfac_log('xfac_tools_connect pushed $wpUser (#%d)', $user->ID);
            } else {
                $errors = xfac_api_getLastErrors();
                if (!is_array($errors)) {
                    $errors = array(__('Unknown error', 'xenforo-api-consumer'));
                }
                xfac_log('xfac_tools_connect failed to push $wpUser (#%d): %s', $user->ID, implode(', ', $errors));
            }
        }
    }
    $optionsStr = '';
    foreach ($options as $optionKey => $optionValue) {
        if ($optionValue !== $optionFilters[$optionKey]['default']) {
            $optionsStr .= sprintf('&%s=%s', $optionKey, rawurlencode($optionValue));
        }
    }
    die(sprintf('<script>window.location = "%s";</script>', admin_url(sprintf('tools.php?action=xfac_tools_connect%s', $optionsStr))));
}
Example #4
0
function _xfac_subscription_handleCallback_user($config, $ping)
{
    $wpUserData = xfac_user_getUserDataByApiData($config['root'], $ping['object_data']);
    if (empty($wpUserData)) {
        return false;
    }
    $accessToken = xfac_user_getAccessToken($wpUserData->ID);
    if (empty($accessToken)) {
        return false;
    }
    $me = xfac_api_getUsersMe($config, $accessToken, false);
    if (empty($me)) {
        return false;
    }
    $xfUser = $me['user'];
    $wpUser = new WP_User($wpUserData);
    xfac_syncLogin_syncBasic($config, $wpUser, $xfUser);
    xfac_syncLogin_syncRole($config, $wpUser, $xfUser);
    if (xfac_user_updateRecord($wpUserData->ID, $config['root'], $xfUser['user_id'], $xfUser)) {
        return 'updated user record';
    } else {
        return false;
    }
}
Example #5
0
function xfac_login_init()
{
    if (empty($_REQUEST['xfac'])) {
        return;
    }
    $config = xfac_option_getConfig();
    if (empty($config)) {
        return;
    }
    $loginUrl = site_url('wp-login.php', 'login_post');
    $redirectTo = xfac_api_getRedirectTo();
    $redirectToRequested = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : '';
    $redirectBaseUrl = $loginUrl . (strpos($loginUrl, '?') !== false ? '&' : '?') . 'redirect_to=' . urlencode($redirectTo);
    $callbackUrl = $redirectBaseUrl . '&xfac=callback';
    $token = false;
    $associateConfirmed = false;
    switch ($_REQUEST['xfac']) {
        case 'callback':
            define('XFAC_SYNC_LOGIN_SKIP_REDIRECT', 1);
            if (!empty($_REQUEST['authorizeHash'])) {
                $callbackUrl .= '&authorizeHash=' . urlencode($_REQUEST['authorizeHash']);
                $associateConfirmed = _xfac_login_verifyAuthorizeHash($_REQUEST['authorizeHash']);
            }
            if (!empty($_REQUEST['code'])) {
                $token = xfac_api_getAccessTokenFromCode($config, $_REQUEST['code'], $callbackUrl);
            }
            break;
        case 'associate':
            define('XFAC_SYNC_LOGIN_SKIP_REDIRECT', 1);
            if (empty($_REQUEST['refresh_token'])) {
                wp_redirect($redirectBaseUrl . '&xfac_error=no_refresh_token');
                exit;
            }
            if (empty($_REQUEST['scope'])) {
                wp_redirect($redirectBaseUrl . '&xfac_error=no_scope');
                exit;
            }
            if (empty($_REQUEST['xf_user']) or !is_array($_REQUEST['xf_user'])) {
                wp_redirect($redirectBaseUrl . '&xfac_error=no_request_xf_user');
                exit;
            }
            if (empty($_REQUEST['user_login'])) {
                wp_redirect($redirectBaseUrl . '&xfac_error=no_user_login');
                exit;
            }
            $wpUserForAssociate = get_user_by('login', $_REQUEST['user_login']);
            if (!$wpUserForAssociate instanceof WP_User) {
                wp_redirect($redirectBaseUrl . '&xfac_error=no_user_login_found');
                exit;
            }
            if (empty($_REQUEST['pwd'])) {
                _xfac_login_renderAssociateForm($wpUserForAssociate, $_REQUEST['xf_user'], $_REQUEST['refresh_token'], $_REQUEST['scope'], $redirectTo);
                exit;
            }
            $password = $_REQUEST['pwd'];
            $authenticatedUser = wp_authenticate($wpUserForAssociate->user_login, $password);
            if (is_wp_error($authenticatedUser) or $authenticatedUser->ID != $wpUserForAssociate->ID) {
                _xfac_login_renderAssociateForm($wpUserForAssociate, $_REQUEST['xf_user'], $_REQUEST['refresh_token'], $_REQUEST['scope'], $redirectTo);
                exit;
            }
            $token = xfac_api_getAccessTokenFromRefreshToken($config, $_REQUEST['refresh_token']);
            $associateConfirmed = $wpUserForAssociate->ID;
            break;
        case 'authorize':
        default:
            $scope = '';
            if (!empty($_REQUEST['admin'])) {
                $scope = XFAC_API_SCOPE . ' admincp';
            }
            if ($_REQUEST['xfac'] === 'authorize') {
                // user is requesting to connect their own account
                // include a hash to skip the associate submission if possible
                $callbackUrl .= '&authorizeHash=' . urlencode(_xfac_login_getAuthorizeHash());
            }
            $authorizeUrl = xfac_api_getAuthorizeUrl($config, $callbackUrl, $scope);
            // wp_redirect($authorizeUrl);
            // cannot use wp_redirect because wp_sanitize_redirect changes our url
            // issues: it removes basic auth (http://user:password@path)
            // TODO: find better way to do this
            header("Location: {$authorizeUrl}", true, 302);
            exit;
    }
    if (empty($token)) {
        wp_redirect($redirectBaseUrl . '&xfac_error=no_token');
        exit;
    }
    if (empty($token['scope'])) {
        wp_redirect($redirectBaseUrl . '&xfac_error=no_scope');
        exit;
    }
    $me = xfac_api_getUsersMe($config, $token['access_token']);
    if (empty($me['user'])) {
        wp_redirect($redirectBaseUrl . '&xfac_error=no_xf_user');
        exit;
    }
    $xfUser = $me['user'];
    $wpUser = xfac_user_getUserByApiData($config['root'], $xfUser['user_id']);
    if (empty($wpUser)) {
        // no user with the API data found
        // find user with matching email...
        if (!empty($xfUser['user_email'])) {
            $wpUserMatchingEmail = get_user_by('email', $xfUser['user_email']);
            if (!empty($wpUserMatchingEmail)) {
                // user with matching email found
                if (!$associateConfirmed) {
                    _xfac_login_renderAssociateForm($wpUserMatchingEmail, $xfUser, $token['refresh_token'], $token['scope'], $redirectTo);
                    exit;
                } elseif ($associateConfirmed == $wpUserMatchingEmail->ID) {
                    // association has been confirmed
                    $wpUser = $wpUserMatchingEmail;
                }
            }
        }
    }
    if (empty($wpUser)) {
        $currentWpUser = wp_get_current_user();
        if (!empty($currentWpUser) and $currentWpUser->ID > 0) {
            // a user is currently logged in, try to associate now
            if (!$associateConfirmed) {
                _xfac_login_renderAssociateForm($currentWpUser, $xfUser, $token['refresh_token'], $token['scope'], $redirectTo);
                exit;
            } elseif ($associateConfirmed == $currentWpUser->ID) {
                // association has been confirmed
                $wpUser = $currentWpUser;
                if ($redirectTo == admin_url('profile.php')) {
                    // redirect target is profile.php page, it will alter it a bit
                    $redirectTo = admin_url('profile.php?xfac=associated');
                }
            }
        } else {
            // no matching user found, try to register
            if (!!get_option('users_can_register') or !!get_option('xfac_bypass_users_can_register')) {
                $newUserId = wp_create_user($xfUser['username'], wp_generate_password(), $xfUser['user_email']);
                if (is_wp_error($newUserId)) {
                    wp_redirect($redirectBaseUrl . '&xfac_error=register_error&message=' . urlencode($newUserId->get_error_message()));
                    exit;
                }
                $wpUser = new WP_User($newUserId);
            } else {
                wp_redirect($redirectBaseUrl . '&xfac_error=users_cannot_register');
                exit;
            }
        }
    }
    if (!empty($wpUser)) {
        xfac_syncLogin_syncBasic($config, $wpUser, $xfUser);
        xfac_syncLogin_syncRole($config, $wpUser, $xfUser);
        xfac_user_updateRecord($wpUser->ID, $config['root'], $xfUser['user_id'], $xfUser, $token);
        wp_set_auth_cookie($wpUser->ID, true);
        $redirectToFiltered = apply_filters('login_redirect', $redirectTo, $redirectToRequested, $wpUser);
        wp_redirect($redirectToFiltered);
        exit;
    }
}