/**
  * @task edit
  */
 public function changeUsername(PhabricatorUser $user, $username)
 {
     $actor = $this->requireActor();
     if (!$user->getID()) {
         throw new Exception("User has not been created yet!");
     }
     if (!PhabricatorUser::validateUsername($username)) {
         $valid = PhabricatorUser::describeValidUsername();
         throw new Exception("Username is invalid! {$valid}");
     }
     $old_username = $user->getUsername();
     $user->openTransaction();
     $user->reload();
     $user->setUsername($username);
     try {
         $user->save();
     } catch (AphrontQueryDuplicateKeyException $ex) {
         $user->setUsername($old_username);
         $user->killTransaction();
         throw $ex;
     }
     $log = PhabricatorUserLog::newLog($this->actor, $user, PhabricatorUserLog::ACTION_CHANGE_USERNAME);
     $log->setOldValue($old_username);
     $log->setNewValue($username);
     $log->save();
     $user->saveTransaction();
     $user->sendUsernameChangeEmail($actor, $old_username);
 }
 public function processRequest()
 {
     $provider = $this->getOAuthProvider();
     $oauth_info = $this->getOAuthInfo();
     $request = $this->getRequest();
     $errors = array();
     $e_username = true;
     $e_email = true;
     $e_realname = true;
     $user = new PhabricatorUser();
     $user->setUsername($provider->retrieveUserAccountName());
     $user->setRealName($provider->retrieveUserRealName());
     $user->setEmail($provider->retrieveUserEmail());
     if ($request->isFormPost()) {
         $user->setUsername($request->getStr('username'));
         $username = $user->getUsername();
         if (!strlen($user->getUsername())) {
             $e_username = '******';
             $errors[] = 'Username is required.';
         } else {
             if (!PhabricatorUser::validateUsername($username)) {
                 $e_username = '******';
                 $errors[] = 'Username must consist of only numbers and letters.';
             } else {
                 $e_username = null;
             }
         }
         if ($user->getEmail() === null) {
             $user->setEmail($request->getStr('email'));
             if (!strlen($user->getEmail())) {
                 $e_email = 'Required';
                 $errors[] = 'Email is required.';
             } else {
                 $e_email = null;
             }
         }
         if (!strlen($user->getRealName())) {
             $user->setRealName($request->getStr('realname'));
             if (!strlen($user->getRealName())) {
                 $e_realname = 'Required';
                 $errors[] = 'Real name is required.';
             } else {
                 $e_realname = null;
             }
         }
         if (!$errors) {
             $image = $provider->retrieveUserProfileImage();
             if ($image) {
                 $file = PhabricatorFile::newFromFileData($image, array('name' => $provider->getProviderKey() . '-profile.jpg', 'authorPHID' => $user->getPHID()));
                 $user->setProfileImagePHID($file->getPHID());
             }
             try {
                 $user->save();
                 $oauth_info->setUserID($user->getID());
                 $oauth_info->save();
                 $session_key = $user->establishSession('web');
                 $request->setCookie('phusr', $user->getUsername());
                 $request->setCookie('phsid', $session_key);
                 return id(new AphrontRedirectResponse())->setURI('/');
             } catch (AphrontQueryDuplicateKeyException $exception) {
                 $same_username = id(new PhabricatorUser())->loadOneWhere('userName = %s', $user->getUserName());
                 $same_email = id(new PhabricatorUser())->loadOneWhere('email = %s', $user->getEmail());
                 if ($same_username) {
                     $e_username = '******';
                     $errors[] = 'That username or email is not unique.';
                 } else {
                     if ($same_email) {
                         $e_email = 'Duplicate';
                         $errors[] = 'That email is not unique.';
                     } else {
                         throw $exception;
                     }
                 }
             }
         }
     }
     $error_view = null;
     if ($errors) {
         $error_view = new AphrontErrorView();
         $error_view->setTitle('Registration Failed');
         $error_view->setErrors($errors);
     }
     // Strip the URI down to the path, because otherwise we'll trigger
     // external CSRF protection (by having a protocol in the form "action")
     // and generate a form with no CSRF token.
     $action_uri = new PhutilURI($provider->getRedirectURI());
     $action_path = $action_uri->getPath();
     $form = new AphrontFormView();
     $form->addHiddenInput('token', $provider->getAccessToken())->addHiddenInput('expires', $oauth_info->getTokenExpires())->addHiddenInput('state', $this->getOAuthState())->setUser($request->getUser())->setAction($action_path)->appendChild(id(new AphrontFormTextControl())->setLabel('Username')->setName('username')->setValue($user->getUsername())->setError($e_username));
     if ($provider->retrieveUserEmail() === null) {
         $form->appendChild(id(new AphrontFormTextControl())->setLabel('Email')->setName('email')->setValue($request->getStr('email'))->setError($e_email));
     }
     if ($provider->retrieveUserRealName() === null) {
         $form->appendChild(id(new AphrontFormTextControl())->setLabel('Real Name')->setName('realname')->setValue($request->getStr('realname'))->setError($e_realname));
     }
     $form->appendChild(id(new AphrontFormSubmitControl())->setValue('Create Account'));
     $panel = new AphrontPanelView();
     $panel->setHeader('Create New Account');
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     $panel->appendChild($form);
     return $this->buildStandardPageResponse(array($error_view, $panel), array('title' => 'Create New Account'));
 }
 /**
  * Verify a user's email address.
  *
  * This verifies an individual email address. If the address is the user's
  * primary address and their account was not previously verified, their
  * account is marked as email verified.
  *
  * @task email
  */
 public function verifyEmail(PhabricatorUser $user, PhabricatorUserEmail $email)
 {
     $actor = $this->requireActor();
     if (!$user->getID()) {
         throw new Exception('User has not been created yet!');
     }
     if (!$email->getID()) {
         throw new Exception('Email has not been created yet!');
     }
     $user->openTransaction();
     $user->beginWriteLocking();
     $user->reload();
     $email->reload();
     if ($email->getUserPHID() != $user->getPHID()) {
         throw new Exception(pht('User does not own email!'));
     }
     if (!$email->getIsVerified()) {
         $email->setIsVerified(1);
         $email->save();
         $log = PhabricatorUserLog::initializeNewLog($actor, $user->getPHID(), PhabricatorUserLog::ACTION_EMAIL_VERIFY);
         $log->setNewValue($email->getAddress());
         $log->save();
     }
     if (!$user->getIsEmailVerified()) {
         // If the user just verified their primary email address, mark their
         // account as email verified.
         $user_primary = $user->loadPrimaryEmail();
         if ($user_primary->getID() == $email->getID()) {
             $user->setIsEmailVerified(1);
             $user->save();
         }
     }
     $user->endWriteLocking();
     $user->saveTransaction();
 }
 private function processBasicRequest(PhabricatorUser $user)
 {
     $request = $this->getRequest();
     $admin = $request->getUser();
     $e_username = true;
     $e_realname = true;
     $e_email = true;
     $errors = array();
     $welcome_checked = true;
     $request = $this->getRequest();
     if ($request->isFormPost()) {
         $welcome_checked = $request->getInt('welcome');
         if (!$user->getID()) {
             $user->setUsername($request->getStr('username'));
             $user->setEmail($request->getStr('email'));
             if ($request->getStr('role') == 'agent') {
                 $user->setIsSystemAgent(true);
             }
         }
         $user->setRealName($request->getStr('realname'));
         if (!strlen($user->getUsername())) {
             $errors[] = "Username is required.";
             $e_username = '******';
         } else {
             if (!PhabricatorUser::validateUsername($user->getUsername())) {
                 $errors[] = "Username must consist of only numbers and letters.";
                 $e_username = '******';
             } else {
                 $e_username = null;
             }
         }
         if (!strlen($user->getRealName())) {
             $errors[] = 'Real name is required.';
             $e_realname = 'Required';
         } else {
             $e_realname = null;
         }
         if (!strlen($user->getEmail())) {
             $errors[] = 'Email is required.';
             $e_email = 'Required';
         } else {
             $e_email = null;
         }
         if (!$errors) {
             try {
                 $is_new = !$user->getID();
                 $user->save();
                 if ($is_new) {
                     $log = PhabricatorUserLog::newLog($admin, $user, PhabricatorUserLog::ACTION_CREATE);
                     $log->save();
                     if ($welcome_checked) {
                         $user->sendWelcomeEmail($admin);
                     }
                 }
                 $response = id(new AphrontRedirectResponse())->setURI('/people/edit/' . $user->getID() . '/?saved=true');
                 return $response;
             } catch (AphrontQueryDuplicateKeyException $ex) {
                 $errors[] = 'Username and email must be unique.';
                 $same_username = id(new PhabricatorUser())->loadOneWhere('username = %s', $user->getUsername());
                 $same_email = id(new PhabricatorUser())->loadOneWhere('email = %s', $user->getEmail());
                 if ($same_username) {
                     $e_username = '******';
                 }
                 if ($same_email) {
                     $e_email = 'Duplicate';
                 }
             }
         }
     }
     $error_view = null;
     if ($errors) {
         $error_view = id(new AphrontErrorView())->setTitle('Form Errors')->setErrors($errors);
     }
     $form = new AphrontFormView();
     $form->setUser($admin);
     if ($user->getID()) {
         $form->setAction('/people/edit/' . $user->getID() . '/');
     } else {
         $form->setAction('/people/edit/');
     }
     if ($user->getID()) {
         $is_immutable = true;
     } else {
         $is_immutable = false;
     }
     $form->appendChild(id(new AphrontFormTextControl())->setLabel('Username')->setName('username')->setValue($user->getUsername())->setError($e_username)->setDisabled($is_immutable)->setCaption('Usernames are permanent and can not be changed later!'))->appendChild(id(new AphrontFormTextControl())->setLabel('Real Name')->setName('realname')->setValue($user->getRealName())->setError($e_realname))->appendChild(id(new AphrontFormTextControl())->setLabel('Email')->setName('email')->setDisabled($is_immutable)->setValue($user->getEmail())->setError($e_email))->appendChild($this->getRoleInstructions());
     if (!$user->getID()) {
         $form->appendChild(id(new AphrontFormSelectControl())->setLabel('Role')->setName('role')->setValue('user')->setOptions(array('user' => 'Normal User', 'agent' => 'System Agent'))->setCaption('You can create a "system agent" account for bots, scripts, ' . 'etc.'))->appendChild(id(new AphrontFormCheckboxControl())->addCheckbox('welcome', 1, 'Send "Welcome to Phabricator" email.', $welcome_checked));
     } else {
         $form->appendChild(id(new AphrontFormStaticControl())->setLabel('Role')->setValue($user->getIsSystemAgent() ? 'System Agent' : 'Normal User'));
     }
     $form->appendChild(id(new AphrontFormSubmitControl())->setValue('Save'));
     $panel = new AphrontPanelView();
     if ($user->getID()) {
         $panel->setHeader('Edit User');
     } else {
         $panel->setHeader('Create New User');
     }
     $panel->appendChild($form);
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     return array($error_view, $panel);
 }
