public function testParseLocalTime() { $u = new PhabricatorUser(); $u->setTimezoneIdentifier('UTC'); $v = new PhabricatorUser(); $v->setTimezoneIdentifier('America/Los_Angeles'); $t = 1370202281; // 2013-06-02 12:44:41 -0700 $time = PhabricatorTime::pushTime($t, 'America/Los_Angeles'); $this->assertEqual($t, PhabricatorTime::parseLocalTime('now', $u)); $this->assertEqual($t, PhabricatorTime::parseLocalTime('now', $v)); $this->assertEqual($t, PhabricatorTime::parseLocalTime('2013-06-02 12:44:41 -0700', $u)); $this->assertEqual($t, PhabricatorTime::parseLocalTime('2013-06-02 12:44:41 -0700', $v)); $this->assertEqual($t, PhabricatorTime::parseLocalTime('2013-06-02 12:44:41 PDT', $u)); $this->assertEqual($t, PhabricatorTime::parseLocalTime('2013-06-02 12:44:41 PDT', $v)); $this->assertEqual($t, PhabricatorTime::parseLocalTime('2013-06-02 19:44:41', $u)); $this->assertEqual($t, PhabricatorTime::parseLocalTime('2013-06-02 12:44:41', $v)); $this->assertEqual($t + 3600, PhabricatorTime::parseLocalTime('+1 hour', $u)); $this->assertEqual($t + 3600, PhabricatorTime::parseLocalTime('+1 hour', $v)); unset($time); $t = 1370239200; // 2013-06-02 23:00:00 -0700 $time = PhabricatorTime::pushTime($t, 'America/Los_Angeles'); // For the UTC user, midnight was 6 hours ago because it's early in the // morning for htem. For the PDT user, midnight was 23 hours ago. $this->assertEqual($t + -6 * 3600 + 60, PhabricatorTime::parseLocalTime('12:01:00 AM', $u)); $this->assertEqual($t + -23 * 3600 + 60, PhabricatorTime::parseLocalTime('12:01:00 AM', $v)); unset($time); }
public static function applyLeaveProject(PhabricatorProject $project, PhabricatorUser $user) { $members = array_fill_keys($project->getMemberPHIDs(), true); unset($members[$user->getPHID()]); $members = array_keys($members); self::applyOneTransaction($project, $user, PhabricatorProjectTransactionType::TYPE_MEMBERS, $members); }
public function didMarkupText() { $engine = $this->getEngine(); $metadata_key = self::KEY_RULE_MENTION; $metadata = $engine->getTextMetadata($metadata_key, array()); if (empty($metadata)) { // No mentions, or we already processed them. return; } $usernames = array_keys($metadata); $user_table = new PhabricatorUser(); $real_user_names = queryfx_all($user_table->establishConnection('r'), 'SELECT username, phid, realName FROM %T WHERE username IN (%Ls)', $user_table->getTableName(), $usernames); $actual_users = array(); $mentioned_key = self::KEY_MENTIONED; $mentioned = $engine->getTextMetadata($mentioned_key, array()); foreach ($real_user_names as $row) { $actual_users[strtolower($row['username'])] = $row; $mentioned[$row['phid']] = $row['phid']; } $engine->setTextMetadata($mentioned_key, $mentioned); foreach ($metadata as $username => $tokens) { $exists = isset($actual_users[$username]); $class = $exists ? 'phabricator-remarkup-mention-exists' : 'phabricator-remarkup-mention-unknown'; if ($exists) { $tag = phutil_render_tag('a', array('class' => $class, 'href' => '/p/' . $username . '/', 'target' => '_blank', 'title' => $actual_users[$username]['realName']), phutil_escape_html('@' . $username)); } else { $tag = phutil_render_tag('span', array('class' => $class), phutil_escape_html('@' . $username)); } foreach ($tokens as $token) { $engine->overwriteStoredText($token, $tag); } } // Don't re-process these mentions. $engine->setTextMetadata($metadata_key, array()); }
public static function loadNeedAttentionRevisions(PhabricatorUser $viewer) { if (!$viewer->isLoggedIn()) { return array(); } $viewer_phid = $viewer->getPHID(); $responsible_phids = id(new DifferentialResponsibleDatasource())->setViewer($viewer)->evaluateTokens(array($viewer_phid)); $revision_query = id(new DifferentialRevisionQuery())->setViewer($viewer)->withStatus(DifferentialRevisionQuery::STATUS_OPEN)->withResponsibleUsers($responsible_phids)->needReviewerStatus(true)->needRelationships(true)->needFlags(true)->needDrafts(true)->setLimit(self::MAX_STATUS_ITEMS); $revisions = $revision_query->execute(); $query = id(new PhabricatorSavedQuery())->attachParameterMap(array('responsiblePHIDs' => $responsible_phids)); $groups = id(new DifferentialRevisionRequiredActionResultBucket())->setViewer($viewer)->newResultGroups($query, $revisions); $include = array(); foreach ($groups as $group) { switch ($group->getKey()) { case DifferentialRevisionRequiredActionResultBucket::KEY_MUSTREVIEW: case DifferentialRevisionRequiredActionResultBucket::KEY_SHOULDREVIEW: foreach ($group->getObjects() as $object) { $include[] = $object; } break; default: break; } } return $include; }
public function buildIconNavView(PhabricatorUser $user) { $viewer = $this->getViewer(); $picture = $user->getProfileImageURI(); $name = $user->getUsername(); $nav = new AphrontSideNavFilterView(); $nav->setIconNav(true); $nav->setBaseURI(new PhutilURI('/p/')); $nav->addIcon("{$name}/", $name, null, $picture); $class = 'PhabricatorCalendarApplication'; if (PhabricatorApplication::isClassInstalledForViewer($class, $viewer)) { $nav->addIcon("{$name}/calendar/", pht('Calendar'), 'fa-calendar'); } $class = 'PhabricatorManiphestApplication'; if (PhabricatorApplication::isClassInstalledForViewer($class, $viewer)) { $phid = $user->getPHID(); $view_uri = sprintf('/maniphest/?statuses=open()&assigned=%s#R', $phid); $nav->addIcon('maniphest', pht('Open Tasks'), 'fa-anchor', null, $view_uri); } $class = 'PhabricatorDifferentialApplication'; if (PhabricatorApplication::isClassInstalledForViewer($class, $viewer)) { $username = phutil_escape_uri($name); $view_uri = '/differential/?authors=' . $username; $nav->addIcon('differential', pht('Revisions'), 'fa-cog', null, $view_uri); } $class = 'PhabricatorAuditApplication'; if (PhabricatorApplication::isClassInstalledForViewer($class, $viewer)) { $username = phutil_escape_uri($name); $view_uri = '/audit/?authors=' . $username; $nav->addIcon('audit', pht('Commits'), 'fa-code', null, $view_uri); } return $nav; }
private function processImportRequest($request) { $admin = $request->getUser(); $usernames = $request->getArr('usernames'); $emails = $request->getArr('email'); $names = $request->getArr('name'); $panel = new AphrontErrorView(); $panel->setSeverity(AphrontErrorView::SEVERITY_NOTICE); $panel->setTitle("Import Successful"); $errors = array("Successfully imported users from LDAP"); foreach ($usernames as $username) { $user = new PhabricatorUser(); $user->setUsername($username); $user->setRealname($names[$username]); $email_obj = id(new PhabricatorUserEmail())->setAddress($emails[$username])->setIsVerified(1); try { id(new PhabricatorUserEditor())->setActor($admin)->createNewUser($user, $email_obj); $ldap_info = new PhabricatorUserLDAPInfo(); $ldap_info->setLDAPUsername($username); $ldap_info->setUserID($user->getID()); $ldap_info->save(); $errors[] = 'Successfully added ' . $username; } catch (Exception $ex) { $errors[] = 'Failed to add ' . $username . ' ' . $ex->getMessage(); } } $panel->setErrors($errors); return $panel; }
function phabricator_form(PhabricatorUser $user, $attributes, $content) { $body = array(); $http_method = idx($attributes, 'method'); $is_post = strcasecmp($http_method, 'POST') === 0; $http_action = idx($attributes, 'action'); $is_absolute_uri = preg_match('#^(https?:|//)#', $http_action); if ($is_post) { // NOTE: We only include CSRF tokens if a URI is a local URI on the same // domain. This is an important security feature and prevents forms which // submit to foreign sites from leaking CSRF tokens. // In some cases, we may construct a fully-qualified local URI. For example, // we can construct these for download links, depending on configuration. // These forms do not receive CSRF tokens, even though they safely could. // This can be confusing, if you're developing for Phabricator and // manage to construct a local form with a fully-qualified URI, since it // won't get CSRF tokens and you'll get an exception at the other end of // the request which is a bit disconnected from the actual root cause. // However, this is rare, and there are reasonable cases where this // construction occurs legitimately, and the simplest fix is to omit CSRF // tokens for these URIs in all cases. The error message you receive also // gives you some hints as to this potential source of error. if (!$is_absolute_uri) { $body[] = phutil_tag('input', array('type' => 'hidden', 'name' => AphrontRequest::getCSRFTokenName(), 'value' => $user->getCSRFToken())); $body[] = phutil_tag('input', array('type' => 'hidden', 'name' => '__form__', 'value' => true)); } } if (is_array($content)) { $body = array_merge($body, $content); } else { $body[] = $content; } return javelin_tag('form', $attributes, $body); }
public final function willBeginExecution() { $request = $this->getRequest(); $user = new PhabricatorUser(); $phusr = $request->getCookie('phusr'); $phsid = $request->getCookie('phsid'); if ($phusr && $phsid) { $info = queryfx_one($user->establishConnection('r'), 'SELECT u.* FROM %T u JOIN %T s ON u.phid = s.userPHID AND s.type LIKE %> AND s.sessionKey = %s', $user->getTableName(), 'phabricator_session', 'web-', $phsid); if ($info) { $user->loadFromArray($info); } } $request->setUser($user); if ($user->getIsDisabled() && $this->shouldRequireEnabledUser()) { $disabled_user_controller = newv('PhabricatorDisabledUserController', array($request)); return $this->delegateToController($disabled_user_controller); } if (PhabricatorEnv::getEnvConfig('darkconsole.enabled')) { if ($user->getConsoleEnabled() || PhabricatorEnv::getEnvConfig('darkconsole.always-on')) { $console = new DarkConsoleCore(); $request->getApplicationConfiguration()->setConsole($console); } } if ($this->shouldRequireLogin() && !$user->getPHID()) { $login_controller = newv('PhabricatorLoginController', array($request)); return $this->delegateToController($login_controller); } if ($this->shouldRequireAdmin() && !$user->getIsAdmin()) { return new Aphront403Response(); } }
protected function buildUserInformationDictionary(PhabricatorUser $user, PhabricatorUserStatus $current_status = null) { $roles = array(); if ($user->getIsDisabled()) { $roles[] = 'disabled'; } if ($user->getIsSystemAgent()) { $roles[] = 'agent'; } if ($user->getIsAdmin()) { $roles[] = 'admin'; } $primary = $user->loadPrimaryEmail(); if ($primary && $primary->getIsVerified()) { $roles[] = 'verified'; } else { $roles[] = 'unverified'; } $return = array('phid' => $user->getPHID(), 'userName' => $user->getUserName(), 'realName' => $user->getRealName(), 'image' => $user->loadProfileImageURI(), 'uri' => PhabricatorEnv::getURI('/p/' . $user->getUsername() . '/'), 'roles' => $roles); if ($current_status) { $return['currentStatus'] = $current_status->getTextStatus(); $return['currentStatusUntil'] = $current_status->getDateTo(); } return $return; }
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { if ($viewer->getPHID() == $this->userPHID) { return true; } return false; }
public function apply($text) { // NOTE: Negative lookahead for period prevents us from picking up email // addresses, while allowing constructs like "@tomo, lol". The negative // lookbehind for a word character prevents us from matching "mail@lists" // while allowing "@tomo/@mroch". The negative lookahead prevents us from // matching "@joe.com" while allowing us to match "hey, @joe.". $regexp = '/(?<!\\w)@([a-zA-Z0-9]+)\\b(?![.]\\w)/'; $matches = null; $ok = preg_match_all($regexp, $text, $matches); if (!$ok) { // No mentions in this text. return $text; } $usernames = $matches[1]; // TODO: This is a little sketchy perf-wise. Once APC comes up, it is an // ideal candidate to back with an APC cache. $user_table = new PhabricatorUser(); $real_user_names = queryfx_all($user_table->establishConnection('r'), 'SELECT username, phid, realName FROM %T WHERE username IN (%Ls)', $user_table->getTableName(), $usernames); $engine = $this->getEngine(); $metadata_key = 'phabricator.mentioned-user-phids'; $mentioned = $engine->getTextMetadata($metadata_key, array()); foreach ($real_user_names as $row) { $this->actualUsers[strtolower($row['username'])] = $row; $mentioned[$row['phid']] = $row['phid']; } $engine->setTextMetadata($metadata_key, $mentioned); return preg_replace_callback($regexp, array($this, 'markupMention'), $text); }
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { $can_edit = PhabricatorPolicyCapability::CAN_EDIT; switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: if ($this->isUserMember($viewer->getPHID())) { // Project members can always view a project. return true; } break; case PhabricatorPolicyCapability::CAN_EDIT: $parent = $this->getParentProject(); if ($parent) { $can_edit_parent = PhabricatorPolicyFilter::hasCapability($viewer, $parent, $can_edit); if ($can_edit_parent) { return true; } } break; case PhabricatorPolicyCapability::CAN_JOIN: if (PhabricatorPolicyFilter::hasCapability($viewer, $this, $can_edit)) { // Project editors can always join a project. return true; } break; } return false; }
private function processImportRequest($request) { $admin = $request->getUser(); $usernames = $request->getArr('usernames'); $emails = $request->getArr('email'); $names = $request->getArr('name'); $notice_view = new PHUIInfoView(); $notice_view->setSeverity(PHUIInfoView::SEVERITY_NOTICE); $notice_view->setTitle(pht('Import Successful')); $notice_view->setErrors(array(pht('Successfully imported users from LDAP'))); $list = new PHUIObjectItemListView(); $list->setNoDataString(pht('No users imported?')); foreach ($usernames as $username) { $user = new PhabricatorUser(); $user->setUsername($username); $user->setRealname($names[$username]); $email_obj = id(new PhabricatorUserEmail())->setAddress($emails[$username])->setIsVerified(1); try { id(new PhabricatorUserEditor())->setActor($admin)->createNewUser($user, $email_obj); id(new PhabricatorExternalAccount())->setUserPHID($user->getPHID())->setAccountType('ldap')->setAccountDomain('self')->setAccountID($username)->save(); $header = pht('Successfully added %s', $username); $attribute = null; $color = 'fa-check green'; } catch (Exception $ex) { $header = pht('Failed to add %s', $username); $attribute = $ex->getMessage(); $color = 'fa-times red'; } $item = id(new PHUIObjectItemView())->setHeader($header)->addAttribute($attribute)->setStatusIcon($color); $list->addItem($item); } return array($notice_view, $list); }
public static function createConpherence(PhabricatorUser $creator, array $participant_phids, $title, $message, PhabricatorContentSource $source) { $conpherence = id(new ConpherenceThread())->attachParticipants(array())->attachFilePHIDs(array())->setMessageCount(0); $files = array(); $errors = array(); if (empty($participant_phids)) { $errors[] = self::ERROR_EMPTY_PARTICIPANTS; } else { $participant_phids[] = $creator->getPHID(); $participant_phids = array_unique($participant_phids); $conpherence->setRecentParticipantPHIDs(array_slice($participant_phids, 0, 10)); } if (empty($message)) { $errors[] = self::ERROR_EMPTY_MESSAGE; } $file_phids = PhabricatorMarkupEngine::extractFilePHIDsFromEmbeddedFiles($creator, array($message)); if ($file_phids) { $files = id(new PhabricatorFileQuery())->setViewer($creator)->withPHIDs($file_phids)->execute(); } if (!$errors) { $xactions = array(); $xactions[] = id(new ConpherenceTransaction())->setTransactionType(ConpherenceTransactionType::TYPE_PARTICIPANTS)->setNewValue(array('+' => $participant_phids)); if ($files) { $xactions[] = id(new ConpherenceTransaction())->setTransactionType(ConpherenceTransactionType::TYPE_FILES)->setNewValue(array('+' => mpull($files, 'getPHID'))); } if ($title) { $xactions[] = id(new ConpherenceTransaction())->setTransactionType(ConpherenceTransactionType::TYPE_TITLE)->setNewValue($title); } $xactions[] = id(new ConpherenceTransaction())->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)->attachComment(id(new ConpherenceTransactionComment())->setContent($message)->setConpherencePHID($conpherence->getPHID())); id(new ConpherenceEditor())->setContentSource($source)->setContinueOnNoEffect(true)->setActor($creator)->applyTransactions($conpherence, $xactions); } return array($errors, $conpherence); }
function phabricator_render_form(PhabricatorUser $user, $attributes, $content) { if (strcasecmp(idx($attributes, 'method'), 'POST') == 0 && !preg_match('#^(https?:|//)#', idx($attributes, 'action'))) { $content = phutil_render_tag('input', array('type' => 'hidden', 'name' => AphrontRequest::getCSRFTokenName(), 'value' => $user->getCSRFToken())) . phutil_render_tag('input', array('type' => 'hidden', 'name' => '__form__', 'value' => true)) . $content; } return javelin_render_tag('form', $attributes, $content); }
public static function initializeNewProject(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery())->setViewer(PhabricatorUser::getOmnipotentUser())->withClasses(array('PhabricatorProjectApplication'))->executeOne(); $view_policy = $app->getPolicy(ProjectDefaultViewCapability::CAPABILITY); $edit_policy = $app->getPolicy(ProjectDefaultEditCapability::CAPABILITY); $join_policy = $app->getPolicy(ProjectDefaultJoinCapability::CAPABILITY); return id(new PhabricatorProject())->setAuthorPHID($actor->getPHID())->setIcon(self::DEFAULT_ICON)->setColor(self::DEFAULT_COLOR)->setViewPolicy($view_policy)->setEditPolicy($edit_policy)->setJoinPolicy($join_policy)->setIsMembershipLocked(0)->attachMemberPHIDs(array())->attachSlugs(array())->setHasWorkboard(0)->setHasMilestones(0)->setHasSubprojects(0)->attachParentProject(null); }
public static function initializeNewMessage(PhabricatorUser $actor) { $actor_phid = $actor->getPHID(); if (!$actor_phid) { $actor_phid = id(new PhabricatorHarbormasterApplication())->getPHID(); } return id(new HarbormasterBuildMessage())->setAuthorPHID($actor_phid)->setIsConsumed(0); }
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { switch ($capability) { case PhabricatorPolicyCapability::CAN_EDIT: return $viewer->getPHID() == $this->getCreatorPHID(); } return false; }
public function applyRule(PhabricatorUser $viewer, $value, PhabricatorPolicyInterface $object) { $viewer_phid = $viewer->getPHID(); if (!$viewer_phid) { return false; } return $object->getHostPHID() == $viewer_phid; }
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { $members = array_fuse($this->getMemberPHIDs()); if (isset($members[$viewer->getPHID()])) { return true; } return false; }
public function applyRule(PhabricatorUser $viewer, $value, PhabricatorPolicyInterface $object) { $viewer_phid = $viewer->getPHID(); if (!$viewer_phid) { return false; } return (bool) $object->getParticipantIfExists($viewer_phid); }
public function countUnread(PhabricatorUser $user) { $conn = $this->establishConnection('r'); $data = queryfx_one($conn, 'SELECT COUNT(*) as count FROM %T WHERE userPHID = %s AND hasViewed = 0', $this->getTableName(), $user->getPHID()); return $data['count']; }
private function getPasswordHashInput(PhutilOpaqueEnvelope $password, PhabricatorUser $user) { if ($user->getPHID() != $this->getUserPHID()) { throw new Exception(pht('User does not match password user PHID!')); } $raw_input = PhabricatorHash::digestPassword($password, $user->getPHID()); return new PhutilOpaqueEnvelope($raw_input); }
public function applyRule(PhabricatorUser $viewer, $value, PhabricatorPolicyInterface $object) { foreach ($value as $phid) { if ($phid == $viewer->getPHID()) { return true; } } return false; }
public function applyRule(PhabricatorUser $viewer, $value, PhabricatorPolicyInterface $object) { foreach ($value as $project_phid) { if (isset($this->memberships[$viewer->getPHID()][$project_phid])) { return true; } } return false; }
public function startTracking(PhabricatorUser $user, $phid, $timestamp) { $usertime = new PhrequentUserTime(); $usertime->setDateStarted($timestamp); $usertime->setUserPHID($user->getPHID()); $usertime->setObjectPHID($phid); $usertime->save(); return $phid; }
private function generateTestFile(PhabricatorUser $actor) { $engine = new PhabricatorTestStorageEngine(); $data = Filesystem::readRandomCharacters(64); $params = array('name' => 'test.' . $actor->getPHID(), 'viewPolicy' => $actor->getPHID(), 'authorPHID' => $actor->getPHID(), 'storageEngines' => array($engine)); $file = PhabricatorFile::newFromFileData($data, $params); $file->save(); return $file; }
public function renderForDisplay(PhabricatorUser $viewer) { try { $target = $this->loadBuildTarget(); } catch (Exception $ex) { return null; } return $viewer->renderHandle($target->getPHID()); }
public function applyRule(PhabricatorUser $viewer, $value, PhabricatorPolicyInterface $object) { $viewer_phid = $viewer->getPHID(); if (!$viewer_phid) { return false; } $memberships = idx($this->memberships, $viewer_phid); return isset($memberships[$object->getPHID()]); }
public function loadStatus(PhabricatorUser $user) { $status = array(); $flags = id(new PhabricatorFlagQuery())->withOwnerPHIDs(array($user->getPHID()))->execute(); $count = count($flags); $type = $count ? PhabricatorApplicationStatusView::TYPE_INFO : PhabricatorApplicationStatusView::TYPE_EMPTY; $status[] = id(new PhabricatorApplicationStatusView())->setType($type)->setText(pht('%d Flagged Object(s)', $count))->setCount($count); return $status; }