Page MenuHomestyx hydra

No OneTemporary

diff --git a/src/applications/people/PhabricatorPeopleQuery.php b/src/applications/people/PhabricatorPeopleQuery.php
index 215eafbcec..0da8fb731d 100644
--- a/src/applications/people/PhabricatorPeopleQuery.php
+++ b/src/applications/people/PhabricatorPeopleQuery.php
@@ -1,108 +1,156 @@
<?php
final class PhabricatorPeopleQuery extends PhabricatorOffsetPagedQuery {
private $usernames;
private $realnames;
private $emails;
private $phids;
private $ids;
private $needPrimaryEmail;
+ private $needProfile;
+ private $needProfileImage;
public function withIds(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPhids(array $phids) {
$this->phids = $phids;
return $this;
}
public function withEmails(array $emails) {
$this->emails = $emails;
return $this;
}
public function withRealnames(array $realnames) {
$this->realnames = $realnames;
return $this;
}
public function withUsernames(array $usernames) {
$this->usernames = $usernames;
return $this;
}
public function needPrimaryEmail($need) {
$this->needPrimaryEmail = $need;
return $this;
}
+ public function needProfile($need) {
+ $this->needProfile = $need;
+ return $this;
+ }
+
+ public function needProfileImage($need) {
+ $this->needProfileImage = $need;
+ return $this;
+ }
+
public function execute() {
$table = new PhabricatorUser();
$conn_r = $table->establishConnection('r');
$joins_clause = $this->buildJoinsClause($conn_r);
$where_clause = $this->buildWhereClause($conn_r);
$limit_clause = $this->buildLimitClause($conn_r);
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T user %Q %Q %Q',
$table->getTableName(),
$joins_clause,
$where_clause,
$limit_clause);
if ($this->needPrimaryEmail) {
$table->putInSet(new LiskDAOSet());
}
$users = $table->loadAllFromArray($data);
+
+ if ($this->needProfile) {
+ $user_list = mpull($users, null, 'getPHID');
+ $profiles = new PhabricatorUserProfile();
+ $profiles = $profiles->loadAllWhere('userPHID IN (%Ls)',
+ array_keys($user_list));
+
+ $profiles = mpull($profiles, null, 'getUserPHID');
+ foreach ($user_list as $user_phid => $user) {
+ $profile = idx($profiles, $user_phid);
+ if (!$profile) {
+ $profile = new PhabricatorUserProfile();
+ $profile->setUserPHID($user_phid);
+ }
+
+ $user->attachUserProfile($profile);
+ }
+ }
+
+ if ($this->needProfileImage) {
+ // Change this once we migrate this to CursorPagedPolicyAwareQuery
+ $files = id(new PhabricatorFile())
+ ->loadAllWhere('phid IN (%Ls)', mpull($users, 'getProfileImagePHID'));
+ $files = mpull($files, null, 'getPHID');
+ foreach ($users as $user) {
+ $image_phid = $user->getProfileImagePHID();
+ if (isset($files[$image_phid])) {
+ $profile_image_uri = $files[$image_phid]->getBestURI();
+ } else {
+ $profile_image_uri = PhabricatorUser::getDefaultProfileImageURI();
+ }
+ $user->attachProfileImageURI($profile_image_uri);
+ }
+ }
+
return $users;
}
private function buildJoinsClause($conn_r) {
$joins = array();
if ($this->emails) {
$email_table = new PhabricatorUserEmail();
$joins[] = qsprintf(
$conn_r,
'JOIN %T email ON email.userPHID = user.PHID',
$email_table->getTableName());
}
$joins = implode(' ', $joins);
return $joins;
}
private function buildWhereClause($conn_r) {
$where = array();
if ($this->usernames) {
$where[] = qsprintf($conn_r,
'user.userName IN (%Ls)',
$this->usernames);
}
if ($this->emails) {
$where[] = qsprintf($conn_r,
'email.address IN (%Ls)',
$this->emails);
}
if ($this->realnames) {
$where[] = qsprintf($conn_r,
'user.realName IN (%Ls)',
$this->realnames);
}
if ($this->phids) {
$where[] = qsprintf($conn_r,
'user.phid IN (%Ls)',
$this->phids);
}
if ($this->ids) {
$where[] = qsprintf($conn_r,
'user.id IN (%Ld)',
$this->ids);
}
return $this->formatWhereClause($where);
}
+
}
diff --git a/src/applications/people/controller/PhabricatorPeopleEditController.php b/src/applications/people/controller/PhabricatorPeopleEditController.php
index ba19ba0b19..5dcefe17a5 100644
--- a/src/applications/people/controller/PhabricatorPeopleEditController.php
+++ b/src/applications/people/controller/PhabricatorPeopleEditController.php
@@ -1,842 +1,838 @@
<?php
final class PhabricatorPeopleEditController
extends PhabricatorPeopleController {
private $id;
private $view;
public function willProcessRequest(array $data) {
$this->id = idx($data, 'id');
$this->view = idx($data, 'view');
}
public function processRequest() {
$request = $this->getRequest();
$admin = $request->getUser();
$crumbs = $this->buildApplicationCrumbs($this->buildSideNavView());
if ($this->id) {
$user = id(new PhabricatorUser())->load($this->id);
if (!$user) {
return new Aphront404Response();
}
$base_uri = '/people/edit/'.$user->getID().'/';
$crumbs->addCrumb(
id(new PhabricatorCrumbView())
->setName(pht('Edit User'))
->setHref('/people/edit/'));
$crumbs->addCrumb(
id(new PhabricatorCrumbView())
->setName($user->getFullName())
->setHref($base_uri));
} else {
$user = new PhabricatorUser();
$base_uri = '/people/edit/';
$crumbs->addCrumb(
id(new PhabricatorCrumbView())
->setName(pht('Create New User'))
->setHref($base_uri));
}
$nav = new AphrontSideNavFilterView();
$nav->setBaseURI(new PhutilURI($base_uri));
$nav->addLabel(pht('User Information'));
$nav->addFilter('basic', pht('Basic Information'));
$nav->addFilter('role', pht('Edit Roles'));
$nav->addFilter('cert', pht('Conduit Certificate'));
$nav->addFilter('profile',
pht('View Profile'), '/p/'.$user->getUsername().'/');
$nav->addLabel(pht('Special'));
$nav->addFilter('rename', pht('Change Username'));
if ($user->getIsSystemAgent()) {
$nav->addFilter('picture', pht('Set Account Picture'));
}
$nav->addFilter('delete', pht('Delete User'));
if (!$user->getID()) {
$this->view = 'basic';
}
$view = $nav->selectFilter($this->view, 'basic');
$content = array();
if ($request->getStr('saved')) {
$notice = new AphrontErrorView();
$notice->setSeverity(AphrontErrorView::SEVERITY_NOTICE);
$notice->setTitle(pht('Changes Saved'));
$notice->appendChild(
phutil_tag('p', array(), pht('Your changes were saved.')));
$content[] = $notice;
}
switch ($view) {
case 'basic':
$response = $this->processBasicRequest($user);
break;
case 'role':
$response = $this->processRoleRequest($user);
break;
case 'cert':
$response = $this->processCertificateRequest($user);
break;
case 'rename':
$response = $this->processRenameRequest($user);
break;
case 'picture':
$response = $this->processSetAccountPicture($user);
break;
case 'delete':
$response = $this->processDeleteRequest($user);
break;
default:
return new Aphront404Response();
}
if ($response instanceof AphrontResponse) {
return $response;
}
$content[] = $response;
if ($user->getID()) {
$nav->appendChild($content);
} else {
$nav = $this->buildSideNavView();
$nav->selectFilter('edit');
$nav->appendChild($content);
}
$nav->setCrumbs($crumbs);
return $this->buildApplicationPage(
$nav,
array(
'title' => pht('Edit User'),
'device' => true,
));
}
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;
$new_email = null;
$request = $this->getRequest();
if ($request->isFormPost()) {
$welcome_checked = $request->getInt('welcome');
$is_new = !$user->getID();
if ($is_new) {
$user->setUsername($request->getStr('username'));
$new_email = $request->getStr('email');
if (!strlen($new_email)) {
$errors[] = pht('Email is required.');
$e_email = pht('Required');
} else if (!PhabricatorUserEmail::isAllowedAddress($new_email)) {
$e_email = pht('Invalid');
$errors[] = PhabricatorUserEmail::describeAllowedAddresses();
} else {
$e_email = null;
}
}
$user->setRealName($request->getStr('realname'));
if (!strlen($user->getUsername())) {
$errors[] = pht("Username is required.");
$e_username = pht('Required');
} else if (!PhabricatorUser::validateUsername($user->getUsername())) {
$errors[] = PhabricatorUser::describeValidUsername();
$e_username = pht('Invalid');
} else {
$e_username = null;
}
if (!strlen($user->getRealName())) {
$errors[] = pht('Real name is required.');
$e_realname = pht('Required');
} else {
$e_realname = null;
}
if (!$errors) {
try {
if (!$is_new) {
id(new PhabricatorUserEditor())
->setActor($admin)
->updateUser($user);
} else {
$email = id(new PhabricatorUserEmail())
->setAddress($new_email)
->setIsVerified(0);
id(new PhabricatorUserEditor())
->setActor($admin)
->createNewUser($user, $email);
if ($request->getStr('role') == 'agent') {
id(new PhabricatorUserEditor())
->setActor($admin)
->makeSystemAgentUser($user, true);
}
}
if ($welcome_checked) {
$user->sendWelcomeEmail($admin);
}
$response = id(new AphrontRedirectResponse())
->setURI('/people/edit/'.$user->getID().'/?saved=true');
return $response;
} catch (AphrontQueryDuplicateKeyException $ex) {
$errors[] = pht('Username and email must be unique.');
$same_username = id(new PhabricatorUser())
->loadOneWhere('username = %s', $user->getUsername());
$same_email = id(new PhabricatorUserEmail())
->loadOneWhere('address = %s', $new_email);
if ($same_username) {
$e_username = pht('Duplicate');
}
if ($same_email) {
$e_email = pht('Duplicate');
}
}
}
}
$error_view = null;
if ($errors) {
$error_view = id(new AphrontErrorView())
->setTitle(pht('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(pht('Username'))
->setName('username')
->setValue($user->getUsername())
->setError($e_username)
->setDisabled($is_immutable))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Real Name'))
->setName('realname')
->setValue($user->getRealName())
->setError($e_realname));
if (!$user->getID()) {
$form->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Email'))
->setName('email')
->setDisabled($is_immutable)
->setValue($new_email)
->setCaption(PhabricatorUserEmail::describeAllowedAddresses())
->setError($e_email));
} else {
$email = $user->loadPrimaryEmail();
if ($email) {
$status = $email->getIsVerified() ?
pht('Verified') : pht('Unverified');
} else {
$status = pht('No Email Address');
}
$form->appendChild(
id(new AphrontFormStaticControl())
->setLabel(pht('Email'))
->setValue($status));
$form->appendChild(
id(new AphrontFormCheckboxControl())
->addCheckbox(
'welcome',
1,
pht('Re-send "Welcome to Phabricator" email.'),
false));
}
$form->appendChild($this->getRoleInstructions());
if (!$user->getID()) {
$form
->appendChild(
id(new AphrontFormSelectControl())
->setLabel(pht('Role'))
->setName('role')
->setValue('user')
->setOptions(
array(
'user' => pht('Normal User'),
'agent' => pht('System Agent'),
))
->setCaption(
pht('You can create a "system agent" account for bots, '.
'scripts, etc.')))
->appendChild(
id(new AphrontFormCheckboxControl())
->addCheckbox(
'welcome',
1,
pht('Send "Welcome to Phabricator" email.'),
$welcome_checked));
} else {
$roles = array();
if ($user->getIsSystemAgent()) {
$roles[] = pht('System Agent');
}
if ($user->getIsAdmin()) {
$roles[] = pht('Admin');
}
if ($user->getIsDisabled()) {
$roles[] = pht('Disabled');
}
if (!$roles) {
$roles[] = pht('Normal User');
}
$roles = implode(', ', $roles);
$form->appendChild(
id(new AphrontFormStaticControl())
->setLabel('Roles')
->setValue($roles));
}
$form
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Save')));
$panel = new AphrontPanelView();
if ($user->getID()) {
$panel->setHeader(pht('Edit User'));
} else {
$panel->setHeader(pht('Create New User'));
}
$panel->appendChild($form);
$panel->setNoBackground();
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
return array($error_view, $panel);
}
private function processRoleRequest(PhabricatorUser $user) {
$request = $this->getRequest();
$admin = $request->getUser();
$is_self = ($user->getID() == $admin->getID());
$errors = array();
if ($request->isFormPost()) {
$log_template = PhabricatorUserLog::newLog(
$admin,
$user,
null);
$logs = array();
if ($is_self) {
$errors[] = pht("You can not edit your own role.");
} else {
$new_admin = (bool)$request->getBool('is_admin');
$old_admin = (bool)$user->getIsAdmin();
if ($new_admin != $old_admin) {
id(new PhabricatorUserEditor())
->setActor($admin)
->makeAdminUser($user, $new_admin);
}
$new_disabled = (bool)$request->getBool('is_disabled');
$old_disabled = (bool)$user->getIsDisabled();
if ($new_disabled != $old_disabled) {
id(new PhabricatorUserEditor())
->setActor($admin)
->disableUser($user, $new_disabled);
}
}
if (!$errors) {
return id(new AphrontRedirectResponse())
->setURI($request->getRequestURI()->alter('saved', 'true'));
}
}
$error_view = null;
if ($errors) {
$error_view = id(new AphrontErrorView())
->setTitle(pht('Form Errors'))
->setErrors($errors);
}
$form = id(new AphrontFormView())
->setUser($admin)
->setAction($request->getRequestURI()->alter('saved', null));
if ($is_self) {
$inst = pht('NOTE: You can not edit your own role.');
$form->appendChild(hsprintf(
'<p class="aphront-form-instructions">%s</p>', $inst));
}
$form
->appendChild($this->getRoleInstructions())
->appendChild(
id(new AphrontFormCheckboxControl())
->addCheckbox(
'is_admin',
1,
pht('Administrator'),
$user->getIsAdmin())
->setDisabled($is_self))
->appendChild(
id(new AphrontFormCheckboxControl())
->addCheckbox(
'is_disabled',
1,
pht('Disabled'),
$user->getIsDisabled())
->setDisabled($is_self))
->appendChild(
id(new AphrontFormCheckboxControl())
->addCheckbox(
'is_agent',
1,
pht('System Agent (Bot/Script User)'),
$user->getIsSystemAgent())
->setDisabled(true));
if (!$is_self) {
$form
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Edit Role')));
}
$panel = new AphrontPanelView();
$panel->setHeader(pht('Edit Role'));
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setNoBackground();
$panel->appendChild($form);
return array($error_view, $panel);
}
private function processCertificateRequest($user) {
$request = $this->getRequest();
$admin = $request->getUser();
$inst = pht('You can use this certificate '.
'to write scripts or bots which interface with Phabricator over '.
'Conduit.');
$form = new AphrontFormView();
$form
->setUser($admin)
->setAction($request->getRequestURI())
->appendChild(hsprintf(
'<p class="aphront-form-instructions">%s</p>', $inst));
if ($user->getIsSystemAgent()) {
$form
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Username'))
->setValue($user->getUsername()))
->appendChild(
id(new AphrontFormTextAreaControl())
->setLabel(pht('Certificate'))
->setValue($user->getConduitCertificate()));
} else {
$form->appendChild(
id(new AphrontFormStaticControl())
->setLabel(pht('Certificate'))
->setValue(
pht('You may only view the certificates of System Agents.')));
}
$panel = new AphrontPanelView();
$panel->setHeader(pht('Conduit Certificate'));
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setNoBackground();
$panel->appendChild($form);
return array($panel);
}
private function processRenameRequest(PhabricatorUser $user) {
$request = $this->getRequest();
$admin = $request->getUser();
$e_username = true;
$username = $user->getUsername();
$errors = array();
if ($request->isFormPost()) {
$username = $request->getStr('username');
if (!strlen($username)) {
$e_username = pht('Required');
$errors[] = pht('New username is required.');
} else if ($username == $user->getUsername()) {
$e_username = pht('Invalid');
$errors[] = pht('New username must be different from old username.');
} else if (!PhabricatorUser::validateUsername($username)) {
$e_username = pht('Invalid');
$errors[] = PhabricatorUser::describeValidUsername();
}
if (!$errors) {
try {
id(new PhabricatorUserEditor())
->setActor($admin)
->changeUsername($user, $username);
return id(new AphrontRedirectResponse())
->setURI($request->getRequestURI()->alter('saved', true));
} catch (AphrontQueryDuplicateKeyException $ex) {
$e_username = pht('Not Unique');
$errors[] = pht('Another user already has that username.');
}
}
}
if ($errors) {
$errors = id(new AphrontErrorView())
->setTitle(pht('Form Errors'))
->setErrors($errors);
} else {
$errors = null;
}
$inst1 = pht('Be careful when renaming users!');
$inst2 = pht('The old username will no longer be tied to the user, so '.
'anything which uses it (like old commit messages) will no longer '.
'associate correctly. And if you give a user a username which some '.
'other user used to have, username lookups will begin returning '.
'the wrong user.');
$inst3 = pht('It is generally safe to rename newly created users (and '.
'test users and so on), but less safe to rename established users '.
'and unsafe to reissue a username.');
$inst4 = pht('Users who rely on password auth will need to reset their '.
'passwordafter their username is changed (their username is part '.
'of the salt in the password hash). They will receive an email '.
'with instructions on how to do this.');
$form = new AphrontFormView();
$form
->setUser($admin)
->setAction($request->getRequestURI())
->appendChild(hsprintf(
'<p class="aphront-form-instructions">'.
'<strong>%s</strong> '.
'%s'.
'</p>'.
'<p class="aphront-form-instructions">'.
'%s'.
'</p>'.
'<p class="aphront-form-instructions">'.
'%s'.
'</p>', $inst1, $inst2, $inst3, $inst4))
->appendChild(
id(new AphrontFormStaticControl())
->setLabel(pht('Old Username'))
->setValue($user->getUsername()))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('New Username'))
->setValue($username)
->setName('username')
->setError($e_username))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Change Username')));
$panel = new AphrontPanelView();
$panel->setHeader(pht('Change Username'));
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setNoBackground();
$panel->appendChild($form);
return array($errors, $panel);
}
private function processDeleteRequest(PhabricatorUser $user) {
$request = $this->getRequest();
$admin = $request->getUser();
$far1 = pht('As you stare into the gaping maw of the abyss, something '.
'hold you back.');
$far2 = pht('You can not delete your own account.');
if ($user->getPHID() == $admin->getPHID()) {
$error = new AphrontErrorView();
$error->setTitle(pht('You Shall Journey No Farther'));
$error->appendChild(hsprintf(
'<p>%s</p><p>%s</p>', $far1, $far2));
return $error;
}
$e_username = true;
$username = null;
$errors = array();
if ($request->isFormPost()) {
$username = $request->getStr('username');
if (!strlen($username)) {
$e_username = pht('Required');
$errors[] = pht('You must type the username to confirm deletion.');
} else if ($username != $user->getUsername()) {
$e_username = pht('Invalid');
$errors[] = pht('You must type the username correctly.');
}
if (!$errors) {
id(new PhabricatorUserEditor())
->setActor($admin)
->deleteUser($user);
return id(new AphrontRedirectResponse())->setURI('/people/');
}
}
if ($errors) {
$errors = id(new AphrontErrorView())
->setTitle(pht('Form Errors'))
->setErrors($errors);
} else {
$errors = null;
}
$str1 = pht('Be careful when deleting users!');
$str2 = pht('If this user interacted with anything, it is generally '.
'better to disable them, not delete them. If you delete them, it will '.
'no longer be possible to search for their objects, for example, '.
'and you will lose other information about their history. Disabling '.
'them instead will prevent them from logging in but not destroy '.
'any of their data.');
$str3 = pht('It is generally safe to delete newly created users (and '.
'test users and so on), but less safe to delete established users. '.
'If possible, disable them instead.');
$form = new AphrontFormView();
$form
->setUser($admin)
->setAction($request->getRequestURI())
->appendChild(hsprintf(
'<p class="aphront-form-instructions">'.
'<strong>%s</strong> %s'.
'</p>'.
'<p class="aphront-form-instructions">'.
'%s'.
'</p>', $str1, $str2, $str3))
->appendChild(
id(new AphrontFormStaticControl())
->setLabel(pht('Username'))
->setValue($user->getUsername()))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Confirm'))
->setValue($username)
->setName('username')
->setCaption(pht("Type the username again to confirm deletion."))
->setError($e_username))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Delete User')));
$panel = new AphrontPanelView();
$panel->setHeader(pht('Delete User'));
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setNoBackground();
$panel->appendChild($form);
return array($errors, $panel);
}
private function getRoleInstructions() {
$roles_link = phutil_tag(
'a',
array(
'href' => PhabricatorEnv::getDoclink(
'article/User_Guide_Account_Roles.html'),
'target' => '_blank',
),
pht('User Guide: Account Roles'));
$inst = pht('For a detailed explanation of account roles, see %s.',
$roles_link);
return hsprintf(
'<p class="aphront-form-instructions">%s</p>',
$inst);
}
private function processSetAccountPicture(PhabricatorUser $user) {
$request = $this->getRequest();
$admin = $request->getUser();
- $profile = id(new PhabricatorUserProfile())->loadOneWhere(
- 'userPHID = %s',
- $user->getPHID());
- if (!$profile) {
- $profile = new PhabricatorUserProfile();
- $profile->setUserPHID($user->getPHID());
+ $profile = $user->loadUserProfile();
+ if (!$profile->getID()) {
$profile->setTitle('');
$profile->setBlurb('');
}
$supported_formats = PhabricatorFile::getTransformableImageFormats();
$e_image = null;
$errors = array();
if ($request->isFormPost()) {
$default_image = $request->getExists('default_image');
if ($default_image) {
$profile->setProfileImagePHID(null);
$user->setProfileImagePHID(null);
} else if ($request->getFileExists('image')) {
$file = null;
$file = PhabricatorFile::newFromPHPUpload(
$_FILES['image'],
array(
'authorPHID' => $admin->getPHID(),
));
$okay = $file->isTransformableImage();
if ($okay) {
$xformer = new PhabricatorImageTransformer();
// Generate the large picture for the profile page.
$large_xformed = $xformer->executeProfileTransform(
$file,
$width = 280,
$min_height = 140,
$max_height = 420);
$profile->setProfileImagePHID($large_xformed->getPHID());
// Generate the small picture for comments, etc.
$small_xformed = $xformer->executeProfileTransform(
$file,
$width = 50,
$min_height = 50,
$max_height = 50);
$user->setProfileImagePHID($small_xformed->getPHID());
} else {
$e_image = pht('Not Supported');
$errors[] =
pht('This server only supports these image formats:').
' ' .implode(', ', $supported_formats);
}
}
if (!$errors) {
$user->save();
$profile->save();
$response = id(new AphrontRedirectResponse())
->setURI('/people/edit/'.$user->getID().'/picture/');
return $response;
}
}
$error_view = null;
if ($errors) {
$error_view = new AphrontErrorView();
$error_view->setTitle(pht('Form Errors'));
$error_view->setErrors($errors);
} else {
if ($request->getStr('saved')) {
$error_view = new AphrontErrorView();
$error_view->setSeverity(AphrontErrorView::SEVERITY_NOTICE);
$error_view->setTitle(pht('Changes Saved'));
$error_view->appendChild(
phutil_tag('p', array(), pht('Your changes have been saved.')));
$error_view = $error_view->render();
}
}
$img_src = $user->loadProfileImageURI();
$form = new AphrontFormView();
$form
->setUser($admin)
->setAction($request->getRequestURI())
->setEncType('multipart/form-data')
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Profile Image'))
->setValue(
phutil_tag(
'img',
array(
'src' => $img_src,
))))
->appendChild(
id(new AphrontFormImageControl())
->setLabel(pht('Change Image'))
->setName('image')
->setError($e_image)
->setCaption(
pht('Supported formats: %s', implode(', ', $supported_formats))));
$form->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Save'))
->addCancelButton('/people/edit/'.$user->getID().'/'));
$panel = new AphrontPanelView();
$panel->setHeader(pht('Set Profile Picture'));
$panel->setWidth(AphrontPanelView::WIDTH_FORM);
$panel->setNoBackground();
$panel->appendChild($form);
return array($error_view, $panel);
}
}
diff --git a/src/applications/people/controller/PhabricatorPeopleProfileController.php b/src/applications/people/controller/PhabricatorPeopleProfileController.php
index 50000f3467..d489c3c259 100644
--- a/src/applications/people/controller/PhabricatorPeopleProfileController.php
+++ b/src/applications/people/controller/PhabricatorPeopleProfileController.php
@@ -1,243 +1,238 @@
<?php
final class PhabricatorPeopleProfileController
extends PhabricatorPeopleController {
private $username;
private $page;
private $profileUser;
public function shouldRequireAdmin() {
// Default for people app is true
// We desire public access here
return false;
}
public function willProcessRequest(array $data) {
$this->username = idx($data, 'username');
$this->page = idx($data, 'page');
}
public function getProfileUser() {
return $this->profileUser;
}
private function getMainFilters($username) {
return array(
array(
'key' => 'feed',
'name' => pht('Feed'),
'href' => '/p/'.$username.'/feed/'
),
array(
'key' => 'about',
'name' => pht('About'),
'href' => '/p/'.$username.'/about/'
)
);
}
public function processRequest() {
$viewer = $this->getRequest()->getUser();
$user = id(new PhabricatorUser())->loadOneWhere(
'userName = %s',
$this->username);
if (!$user) {
return new Aphront404Response();
}
$this->profileUser = $user;
require_celerity_resource('phabricator-profile-css');
- $profile = id(new PhabricatorUserProfile())->loadOneWhere(
- 'userPHID = %s',
- $user->getPHID());
- if (!$profile) {
- $profile = new PhabricatorUserProfile();
- }
+ $profile = $user->loadUserProfile();
$username = phutil_escape_uri($user->getUserName());
$menu = new PhabricatorMenuView();
foreach ($this->getMainFilters($username) as $filter) {
$menu->newLink($filter['name'], $filter['href'], $filter['key']);
}
$menu->newLabel(pht('Activity'), 'activity');
// NOTE: applications install the various links through PhabricatorEvent
// listeners
$oauths = id(new PhabricatorUserOAuthInfo())->loadAllWhere(
'userID = %d',
$user->getID());
$oauths = mpull($oauths, null, 'getOAuthProvider');
$providers = PhabricatorOAuthProvider::getAllProviders();
$added_label = false;
foreach ($providers as $provider) {
if (!$provider->isProviderEnabled()) {
continue;
}
$provider_key = $provider->getProviderKey();
if (!isset($oauths[$provider_key])) {
continue;
}
$name = pht('%s Profile', $provider->getProviderName());
$href = $oauths[$provider_key]->getAccountURI();
if ($href) {
if (!$added_label) {
$menu->newLabel(pht('Linked Accounts'), 'linked_accounts');
$added_label = true;
}
$menu->addMenuItem(
id(new PhabricatorMenuItemView())
->setIsExternal(true)
->setName($name)
->setHref($href)
->setType(PhabricatorMenuItemView::TYPE_LINK));
}
}
$event = new PhabricatorEvent(
PhabricatorEventType::TYPE_PEOPLE_DIDRENDERMENU,
array(
'menu' => $menu,
'person' => $user,
));
$event->setUser($viewer);
PhutilEventEngine::dispatchEvent($event);
$nav = AphrontSideNavFilterView::newFromMenu($event->getValue('menu'));
$this->page = $nav->selectFilter($this->page, 'feed');
switch ($this->page) {
case 'feed':
$content = $this->renderUserFeed($user);
break;
case 'about':
$content = $this->renderBasicInformation($user, $profile);
break;
default:
throw new Exception("Unknown page '{$this->page}'!");
}
$picture = $user->loadProfileImageURI();
$header = new PhabricatorProfileHeaderView();
$header
->setProfilePicture($picture)
->setName($user->getUserName().' ('.$user->getRealName().')')
->setDescription($profile->getTitle());
if ($user->getIsDisabled()) {
$header->setStatus('Disabled');
} else {
$statuses = id(new PhabricatorUserStatus())->loadCurrentStatuses(
array($user->getPHID()));
if ($statuses) {
$header->setStatus(reset($statuses)->getTerseSummary($viewer));
}
}
$nav->appendChild($header);
$content = hsprintf('<div style="padding: 1em;">%s</div>', $content);
$header->appendChild($content);
if ($user->getPHID() == $viewer->getPHID()) {
$nav->addFilter(
null,
pht('Edit Profile...'),
'/settings/panel/profile/');
}
if ($viewer->getIsAdmin()) {
$nav->addFilter(
null,
pht('Administrate User...'),
'/people/edit/'.$user->getID().'/');
}
return $this->buildApplicationPage(
$nav,
array(
'title' => $user->getUsername(),
));
}
private function renderBasicInformation($user, $profile) {
$blurb = nonempty(
$profile->getBlurb(),
'//'.pht('Nothing is known about this rare specimen.').'//');
$viewer = $this->getRequest()->getUser();
$engine = PhabricatorMarkupEngine::newProfileMarkupEngine();
$engine->setConfig('viewer', $viewer);
$blurb = $engine->markupText($blurb);
$content = hsprintf(
'<div class="phabricator-profile-info-group">
<h1 class="phabricator-profile-info-header">Basic Information</h1>
<div class="phabricator-profile-info-pane">
<table class="phabricator-profile-info-table">
<tr>
<th>PHID</th>
<td>%s</td>
</tr>
<tr>
<th>User Since</th>
<td>%s</td>
</tr>
</table>
</div>
</div>'.
'<div class="phabricator-profile-info-group">
<h1 class="phabricator-profile-info-header">Flavor Text</h1>
<div class="phabricator-profile-info-pane">
<table class="phabricator-profile-info-table">
<tr>
<th>Blurb</th>
<td>%s</td>
</tr>
</table>
</div>
</div>',
$user->getPHID(),
phabricator_datetime($user->getDateCreated(), $viewer),
$blurb);
return $content;
}
private function renderUserFeed(PhabricatorUser $user) {
$viewer = $this->getRequest()->getUser();
$query = new PhabricatorFeedQuery();
$query->setFilterPHIDs(
array(
$user->getPHID(),
));
$query->setLimit(100);
$query->setViewer($viewer);
$stories = $query->execute();
$builder = new PhabricatorFeedBuilder($stories);
$builder->setUser($viewer);
$view = $builder->buildView();
return hsprintf(
'<div class="phabricator-profile-info-group">
<h1 class="phabricator-profile-info-header">Activity Feed</h1>
<div class="phabricator-profile-info-pane">%s</div>
</div>',
$view->render());
}
}
diff --git a/src/applications/people/storage/PhabricatorUser.php b/src/applications/people/storage/PhabricatorUser.php
index cfe468a546..9845a110c1 100644
--- a/src/applications/people/storage/PhabricatorUser.php
+++ b/src/applications/people/storage/PhabricatorUser.php
@@ -1,696 +1,734 @@
<?php
final class PhabricatorUser extends PhabricatorUserDAO implements PhutilPerson {
const SESSION_TABLE = 'phabricator_session';
const NAMETOKEN_TABLE = 'user_nametoken';
protected $phid;
protected $userName;
protected $realName;
protected $sex;
protected $translation;
protected $passwordSalt;
protected $passwordHash;
protected $profileImagePHID;
protected $timezoneIdentifier = '';
protected $consoleEnabled = 0;
protected $consoleVisible = 0;
protected $consoleTab = '';
protected $conduitCertificate;
protected $isSystemAgent = 0;
protected $isAdmin = 0;
protected $isDisabled = 0;
+ private $profileImage = null;
+ private $profile = null;
+ private $status = null;
private $preferences = null;
private $omnipotent = false;
protected function readField($field) {
switch ($field) {
case 'timezoneIdentifier':
// If the user hasn't set one, guess the server's time.
return nonempty(
$this->timezoneIdentifier,
date_default_timezone_get());
// Make sure these return booleans.
case 'isAdmin':
return (bool)$this->isAdmin;
case 'isDisabled':
return (bool)$this->isDisabled;
case 'isSystemAgent':
return (bool)$this->isSystemAgent;
default:
return parent::readField($field);
}
}
public function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_PARTIAL_OBJECTS => true,
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorPHIDConstants::PHID_TYPE_USER);
}
public function setPassword(PhutilOpaqueEnvelope $envelope) {
if (!$this->getPHID()) {
throw new Exception(
"You can not set a password for an unsaved user because their PHID ".
"is a salt component in the password hash.");
}
if (!strlen($envelope->openEnvelope())) {
$this->setPasswordHash('');
} else {
$this->setPasswordSalt(md5(mt_rand()));
$hash = $this->hashPassword($envelope);
$this->setPasswordHash($hash);
}
return $this;
}
// To satisfy PhutilPerson.
public function getSex() {
return $this->sex;
}
public function getTranslation() {
try {
if ($this->translation &&
class_exists($this->translation) &&
is_subclass_of($this->translation, 'PhabricatorTranslation')) {
return $this->translation;
}
} catch (PhutilMissingSymbolException $ex) {
return null;
}
return null;
}
public function isLoggedIn() {
return !($this->getPHID() === null);
}
public function save() {
if (!$this->getConduitCertificate()) {
$this->setConduitCertificate($this->generateConduitCertificate());
}
$result = parent::save();
$this->updateNameTokens();
id(new PhabricatorSearchIndexer())
->indexDocumentByPHID($this->getPHID());
return $result;
}
private function generateConduitCertificate() {
return Filesystem::readRandomCharacters(255);
}
public function comparePassword(PhutilOpaqueEnvelope $envelope) {
if (!strlen($envelope->openEnvelope())) {
return false;
}
if (!strlen($this->getPasswordHash())) {
return false;
}
$password_hash = $this->hashPassword($envelope);
return ($password_hash === $this->getPasswordHash());
}
private function hashPassword(PhutilOpaqueEnvelope $envelope) {
$hash = $this->getUsername().
$envelope->openEnvelope().
$this->getPHID().
$this->getPasswordSalt();
for ($ii = 0; $ii < 1000; $ii++) {
$hash = md5($hash);
}
return $hash;
}
const CSRF_CYCLE_FREQUENCY = 3600;
const CSRF_TOKEN_LENGTH = 16;
const EMAIL_CYCLE_FREQUENCY = 86400;
const EMAIL_TOKEN_LENGTH = 24;
public function getCSRFToken($offset = 0) {
return $this->generateToken(
time() + (self::CSRF_CYCLE_FREQUENCY * $offset),
self::CSRF_CYCLE_FREQUENCY,
PhabricatorEnv::getEnvConfig('phabricator.csrf-key'),
self::CSRF_TOKEN_LENGTH);
}
public function validateCSRFToken($token) {
if (!$this->getPHID()) {
return true;
}
// When the user posts a form, we check that it contains a valid CSRF token.
// Tokens cycle each hour (every CSRF_CYLCE_FREQUENCY seconds) and we accept
// either the current token, the next token (users can submit a "future"
// token if you have two web frontends that have some clock skew) or any of
// the last 6 tokens. This means that pages are valid for up to 7 hours.
// There is also some Javascript which periodically refreshes the CSRF
// tokens on each page, so theoretically pages should be valid indefinitely.
// However, this code may fail to run (if the user loses their internet
// connection, or there's a JS problem, or they don't have JS enabled).
// Choosing the size of the window in which we accept old CSRF tokens is
// an issue of balancing concerns between security and usability. We could
// choose a very narrow (e.g., 1-hour) window to reduce vulnerability to
// attacks using captured CSRF tokens, but it's also more likely that real
// users will be affected by this, e.g. if they close their laptop for an
// hour, open it back up, and try to submit a form before the CSRF refresh
// can kick in. Since the user experience of submitting a form with expired
// CSRF is often quite bad (you basically lose data, or it's a big pain to
// recover at least) and I believe we gain little additional protection
// by keeping the window very short (the overwhelming value here is in
// preventing blind attacks, and most attacks which can capture CSRF tokens
// can also just capture authentication information [sniffing networks]
// or act as the user [xss]) the 7 hour default seems like a reasonable
// balance. Other major platforms have much longer CSRF token lifetimes,
// like Rails (session duration) and Django (forever), which suggests this
// is a reasonable analysis.
$csrf_window = 6;
for ($ii = -$csrf_window; $ii <= 1; $ii++) {
$valid = $this->getCSRFToken($ii);
if ($token == $valid) {
return true;
}
}
return false;
}
private function generateToken($epoch, $frequency, $key, $len) {
$time_block = floor($epoch / $frequency);
$vec = $this->getPHID().$this->getPasswordHash().$key.$time_block;
return substr(PhabricatorHash::digest($vec), 0, $len);
}
/**
* Issue a new session key to this user. Phabricator supports different
* types of sessions (like "web" and "conduit") and each session type may
* have multiple concurrent sessions (this allows a user to be logged in on
* multiple browsers at the same time, for instance).
*
* Note that this method is transport-agnostic and does not set cookies or
* issue other types of tokens, it ONLY generates a new session key.
*
* You can configure the maximum number of concurrent sessions for various
* session types in the Phabricator configuration.
*
* @param string Session type, like "web".
* @return string Newly generated session key.
*/
public function establishSession($session_type) {
$conn_w = $this->establishConnection('w');
if (strpos($session_type, '-') !== false) {
throw new Exception("Session type must not contain hyphen ('-')!");
}
// We allow multiple sessions of the same type, so when a caller requests
// a new session of type "web", we give them the first available session in
// "web-1", "web-2", ..., "web-N", up to some configurable limit. If none
// of these sessions is available, we overwrite the oldest session and
// reissue a new one in its place.
$session_limit = 1;
switch ($session_type) {
case 'web':
$session_limit = PhabricatorEnv::getEnvConfig('auth.sessions.web');
break;
case 'conduit':
$session_limit = PhabricatorEnv::getEnvConfig('auth.sessions.conduit');
break;
default:
throw new Exception("Unknown session type '{$session_type}'!");
}
$session_limit = (int)$session_limit;
if ($session_limit <= 0) {
throw new Exception(
"Session limit for '{$session_type}' must be at least 1!");
}
// NOTE: Session establishment is sensitive to race conditions, as when
// piping `arc` to `arc`:
//
// arc export ... | arc paste ...
//
// To avoid this, we overwrite an old session only if it hasn't been
// re-established since we read it.
// Consume entropy to generate a new session key, forestalling the eventual
// heat death of the universe.
$session_key = Filesystem::readRandomCharacters(40);
// Load all the currently active sessions.
$sessions = queryfx_all(
$conn_w,
'SELECT type, sessionKey, sessionStart FROM %T
WHERE userPHID = %s AND type LIKE %>',
PhabricatorUser::SESSION_TABLE,
$this->getPHID(),
$session_type.'-');
$sessions = ipull($sessions, null, 'type');
$sessions = isort($sessions, 'sessionStart');
$existing_sessions = array_keys($sessions);
// UNGUARDED WRITES: Logging-in users don't have CSRF stuff yet.
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$retries = 0;
while (true) {
// Choose which 'type' we'll actually establish, i.e. what number we're
// going to append to the basic session type. To do this, just check all
// the numbers sequentially until we find an available session.
$establish_type = null;
for ($ii = 1; $ii <= $session_limit; $ii++) {
$try_type = $session_type.'-'.$ii;
if (!in_array($try_type, $existing_sessions)) {
$establish_type = $try_type;
$expect_key = $session_key;
$existing_sessions[] = $try_type;
// Ensure the row exists so we can issue an update below. We don't
// care if we race here or not.
queryfx(
$conn_w,
'INSERT IGNORE INTO %T (userPHID, type, sessionKey, sessionStart)
VALUES (%s, %s, %s, 0)',
self::SESSION_TABLE,
$this->getPHID(),
$establish_type,
$session_key);
break;
}
}
// If we didn't find an available session, choose the oldest session and
// overwrite it.
if (!$establish_type) {
$oldest = reset($sessions);
$establish_type = $oldest['type'];
$expect_key = $oldest['sessionKey'];
}
// This is so that we'll only overwrite the session if it hasn't been
// refreshed since we read it. If it has, the session key will be
// different and we know we're racing other processes. Whichever one
// won gets the session, we go back and try again.
queryfx(
$conn_w,
'UPDATE %T SET sessionKey = %s, sessionStart = UNIX_TIMESTAMP()
WHERE userPHID = %s AND type = %s AND sessionKey = %s',
self::SESSION_TABLE,
$session_key,
$this->getPHID(),
$establish_type,
$expect_key);
if ($conn_w->getAffectedRows()) {
// The update worked, so the session is valid.
break;
} else {
// We know this just got grabbed, so don't try it again.
unset($sessions[$establish_type]);
}
if (++$retries > $session_limit) {
throw new Exception("Failed to establish a session!");
}
}
$log = PhabricatorUserLog::newLog(
$this,
$this,
PhabricatorUserLog::ACTION_LOGIN);
$log->setDetails(
array(
'session_type' => $session_type,
'session_issued' => $establish_type,
));
$log->setSession($session_key);
$log->save();
return $session_key;
}
public function destroySession($session_key) {
$conn_w = $this->establishConnection('w');
queryfx(
$conn_w,
'DELETE FROM %T WHERE userPHID = %s AND sessionKey = %s',
self::SESSION_TABLE,
$this->getPHID(),
$session_key);
}
private function generateEmailToken(
PhabricatorUserEmail $email,
$offset = 0) {
$key = implode(
'-',
array(
PhabricatorEnv::getEnvConfig('phabricator.csrf-key'),
$this->getPHID(),
$email->getVerificationCode(),
));
return $this->generateToken(
time() + ($offset * self::EMAIL_CYCLE_FREQUENCY),
self::EMAIL_CYCLE_FREQUENCY,
$key,
self::EMAIL_TOKEN_LENGTH);
}
public function validateEmailToken(
PhabricatorUserEmail $email,
$token) {
for ($ii = -1; $ii <= 1; $ii++) {
$valid = $this->generateEmailToken($email, $ii);
if ($token == $valid) {
return true;
}
}
return false;
}
public function getEmailLoginURI(PhabricatorUserEmail $email = null) {
if (!$email) {
$email = $this->loadPrimaryEmail();
if (!$email) {
throw new Exception("User has no primary email!");
}
}
$token = $this->generateEmailToken($email);
$uri = PhabricatorEnv::getProductionURI('/login/etoken/'.$token.'/');
$uri = new PhutilURI($uri);
return $uri->alter('email', $email->getAddress());
}
+ public function attachUserProfile(PhabricatorUserProfile $profile) {
+ $this->profile = $profile;
+ return $this;
+ }
+
+ public function loadUserProfile() {
+ if ($this->profile) {
+ return $this->profile;
+ }
+
+ $profile_dao = new PhabricatorUserProfile();
+ $this->profile = $profile_dao->loadOneWhere('userPHID = %s',
+ $this->getPHID());
+
+ if (!$this->profile) {
+ $profile_dao->setUserPHID($this->getPHID());
+ $this->profile = $profile_dao;
+ }
+
+ return $this->profile;
+ }
+
public function loadPrimaryEmailAddress() {
$email = $this->loadPrimaryEmail();
if (!$email) {
throw new Exception("User has no primary email address!");
}
return $email->getAddress();
}
public function loadPrimaryEmail() {
return $this->loadOneRelative(
new PhabricatorUserEmail(),
'userPHID',
'getPHID',
'(isPrimary = 1)');
}
public function loadPreferences() {
if ($this->preferences) {
return $this->preferences;
}
$preferences = id(new PhabricatorUserPreferences())->loadOneWhere(
'userPHID = %s',
$this->getPHID());
if (!$preferences) {
$preferences = new PhabricatorUserPreferences();
$preferences->setUserPHID($this->getPHID());
$default_dict = array(
PhabricatorUserPreferences::PREFERENCE_TITLES => 'glyph',
PhabricatorUserPreferences::PREFERENCE_EDITOR => '',
PhabricatorUserPreferences::PREFERENCE_MONOSPACED => '',
PhabricatorUserPreferences::PREFERENCE_DARK_CONSOLE => 0);
$preferences->setPreferences($default_dict);
}
$this->preferences = $preferences;
return $preferences;
}
public function loadEditorLink($path, $line, $callsign) {
$editor = $this->loadPreferences()->getPreference(
PhabricatorUserPreferences::PREFERENCE_EDITOR);
if (is_array($path)) {
$multiedit = $this->loadPreferences()->getPreference(
PhabricatorUserPreferences::PREFERENCE_MULTIEDIT);
switch ($multiedit) {
case '':
$path = implode(' ', $path);
break;
case 'disable':
return null;
}
}
if ($editor) {
return strtr($editor, array(
'%%' => '%',
'%f' => phutil_escape_uri($path),
'%l' => phutil_escape_uri($line),
'%r' => phutil_escape_uri($callsign),
));
}
}
private static function tokenizeName($name) {
if (function_exists('mb_strtolower')) {
$name = mb_strtolower($name, 'UTF-8');
} else {
$name = strtolower($name);
}
$name = trim($name);
if (!strlen($name)) {
return array();
}
return preg_split('/\s+/', $name);
}
/**
* Populate the nametoken table, which used to fetch typeahead results. When
* a user types "linc", we want to match "Abraham Lincoln" from on-demand
* typeahead sources. To do this, we need a separate table of name fragments.
*/
public function updateNameTokens() {
$tokens = array_merge(
self::tokenizeName($this->getRealName()),
self::tokenizeName($this->getUserName()));
$tokens = array_unique($tokens);
$table = self::NAMETOKEN_TABLE;
$conn_w = $this->establishConnection('w');
$sql = array();
foreach ($tokens as $token) {
$sql[] = qsprintf(
$conn_w,
'(%d, %s)',
$this->getID(),
$token);
}
queryfx(
$conn_w,
'DELETE FROM %T WHERE userID = %d',
$table,
$this->getID());
if ($sql) {
queryfx(
$conn_w,
'INSERT INTO %T (userID, token) VALUES %Q',
$table,
implode(', ', $sql));
}
}
public function sendWelcomeEmail(PhabricatorUser $admin) {
$admin_username = $admin->getUserName();
$admin_realname = $admin->getRealName();
$user_username = $this->getUserName();
$is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');
$base_uri = PhabricatorEnv::getProductionURI('/');
$uri = $this->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}
EOBODY;
if (!$is_serious) {
$body .= <<<EOBODY
Love,
Phabricator
EOBODY;
}
$mail = id(new PhabricatorMetaMTAMail())
->addTos(array($this->getPHID()))
->setSubject('[Phabricator] Welcome to Phabricator')
->setBody($body)
->setFrom($admin->getPHID())
->saveAndSend();
}
public function sendUsernameChangeEmail(
PhabricatorUser $admin,
$old_username) {
$admin_username = $admin->getUserName();
$admin_realname = $admin->getRealName();
$new_username = $this->getUserName();
$password_instructions = null;
if (PhabricatorEnv::getEnvConfig('auth.password-auth-enabled')) {
$uri = $this->getEmailLoginURI();
$password_instructions = <<<EOTXT
If you use a password to login, you'll need to reset it before you can login
again. You can reset your password by following this link:
{$uri}
And, of course, you'll need to use your new username to login from now on. If
you use OAuth to login, nothing should change.
EOTXT;
}
$body = <<<EOBODY
{$admin_username} ({$admin_realname}) has changed your Phabricator username.
Old Username: {$old_username}
New Username: {$new_username}
{$password_instructions}
EOBODY;
$mail = id(new PhabricatorMetaMTAMail())
->addTos(array($this->getPHID()))
->setSubject('[Phabricator] Username Changed')
->setBody($body)
->setFrom($admin->getPHID())
->saveAndSend();
}
public static function describeValidUsername() {
return 'Usernames must contain only numbers, letters, period, underscore '.
'and hyphen, and can not end with a period.';
}
public static function validateUsername($username) {
// NOTE: If you update this, make sure to update:
//
// - Remarkup rule for @mentions.
// - Routing rule for "/p/username/".
// - Unit tests, obviously.
// - describeValidUsername() method, above.
return (bool)preg_match('/^[a-zA-Z0-9._-]*[a-zA-Z0-9_-]$/', $username);
}
public static function getDefaultProfileImageURI() {
return celerity_get_resource_uri('/rsrc/image/avatar.png');
}
+ public function attachProfileImageURI($uri) {
+ $this->profileImage = $uri;
+ return $this;
+ }
+
public function loadProfileImageURI() {
+ if ($this->profileImage) {
+ return $this->profileImage;
+ }
+
$src_phid = $this->getProfileImagePHID();
if ($src_phid) {
$file = id(new PhabricatorFile())->loadOneWhere('phid = %s', $src_phid);
if ($file) {
- return $file->getBestURI();
+ $this->profileImage = $file->getBestURI();
}
}
- return self::getDefaultProfileImageURI();
+ if (!$this->profileImage) {
+ $this->profileImage = self::getDefaultProfileImageURI();
+ }
+
+ return $this->profileImage;
}
public function getFullName() {
return $this->getUsername().' ('.$this->getRealName().')';
}
public function __toString() {
return $this->getUsername();
}
public static function loadOneWithEmailAddress($address) {
$email = id(new PhabricatorUserEmail())->loadOneWhere(
'address = %s',
$address);
if (!$email) {
return null;
}
return id(new PhabricatorUser())->loadOneWhere(
'phid = %s',
$email->getUserPHID());
}
/* -( Omnipotence )-------------------------------------------------------- */
/**
* Returns true if this user is omnipotent. Omnipotent users bypass all policy
* checks.
*
* @return bool True if the user bypasses policy checks.
*/
public function isOmnipotent() {
return $this->omnipotent;
}
/**
* Get an omnipotent user object for use in contexts where there is no acting
* user, notably daemons.
*
* @return PhabricatorUser An omnipotent user.
*/
public static function getOmnipotentUser() {
static $user = null;
if (!$user) {
$user = new PhabricatorUser();
$user->omnipotent = true;
$user->makeEphemeral();
}
return $user;
}
}
diff --git a/src/applications/settings/panel/PhabricatorSettingsPanelProfile.php b/src/applications/settings/panel/PhabricatorSettingsPanelProfile.php
index 317e69b659..3c9c9a736d 100644
--- a/src/applications/settings/panel/PhabricatorSettingsPanelProfile.php
+++ b/src/applications/settings/panel/PhabricatorSettingsPanelProfile.php
@@ -1,237 +1,231 @@
<?php
final class PhabricatorSettingsPanelProfile
extends PhabricatorSettingsPanel {
public function getPanelKey() {
return 'profile';
}
public function getPanelName() {
return pht('Profile');
}
public function getPanelGroup() {
return pht('Account Information');
}
public function processRequest(AphrontRequest $request) {
$user = $request->getUser();
- $profile = id(new PhabricatorUserProfile())->loadOneWhere(
- 'userPHID = %s',
- $user->getPHID());
- if (!$profile) {
- $profile = new PhabricatorUserProfile();
- $profile->setUserPHID($user->getPHID());
- }
+ $profile = $user->loadUserProfile();
$supported_formats = PhabricatorFile::getTransformableImageFormats();
$e_image = null;
$errors = array();
if ($request->isFormPost()) {
$profile->setTitle($request->getStr('title'));
$profile->setBlurb($request->getStr('blurb'));
$sex = $request->getStr('sex');
$sexes = array(PhutilPerson::SEX_MALE, PhutilPerson::SEX_FEMALE);
if (in_array($sex, $sexes)) {
$user->setSex($sex);
} else {
$user->setSex(null);
}
// Checked in runtime.
$user->setTranslation($request->getStr('translation'));
$default_image = $request->getExists('default_image');
$gravatar_email = $request->getStr('gravatar');
if ($default_image) {
$profile->setProfileImagePHID(null);
$user->setProfileImagePHID(null);
} else if (!empty($gravatar_email) || $request->getFileExists('image')) {
$file = null;
if (!empty($gravatar_email)) {
// These steps recommended by:
// https://en.gravatar.com/site/implement/hash/
$trimmed = trim($gravatar_email);
$lower_cased = strtolower($trimmed);
$hash = md5($lower_cased);
$url = 'http://www.gravatar.com/avatar/'.($hash).'?s=200';
$file = PhabricatorFile::newFromFileDownload(
$url,
array(
'name' => 'gravatar',
'authorPHID' => $user->getPHID(),
));
} else if ($request->getFileExists('image')) {
$file = PhabricatorFile::newFromPHPUpload(
$_FILES['image'],
array(
'authorPHID' => $user->getPHID(),
));
}
$okay = $file->isTransformableImage();
if ($okay) {
$xformer = new PhabricatorImageTransformer();
// Generate the large picture for the profile page.
$large_xformed = $xformer->executeProfileTransform(
$file,
$width = 280,
$min_height = 140,
$max_height = 420);
$profile->setProfileImagePHID($large_xformed->getPHID());
// Generate the small picture for comments, etc.
$small_xformed = $xformer->executeProfileTransform(
$file,
$width = 50,
$min_height = 50,
$max_height = 50);
$user->setProfileImagePHID($small_xformed->getPHID());
} else {
$e_image = pht('Not Supported');
$errors[] =
pht('This server only supports these image formats:').
' ' .implode(', ', $supported_formats);
}
}
if (!$errors) {
$user->save();
$profile->save();
$response = id(new AphrontRedirectResponse())
->setURI($this->getPanelURI('?saved=true'));
return $response;
}
}
$error_view = null;
if ($errors) {
$error_view = new AphrontErrorView();
$error_view->setTitle(pht('Form Errors'));
$error_view->setErrors($errors);
} else {
if ($request->getStr('saved')) {
$error_view = new AphrontErrorView();
$error_view->setSeverity(AphrontErrorView::SEVERITY_NOTICE);
$error_view->setTitle(pht('Changes Saved'));
$error_view->appendChild(
phutil_tag('p', array(), pht('Your changes have been saved.')));
$error_view = $error_view->render();
}
}
$img_src = $user->loadProfileImageURI();
$profile_uri = PhabricatorEnv::getURI('/p/'.$user->getUsername().'/');
$sexes = array(
PhutilPerson::SEX_UNKNOWN => pht('Unknown'),
PhutilPerson::SEX_MALE => pht('Male'),
PhutilPerson::SEX_FEMALE => pht('Female'),
);
$translations = array();
$symbols = id(new PhutilSymbolLoader())
->setType('class')
->setAncestorClass('PhabricatorTranslation')
->setConcreteOnly(true)
->selectAndLoadSymbols();
foreach ($symbols as $symbol) {
$class = $symbol['name'];
$translations[$class] = newv($class, array())->getName();
}
asort($translations);
$default = PhabricatorEnv::newObjectFromConfig('translation.provider');
$translations = array(
'' => pht('Server Default (%s)', $default->getName()),
) + $translations;
$form = new AphrontFormView();
$form
->setUser($request->getUser())
->setEncType('multipart/form-data')
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Title'))
->setName('title')
->setValue($profile->getTitle())
->setCaption(pht('Serious business title.')))
->appendChild(
id(new AphrontFormSelectControl())
->setOptions($sexes)
->setLabel(pht('Sex'))
->setName('sex')
->setValue($user->getSex()))
->appendChild(
id(new AphrontFormSelectControl())
->setOptions($translations)
->setLabel(pht('Translation'))
->setName('translation')
->setValue($user->getTranslation()))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Profile URI'))
->setValue(
phutil_tag(
'a',
array(
'href' => $profile_uri,
),
$profile_uri)))
->appendChild(hsprintf(
'<p class="aphront-form-instructions">%s</p>',
pht('Write something about yourself! Make sure to include important ' .
'information like your favorite Pokemon and which Starcraft race ' .
'you play.')))
->appendChild(
id(new AphrontFormTextAreaControl())
->setLabel(pht('Blurb'))
->setName('blurb')
->setValue($profile->getBlurb()))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Profile Image'))
->setValue(
phutil_tag(
'img',
array(
'src' => $img_src,
))))
->appendChild(
id(new AphrontFormImageControl())
->setLabel(pht('Change Image'))
->setName('image')
->setError($e_image)
->setCaption(
pht('Supported formats: %s', implode(', ', $supported_formats))));
if (PhabricatorEnv::getEnvConfig('security.allow-outbound-http')) {
$form->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Import Gravatar'))
->setName('gravatar')
->setError($e_image)
->setCaption(pht('Enter gravatar email address')));
}
$form->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Save'))
->addCancelButton('/p/'.$user->getUsername().'/'));
$panel = new AphrontPanelView();
$panel->setHeader(pht('Edit Profile Details'));
$panel->appendChild($form);
$panel->setNoBackground();
return array(
$error_view,
$panel,
);
}
}

File Metadata

Mime Type
text/x-diff
Expires
Fri, Oct 31, 6:36 AM (12 h, 20 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
312039
Default Alt Text
(67 KB)

Event Timeline