// it.
phutil_passthru('stty -echo');
$password = phutil_console_prompt("Enter a password for this user [blank to leave unchanged]:");
phutil_passthru('stty echo');
if (strlen($password)) {
    $changed_pass = $password;
}
$is_admin = $user->getIsAdmin();
$set_admin = phutil_console_confirm('Should this user be an administrator?', $default_no = !$is_admin);
$user->setIsAdmin($set_admin);
echo "\n\nACCOUNT SUMMARY\n\n";
$tpl = "%12s   %-30s   %-30s\n";
printf($tpl, null, 'OLD VALUE', 'NEW VALUE');
printf($tpl, 'Username', $original->getUsername(), $user->getUsername());
printf($tpl, 'Real Name', $original->getRealName(), $user->getRealName());
printf($tpl, 'Email', $original->getEmail(), $user->getEmail());
printf($tpl, 'Password', null, $changed_pass !== false ? 'Updated' : 'Unchanged');
printf($tpl, 'Admin', $original->getIsAdmin() ? 'Y' : 'N', $user->getIsAdmin() ? 'Y' : 'N');
echo "\n";
if (!phutil_console_confirm("Save these changes?", $default_no = false)) {
    echo "Cancelled.\n";
    exit(1);
}
$user->save();
if ($changed_pass !== false) {
    // This must happen after saving the user because we use their PHID as a
    // component of the password hash.
    $user->setPassword($changed_pass);
    $user->save();
}
echo "Saved changes.\n";
    private function processBasicRequest(PhabricatorUser $user)
    {
        $request = $this->getRequest();
        $admin = $request->getUser();
        $e_username = true;
        $e_realname = true;
        $e_email = true;
        $errors = array();
        $welcome_checked = true;
        $request = $this->getRequest();
        if ($request->isFormPost()) {
            $welcome_checked = $request->getInt('welcome');
            if (!$user->getID()) {
                $user->setUsername($request->getStr('username'));
                $user->setEmail($request->getStr('email'));
                if ($request->getStr('role') == 'agent') {
                    $user->setIsSystemAgent(true);
                }
            }
            $user->setRealName($request->getStr('realname'));
            if (!strlen($user->getUsername())) {
                $errors[] = "Username is required.";
                $e_username = '******';
            } else {
                if (!preg_match('/^[a-z0-9]+$/', $user->getUsername())) {
                    $errors[] = "Username must consist of only numbers and letters.";
                    $e_username = '******';
                } else {
                    $e_username = null;
                }
            }
            if (!strlen($user->getRealName())) {
                $errors[] = 'Real name is required.';
                $e_realname = 'Required';
            } else {
                $e_realname = null;
            }
            if (!strlen($user->getEmail())) {
                $errors[] = 'Email is required.';
                $e_email = 'Required';
            } else {
                $e_email = null;
            }
            if (!$errors) {
                try {
                    $is_new = !$user->getID();
                    $user->save();
                    if ($is_new) {
                        $log = PhabricatorUserLog::newLog($admin, $user, PhabricatorUserLog::ACTION_CREATE);
                        $log->save();
                        if ($welcome_checked) {
                            $admin_username = $admin->getUserName();
                            $admin_realname = $admin->getRealName();
                            $user_username = $user->getUserName();
                            $base_uri = PhabricatorEnv::getProductionURI('/');
                            $uri = $user->getEmailLoginURI();
                            $body = <<<EOBODY
Welcome to Phabricator!

{$admin_username} ({$admin_realname}) has created an account for you.

  Username: {$user_username}

To login to Phabricator, follow this link and set a password:

  {$uri}

After you have set a password, you can login in the future by going here:

  {$base_uri}

Love,
Phabricator

EOBODY;
                            $mail = id(new PhabricatorMetaMTAMail())->addTos(array($user->getPHID()))->setSubject('[Phabricator] Welcome to Phabricator')->setBody($body)->setFrom($admin->getPHID())->saveAndSend();
                        }
                    }
                    $response = id(new AphrontRedirectResponse())->setURI('/people/edit/' . $user->getID() . '/?saved=true');
                    return $response;
                } catch (AphrontQueryDuplicateKeyException $ex) {
                    $errors[] = 'Username and email must be unique.';
                    $same_username = id(new PhabricatorUser())->loadOneWhere('username = %s', $user->getUsername());
                    $same_email = id(new PhabricatorUser())->loadOneWhere('email = %s', $user->getEmail());
                    if ($same_username) {
                        $e_username = '******';
                    }
                    if ($same_email) {
                        $e_email = 'Duplicate';
                    }
                }
            }
        }
        $error_view = null;
        if ($errors) {
            $error_view = id(new AphrontErrorView())->setTitle('Form Errors')->setErrors($errors);
        }
        $form = new AphrontFormView();
        $form->setUser($admin);
        if ($user->getID()) {
            $form->setAction('/people/edit/' . $user->getID() . '/');
        } else {
            $form->setAction('/people/edit/');
        }
        if ($user->getID()) {
            $is_immutable = true;
        } else {
            $is_immutable = false;
        }
        $form->appendChild(id(new AphrontFormTextControl())->setLabel('Username')->setName('username')->setValue($user->getUsername())->setError($e_username)->setDisabled($is_immutable)->setCaption('Usernames are permanent and can not be changed later!'))->appendChild(id(new AphrontFormTextControl())->setLabel('Real Name')->setName('realname')->setValue($user->getRealName())->setError($e_realname))->appendChild(id(new AphrontFormTextControl())->setLabel('Email')->setName('email')->setDisabled($is_immutable)->setValue($user->getEmail())->setError($e_email));
        if (!$user->getID()) {
            $form->appendChild(id(new AphrontFormSelectControl())->setLabel('Role')->setName('role')->setValue('user')->setOptions(array('user' => 'Normal User', 'agent' => 'System Agent'))->setCaption('You can create a "system agent" account for bots, scripts, ' . 'etc.'))->appendChild(id(new AphrontFormCheckboxControl())->addCheckbox('welcome', 1, 'Send "Welcome to Phabricator" email.', $welcome_checked));
        } else {
            $form->appendChild(id(new AphrontFormStaticControl())->setLabel('Role')->setValue($user->getIsSystemAgent() ? 'System Agent' : 'Normal User'));
        }
        $form->appendChild(id(new AphrontFormSubmitControl())->setValue('Save'));
        $panel = new AphrontPanelView();
        if ($user->getID()) {
            $panel->setHeader('Edit User');
        } else {
            $panel->setHeader('Create New User');
        }
        $panel->appendChild($form);
        $panel->setWidth(AphrontPanelView::WIDTH_FORM);
        return array($error_view, $panel);
    }