示例#1
0
/**
* Upload new photo, delete old photo
*
* @param    string  $delete_photo   'on': delete old photo
* @return   string                  filename of new photo (empty = no new photo)
*
*/
function handlePhotoUpload($delete_photo = '')
{
    global $_CONF, $_TABLES, $_USER, $LANG24;
    require_once $_CONF['path_system'] . 'classes/upload.class.php';
    $upload = new upload();
    if (!empty($_CONF['image_lib'])) {
        if ($_CONF['image_lib'] == 'imagemagick') {
            // Using imagemagick
            $upload->setMogrifyPath($_CONF['path_to_mogrify']);
        } elseif ($_CONF['image_lib'] == 'netpbm') {
            // using netPBM
            $upload->setNetPBM($_CONF['path_to_netpbm']);
        } elseif ($_CONF['image_lib'] == 'gdlib') {
            // using the GD library
            $upload->setGDLib();
        }
        $upload->setAutomaticResize(true);
        if (isset($_CONF['debug_image_upload']) && $_CONF['debug_image_upload']) {
            $upload->setLogFile($_CONF['path'] . 'logs/error.log');
            $upload->setDebug(true);
        }
        if (isset($_CONF['jpeg_quality'])) {
            $upload->setJpegQuality($_CONF['jpeg_quality']);
        }
    }
    $upload->setAllowedMimeTypes(array('image/gif' => '.gif', 'image/jpeg' => '.jpg,.jpeg', 'image/pjpeg' => '.jpg,.jpeg', 'image/x-png' => '.png', 'image/png' => '.png'));
    if (!$upload->setPath($_CONF['path_images'] . 'userphotos')) {
        $display = COM_siteHeader('menu', $LANG24[30]);
        $display .= COM_startBlock($LANG24[30], '', COM_getBlockTemplate('_msg_block', 'header'));
        $display .= $upload->printErrors(false);
        $display .= COM_endBlock(COM_getBlockTemplate('_msg_block', 'footer'));
        $display .= COM_siteFooter();
        COM_output($display);
        exit;
        // don't return
    }
    $filename = '';
    if (!empty($delete_photo) && $delete_photo == 'on') {
        $delete_photo = true;
    } else {
        $delete_photo = false;
    }
    $curphoto = DB_getItem($_TABLES['users'], 'photo', "uid = {$_USER['uid']}");
    if (empty($curphoto)) {
        $delete_photo = false;
    }
    // see if user wants to upload a (new) photo
    $newphoto = $_FILES['photo'];
    if (!empty($newphoto['name'])) {
        $pos = strrpos($newphoto['name'], '.') + 1;
        $fextension = substr($newphoto['name'], $pos);
        $filename = $_USER['username'] . '.' . $fextension;
        if (!empty($curphoto) && $filename != $curphoto) {
            $delete_photo = true;
        } else {
            $delete_photo = false;
        }
    }
    // delete old photo first
    if ($delete_photo) {
        USER_deletePhoto($curphoto);
    }
    // now do the upload
    if (!empty($filename)) {
        $upload->setFileNames($filename);
        $upload->setPerms('0644');
        if ($_CONF['max_photo_width'] > 0 && $_CONF['max_photo_height'] > 0) {
            $upload->setMaxDimensions($_CONF['max_photo_width'], $_CONF['max_photo_height']);
        } else {
            $upload->setMaxDimensions($_CONF['max_image_width'], $_CONF['max_image_height']);
        }
        if ($_CONF['max_photo_size'] > 0) {
            $upload->setMaxFileSize($_CONF['max_photo_size']);
        } else {
            $upload->setMaxFileSize($_CONF['max_image_size']);
        }
        $upload->uploadFiles();
        if ($upload->areErrors()) {
            $display = COM_siteHeader('menu', $LANG24[30]);
            $display .= COM_startBlock($LANG24[30], '', COM_getBlockTemplate('_msg_block', 'header'));
            $display .= $upload->printErrors(false);
            $display .= COM_endBlock(COM_getBlockTemplate('_msg_block', 'footer'));
            $display .= COM_siteFooter();
            COM_output($display);
            exit;
            // don't return
        }
    } else {
        if (!$delete_photo && !empty($curphoto)) {
            $filename = $curphoto;
        }
    }
    return $filename;
}
示例#2
0
/**
* Saves user to the database
*
* @param    int     $uid            user id
* @param    string  $usernmae       (short) username
* @param    string  $fullname       user's full name
* @param    string  $email          user's email address
* @param    string  $regdate        date the user registered with the site
* @param    string  $homepage       user's homepage URL
* @param    array   $groups         groups the user belongs to
* @param    string  $delete_photo   delete user's photo if == 'on'
* @return   string                  HTML redirect or error message
*
*/
function saveusers($uid, $username, $fullname, $passwd, $passwd_conf, $email, $regdate, $homepage, $groups, $delete_photo = '', $userstatus = 3, $oldstatus = 3)
{
    global $_CONF, $_TABLES, $_USER, $LANG28, $_USER_VERBOSE;
    $retval = '';
    $userChanged = false;
    if ($_USER_VERBOSE) {
        COM_errorLog("**** entering saveusers****", 1);
        COM_errorLog("group size at beginning = " . count($groups), 1);
    }
    $service = DB_getItem($_TABLES['users'], 'remoteservice', "uid = {$uid}");
    // If remote service then assume blank password
    if (!empty($service)) {
        $passwd = '';
        $passwd_conf = '';
    }
    $passwd_changed = true;
    if (empty($service) && SEC_encryptUserPassword($passwd, $uid) === 0 && $passwd_conf === '') {
        $passwd_changed = false;
    }
    if ($passwd_changed && $passwd != $passwd_conf) {
        // passwords don't match
        return edituser($uid, 67);
    }
    $nameAndEmailOkay = true;
    if (empty($username)) {
        $nameAndEmailOkay = false;
    } elseif (empty($email)) {
        if (empty($uid)) {
            $nameAndEmailOkay = false;
            // new users need an email address
        } else {
            if (empty($service)) {
                $nameAndEmailOkay = false;
                // not a remote user - needs email
            }
        }
    }
    if ($nameAndEmailOkay) {
        if (!empty($email) && !COM_isEmail($email)) {
            return edituser($uid, 52);
        }
        $uname = DB_escapeString($username);
        if (empty($uid)) {
            $ucount = DB_getItem($_TABLES['users'], 'COUNT(*)', "username = '******'");
        } else {
            if (!empty($service)) {
                $uservice = DB_escapeString($service);
                $ucount = DB_getItem($_TABLES['users'], 'COUNT(*)', "username = '******' AND uid <> {$uid} AND remoteservice = '{$uservice}'");
            } else {
                $ucount = DB_getItem($_TABLES['users'], 'COUNT(*)', "username = '******' AND uid <> {$uid} AND (remoteservice = '' OR remoteservice IS NULL)");
            }
        }
        if ($ucount > 0) {
            // Admin just changed a user's username to one that already exists
            return edituser($uid, 51);
        }
        $emailaddr = DB_escapeString($email);
        $exclude_remote = " AND (remoteservice IS NULL OR remoteservice = '')";
        if (empty($uid)) {
            $ucount = DB_getItem($_TABLES['users'], 'COUNT(*)', "email = '{$emailaddr}'" . $exclude_remote);
        } else {
            $old_email = DB_getItem($_TABLES['users'], 'email', "uid = '{$uid}'");
            if ($old_email == $email) {
                // email address didn't change so don't care
                $ucount = 0;
            } else {
                $ucount = DB_getItem($_TABLES['users'], 'COUNT(*)', "email = '{$emailaddr}' AND uid <> {$uid}" . $exclude_remote);
            }
        }
        if ($ucount > 0) {
            // Admin just changed a user's email to one that already exists
            return edituser($uid, 56);
        }
        if ($_CONF['custom_registration'] && function_exists('CUSTOM_userCheck')) {
            $ret = CUSTOM_userCheck($username, $email);
            if (!empty($ret)) {
                // need a numeric return value - otherwise use default message
                if (!is_numeric($ret['number'])) {
                    $ret['number'] = 400;
                }
                return edituser($uid, $ret['number']);
            }
        }
        if (empty($uid)) {
            if (empty($passwd)) {
                // no password? create one ...
                $passwd = SEC_generateRandomPassword();
            }
            $uid = USER_createAccount($username, $email, $passwd, $fullname, $homepage);
            if ($uid > 1) {
                DB_query("UPDATE {$_TABLES['users']} SET status = {$userstatus} WHERE uid = {$uid}");
            }
        } else {
            $fullname = DB_escapeString($fullname);
            $homepage = DB_escapeString($homepage);
            $curphoto = DB_getItem($_TABLES['users'], 'photo', "uid = {$uid}");
            if (!empty($curphoto) && $delete_photo == 'on') {
                USER_deletePhoto($curphoto);
                $curphoto = '';
            }
            if ($_CONF['allow_user_photo'] == 1 && !empty($curphoto)) {
                $curusername = DB_getItem($_TABLES['users'], 'username', "uid = {$uid}");
                if ($curusername != $username) {
                    // user has been renamed - rename the photo, too
                    $newphoto = preg_replace('/' . $curusername . '/', $username, $curphoto, 1);
                    $imgpath = $_CONF['path_images'] . 'userphotos/';
                    if (@rename($imgpath . $curphoto, $imgpath . $newphoto) === false) {
                        $retval .= COM_errorLog('Could not rename userphoto "' . $curphoto . '" to "' . $newphoto . '".');
                        return $retval;
                    }
                    $curphoto = $newphoto;
                }
            }
            $curphoto = DB_escapeString($curphoto);
            DB_query("UPDATE {$_TABLES['users']} SET username = '******', fullname = '{$fullname}', email = '{$email}', homepage = '{$homepage}', photo = '{$curphoto}', status='{$userstatus}' WHERE uid = {$uid}");
            if ($passwd_changed && !empty($passwd)) {
                SEC_updateUserPassword($passwd, $uid);
            }
            if ($_CONF['custom_registration'] and function_exists('CUSTOM_userSave')) {
                CUSTOM_userSave($uid);
            }
            if ($_CONF['usersubmission'] == 1 && $oldstatus == USER_ACCOUNT_AWAITING_APPROVAL && $userstatus == USER_ACCOUNT_ACTIVE) {
                USER_createAndSendPassword($username, $email, $uid);
            }
            if ($userstatus == USER_ACCOUNT_DISABLED) {
                SESS_endUserSession($uid);
            }
            $userChanged = true;
        }
        // check that the user is allowed to change group assignments
        if (is_array($groups) && SEC_hasRights('group.assign')) {
            if (!SEC_inGroup('Root')) {
                $rootgrp = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'Root'");
                if (in_array($rootgrp, $groups)) {
                    COM_accessLog("User {$_USER['username']} ({$_USER['uid']}) just tried to give Root permissions to user {$username}.");
                    echo COM_refresh($_CONF['site_admin_url'] . '/index.php');
                    exit;
                }
            }
            // make sure the Remote Users group is in $groups
            if (SEC_inGroup('Remote Users', $uid)) {
                $remUsers = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'Remote Users'");
                if (!in_array($remUsers, $groups)) {
                    $groups[] = $remUsers;
                }
            }
            if ($_USER_VERBOSE) {
                COM_errorLog("deleting all group_assignments for user {$uid}/{$username}", 1);
            }
            // remove user from all groups that the User Admin is a member of
            $UserAdminGroups = SEC_getUserGroups();
            $whereGroup = 'ug_main_grp_id IN (' . implode(',', $UserAdminGroups) . ')';
            DB_query("DELETE FROM {$_TABLES['group_assignments']} WHERE (ug_uid = {$uid}) AND " . $whereGroup);
            // make sure to add user to All Users and Logged-in Users groups
            $allUsers = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'All Users'");
            if (!in_array($allUsers, $groups)) {
                $groups[] = $allUsers;
            }
            $logUsers = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'Logged-in Users'");
            if (!in_array($logUsers, $groups)) {
                $groups[] = $logUsers;
            }
            foreach ($groups as $userGroup) {
                if (in_array($userGroup, $UserAdminGroups)) {
                    if ($_USER_VERBOSE) {
                        COM_errorLog("adding group_assignment " . $userGroup . " for {$username}", 1);
                    }
                    $sql = "INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id, ug_uid) VALUES ({$userGroup}, {$uid})";
                    DB_query($sql);
                }
            }
        }
        if ($userChanged) {
            PLG_userInfoChanged($uid);
        }
        $errors = DB_error();
        if (empty($errors)) {
            echo PLG_afterSaveSwitch($_CONF['aftersave_user'], "{$_CONF['site_url']}/users.php?mode=profile&uid={$uid}", 'user', 21);
        } else {
            $retval .= COM_errorLog('Error in saveusers in ' . $_CONF['site_admin_url'] . '/user.php');
            $retval = COM_createHTMLDocument($retval, array('pagetitle' => $LANG28[22]));
            echo $retval;
            exit;
        }
    } else {
        $retval .= COM_showMessageText($LANG28[10]);
        if (!empty($uid) && $uid > 1 && DB_count($_TABLES['users'], 'uid', $uid) > 0) {
            $retval .= edituser($uid);
        } else {
            $retval .= edituser();
        }
        $retval = COM_createHTMLDocument($retval, array('pagetitle' => $LANG28[1]));
        COM_output($retval);
        exit;
    }
    if ($_USER_VERBOSE) {
        COM_errorLog("***************leaving saveusers*****************", 1);
    }
    return $retval;
}
示例#3
0
/**
* Upload new photo, delete old photo
*
* @param    string  $delete_photo   'on': delete old photo
* @return   string                  filename of new photo (empty = no new photo)
*
*/
function USER_handlePhotoUpload($uid, $delete_photo = '')
{
    global $_CONF, $_TABLES, $LANG24;
    USES_class_upload();
    $upload = new upload();
    if (!empty($_CONF['image_lib'])) {
        $upload->setAutomaticResize(true);
        if (isset($_CONF['debug_image_upload']) && $_CONF['debug_image_upload']) {
            $upload->setLogFile($_CONF['path'] . 'logs/error.log');
            $upload->setDebug(true);
        }
    }
    $upload->setAllowedMimeTypes(array('image/gif' => '.gif', 'image/jpeg' => '.jpg,.jpeg', 'image/pjpeg' => '.jpg,.jpeg', 'image/x-png' => '.png', 'image/png' => '.png'));
    if (!$upload->setPath($_CONF['path_images'] . 'userphotos')) {
        return '';
    }
    $filename = '';
    if (!empty($delete_photo) && $delete_photo == 1) {
        $delete_photo = true;
    } else {
        $delete_photo = false;
    }
    $curphoto = DB_getItem($_TABLES['users'], 'photo', "uid = " . (int) $uid);
    if (empty($curphoto)) {
        $delete_photo = false;
    }
    // see if user wants to upload a (new) photo
    $newphoto = $_FILES['photo'];
    if (!empty($newphoto['name'])) {
        $pos = strrpos($newphoto['name'], '.') + 1;
        $fextension = substr($newphoto['name'], $pos);
        $filename = $uid . '.' . $fextension;
        if (!empty($curphoto) && $filename != $curphoto) {
            $delete_photo = true;
        } else {
            $delete_photo = false;
        }
    }
    // delete old photo first
    if ($delete_photo) {
        USER_deletePhoto($curphoto);
    }
    // now do the upload
    if (!empty($filename)) {
        $upload->setFileNames($filename);
        $upload->setFieldName('photo');
        $upload->setPerms('0644');
        $upload->setMaxDimensions(1024000, 1024000);
        $upload->uploadFiles();
        if ($upload->areErrors()) {
            return '';
        }
        IMG_resizeImage($_CONF['path_images'] . 'userphotos/' . $filename, $_CONF['path_images'] . 'userphotos/' . $filename, $_CONF['max_photo_height'], $_CONF['max_photo_width']);
    } else {
        if (!$delete_photo && !empty($curphoto)) {
            $filename = $curphoto;
        }
    }
    return $filename;
}
示例#4
0
/**
* Delete a user account
*
* @param    int       $uid   id of the user to delete
* @return   boolean   true = user deleted, false = an error occured
*
*/
function USER_deleteAccount($uid)
{
    global $_CONF, $_TABLES, $_USER;
    // first some checks ...
    if ($uid == $_USER['uid'] && $_CONF['allow_account_delete'] == 1 || SEC_hasRights('user.delete')) {
        if (SEC_inGroup('Root', $uid)) {
            if (!SEC_inGroup('Root')) {
                // can't delete a Root user without being in the Root group
                COM_accessLog("User {$_USER['uid']} just tried to delete Root user {$uid} with insufficient privileges.");
                return false;
            } else {
                $rootgrp = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'Root'");
                $result = DB_query("SELECT COUNT(DISTINCT {$_TABLES['users']}.uid) AS count FROM {$_TABLES['users']},{$_TABLES['group_assignments']} WHERE {$_TABLES['users']}.uid > 1 AND {$_TABLES['users']}.uid = {$_TABLES['group_assignments']}.ug_uid AND ({$_TABLES['group_assignments']}.ug_main_grp_id = {$rootgrp})");
                $A = DB_fetchArray($result);
                if ($A['count'] <= 1) {
                    // make sure there's at least 1 Root user left
                    COM_errorLog("You can't delete the last user from the Root group.", 1);
                    return false;
                }
            }
        }
    } else {
        // you can only delete your own account (if enabled) or you need
        // proper permissions to do so (user.delete)
        COM_accessLog("User {$_USER['uid']} just tried to delete user {$uid} with insufficient privileges.");
        return false;
    }
    // log the user out
    SESS_endUserSession($uid);
    // Ok, now delete everything related to this user
    // let plugins update their data for this user
    PLG_deleteUser($uid);
    // Call custom account profile delete function if enabled and exists
    if ($_CONF['custom_registration'] && function_exists('CUSTOM_userDelete')) {
        CUSTOM_userDelete($uid);
    }
    // remove from all security groups
    DB_delete($_TABLES['group_assignments'], 'ug_uid', $uid);
    // remove user information and preferences
    DB_delete($_TABLES['userprefs'], 'uid', $uid);
    DB_delete($_TABLES['userindex'], 'uid', $uid);
    DB_delete($_TABLES['usercomment'], 'uid', $uid);
    DB_delete($_TABLES['userinfo'], 'uid', $uid);
    // avoid having orphand stories/comments by making them anonymous posts
    DB_query("UPDATE {$_TABLES['comments']} SET uid = 1 WHERE uid = {$uid}");
    DB_query("UPDATE {$_TABLES['stories']} SET uid = 1 WHERE uid = {$uid}");
    DB_query("UPDATE {$_TABLES['stories']} SET owner_id = 1 WHERE owner_id = {$uid}");
    // delete story submissions
    DB_delete($_TABLES['storysubmission'], 'uid', $uid);
    // delete user photo, if enabled & exists
    if ($_CONF['allow_user_photo'] == 1) {
        $photo = DB_getItem($_TABLES['users'], 'photo', "uid = {$uid}");
        USER_deletePhoto($photo, false);
    }
    // in case the user owned any objects that require Admin access, assign
    // them to the Root user with the lowest uid
    $rootgroup = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'Root'");
    $result = DB_query("SELECT DISTINCT ug_uid FROM {$_TABLES['group_assignments']} WHERE ug_main_grp_id = {$rootgroup} ORDER BY ug_uid LIMIT 1");
    $A = DB_fetchArray($result);
    $rootuser = $A['ug_uid'];
    DB_query("UPDATE {$_TABLES['blocks']} SET owner_id = {$rootuser} WHERE owner_id = {$uid}");
    DB_query("UPDATE {$_TABLES['topics']} SET owner_id = {$rootuser} WHERE owner_id = {$uid}");
    // now delete the user itself
    DB_delete($_TABLES['users'], 'uid', $uid);
    return true;
}
 protected function _DBupdate_users($uid, $users)
 {
     global $_TABLES, $_CONF;
     $photo = '';
     $sql = "UPDATE {$_TABLES['users']} SET remoteusername = '******'remoteusername']) . "', remoteservice = '" . DB_escapeString($users['remoteservice']) . "', status = 3 ";
     if (!empty($users['remotephoto'])) {
         $save_img = $_CONF['path_images'] . 'userphotos/' . $uid;
         $imgsize = $this->_saveUserPhoto($users['remotephoto'], $save_img);
         if (!empty($imgsize)) {
             $ext = $this->_getImageExt($save_img);
             $image = $save_img . $ext;
             if (file_exists($image)) {
                 unlink($image);
             }
             rename($save_img, $image);
             $photo = $uid . $ext;
             $img_path = $this->_handleImageResize($_CONF['path_images'] . 'userphotos/' . $photo);
             // If nothing returned then image resize did not go right
             if (!empty($img_path)) {
                 if (!file_exists($img_path)) {
                     $photo = '';
                 }
             } else {
                 USER_deletePhoto($photo, false);
                 $photo = '';
             }
             $sql .= ", photo = '" . DB_escapeString($photo) . "'";
             // update photo even if blank just incase OAuth profile picture has been removed
         }
     }
     $sql .= " WHERE uid = " . (int) $uid;
     DB_query($sql);
 }
