/**
 * What to do when the user is logged out of phpBB
 * in WP-United prior to v0.9.0, we would forcibly log them out
 * However this is left open as a prelude to bi-directional user integration
 */
function wpu_int_phpbb_logged_out()
{
    global $wpuDebug, $phpbbForum, $wpUnited, $current_user;
    // Check if user is logged into WP
    get_currentuserinfo();
    $wpUser = $current_user;
    if (!$wpUser->ID) {
        $wpuDebug->add('phpBB & WP both logged out.');
        return false;
    }
    // no native way to tell if login is persistent
    $persist = (bool) get_user_meta($wpUser->ID, 'wpu-remember-login', true);
    $wpuDebug->add('WP already logged in, phpBB logged out.');
    $createdUser = false;
    $phpbbId = wpu_get_integrated_phpbbuser($wpUser->ID);
    if (!$phpbbId) {
        // The user has no account in phpBB, so we create one:
        if (!$wpUnited->get_setting('integcreatephpbb')) {
            $wpuDebug->add('No integrated phpBB account, leaving unintegrated.');
            return $wpUser->ID;
        }
        $wpuDebug->add('No integrated phpBB account. Creating.');
        // We just create standard users here for now, no setting of roles
        $phpbbId = wpu_create_phpbb_user($wpUser->ID);
        if ($phpbbId == 0) {
            $wpuDebug->add("Couldn't create phpBB user. Giving up.");
            //We couldn't create a user in phPBB. Before we wp_die()d. But just handle it silently.
            return $wpUser->ID;
        }
        $createdUser = true;
        $wpuDebug->add("Created phpBB user ID = {$phpbbId}.");
    }
    $wpuDebug->add("Logging in to integrated phpBB account, user ID = {$phpbbId}.");
    // the user now has an integrated phpBB account, log them into it
    if (headers_sent()) {
        $wpuDebug->add("WARNING: headers have already been sent, won't be able to set phpBB cookie!");
    }
    if ($phpbbForum->create_phpbb_session($phpbbId, $persist)) {
        $wpuDebug->add("Established Session for user {$phpbbId}.");
    } else {
        $wpuDebug->add("Could not establish session for user {$phpbbId}. Maybe they were deleted? Giving up.");
        return $wpUser->ID;
    }
    if ($createdUser) {
        wpu_sync_profiles($wpUsr, $phpbbForum->get_userdata(), 'sync');
    }
    // if this is a phpBB-in-WordPress page, this has probably just been called after phpBB has already been generated.
    if ($wpUnited->should_do_action('template-p-in-w')) {
        wpu_reload_page_if_no_post();
    }
    return $wpUser->ID;
}
/**
 * Perform an action requested by the user mapper
 */
