function widget($args, $instance) { if (!is_search()) { return ''; } /** @var WP_Query $wp_query */ global $wp_query; extract($args); $limit = !empty($instance['limit']) ? absint($instance['limit']) : 5; if (empty($limit)) { $limit = 5; } $title = !empty($instance['title']) ? $instance['title'] : __('Forum Results'); $title = apply_filters('widget_title', $title, $instance, $this->id_base); $config = xfac_option_getConfig(); $threads = array(); if (!empty($config)) { $accessToken = xfac_user_getSystemAccessToken($config, true); $results = xfac_api_postSearchThreads($config, $accessToken, $wp_query->get('s'), $limit); if (!empty($results['data'])) { $threads = $results['data']; } } require xfac_template_locateTemplate('widget_search.php'); }
function widget($args, $instance) { $cache = wp_cache_get(__CLASS__); if (!is_array($cache)) { $cache = array(); } if (empty($args['widget_id'])) { $args['widget_id'] = $this->id; } if (isset($cache[$args['widget_id']])) { echo $cache[$args['widget_id']]; return; } ob_start(); extract($args); $limit = !empty($instance['limit']) ? absint($instance['limit']) : 5; if (empty($limit)) { $limit = 5; } $title = !empty($instance['title']) ? $instance['title'] : false; $availableTypes = $this->_getAvailableTypes(); if (empty($instance['type']) or !isset($availableTypes[$instance['type']])) { $tmp = array_keys($availableTypes); $instance['type'] = reset($tmp); } if ($title === false) { $title = $availableTypes[$instance['type']]; } $title = apply_filters('widget_title', $title, $instance, $this->id_base); $config = xfac_option_getConfig(); $threads = array(); if (!empty($config) && !empty($instance['forumIds'])) { $forumId = implode(',', $instance['forumIds']); $extraParams = array('_xfac' => 'threads.php', 'limit' => $limit, 'sticky' => 0); switch ($instance['type']) { case 'recent': $extraParams['order'] = 'thread_update_date_reverse'; break; case 'most_viewed': $extraParams['order'] = 'thread_view_count_reverse'; break; case 'most_replied': $extraParams['order'] = 'thread_post_count_reverse'; break; case 'new': default: // this is the default order // $extraParams['order'] = 'thread_create_date_reverse'; break; } $extraParams = http_build_query($extraParams); $results = xfac_api_getThreadsInForums($config, $forumId, '', $extraParams); if (!empty($results['threads'])) { $threads = $results['threads']; } } require xfac_template_locateTemplate('widget_threads.php'); $cache[$args['widget_id']] = ob_get_flush(); wp_cache_set(__CLASS__, $cache); }
function xfac_whitelist_options($whitelist_options) { if (xfac_option_getWorkingMode() === 'blog') { $whitelist_options['xfac'][] = 'xfac_root'; $whitelist_options['xfac'][] = 'xfac_client_id'; $whitelist_options['xfac'][] = 'xfac_client_secret'; } $config = xfac_option_getConfig(); $meta = xfac_option_getMeta($config); if (!empty($meta['linkIndex'])) { $whitelist_options['xfac'][] = 'xfac_tag_forum_mappings'; $whitelist_options['xfac'][] = 'xfac_sync_post_wp_xf'; $whitelist_options['xfac'][] = 'xfac_sync_post_wp_xf_excerpt'; $whitelist_options['xfac'][] = 'xfac_sync_post_wp_xf_link'; $whitelist_options['xfac'][] = 'xfac_sync_post_xf_wp'; $whitelist_options['xfac'][] = 'xfac_sync_post_xf_wp_publish'; $whitelist_options['xfac'][] = 'xfac_search_index_post'; $whitelist_options['xfac'][] = 'xfac_sync_comment_wp_xf'; $whitelist_options['xfac'][] = 'xfac_sync_comment_wp_xf_as_guest'; $whitelist_options['xfac'][] = 'xfac_sync_comment_xf_wp'; $whitelist_options['xfac'][] = 'xfac_sync_comment_xf_wp_as_guest'; $whitelist_options['xfac'][] = 'xfac_search_index_comment'; $whitelist_options['xfac'][] = 'xfac_sync_avatar_xf_wp'; $whitelist_options['xfac'][] = 'xfac_bypass_users_can_register'; $whitelist_options['xfac'][] = 'xfac_sync_password'; $whitelist_options['xfac'][] = 'xfac_sync_login'; $whitelist_options['xfac'][] = 'xfac_sync_user_wp_xf'; $whitelist_options['xfac'][] = 'xfac_sync_user_wp_xf_as_admin'; $whitelist_options['xfac'][] = 'xfac_sync_user_wp_xf_password'; $whitelist_options['xfac'][] = 'xfac_sync_role'; $whitelist_options['xfac'][] = 'xfac_sync_role_wp_xf'; $whitelist_options['xfac'][] = 'xfac_top_bar_forums'; $whitelist_options['xfac'][] = 'xfac_top_bar_notifications'; $whitelist_options['xfac'][] = 'xfac_top_bar_conversations'; $whitelist_options['xfac'][] = 'xfac_top_bar_replace'; $whitelist_options['xfac'][] = 'xfac_top_bar_always'; $whitelist_options['xfac'][] = 'xfac_xf_guest_account'; $whitelist_options['xfac'][] = 'xfac_xf_admin_account'; } // always show advanced sections $whitelist_options['xfac'][] = 'xfac_server_ip'; return $whitelist_options; }
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); } } } } } }
function xfac_syncComment_cron() { $config = xfac_option_getConfig(); if (empty($config)) { return; } $postSyncRecords = xfac_sync_getRecordsByProviderTypeAndRecent('', 'thread'); foreach ($postSyncRecords as $postSyncRecord) { xfac_syncComment_processPostSyncRecord($config, $postSyncRecord); } }
function xfac_topBar_wp_enqueue_scripts() { $config = xfac_option_getConfig(); if (empty($config)) { // do nothing return; } $wpUser = wp_get_current_user(); if ($wpUser->ID > 0) { wp_enqueue_script('jquery'); wp_enqueue_script('xfac-sdk', xfac_api_getSdkJsUrl($config)); wp_enqueue_script('xfac-script.js', XFAC_PLUGIN_URL . '/js/script.js'); wp_enqueue_style('xfac-top_bar.css', XFAC_PLUGIN_URL . '/css/top_bar.css'); } }
function xfac_profile_update_user_pass($wpUserId) { if (empty($GLOBALS['_xfac_syncLogin_pending_user_pass'])) { // no data return; } $pending = $GLOBALS['_xfac_syncLogin_pending_user_pass']; if (!is_array($pending) || count($pending) != 2) { // data unrecognized return; } if ($pending[0] != $wpUserId) { // user_id not matched return; } $config = xfac_option_getConfig(); if (empty($config)) { // no config return; } $adminAccessToken = xfac_user_getAdminAccessToken($config); if (empty($adminAccessToken)) { // no admin access token return; } $records = xfac_user_getRecordsByUserId($wpUserId); if (empty($records)) { // no user record return null; } $record = reset($records); xfac_api_postUserPassword($config, $adminAccessToken, $record->identifier, $pending[1]); xfac_log('xfac_profile_update_user_pass pushed password for $wpUser (#%d)', $wpUserId); }
function xfac_tools_search_index() { /** @var wpdb $wpdb */ global $wpdb; $config = xfac_option_getConfig(); if (empty($config)) { wp_die(__('XenForo API configuration is missing.', 'xenforo-api-consumer')); } if (!xfac_api_hasModuleVersion($config, 'search/indexing', 2015091501)) { wp_die(__('Please update XenForo API to run this tool.', 'xenforo-api-consumer')); } $optionFilters = array('type' => array('filter' => FILTER_DEFAULT, 'default' => ''), 'position' => array('filter' => FILTER_VALIDATE_INT, 'default' => 0), 'limit' => array('filter' => FILTER_VALIDATE_INT, 'default' => 10)); $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']; } } $contentTypes = preg_split('#[,\\s]#', $options['type'], -1, PREG_SPLIT_NO_EMPTY); $contentType = ''; $contentTable = ''; $contentIdField = ''; $syncProviderType = ''; while (true) { if (empty($contentTypes)) { die(__('Done.', 'xenforo-api-consumer')); } $contentType = reset($contentTypes); switch ($contentType) { case 'post': $contentTable = 'posts'; $contentIdField = 'ID'; $syncProviderType = 'thread'; break; case 'comment': $contentTable = 'comments'; $contentIdField = 'comment_ID'; $syncProviderType = 'post'; break; } $maxContentId = $wpdb->get_var("SELECT MAX({$contentIdField}) FROM {$wpdb->prefix}{$contentTable}"); if ($options['position'] < $maxContentId) { // position is good, break the while(true) and start working break; } $options['position'] = 0; array_shift($contentTypes); $options['type'] = implode(',', $contentTypes); } $contents = $wpdb->get_results($wpdb->prepare("\n SELECT {$contentIdField} AS ID\n FROM {$wpdb->prefix}{$contentTable}\n WHERE {$contentIdField} > %d\n LIMIT %d", array($options['position'], $options['limit']))); $contentIds = array(); foreach ($contents as $content) { $contentIds[] = $content->ID; } $syncRecords = xfac_sync_getRecordsByProviderTypeAndSyncIds('', $syncProviderType, $contentIds); foreach ($contents as $content) { $options['position'] = max($options['position'], $content->ID); $latestSyncDate = 0; foreach ($syncRecords as $syncRecord) { if ($syncRecord->sync_id == $content->ID) { $latestSyncDate = max($latestSyncDate, $syncRecord->sync_date); } } switch ($contentType) { case 'post': xfac_search_indexPost($config, $content->ID, $latestSyncDate); break; case 'comment': xfac_search_indexComment($config, $content->ID, $latestSyncDate); break; } } $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_search_index%s', $optionsStr)))); }
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)))); }
function xfac_post_meta_box_info($post) { $config = xfac_option_getConfig(); $meta = xfac_option_getMeta($config); $records = xfac_sync_getRecordsByProviderTypeAndSyncId('', 'thread', $post->ID); require xfac_template_locateTemplate('post_meta_box_info.php'); }
function xfac_subscription_handleCallback(array $json) { $config = xfac_option_getConfig(); if (empty($config['clientId'])) { return; } $xfThreadIds = array(); $xfPostIds = array(); // phrase 1: preparation foreach ($json as &$pingRef) { if (empty($pingRef['client_id']) or $pingRef['client_id'] != $config['clientId']) { continue; } if (empty($pingRef['topic'])) { continue; } $parts = explode('_', $pingRef['topic']); $pingRef['topic_id'] = array_pop($parts); $pingRef['topic_type'] = implode('_', $parts); switch ($pingRef['topic_type']) { case 'thread_post': $xfThreadIds[] = $pingRef['topic_id']; $xfPostIds[] = $pingRef['object_data']; break; } } // phrase 2: fetch sync records $postSyncRecords = array(); if (!empty($xfPostIds)) { $postSyncRecords = xfac_sync_getRecordsByProviderTypeAndIds('', 'thread', $xfThreadIds); } $commentSyncRecords = array(); if (!empty($xfPostIds)) { $commentSyncRecords = xfac_sync_getRecordsByProviderTypeAndIds('', 'post', $xfPostIds); } // phrase 3: sync data foreach ($json as &$pingRef) { if (empty($pingRef['topic_type'])) { continue; } switch ($pingRef['topic_type']) { case 'thread_post': $postSyncRecord = null; $commentSyncRecord = null; foreach ($postSyncRecords as $_postSyncRecord) { if ($_postSyncRecord->provider_content_id == $pingRef['topic_id']) { $postSyncRecord = $_postSyncRecord; } } if (!empty($postSyncRecord)) { foreach ($commentSyncRecords as $_commentSyncRecord) { if ($_commentSyncRecord->provider_content_id == $pingRef['object_data']) { $commentSyncRecord = $_commentSyncRecord; } } $pingRef['result'] = _xfac_subscription_handleCallback_threadPost($config, $pingRef, $postSyncRecord, $commentSyncRecord); if (!empty($pingRef['result'])) { xfac_sync_updateRecordDate($postSyncRecord); if (!empty($commentSyncRecord)) { xfac_sync_updateRecordDate($commentSyncRecord); } } } break; case 'user_notification': $pingRef['result'] = _xfac_subscription_handleCallback_userNotification($config, $pingRef); break; case 'user': $pingRef['result'] = _xfac_subscription_handleCallback_user($config, $pingRef); break; } } // phrase 4: output results $results = array(); foreach ($json as $ping) { if (!empty($ping['result'])) { $results[] = $ping; xfac_log('xfac_subscription_handleCallback %s/%s -> %s', $ping['topic_type'], $ping['topic_id'], $ping['result']); } } echo json_encode($results); }
function xfac_dashboardOptions_admin_init() { if (empty($_REQUEST['page'])) { return; } if ($_REQUEST['page'] !== 'xfac') { return; } if (!empty($_REQUEST['cron'])) { switch ($_REQUEST['cron']) { case 'hourly': do_action('xfac_cron_hourly'); wp_redirect(admin_url('options-general.php?page=xfac&ran=hourly')); exit; } } elseif (!empty($_REQUEST['do'])) { switch ($_REQUEST['do']) { case 'xfac_meta': update_option('xfac_meta', array()); wp_redirect(admin_url('options-general.php?page=xfac&done=xfac_meta')); break; case 'xfac_xf_guest_account_submit': $config = xfac_option_getConfig(); if (empty($config)) { wp_die('no_config'); } $username = $_REQUEST['xfac_guest_username']; if (empty($username)) { wp_die('no_username'); } $password = $_REQUEST['xfac_guest_password']; if (empty($password)) { wp_die('no_password'); } $token = xfac_api_getAccessTokenFromUsernamePassword($config, $username, $password); if (empty($token)) { wp_die('no_token'); } $guest = xfac_api_getUsersMe($config, $token['access_token'], false); if (empty($guest['user'])) { wp_die('no_xf_user'); } xfac_user_updateRecord(0, $config['root'], $guest['user']['user_id'], $guest['user'], $token); $records = xfac_user_getRecordsByUserId(0); $record = reset($records); update_option('xfac_xf_guest_account', $record->id); // force meta rebuild update_option('xfac_meta', array()); wp_redirect(admin_url('options-general.php?page=xfac&done=xfac_xf_guest_account')); break; } } }
function xfac_user_getAccessTokenForRecord($record) { $token = $record->token; if (!empty($token['expire_date']) && $token['expire_date'] > time()) { return $token['access_token']; } $config = xfac_option_getConfig(); if (empty($config)) { return null; } if (empty($newToken)) { // try to refresh and get new token if (!empty($token['refresh_token']) && (!isset($token['refresh_token_expire_date']) || $token['refresh_token_expire_date'] > time())) { $newToken = xfac_api_getAccessTokenFromRefreshToken($config, $token['refresh_token']); } } if (empty($newToken)) { // try to get new token with admin token // of course do not attempt that if the current record IS the admin record $xfAdminAccountOption = intval(get_option('xfac_xf_admin_account')); if ($xfAdminAccountOption > 0 && $record->id != $xfAdminAccountOption) { $adminAccessToken = xfac_user_getAdminAccessToken($config); if (!empty($adminAccessToken)) { $newToken = xfac_api_postOauthTokenAdmin($config, $adminAccessToken, $record->identifier); } } } if (empty($newToken)) { return null; } xfac_user_updateRecord($record->user_id, $config['root'], $record->identifier, $record->profile, $newToken); return $newToken['access_token']; }
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; } }