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();
     }
 }
 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 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 final function willBeginExecution()
 {
     $request = $this->getRequest();
     $user = new PhabricatorUser();
     $phusr = $request->getCookie('phusr');
     $phsid = $request->getCookie('phsid');
     if (strlen($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);
         }
     }
     $translation = $user->getTranslation();
     if ($translation && $translation != PhabricatorEnv::getEnvConfig('translation.provider')) {
         $translation = newv($translation, array());
         PhutilTranslator::getInstance()->setLanguage($translation->getLanguage())->addTranslations($translation->getTranslations());
     }
     $request->setUser($user);
     if ($user->getIsDisabled() && $this->shouldRequireEnabledUser()) {
         $disabled_user_controller = new PhabricatorDisabledUserController($request);
         return $this->delegateToController($disabled_user_controller);
     }
     $event = new PhabricatorEvent(PhabricatorEventType::TYPE_CONTROLLER_CHECKREQUEST, array('request' => $request, 'controller' => get_class($this)));
     $event->setUser($user);
     PhutilEventEngine::dispatchEvent($event);
     $checker_controller = $event->getValue('controller');
     if ($checker_controller != get_class($this)) {
         return $this->delegateToController($checker_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 = new PhabricatorLoginController($request);
         return $this->delegateToController($login_controller);
     }
     if ($this->shouldRequireEmailVerification()) {
         $email = $user->loadPrimaryEmail();
         if (!$email) {
             throw new Exception("No primary email address associated with this account!");
         }
         if (!$email->getIsVerified()) {
             $verify_controller = new PhabricatorMustVerifyEmailController($request);
             return $this->delegateToController($verify_controller);
         }
     }
     if ($this->shouldRequireAdmin() && !$user->getIsAdmin()) {
         return new Aphront403Response();
     }
 }
 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;
     }
     $original_key = self::KEY_RULE_MENTION_ORIGINAL;
     $original = $engine->getTextMetadata($original_key, array());
     $usernames = array_keys($metadata);
     $user_table = new PhabricatorUser();
     $real_user_names = queryfx_all($user_table->establishConnection('r'), 'SELECT username, phid, realName, isDisabled
     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]);
         if (!$exists) {
             $class = 'phabricator-remarkup-mention-unknown';
         } else {
             if ($actual_users[$username]['isDisabled']) {
                 $class = 'phabricator-remarkup-mention-disabled';
             } else {
                 $class = 'phabricator-remarkup-mention-exists';
             }
         }
         if ($exists) {
             $tag = phutil_render_tag('a', array('class' => $class, 'href' => '/p/' . $actual_users[$username]['username'] . '/', 'target' => '_blank', 'title' => $actual_users[$username]['realName']), phutil_escape_html('@' . $actual_users[$username]['username']));
             foreach ($tokens as $token) {
                 $engine->overwriteStoredText($token, $tag);
             }
         } else {
             // NOTE: The structure here is different from the 'exists' branch,
             // because we want to preserve the original text capitalization and it
             // may differ for each token.
             foreach ($tokens as $token) {
                 $tag = phutil_render_tag('span', array('class' => $class), phutil_escape_html('@' . idx($original, $token, $username)));
                 $engine->overwriteStoredText($token, $tag);
             }
         }
     }
     // Don't re-process these mentions.
     $engine->setTextMetadata($metadata_key, array());
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $viewer = $request->getUser();
     $is_admin = $viewer->getIsAdmin();
     $user = new PhabricatorUser();
     $count = queryfx_one($user->establishConnection('r'), 'SELECT COUNT(*) N FROM %T', $user->getTableName());
     $count = idx($count, 'N', 0);
     $pager = new AphrontPagerView();
     $pager->setOffset($request->getInt('page', 0));
     $pager->setCount($count);
     $pager->setURI($request->getRequestURI(), 'page');
     $users = id(new PhabricatorPeopleQuery())->needPrimaryEmail(true)->executeWithOffsetPager($pager);
     $rows = array();
     foreach ($users as $user) {
         $primary_email = $user->loadPrimaryEmail();
         if ($primary_email && $primary_email->getIsVerified()) {
             $email = 'Verified';
         } else {
             $email = 'Unverified';
         }
         $status = array();
         if ($user->getIsDisabled()) {
             $status[] = 'Disabled';
         }
         if ($user->getIsAdmin()) {
             $status[] = 'Admin';
         }
         if ($user->getIsSystemAgent()) {
             $status[] = 'System Agent';
         }
         $status = implode(', ', $status);
         $rows[] = array(phabricator_date($user->getDateCreated(), $viewer), phabricator_time($user->getDateCreated(), $viewer), phutil_render_tag('a', array('href' => '/p/' . $user->getUsername() . '/'), phutil_escape_html($user->getUserName())), phutil_escape_html($user->getRealName()), $status, $email, phutil_render_tag('a', array('class' => 'button grey small', 'href' => '/people/edit/' . $user->getID() . '/'), 'Administrate User'));
     }
     $table = new AphrontTableView($rows);
     $table->setHeaders(array('Join Date', 'Time', 'Username', 'Real Name', 'Roles', 'Email', ''));
     $table->setColumnClasses(array(null, 'right', 'pri', 'wide', null, null, 'action'));
     $table->setColumnVisibility(array(true, true, true, true, $is_admin, $is_admin, $is_admin));
     $panel = new AphrontPanelView();
     $panel->setHeader('People (' . number_format($count) . ')');
     $panel->appendChild($table);
     $panel->appendChild($pager);
     if ($is_admin) {
         $panel->addButton(phutil_render_tag('a', array('href' => '/people/edit/', 'class' => 'button green'), 'Create New Account'));
         if (PhabricatorEnv::getEnvConfig('ldap.auth-enabled')) {
             $panel->addButton(phutil_render_tag('a', array('href' => '/people/ldap/', 'class' => 'button green'), 'Import from LDAP'));
         }
     }
     $nav = $this->buildSideNavView();
     $nav->selectFilter('people');
     $nav->appendChild($panel);
     return $this->buildApplicationPage($nav, array('title' => 'People'));
 }
 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);
     return $users;
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $viewer = $request->getUser();
     $is_admin = $viewer->getIsAdmin();
     $user = new PhabricatorUser();
     $count = queryfx_one($user->establishConnection('r'), 'SELECT COUNT(*) N FROM %T', $user->getTableName());
     $count = idx($count, 'N', 0);
     $pager = new AphrontPagerView();
     $pager->setOffset($request->getInt('page', 0));
     $pager->setCount($count);
     $pager->setURI($request->getRequestURI(), 'page');
     $users = id(new PhabricatorUser())->loadAllWhere('1 = 1 ORDER BY id DESC LIMIT %d, %d', $pager->getOffset(), $pager->getPageSize());
     $rows = array();
     foreach ($users as $user) {
         $status = '';
         if ($user->getIsDisabled()) {
             $status = 'Disabled';
         } else {
             if ($user->getIsAdmin()) {
                 $status = 'Admin';
             } else {
                 $status = '-';
             }
         }
         $rows[] = array(phabricator_date($user->getDateCreated(), $viewer), phabricator_time($user->getDateCreated(), $viewer), phutil_render_tag('a', array('href' => '/p/' . $user->getUsername() . '/'), phutil_escape_html($user->getUserName())), phutil_escape_html($user->getRealName()), $status, phutil_render_tag('a', array('class' => 'button grey small', 'href' => '/people/edit/' . $user->getID() . '/'), 'Administrate User'));
     }
     $table = new AphrontTableView($rows);
     $table->setHeaders(array('Join Date', 'Time', 'Username', 'Real Name', 'Status', ''));
     $table->setColumnClasses(array(null, 'right', 'pri', 'wide', null, 'action'));
     $table->setColumnVisibility(array(true, true, true, true, $is_admin, $is_admin));
     $panel = new AphrontPanelView();
     $panel->setHeader('People (' . number_format($count) . ')');
     $panel->appendChild($table);
     $panel->appendChild($pager);
     if ($is_admin) {
         $panel->addButton(phutil_render_tag('a', array('href' => '/people/edit/', 'class' => 'button green'), 'Create New Account'));
     }
     return $this->buildStandardPageResponse($panel, array('title' => 'People', 'tab' => 'directory'));
 }
 public function loadPage()
 {
     $table = new PhabricatorUser();
     $conn_r = $table->establishConnection('r');
     $data = queryfx_all($conn_r, 'SELECT * FROM %T user %Q %Q %Q %Q %Q', $table->getTableName(), $this->buildJoinsClause($conn_r), $this->buildWhereClause($conn_r), $this->buildApplicationSearchGroupClause($conn_r), $this->buildOrderClause($conn_r), $this->buildLimitClause($conn_r));
     if ($this->needPrimaryEmail) {
         $table->putInSet(new LiskDAOSet());
     }
     return $table->loadAllFromArray($data);
 }
 /**
  * Load the user identity associated with a session of a given type,
  * identified by token.
  *
  * When the user presents a session token to an API, this method verifies
  * it is of the correct type and loads the corresponding identity if the
  * session exists and is valid.
  *
  * NOTE: `$session_type` is the type of session that is required by the
  * loading context. This prevents use of a Conduit sesssion as a Web
  * session, for example.
  *
  * @param const The type of session to load.
  * @param string The session token.
  * @return PhabricatorUser|null
  * @task use
  */
 public function loadUserForSession($session_type, $session_token)
 {
     $session_kind = self::getSessionKindFromToken($session_token);
     switch ($session_kind) {
         case self::KIND_ANONYMOUS:
             // Don't bother trying to load a user for an anonymous session, since
             // neither the session nor the user exist.
             return null;
         case self::KIND_UNKNOWN:
             // If we don't know what kind of session this is, don't go looking for
             // it.
             return null;
         case self::KIND_USER:
             break;
         case self::KIND_EXTERNAL:
             // TODO: Implement these (T4310).
             return null;
     }
     $session_table = new PhabricatorAuthSession();
     $user_table = new PhabricatorUser();
     $conn_r = $session_table->establishConnection('r');
     $session_key = PhabricatorHash::digest($session_token);
     $cache_parts = $this->getUserCacheQueryParts($conn_r);
     list($cache_selects, $cache_joins, $cache_map, $types_map) = $cache_parts;
     $info = queryfx_one($conn_r, 'SELECT
       s.id AS s_id,
       s.sessionExpires AS s_sessionExpires,
       s.sessionStart AS s_sessionStart,
       s.highSecurityUntil AS s_highSecurityUntil,
       s.isPartial AS s_isPartial,
       s.signedLegalpadDocuments as s_signedLegalpadDocuments,
       u.*
       %Q
     FROM %T u JOIN %T s ON u.phid = s.userPHID
     AND s.type = %s AND s.sessionKey = %s %Q', $cache_selects, $user_table->getTableName(), $session_table->getTableName(), $session_type, $session_key, $cache_joins);
     if (!$info) {
         return null;
     }
     $session_dict = array('userPHID' => $info['phid'], 'sessionKey' => $session_key, 'type' => $session_type);
     $cache_raw = array_fill_keys($cache_map, null);
     foreach ($info as $key => $value) {
         if (strncmp($key, 's_', 2) === 0) {
             unset($info[$key]);
             $session_dict[substr($key, 2)] = $value;
             continue;
         }
         if (isset($cache_map[$key])) {
             unset($info[$key]);
             $cache_raw[$cache_map[$key]] = $value;
             continue;
         }
     }
     $user = $user_table->loadFromArray($info);
     $cache_raw = $this->filterRawCacheData($user, $types_map, $cache_raw);
     $user->attachRawCacheData($cache_raw);
     switch ($session_type) {
         case PhabricatorAuthSession::TYPE_WEB:
             // Explicitly prevent bots and mailing lists from establishing web
             // sessions. It's normally impossible to attach authentication to these
             // accounts, and likewise impossible to generate sessions, but it's
             // technically possible that a session could exist in the database. If
             // one does somehow, refuse to load it.
             if (!$user->canEstablishWebSessions()) {
                 return null;
             }
             break;
     }
     $session = id(new PhabricatorAuthSession())->loadFromArray($session_dict);
     $ttl = PhabricatorAuthSession::getSessionTypeTTL($session_type);
     // If more than 20% of the time on this session has been used, refresh the
     // TTL back up to the full duration. The idea here is that sessions are
     // good forever if used regularly, but get GC'd when they fall out of use.
     // NOTE: If we begin rotating session keys when extending sessions, the
     // CSRF code needs to be updated so CSRF tokens survive session rotation.
     if (time() + 0.8 * $ttl > $session->getSessionExpires()) {
         $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
         $conn_w = $session_table->establishConnection('w');
         queryfx($conn_w, 'UPDATE %T SET sessionExpires = UNIX_TIMESTAMP() + %d WHERE id = %d', $session->getTableName(), $ttl, $session->getID());
         unset($unguarded);
     }
     $user->attachSession($session);
     return $user;
 }
Beispiel #11
0
<?php

echo "Migrating user emails...\n";
$table = new PhabricatorUser();
$table->openTransaction();
$conn = $table->establishConnection('w');
$emails = queryfx_all($conn, 'SELECT phid, email FROM %T LOCK IN SHARE MODE', $table->getTableName());
$emails = ipull($emails, 'email', 'phid');
$etable = new PhabricatorUserEmail();
foreach ($emails as $phid => $email) {
    // NOTE: Grandfather all existing email in as primary / verified. We generate
    // verification codes because they are used for password resets, etc.
    echo "Migrating '{$phid}'...\n";
    queryfx($conn, 'INSERT INTO %T (userPHID, address, verificationCode, isVerified, isPrimary)
      VALUES (%s, %s, %s, 1, 1)', $etable->getTableName(), $phid, $email, Filesystem::readRandomCharacters(24));
}
$table->saveTransaction();
echo "Done.\n";
<?php

$table = new PhabricatorUser();
$conn_w = $table->establishConnection('w');
foreach (new LiskMigrationIterator($table) as $user) {
    $username = $user->getUsername();
    echo pht('Migrating %s...', $username) . "\n";
    if ($user->getIsEmailVerified()) {
        // Email already verified.
        continue;
    }
    $primary = $user->loadPrimaryEmail();
    if (!$primary) {
        // No primary email.
        continue;
    }
    if (!$primary->getIsVerified()) {
        // Primary email not verified.
        continue;
    }
    // Primary email is verified, so mark the account as verified.
    queryfx($conn_w, 'UPDATE %T SET isEmailVerified = 1 WHERE id = %d', $table->getTableName(), $user->getID());
}
echo pht('Done.') . "\n";
Beispiel #13
0
#!/usr/bin/env php
<?php 
$root = dirname(dirname(dirname(__FILE__)));
require_once $root . '/scripts/__init_script__.php';
$table = new PhabricatorUser();
$any_user = queryfx_one($table->establishConnection('r'), 'SELECT * FROM %T LIMIT 1', $table->getTableName());
$is_first_user = !$any_user;
if ($is_first_user) {
    echo pht("WARNING\n\n" . "You're about to create the first account on this install. Normally, " . "you should use the web interface to create the first account, not " . "this script.\n\n" . "If you use the web interface, it will drop you into a nice UI workflow " . "which gives you more help setting up your install. If you create an " . "account with this script instead, you will skip the setup help and you " . "will not be able to access it later.");
    if (!phutil_console_confirm(pht('Skip easy setup and create account?'))) {
        echo pht('Cancelled.') . "\n";
        exit(1);
    }
}
echo pht('Enter a username to create a new account or edit an existing account.');
$username = phutil_console_prompt(pht('Enter a username:'******'Cancelled.') . "\n";
    exit(1);
}
if (!PhabricatorUser::validateUsername($username)) {
    $valid = PhabricatorUser::describeValidUsername();
    echo pht("The username '%s' is invalid. %s", $username, $valid) . "\n";
    exit(1);
}
$user = id(new PhabricatorUser())->loadOneWhere('username = %s', $username);
if (!$user) {
    $original = new PhabricatorUser();
    echo pht("There is no existing user account '%s'.", $username) . "\n";
    $ok = phutil_console_confirm(pht("Do you want to create a new '%s' account?", $username), $default_no = false);
    if (!$ok) {
<?php

// Move timezone, translation and pronoun from the user object to preferences
// so they can be defaulted and edited like other settings.
$table = new PhabricatorUser();
$conn_w = $table->establishConnection('w');
$table_name = $table->getTableName();
$prefs_table = new PhabricatorUserPreferences();
foreach (new LiskRawMigrationIterator($conn_w, $table_name) as $row) {
    $phid = $row['phid'];
    $pref_row = queryfx_one($conn_w, 'SELECT preferences FROM %T WHERE userPHID = %s', $prefs_table->getTableName(), $phid);
    if ($pref_row) {
        try {
            $prefs = phutil_json_decode($pref_row['preferences']);
        } catch (Exception $ex) {
            $prefs = array();
        }
    } else {
        $prefs = array();
    }
    $zone = $row['timezoneIdentifier'];
    if (strlen($zone)) {
        $prefs[PhabricatorTimezoneSetting::SETTINGKEY] = $zone;
    }
    $pronoun = $row['sex'];
    if (strlen($pronoun)) {
        $prefs[PhabricatorPronounSetting::SETTINGKEY] = $pronoun;
    }
    $translation = $row['translation'];
    if (strlen($translation)) {
        $prefs[PhabricatorTranslationSetting::SETTINGKEY] = $translation;
Beispiel #15
0
$root = dirname(dirname(dirname(__FILE__)));
require_once $root . '/scripts/__init_script__.php';
$cert = file_get_contents('php://stdin');
if (!$cert) {
    exit(1);
}
$parts = preg_split('/\\s+/', $cert);
if (count($parts) < 2) {
    exit(1);
}
list($type, $body) = $parts;
$user_dao = new PhabricatorUser();
$ssh_dao = new PhabricatorUserSSHKey();
$conn_r = $user_dao->establishConnection('r');
$row = queryfx_one($conn_r, 'SELECT userName FROM %T u JOIN %T ssh ON u.phid = ssh.userPHID
    WHERE ssh.keyType = %s AND ssh.keyBody = %s', $user_dao->getTableName(), $ssh_dao->getTableName(), $type, $body);
if (!$row) {
    exit(1);
}
$user = idx($row, 'userName');
if (!$user) {
    exit(1);
}
if (!PhabricatorUser::validateUsername($user)) {
    exit(1);
}
$bin = $root . '/bin/ssh-exec';
$cmd = csprintf('%s --phabricator-ssh-user %s', $bin, $user);
// This is additional escaping for the SSH 'command="..."' string.
$cmd = addcslashes($cmd, '"\\');
$options = array('command="' . $cmd . '"', 'no-port-forwarding', 'no-X11-forwarding', 'no-agent-forwarding', 'no-pty');
 protected function applyFinalEffects(PhabricatorLiskDAO $object, array $xactions)
 {
     // Clear the availability caches for users whose availability is affected
     // by this edit.
     $invalidate_all = false;
     $invalidate_phids = array();
     foreach ($xactions as $xaction) {
         switch ($xaction->getTransactionType()) {
             case PhabricatorCalendarEventUntilDateTransaction::TRANSACTIONTYPE:
             case PhabricatorCalendarEventStartDateTransaction::TRANSACTIONTYPE:
             case PhabricatorCalendarEventEndDateTransaction::TRANSACTIONTYPE:
             case PhabricatorCalendarEventCancelTransaction::TRANSACTIONTYPE:
             case PhabricatorCalendarEventAllDayTransaction::TRANSACTIONTYPE:
                 // For these kinds of changes, we need to invalidate the availabilty
                 // caches for all attendees.
                 $invalidate_all = true;
                 break;
             case PhabricatorCalendarEventAcceptTransaction::TRANSACTIONTYPE:
             case PhabricatorCalendarEventDeclineTransaction::TRANSACTIONTYPE:
                 $acting_phid = $this->getActingAsPHID();
                 $invalidate_phids[$acting_phid] = $acting_phid;
                 break;
             case PhabricatorCalendarEventInviteTransaction::TRANSACTIONTYPE:
                 foreach ($xaction->getNewValue() as $phid => $ignored) {
                     $invalidate_phids[$phid] = $phid;
                 }
                 break;
         }
     }
     $phids = mpull($object->getInvitees(), 'getInviteePHID');
     $phids = array_fuse($phids);
     if (!$invalidate_all) {
         $phids = array_select_keys($phids, $invalidate_phids);
     }
     if ($phids) {
         $object->applyViewerTimezone($this->getActor());
         $user = new PhabricatorUser();
         $conn_w = $user->establishConnection('w');
         queryfx($conn_w, 'UPDATE %T SET availabilityCacheTTL = NULL
       WHERE phid IN (%Ls) AND availabilityCacheTTL >= %d', $user->getTableName(), $phids, $object->getDateFromForCache());
     }
     return $xactions;
 }
 public function loadResults()
 {
     $viewer = $this->getViewer();
     $raw_query = $this->getRawQuery();
     $results = array();
     $users = array();
     if (strlen($raw_query)) {
         // This is an arbitrary limit which is just larger than any limit we
         // actually use in the application.
         // TODO: The datasource should pass this in the query.
         $limit = 15;
         $user_table = new PhabricatorUser();
         $conn_r = $user_table->establishConnection('r');
         $ids = queryfx_all($conn_r, 'SELECT id FROM %T WHERE username LIKE %>
       ORDER BY username ASC LIMIT %d', $user_table->getTableName(), $raw_query, $limit);
         $ids = ipull($ids, 'id');
         if (count($ids) < $limit) {
             // If we didn't find enough username hits, look for real name hits.
             // We need to pull the entire pagesize so that we end up with the
             // right number of items if this query returns many duplicate IDs
             // that we've already selected.
             $realname_ids = queryfx_all($conn_r, 'SELECT DISTINCT userID FROM %T WHERE token LIKE %>
         ORDER BY token ASC LIMIT %d', PhabricatorUser::NAMETOKEN_TABLE, $raw_query, $limit);
             $realname_ids = ipull($realname_ids, 'userID');
             $ids = array_merge($ids, $realname_ids);
             $ids = array_unique($ids);
             $ids = array_slice($ids, 0, $limit);
         }
         // Always add the logged-in user because some tokenizers autosort them
         // first. They'll be filtered out on the client side if they don't
         // match the query.
         if ($viewer->getID()) {
             $ids[] = $viewer->getID();
         }
         if ($ids) {
             $users = id(new PhabricatorPeopleQuery())->setViewer($viewer)->withIDs($ids)->execute();
         }
     }
     if ($this->enrichResults && $users) {
         $phids = mpull($users, 'getPHID');
         $handles = id(new PhabricatorHandleQuery())->setViewer($viewer)->withPHIDs($phids)->execute();
     }
     foreach ($users as $user) {
         $closed = null;
         if ($user->getIsDisabled()) {
             $closed = pht('Disabled');
         } else {
             if ($user->getIsSystemAgent()) {
                 $closed = pht('Bot/Script');
             }
         }
         $result = id(new PhabricatorTypeaheadResult())->setName($user->getFullName())->setURI('/p/' . $user->getUsername())->setPHID($user->getPHID())->setPriorityString($user->getUsername())->setPriorityType('user')->setClosed($closed);
         if ($this->enrichResults) {
             $display_type = 'User';
             if ($user->getIsAdmin()) {
                 $display_type = 'Administrator';
             }
             $result->setDisplayType($display_type);
             $result->setImageURI($handles[$user->getPHID()]->getImageURI());
         }
         $results[] = $result;
     }
     return $results;
 }
Beispiel #18
0
#!/usr/bin/env php
<?php 
$root = dirname(dirname(dirname(__FILE__)));
require_once $root . '/scripts/__init_script__.php';
$user_dao = new PhabricatorUser();
$ssh_dao = new PhabricatorUserSSHKey();
$conn_r = $user_dao->establishConnection('r');
$rows = queryfx_all($conn_r, 'SELECT userName, keyBody, keyType FROM %T u JOIN %T ssh
    ON u.phid = ssh.userPHID', $user_dao->getTableName(), $ssh_dao->getTableName());
if (!$rows) {
    echo pht('No keys found.') . "\n";
    exit(1);
}
$bin = $root . '/bin/ssh-exec';
foreach ($rows as $row) {
    $user = $row['userName'];
    $cmd = csprintf('%s --phabricator-ssh-user %s', $bin, $user);
    // This is additional escaping for the SSH 'command="..."' string.
    $cmd = addcslashes($cmd, '"\\');
    // Strip out newlines and other nonsense from the key type and key body.
    $type = $row['keyType'];
    $type = preg_replace('@[\\x00-\\x20]+@', '', $type);
    $key = $row['keyBody'];
    $key = preg_replace('@[\\x00-\\x20]+@', '', $key);
    $options = array('command="' . $cmd . '"', 'no-port-forwarding', 'no-X11-forwarding', 'no-agent-forwarding', 'no-pty');
    $options = implode(',', $options);
    $lines[] = $options . ' ' . $type . ' ' . $key . "\n";
}
echo implode('', $lines);
exit(0);
Beispiel #19
0
/*
 * Copyright 2012 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
echo "Migrating user emails...\n";
$table = new PhabricatorUser();
$conn = $table->establishConnection('r');
$emails = queryfx_all($conn, 'SELECT phid, email FROM %T', $table->getTableName());
$emails = ipull($emails, 'email', 'phid');
$etable = new PhabricatorUserEmail();
$econn = $etable->establishConnection('w');
foreach ($emails as $phid => $email) {
    // NOTE: Grandfather all existing email in as primary / verified. We generate
    // verification codes because they are used for password resets, etc.
    echo "Migrating '{$phid}'...\n";
    queryfx($econn, 'INSERT INTO %T (userPHID, address, verificationCode, isVerified, isPrimary)
      VALUES (%s, %s, %s, 1, 1)', $etable->getTableName(), $phid, $email, Filesystem::readRandomCharacters(24));
}
echo "Done.\n";
<?php

$table = new PhabricatorUser();
$conn_w = $table->establishConnection('w');
echo "Trimming trailing whitespace from user real names...\n";
foreach (new LiskMigrationIterator($table) as $user) {
    $id = $user->getID();
    $real = $user->getRealName();
    $trim = rtrim($real);
    if ($trim == $real) {
        echo "User {$id} is already trim.\n";
        continue;
    }
    echo "Trimming user {$id} from '{$real}' to '{$trim}'.\n";
    qsprintf($conn_w, 'UPDATE %T SET realName = %s WHERE id = %d', $table->getTableName(), $real, $id);
}
echo "Done.\n";
 /**
  * Load the user identity associated with a session of a given type,
  * identified by token.
  *
  * When the user presents a session token to an API, this method verifies
  * it is of the correct type and loads the corresponding identity if the
  * session exists and is valid.
  *
  * NOTE: `$session_type` is the type of session that is required by the
  * loading context. This prevents use of a Conduit sesssion as a Web
  * session, for example.
  *
  * @param const The type of session to load.
  * @param string The session token.
  * @return PhabricatorUser|null
  * @task use
  */
 public function loadUserForSession($session_type, $session_token)
 {
     $session_kind = self::getSessionKindFromToken($session_token);
     switch ($session_kind) {
         case self::KIND_ANONYMOUS:
             // Don't bother trying to load a user for an anonymous session, since
             // neither the session nor the user exist.
             return null;
         case self::KIND_UNKNOWN:
             // If we don't know what kind of session this is, don't go looking for
             // it.
             return null;
         case self::KIND_USER:
             break;
         case self::KIND_EXTERNAL:
             // TODO: Implement these (T4310).
             return null;
     }
     $session_table = new PhabricatorAuthSession();
     $user_table = new PhabricatorUser();
     $conn_r = $session_table->establishConnection('r');
     $session_key = PhabricatorHash::digest($session_token);
     // NOTE: We're being clever here because this happens on every page load,
     // and by joining we can save a query. This might be getting too clever
     // for its own good, though...
     $info = queryfx_one($conn_r, 'SELECT
       s.id AS s_id,
       s.sessionExpires AS s_sessionExpires,
       s.sessionStart AS s_sessionStart,
       s.highSecurityUntil AS s_highSecurityUntil,
       s.isPartial AS s_isPartial,
       u.*
     FROM %T u JOIN %T s ON u.phid = s.userPHID
     AND s.type = %s AND s.sessionKey = %s', $user_table->getTableName(), $session_table->getTableName(), $session_type, $session_key);
     if (!$info) {
         return null;
     }
     $session_dict = array('userPHID' => $info['phid'], 'sessionKey' => $session_key, 'type' => $session_type);
     foreach ($info as $key => $value) {
         if (strncmp($key, 's_', 2) === 0) {
             unset($info[$key]);
             $session_dict[substr($key, 2)] = $value;
         }
     }
     $session = id(new PhabricatorAuthSession())->loadFromArray($session_dict);
     $ttl = PhabricatorAuthSession::getSessionTypeTTL($session_type);
     // If more than 20% of the time on this session has been used, refresh the
     // TTL back up to the full duration. The idea here is that sessions are
     // good forever if used regularly, but get GC'd when they fall out of use.
     // NOTE: If we begin rotating session keys when extending sessions, the
     // CSRF code needs to be updated so CSRF tokens survive session rotation.
     if (time() + 0.8 * $ttl > $session->getSessionExpires()) {
         $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
         $conn_w = $session_table->establishConnection('w');
         queryfx($conn_w, 'UPDATE %T SET sessionExpires = UNIX_TIMESTAMP() + %d WHERE id = %d', $session->getTableName(), $ttl, $session->getID());
         unset($unguarded);
     }
     $user = $user_table->loadFromArray($info);
     $user->attachSession($session);
     return $user;
 }
<?php

$table = new ManiphestTask();
$conn_w = $table->establishConnection('w');
$user_table = new PhabricatorUser();
$user_conn = $user_table->establishConnection('r');
foreach (new LiskMigrationIterator($table) as $task) {
    $id = $task->getID();
    echo pht('Checking task %s...', "T{$id}") . "\n";
    $owner_phid = $task->getOwnerPHID();
    if (!$owner_phid && !$task->getOwnerOrdering()) {
        // No owner and no ordering; we're all set.
        continue;
    }
    $owner_row = queryfx_one($user_conn, 'SELECT * FROM %T WHERE phid = %s', $user_table->getTableName(), $owner_phid);
    if ($owner_row) {
        $value = $owner_row['userName'];
    } else {
        $value = null;
    }
    if ($value !== $task->getOwnerOrdering()) {
        queryfx($conn_w, 'UPDATE %T SET ownerOrdering = %ns WHERE id = %d', $table->getTableName(), $value, $task->getID());
    }
}
echo pht('Done.') . "\n";
 protected function applyFinalEffects(PhabricatorLiskDAO $object, array $xactions)
 {
     // Clear the availability caches for users whose availability is affected
     // by this edit.
     $invalidate_all = false;
     $invalidate_phids = array();
     foreach ($xactions as $xaction) {
         switch ($xaction->getTransactionType()) {
             case PhabricatorCalendarEventTransaction::TYPE_ICON:
                 break;
             case PhabricatorCalendarEventTransaction::TYPE_RECURRING:
             case PhabricatorCalendarEventTransaction::TYPE_FREQUENCY:
             case PhabricatorCalendarEventTransaction::TYPE_RECURRENCE_END_DATE:
             case PhabricatorCalendarEventTransaction::TYPE_INSTANCE_OF_EVENT:
             case PhabricatorCalendarEventTransaction::TYPE_SEQUENCE_INDEX:
             case PhabricatorCalendarEventTransaction::TYPE_START_DATE:
             case PhabricatorCalendarEventTransaction::TYPE_END_DATE:
             case PhabricatorCalendarEventTransaction::TYPE_CANCEL:
             case PhabricatorCalendarEventTransaction::TYPE_ALL_DAY:
                 // For these kinds of changes, we need to invalidate the availabilty
                 // caches for all attendees.
                 $invalidate_all = true;
                 break;
             case PhabricatorCalendarEventTransaction::TYPE_INVITE:
                 foreach ($xaction->getNewValue() as $phid => $ignored) {
                     $invalidate_phids[$phid] = $phid;
                 }
                 break;
         }
     }
     $phids = mpull($object->getInvitees(), 'getInviteePHID');
     $phids = array_fuse($phids);
     if (!$invalidate_all) {
         $phids = array_select_keys($phids, $invalidate_phids);
     }
     if ($phids) {
         $user = new PhabricatorUser();
         $conn_w = $user->establishConnection('w');
         queryfx($conn_w, 'UPDATE %T SET availabilityCacheTTL = NULL
       WHERE phid IN (%Ls) AND availabilityCacheTTL >= %d', $user->getTableName(), $phids, $object->getDateFromForCache());
     }
     return $xactions;
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $query = $request->getStr('q');
     $need_rich_data = false;
     $need_users = false;
     $need_applications = false;
     $need_all_users = false;
     $need_lists = false;
     $need_projs = false;
     $need_repos = false;
     $need_packages = false;
     $need_upforgrabs = false;
     $need_arcanist_projects = false;
     $need_noproject = false;
     $need_symbols = false;
     switch ($this->type) {
         case 'mainsearch':
             $need_users = true;
             $need_applications = true;
             $need_rich_data = true;
             $need_symbols = true;
             break;
         case 'searchowner':
             $need_users = true;
             $need_upforgrabs = true;
             break;
         case 'searchproject':
             $need_projs = true;
             $need_noproject = true;
             break;
         case 'users':
             $need_users = true;
             break;
         case 'mailable':
             $need_users = true;
             $need_lists = true;
             break;
         case 'allmailable':
             $need_users = true;
             $need_all_users = true;
             $need_lists = true;
             break;
         case 'projects':
             $need_projs = true;
             break;
         case 'usersorprojects':
             $need_users = true;
             $need_projs = true;
             break;
         case 'repositories':
             $need_repos = true;
             break;
         case 'packages':
             $need_packages = true;
             break;
         case 'accounts':
             $need_users = true;
             $need_all_users = true;
             break;
         case 'arcanistprojects':
             $need_arcanist_projects = true;
             break;
     }
     $results = array();
     if ($need_upforgrabs) {
         $results[] = id(new PhabricatorTypeaheadResult())->setName('upforgrabs (Up For Grabs)')->setPHID(ManiphestTaskOwner::OWNER_UP_FOR_GRABS);
     }
     if ($need_noproject) {
         $results[] = id(new PhabricatorTypeaheadResult())->setName('noproject (No Project)')->setPHID(ManiphestTaskOwner::PROJECT_NO_PROJECT);
     }
     if ($need_users) {
         $columns = array('isSystemAgent', 'isAdmin', 'isDisabled', 'userName', 'realName', 'phid');
         if ($query) {
             // This is an arbitrary limit which is just larger than any limit we
             // actually use in the application.
             // TODO: The datasource should pass this in the query.
             $limit = 15;
             $user_table = new PhabricatorUser();
             $conn_r = $user_table->establishConnection('r');
             $ids = queryfx_all($conn_r, 'SELECT id FROM %T WHERE username LIKE %>
         ORDER BY username ASC LIMIT %d', $user_table->getTableName(), $query, $limit);
             $ids = ipull($ids, 'id');
             if (count($ids) < $limit) {
                 // If we didn't find enough username hits, look for real name hits.
                 // We need to pull the entire pagesize so that we end up with the
                 // right number of items if this query returns many duplicate IDs
                 // that we've already selected.
                 $realname_ids = queryfx_all($conn_r, 'SELECT DISTINCT userID FROM %T WHERE token LIKE %>
           ORDER BY token ASC LIMIT %d', PhabricatorUser::NAMETOKEN_TABLE, $query, $limit);
                 $realname_ids = ipull($realname_ids, 'userID');
                 $ids = array_merge($ids, $realname_ids);
                 $ids = array_unique($ids);
                 $ids = array_slice($ids, 0, $limit);
             }
             // Always add the logged-in user because some tokenizers autosort them
             // first. They'll be filtered out on the client side if they don't
             // match the query.
             $ids[] = $request->getUser()->getID();
             if ($ids) {
                 $users = id(new PhabricatorUser())->loadColumnsWhere($columns, 'id IN (%Ld)', $ids);
             } else {
                 $users = array();
             }
         } else {
             $users = id(new PhabricatorUser())->loadColumns($columns);
         }
         if ($need_rich_data) {
             $phids = mpull($users, 'getPHID');
             $handles = id(new PhabricatorObjectHandleData($phids))->loadHandles();
         }
         foreach ($users as $user) {
             if (!$need_all_users) {
                 if ($user->getIsSystemAgent()) {
                     continue;
                 }
                 if ($user->getIsDisabled()) {
                     continue;
                 }
             }
             $result = id(new PhabricatorTypeaheadResult())->setName($user->getFullName())->setURI('/p/' . $user->getUsername())->setPHID($user->getPHID())->setPriorityString($user->getUsername());
             if ($need_rich_data) {
                 $display_type = 'User';
                 if ($user->getIsAdmin()) {
                     $display_type = 'Administrator';
                 }
                 $result->setDisplayType($display_type);
                 $result->setImageURI($handles[$user->getPHID()]->getImageURI());
                 $result->setPriorityType('user');
             }
             $results[] = $result;
         }
     }
     if ($need_lists) {
         $lists = id(new PhabricatorMetaMTAMailingList())->loadAll();
         foreach ($lists as $list) {
             $results[] = id(new PhabricatorTypeaheadResult())->setName($list->getName())->setURI($list->getURI())->setPHID($list->getPHID());
         }
     }
     if ($need_projs) {
         $projs = id(new PhabricatorProject())->loadAllWhere('status != %d', PhabricatorProjectStatus::STATUS_ARCHIVED);
         foreach ($projs as $proj) {
             $results[] = id(new PhabricatorTypeaheadResult())->setName($proj->getName())->setURI('/project/view/' . $proj->getID() . '/')->setPHID($proj->getPHID());
         }
     }
     if ($need_repos) {
         $repos = id(new PhabricatorRepository())->loadAll();
         foreach ($repos as $repo) {
             $results[] = id(new PhabricatorTypeaheadResult())->setName('r' . $repo->getCallsign() . ' (' . $repo->getName() . ')')->setURI('/diffusion/' . $repo->getCallsign() . '/')->setPHID($repo->getPHID())->setPriorityString('r' . $repo->getCallsign());
         }
     }
     if ($need_packages) {
         $packages = id(new PhabricatorOwnersPackage())->loadAll();
         foreach ($packages as $package) {
             $results[] = id(new PhabricatorTypeaheadResult())->setName($package->getName())->setURI('/owners/package/' . $package->getID() . '/')->setPHID($package->getPHID());
         }
     }
     if ($need_arcanist_projects) {
         $arcprojs = id(new PhabricatorRepositoryArcanistProject())->loadAll();
         foreach ($arcprojs as $proj) {
             $results[] = id(new PhabricatorTypeaheadResult())->setName($proj->getName())->setPHID($proj->getPHID());
         }
     }
     if ($need_applications) {
         $applications = PhabricatorApplication::getAllInstalledApplications();
         foreach ($applications as $application) {
             $uri = $application->getTypeaheadURI();
             if (!$uri) {
                 continue;
             }
             $name = $application->getName() . ' ' . $application->getShortDescription();
             $results[] = id(new PhabricatorTypeaheadResult())->setName($name)->setURI($uri)->setPHID($application->getPHID())->setPriorityString($application->getName())->setDisplayName($application->getName())->setDisplayType($application->getShortDescription())->setImageuRI($application->getIconURI())->setPriorityType('apps');
         }
     }
     if ($need_symbols) {
         $symbols = id(new DiffusionSymbolQuery())->setNamePrefix($query)->setLimit(15)->needArcanistProjects(true)->needRepositories(true)->needPaths(true)->execute();
         foreach ($symbols as $symbol) {
             $lang = $symbol->getSymbolLanguage();
             $name = $symbol->getSymbolName();
             $type = $symbol->getSymbolType();
             $proj = $symbol->getArcanistProject()->getName();
             $results[] = id(new PhabricatorTypeaheadResult())->setName($name)->setURI($symbol->getURI())->setPHID(md5($symbol->getURI()))->setDisplayName($symbol->getName())->setDisplayType(strtoupper($lang) . ' ' . ucwords($type) . ' (' . $proj . ')')->setPriorityType('symb');
         }
     }
     $content = mpull($results, 'getWireFormat');
     if ($request->isAjax()) {
         return id(new AphrontAjaxResponse())->setContent($content);
     }
     // If there's a non-Ajax request to this endpoint, show results in a tabular
     // format to make it easier to debug typeahead output.
     $rows = array();
     foreach ($results as $result) {
         $wire = $result->getWireFormat();
         foreach ($wire as $k => $v) {
             $wire[$k] = phutil_escape_html($v);
         }
         $rows[] = $wire;
     }
     $table = new AphrontTableView($rows);
     $table->setHeaders(array('Name', 'URI', 'PHID', 'Priority', 'Display Name', 'Display Type', 'Image URI', 'Priority Type'));
     $panel = new AphrontPanelView();
     $panel->setHeader('Typeahead Results');
     $panel->appendChild($table);
     return $this->buildStandardPageResponse($panel, array('title' => 'Typeahead Results'));
 }