function wpu_process_mapaction()
{
    global $phpbbForum, $db, $wpdb, $phpbb_root_path, $phpEx;
    wpu_ajax_header();
    echo '<wpumapaction>';
    $action = isset($_POST['type']) ? (string) $_POST['type'] : '';
    $userID = isset($_POST['userid']) ? (int) $_POST['userid'] : 0;
    $intUserID = isset($_POST['intuserid']) ? (int) $_POST['intuserid'] : 0;
    $package = isset($_POST['package']) ? (string) $_POST['package'] : '';
    if (empty($action) || empty($userID) || empty($package) || $action == 'delboth' && empty($intUserID) || $action == 'break' && empty($intUserID) || $action == 'sync' && empty($intUserID)) {
        wpu_map_action_error('Cannot perform action, required details are missing');
    }
    require_once $phpbb_root_path . 'includes/functions_user.' . $phpEx;
    switch ($action) {
        case 'del':
            if ($package == 'wp') {
                // First break if the user is integrated
                wpu_map_break($userID);
                wp_delete_user($userID, '0');
            } else {
                $fStateChanged = $phpbbForum->foreground();
                user_delete('retain', $userID);
                $phpbbForum->background($fStateChanged);
            }
            echo '<status>OK</status>';
            break;
        case 'delboth':
            $wUserID = $package == 'wp' ? $userID : $intUserID;
            $pUserID = $package == 'wp' ? $intUserID : $userID;
            wp_delete_user($wUserID, '0');
            $fStateChanged = $phpbbForum->foreground();
            user_delete('retain', $pUserID);
            $phpbbForum->background($fStateChanged);
            echo '<status>OK</status>';
            break;
        case 'integrate':
            $wUserID = $package == 'wp' ? $userID : $intUserID;
            $pUserID = $package == 'wp' ? $intUserID : $userID;
            if (!empty($wUserID) && !empty($pUserID)) {
                wpu_update_int_id($pUserID, $wUserID);
                // Sync profiles
                $wpuNewDetails = $phpbbForum->get_userdata('', $pUserID);
                $phpbbForum->background($fStateChanged);
                $wpUsrData = get_userdata($wUserID);
                // Don't modify passwords
                wpu_sync_profiles($wpUsrData, $wpuNewDetails, 'sync', true);
                echo '<status>OK</status>';
            }
            break;
        case 'break':
            $id = $package == 'wp' ? $userID : $intUserID;
            wpu_map_break($id);
            echo '<status>OK</status>';
            break;
        case 'sync':
            $wpUserID = $package == 'wp' ? $userID : $intUserID;
            $pUserID = $package == 'wp' ? $intUserID : $userID;
            $wpUsrData = get_userdata($wpUserID);
            $pUsrData = $phpbbForum->get_userdata('', $pUserID);
            wpu_sync_profiles($wpUsrData, $pUsrData, 'sync', true);
            echo '<status>OK</status>';
            break;
        case 'createin':
            // create user in phpBB
            if ($package == 'phpbb') {
                $phpbbID = wpu_create_phpbb_user($userID);
                if ($phpbbID == 0) {
                    die('<status>FAIL</status><details>' . __('Could not add user to phpBB', 'wp-united') . '</details></wpumapaction>');
                } else {
                    if ($phpbbID == -1) {
                        die('<status>FAIL</status><details>' . __('A suitable username could not be found in phpBB', 'wp-united') . '</details></wpumapaction>');
                    }
                }
                wpu_sync_profiles(get_userdata($userID), $phpbbForum->get_userdata('', $phpbbID), 'wp-update');
            } else {
                // create user in WordPress
                $wpuNewDetails = $phpbbForum->get_userdata('', $userID);
                require_once ABSPATH . WPINC . '/registration.php';
                if (!($userLevel = wpu_get_user_level($userID))) {
                    die('<status>FAIL</status><details>' . __('Cannot create integrated user, as they would have no integration permissions.', 'wp-united') . '</details></wpumapaction>');
                }
                $newUserID = wpu_create_wp_user($wpuNewDetails['username'], $wpuNewDetails['user_password'], $wpuNewDetails);
                if ($newUserID) {
                    if ($wpUser = get_userdata($newUserID)) {
                        wpu_update_int_id($userID, $wpUser->ID);
                        wpu_sync_profiles($wpUser, $wpuNewDetails, 'phpbb-update');
                        wpu_set_role($wpUser->ID, $userLevel);
                    }
                } else {
                    die('<status>FAIL</status><details>' . __('Could not add user to WordPress', 'wp-united') . '</details></wpumapaction>');
                }
            }
            echo '<status>OK</status>';
            break;
    }
    echo '<nonce>' . wp_create_nonce('wp-united-mapaction') . '</nonce>';
    echo '</wpumapaction>';
    die;
}
 /**
  * checks a new registration 
  * This occurs after the account has been created, so it is only for naughty plugins that
  * leave no other way to intercept them.
  * If it is found to be an erroneous user creation, then we remove the newly-added user.
  * This action is removed by WP-United when adding a user, so we avoid unsetting our own additions
  * @param int $userID the user ID
  * @ return mixed void or hellfire
  */
 public function process_new_wp_reg($userID)
 {
     global $phpbbForum;
     static $justCreatedUser = -1;
     /*
      * if we've already created a user in this session, 
      * it is likely an error from a plugin calling the user_register hook 
      * after wp_insert_user has already called it. The Social Login plugin does this
      * 
      * At any rate, it is pointless to check twice
      */
     if ($justCreatedUser === $userID) {
         return;
     }
     // some registration plugins don't init WP and call the action hook directly. This is enough to get us a phpBB env
     $this->init_plugin();
     // neeed some user add / delete functions
     if (!defined('WP_ADMIN')) {
         require_once ABSPATH . 'wp-admin/includes/user.php';
     }
     if ($this->get_setting('integrateLogin')) {
         $errors = new WP_Error();
         $user = get_userdata($userID);
         $result = wpu_validate_new_user($user->user_login, $user->user_email, $errors);
         if ($result !== false) {
             // An error occurred validating the new WP user, remove the user.
             wp_delete_user($userID, 0);
             $message = '<h1>' . __('Error:', 'wp-united') . '</h1>';
             $message .= '<p>' . implode('</p><p>', $errors->get_error_messages()) . '</p><p>';
             $message .= __('Please go back and try again, or contact an administrator if you keep seeing this error.', 'wp-united') . '</p>';
             wp_die($message);
             exit;
         } else {
             // create new integrated user in phpBB to match
             $phpbbID = wpu_create_phpbb_user($userID);
             $justCreatedUser = $userID;
             wpu_sync_profiles($user, $phpbbForum->get_userdata('', $phpbbID), 'sync');
         }
     }
 }