示例#6
0
/**
* Upload new photo, delete old photo
*
* @param    string  $delete_photo   'on': delete old photo
* @return   string                  filename of new photo (empty = no new photo)
*
*/
function handlePhotoUpload($delete_photo = '')
{
    global $_CONF, $_TABLES, $_USER, $LANG24;
    require_once $_CONF['path_system'] . 'classes/upload.class.php';
    $upload = new upload();
    if (!empty($_CONF['image_lib'])) {
        $upload->setAutomaticResize(true);
        if (isset($_CONF['debug_image_upload']) && $_CONF['debug_image_upload']) {
            $upload->setLogFile($_CONF['path'] . 'logs/error.log');
            $upload->setDebug(true);
        }
    }
    $upload->setAllowedMimeTypes(array('image/gif' => '.gif', 'image/jpeg' => '.jpg,.jpeg', 'image/pjpeg' => '.jpg,.jpeg', 'image/x-png' => '.png', 'image/png' => '.png'));
    if (!$upload->setPath($_CONF['path_images'] . 'userphotos')) {
        $display = COM_siteHeader('menu', $LANG24[30]);
        $display .= COM_showMessageText($upload->printErrors(false), $LANG24[30], true);
        $display .= COM_siteFooter();
        echo $display;
        exit;
        // don't return
    }
    $filename = '';
    if (!empty($delete_photo) && $delete_photo == 'on') {
        $delete_photo = true;
    } else {
        $delete_photo = false;
    }
    $curphoto = DB_getItem($_TABLES['users'], 'photo', "uid = {$_USER['uid']}");
    if (empty($curphoto)) {
        $delete_photo = false;
    }
    // see if user wants to upload a (new) photo
    $newphoto = $_FILES['photo'];
    if (!empty($newphoto['name'])) {
        $pos = strrpos($newphoto['name'], '.') + 1;
        $fextension = substr($newphoto['name'], $pos);
        $filename = $_USER['uid'] . '.' . $fextension;
        if (!empty($curphoto) && $filename != $curphoto) {
            $delete_photo = true;
        } else {
            $delete_photo = false;
        }
    }
    // delete old photo first
    if ($delete_photo) {
        USER_deletePhoto($curphoto);
    }
    // now do the upload
    if (!empty($filename)) {
        $upload->setFileNames($filename);
        $upload->setFieldName('photo');
        $upload->setPerms('0644');
        if ($_CONF['max_photo_width'] > 0 && $_CONF['max_photo_height'] > 0) {
            $upload->setMaxDimensions($_CONF['max_photo_width'], $_CONF['max_photo_height']);
        } else {
            $upload->setMaxDimensions($_CONF['max_image_width'], $_CONF['max_image_height']);
        }
        if ($_CONF['max_photo_size'] > 0) {
            $upload->setMaxFileSize($_CONF['max_photo_size']);
        } else {
            $upload->setMaxFileSize($_CONF['max_image_size']);
        }
        $upload->uploadFiles();
        if ($upload->areErrors()) {
            $display = COM_siteHeader('menu', $LANG24[30]);
            $display .= COM_showMessageText($upload->printErrors(false), $LANG24[30], true);
            $display .= COM_siteFooter();
            echo $display;
            exit;
            // don't return
        }
    } else {
        if (!$delete_photo && !empty($curphoto)) {
            $filename = $curphoto;
        }
    }
    return $filename;
}
示例#7
0
/**
* Merge User Accounts
*
* This validates the entered password and then merges a remote
* account with a local account.
*
* @return   string          HTML merge form if error, redirect on success
*
*/
function USER_mergeAccounts()
{
    global $_CONF, $_SYSTEM, $_TABLES, $_USER, $LANG04, $LANG12, $LANG20;
    $retval = '';
    $remoteUID = COM_applyFilter($_POST['remoteuid'], true);
    $localUID = COM_applyFilter($_POST['localuid'], true);
    $localpwd = $_POST['localp'];
    $localResult = DB_query("SELECT * FROM {$_TABLES['users']} WHERE uid=" . (int) $localUID);
    $localRow = DB_fetchArray($localResult);
    if (SEC_check_hash($localpwd, $localRow['passwd'])) {
        // password is valid
        $sql = "SELECT * FROM {$_TABLES['users']} WHERE remoteusername <> '' and email='" . DB_escapeString($localRow['email']) . "'";
        $result = DB_query($sql);
        $numRows = DB_numRows($result);
        if ($numRows == 1) {
            $remoteRow = DB_fetchArray($result);
            if ($remoteUID == $remoteRow['uid']) {
                $remoteUID = (int) $remoteRow['uid'];
                $remoteService = substr($remoteRow['remoteservice'], 6);
            } else {
                echo COM_refresh($_CONF['site_url'] . '/index.php');
            }
        } else {
            echo COM_refresh($_CONF['site_url'] . '/index.php');
        }
        $sql = "UPDATE {$_TABLES['users']} SET remoteusername='******'remoteusername']) . "'," . "remoteservice='" . DB_escapeString($remoteRow['remoteservice']) . "', " . "account_type=3 " . " WHERE uid=" . (int) $localUID;
        DB_query($sql);
        $_USER['uid'] = $localRow['uid'];
        $local_login = true;
        SESS_completeLogin($localUID);
        $_GROUPS = SEC_getUserGroups($_USER['uid']);
        $_RIGHTS = explode(',', SEC_getUserPermissions());
        if ($_SYSTEM['admin_session'] > 0 && $local_login) {
            if (SEC_isModerator() || SEC_hasRights('story.edit,block.edit,topic.edit,user.edit,plugin.edit,user.mail,syndication.edit', 'OR') || count(PLG_getAdminOptions()) > 0) {
                $admin_token = SEC_createTokenGeneral('administration', $_SYSTEM['admin_session']);
                SEC_setCookie('token', $admin_token, 0, $_CONF['cookie_path'], $_CONF['cookiedomain'], $_CONF['cookiesecure'], true);
            }
        }
        COM_resetSpeedlimit('login');
        // log the user out
        SESS_endUserSession($remoteUID);
        // Let plugins know a user is being merged
        PLG_moveUser($remoteUID, $_USER['uid']);
        // Ok, now delete everything related to this user
        // let plugins update their data for this user
        PLG_deleteUser($remoteUID);
        if (function_exists('CUSTOM_userDeleteHook')) {
            CUSTOM_userDeleteHook($remoteUID);
        }
        // Call custom account profile delete function if enabled and exists
        if ($_CONF['custom_registration'] && function_exists('CUSTOM_userDelete')) {
            CUSTOM_userDelete($remoteUID);
        }
        // remove from all security groups
        DB_delete($_TABLES['group_assignments'], 'ug_uid', $remoteUID);
        // remove user information and preferences
        DB_delete($_TABLES['userprefs'], 'uid', $remoteUID);
        DB_delete($_TABLES['userindex'], 'uid', $remoteUID);
        DB_delete($_TABLES['usercomment'], 'uid', $remoteUID);
        DB_delete($_TABLES['userinfo'], 'uid', $remoteUID);
        // delete user photo, if enabled & exists
        if ($_CONF['allow_user_photo'] == 1) {
            $photo = DB_getItem($_TABLES['users'], 'photo', "uid = {$remoteUID}");
            USER_deletePhoto($photo, false);
        }
        // delete subscriptions
        DB_delete($_TABLES['subscriptions'], 'uid', $remoteUID);
        // in case the user owned any objects that require Admin access, assign
        // them to the Root user with the lowest uid
        $rootgroup = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'Root'");
        $result = DB_query("SELECT DISTINCT ug_uid FROM {$_TABLES['group_assignments']} WHERE ug_main_grp_id = '{$rootgroup}' ORDER BY ug_uid LIMIT 1");
        $A = DB_fetchArray($result);
        $rootuser = $A['ug_uid'];
        if ($rootuser == '' || $rootuser < 2) {
            $rootuser = 2;
        }
        DB_query("UPDATE {$_TABLES['blocks']} SET owner_id = {$rootuser} WHERE owner_id = {$remoteUID}");
        DB_query("UPDATE {$_TABLES['topics']} SET owner_id = {$rootuser} WHERE owner_id = {$remoteUID}");
        // now delete the user itself
        DB_delete($_TABLES['users'], 'uid', $remoteUID);
    } else {
        // invalid password - let's try one more time
        // need to set speed limit and give them 3 tries
        COM_clearSpeedlimit($_CONF['login_speedlimit'], 'merge');
        $last = COM_checkSpeedlimit('merge', 4);
        if ($last > 0) {
            COM_setMsg($LANG04[190], 'error');
            echo COM_refresh($_CONF['site_url'] . '/users.php');
        } else {
            COM_updateSpeedlimit('merge');
            USER_mergeAccountScreen($remoteUID, $localUID, $LANG20[3]);
        }
        return $retval;
    }
    // can't use COM_setMsg here since the session is being destroyed.
    echo COM_refresh($_CONF['site_url'] . '/index.php?msg=522');
}