repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilAuthAdapter.php | src/applications/auth/adapter/PhutilAuthAdapter.php | <?php
/**
* Abstract interface to an identity provider or authentication source, like
* Twitter, Facebook, or Google.
*
* Generally, adapters are handed some set of credentials particular to the
* provider they adapt, and they turn those credentials into standard
* information about the user's identity. For example, the LDAP adapter is given
* a username and password (and some other configuration information), uses them
* to talk to the LDAP server, and produces a username, email, and so forth.
*
* Since the credentials a provider requires are specific to each provider, the
* base adapter does not specify how an adapter should be constructed or
* configured -- only what information it is expected to be able to provide once
* properly configured.
*/
abstract class PhutilAuthAdapter extends Phobject {
final public function getAccountIdentifiers() {
$result = $this->newAccountIdentifiers();
assert_instances_of($result, 'PhabricatorExternalAccountIdentifier');
return $result;
}
protected function newAccountIdentifiers() {
$identifiers = array();
$raw_identifier = $this->getAccountID();
if ($raw_identifier !== null) {
$identifiers[] = $this->newAccountIdentifier($raw_identifier);
}
return $identifiers;
}
final protected function newAccountIdentifier($raw_identifier) {
return id(new PhabricatorExternalAccountIdentifier())
->setIdentifierRaw($raw_identifier);
}
/**
* Get a unique identifier associated with the account.
*
* This identifier should be permanent, immutable, and uniquely identify
* the account. If possible, it should be nonsensitive. For providers that
* have a GUID or PHID value for accounts, these are the best values to use.
*
* You can implement @{method:newAccountIdentifiers} instead if a provider
* is unable to emit identifiers with all of these properties.
*
* If the adapter was unable to authenticate an identity, it should return
* `null`.
*
* @return string|null Unique account identifier, or `null` if authentication
* failed.
*/
public function getAccountID() {
throw new PhutilMethodNotImplementedException();
}
/**
* Get a string identifying this adapter, like "ldap". This string should be
* unique to the adapter class.
*
* @return string Unique adapter identifier.
*/
abstract public function getAdapterType();
/**
* Get a string identifying the domain this adapter is acting on. This allows
* an adapter (like LDAP) to act against different identity domains without
* conflating credentials. For providers like Facebook or Google, the adapters
* just return the relevant domain name.
*
* @return string Domain the adapter is associated with.
*/
abstract public function getAdapterDomain();
/**
* Generate a string uniquely identifying this adapter configuration. Within
* the scope of a given key, all account IDs must uniquely identify exactly
* one identity.
*
* @return string Unique identifier for this adapter configuration.
*/
public function getAdapterKey() {
return $this->getAdapterType().':'.$this->getAdapterDomain();
}
/**
* Optionally, return an email address associated with this account.
*
* @return string|null An email address associated with the account, or
* `null` if data is not available.
*/
public function getAccountEmail() {
return null;
}
/**
* Optionally, return a human readable username associated with this account.
*
* @return string|null Account username, or `null` if data isn't available.
*/
public function getAccountName() {
return null;
}
/**
* Optionally, return a URI corresponding to a human-viewable profile for
* this account.
*
* @return string|null A profile URI associated with this account, or
* `null` if the data isn't available.
*/
public function getAccountURI() {
return null;
}
/**
* Optionally, return a profile image URI associated with this account.
*
* @return string|null URI for an account profile image, or `null` if one is
* not available.
*/
public function getAccountImageURI() {
return null;
}
/**
* Optionally, return a real name associated with this account.
*
* @return string|null A human real name, or `null` if this data is not
* available.
*/
public function getAccountRealName() {
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilTwitchAuthAdapter.php | src/applications/auth/adapter/PhutilTwitchAuthAdapter.php | <?php
/**
* Authentication adapter for Twitch.tv OAuth2.
*/
final class PhutilTwitchAuthAdapter extends PhutilOAuthAuthAdapter {
public function getAdapterType() {
return 'twitch';
}
public function getAdapterDomain() {
return 'twitch.tv';
}
public function getAccountID() {
return $this->getOAuthAccountData('_id');
}
public function getAccountEmail() {
return $this->getOAuthAccountData('email');
}
public function getAccountName() {
return $this->getOAuthAccountData('name');
}
public function getAccountImageURI() {
return $this->getOAuthAccountData('logo');
}
public function getAccountURI() {
$name = $this->getAccountName();
if ($name) {
return 'http://www.twitch.tv/'.$name;
}
return null;
}
public function getAccountRealName() {
return $this->getOAuthAccountData('display_name');
}
protected function getAuthenticateBaseURI() {
return 'https://api.twitch.tv/kraken/oauth2/authorize';
}
protected function getTokenBaseURI() {
return 'https://api.twitch.tv/kraken/oauth2/token';
}
public function getScope() {
return 'user_read';
}
public function getExtraAuthenticateParameters() {
return array(
'response_type' => 'code',
);
}
public function getExtraTokenParameters() {
return array(
'grant_type' => 'authorization_code',
);
}
protected function loadOAuthAccountData() {
return id(new PhutilTwitchFuture())
->setClientID($this->getClientID())
->setAccessToken($this->getAccessToken())
->setRawTwitchQuery('user')
->resolve();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilDisqusAuthAdapter.php | src/applications/auth/adapter/PhutilDisqusAuthAdapter.php | <?php
/**
* Authentication adapter for Disqus OAuth2.
*/
final class PhutilDisqusAuthAdapter extends PhutilOAuthAuthAdapter {
public function getAdapterType() {
return 'disqus';
}
public function getAdapterDomain() {
return 'disqus.com';
}
public function getAccountID() {
return $this->getOAuthAccountData('id');
}
public function getAccountEmail() {
return $this->getOAuthAccountData('email');
}
public function getAccountName() {
return $this->getOAuthAccountData('username');
}
public function getAccountImageURI() {
return $this->getOAuthAccountData('avatar', 'permalink');
}
public function getAccountURI() {
return $this->getOAuthAccountData('profileUrl');
}
public function getAccountRealName() {
return $this->getOAuthAccountData('name');
}
protected function getAuthenticateBaseURI() {
return 'https://disqus.com/api/oauth/2.0/authorize/';
}
protected function getTokenBaseURI() {
return 'https://disqus.com/api/oauth/2.0/access_token/';
}
public function getScope() {
return 'read';
}
public function getExtraAuthenticateParameters() {
return array(
'response_type' => 'code',
);
}
public function getExtraTokenParameters() {
return array(
'grant_type' => 'authorization_code',
);
}
protected function loadOAuthAccountData() {
$uri = new PhutilURI('https://disqus.com/api/3.0/users/details.json');
$uri->replaceQueryParam('api_key', $this->getClientID());
$uri->replaceQueryParam('access_token', $this->getAccessToken());
$uri = (string)$uri;
$future = new HTTPSFuture($uri);
$future->setMethod('GET');
list($body) = $future->resolvex();
try {
$data = phutil_json_decode($body);
return $data['response'];
} catch (PhutilJSONParserException $ex) {
throw new PhutilProxyException(
pht('Expected valid JSON response from Disqus account data request.'),
$ex);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilOAuthAuthAdapter.php | src/applications/auth/adapter/PhutilOAuthAuthAdapter.php | <?php
/**
* Abstract adapter for OAuth2 providers.
*/
abstract class PhutilOAuthAuthAdapter extends PhutilAuthAdapter {
private $clientID;
private $clientSecret;
private $redirectURI;
private $scope;
private $state;
private $code;
private $accessTokenData;
private $oauthAccountData;
abstract protected function getAuthenticateBaseURI();
abstract protected function getTokenBaseURI();
abstract protected function loadOAuthAccountData();
public function getAuthenticateURI() {
$params = array(
'client_id' => $this->getClientID(),
'scope' => $this->getScope(),
'redirect_uri' => $this->getRedirectURI(),
'state' => $this->getState(),
) + $this->getExtraAuthenticateParameters();
$uri = new PhutilURI($this->getAuthenticateBaseURI(), $params);
return phutil_string_cast($uri);
}
public function getAdapterType() {
$this_class = get_class($this);
$type_name = str_replace('PhutilAuthAdapterOAuth', '', $this_class);
return strtolower($type_name);
}
public function setState($state) {
$this->state = $state;
return $this;
}
public function getState() {
return $this->state;
}
public function setCode($code) {
$this->code = $code;
return $this;
}
public function getCode() {
return $this->code;
}
public function setRedirectURI($redirect_uri) {
$this->redirectURI = $redirect_uri;
return $this;
}
public function getRedirectURI() {
return $this->redirectURI;
}
public function getExtraAuthenticateParameters() {
return array();
}
public function getExtraTokenParameters() {
return array();
}
public function getExtraRefreshParameters() {
return array();
}
public function setScope($scope) {
$this->scope = $scope;
return $this;
}
public function getScope() {
return $this->scope;
}
public function setClientSecret(PhutilOpaqueEnvelope $client_secret) {
$this->clientSecret = $client_secret;
return $this;
}
public function getClientSecret() {
return $this->clientSecret;
}
public function setClientID($client_id) {
$this->clientID = $client_id;
return $this;
}
public function getClientID() {
return $this->clientID;
}
public function getAccessToken() {
return $this->getAccessTokenData('access_token');
}
public function getAccessTokenExpires() {
return $this->getAccessTokenData('expires_epoch');
}
public function getRefreshToken() {
return $this->getAccessTokenData('refresh_token');
}
protected function getAccessTokenData($key, $default = null) {
if ($this->accessTokenData === null) {
$this->accessTokenData = $this->loadAccessTokenData();
}
return idx($this->accessTokenData, $key, $default);
}
public function supportsTokenRefresh() {
return false;
}
public function refreshAccessToken($refresh_token) {
$this->accessTokenData = $this->loadRefreshTokenData($refresh_token);
return $this;
}
protected function loadRefreshTokenData($refresh_token) {
$params = array(
'refresh_token' => $refresh_token,
) + $this->getExtraRefreshParameters();
// NOTE: Make sure we return the refresh_token so that subsequent
// calls to getRefreshToken() return it; providers normally do not echo
// it back for token refresh requests.
return $this->makeTokenRequest($params) + array(
'refresh_token' => $refresh_token,
);
}
protected function loadAccessTokenData() {
$code = $this->getCode();
if (!$code) {
throw new PhutilInvalidStateException('setCode');
}
$params = array(
'code' => $this->getCode(),
) + $this->getExtraTokenParameters();
return $this->makeTokenRequest($params);
}
private function makeTokenRequest(array $params) {
$uri = $this->getTokenBaseURI();
$query_data = array(
'client_id' => $this->getClientID(),
'client_secret' => $this->getClientSecret()->openEnvelope(),
'redirect_uri' => $this->getRedirectURI(),
) + $params;
$future = new HTTPSFuture($uri, $query_data);
$future->setMethod('POST');
list($body) = $future->resolvex();
$data = $this->readAccessTokenResponse($body);
if (isset($data['expires_in'])) {
$data['expires_epoch'] = $data['expires_in'];
} else if (isset($data['expires'])) {
$data['expires_epoch'] = $data['expires'];
}
// If we got some "expires" value back, interpret it as an epoch timestamp
// if it's after the year 2010 and as a relative number of seconds
// otherwise.
if (isset($data['expires_epoch'])) {
if ($data['expires_epoch'] < (60 * 60 * 24 * 365 * 40)) {
$data['expires_epoch'] += time();
}
}
if (isset($data['error'])) {
throw new Exception(pht('Access token error: %s', $data['error']));
}
return $data;
}
protected function readAccessTokenResponse($body) {
// NOTE: Most providers either return JSON or HTTP query strings, so try
// both mechanisms. If your provider does something else, override this
// method.
$data = json_decode($body, true);
if (!is_array($data)) {
$data = array();
parse_str($body, $data);
}
if (empty($data['access_token']) &&
empty($data['error'])) {
throw new Exception(
pht('Failed to decode OAuth access token response: %s', $body));
}
return $data;
}
protected function getOAuthAccountData($key, $default = null) {
if ($this->oauthAccountData === null) {
$this->oauthAccountData = $this->loadOAuthAccountData();
}
return idx($this->oauthAccountData, $key, $default);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilPhabricatorAuthAdapter.php | src/applications/auth/adapter/PhutilPhabricatorAuthAdapter.php | <?php
/**
* Authentication adapter for Phabricator OAuth2.
*/
final class PhutilPhabricatorAuthAdapter extends PhutilOAuthAuthAdapter {
private $phabricatorBaseURI;
private $adapterDomain;
public function setPhabricatorBaseURI($uri) {
$this->phabricatorBaseURI = $uri;
return $this;
}
public function getPhabricatorBaseURI() {
return $this->phabricatorBaseURI;
}
public function getAdapterDomain() {
return $this->adapterDomain;
}
public function setAdapterDomain($domain) {
$this->adapterDomain = $domain;
return $this;
}
public function getAdapterType() {
return 'phabricator';
}
public function getAccountID() {
return $this->getOAuthAccountData('phid');
}
public function getAccountEmail() {
return $this->getOAuthAccountData('primaryEmail');
}
public function getAccountName() {
return $this->getOAuthAccountData('userName');
}
public function getAccountImageURI() {
return $this->getOAuthAccountData('image');
}
public function getAccountURI() {
return $this->getOAuthAccountData('uri');
}
public function getAccountRealName() {
return $this->getOAuthAccountData('realName');
}
protected function getAuthenticateBaseURI() {
return $this->getPhabricatorURI('oauthserver/auth/');
}
protected function getTokenBaseURI() {
return $this->getPhabricatorURI('oauthserver/token/');
}
public function getScope() {
return '';
}
public function getExtraAuthenticateParameters() {
return array(
'response_type' => 'code',
);
}
public function getExtraTokenParameters() {
return array(
'grant_type' => 'authorization_code',
);
}
protected function loadOAuthAccountData() {
$uri = id(new PhutilURI($this->getPhabricatorURI('api/user.whoami')))
->replaceQueryParam('access_token', $this->getAccessToken());
list($body) = id(new HTTPSFuture($uri))->resolvex();
try {
$data = phutil_json_decode($body);
return $data['result'];
} catch (PhutilJSONParserException $ex) {
throw new Exception(
pht(
'Expected valid JSON response from "user.whoami" request.'),
$ex);
}
}
private function getPhabricatorURI($path) {
return rtrim($this->phabricatorBaseURI, '/').'/'.ltrim($path, '/');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilWordPressAuthAdapter.php | src/applications/auth/adapter/PhutilWordPressAuthAdapter.php | <?php
/**
* Authentication adapter for WordPress.com OAuth2.
*/
final class PhutilWordPressAuthAdapter extends PhutilOAuthAuthAdapter {
public function getAdapterType() {
return 'wordpress';
}
public function getAdapterDomain() {
return 'wordpress.com';
}
public function getAccountID() {
return $this->getOAuthAccountData('ID');
}
public function getAccountEmail() {
return $this->getOAuthAccountData('email');
}
public function getAccountName() {
return $this->getOAuthAccountData('username');
}
public function getAccountImageURI() {
return $this->getOAuthAccountData('avatar_URL');
}
public function getAccountURI() {
return $this->getOAuthAccountData('profile_URL');
}
public function getAccountRealName() {
return $this->getOAuthAccountData('display_name');
}
protected function getAuthenticateBaseURI() {
return 'https://public-api.wordpress.com/oauth2/authorize';
}
protected function getTokenBaseURI() {
return 'https://public-api.wordpress.com/oauth2/token';
}
public function getScope() {
return 'user_read';
}
public function getExtraAuthenticateParameters() {
return array(
'response_type' => 'code',
'blog_id' => 0,
);
}
public function getExtraTokenParameters() {
return array(
'grant_type' => 'authorization_code',
);
}
protected function loadOAuthAccountData() {
return id(new PhutilWordPressFuture())
->setClientID($this->getClientID())
->setAccessToken($this->getAccessToken())
->setRawWordPressQuery('/me/')
->resolve();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilGoogleAuthAdapter.php | src/applications/auth/adapter/PhutilGoogleAuthAdapter.php | <?php
/**
* Authentication adapter for Google OAuth2.
*/
final class PhutilGoogleAuthAdapter extends PhutilOAuthAuthAdapter {
public function getAdapterType() {
return 'google';
}
public function getAdapterDomain() {
return 'google.com';
}
protected function newAccountIdentifiers() {
$identifiers = array();
$account_id = $this->getOAuthAccountData('id');
if ($account_id !== null) {
$account_id = sprintf(
'id(%s)',
$account_id);
$identifiers[] = $this->newAccountIdentifier($account_id);
}
$email = $this->getAccountEmail();
if ($email !== null) {
$identifiers[] = $this->newAccountIdentifier($email);
}
return $identifiers;
}
public function getAccountEmail() {
return $this->getOAuthAccountData('email');
}
public function getAccountName() {
// Guess account name from email address, this is just a hint anyway.
$email = $this->getAccountEmail();
$email = explode('@', $email);
$email = head($email);
return $email;
}
public function getAccountImageURI() {
$uri = $this->getOAuthAccountData('picture');
// Change the "sz" parameter ("size") from the default to 100 to ask for
// a 100x100px image.
if ($uri !== null) {
$uri = new PhutilURI($uri);
$uri->replaceQueryParam('sz', 100);
$uri = (string)$uri;
}
return $uri;
}
public function getAccountURI() {
return $this->getOAuthAccountData('link');
}
public function getAccountRealName() {
return $this->getOAuthAccountData('name');
}
protected function getAuthenticateBaseURI() {
return 'https://accounts.google.com/o/oauth2/auth';
}
protected function getTokenBaseURI() {
return 'https://accounts.google.com/o/oauth2/token';
}
public function getScope() {
$scopes = array(
'email',
'profile',
);
return implode(' ', $scopes);
}
public function getExtraAuthenticateParameters() {
return array(
'response_type' => 'code',
);
}
public function getExtraTokenParameters() {
return array(
'grant_type' => 'authorization_code',
);
}
protected function loadOAuthAccountData() {
$uri = new PhutilURI('https://www.googleapis.com/userinfo/v2/me');
$uri->replaceQueryParam('access_token', $this->getAccessToken());
$future = new HTTPSFuture($uri);
list($status, $body) = $future->resolve();
if ($status->isError()) {
throw $status;
}
try {
$result = phutil_json_decode($body);
} catch (PhutilJSONParserException $ex) {
throw new PhutilProxyException(
pht('Expected valid JSON response from Google account data request.'),
$ex);
}
return $result;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilSlackAuthAdapter.php | src/applications/auth/adapter/PhutilSlackAuthAdapter.php | <?php
/**
* Authentication adapter for Slack OAuth2.
*/
final class PhutilSlackAuthAdapter extends PhutilOAuthAuthAdapter {
public function getAdapterType() {
return 'Slack';
}
public function getAdapterDomain() {
return 'slack.com';
}
public function getAccountID() {
$user = $this->getOAuthAccountData('user');
return idx($user, 'id');
}
public function getAccountEmail() {
$user = $this->getOAuthAccountData('user');
return idx($user, 'email');
}
public function getAccountImageURI() {
$user = $this->getOAuthAccountData('user');
return idx($user, 'image_512');
}
public function getAccountRealName() {
$user = $this->getOAuthAccountData('user');
return idx($user, 'name');
}
protected function getAuthenticateBaseURI() {
return 'https://slack.com/oauth/authorize';
}
protected function getTokenBaseURI() {
return 'https://slack.com/api/oauth.access';
}
public function getScope() {
return 'identity.basic,identity.team,identity.avatar';
}
public function getExtraAuthenticateParameters() {
return array(
'response_type' => 'code',
);
}
protected function loadOAuthAccountData() {
return id(new PhutilSlackFuture())
->setAccessToken($this->getAccessToken())
->setRawSlackQuery('users.identity')
->resolve();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilTwitterAuthAdapter.php | src/applications/auth/adapter/PhutilTwitterAuthAdapter.php | <?php
/**
* Authentication adapter for Twitter OAuth1.
*/
final class PhutilTwitterAuthAdapter extends PhutilOAuth1AuthAdapter {
private $userInfo;
public function getAccountID() {
return idx($this->getHandshakeData(), 'user_id');
}
public function getAccountName() {
return idx($this->getHandshakeData(), 'screen_name');
}
public function getAccountURI() {
$name = $this->getAccountName();
if (strlen($name)) {
return 'https://twitter.com/'.$name;
}
return null;
}
public function getAccountImageURI() {
$info = $this->getUserInfo();
return idx($info, 'profile_image_url');
}
public function getAccountRealName() {
$info = $this->getUserInfo();
return idx($info, 'name');
}
public function getAdapterType() {
return 'twitter';
}
public function getAdapterDomain() {
return 'twitter.com';
}
protected function getRequestTokenURI() {
return 'https://api.twitter.com/oauth/request_token';
}
protected function getAuthorizeTokenURI() {
return 'https://api.twitter.com/oauth/authorize';
}
protected function getValidateTokenURI() {
return 'https://api.twitter.com/oauth/access_token';
}
private function getUserInfo() {
if ($this->userInfo === null) {
$params = array(
'user_id' => $this->getAccountID(),
);
$uri = new PhutilURI(
'https://api.twitter.com/1.1/users/show.json',
$params);
$data = $this->newOAuth1Future($uri)
->setMethod('GET')
->resolveJSON();
$this->userInfo = $data;
}
return $this->userInfo;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilLDAPAuthAdapter.php | src/applications/auth/adapter/PhutilLDAPAuthAdapter.php | <?php
/**
* Retrieve identify information from LDAP accounts.
*/
final class PhutilLDAPAuthAdapter extends PhutilAuthAdapter {
private $hostname;
private $port = 389;
private $baseDistinguishedName;
private $searchAttributes = array();
private $usernameAttribute;
private $realNameAttributes = array();
private $ldapVersion = 3;
private $ldapReferrals;
private $ldapStartTLS;
private $anonymousUsername;
private $anonymousPassword;
private $activeDirectoryDomain;
private $alwaysSearch;
private $loginUsername;
private $loginPassword;
private $ldapUserData;
private $ldapConnection;
public function getAdapterType() {
return 'ldap';
}
public function setHostname($host) {
$this->hostname = $host;
return $this;
}
public function setPort($port) {
$this->port = $port;
return $this;
}
public function getAdapterDomain() {
return 'self';
}
public function setBaseDistinguishedName($base_distinguished_name) {
$this->baseDistinguishedName = $base_distinguished_name;
return $this;
}
public function setSearchAttributes(array $search_attributes) {
$this->searchAttributes = $search_attributes;
return $this;
}
public function setUsernameAttribute($username_attribute) {
$this->usernameAttribute = $username_attribute;
return $this;
}
public function setRealNameAttributes(array $attributes) {
$this->realNameAttributes = $attributes;
return $this;
}
public function setLDAPVersion($ldap_version) {
$this->ldapVersion = $ldap_version;
return $this;
}
public function setLDAPReferrals($ldap_referrals) {
$this->ldapReferrals = $ldap_referrals;
return $this;
}
public function setLDAPStartTLS($ldap_start_tls) {
$this->ldapStartTLS = $ldap_start_tls;
return $this;
}
public function setAnonymousUsername($anonymous_username) {
$this->anonymousUsername = $anonymous_username;
return $this;
}
public function setAnonymousPassword(
PhutilOpaqueEnvelope $anonymous_password) {
$this->anonymousPassword = $anonymous_password;
return $this;
}
public function setLoginUsername($login_username) {
$this->loginUsername = $login_username;
return $this;
}
public function setLoginPassword(PhutilOpaqueEnvelope $login_password) {
$this->loginPassword = $login_password;
return $this;
}
public function setActiveDirectoryDomain($domain) {
$this->activeDirectoryDomain = $domain;
return $this;
}
public function setAlwaysSearch($always_search) {
$this->alwaysSearch = $always_search;
return $this;
}
public function getAccountID() {
return $this->readLDAPRecordAccountID($this->getLDAPUserData());
}
public function getAccountName() {
return $this->readLDAPRecordAccountName($this->getLDAPUserData());
}
public function getAccountRealName() {
return $this->readLDAPRecordRealName($this->getLDAPUserData());
}
public function getAccountEmail() {
return $this->readLDAPRecordEmail($this->getLDAPUserData());
}
public function readLDAPRecordAccountID(array $record) {
$key = $this->usernameAttribute;
if (!strlen($key)) {
$key = head($this->searchAttributes);
}
return $this->readLDAPData($record, $key);
}
public function readLDAPRecordAccountName(array $record) {
return $this->readLDAPRecordAccountID($record);
}
public function readLDAPRecordRealName(array $record) {
$parts = array();
foreach ($this->realNameAttributes as $attribute) {
$parts[] = $this->readLDAPData($record, $attribute);
}
$parts = array_filter($parts);
if ($parts) {
return implode(' ', $parts);
}
return null;
}
public function readLDAPRecordEmail(array $record) {
return $this->readLDAPData($record, 'mail');
}
private function getLDAPUserData() {
if ($this->ldapUserData === null) {
$this->ldapUserData = $this->loadLDAPUserData();
}
return $this->ldapUserData;
}
private function readLDAPData(array $data, $key, $default = null) {
$list = idx($data, $key);
if ($list === null) {
// At least in some cases (and maybe in all cases) the results from
// ldap_search() are keyed in lowercase. If we missed on the first
// try, retry with a lowercase key.
$list = idx($data, phutil_utf8_strtolower($key));
}
// NOTE: In most cases, the property is an array, like:
//
// array(
// 'count' => 1,
// 0 => 'actual-value-we-want',
// )
//
// However, in at least the case of 'dn', the property is a bare string.
if (is_scalar($list) && strlen($list)) {
return $list;
} else if (is_array($list)) {
return $list[0];
} else {
return $default;
}
}
private function formatLDAPAttributeSearch($attribute, $login_user) {
// If the attribute contains the literal token "${login}", treat it as a
// query and substitute the user's login name for the token.
if (strpos($attribute, '${login}') !== false) {
$escaped_user = ldap_sprintf('%S', $login_user);
$attribute = str_replace('${login}', $escaped_user, $attribute);
return $attribute;
}
// Otherwise, treat it as a simple attribute search.
return ldap_sprintf(
'%Q=%S',
$attribute,
$login_user);
}
private function loadLDAPUserData() {
$conn = $this->establishConnection();
$login_user = $this->loginUsername;
$login_pass = $this->loginPassword;
if ($this->shouldBindWithoutIdentity()) {
$distinguished_name = null;
$search_query = null;
foreach ($this->searchAttributes as $attribute) {
$search_query = $this->formatLDAPAttributeSearch(
$attribute,
$login_user);
$record = $this->searchLDAPForRecord($search_query);
if ($record) {
$distinguished_name = $this->readLDAPData($record, 'dn');
break;
}
}
if ($distinguished_name === null) {
throw new PhutilAuthCredentialException();
}
} else {
$search_query = $this->formatLDAPAttributeSearch(
head($this->searchAttributes),
$login_user);
if ($this->activeDirectoryDomain) {
$distinguished_name = ldap_sprintf(
'%s@%Q',
$login_user,
$this->activeDirectoryDomain);
} else {
$distinguished_name = ldap_sprintf(
'%Q,%Q',
$search_query,
$this->baseDistinguishedName);
}
}
$this->bindLDAP($conn, $distinguished_name, $login_pass);
$result = $this->searchLDAPForRecord($search_query);
if (!$result) {
// This is unusual (since the bind succeeded) but we've seen it at least
// once in the wild, where the anonymous user is allowed to search but
// the credentialed user is not.
// If we don't have anonymous credentials, raise an explicit exception
// here since we'll fail a typehint if we don't return an array anyway
// and this is a more useful error.
// If we do have anonymous credentials, we'll rebind and try the search
// again below. Doing this automatically means things work correctly more
// often without requiring additional configuration.
if (!$this->shouldBindWithoutIdentity()) {
// No anonymous credentials, so we just fail here.
throw new Exception(
pht(
'LDAP: Failed to retrieve record for user "%s" when searching. '.
'Credentialed users may not be able to search your LDAP server. '.
'Try configuring anonymous credentials or fully anonymous binds.',
$login_user));
} else {
// Rebind as anonymous and try the search again.
$user = $this->anonymousUsername;
$pass = $this->anonymousPassword;
$this->bindLDAP($conn, $user, $pass);
$result = $this->searchLDAPForRecord($search_query);
if (!$result) {
throw new Exception(
pht(
'LDAP: Failed to retrieve record for user "%s" when searching '.
'with both user and anonymous credentials.',
$login_user));
}
}
}
return $result;
}
private function establishConnection() {
if (!$this->ldapConnection) {
$host = $this->hostname;
$port = $this->port;
$profiler = PhutilServiceProfiler::getInstance();
$call_id = $profiler->beginServiceCall(
array(
'type' => 'ldap',
'call' => 'connect',
'host' => $host,
'port' => $this->port,
));
$conn = @ldap_connect($host, $this->port);
$profiler->endServiceCall(
$call_id,
array(
'ok' => (bool)$conn,
));
if (!$conn) {
throw new Exception(
pht('Unable to connect to LDAP server (%s:%d).', $host, $port));
}
$options = array(
LDAP_OPT_PROTOCOL_VERSION => (int)$this->ldapVersion,
LDAP_OPT_REFERRALS => (int)$this->ldapReferrals,
);
foreach ($options as $name => $value) {
$ok = @ldap_set_option($conn, $name, $value);
if (!$ok) {
$this->raiseConnectionException(
$conn,
pht(
"Unable to set LDAP option '%s' to value '%s'!",
$name,
$value));
}
}
if ($this->ldapStartTLS) {
$profiler = PhutilServiceProfiler::getInstance();
$call_id = $profiler->beginServiceCall(
array(
'type' => 'ldap',
'call' => 'start-tls',
));
// NOTE: This boils down to a function call to ldap_start_tls_s() in
// C, which is a service call.
$ok = @ldap_start_tls($conn);
$profiler->endServiceCall(
$call_id,
array());
if (!$ok) {
$this->raiseConnectionException(
$conn,
pht('Unable to start TLS connection when connecting to LDAP.'));
}
}
if ($this->shouldBindWithoutIdentity()) {
$user = $this->anonymousUsername;
$pass = $this->anonymousPassword;
$this->bindLDAP($conn, $user, $pass);
}
$this->ldapConnection = $conn;
}
return $this->ldapConnection;
}
private function searchLDAPForRecord($dn) {
$conn = $this->establishConnection();
$results = $this->searchLDAP('%Q', $dn);
if (!$results) {
return null;
}
if (count($results) > 1) {
throw new Exception(
pht(
'LDAP record query returned more than one result. The query must '.
'uniquely identify a record.'));
}
return head($results);
}
public function searchLDAP($pattern /* ... */) {
$args = func_get_args();
$query = call_user_func_array('ldap_sprintf', $args);
$conn = $this->establishConnection();
$profiler = PhutilServiceProfiler::getInstance();
$call_id = $profiler->beginServiceCall(
array(
'type' => 'ldap',
'call' => 'search',
'dn' => $this->baseDistinguishedName,
'query' => $query,
));
$result = @ldap_search($conn, $this->baseDistinguishedName, $query);
$profiler->endServiceCall($call_id, array());
if (!$result) {
$this->raiseConnectionException(
$conn,
pht('LDAP search failed.'));
}
$entries = @ldap_get_entries($conn, $result);
if (!$entries) {
$this->raiseConnectionException(
$conn,
pht('Failed to get LDAP entries from search result.'));
}
$results = array();
for ($ii = 0; $ii < $entries['count']; $ii++) {
$results[] = $entries[$ii];
}
return $results;
}
private function raiseConnectionException($conn, $message) {
$errno = @ldap_errno($conn);
$error = @ldap_error($conn);
// This is `LDAP_INVALID_CREDENTIALS`.
if ($errno == 49) {
throw new PhutilAuthCredentialException();
}
if ($errno || $error) {
$full_message = pht(
"LDAP Exception: %s\nLDAP Error #%d: %s",
$message,
$errno,
$error);
} else {
$full_message = pht(
'LDAP Exception: %s',
$message);
}
throw new Exception($full_message);
}
private function bindLDAP($conn, $user, PhutilOpaqueEnvelope $pass) {
$profiler = PhutilServiceProfiler::getInstance();
$call_id = $profiler->beginServiceCall(
array(
'type' => 'ldap',
'call' => 'bind',
'user' => $user,
));
// NOTE: ldap_bind() dumps cleartext passwords into logs by default. Keep
// it quiet.
if (strlen($user)) {
$ok = @ldap_bind($conn, $user, $pass->openEnvelope());
} else {
$ok = @ldap_bind($conn);
}
$profiler->endServiceCall($call_id, array());
if (!$ok) {
if (strlen($user)) {
$this->raiseConnectionException(
$conn,
pht('Failed to bind to LDAP server (as user "%s").', $user));
} else {
$this->raiseConnectionException(
$conn,
pht('Failed to bind to LDAP server (without username).'));
}
}
}
/**
* Determine if this adapter should attempt to bind to the LDAP server
* without a user identity.
*
* Generally, we can bind directly if we have a username/password, or if the
* "Always Search" flag is set, indicating that the empty username and
* password are sufficient.
*
* @return bool True if the adapter should perform binds without identity.
*/
private function shouldBindWithoutIdentity() {
return $this->alwaysSearch || strlen($this->anonymousUsername);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilFacebookAuthAdapter.php | src/applications/auth/adapter/PhutilFacebookAuthAdapter.php | <?php
/**
* Authentication adapter for Facebook OAuth2.
*/
final class PhutilFacebookAuthAdapter extends PhutilOAuthAuthAdapter {
public function getAdapterType() {
return 'facebook';
}
public function getAdapterDomain() {
return 'facebook.com';
}
public function getAccountID() {
return $this->getOAuthAccountData('id');
}
public function getAccountEmail() {
return $this->getOAuthAccountData('email');
}
public function getAccountName() {
$link = $this->getOAuthAccountData('link');
if (!$link) {
return null;
}
$matches = null;
if (!preg_match('@/([^/]+)$@', $link, $matches)) {
return null;
}
return $matches[1];
}
public function getAccountImageURI() {
$picture = $this->getOAuthAccountData('picture');
if ($picture) {
$picture_data = idx($picture, 'data');
if ($picture_data) {
return idx($picture_data, 'url');
}
}
return null;
}
public function getAccountURI() {
return $this->getOAuthAccountData('link');
}
public function getAccountRealName() {
return $this->getOAuthAccountData('name');
}
protected function getAuthenticateBaseURI() {
return 'https://www.facebook.com/dialog/oauth';
}
protected function getTokenBaseURI() {
return 'https://graph.facebook.com/oauth/access_token';
}
protected function loadOAuthAccountData() {
$fields = array(
'id',
'name',
'email',
'link',
'picture',
);
$uri = new PhutilURI('https://graph.facebook.com/me');
$uri->replaceQueryParam('access_token', $this->getAccessToken());
$uri->replaceQueryParam('fields', implode(',', $fields));
list($body) = id(new HTTPSFuture($uri))->resolvex();
$data = null;
try {
$data = phutil_json_decode($body);
} catch (PhutilJSONParserException $ex) {
throw new PhutilProxyException(
pht('Expected valid JSON response from Facebook account data request.'),
$ex);
}
return $data;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilOAuth1AuthAdapter.php | src/applications/auth/adapter/PhutilOAuth1AuthAdapter.php | <?php
/**
* Abstract adapter for OAuth1 providers.
*/
abstract class PhutilOAuth1AuthAdapter extends PhutilAuthAdapter {
private $consumerKey;
private $consumerSecret;
private $token;
private $tokenSecret;
private $verifier;
private $handshakeData;
private $callbackURI;
private $privateKey;
public function setPrivateKey(PhutilOpaqueEnvelope $private_key) {
$this->privateKey = $private_key;
return $this;
}
public function getPrivateKey() {
return $this->privateKey;
}
public function setCallbackURI($callback_uri) {
$this->callbackURI = $callback_uri;
return $this;
}
public function getCallbackURI() {
return $this->callbackURI;
}
public function setVerifier($verifier) {
$this->verifier = $verifier;
return $this;
}
public function getVerifier() {
return $this->verifier;
}
public function setConsumerSecret(PhutilOpaqueEnvelope $consumer_secret) {
$this->consumerSecret = $consumer_secret;
return $this;
}
public function getConsumerSecret() {
return $this->consumerSecret;
}
public function setConsumerKey($consumer_key) {
$this->consumerKey = $consumer_key;
return $this;
}
public function getConsumerKey() {
return $this->consumerKey;
}
public function setTokenSecret($token_secret) {
$this->tokenSecret = $token_secret;
return $this;
}
public function getTokenSecret() {
return $this->tokenSecret;
}
public function setToken($token) {
$this->token = $token;
return $this;
}
public function getToken() {
return $this->token;
}
protected function getHandshakeData() {
if ($this->handshakeData === null) {
$this->finishOAuthHandshake();
}
return $this->handshakeData;
}
abstract protected function getRequestTokenURI();
abstract protected function getAuthorizeTokenURI();
abstract protected function getValidateTokenURI();
protected function getSignatureMethod() {
return 'HMAC-SHA1';
}
public function getContentSecurityPolicyFormActions() {
return array(
$this->getAuthorizeTokenURI(),
);
}
protected function newOAuth1Future($uri, $data = array()) {
$future = id(new PhutilOAuth1Future($uri, $data))
->setMethod('POST')
->setSignatureMethod($this->getSignatureMethod());
$consumer_key = $this->getConsumerKey();
if (strlen($consumer_key)) {
$future->setConsumerKey($consumer_key);
} else {
throw new Exception(
pht(
'%s is required!',
'setConsumerKey()'));
}
$consumer_secret = $this->getConsumerSecret();
if ($consumer_secret) {
$future->setConsumerSecret($consumer_secret);
}
if (strlen($this->getToken())) {
$future->setToken($this->getToken());
}
if (strlen($this->getTokenSecret())) {
$future->setTokenSecret($this->getTokenSecret());
}
if ($this->getPrivateKey()) {
$future->setPrivateKey($this->getPrivateKey());
}
return $future;
}
public function getClientRedirectURI() {
$request_token_uri = $this->getRequestTokenURI();
$future = $this->newOAuth1Future($request_token_uri);
if (strlen($this->getCallbackURI())) {
$future->setCallbackURI($this->getCallbackURI());
}
list($body) = $future->resolvex();
$data = id(new PhutilQueryStringParser())->parseQueryString($body);
// NOTE: Per the spec, this value MUST be the string 'true'.
$confirmed = idx($data, 'oauth_callback_confirmed');
if ($confirmed !== 'true') {
throw new Exception(
pht("Expected '%s' to be '%s'!", 'oauth_callback_confirmed', 'true'));
}
$this->readTokenAndTokenSecret($data);
$authorize_token_uri = new PhutilURI($this->getAuthorizeTokenURI());
$authorize_token_uri->replaceQueryParam('oauth_token', $this->getToken());
return phutil_string_cast($authorize_token_uri);
}
protected function finishOAuthHandshake() {
$this->willFinishOAuthHandshake();
if (!$this->getToken()) {
throw new Exception(pht('Expected token to finish OAuth handshake!'));
}
if (!$this->getVerifier()) {
throw new Exception(pht('Expected verifier to finish OAuth handshake!'));
}
$validate_uri = $this->getValidateTokenURI();
$params = array(
'oauth_verifier' => $this->getVerifier(),
);
list($body) = $this->newOAuth1Future($validate_uri, $params)->resolvex();
$data = id(new PhutilQueryStringParser())->parseQueryString($body);
$this->readTokenAndTokenSecret($data);
$this->handshakeData = $data;
}
private function readTokenAndTokenSecret(array $data) {
$token = idx($data, 'oauth_token');
if (!$token) {
throw new Exception(pht("Expected '%s' in response!", 'oauth_token'));
}
$token_secret = idx($data, 'oauth_token_secret');
if (!$token_secret) {
throw new Exception(
pht("Expected '%s' in response!", 'oauth_token_secret'));
}
$this->setToken($token);
$this->setTokenSecret($token_secret);
return $this;
}
/**
* Hook that allows subclasses to take actions before the OAuth handshake
* is completed.
*/
protected function willFinishOAuthHandshake() {
return;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilAmazonAuthAdapter.php | src/applications/auth/adapter/PhutilAmazonAuthAdapter.php | <?php
/**
* Authentication adapter for Amazon OAuth2.
*/
final class PhutilAmazonAuthAdapter extends PhutilOAuthAuthAdapter {
public function getAdapterType() {
return 'amazon';
}
public function getAdapterDomain() {
return 'amazon.com';
}
public function getAccountID() {
return $this->getOAuthAccountData('user_id');
}
public function getAccountEmail() {
return $this->getOAuthAccountData('email');
}
public function getAccountName() {
return null;
}
public function getAccountImageURI() {
return null;
}
public function getAccountURI() {
return null;
}
public function getAccountRealName() {
return $this->getOAuthAccountData('name');
}
protected function getAuthenticateBaseURI() {
return 'https://www.amazon.com/ap/oa';
}
protected function getTokenBaseURI() {
return 'https://api.amazon.com/auth/o2/token';
}
public function getScope() {
return 'profile';
}
public function getExtraAuthenticateParameters() {
return array(
'response_type' => 'code',
);
}
public function getExtraTokenParameters() {
return array(
'grant_type' => 'authorization_code',
);
}
protected function loadOAuthAccountData() {
$uri = new PhutilURI('https://api.amazon.com/user/profile');
$uri->replaceQueryParam('access_token', $this->getAccessToken());
$future = new HTTPSFuture($uri);
list($body) = $future->resolvex();
try {
return phutil_json_decode($body);
} catch (PhutilJSONParserException $ex) {
throw new PhutilProxyException(
pht('Expected valid JSON response from Amazon account data request.'),
$ex);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilJIRAAuthAdapter.php | src/applications/auth/adapter/PhutilJIRAAuthAdapter.php | <?php
/**
* Authentication adapter for JIRA OAuth1.
*/
final class PhutilJIRAAuthAdapter extends PhutilOAuth1AuthAdapter {
// TODO: JIRA tokens expire (after 5 years) and we could surface and store
// that.
private $jiraBaseURI;
private $adapterDomain;
private $userInfo;
public function setJIRABaseURI($jira_base_uri) {
$this->jiraBaseURI = $jira_base_uri;
return $this;
}
public function getJIRABaseURI() {
return $this->jiraBaseURI;
}
protected function newAccountIdentifiers() {
// Make sure the handshake is finished; this method is used for its
// side effect by Auth providers.
$this->getHandshakeData();
$info = $this->getUserInfo();
// See T13493. Older versions of JIRA provide a "key" with a username or
// email address. Newer versions of JIRA provide a GUID "accountId".
// Intermediate versions of JIRA provide both.
$identifiers = array();
$account_key = idx($info, 'key');
if ($account_key !== null) {
$identifiers[] = $this->newAccountIdentifier($account_key);
}
$account_id = idx($info, 'accountId');
if ($account_id !== null) {
$identifiers[] = $this->newAccountIdentifier(
sprintf(
'accountId(%s)',
$account_id));
}
return $identifiers;
}
public function getAccountName() {
return idx($this->getUserInfo(), 'name');
}
public function getAccountImageURI() {
$avatars = idx($this->getUserInfo(), 'avatarUrls');
if ($avatars) {
return idx($avatars, '48x48');
}
return null;
}
public function getAccountRealName() {
return idx($this->getUserInfo(), 'displayName');
}
public function getAccountEmail() {
return idx($this->getUserInfo(), 'emailAddress');
}
public function getAdapterType() {
return 'jira';
}
public function getAdapterDomain() {
return $this->adapterDomain;
}
public function setAdapterDomain($domain) {
$this->adapterDomain = $domain;
return $this;
}
protected function getSignatureMethod() {
return 'RSA-SHA1';
}
protected function getRequestTokenURI() {
return $this->getJIRAURI('plugins/servlet/oauth/request-token');
}
protected function getAuthorizeTokenURI() {
return $this->getJIRAURI('plugins/servlet/oauth/authorize');
}
protected function getValidateTokenURI() {
return $this->getJIRAURI('plugins/servlet/oauth/access-token');
}
private function getJIRAURI($path) {
return rtrim($this->jiraBaseURI, '/').'/'.ltrim($path, '/');
}
private function getUserInfo() {
if ($this->userInfo === null) {
$this->userInfo = $this->newUserInfo();
}
return $this->userInfo;
}
private function newUserInfo() {
// See T13493. Try a relatively modern (circa early 2020) API call first.
try {
return $this->newJIRAFuture('rest/api/3/myself', 'GET')
->resolveJSON();
} catch (Exception $ex) {
// If we failed the v3 call, assume the server version is too old
// to support this API and fall back to trying the older method.
}
$session = $this->newJIRAFuture('rest/auth/1/session', 'GET')
->resolveJSON();
// The session call gives us the username, but not the user key or other
// information. Make a second call to get additional information.
$params = array(
'username' => $session['name'],
);
return $this->newJIRAFuture('rest/api/2/user', 'GET', $params)
->resolveJSON();
}
public static function newJIRAKeypair() {
$config = array(
'digest_alg' => 'sha512',
'private_key_bits' => 4096,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
);
$res = openssl_pkey_new($config);
if (!$res) {
throw new Exception(pht('%s failed!', 'openssl_pkey_new()'));
}
$private_key = null;
$ok = openssl_pkey_export($res, $private_key);
if (!$ok) {
throw new Exception(pht('%s failed!', 'openssl_pkey_export()'));
}
$public_key = openssl_pkey_get_details($res);
if (!$ok || empty($public_key['key'])) {
throw new Exception(pht('%s failed!', 'openssl_pkey_get_details()'));
}
$public_key = $public_key['key'];
return array($public_key, $private_key);
}
/**
* JIRA indicates that the user has clicked the "Deny" button by passing a
* well known `oauth_verifier` value ("denied"), which we check for here.
*/
protected function willFinishOAuthHandshake() {
$jira_magic_word = 'denied';
if ($this->getVerifier() == $jira_magic_word) {
throw new PhutilAuthUserAbortedException();
}
}
public function newJIRAFuture($path, $method, $params = array()) {
if ($method == 'GET') {
$uri_params = $params;
$body_params = array();
} else {
// For other types of requests, JIRA expects the request body to be
// JSON encoded.
$uri_params = array();
$body_params = phutil_json_encode($params);
}
$uri = new PhutilURI($this->getJIRAURI($path), $uri_params);
// JIRA returns a 415 error if we don't provide a Content-Type header.
return $this->newOAuth1Future($uri, $body_params)
->setMethod($method)
->addHeader('Content-Type', 'application/json');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilGitHubAuthAdapter.php | src/applications/auth/adapter/PhutilGitHubAuthAdapter.php | <?php
/**
* Authentication adapter for Github OAuth2.
*/
final class PhutilGitHubAuthAdapter extends PhutilOAuthAuthAdapter {
public function getAdapterType() {
return 'github';
}
public function getAdapterDomain() {
return 'github.com';
}
public function getAccountID() {
return $this->getOAuthAccountData('id');
}
public function getAccountEmail() {
return $this->getOAuthAccountData('email');
}
public function getAccountName() {
return $this->getOAuthAccountData('login');
}
public function getAccountImageURI() {
return $this->getOAuthAccountData('avatar_url');
}
public function getAccountURI() {
$name = $this->getAccountName();
if (strlen($name)) {
return 'https://github.com/'.$name;
}
return null;
}
public function getAccountRealName() {
return $this->getOAuthAccountData('name');
}
protected function getAuthenticateBaseURI() {
return 'https://github.com/login/oauth/authorize';
}
protected function getTokenBaseURI() {
return 'https://github.com/login/oauth/access_token';
}
protected function loadOAuthAccountData() {
$uri = new PhutilURI('https://api.github.com/user');
$future = new HTTPSFuture($uri);
// NOTE: GitHub requires a User-Agent string.
$future->addHeader('User-Agent', __CLASS__);
// See T13485. Circa early 2020, GitHub has deprecated use of the
// "access_token" URI parameter.
$token_header = sprintf('token %s', $this->getAccessToken());
$future->addHeader('Authorization', $token_header);
list($body) = $future->resolvex();
try {
return phutil_json_decode($body);
} catch (PhutilJSONParserException $ex) {
throw new PhutilProxyException(
pht('Expected valid JSON response from GitHub account data request.'),
$ex);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/adapter/PhutilBitbucketAuthAdapter.php | src/applications/auth/adapter/PhutilBitbucketAuthAdapter.php | <?php
final class PhutilBitbucketAuthAdapter extends PhutilOAuth1AuthAdapter {
private $userInfo;
public function getAccountID() {
return idx($this->getUserInfo(), 'username');
}
public function getAccountName() {
return idx($this->getUserInfo(), 'display_name');
}
public function getAccountURI() {
$name = $this->getAccountID();
if (strlen($name)) {
return 'https://bitbucket.org/'.$name;
}
return null;
}
public function getAccountImageURI() {
return idx($this->getUserInfo(), 'avatar');
}
public function getAccountRealName() {
$parts = array(
idx($this->getUserInfo(), 'first_name'),
idx($this->getUserInfo(), 'last_name'),
);
$parts = array_filter($parts);
return implode(' ', $parts);
}
public function getAdapterType() {
return 'bitbucket';
}
public function getAdapterDomain() {
return 'bitbucket.org';
}
protected function getRequestTokenURI() {
return 'https://bitbucket.org/api/1.0/oauth/request_token';
}
protected function getAuthorizeTokenURI() {
return 'https://bitbucket.org/api/1.0/oauth/authenticate';
}
protected function getValidateTokenURI() {
return 'https://bitbucket.org/api/1.0/oauth/access_token';
}
private function getUserInfo() {
if ($this->userInfo === null) {
// We don't need any of the data in the handshake, but do need to
// finish the process. This makes sure we've completed the handshake.
$this->getHandshakeData();
$uri = new PhutilURI('https://bitbucket.org/api/1.0/user');
$data = $this->newOAuth1Future($uri)
->setMethod('GET')
->resolveJSON();
$this->userInfo = idx($data, 'user', array());
}
return $this->userInfo;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/future/PhabricatorDuoFuture.php | src/applications/auth/future/PhabricatorDuoFuture.php | <?php
final class PhabricatorDuoFuture
extends FutureProxy {
private $future;
private $integrationKey;
private $secretKey;
private $apiHostname;
private $httpMethod = 'POST';
private $method;
private $parameters;
private $timeout;
public function __construct() {
parent::__construct(null);
}
public function setIntegrationKey($integration_key) {
$this->integrationKey = $integration_key;
return $this;
}
public function setSecretKey(PhutilOpaqueEnvelope $key) {
$this->secretKey = $key;
return $this;
}
public function setAPIHostname($hostname) {
$this->apiHostname = $hostname;
return $this;
}
public function setMethod($method, array $parameters) {
$this->method = $method;
$this->parameters = $parameters;
return $this;
}
public function setTimeout($timeout) {
$this->timeout = $timeout;
return $this;
}
public function getTimeout() {
return $this->timeout;
}
public function setHTTPMethod($method) {
$this->httpMethod = $method;
return $this;
}
public function getHTTPMethod() {
return $this->httpMethod;
}
protected function getProxiedFuture() {
if (!$this->future) {
if ($this->integrationKey === null) {
throw new PhutilInvalidStateException('setIntegrationKey');
}
if ($this->secretKey === null) {
throw new PhutilInvalidStateException('setSecretKey');
}
if ($this->apiHostname === null) {
throw new PhutilInvalidStateException('setAPIHostname');
}
if ($this->method === null || $this->parameters === null) {
throw new PhutilInvalidStateException('setMethod');
}
$path = (string)urisprintf('/auth/v2/%s', $this->method);
$host = $this->apiHostname;
$host = phutil_utf8_strtolower($host);
$data = $this->parameters;
$date = date('r');
$http_method = $this->getHTTPMethod();
ksort($data);
$data_parts = phutil_build_http_querystring($data);
$corpus = array(
$date,
$http_method,
$host,
$path,
$data_parts,
);
$corpus = implode("\n", $corpus);
$signature = hash_hmac(
'sha1',
$corpus,
$this->secretKey->openEnvelope());
$signature = new PhutilOpaqueEnvelope($signature);
if ($http_method === 'GET') {
$uri_data = $data;
$body_data = array();
} else {
$uri_data = array();
$body_data = $data;
}
$uri = id(new PhutilURI('', $uri_data))
->setProtocol('https')
->setDomain($host)
->setPath($path);
$future = id(new HTTPSFuture($uri, $body_data))
->setHTTPBasicAuthCredentials($this->integrationKey, $signature)
->setMethod($http_method)
->addHeader('Accept', 'application/json')
->addHeader('Date', $date);
$timeout = $this->getTimeout();
if ($timeout) {
$future->setTimeout($timeout);
}
$this->future = $future;
}
return $this->future;
}
protected function didReceiveResult($result) {
list($status, $body, $headers) = $result;
if ($status->isError()) {
throw $status;
}
try {
$data = phutil_json_decode($body);
} catch (PhutilJSONParserException $ex) {
throw new PhutilProxyException(
pht('Expected JSON response from Duo.'),
$ex);
}
return $data;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/tokentype/PhabricatorAuthOneTimeLoginTemporaryTokenType.php | src/applications/auth/tokentype/PhabricatorAuthOneTimeLoginTemporaryTokenType.php | <?php
final class PhabricatorAuthOneTimeLoginTemporaryTokenType
extends PhabricatorAuthTemporaryTokenType {
const TOKENTYPE = 'login:onetime';
public function getTokenTypeDisplayName() {
return pht('One-Time Login');
}
public function getTokenReadableTypeName(
PhabricatorAuthTemporaryToken $token) {
return pht('One-Time Login Token');
}
public function isTokenRevocable(PhabricatorAuthTemporaryToken $token) {
return true;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/tokentype/PhabricatorAuthTemporaryTokenType.php | src/applications/auth/tokentype/PhabricatorAuthTemporaryTokenType.php | <?php
abstract class PhabricatorAuthTemporaryTokenType
extends Phobject {
abstract public function getTokenTypeDisplayName();
abstract public function getTokenReadableTypeName(
PhabricatorAuthTemporaryToken $token);
public function isTokenRevocable(PhabricatorAuthTemporaryToken $token) {
return false;
}
final public function getTokenTypeConstant() {
return $this->getPhobjectClassConstant('TOKENTYPE', 64);
}
final public static function getAllTypes() {
return id(new PhutilClassMapQuery())
->setAncestorClass(__CLASS__)
->setUniqueMethod('getTokenTypeConstant')
->execute();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/tokentype/PhabricatorAuthPasswordResetTemporaryTokenType.php | src/applications/auth/tokentype/PhabricatorAuthPasswordResetTemporaryTokenType.php | <?php
final class PhabricatorAuthPasswordResetTemporaryTokenType
extends PhabricatorAuthTemporaryTokenType {
const TOKENTYPE = 'login:password';
public function getTokenTypeDisplayName() {
return pht('Password Reset');
}
public function getTokenReadableTypeName(
PhabricatorAuthTemporaryToken $token) {
return pht('Password Reset Token');
}
public function isTokenRevocable(PhabricatorAuthTemporaryToken $token) {
return true;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/tokentype/PhabricatorAuthTemporaryTokenTypeModule.php | src/applications/auth/tokentype/PhabricatorAuthTemporaryTokenTypeModule.php | <?php
final class PhabricatorAuthTemporaryTokenTypeModule
extends PhabricatorConfigModule {
public function getModuleKey() {
return 'temporarytoken';
}
public function getModuleName() {
return pht('Temporary Token Types');
}
public function renderModuleStatus(AphrontRequest $request) {
$viewer = $request->getViewer();
$types = PhabricatorAuthTemporaryTokenType::getAllTypes();
$rows = array();
foreach ($types as $type) {
$rows[] = array(
get_class($type),
$type->getTokenTypeConstant(),
$type->getTokenTypeDisplayName(),
);
}
return id(new AphrontTableView($rows))
->setHeaders(
array(
pht('Class'),
pht('Key'),
pht('Name'),
))
->setColumnClasses(
array(
null,
null,
'wide pri',
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/constants/PhabricatorCommonPasswords.php | src/applications/auth/constants/PhabricatorCommonPasswords.php | <?php
/**
* Check if a password is extremely common. Preventing use of the most common
* passwords is an attempt to mitigate slow botnet attacks against an entire
* userbase. See T4143 for discussion.
*
* @task common Checking Common Passwords
*/
final class PhabricatorCommonPasswords extends Phobject {
/* -( Checking Common Passwords )------------------------------------------ */
/**
* Check if a password is extremely common.
*
* @param string Password to test.
* @return bool True if the password is pathologically weak.
*
* @task common
*/
public static function isCommonPassword($password) {
static $list;
if ($list === null) {
$list = self::loadWordlist();
}
return isset($list[strtolower($password)]);
}
/**
* Load the common password wordlist.
*
* @return map<string, bool> Map of common passwords.
*
* @task common
*/
private static function loadWordlist() {
$root = dirname(phutil_get_library_root('phabricator'));
$file = $root.'/externals/wordlist/password.lst';
$data = Filesystem::readFile($file);
$words = phutil_split_lines($data, $retain_endings = false);
$map = array();
foreach ($words as $key => $word) {
// The wordlist file has some comments at the top, strip those out.
if (preg_match('/^#!comment:/', $word)) {
continue;
}
$map[strtolower($word)] = true;
}
// Add in some application-specific passwords.
$map += array(
'phabricator' => true,
'phab' => true,
'devtools' => true,
'differential' => true,
'codereview' => true,
'review' => true,
);
return $map;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/constants/PhabricatorCookies.php | src/applications/auth/constants/PhabricatorCookies.php | <?php
/**
* Consolidates Phabricator application cookies, including registration
* and session management.
*
* @task clientid Client ID Cookie
* @task next Next URI Cookie
*/
final class PhabricatorCookies extends Phobject {
/**
* Stores the login username for password authentication. This is just a
* display value for convenience, used to prefill the login form. It is not
* authoritative.
*/
const COOKIE_USERNAME = 'phusr';
/**
* Stores the user's current session ID. This is authoritative and establishes
* the user's identity.
*/
const COOKIE_SESSION = 'phsid';
/**
* Stores a secret used during new account registration to prevent an attacker
* from tricking a victim into registering an account which is linked to
* credentials the attacker controls.
*/
const COOKIE_REGISTRATION = 'phreg';
/**
* Stores a secret used during OAuth2 handshakes to prevent various attacks
* where an attacker hands a victim a URI corresponding to the middle of an
* OAuth2 workflow and we might otherwise do something sketchy. Particularly,
* this corresponds to the OAuth2 "code".
*/
const COOKIE_CLIENTID = 'phcid';
/**
* Stores the URI to redirect the user to after login. This allows users to
* visit a path like `/feed/`, be prompted to login, and then be redirected
* back to `/feed/` after the workflow completes.
*/
const COOKIE_NEXTURI = 'next_uri';
/**
* Stores a hint that the user should be moved directly into high security
* after upgrading a partial login session. This is used during password
* recovery to avoid a double-prompt.
*/
const COOKIE_HISEC = 'jump_to_hisec';
/**
* Stores an invite code.
*/
const COOKIE_INVITE = 'invite';
/**
* Stores a workflow completion across a redirect-after-POST following a
* form submission. This can be used to show "Changes Saved" messages.
*/
const COOKIE_SUBMIT = 'phfrm';
/* -( Client ID Cookie )--------------------------------------------------- */
/**
* Set the client ID cookie. This is a random cookie used like a CSRF value
* during authentication workflows.
*
* @param AphrontRequest Request to modify.
* @return void
* @task clientid
*/
public static function setClientIDCookie(AphrontRequest $request) {
// NOTE: See T3471 for some discussion. Some browsers and browser extensions
// can make duplicate requests, so we overwrite this cookie only if it is
// not present in the request. The cookie lifetime is limited by making it
// temporary and clearing it when users log out.
$value = $request->getCookie(self::COOKIE_CLIENTID);
if ($value === null || !strlen($value)) {
$request->setTemporaryCookie(
self::COOKIE_CLIENTID,
Filesystem::readRandomCharacters(16));
}
}
/* -( Next URI Cookie )---------------------------------------------------- */
/**
* Set the Next URI cookie. We only write the cookie if it wasn't recently
* written, to avoid writing over a real URI with a bunch of "humans.txt"
* stuff. See T3793 for discussion.
*
* @param AphrontRequest Request to write to.
* @param string URI to write.
* @param bool Write this cookie even if we have a fresh
* cookie already.
* @return void
*
* @task next
*/
public static function setNextURICookie(
AphrontRequest $request,
$next_uri,
$force = false) {
if (!$force) {
$cookie_value = $request->getCookie(self::COOKIE_NEXTURI);
list($set_at, $current_uri) = self::parseNextURICookie($cookie_value);
// If the cookie was set within the last 2 minutes, don't overwrite it.
// Primarily, this prevents browser requests for resources which do not
// exist (like "humans.txt" and various icons) from overwriting a normal
// URI like "/feed/".
if ($set_at > (time() - 120)) {
return;
}
}
$new_value = time().','.$next_uri;
$request->setTemporaryCookie(self::COOKIE_NEXTURI, $new_value);
}
/**
* Read the URI out of the Next URI cookie.
*
* @param AphrontRequest Request to examine.
* @return string|null Next URI cookie's URI value.
*
* @task next
*/
public static function getNextURICookie(AphrontRequest $request) {
$cookie_value = $request->getCookie(self::COOKIE_NEXTURI);
list($set_at, $next_uri) = self::parseNextURICookie($cookie_value);
return $next_uri;
}
/**
* Parse a Next URI cookie into its components.
*
* @param string Raw cookie value.
* @return list<string> List of timestamp and URI.
*
* @task next
*/
private static function parseNextURICookie($cookie) {
// Old cookies look like: /uri
// New cookies look like: timestamp,/uri
if (!phutil_nonempty_string($cookie)) {
return null;
}
if (strpos($cookie, ',') !== false) {
list($timestamp, $uri) = explode(',', $cookie, 2);
return array((int)$timestamp, $uri);
}
return array(0, $cookie);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/auth/constants/PhabricatorAuthFactorProviderStatus.php | src/applications/auth/constants/PhabricatorAuthFactorProviderStatus.php | <?php
final class PhabricatorAuthFactorProviderStatus
extends Phobject {
private $key;
private $spec = array();
const STATUS_ACTIVE = 'active';
const STATUS_DEPRECATED = 'deprecated';
const STATUS_DISABLED = 'disabled';
public static function newForStatus($status) {
$result = new self();
$result->key = $status;
$result->spec = self::newSpecification($status);
return $result;
}
public function getName() {
return idx($this->spec, 'name', $this->key);
}
public function getStatusHeaderIcon() {
return idx($this->spec, 'header.icon');
}
public function getStatusHeaderColor() {
return idx($this->spec, 'header.color');
}
public function isActive() {
return ($this->key === self::STATUS_ACTIVE);
}
public function getListIcon() {
return idx($this->spec, 'list.icon');
}
public function getListColor() {
return idx($this->spec, 'list.color');
}
public function getFactorIcon() {
return idx($this->spec, 'factor.icon');
}
public function getFactorColor() {
return idx($this->spec, 'factor.color');
}
public function getOrder() {
return idx($this->spec, 'order', 0);
}
public static function getMap() {
$specs = self::newSpecifications();
return ipull($specs, 'name');
}
private static function newSpecification($key) {
$specs = self::newSpecifications();
return idx($specs, $key, array());
}
private static function newSpecifications() {
return array(
self::STATUS_ACTIVE => array(
'name' => pht('Active'),
'header.icon' => 'fa-check',
'header.color' => null,
'list.icon' => null,
'list.color' => null,
'factor.icon' => 'fa-check',
'factor.color' => 'green',
'order' => 1,
),
self::STATUS_DEPRECATED => array(
'name' => pht('Deprecated'),
'header.icon' => 'fa-ban',
'header.color' => 'indigo',
'list.icon' => 'fa-ban',
'list.color' => 'indigo',
'factor.icon' => 'fa-ban',
'factor.color' => 'indigo',
'order' => 2,
),
self::STATUS_DISABLED => array(
'name' => pht('Disabled'),
'header.icon' => 'fa-times',
'header.color' => 'red',
'list.icon' => 'fa-times',
'list.color' => 'red',
'factor.icon' => 'fa-times',
'factor.color' => 'grey',
'order' => 3,
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentSignatureViewController.php | src/applications/legalpad/controller/LegalpadDocumentSignatureViewController.php | <?php
final class LegalpadDocumentSignatureViewController extends LegalpadController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$signature = id(new LegalpadDocumentSignatureQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$signature) {
return new Aphront404Response();
}
// NOTE: In order to see signature details (which include the relatively
// internal-feeling "notes" field) you must be able to edit the document.
// Essentially, this power is for document managers. Notably, this prevents
// users from seeing notes about their own exemptions by guessing their
// signature ID. This is purely a policy check.
$document = id(new LegalpadDocumentQuery())
->setViewer($viewer)
->withIDs(array($signature->getDocument()->getID()))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$document) {
return new Aphront404Response();
}
$document_id = $signature->getDocument()->getID();
$next_uri = $this->getApplicationURI('signatures/'.$document_id.'/');
$data = $signature->getSignatureData();
$exemption_phid = $signature->getExemptionPHID();
$actor_phid = idx($data, 'actorPHID');
$handles = $this->loadViewerHandles(
array(
$exemption_phid,
$actor_phid,
));
$exemptor_handle = $handles[$exemption_phid];
$actor_handle = $handles[$actor_phid];
$form = id(new AphrontFormView())
->setUser($viewer);
if ($signature->getExemptionPHID()) {
$form
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Exemption By'))
->setValue($exemptor_handle->renderLink()))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Notes'))
->setValue(idx($data, 'notes')));
}
$type_corporation = LegalpadDocument::SIGNATURE_TYPE_CORPORATION;
if ($signature->getSignatureType() == $type_corporation) {
$form
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Signing User'))
->setValue($actor_handle->renderLink()))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Company Name'))
->setValue(idx($data, 'name')))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Address'))
->setValue(phutil_escape_html_newlines(idx($data, 'address'))))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Contact Name'))
->setValue(idx($data, 'contact.name')))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Contact Email'))
->setValue(
phutil_tag(
'a',
array(
'href' => 'mailto:'.idx($data, 'email'),
),
idx($data, 'email'))));
}
return $this->newDialog()
->setTitle(pht('Signature Details'))
->setWidth(AphrontDialogView::WIDTH_FORM)
->appendChild($form->buildLayoutView())
->addCancelButton($next_uri, pht('Close'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentManageController.php | src/applications/legalpad/controller/LegalpadDocumentManageController.php | <?php
final class LegalpadDocumentManageController extends LegalpadController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
// NOTE: We require CAN_EDIT to view this page.
$document = id(new LegalpadDocumentQuery())
->setViewer($viewer)
->withIDs(array($id))
->needDocumentBodies(true)
->needContributors(true)
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$document) {
return new Aphront404Response();
}
$subscribers = PhabricatorSubscribersQuery::loadSubscribersForPHID(
$document->getPHID());
$document_body = $document->getDocumentBody();
$engine = id(new PhabricatorMarkupEngine())
->setViewer($viewer);
$engine->addObject(
$document_body,
LegalpadDocumentBody::MARKUP_FIELD_TEXT);
$timeline = $this->buildTransactionTimeline(
$document,
new LegalpadTransactionQuery(),
$engine);
$timeline->setQuoteRef($document->getMonogram());
$title = $document_body->getTitle();
$header = id(new PHUIHeaderView())
->setHeader($title)
->setUser($viewer)
->setPolicyObject($document)
->setHeaderIcon('fa-gavel');
$curtain = $this->buildCurtainView($document);
$properties = $this->buildPropertyView($document, $engine);
$document_view = $this->buildDocumentView($document, $engine);
$comment_form = $this->buildCommentView($document, $timeline);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb(
$document->getMonogram(),
'/'.$document->getMonogram());
$crumbs->addTextCrumb(pht('Manage'));
$crumbs->setBorder(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$properties,
$document_view,
$timeline,
$comment_form,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->setPageObjectPHIDs(array($document->getPHID()))
->appendChild($view);
}
private function buildDocumentView(
LegalpadDocument $document,
PhabricatorMarkupEngine $engine) {
$viewer = $this->getViewer();
$view = id(new PHUIPropertyListView())
->setUser($viewer);
$document_body = $document->getDocumentBody();
$document_text = $engine->getOutput(
$document_body, LegalpadDocumentBody::MARKUP_FIELD_TEXT);
$preamble_box = null;
if (strlen($document->getPreamble())) {
$preamble_text = new PHUIRemarkupView($viewer, $document->getPreamble());
$view->addTextContent($preamble_text);
$view->addSectionHeader('');
$view->addTextContent($document_text);
} else {
$view->addTextContent($document_text);
}
return id(new PHUIObjectBoxView())
->setHeaderText(pht('DOCUMENT'))
->addPropertyList($view)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY);
}
private function buildCurtainView(LegalpadDocument $document) {
$viewer = $this->getViewer();
$curtain = $this->newCurtainView($document);
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$document,
PhabricatorPolicyCapability::CAN_EDIT);
$doc_id = $document->getID();
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-pencil-square')
->setName(pht('View/Sign Document'))
->setHref('/'.$document->getMonogram()));
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-pencil')
->setName(pht('Edit Document'))
->setHref($this->getApplicationURI('/edit/'.$doc_id.'/'))
->setDisabled(!$can_edit)
->setWorkflow(!$can_edit));
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-terminal')
->setName(pht('View Signatures'))
->setHref($this->getApplicationURI('/signatures/'.$doc_id.'/')));
return $curtain;
}
private function buildPropertyView(
LegalpadDocument $document,
PhabricatorMarkupEngine $engine) {
$viewer = $this->getViewer();
$properties = id(new PHUIPropertyListView())
->setUser($viewer);
$properties->addProperty(
pht('Signature Type'),
$document->getSignatureTypeName());
$properties->addProperty(
pht('Last Updated'),
phabricator_datetime($document->getDateModified(), $viewer));
$properties->addProperty(
pht('Updated By'),
$viewer->renderHandle($document->getDocumentBody()->getCreatorPHID()));
$properties->addProperty(
pht('Versions'),
$document->getVersions());
if ($document->getContributors()) {
$properties->addProperty(
pht('Contributors'),
$viewer
->renderHandleList($document->getContributors())
->setAsInline(true));
}
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Properties'))
->addPropertyList($properties)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY);
}
private function buildCommentView(LegalpadDocument $document, $timeline) {
$viewer = $this->getViewer();
$box = id(new LegalpadDocumentEditEngine())
->setViewer($viewer)
->buildEditEngineCommentView($document)
->setTransactionTimeline($timeline);
return $box;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentSignatureVerificationController.php | src/applications/legalpad/controller/LegalpadDocumentSignatureVerificationController.php | <?php
final class LegalpadDocumentSignatureVerificationController
extends LegalpadController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$code = $request->getURIData('code');
// NOTE: We're using the omnipotent user to handle logged-out signatures
// and corporate signatures.
$signature = id(new LegalpadDocumentSignatureQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withSecretKeys(array($code))
->executeOne();
if (!$signature) {
return $this->newDialog()
->setTitle(pht('Unable to Verify Signature'))
->appendParagraph(
pht(
'The signature verification code is incorrect, or the signature '.
'has been invalidated. Make sure you followed the link in the '.
'email correctly.'))
->addCancelButton('/', pht('Rats!'));
}
if ($signature->isVerified()) {
return $this->newDialog()
->setTitle(pht('Signature Already Verified'))
->appendParagraph(pht('This signature has already been verified.'))
->addCancelButton('/', pht('Okay'));
}
if ($request->isFormPost()) {
$signature
->setVerified(LegalpadDocumentSignature::VERIFIED)
->save();
return $this->newDialog()
->setTitle(pht('Signature Verified'))
->appendParagraph(pht('The signature is now verified.'))
->addCancelButton('/', pht('Okay'));
}
$document_link = phutil_tag(
'a',
array(
'href' => '/'.$signature->getDocument()->getMonogram(),
'target' => '_blank',
),
$signature->getDocument()->getTitle());
$signed_at = phabricator_datetime($signature->getDateCreated(), $viewer);
$name = $signature->getSignerName();
$email = $signature->getSignerEmail();
$form = id(new AphrontFormView())
->setUser($viewer)
->appendRemarkupInstructions(
pht('Please verify this document signature.'))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Document'))
->setValue($document_link))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Signed At'))
->setValue($signed_at))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Name'))
->setValue($name))
->appendChild(
id(new AphrontFormMarkupControl())
->setLabel(pht('Email'))
->setValue($email));
return $this->newDialog()
->setTitle(pht('Verify Signature?'))
->appendChild($form->buildLayoutView())
->addCancelButton('/')
->addSubmitButton(pht('Verify Signature'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentDoneController.php | src/applications/legalpad/controller/LegalpadDocumentDoneController.php | <?php
final class LegalpadDocumentDoneController extends LegalpadController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
return $this->newDialog()
->setTitle(pht('Verify Signature'))
->appendParagraph(
pht(
'Thank you for signing this document. Please check your email '.
'to verify your signature and complete the process.'))
->addCancelButton('/', pht('Okay'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentEditController.php | src/applications/legalpad/controller/LegalpadDocumentEditController.php | <?php
final class LegalpadDocumentEditController extends LegalpadController {
public function handleRequest(AphrontRequest $request) {
return id(new LegalpadDocumentEditEngine())
->setController($this)
->buildResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentSignatureAddController.php | src/applications/legalpad/controller/LegalpadDocumentSignatureAddController.php | <?php
final class LegalpadDocumentSignatureAddController extends LegalpadController {
public function handleRequest(AphrontRequest $request) {
$request = $this->getRequest();
$viewer = $request->getUser();
$document = id(new LegalpadDocumentQuery())
->setViewer($viewer)
->needDocumentBodies(true)
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->withIDs(array($request->getURIData('id')))
->executeOne();
if (!$document) {
return new Aphront404Response();
}
$next_uri = $this->getApplicationURI('signatures/'.$document->getID().'/');
$e_name = true;
$e_user = true;
$v_users = array();
$v_notes = '';
$v_name = '';
$errors = array();
$type_individual = LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL;
$is_individual = ($document->getSignatureType() == $type_individual);
if ($request->isFormPost()) {
$v_notes = $request->getStr('notes');
$v_users = array_slice($request->getArr('users'), 0, 1);
$v_name = $request->getStr('name');
if ($is_individual) {
$user_phid = head($v_users);
if (!$user_phid) {
$e_user = pht('Required');
$errors[] = pht('You must choose a user to exempt.');
} else {
$user = id(new PhabricatorPeopleQuery())
->setViewer($viewer)
->withPHIDs(array($user_phid))
->executeOne();
if (!$user) {
$e_user = pht('Invalid');
$errors[] = pht('That user does not exist.');
} else {
$signature = id(new LegalpadDocumentSignatureQuery())
->setViewer($viewer)
->withDocumentPHIDs(array($document->getPHID()))
->withSignerPHIDs(array($user->getPHID()))
->executeOne();
if ($signature) {
$e_user = pht('Signed');
$errors[] = pht('That user has already signed this document.');
} else {
$e_user = null;
}
}
}
} else {
$company_name = $v_name;
if (!strlen($company_name)) {
$e_name = pht('Required');
$errors[] = pht('You must choose a company to add an exemption for.');
}
}
if (!$errors) {
if ($is_individual) {
$name = $user->getRealName();
$email = $user->loadPrimaryEmailAddress();
$signer_phid = $user->getPHID();
$signature_data = array(
'name' => $name,
'email' => $email,
'notes' => $v_notes,
);
} else {
$name = $company_name;
$email = '';
$signer_phid = null;
$signature_data = array(
'name' => $name,
'email' => null,
'notes' => $v_notes,
'actorPHID' => $viewer->getPHID(),
);
}
$signature = id(new LegalpadDocumentSignature())
->setDocumentPHID($document->getPHID())
->setDocumentVersion($document->getVersions())
->setSignerPHID($signer_phid)
->setSignerName($name)
->setSignerEmail($email)
->setSignatureType($document->getSignatureType())
->setIsExemption(1)
->setExemptionPHID($viewer->getPHID())
->setVerified(LegalpadDocumentSignature::VERIFIED)
->setSignatureData($signature_data);
$signature->save();
return id(new AphrontRedirectResponse())->setURI($next_uri);
}
}
$form = id(new AphrontFormView())
->setUser($viewer);
if ($is_individual) {
$form
->appendControl(
id(new AphrontFormTokenizerControl())
->setLabel(pht('Exempt User'))
->setName('users')
->setLimit(1)
->setDatasource(new PhabricatorPeopleDatasource())
->setValue($v_users)
->setError($e_user));
} else {
$form
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Company Name'))
->setName('name')
->setError($e_name)
->setValue($v_name));
}
$form
->appendChild(
id(new AphrontFormTextAreaControl())
->setLabel(pht('Notes'))
->setName('notes')
->setValue($v_notes));
return $this->newDialog()
->setTitle(pht('Add Signature Exemption'))
->setWidth(AphrontDialogView::WIDTH_FORM)
->setErrors($errors)
->appendParagraph(
pht(
'You can record a signature exemption if a user has signed an '.
'equivalent document. Other applications will behave as through the '.
'user has signed this document.'))
->appendParagraph(null)
->appendChild($form->buildLayoutView())
->addSubmitButton(pht('Add Exemption'))
->addCancelButton($next_uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentSignatureListController.php | src/applications/legalpad/controller/LegalpadDocumentSignatureListController.php | <?php
final class LegalpadDocumentSignatureListController extends LegalpadController {
private $document;
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$querykey = $request->getURIData('queryKey');
if ($id) {
$document = id(new LegalpadDocumentQuery())
->setViewer($viewer)
->withIDs(array($id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$document) {
return new Aphront404Response();
}
$this->document = $document;
}
$engine = id(new LegalpadDocumentSignatureSearchEngine());
if ($this->document) {
$engine->setDocument($this->document);
}
$controller = id(new PhabricatorApplicationSearchController())
->setQueryKey($querykey)
->setSearchEngine($engine)
->setNavigation($this->buildSideNav());
return $this->delegateToController($controller);
}
public function buildSideNav($for_app = false) {
$viewer = $this->getViewer();
$nav = new AphrontSideNavFilterView();
$nav->setBaseURI(new PhutilURI($this->getApplicationURI()));
$engine = id(new LegalpadDocumentSignatureSearchEngine())
->setViewer($viewer);
if ($this->document) {
$engine->setDocument($this->document);
}
$engine->addNavigationItems($nav->getMenu());
return $nav;
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
if ($this->document) {
$crumbs->addTextCrumb(
$this->document->getMonogram(),
'/'.$this->document->getMonogram());
$crumbs->addTextCrumb(
pht('Manage'),
$this->getApplicationURI('view/'.$this->document->getID().'/'));
} else {
$crumbs->addTextCrumb(
pht('Signatures'),
'/legalpad/signatures/');
}
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadController.php | src/applications/legalpad/controller/LegalpadController.php | <?php
abstract class LegalpadController extends PhabricatorController {
public function buildSideNav($for_app = false) {
$user = $this->getRequest()->getUser();
$nav = new AphrontSideNavFilterView();
$nav->setBaseURI(new PhutilURI($this->getApplicationURI()));
if ($for_app) {
$nav->addFilter('edit/', pht('Create Document'));
}
id(new LegalpadDocumentSearchEngine())
->setViewer($user)
->addNavigationItems($nav->getMenu());
$nav->addLabel(pht('Signatures'));
$nav->addFilter('signatures/', pht('Find Signatures'));
return $nav;
}
public function buildApplicationMenu() {
return $this->buildSideNav(true)->getMenu();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentListController.php | src/applications/legalpad/controller/LegalpadDocumentListController.php | <?php
final class LegalpadDocumentListController extends LegalpadController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$querykey = $request->getURIData('queryKey');
$controller = id(new PhabricatorApplicationSearchController())
->setQueryKey($querykey)
->setSearchEngine(new LegalpadDocumentSearchEngine())
->setNavigation($this->buildSideNav());
return $this->delegateToController($controller);
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$can_create = $this->hasApplicationCapability(
LegalpadCreateDocumentsCapability::CAPABILITY);
$crumbs->addAction(
id(new PHUIListItemView())
->setName(pht('Create Document'))
->setHref($this->getApplicationURI('edit/'))
->setIcon('fa-plus-square')
->setDisabled(!$can_create)
->setWorkflow(!$can_create));
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/controller/LegalpadDocumentSignController.php | src/applications/legalpad/controller/LegalpadDocumentSignController.php | <?php
final class LegalpadDocumentSignController extends LegalpadController {
private $isSessionGate;
public function shouldAllowPublic() {
return true;
}
public function shouldAllowLegallyNonCompliantUsers() {
return true;
}
public function setIsSessionGate($is_session_gate) {
$this->isSessionGate = $is_session_gate;
return $this;
}
public function getIsSessionGate() {
return $this->isSessionGate;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getUser();
$document = id(new LegalpadDocumentQuery())
->setViewer($viewer)
->withIDs(array($request->getURIData('id')))
->needDocumentBodies(true)
->executeOne();
if (!$document) {
return new Aphront404Response();
}
$information = $this->readSignerInformation(
$document,
$request);
if ($information instanceof AphrontResponse) {
return $information;
}
list($signer_phid, $signature_data) = $information;
$signature = null;
$type_individual = LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL;
$is_individual = ($document->getSignatureType() == $type_individual);
switch ($document->getSignatureType()) {
case LegalpadDocument::SIGNATURE_TYPE_NONE:
// nothing to sign means this should be true
$has_signed = true;
// this is a status UI element
$signed_status = null;
break;
case LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL:
if ($signer_phid) {
// TODO: This is odd and should probably be adjusted after
// grey/external accounts work better, but use the omnipotent
// viewer to check for a signature so we can pick up
// anonymous/grey signatures.
$signature = id(new LegalpadDocumentSignatureQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withDocumentPHIDs(array($document->getPHID()))
->withSignerPHIDs(array($signer_phid))
->executeOne();
if ($signature && !$viewer->isLoggedIn()) {
return $this->newDialog()
->setTitle(pht('Already Signed'))
->appendParagraph(pht('You have already signed this document!'))
->addCancelButton('/'.$document->getMonogram(), pht('Okay'));
}
}
$signed_status = null;
if (!$signature) {
$has_signed = false;
$signature = id(new LegalpadDocumentSignature())
->setSignerPHID($signer_phid)
->setDocumentPHID($document->getPHID())
->setDocumentVersion($document->getVersions());
// If the user is logged in, show a notice that they haven't signed.
// If they aren't logged in, we can't be as sure, so don't show
// anything.
if ($viewer->isLoggedIn()) {
$signed_status = id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_WARNING)
->setErrors(
array(
pht('You have not signed this document yet.'),
));
}
} else {
$has_signed = true;
$signature_data = $signature->getSignatureData();
// In this case, we know they've signed.
$signed_at = $signature->getDateCreated();
if ($signature->getIsExemption()) {
$exemption_phid = $signature->getExemptionPHID();
$handles = $this->loadViewerHandles(array($exemption_phid));
$exemption_handle = $handles[$exemption_phid];
$signed_text = pht(
'You do not need to sign this document. '.
'%s added a signature exemption for you on %s.',
$exemption_handle->renderLink(),
phabricator_datetime($signed_at, $viewer));
} else {
$signed_text = pht(
'You signed this document on %s.',
phabricator_datetime($signed_at, $viewer));
}
$signed_status = id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_NOTICE)
->setErrors(array($signed_text));
}
$field_errors = array(
'name' => true,
'email' => true,
'agree' => true,
);
$signature->setSignatureData($signature_data);
break;
case LegalpadDocument::SIGNATURE_TYPE_CORPORATION:
$signature = id(new LegalpadDocumentSignature())
->setDocumentPHID($document->getPHID())
->setDocumentVersion($document->getVersions());
if ($viewer->isLoggedIn()) {
$has_signed = false;
$signed_status = null;
} else {
// This just hides the form.
$has_signed = true;
$login_text = pht(
'This document requires a corporate signatory. You must log in to '.
'accept this document on behalf of a company you represent.');
$signed_status = id(new PHUIInfoView())
->setSeverity(PHUIInfoView::SEVERITY_WARNING)
->setErrors(array($login_text));
}
$field_errors = array(
'name' => true,
'address' => true,
'contact.name' => true,
'email' => true,
);
$signature->setSignatureData($signature_data);
break;
}
$errors = array();
$hisec_token = null;
if ($request->isFormOrHisecPost() && !$has_signed) {
list($form_data, $errors, $field_errors) = $this->readSignatureForm(
$document,
$request);
$signature_data = $form_data + $signature_data;
$signature->setSignatureData($signature_data);
$signature->setSignatureType($document->getSignatureType());
$signature->setSignerName((string)idx($signature_data, 'name'));
$signature->setSignerEmail((string)idx($signature_data, 'email'));
$agree = $request->getExists('agree');
if (!$agree) {
$errors[] = pht(
'You must check "I agree to the terms laid forth above."');
$field_errors['agree'] = pht('Required');
}
if ($viewer->isLoggedIn() && $is_individual) {
$verified = LegalpadDocumentSignature::VERIFIED;
} else {
$verified = LegalpadDocumentSignature::UNVERIFIED;
}
$signature->setVerified($verified);
if (!$errors) {
// Require MFA to sign legal documents.
if ($viewer->isLoggedIn()) {
$workflow_key = sprintf(
'legalpad.sign(%s)',
$document->getPHID());
$hisec_token = id(new PhabricatorAuthSessionEngine())
->setWorkflowKey($workflow_key)
->requireHighSecurityToken(
$viewer,
$request,
$document->getURI());
}
$signature->save();
// If the viewer is logged in, signing for themselves, send them to
// the document page, which will show that they have signed the
// document. Unless of course they were required to sign the
// document to use Phabricator; in that case try really hard to
// re-direct them to where they wanted to go.
//
// Otherwise, send them to a completion page.
if ($viewer->isLoggedIn() && $is_individual) {
$next_uri = '/'.$document->getMonogram();
if ($document->getRequireSignature()) {
$request_uri = $request->getRequestURI();
$next_uri = (string)$request_uri;
}
} else {
$this->sendVerifySignatureEmail(
$document,
$signature);
$next_uri = $this->getApplicationURI('done/');
}
return id(new AphrontRedirectResponse())->setURI($next_uri);
}
}
$document_body = $document->getDocumentBody();
$engine = id(new PhabricatorMarkupEngine())
->setViewer($viewer);
$engine->addObject(
$document_body,
LegalpadDocumentBody::MARKUP_FIELD_TEXT);
$engine->process();
$document_markup = $engine->getOutput(
$document_body,
LegalpadDocumentBody::MARKUP_FIELD_TEXT);
$title = $document_body->getTitle();
$manage_uri = $this->getApplicationURI('view/'.$document->getID().'/');
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$document,
PhabricatorPolicyCapability::CAN_EDIT);
// Use the last content update as the modified date. We don't want to
// show that a document like a TOS was "updated" by an incidental change
// to a field like the preamble or privacy settings which does not actually
// affect the content of the agreement.
$content_updated = $document_body->getDateCreated();
// NOTE: We're avoiding `setPolicyObject()` here so we don't pick up
// extra UI elements that are unnecessary and clutter the signature page.
// These details are available on the "Manage" page.
$header = id(new PHUIHeaderView())
->setHeader($title)
->setUser($viewer)
->setEpoch($content_updated);
// If we're showing the user this document because it's required to use
// Phabricator and they haven't signed it, don't show the "Manage" button,
// since it won't work.
$is_gate = $this->getIsSessionGate();
if (!$is_gate) {
$header->addActionLink(
id(new PHUIButtonView())
->setTag('a')
->setIcon('fa-pencil')
->setText(pht('Manage'))
->setHref($manage_uri)
->setDisabled(!$can_edit)
->setWorkflow(!$can_edit));
}
$preamble_box = null;
if (strlen($document->getPreamble())) {
$preamble_text = new PHUIRemarkupView($viewer, $document->getPreamble());
// NOTE: We're avoiding `setObject()` here so we don't pick up extra UI
// elements like "Subscribers". This information is available on the
// "Manage" page, but just clutters up the "Signature" page.
$preamble = id(new PHUIPropertyListView())
->setUser($viewer)
->addSectionHeader(pht('Preamble'))
->addTextContent($preamble_text);
$preamble_box = new PHUIPropertyGroupView();
$preamble_box->addPropertyList($preamble);
}
$content = id(new PHUIDocumentView())
->addClass('legalpad')
->setHeader($header)
->appendChild(
array(
$signed_status,
$preamble_box,
$document_markup,
));
$signature_box = null;
if (!$has_signed) {
$error_view = null;
if ($errors) {
$error_view = id(new PHUIInfoView())
->setErrors($errors);
}
$signature_form = $this->buildSignatureForm(
$document,
$signature,
$field_errors);
switch ($document->getSignatureType()) {
default:
break;
case LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL:
case LegalpadDocument::SIGNATURE_TYPE_CORPORATION:
$box = id(new PHUIObjectBoxView())
->addClass('document-sign-box')
->setHeaderText(pht('Agree and Sign Document'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setForm($signature_form);
if ($error_view) {
$box->setInfoView($error_view);
}
$signature_box = phutil_tag_div(
'phui-document-view-pro-box plt', $box);
break;
}
}
$crumbs = $this->buildApplicationCrumbs();
$crumbs->setBorder(true);
$crumbs->addTextCrumb($document->getMonogram());
$box = id(new PHUITwoColumnView())
->setFooter($signature_box);
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->setPageObjectPHIDs(array($document->getPHID()))
->appendChild(array(
$content,
$box,
));
}
private function readSignerInformation(
LegalpadDocument $document,
AphrontRequest $request) {
$viewer = $request->getUser();
$signer_phid = null;
$signature_data = array();
switch ($document->getSignatureType()) {
case LegalpadDocument::SIGNATURE_TYPE_NONE:
break;
case LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL:
if ($viewer->isLoggedIn()) {
$signer_phid = $viewer->getPHID();
$signature_data = array(
'name' => $viewer->getRealName(),
'email' => $viewer->loadPrimaryEmailAddress(),
);
} else if ($request->isFormPost()) {
$email = new PhutilEmailAddress($request->getStr('email'));
if (strlen($email->getDomainName())) {
$email_obj = id(new PhabricatorUserEmail())
->loadOneWhere('address = %s', $email->getAddress());
if ($email_obj) {
return $this->signInResponse();
}
}
}
break;
case LegalpadDocument::SIGNATURE_TYPE_CORPORATION:
$signer_phid = $viewer->getPHID();
if ($signer_phid) {
$signature_data = array(
'contact.name' => $viewer->getRealName(),
'email' => $viewer->loadPrimaryEmailAddress(),
'actorPHID' => $viewer->getPHID(),
);
}
break;
}
return array($signer_phid, $signature_data);
}
private function buildSignatureForm(
LegalpadDocument $document,
LegalpadDocumentSignature $signature,
array $errors) {
$viewer = $this->getRequest()->getUser();
$data = $signature->getSignatureData();
$form = id(new AphrontFormView())
->setUser($viewer);
$signature_type = $document->getSignatureType();
switch ($signature_type) {
case LegalpadDocument::SIGNATURE_TYPE_NONE:
// bail out of here quick
return;
case LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL:
$this->buildIndividualSignatureForm(
$form,
$document,
$signature,
$errors);
break;
case LegalpadDocument::SIGNATURE_TYPE_CORPORATION:
$this->buildCorporateSignatureForm(
$form,
$document,
$signature,
$errors);
break;
default:
throw new Exception(
pht(
'This document has an unknown signature type ("%s").',
$signature_type));
}
$form
->appendChild(
id(new AphrontFormCheckboxControl())
->setError(idx($errors, 'agree', null))
->addCheckbox(
'agree',
'agree',
pht('I agree to the terms laid forth above.'),
false));
if ($document->getRequireSignature()) {
$cancel_uri = '/logout/';
$cancel_text = pht('Log Out');
} else {
$cancel_uri = $this->getApplicationURI();
$cancel_text = pht('Cancel');
}
$form
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Sign Document'))
->addCancelButton($cancel_uri, $cancel_text));
return $form;
}
private function buildIndividualSignatureForm(
AphrontFormView $form,
LegalpadDocument $document,
LegalpadDocumentSignature $signature,
array $errors) {
$data = $signature->getSignatureData();
$form
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Name'))
->setValue(idx($data, 'name', ''))
->setName('name')
->setError(idx($errors, 'name', null)));
$viewer = $this->getRequest()->getUser();
if (!$viewer->isLoggedIn()) {
$form->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Email'))
->setValue(idx($data, 'email', ''))
->setName('email')
->setError(idx($errors, 'email', null)));
}
return $form;
}
private function buildCorporateSignatureForm(
AphrontFormView $form,
LegalpadDocument $document,
LegalpadDocumentSignature $signature,
array $errors) {
$data = $signature->getSignatureData();
$form
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Company Name'))
->setValue(idx($data, 'name', ''))
->setName('name')
->setError(idx($errors, 'name', null)))
->appendChild(
id(new AphrontFormTextAreaControl())
->setLabel(pht('Company Address'))
->setValue(idx($data, 'address', ''))
->setName('address')
->setError(idx($errors, 'address', null)))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Contact Name'))
->setValue(idx($data, 'contact.name', ''))
->setName('contact.name')
->setError(idx($errors, 'contact.name', null)))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Contact Email'))
->setValue(idx($data, 'email', ''))
->setName('email')
->setError(idx($errors, 'email', null)));
return $form;
}
private function readSignatureForm(
LegalpadDocument $document,
AphrontRequest $request) {
$signature_type = $document->getSignatureType();
switch ($signature_type) {
case LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL:
$result = $this->readIndividualSignatureForm(
$document,
$request);
break;
case LegalpadDocument::SIGNATURE_TYPE_CORPORATION:
$result = $this->readCorporateSignatureForm(
$document,
$request);
break;
default:
throw new Exception(
pht(
'This document has an unknown signature type ("%s").',
$signature_type));
}
return $result;
}
private function readIndividualSignatureForm(
LegalpadDocument $document,
AphrontRequest $request) {
$signature_data = array();
$errors = array();
$field_errors = array();
$name = $request->getStr('name');
if (!strlen($name)) {
$field_errors['name'] = pht('Required');
$errors[] = pht('Name field is required.');
} else {
$field_errors['name'] = null;
}
$signature_data['name'] = $name;
$viewer = $request->getUser();
if ($viewer->isLoggedIn()) {
$email = $viewer->loadPrimaryEmailAddress();
} else {
$email = $request->getStr('email');
$addr_obj = null;
if (!strlen($email)) {
$field_errors['email'] = pht('Required');
$errors[] = pht('Email field is required.');
} else {
$addr_obj = new PhutilEmailAddress($email);
$domain = $addr_obj->getDomainName();
if (!$domain) {
$field_errors['email'] = pht('Invalid');
$errors[] = pht('A valid email is required.');
} else {
$field_errors['email'] = null;
}
}
}
$signature_data['email'] = $email;
return array($signature_data, $errors, $field_errors);
}
private function readCorporateSignatureForm(
LegalpadDocument $document,
AphrontRequest $request) {
$viewer = $request->getUser();
if (!$viewer->isLoggedIn()) {
throw new Exception(
pht(
'You can not sign a document on behalf of a corporation unless '.
'you are logged in.'));
}
$signature_data = array();
$errors = array();
$field_errors = array();
$name = $request->getStr('name');
if (!strlen($name)) {
$field_errors['name'] = pht('Required');
$errors[] = pht('Company name is required.');
} else {
$field_errors['name'] = null;
}
$signature_data['name'] = $name;
$address = $request->getStr('address');
if (!strlen($address)) {
$field_errors['address'] = pht('Required');
$errors[] = pht('Company address is required.');
} else {
$field_errors['address'] = null;
}
$signature_data['address'] = $address;
$contact_name = $request->getStr('contact.name');
if (!strlen($contact_name)) {
$field_errors['contact.name'] = pht('Required');
$errors[] = pht('Contact name is required.');
} else {
$field_errors['contact.name'] = null;
}
$signature_data['contact.name'] = $contact_name;
$email = $request->getStr('email');
$addr_obj = null;
if (!strlen($email)) {
$field_errors['email'] = pht('Required');
$errors[] = pht('Contact email is required.');
} else {
$addr_obj = new PhutilEmailAddress($email);
$domain = $addr_obj->getDomainName();
if (!$domain) {
$field_errors['email'] = pht('Invalid');
$errors[] = pht('A valid email is required.');
} else {
$field_errors['email'] = null;
}
}
$signature_data['email'] = $email;
return array($signature_data, $errors, $field_errors);
}
private function sendVerifySignatureEmail(
LegalpadDocument $doc,
LegalpadDocumentSignature $signature) {
$signature_data = $signature->getSignatureData();
$email = new PhutilEmailAddress($signature_data['email']);
$doc_name = $doc->getTitle();
$doc_link = PhabricatorEnv::getProductionURI('/'.$doc->getMonogram());
$path = $this->getApplicationURI(sprintf(
'/verify/%s/',
$signature->getSecretKey()));
$link = PhabricatorEnv::getProductionURI($path);
$name = idx($signature_data, 'name');
$body = pht(
"%s:\n\n".
"This email address was used to sign a Legalpad document ".
"in %s:\n\n".
" %s\n\n".
"Please verify you own this email address and accept the ".
"agreement by clicking this link:\n\n".
" %s\n\n".
"Your signature is not valid until you complete this ".
"verification step.\n\nYou can review the document here:\n\n".
" %s\n",
$name,
PlatformSymbols::getPlatformServerName(),
$doc_name,
$link,
$doc_link);
id(new PhabricatorMetaMTAMail())
->addRawTos(array($email->getAddress()))
->setSubject(pht('[Legalpad] Signature Verification'))
->setForceDelivery(true)
->setBody($body)
->setRelatedPHID($signature->getDocumentPHID())
->saveAndSend();
}
private function signInResponse() {
return id(new Aphront403Response())
->setForbiddenText(
pht(
'The email address specified is associated with an account. '.
'Please login to that account and sign this document again.'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/storage/LegalpadDocumentBody.php | src/applications/legalpad/storage/LegalpadDocumentBody.php | <?php
final class LegalpadDocumentBody extends LegalpadDAO
implements
PhabricatorMarkupInterface {
const MARKUP_FIELD_TEXT = 'markup:text ';
protected $phid;
protected $creatorPHID;
protected $documentPHID;
protected $version;
protected $title;
protected $text;
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_COLUMN_SCHEMA => array(
'version' => 'uint32',
'title' => 'text255',
'text' => 'text?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_document' => array(
'columns' => array('documentPHID', 'version'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorPHIDConstants::PHID_TYPE_LEGB);
}
/* -( PhabricatorMarkupInterface )----------------------------------------- */
public function getMarkupFieldKey($field) {
$content = $this->getMarkupText($field);
return PhabricatorMarkupEngine::digestRemarkupContent($this, $content);
}
public function newMarkupEngine($field) {
return PhabricatorMarkupEngine::newMarkupEngine(array());
}
public function getMarkupText($field) {
switch ($field) {
case self::MARKUP_FIELD_TEXT:
$text = $this->getText();
break;
default:
throw new Exception(pht('Unknown field: %s', $field));
break;
}
return $text;
}
public function didMarkupText($field, $output, PhutilMarkupEngine $engine) {
require_celerity_resource('phabricator-remarkup-css');
return phutil_tag(
'div',
array(
'class' => 'phabricator-remarkup',
),
$output);
}
public function shouldUseMarkupCache($field) {
return (bool)$this->getID();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/storage/LegalpadDocumentSignature.php | src/applications/legalpad/storage/LegalpadDocumentSignature.php | <?php
final class LegalpadDocumentSignature
extends LegalpadDAO
implements PhabricatorPolicyInterface {
const VERIFIED = 0;
const UNVERIFIED = 1;
protected $documentPHID;
protected $documentVersion;
protected $signatureType;
protected $signerPHID;
protected $signerName;
protected $signerEmail;
protected $signatureData = array();
protected $verified;
protected $isExemption = 0;
protected $exemptionPHID;
protected $secretKey;
private $document = self::ATTACHABLE;
protected function getConfiguration() {
return array(
self::CONFIG_SERIALIZATION => array(
'signatureData' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'documentVersion' => 'uint32',
'signatureType' => 'text4',
'signerPHID' => 'phid?',
'signerName' => 'text255',
'signerEmail' => 'text255',
'secretKey' => 'bytes20',
'verified' => 'bool?',
'isExemption' => 'bool',
'exemptionPHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_signer' => array(
'columns' => array('signerPHID', 'dateModified'),
),
'secretKey' => array(
'columns' => array('secretKey'),
),
'key_document' => array(
'columns' => array('documentPHID', 'signerPHID', 'documentVersion'),
),
),
) + parent::getConfiguration();
}
public function save() {
if (!$this->getSecretKey()) {
$this->setSecretKey(Filesystem::readRandomCharacters(20));
}
return parent::save();
}
public function isVerified() {
return ($this->getVerified() != self::UNVERIFIED);
}
public function getDocument() {
return $this->assertAttached($this->document);
}
public function attachDocument(LegalpadDocument $document) {
$this->document = $document;
return $this;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return $this->getDocument()->getPolicy(
PhabricatorPolicyCapability::CAN_EDIT);
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return ($viewer->getPHID() == $this->getSignerPHID());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/storage/LegalpadTransactionComment.php | src/applications/legalpad/storage/LegalpadTransactionComment.php | <?php
final class LegalpadTransactionComment
extends PhabricatorApplicationTransactionComment {
protected $documentID;
protected $lineNumber = 0;
protected $lineLength = 0;
protected $fixedState;
protected $hasReplies = 0;
protected $replyToCommentPHID;
public function getApplicationTransactionObject() {
return new LegalpadTransaction();
}
public function shouldUseMarkupCache($field) {
// Only cache submitted comments.
return ($this->getTransactionPHID() != null);
}
protected function getConfiguration() {
$config = parent::getConfiguration();
$config[self::CONFIG_COLUMN_SCHEMA] = array(
'documentID' => 'id?',
'lineNumber' => 'uint32',
'lineLength' => 'uint32',
'fixedState' => 'text12?',
'hasReplies' => 'bool',
'replyToCommentPHID' => 'phid?',
) + $config[self::CONFIG_COLUMN_SCHEMA];
$config[self::CONFIG_KEY_SCHEMA] = array(
'key_draft' => array(
'columns' => array('authorPHID', 'documentID', 'transactionPHID'),
'unique' => true,
),
) + $config[self::CONFIG_KEY_SCHEMA];
return $config;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/storage/LegalpadDAO.php | src/applications/legalpad/storage/LegalpadDAO.php | <?php
abstract class LegalpadDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'legalpad';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/storage/LegalpadDocument.php | src/applications/legalpad/storage/LegalpadDocument.php | <?php
final class LegalpadDocument extends LegalpadDAO
implements
PhabricatorPolicyInterface,
PhabricatorSubscribableInterface,
PhabricatorApplicationTransactionInterface,
PhabricatorDestructibleInterface {
protected $title;
protected $contributorCount;
protected $recentContributorPHIDs = array();
protected $creatorPHID;
protected $versions;
protected $documentBodyPHID;
protected $viewPolicy;
protected $editPolicy;
protected $mailKey;
protected $signatureType;
protected $preamble;
protected $requireSignature;
const SIGNATURE_TYPE_NONE = 'none';
const SIGNATURE_TYPE_INDIVIDUAL = 'user';
const SIGNATURE_TYPE_CORPORATION = 'corp';
private $documentBody = self::ATTACHABLE;
private $contributors = self::ATTACHABLE;
private $signatures = self::ATTACHABLE;
private $userSignatures = array();
public static function initializeNewDocument(PhabricatorUser $actor) {
$app = id(new PhabricatorApplicationQuery())
->setViewer($actor)
->withClasses(array('PhabricatorLegalpadApplication'))
->executeOne();
$view_policy = $app->getPolicy(LegalpadDefaultViewCapability::CAPABILITY);
$edit_policy = $app->getPolicy(LegalpadDefaultEditCapability::CAPABILITY);
return id(new LegalpadDocument())
->setVersions(0)
->setCreatorPHID($actor->getPHID())
->setContributorCount(0)
->setRecentContributorPHIDs(array())
->attachSignatures(array())
->setSignatureType(self::SIGNATURE_TYPE_INDIVIDUAL)
->setPreamble('')
->setRequireSignature(0)
->setViewPolicy($view_policy)
->setEditPolicy($edit_policy);
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'recentContributorPHIDs' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'title' => 'text255',
'contributorCount' => 'uint32',
'versions' => 'uint32',
'mailKey' => 'bytes20',
'signatureType' => 'text4',
'preamble' => 'text',
'requireSignature' => 'bool',
),
self::CONFIG_KEY_SCHEMA => array(
'key_creator' => array(
'columns' => array('creatorPHID', 'dateModified'),
),
'key_required' => array(
'columns' => array('requireSignature', 'dateModified'),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhabricatorLegalpadDocumentPHIDType::TYPECONST);
}
public function getDocumentBody() {
return $this->assertAttached($this->documentBody);
}
public function attachDocumentBody(LegalpadDocumentBody $body) {
$this->documentBody = $body;
return $this;
}
public function getContributors() {
return $this->assertAttached($this->contributors);
}
public function attachContributors(array $contributors) {
$this->contributors = $contributors;
return $this;
}
public function getSignatures() {
return $this->assertAttached($this->signatures);
}
public function attachSignatures(array $signatures) {
$this->signatures = $signatures;
return $this;
}
public function save() {
if (!$this->getMailKey()) {
$this->setMailKey(Filesystem::readRandomCharacters(20));
}
return parent::save();
}
public function getMonogram() {
return 'L'.$this->getID();
}
public function getURI() {
return '/'.$this->getMonogram();
}
public function getUserSignature($phid) {
return $this->assertAttachedKey($this->userSignatures, $phid);
}
public function attachUserSignature(
$user_phid,
LegalpadDocumentSignature $signature = null) {
$this->userSignatures[$user_phid] = $signature;
return $this;
}
public static function getSignatureTypeMap() {
return array(
self::SIGNATURE_TYPE_INDIVIDUAL => pht('Individuals'),
self::SIGNATURE_TYPE_CORPORATION => pht('Corporations'),
self::SIGNATURE_TYPE_NONE => pht('No One'),
);
}
public function getSignatureTypeName() {
$type = $this->getSignatureType();
return idx(self::getSignatureTypeMap(), $type, $type);
}
public function getSignatureTypeIcon() {
$type = $this->getSignatureType();
$map = array(
self::SIGNATURE_TYPE_NONE => '',
self::SIGNATURE_TYPE_INDIVIDUAL => 'fa-user grey',
self::SIGNATURE_TYPE_CORPORATION => 'fa-building-o grey',
);
return idx($map, $type, 'fa-user grey');
}
/* -( PhabricatorSubscribableInterface )----------------------------------- */
public function isAutomaticallySubscribed($phid) {
return ($this->creatorPHID == $phid);
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
$policy = $this->viewPolicy;
break;
case PhabricatorPolicyCapability::CAN_EDIT:
$policy = $this->editPolicy;
break;
default:
$policy = PhabricatorPolicies::POLICY_NOONE;
break;
}
return $policy;
}
public function hasAutomaticCapability($capability, PhabricatorUser $user) {
return ($user->getPHID() == $this->getCreatorPHID());
}
public function describeAutomaticCapability($capability) {
return pht('The author of a document can always view and edit it.');
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new LegalpadDocumentEditor();
}
public function getApplicationTransactionTemplate() {
return new LegalpadTransaction();
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$this->openTransaction();
$this->delete();
$bodies = id(new LegalpadDocumentBody())->loadAllWhere(
'documentPHID = %s',
$this->getPHID());
foreach ($bodies as $body) {
$body->delete();
}
$signatures = id(new LegalpadDocumentSignature())->loadAllWhere(
'documentPHID = %s',
$this->getPHID());
foreach ($signatures as $signature) {
$signature->delete();
}
$this->saveTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/storage/LegalpadTransaction.php | src/applications/legalpad/storage/LegalpadTransaction.php | <?php
final class LegalpadTransaction extends PhabricatorModularTransaction {
public function getApplicationName() {
return 'legalpad';
}
public function getApplicationTransactionType() {
return PhabricatorLegalpadDocumentPHIDType::TYPECONST;
}
public function getApplicationTransactionCommentObject() {
return new LegalpadTransactionComment();
}
public function getBaseTransactionClass() {
return 'LegalpadDocumentTransactionType';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/storage/LegalpadSchemaSpec.php | src/applications/legalpad/storage/LegalpadSchemaSpec.php | <?php
final class LegalpadSchemaSpec
extends PhabricatorConfigSchemaSpec {
public function buildSchemata() {
$this->buildEdgeSchemata(new LegalpadDocument());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/query/LegalpadDocumentSignatureSearchEngine.php | src/applications/legalpad/query/LegalpadDocumentSignatureSearchEngine.php | <?php
final class LegalpadDocumentSignatureSearchEngine
extends PhabricatorApplicationSearchEngine {
private $document;
public function getResultTypeDescription() {
return pht('Legalpad Signatures');
}
public function getApplicationClassName() {
return 'PhabricatorLegalpadApplication';
}
public function setDocument(LegalpadDocument $document) {
$this->document = $document;
return $this;
}
public function buildSavedQueryFromRequest(AphrontRequest $request) {
$saved = new PhabricatorSavedQuery();
$saved->setParameter(
'signerPHIDs',
$this->readUsersFromRequest($request, 'signers'));
$saved->setParameter(
'documentPHIDs',
$this->readPHIDsFromRequest(
$request,
'documents',
array(
PhabricatorLegalpadDocumentPHIDType::TYPECONST,
)));
$saved->setParameter('nameContains', $request->getStr('nameContains'));
$saved->setParameter('emailContains', $request->getStr('emailContains'));
return $saved;
}
public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) {
$query = id(new LegalpadDocumentSignatureQuery());
$signer_phids = $saved->getParameter('signerPHIDs', array());
if ($signer_phids) {
$query->withSignerPHIDs($signer_phids);
}
if ($this->document) {
$query->withDocumentPHIDs(array($this->document->getPHID()));
} else {
$document_phids = $saved->getParameter('documentPHIDs', array());
if ($document_phids) {
$query->withDocumentPHIDs($document_phids);
}
}
$name_contains = $saved->getParameter('nameContains');
if (strlen($name_contains)) {
$query->withNameContains($name_contains);
}
$email_contains = $saved->getParameter('emailContains');
if (strlen($email_contains)) {
$query->withEmailContains($email_contains);
}
return $query;
}
public function buildSearchForm(
AphrontFormView $form,
PhabricatorSavedQuery $saved_query) {
$document_phids = $saved_query->getParameter('documentPHIDs', array());
$signer_phids = $saved_query->getParameter('signerPHIDs', array());
if (!$this->document) {
$form
->appendControl(
id(new AphrontFormTokenizerControl())
->setDatasource(new LegalpadDocumentDatasource())
->setName('documents')
->setLabel(pht('Documents'))
->setValue($document_phids));
}
$name_contains = $saved_query->getParameter('nameContains', '');
$email_contains = $saved_query->getParameter('emailContains', '');
$form
->appendControl(
id(new AphrontFormTokenizerControl())
->setDatasource(new PhabricatorPeopleDatasource())
->setName('signers')
->setLabel(pht('Signers'))
->setValue($signer_phids))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Name Contains'))
->setName('nameContains')
->setValue($name_contains))
->appendChild(
id(new AphrontFormTextControl())
->setLabel(pht('Email Contains'))
->setName('emailContains')
->setValue($email_contains));
}
protected function getURI($path) {
if ($this->document) {
return '/legalpad/signatures/'.$this->document->getID().'/'.$path;
} else {
return '/legalpad/signatures/'.$path;
}
}
protected function getBuiltinQueryNames() {
$names = array(
'all' => pht('All Signatures'),
);
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function getRequiredHandlePHIDsForResultList(
array $signatures,
PhabricatorSavedQuery $query) {
return array_merge(
mpull($signatures, 'getSignerPHID'),
mpull($signatures, 'getDocumentPHID'));
}
protected function renderResultList(
array $signatures,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($signatures, 'LegalpadDocumentSignature');
$viewer = $this->requireViewer();
Javelin::initBehavior('phabricator-tooltips');
$sig_good = $this->renderIcon(
'fa-check',
null,
pht('Verified, Current'));
$sig_corp = $this->renderIcon(
'fa-building-o',
null,
pht('Verified, Corporate'));
$sig_old = $this->renderIcon(
'fa-clock-o',
'orange',
pht('Signed Older Version'));
$sig_unverified = $this->renderIcon(
'fa-envelope',
'red',
pht('Unverified Email'));
$sig_exemption = $this->renderIcon(
'fa-asterisk',
'indigo',
pht('Exemption'));
id(new PHUIIconView())
->setIcon('fa-envelope', 'red')
->addSigil('has-tooltip')
->setMetadata(array('tip' => pht('Unverified Email')));
$type_corporate = LegalpadDocument::SIGNATURE_TYPE_CORPORATION;
$rows = array();
foreach ($signatures as $signature) {
$name = $signature->getSignerName();
$email = $signature->getSignerEmail();
$document = $signature->getDocument();
if ($signature->getIsExemption()) {
$sig_icon = $sig_exemption;
} else if (!$signature->isVerified()) {
$sig_icon = $sig_unverified;
} else if ($signature->getDocumentVersion() != $document->getVersions()) {
$sig_icon = $sig_old;
} else if ($signature->getSignatureType() == $type_corporate) {
$sig_icon = $sig_corp;
} else {
$sig_icon = $sig_good;
}
$signature_href = $this->getApplicationURI(
'signature/'.$signature->getID().'/');
$sig_icon = javelin_tag(
'a',
array(
'href' => $signature_href,
'sigil' => 'workflow',
),
$sig_icon);
$signer_phid = $signature->getSignerPHID();
$rows[] = array(
$sig_icon,
$handles[$document->getPHID()]->renderLink(),
$signer_phid
? $handles[$signer_phid]->renderLink()
: phutil_tag('em', array(), pht('None')),
$name,
phutil_tag(
'a',
array(
'href' => 'mailto:'.$email,
),
$email),
phabricator_datetime($signature->getDateCreated(), $viewer),
);
}
$table = id(new AphrontTableView($rows))
->setNoDataString(pht('No signatures match the query.'))
->setHeaders(
array(
'',
pht('Document'),
pht('Account'),
pht('Name'),
pht('Email'),
pht('Signed'),
))
->setColumnVisibility(
array(
true,
// Only show the "Document" column if we aren't scoped to a
// particular document.
!$this->document,
))
->setColumnClasses(
array(
'',
'',
'',
'',
'wide',
'right',
));
$button = null;
if ($this->document) {
$document_id = $this->document->getID();
$button = id(new PHUIButtonView())
->setText(pht('Add Exemption'))
->setTag('a')
->setHref($this->getApplicationURI('addsignature/'.$document_id.'/'))
->setWorkflow(true)
->setIcon('fa-pencil');
}
if (!$this->document) {
$table->setNotice(
pht('NOTE: You can only see your own signatures and signatures on '.
'documents you have permission to edit.'));
}
$result = new PhabricatorApplicationSearchResultView();
$result->setTable($table);
if ($button) {
$result->addAction($button);
}
return $result;
}
private function renderIcon($icon, $color, $title) {
Javelin::initBehavior('phabricator-tooltips');
return array(
id(new PHUIIconView())
->setIcon($icon, $color)
->addSigil('has-tooltip')
->setMetadata(array('tip' => $title)),
javelin_tag(
'span',
array(
'aural' => true,
),
$title),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/query/LegalpadDocumentSearchEngine.php | src/applications/legalpad/query/LegalpadDocumentSearchEngine.php | <?php
final class LegalpadDocumentSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Legalpad Documents');
}
public function getApplicationClassName() {
return 'PhabricatorLegalpadApplication';
}
public function newQuery() {
return id(new LegalpadDocumentQuery())
->needViewerSignatures(true);
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorUsersSearchField())
->setLabel(pht('Signed By'))
->setKey('signerPHIDs')
->setAliases(array('signer', 'signers', 'signerPHID'))
->setDescription(
pht('Search for documents signed by given users.')),
id(new PhabricatorUsersSearchField())
->setLabel(pht('Creators'))
->setKey('creatorPHIDs')
->setAliases(array('creator', 'creators', 'creatorPHID'))
->setDescription(
pht('Search for documents with given creators.')),
id(new PhabricatorUsersSearchField())
->setLabel(pht('Contributors'))
->setKey('contributorPHIDs')
->setAliases(array('contributor', 'contributors', 'contributorPHID'))
->setDescription(
pht('Search for documents with given contributors.')),
id(new PhabricatorSearchDateField())
->setLabel(pht('Created After'))
->setKey('createdStart'),
id(new PhabricatorSearchDateField())
->setLabel(pht('Created Before'))
->setKey('createdEnd'),
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['signerPHIDs']) {
$query->withSignerPHIDs($map['signerPHIDs']);
}
if ($map['contributorPHIDs']) {
$query->withContributorPHIDs($map['contributorPHIDs']);
}
if ($map['creatorPHIDs']) {
$query->withCreatorPHIDs($map['creatorPHIDs']);
}
if ($map['createdStart']) {
$query->withDateCreatedAfter($map['createdStart']);
}
if ($map['createdEnd']) {
$query->withDateCreatedAfter($map['createdStart']);
}
return $query;
}
protected function getURI($path) {
return '/legalpad/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array();
if ($this->requireViewer()->isLoggedIn()) {
$names['signed'] = pht('Signed Documents');
}
$names['all'] = pht('All Documents');
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
$viewer = $this->requireViewer();
switch ($query_key) {
case 'signed':
return $query->setParameter('signerPHIDs', array($viewer->getPHID()));
case 'all':
return $query;
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $documents,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($documents, 'LegalpadDocument');
$viewer = $this->requireViewer();
$list = new PHUIObjectItemListView();
$list->setUser($viewer);
foreach ($documents as $document) {
$last_updated = phabricator_date($document->getDateModified(), $viewer);
$title = $document->getTitle();
$item = id(new PHUIObjectItemView())
->setObjectName($document->getMonogram())
->setHeader($title)
->setHref('/'.$document->getMonogram())
->setObject($document);
$no_signatures = LegalpadDocument::SIGNATURE_TYPE_NONE;
if ($document->getSignatureType() == $no_signatures) {
$item->addIcon('none', pht('Not Signable'));
} else {
$type_name = $document->getSignatureTypeName();
$type_icon = $document->getSignatureTypeIcon();
$item->addIcon($type_icon, $type_name);
if ($viewer->getPHID()) {
$signature = $document->getUserSignature($viewer->getPHID());
} else {
$signature = null;
}
if ($signature) {
$item->addAttribute(
array(
id(new PHUIIconView())->setIcon('fa-check-square-o', 'green'),
' ',
pht(
'Signed on %s',
phabricator_date($signature->getDateCreated(), $viewer)),
));
} else {
$item->addAttribute(
array(
id(new PHUIIconView())->setIcon('fa-square-o', 'grey'),
' ',
pht('Not Signed'),
));
}
}
$item->addIcon(
'fa-pencil grey',
pht('Version %d (%s)', $document->getVersions(), $last_updated));
$list->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setObjectList($list);
$result->setNoDataString(pht('No documents found.'));
return $result;
}
protected function getNewUserBody() {
$create_button = id(new PHUIButtonView())
->setTag('a')
->setText(pht('Create a Document'))
->setHref('/legalpad/edit/')
->setColor(PHUIButtonView::GREEN);
$icon = $this->getApplication()->getIcon();
$app_name = $this->getApplication()->getName();
$view = id(new PHUIBigInfoView())
->setIcon($icon)
->setTitle(pht('Welcome to %s', $app_name))
->setDescription(
pht('Create documents and track signatures.'))
->addAction($create_button);
return $view;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/query/LegalpadDocumentQuery.php | src/applications/legalpad/query/LegalpadDocumentQuery.php | <?php
final class LegalpadDocumentQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $creatorPHIDs;
private $contributorPHIDs;
private $signerPHIDs;
private $dateCreatedAfter;
private $dateCreatedBefore;
private $signatureRequired;
private $needDocumentBodies;
private $needContributors;
private $needSignatures;
private $needViewerSignatures;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withCreatorPHIDs(array $phids) {
$this->creatorPHIDs = $phids;
return $this;
}
public function withContributorPHIDs(array $phids) {
$this->contributorPHIDs = $phids;
return $this;
}
public function withSignerPHIDs(array $phids) {
$this->signerPHIDs = $phids;
return $this;
}
public function withSignatureRequired($bool) {
$this->signatureRequired = $bool;
return $this;
}
public function needDocumentBodies($need_bodies) {
$this->needDocumentBodies = $need_bodies;
return $this;
}
public function needContributors($need_contributors) {
$this->needContributors = $need_contributors;
return $this;
}
public function needSignatures($need_signatures) {
$this->needSignatures = $need_signatures;
return $this;
}
public function withDateCreatedBefore($date_created_before) {
$this->dateCreatedBefore = $date_created_before;
return $this;
}
public function withDateCreatedAfter($date_created_after) {
$this->dateCreatedAfter = $date_created_after;
return $this;
}
public function needViewerSignatures($need) {
$this->needViewerSignatures = $need;
return $this;
}
public function newResultObject() {
return new LegalpadDocument();
}
protected function willFilterPage(array $documents) {
if ($this->needDocumentBodies) {
$documents = $this->loadDocumentBodies($documents);
}
if ($this->needContributors) {
$documents = $this->loadContributors($documents);
}
if ($this->needSignatures) {
$documents = $this->loadSignatures($documents);
}
if ($this->needViewerSignatures) {
if ($documents) {
if ($this->getViewer()->getPHID()) {
$signatures = id(new LegalpadDocumentSignatureQuery())
->setViewer($this->getViewer())
->withSignerPHIDs(array($this->getViewer()->getPHID()))
->withDocumentPHIDs(mpull($documents, 'getPHID'))
->execute();
$signatures = mpull($signatures, null, 'getDocumentPHID');
} else {
$signatures = array();
}
foreach ($documents as $document) {
$signature = idx($signatures, $document->getPHID());
$document->attachUserSignature(
$this->getViewer()->getPHID(),
$signature);
}
}
}
return $documents;
}
protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) {
$joins = parent::buildJoinClauseParts($conn);
if ($this->contributorPHIDs !== null) {
$joins[] = qsprintf(
$conn,
'JOIN edge contributor ON contributor.src = d.phid
AND contributor.type = %d',
PhabricatorObjectHasContributorEdgeType::EDGECONST);
}
if ($this->signerPHIDs !== null) {
$joins[] = qsprintf(
$conn,
'JOIN %T signer ON signer.documentPHID = d.phid
AND signer.signerPHID IN (%Ls)',
id(new LegalpadDocumentSignature())->getTableName(),
$this->signerPHIDs);
}
return $joins;
}
protected function shouldGroupQueryResultRows() {
if ($this->contributorPHIDs) {
return true;
}
if ($this->signerPHIDs) {
return true;
}
return parent::shouldGroupQueryResultRows();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'd.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'd.phid IN (%Ls)',
$this->phids);
}
if ($this->creatorPHIDs !== null) {
$where[] = qsprintf(
$conn,
'd.creatorPHID IN (%Ls)',
$this->creatorPHIDs);
}
if ($this->dateCreatedAfter !== null) {
$where[] = qsprintf(
$conn,
'd.dateCreated >= %d',
$this->dateCreatedAfter);
}
if ($this->dateCreatedBefore !== null) {
$where[] = qsprintf(
$conn,
'd.dateCreated <= %d',
$this->dateCreatedBefore);
}
if ($this->contributorPHIDs !== null) {
$where[] = qsprintf(
$conn,
'contributor.dst IN (%Ls)',
$this->contributorPHIDs);
}
if ($this->signatureRequired !== null) {
$where[] = qsprintf(
$conn,
'd.requireSignature = %d',
$this->signatureRequired);
}
return $where;
}
private function loadDocumentBodies(array $documents) {
$body_phids = mpull($documents, 'getDocumentBodyPHID');
$bodies = id(new LegalpadDocumentBody())->loadAllWhere(
'phid IN (%Ls)',
$body_phids);
$bodies = mpull($bodies, null, 'getPHID');
foreach ($documents as $document) {
$body = idx($bodies, $document->getDocumentBodyPHID());
$document->attachDocumentBody($body);
}
return $documents;
}
private function loadContributors(array $documents) {
$document_map = mpull($documents, null, 'getPHID');
$edge_type = PhabricatorObjectHasContributorEdgeType::EDGECONST;
$contributor_data = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(array_keys($document_map))
->withEdgeTypes(array($edge_type))
->execute();
foreach ($document_map as $document_phid => $document) {
$data = $contributor_data[$document_phid];
$contributors = array_keys(idx($data, $edge_type, array()));
$document->attachContributors($contributors);
}
return $documents;
}
private function loadSignatures(array $documents) {
$document_map = mpull($documents, null, 'getPHID');
$signatures = id(new LegalpadDocumentSignatureQuery())
->setViewer($this->getViewer())
->withDocumentPHIDs(array_keys($document_map))
->execute();
$signatures = mgroup($signatures, 'getDocumentPHID');
foreach ($documents as $document) {
$sigs = idx($signatures, $document->getPHID(), array());
$document->attachSignatures($sigs);
}
return $documents;
}
public function getQueryApplicationClass() {
return 'PhabricatorLegalpadApplication';
}
protected function getPrimaryTableAlias() {
return 'd';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/query/LegalpadTransactionQuery.php | src/applications/legalpad/query/LegalpadTransactionQuery.php | <?php
final class LegalpadTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new LegalpadTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/query/LegalpadDocumentSignatureQuery.php | src/applications/legalpad/query/LegalpadDocumentSignatureQuery.php | <?php
final class LegalpadDocumentSignatureQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $documentPHIDs;
private $signerPHIDs;
private $documentVersions;
private $secretKeys;
private $nameContains;
private $emailContains;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withDocumentPHIDs(array $phids) {
$this->documentPHIDs = $phids;
return $this;
}
public function withSignerPHIDs(array $phids) {
$this->signerPHIDs = $phids;
return $this;
}
public function withDocumentVersions(array $versions) {
$this->documentVersions = $versions;
return $this;
}
public function withSecretKeys(array $keys) {
$this->secretKeys = $keys;
return $this;
}
public function withNameContains($text) {
$this->nameContains = $text;
return $this;
}
public function withEmailContains($text) {
$this->emailContains = $text;
return $this;
}
protected function loadPage() {
$table = new LegalpadDocumentSignature();
$conn_r = $table->establishConnection('r');
$data = queryfx_all(
$conn_r,
'SELECT * FROM %T %Q %Q %Q',
$table->getTableName(),
$this->buildWhereClause($conn_r),
$this->buildOrderClause($conn_r),
$this->buildLimitClause($conn_r));
$signatures = $table->loadAllFromArray($data);
return $signatures;
}
protected function willFilterPage(array $signatures) {
$document_phids = mpull($signatures, 'getDocumentPHID');
$documents = id(new LegalpadDocumentQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($document_phids)
->execute();
$documents = mpull($documents, null, 'getPHID');
foreach ($signatures as $key => $signature) {
$document_phid = $signature->getDocumentPHID();
$document = idx($documents, $document_phid);
if ($document) {
$signature->attachDocument($document);
} else {
unset($signatures[$key]);
}
}
return $signatures;
}
protected function buildWhereClause(AphrontDatabaseConnection $conn) {
$where = array();
$where[] = $this->buildPagingClause($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->documentPHIDs !== null) {
$where[] = qsprintf(
$conn,
'documentPHID IN (%Ls)',
$this->documentPHIDs);
}
if ($this->signerPHIDs !== null) {
$where[] = qsprintf(
$conn,
'signerPHID IN (%Ls)',
$this->signerPHIDs);
}
if ($this->documentVersions !== null) {
$where[] = qsprintf(
$conn,
'documentVersion IN (%Ld)',
$this->documentVersions);
}
if ($this->secretKeys !== null) {
$where[] = qsprintf(
$conn,
'secretKey IN (%Ls)',
$this->secretKeys);
}
if ($this->nameContains !== null) {
$where[] = qsprintf(
$conn,
'signerName LIKE %~',
$this->nameContains);
}
if ($this->emailContains !== null) {
$where[] = qsprintf(
$conn,
'signerEmail LIKE %~',
$this->emailContains);
}
return $this->formatWhereClause($conn, $where);
}
public function getQueryApplicationClass() {
return 'PhabricatorLegalpadApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/mail/LegalpadMailReceiver.php | src/applications/legalpad/mail/LegalpadMailReceiver.php | <?php
final class LegalpadMailReceiver extends PhabricatorObjectMailReceiver {
public function isEnabled() {
return PhabricatorApplication::isClassInstalled(
'PhabricatorLegalpadApplication');
}
protected function getObjectPattern() {
return 'L[1-9]\d*';
}
protected function loadObject($pattern, PhabricatorUser $viewer) {
$id = (int)substr($pattern, 1);
return id(new LegalpadDocumentQuery())
->setViewer($viewer)
->withIDs(array($id))
->needDocumentBodies(true)
->executeOne();
}
protected function getTransactionReplyHandler() {
return new LegalpadReplyHandler();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/mail/LegalpadReplyHandler.php | src/applications/legalpad/mail/LegalpadReplyHandler.php | <?php
final class LegalpadReplyHandler
extends PhabricatorApplicationTransactionReplyHandler {
public function validateMailReceiver($mail_receiver) {
if (!($mail_receiver instanceof LegalpadDocument)) {
throw new Exception(pht('Mail receiver is not a LegalpadDocument!'));
}
}
public function getObjectPrefix() {
return 'L';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/editor/LegalpadDocumentEditEngine.php | src/applications/legalpad/editor/LegalpadDocumentEditEngine.php | <?php
final class LegalpadDocumentEditEngine
extends PhabricatorEditEngine {
const ENGINECONST = 'legalpad.document';
public function getEngineName() {
return pht('Legalpad');
}
public function getEngineApplicationClass() {
return 'PhabricatorLegalpadApplication';
}
public function getSummaryHeader() {
return pht('Configure Legalpad Forms');
}
public function getSummaryText() {
return pht('Configure creation and editing documents in Legalpad.');
}
public function isEngineConfigurable() {
return false;
}
protected function newEditableObject() {
$viewer = $this->getViewer();
$document = LegalpadDocument::initializeNewDocument($viewer);
$body = id(new LegalpadDocumentBody())
->setCreatorPHID($viewer->getPHID());
$document->attachDocumentBody($body);
$document->setDocumentBodyPHID(PhabricatorPHIDConstants::PHID_VOID);
return $document;
}
protected function newObjectQuery() {
return id(new LegalpadDocumentQuery())
->needDocumentBodies(true);
}
protected function getObjectCreateTitleText($object) {
return pht('Create New Document');
}
protected function getObjectEditTitleText($object) {
$body = $object->getDocumentBody();
$title = $body->getTitle();
return pht('Edit Document: %s', $title);
}
protected function getObjectEditShortText($object) {
$body = $object->getDocumentBody();
return $body->getTitle();
}
protected function getObjectCreateShortText() {
return pht('Create Document');
}
protected function getObjectName() {
return pht('Document');
}
protected function getObjectCreateCancelURI($object) {
return $this->getApplication()->getApplicationURI('/');
}
protected function getEditorURI() {
return $this->getApplication()->getApplicationURI('edit/');
}
protected function getObjectViewURI($object) {
$id = $object->getID();
return $this->getApplication()->getApplicationURI('view/'.$id.'/');
}
protected function getCreateNewObjectPolicy() {
return $this->getApplication()->getPolicy(
LegalpadCreateDocumentsCapability::CAPABILITY);
}
protected function buildCustomEditFields($object) {
$viewer = $this->getViewer();
$body = $object->getDocumentBody();
$document_body = $body->getText();
$is_create = $this->getIsCreate();
$is_admin = $viewer->getIsAdmin();
$fields = array();
$fields[] =
id(new PhabricatorTextEditField())
->setKey('title')
->setLabel(pht('Title'))
->setDescription(pht('Document Title.'))
->setConduitTypeDescription(pht('New document title.'))
->setValue($object->getTitle())
->setIsRequired(true)
->setTransactionType(
LegalpadDocumentTitleTransaction::TRANSACTIONTYPE);
if ($is_create) {
$fields[] =
id(new PhabricatorSelectEditField())
->setKey('signatureType')
->setLabel(pht('Who Should Sign?'))
->setDescription(pht('Type of signature required'))
->setConduitTypeDescription(pht('New document signature type.'))
->setValue($object->getSignatureType())
->setOptions(LegalpadDocument::getSignatureTypeMap())
->setTransactionType(
LegalpadDocumentSignatureTypeTransaction::TRANSACTIONTYPE);
$show_require = true;
} else {
$fields[] = id(new PhabricatorStaticEditField())
->setLabel(pht('Who Should Sign?'))
->setValue($object->getSignatureTypeName());
$individual = LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL;
$show_require = $object->getSignatureType() == $individual;
}
if ($show_require && $is_admin) {
$fields[] =
id(new PhabricatorBoolEditField())
->setKey('requireSignature')
->setOptions(
pht('No Signature Required'),
pht('Signature Required to Log In'))
->setAsCheckbox(true)
->setTransactionType(
LegalpadDocumentRequireSignatureTransaction::TRANSACTIONTYPE)
->setDescription(pht('Marks this document as required signing.'))
->setConduitDescription(
pht('Marks this document as required signing.'))
->setValue($object->getRequireSignature());
}
$fields[] =
id(new PhabricatorRemarkupEditField())
->setKey('preamble')
->setLabel(pht('Preamble'))
->setDescription(pht('The preamble of the document.'))
->setConduitTypeDescription(pht('New document preamble.'))
->setValue($object->getPreamble())
->setTransactionType(
LegalpadDocumentPreambleTransaction::TRANSACTIONTYPE);
$fields[] =
id(new PhabricatorRemarkupEditField())
->setKey('text')
->setLabel(pht('Document Body'))
->setDescription(pht('The body of text of the document.'))
->setConduitTypeDescription(pht('New document body.'))
->setValue($document_body)
->setIsRequired(true)
->setTransactionType(
LegalpadDocumentTextTransaction::TRANSACTIONTYPE);
return $fields;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/editor/LegalpadDocumentEditor.php | src/applications/legalpad/editor/LegalpadDocumentEditor.php | <?php
final class LegalpadDocumentEditor
extends PhabricatorApplicationTransactionEditor {
public function getEditorApplicationClass() {
return 'PhabricatorLegalpadApplication';
}
public function getEditorObjectsDescription() {
return pht('Legalpad Documents');
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorTransactions::TYPE_COMMENT;
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
$types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;
return $types;
}
public function getCreateObjectTitle($author, $object) {
return pht('%s created this document.', $author);
}
public function getCreateObjectTitleForFeed($author, $object) {
return pht('%s created %s.', $author, $object);
}
protected function applyFinalEffects(
PhabricatorLiskDAO $object,
array $xactions) {
$is_contribution = false;
foreach ($xactions as $xaction) {
switch ($xaction->getTransactionType()) {
case LegalpadDocumentTitleTransaction::TRANSACTIONTYPE:
case LegalpadDocumentTextTransaction::TRANSACTIONTYPE:
$is_contribution = true;
break;
}
}
if ($is_contribution) {
$text = $object->getDocumentBody()->getText();
$title = $object->getDocumentBody()->getTitle();
$object->setVersions($object->getVersions() + 1);
$body = new LegalpadDocumentBody();
$body->setCreatorPHID($this->getActingAsPHID());
$body->setText($text);
$body->setTitle($title);
$body->setVersion($object->getVersions());
$body->setDocumentPHID($object->getPHID());
$body->save();
$object->setDocumentBodyPHID($body->getPHID());
$type = PhabricatorContributedToObjectEdgeType::EDGECONST;
id(new PhabricatorEdgeEditor())
->addEdge($this->getActingAsPHID(), $type, $object->getPHID())
->save();
$type = PhabricatorObjectHasContributorEdgeType::EDGECONST;
$contributors = PhabricatorEdgeQuery::loadDestinationPHIDs(
$object->getPHID(),
$type);
$object->setRecentContributorPHIDs(array_slice($contributors, 0, 3));
$object->setContributorCount(count($contributors));
$object->save();
}
return $xactions;
}
protected function validateAllTransactions(PhabricatorLiskDAO $object,
array $xactions) {
$errors = array();
$is_required = (bool)$object->getRequireSignature();
$document_type = $object->getSignatureType();
$individual = LegalpadDocument::SIGNATURE_TYPE_INDIVIDUAL;
foreach ($xactions as $xaction) {
switch ($xaction->getTransactionType()) {
case LegalpadDocumentRequireSignatureTransaction::TRANSACTIONTYPE:
$is_required = (bool)$xaction->getNewValue();
break;
case LegalpadDocumentSignatureTypeTransaction::TRANSACTIONTYPE:
$document_type = $xaction->getNewValue();
break;
}
}
if ($is_required && ($document_type != $individual)) {
$errors[] = new PhabricatorApplicationTransactionValidationError(
LegalpadDocumentRequireSignatureTransaction::TRANSACTIONTYPE,
pht('Invalid'),
pht('Only documents with signature type "individual" may '.
'require signing to log in.'),
null);
}
return $errors;
}
/* -( Sending Mail )------------------------------------------------------- */
protected function shouldSendMail(
PhabricatorLiskDAO $object,
array $xactions) {
return true;
}
protected function buildReplyHandler(PhabricatorLiskDAO $object) {
return id(new LegalpadReplyHandler())
->setMailReceiver($object);
}
protected function buildMailTemplate(PhabricatorLiskDAO $object) {
$id = $object->getID();
$title = $object->getDocumentBody()->getTitle();
return id(new PhabricatorMetaMTAMail())
->setSubject("L{$id}: {$title}");
}
protected function getMailTo(PhabricatorLiskDAO $object) {
return array(
$object->getCreatorPHID(),
$this->requireActor()->getPHID(),
);
}
protected function shouldImplyCC(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case LegalpadDocumentTextTransaction::TRANSACTIONTYPE:
case LegalpadDocumentTitleTransaction::TRANSACTIONTYPE:
case LegalpadDocumentPreambleTransaction::TRANSACTIONTYPE:
case LegalpadDocumentRequireSignatureTransaction::TRANSACTIONTYPE:
return true;
}
return parent::shouldImplyCC($object, $xaction);
}
protected function buildMailBody(
PhabricatorLiskDAO $object,
array $xactions) {
$body = parent::buildMailBody($object, $xactions);
$body->addLinkSection(
pht('DOCUMENT DETAIL'),
PhabricatorEnv::getProductionURI('/legalpad/view/'.$object->getID().'/'));
return $body;
}
protected function getMailSubjectPrefix() {
return pht('[Legalpad]');
}
protected function shouldPublishFeedStory(
PhabricatorLiskDAO $object,
array $xactions) {
return false;
}
protected function supportsSearch() {
return false;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/xaction/LegalpadDocumentSignatureTypeTransaction.php | src/applications/legalpad/xaction/LegalpadDocumentSignatureTypeTransaction.php | <?php
final class LegalpadDocumentSignatureTypeTransaction
extends LegalpadDocumentTransactionType {
const TRANSACTIONTYPE = 'legalpad:signature-type';
public function generateOldValue($object) {
return $object->getSignatureType();
}
public function applyInternalEffects($object, $value) {
$object->setSignatureType($value);
}
public function getTitle() {
return pht(
'%s updated the document signature type.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s updated the document signature type for %s.',
$this->renderAuthor(),
$this->renderObject());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/xaction/LegalpadDocumentTransactionType.php | src/applications/legalpad/xaction/LegalpadDocumentTransactionType.php | <?php
abstract class LegalpadDocumentTransactionType
extends PhabricatorModularTransactionType {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/xaction/LegalpadDocumentPreambleTransaction.php | src/applications/legalpad/xaction/LegalpadDocumentPreambleTransaction.php | <?php
final class LegalpadDocumentPreambleTransaction
extends LegalpadDocumentTransactionType {
// TODO: This is misspelled! See T13005.
const TRANSACTIONTYPE = 'legalpad:premable';
public function generateOldValue($object) {
return $object->getPreamble();
}
public function applyInternalEffects($object, $value) {
$object->setPreamble($value);
}
public function getTitle() {
return pht(
'%s updated the document preamble.',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s updated the document preamble for %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function hasChangeDetailView() {
return true;
}
public function getMailDiffSectionHeader() {
return pht('CHANGES TO DOCUMENT PREAMBLE');
}
public function newChangeDetailView() {
$viewer = $this->getViewer();
return id(new PhabricatorApplicationTransactionTextDiffDetailView())
->setViewer($viewer)
->setOldText($this->getOldValue())
->setNewText($this->getNewValue());
}
public function newRemarkupChanges() {
$changes = array();
$changes[] = $this->newRemarkupChange()
->setOldValue($this->getOldValue())
->setNewValue($this->getNewValue());
return $changes;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/xaction/LegalpadDocumentTextTransaction.php | src/applications/legalpad/xaction/LegalpadDocumentTextTransaction.php | <?php
final class LegalpadDocumentTextTransaction
extends LegalpadDocumentTransactionType {
const TRANSACTIONTYPE = 'text';
public function generateOldValue($object) {
$body = $object->getDocumentBody();
return $body->getText();
}
public function applyInternalEffects($object, $value) {
$body = $object->getDocumentBody();
$body->setText($value);
$object->attachDocumentBody($body);
}
public function getTitle() {
$old = $this->getOldValue();
if (!strlen($old)) {
return pht(
'%s set the document text.',
$this->renderAuthor());
} else {
return pht(
'%s updated the document text.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
return pht(
'%s updated the document text for %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function hasChangeDetailView() {
return true;
}
public function getMailDiffSectionHeader() {
return pht('CHANGES TO DOCUMENT TEXT');
}
public function newChangeDetailView() {
$viewer = $this->getViewer();
return id(new PhabricatorApplicationTransactionTextDiffDetailView())
->setViewer($viewer)
->setOldText($this->getOldValue())
->setNewText($this->getNewValue());
}
public function newRemarkupChanges() {
$changes = array();
$changes[] = $this->newRemarkupChange()
->setOldValue($this->getOldValue())
->setNewValue($this->getNewValue());
return $changes;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/xaction/LegalpadDocumentTitleTransaction.php | src/applications/legalpad/xaction/LegalpadDocumentTitleTransaction.php | <?php
final class LegalpadDocumentTitleTransaction
extends LegalpadDocumentTransactionType {
const TRANSACTIONTYPE = 'title';
public function generateOldValue($object) {
return $object->getTitle();
}
public function applyInternalEffects($object, $value) {
$object->setTitle($value);
$body = $object->getDocumentBody();
$body->setTitle($value);
$object->attachDocumentBody($body);
}
public function getTitle() {
$old = $this->getOldValue();
if (!strlen($old)) {
return pht(
'%s created this document.',
$this->renderAuthor());
} else {
return pht(
'%s renamed this document from %s to %s.',
$this->renderAuthor(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
public function getTitleForFeed() {
$old = $this->getOldValue();
if (!strlen($old)) {
return pht(
'%s created %s.',
$this->renderAuthor(),
$this->renderObject());
} else {
return pht(
'%s renamed %s from %s to %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderOldValue(),
$this->renderNewValue());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
if ($this->isEmptyTextTransaction($object->getTitle(), $xactions)) {
$errors[] = $this->newRequiredError(
pht('Documents must have a title.'));
}
$max_length = $object->getColumnMaximumByteLength('title');
foreach ($xactions as $xaction) {
$new_value = $xaction->getNewValue();
$new_length = strlen($new_value);
if ($new_length > $max_length) {
$errors[] = $this->newInvalidError(
pht('The title can be no longer than %s characters.',
new PhutilNumber($max_length)));
}
}
return $errors;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/xaction/LegalpadDocumentRequireSignatureTransaction.php | src/applications/legalpad/xaction/LegalpadDocumentRequireSignatureTransaction.php | <?php
final class LegalpadDocumentRequireSignatureTransaction
extends LegalpadDocumentTransactionType {
const TRANSACTIONTYPE = 'legalpad:require-signature';
public function generateOldValue($object) {
return (int)$object->getRequireSignature();
}
public function applyInternalEffects($object, $value) {
$object->setRequireSignature((int)$value);
}
public function applyExternalEffects($object, $value) {
if ($value) {
$session = new PhabricatorAuthSession();
queryfx(
$session->establishConnection('w'),
'UPDATE %T SET signedLegalpadDocuments = 0',
$session->getTableName());
}
}
public function getTitle() {
$new = $this->getNewValue();
if ($new) {
return pht(
'%s set the document to require signatures.',
$this->renderAuthor());
} else {
return pht(
'%s set the document to not require signatures.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
$new = $this->getNewValue();
if ($new) {
return pht(
'%s set the document %s to require signatures.',
$this->renderAuthor(),
$this->renderObject());
} else {
return pht(
'%s set the document %s to not require signatures.',
$this->renderAuthor(),
$this->renderObject());
}
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$old = (bool)$object->getRequireSignature();
foreach ($xactions as $xaction) {
$new = (bool)$xaction->getNewValue();
if ($old === $new) {
continue;
}
$is_admin = $this->getActor()->getIsAdmin();
if (!$is_admin) {
$errors[] = $this->newInvalidError(
pht(
'Only administrators may change whether a document '.
'requires a signature.'),
$xaction);
}
}
return $errors;
}
public function getIcon() {
return 'fa-pencil-square';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/application/PhabricatorLegalpadApplication.php | src/applications/legalpad/application/PhabricatorLegalpadApplication.php | <?php
final class PhabricatorLegalpadApplication extends PhabricatorApplication {
public function getBaseURI() {
return '/legalpad/';
}
public function getName() {
return pht('Legalpad');
}
public function getShortDescription() {
return pht('Agreements and Signatures');
}
public function getIcon() {
return 'fa-gavel';
}
public function getTitleGlyph() {
return "\xC2\xA9";
}
public function getApplicationGroup() {
return self::GROUP_UTILITIES;
}
public function getRemarkupRules() {
return array(
new LegalpadDocumentRemarkupRule(),
);
}
public function getHelpDocumentationArticles(PhabricatorUser $viewer) {
return array(
array(
'name' => pht('Legalpad User Guide'),
'href' => PhabricatorEnv::getDoclink('Legalpad User Guide'),
),
);
}
public function getOverview() {
return pht(
'**Legalpad** is a simple application for tracking signatures and '.
'legal agreements. At the moment, it is primarily intended to help '.
'open source projects keep track of Contributor License Agreements.');
}
public function getRoutes() {
return array(
'/L(?P<id>\d+)' => 'LegalpadDocumentSignController',
'/legalpad/' => array(
'' => 'LegalpadDocumentListController',
'(?:query/(?P<queryKey>[^/]+)/)?'
=> 'LegalpadDocumentListController',
$this->getEditRoutePattern('edit/')
=> 'LegalpadDocumentEditController',
'view/(?P<id>\d+)/' => 'LegalpadDocumentManageController',
'done/' => 'LegalpadDocumentDoneController',
'verify/(?P<code>[^/]+)/'
=> 'LegalpadDocumentSignatureVerificationController',
'signatures/(?:(?P<id>\d+)/)?(?:query/(?P<queryKey>[^/]+)/)?'
=> 'LegalpadDocumentSignatureListController',
'addsignature/(?P<id>\d+)/' => 'LegalpadDocumentSignatureAddController',
'signature/(?P<id>\d+)/' => 'LegalpadDocumentSignatureViewController',
'document/' => array(
'preview/' => 'PhabricatorMarkupPreviewController',
),
),
);
}
protected function getCustomCapabilities() {
return array(
LegalpadCreateDocumentsCapability::CAPABILITY => array(),
LegalpadDefaultViewCapability::CAPABILITY => array(
'template' => PhabricatorLegalpadDocumentPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_VIEW,
),
LegalpadDefaultEditCapability::CAPABILITY => array(
'template' => PhabricatorLegalpadDocumentPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_EDIT,
),
);
}
public function getMailCommandObjects() {
return array(
'document' => array(
'name' => pht('Email Commands: Legalpad Documents'),
'header' => pht('Interacting with Legalpad Documents'),
'object' => new LegalpadDocument(),
'summary' => pht(
'This page documents the commands you can use to interact with '.
'documents in Legalpad.'),
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/policyrule/PhabricatorLegalpadSignaturePolicyRule.php | src/applications/legalpad/policyrule/PhabricatorLegalpadSignaturePolicyRule.php | <?php
final class PhabricatorLegalpadSignaturePolicyRule
extends PhabricatorPolicyRule {
private $signatures = array();
public function getRuleDescription() {
return pht('signers of legalpad documents');
}
public function willApplyRules(
PhabricatorUser $viewer,
array $values,
array $objects) {
$values = array_unique(array_filter(array_mergev($values)));
if (!$values) {
return;
}
// TODO: This accepts signature of any version of the document, even an
// older version.
$documents = id(new LegalpadDocumentQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withPHIDs($values)
->withSignerPHIDs(array($viewer->getPHID()))
->execute();
$this->signatures = mpull($documents, 'getPHID', 'getPHID');
}
public function applyRule(
PhabricatorUser $viewer,
$value,
PhabricatorPolicyInterface $object) {
foreach ($value as $document_phid) {
if (!isset($this->signatures[$document_phid])) {
return false;
}
}
return true;
}
public function getValueControlType() {
return self::CONTROL_TYPE_TOKENIZER;
}
public function getValueControlTemplate() {
return $this->getDatasourceTemplate(new LegalpadDocumentDatasource());
}
public function getRuleOrder() {
return 900;
}
public function getValueForStorage($value) {
PhutilTypeSpec::newFromString('list<string>')->check($value);
return array_values($value);
}
public function getValueForDisplay(PhabricatorUser $viewer, $value) {
$handles = id(new PhabricatorHandleQuery())
->setViewer($viewer)
->withPHIDs($value)
->execute();
return mpull($handles, 'getFullName', 'getPHID');
}
public function ruleHasEffect($value) {
return (bool)$value;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/edge/LegalpadSignatureNeededByObjectEdgeType.php | src/applications/legalpad/edge/LegalpadSignatureNeededByObjectEdgeType.php | <?php
final class LegalpadSignatureNeededByObjectEdgeType
extends PhabricatorEdgeType {
const EDGECONST = 50;
public function getInverseEdgeConstant() {
return LegalpadObjectNeedsSignatureEdgeType::EDGECONST;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/edge/LegalpadObjectNeedsSignatureEdgeType.php | src/applications/legalpad/edge/LegalpadObjectNeedsSignatureEdgeType.php | <?php
final class LegalpadObjectNeedsSignatureEdgeType extends PhabricatorEdgeType {
const EDGECONST = 49;
public function getInverseEdgeConstant() {
return LegalpadSignatureNeededByObjectEdgeType::EDGECONST;
}
public function getTransactionAddString(
$actor,
$add_count,
$add_edges) {
return pht(
'%s added %s required legal document(s): %s.',
$actor,
$add_count,
$add_edges);
}
public function getTransactionRemoveString(
$actor,
$rem_count,
$rem_edges) {
return pht(
'%s removed %s required legal document(s): %s.',
$actor,
$rem_count,
$rem_edges);
}
public function getTransactionEditString(
$actor,
$total_count,
$add_count,
$add_edges,
$rem_count,
$rem_edges) {
return pht(
'%s edited %s required legal document(s), added %s: %s; removed %s: %s.',
$actor,
$total_count,
$add_count,
$add_edges,
$rem_count,
$rem_edges);
}
public function getFeedAddString(
$actor,
$object,
$add_count,
$add_edges) {
return pht(
'%s added %s required legal document(s) to %s: %s.',
$actor,
$add_count,
$object,
$add_edges);
}
public function getFeedRemoveString(
$actor,
$object,
$rem_count,
$rem_edges) {
return pht(
'%s removed %s required legal document(s) from %s: %s.',
$actor,
$rem_count,
$object,
$rem_edges);
}
public function getFeedEditString(
$actor,
$object,
$total_count,
$add_count,
$add_edges,
$rem_count,
$rem_edges) {
return pht(
'%s edited %s required legal document(s) for %s, '.
'added %s: %s; removed %s: %s.',
$actor,
$total_count,
$object,
$add_count,
$add_edges,
$rem_count,
$rem_edges);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/phid/PhabricatorLegalpadDocumentPHIDType.php | src/applications/legalpad/phid/PhabricatorLegalpadDocumentPHIDType.php | <?php
final class PhabricatorLegalpadDocumentPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'LEGD';
public function getTypeName() {
return pht('Legalpad Document');
}
public function getTypeIcon() {
return 'fa-file-text-o';
}
public function newObject() {
return new LegalpadDocument();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorLegalpadApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new LegalpadDocumentQuery())
->withPHIDs($phids)
->needDocumentBodies(true);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$document = $objects[$phid];
$name = $document->getDocumentBody()->getTitle();
$handle->setName($document->getMonogram().' '.$name);
$handle->setURI('/'.$document->getMonogram());
}
}
public function canLoadNamedObject($name) {
return preg_match('/^L\d*[1-9]\d*$/i', $name);
}
public function loadNamedObjects(
PhabricatorObjectQuery $query,
array $names) {
$id_map = array();
foreach ($names as $name) {
$id = (int)substr($name, 1);
$id_map[$id][] = $name;
}
$objects = id(new LegalpadDocumentQuery())
->setViewer($query->getViewer())
->withIDs(array_keys($id_map))
->execute();
$results = array();
foreach ($objects as $id => $object) {
foreach (idx($id_map, $id, array()) as $name) {
$results[$name] = $object;
}
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/herald/LegalpadRequireSignatureHeraldAction.php | src/applications/legalpad/herald/LegalpadRequireSignatureHeraldAction.php | <?php
final class LegalpadRequireSignatureHeraldAction
extends HeraldAction {
const DO_SIGNED = 'do.signed';
const DO_REQUIRED = 'do.required';
const ACTIONCONST = 'legalpad.require';
public function getActionGroupKey() {
return HeraldSupportActionGroup::ACTIONGROUPKEY;
}
public function supportsObject($object) {
// TODO: This could probably be more general. Note that we call
// getAuthorPHID() on the object explicitly below, and this also needs to
// be generalized.
return ($object instanceof DifferentialRevision);
}
protected function applyRequire(array $phids) {
$adapter = $this->getAdapter();
$edgetype_legal = LegalpadObjectNeedsSignatureEdgeType::EDGECONST;
$current = $adapter->loadEdgePHIDs($edgetype_legal);
$allowed_types = array(
PhabricatorLegalpadDocumentPHIDType::TYPECONST,
);
$targets = $this->loadStandardTargets($phids, $allowed_types, $current);
if (!$targets) {
return;
}
$phids = array_fuse(array_keys($targets));
$object = $adapter->getObject();
$author_phid = $object->getAuthorPHID();
$signatures = id(new LegalpadDocumentSignatureQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withDocumentPHIDs($phids)
->withSignerPHIDs(array($author_phid))
->execute();
$signatures = mpull($signatures, null, 'getDocumentPHID');
$signed = array();
foreach ($phids as $phid) {
if (isset($signatures[$phid])) {
$signed[] = $phid;
unset($phids[$phid]);
}
}
if ($signed) {
$this->logEffect(self::DO_SIGNED, $phids);
}
if (!$phids) {
return;
}
$xaction = $adapter->newTransaction()
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue('edge:type', $edgetype_legal)
->setNewValue(
array(
'+' => $phids,
));
$adapter->queueTransaction($xaction);
$this->logEffect(self::DO_REQUIRED, $phids);
}
protected function getActionEffectMap() {
return array(
self::DO_SIGNED => array(
'icon' => 'fa-terminal',
'color' => 'green',
'name' => pht('Already Signed'),
),
self::DO_REQUIRED => array(
'icon' => 'fa-terminal',
'color' => 'green',
'name' => pht('Required Signature'),
),
);
}
protected function renderActionEffectDescription($type, $data) {
switch ($type) {
case self::DO_SIGNED:
return pht(
'%s document(s) are already signed: %s.',
phutil_count($data),
$this->renderHandleList($data));
case self::DO_REQUIRED:
return pht(
'Required %s signature(s): %s.',
phutil_count($data),
$this->renderHandleList($data));
}
}
public function getHeraldActionName() {
return pht('Require signatures');
}
public function supportsRuleType($rule_type) {
return ($rule_type != HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
}
public function applyEffect($object, HeraldEffect $effect) {
return $this->applyRequire($effect->getTarget());
}
public function getHeraldActionStandardType() {
return self::STANDARD_PHID_LIST;
}
protected function getDatasource() {
return new LegalpadDocumentDatasource();
}
public function renderActionDescription($value) {
return pht(
'Require document signatures: %s.',
$this->renderHandleList($value));
}
public function isActionAvailable() {
return id(new PhabricatorLegalpadApplication())->isInstalled();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/typeahead/LegalpadDocumentDatasource.php | src/applications/legalpad/typeahead/LegalpadDocumentDatasource.php | <?php
final class LegalpadDocumentDatasource extends PhabricatorTypeaheadDatasource {
public function isBrowsable() {
// TODO: This should be made browsable.
return false;
}
public function getBrowseTitle() {
return pht('Browse Documents');
}
public function getPlaceholderText() {
return pht('Type a document name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorLegalpadApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$results = array();
$documents = id(new LegalpadDocumentQuery())
->setViewer($viewer)
->execute();
foreach ($documents as $document) {
$results[] = id(new PhabricatorTypeaheadResult())
->setPHID($document->getPHID())
->setName($document->getMonogram().' '.$document->getTitle());
}
return $results;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/capability/LegalpadDefaultEditCapability.php | src/applications/legalpad/capability/LegalpadDefaultEditCapability.php | <?php
final class LegalpadDefaultEditCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'legalpad.default.edit';
public function getCapabilityName() {
return pht('Default Edit Policy');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/capability/LegalpadDefaultViewCapability.php | src/applications/legalpad/capability/LegalpadDefaultViewCapability.php | <?php
final class LegalpadDefaultViewCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'legalpad.default.view';
public function getCapabilityName() {
return pht('Default View Policy');
}
public function shouldAllowPublicPolicySetting() {
return true;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/capability/LegalpadCreateDocumentsCapability.php | src/applications/legalpad/capability/LegalpadCreateDocumentsCapability.php | <?php
final class LegalpadCreateDocumentsCapability
extends PhabricatorPolicyCapability {
const CAPABILITY = 'legalpad.create';
public function getCapabilityName() {
return pht('Can Create Documents');
}
public function describeCapabilityRejection() {
return pht('You do not have permission to create new documents.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/legalpad/remarkup/LegalpadDocumentRemarkupRule.php | src/applications/legalpad/remarkup/LegalpadDocumentRemarkupRule.php | <?php
final class LegalpadDocumentRemarkupRule extends PhabricatorObjectRemarkupRule {
protected function getObjectNamePrefix() {
return 'L';
}
protected function loadObjects(array $ids) {
$viewer = $this->getEngine()->getConfig('viewer');
return id(new LegalpadDocumentQuery())
->setViewer($viewer)
->withIDs($ids)
->execute();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacServiceController.php | src/applications/almanac/controller/AlmanacServiceController.php | <?php
abstract class AlmanacServiceController extends AlmanacController {
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$list_uri = $this->getApplicationURI('service/');
$crumbs->addTextCrumb(pht('Services'), $list_uri);
return $crumbs;
}
public function buildApplicationMenu() {
return $this->newApplicationMenu()
->setSearchEngine(new AlmanacServiceSearchEngine());
}
protected function getPropertyDeleteURI($object) {
$id = $object->getID();
return "/almanac/service/delete/{$id}/";
}
protected function getPropertyUpdateURI($object) {
$id = $object->getID();
return "/almanac/service/property/{$id}/";
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacNetworkController.php | src/applications/almanac/controller/AlmanacNetworkController.php | <?php
abstract class AlmanacNetworkController extends AlmanacController {
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$list_uri = $this->getApplicationURI('network/');
$crumbs->addTextCrumb(pht('Networks'), $list_uri);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacDeviceListController.php | src/applications/almanac/controller/AlmanacDeviceListController.php | <?php
final class AlmanacDeviceListController
extends AlmanacDeviceController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new AlmanacDeviceSearchEngine())
->setController($this)
->buildResponse();
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
id(new AlmanacDeviceEditEngine())
->setViewer($this->getViewer())
->addActionToCrumbs($crumbs);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacPropertyController.php | src/applications/almanac/controller/AlmanacPropertyController.php | <?php
abstract class AlmanacPropertyController extends AlmanacController {
private $propertyObject;
public function getPropertyObject() {
return $this->propertyObject;
}
protected function loadPropertyObject() {
$viewer = $this->getViewer();
$request = $this->getRequest();
$object_phid = $request->getStr('objectPHID');
switch (phid_get_type($object_phid)) {
case AlmanacBindingPHIDType::TYPECONST:
$query = new AlmanacBindingQuery();
break;
case AlmanacDevicePHIDType::TYPECONST:
$query = new AlmanacDeviceQuery();
break;
case AlmanacServicePHIDType::TYPECONST:
$query = new AlmanacServiceQuery();
break;
default:
return new Aphront404Response();
}
$object = $query
->setViewer($viewer)
->withPHIDs(array($object_phid))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->needProperties(true)
->executeOne();
if (!$object) {
return new Aphront404Response();
}
if (!($object instanceof AlmanacPropertyInterface)) {
return new Aphront404Response();
}
$this->propertyObject = $object;
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacNamespaceViewController.php | src/applications/almanac/controller/AlmanacNamespaceViewController.php | <?php
final class AlmanacNamespaceViewController
extends AlmanacNamespaceController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$namespace = id(new AlmanacNamespaceQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$namespace) {
return new Aphront404Response();
}
$title = pht('Namespace %s', $namespace->getName());
$curtain = $this->buildCurtain($namespace);
$header = id(new PHUIHeaderView())
->setUser($viewer)
->setHeader($namespace->getName())
->setPolicyObject($namespace)
->setHeaderIcon('fa-asterisk');
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($namespace->getName());
$crumbs->setBorder(true);
$timeline = $this->buildTransactionTimeline(
$namespace,
new AlmanacNamespaceTransactionQuery());
$timeline->setShouldTerminate(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$timeline,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild(
array(
$view,
));
}
private function buildCurtain(AlmanacNamespace $namespace) {
$viewer = $this->getViewer();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$namespace,
PhabricatorPolicyCapability::CAN_EDIT);
$id = $namespace->getID();
$edit_uri = $this->getApplicationURI("namespace/edit/{$id}/");
$curtain = $this->newCurtainView($namespace);
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-pencil')
->setName(pht('Edit Namespace'))
->setHref($edit_uri)
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit));
return $curtain;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacDeviceViewController.php | src/applications/almanac/controller/AlmanacDeviceViewController.php | <?php
final class AlmanacDeviceViewController
extends AlmanacDeviceController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$name = $request->getURIData('name');
$device = id(new AlmanacDeviceQuery())
->setViewer($viewer)
->withNames(array($name))
->needProperties(true)
->executeOne();
if (!$device) {
return new Aphront404Response();
}
$title = pht('Device %s', $device->getName());
$curtain = $this->buildCurtain($device);
$header = id(new PHUIHeaderView())
->setUser($viewer)
->setHeader($device->getName())
->setPolicyObject($device)
->setHeaderIcon('fa-server');
$status = $device->getStatusObject();
if ($status->hasStatusTag()) {
$header->setStatus(
$status->getStatusTagIcon(),
$status->getStatusTagColor(),
$status->getName());
}
$issue = null;
if ($device->isClusterDevice()) {
$issue = $this->addClusterMessage(
pht('This device is bound to a cluster service.'),
pht(
'This device is bound to a cluster service. You do not have '.
'permission to manage cluster services, so the device can not '.
'be edited.'));
}
$interfaces = $this->buildInterfaceList($device);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($device->getName());
$crumbs->setBorder(true);
$timeline = $this->buildTransactionTimeline(
$device,
new AlmanacDeviceTransactionQuery());
$timeline->setShouldTerminate(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$issue,
$interfaces,
$this->buildAlmanacPropertiesTable($device),
$this->buildSSHKeysTable($device),
$this->buildServicesTable($device),
$timeline,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild(
array(
$view,
));
}
private function buildCurtain(AlmanacDevice $device) {
$viewer = $this->getViewer();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$device,
PhabricatorPolicyCapability::CAN_EDIT);
$id = $device->getID();
$edit_uri = $this->getApplicationURI("device/edit/{$id}/");
$curtain = $this->newCurtainView($device);
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-pencil')
->setName(pht('Edit Device'))
->setHref($edit_uri)
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit));
return $curtain;
}
private function buildInterfaceList(AlmanacDevice $device) {
$viewer = $this->getViewer();
$id = $device->getID();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$device,
PhabricatorPolicyCapability::CAN_EDIT);
$interfaces = id(new AlmanacInterfaceQuery())
->setViewer($viewer)
->withDevicePHIDs(array($device->getPHID()))
->execute();
$table = id(new AlmanacInterfaceTableView())
->setUser($viewer)
->setInterfaces($interfaces)
->setCanEdit($can_edit);
$header = id(new PHUIHeaderView())
->setHeader(pht('Device Interfaces'))
->addActionLink(
id(new PHUIButtonView())
->setTag('a')
->setHref($this->getApplicationURI("interface/edit/?deviceID={$id}"))
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit)
->setText(pht('Add Interface'))
->setIcon('fa-plus'));
return id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($table);
}
private function buildSSHKeysTable(AlmanacDevice $device) {
$viewer = $this->getViewer();
$id = $device->getID();
$device_phid = $device->getPHID();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$device,
PhabricatorPolicyCapability::CAN_EDIT);
$keys = id(new PhabricatorAuthSSHKeyQuery())
->setViewer($viewer)
->withObjectPHIDs(array($device_phid))
->withIsActive(true)
->execute();
$table = id(new PhabricatorAuthSSHKeyTableView())
->setUser($viewer)
->setKeys($keys)
->setCanEdit($can_edit)
->setShowID(true)
->setShowTrusted(true)
->setNoDataString(pht('This device has no associated SSH public keys.'));
$menu_button = PhabricatorAuthSSHKeyTableView::newKeyActionsMenu(
$viewer,
$device);
$header = id(new PHUIHeaderView())
->setHeader(pht('SSH Public Keys'))
->addActionLink($menu_button);
return id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($table);
}
private function buildServicesTable(AlmanacDevice $device) {
$viewer = $this->getViewer();
// NOTE: We're loading all services so we can show hidden, locked services.
// In general, we let you know about all the things the device is bound to,
// even if you don't have permission to see their details. This is similar
// to exposing the existence of edges in other applications, with the
// addition of always letting you see that locks exist.
$services = id(new AlmanacServiceQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withDevicePHIDs(array($device->getPHID()))
->execute();
$handles = $viewer->loadHandles(mpull($services, 'getPHID'));
$icon_cluster = id(new PHUIIconView())
->setIcon('fa-sitemap');
$rows = array();
foreach ($services as $service) {
$rows[] = array(
($service->isClusterService()
? $icon_cluster
: null),
$handles->renderHandle($service->getPHID()),
);
}
$table = id(new AphrontTableView($rows))
->setNoDataString(pht('No services are bound to this device.'))
->setHeaders(
array(
null,
pht('Service'),
))
->setColumnClasses(
array(
null,
'wide pri',
));
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Bound Services'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($table);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacNamespaceEditController.php | src/applications/almanac/controller/AlmanacNamespaceEditController.php | <?php
final class AlmanacNamespaceEditController extends AlmanacNamespaceController {
public function handleRequest(AphrontRequest $request) {
return id(new AlmanacNamespaceEditEngine())
->setController($this)
->buildResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacPropertyDeleteController.php | src/applications/almanac/controller/AlmanacPropertyDeleteController.php | <?php
final class AlmanacPropertyDeleteController
extends AlmanacPropertyController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$response = $this->loadPropertyObject();
if ($response) {
return $response;
}
$object = $this->getPropertyObject();
$key = $request->getStr('key');
if (!strlen($key)) {
return new Aphront404Response();
}
$cancel_uri = $object->getURI();
$builtins = $object->getAlmanacPropertyFieldSpecifications();
$is_builtin = isset($builtins[$key]);
if ($is_builtin) {
$title = pht('Reset Property');
$body = pht(
'Reset property "%s" to its default value?',
$key);
$submit_text = pht('Reset Property');
} else {
$title = pht('Delete Property');
$body = pht(
'Delete property "%s"?',
$key);
$submit_text = pht('Delete Property');
}
$validation_exception = null;
if ($request->isFormPost()) {
$xaction_type = $object->getAlmanacPropertyDeleteTransactionType();
$xaction = $object->getApplicationTransactionTemplate()
->setTransactionType($xaction_type)
->setMetadataValue('almanac.property', $key);
$editor = $object->getApplicationTransactionEditor()
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true);
try {
$editor->applyTransactions($object, array($xaction));
return id(new AphrontRedirectResponse())->setURI($cancel_uri);
} catch (PhabricatorApplicationTransactionValidationException $ex) {
$validation_exception = $ex;
}
}
return $this->newDialog()
->setTitle($title)
->setValidationException($validation_exception)
->addHiddenInput('objectPHID', $object->getPHID())
->addHiddenInput('key', $key)
->appendParagraph($body)
->addCancelButton($cancel_uri)
->addSubmitButton($submit_text);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacDeviceEditController.php | src/applications/almanac/controller/AlmanacDeviceEditController.php | <?php
final class AlmanacDeviceEditController
extends AlmanacDeviceController {
public function handleRequest(AphrontRequest $request) {
return id(new AlmanacDeviceEditEngine())
->setController($this)
->buildResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacServiceEditController.php | src/applications/almanac/controller/AlmanacServiceEditController.php | <?php
final class AlmanacServiceEditController
extends AlmanacServiceController {
public function handleRequest(AphrontRequest $request) {
$engine = id(new AlmanacServiceEditEngine())
->setController($this);
$id = $request->getURIData('id');
if (!$id) {
$this->requireApplicationCapability(
AlmanacCreateServicesCapability::CAPABILITY);
$list_uri = $this->getApplicationURI('service/');
$service_type = $request->getStr('serviceType');
$service_types = AlmanacServiceType::getAllServiceTypes();
if (empty($service_types[$service_type])) {
return $this->buildServiceTypeResponse($list_uri);
}
$engine
->addContextParameter('serviceType', $service_type)
->setServiceType($service_type);
}
return $engine->buildResponse();
}
private function buildServiceTypeResponse($cancel_uri) {
$service_types = AlmanacServiceType::getAllServiceTypes();
$request = $this->getRequest();
$viewer = $this->getViewer();
$e_service = null;
$errors = array();
if ($request->isFormPost()) {
$e_service = pht('Required');
$errors[] = pht(
'To create a new service, you must select a service type.');
}
list($can_cluster, $cluster_link) = $this->explainApplicationCapability(
AlmanacManageClusterServicesCapability::CAPABILITY,
pht('You have permission to create cluster services.'),
pht('You do not have permission to create new cluster services.'));
$type_control = id(new AphrontFormRadioButtonControl())
->setLabel(pht('Service Type'))
->setName('serviceType')
->setError($e_service);
foreach ($service_types as $service_type) {
$is_cluster = $service_type->isClusterServiceType();
$is_disabled = ($is_cluster && !$can_cluster);
if ($is_cluster) {
$extra = $cluster_link;
} else {
$extra = null;
}
$type_control->addButton(
$service_type->getServiceTypeConstant(),
$service_type->getServiceTypeName(),
array(
$service_type->getServiceTypeDescription(),
$extra,
),
$is_disabled ? 'disabled' : null,
$is_disabled);
}
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb(pht('Create Service'));
$crumbs->setBorder(true);
$title = pht('Choose Service Type');
$header = id(new PHUIHeaderView())
->setHeader(pht('Create Service'))
->setHeaderIcon('fa-plus-square');
$form = id(new AphrontFormView())
->setUser($viewer)
->appendChild($type_control)
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Continue'))
->addCancelButton($cancel_uri));
$box = id(new PHUIObjectBoxView())
->setFormErrors($errors)
->setHeaderText(pht('Service'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setForm($form);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$box,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild($view);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacServiceViewController.php | src/applications/almanac/controller/AlmanacServiceViewController.php | <?php
final class AlmanacServiceViewController
extends AlmanacServiceController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$name = $request->getURIData('name');
$service = id(new AlmanacServiceQuery())
->setViewer($viewer)
->withNames(array($name))
->needProperties(true)
->executeOne();
if (!$service) {
return new Aphront404Response();
}
$title = pht('Service %s', $service->getName());
$curtain = $this->buildCurtain($service);
$details = $this->buildPropertySection($service);
$header = id(new PHUIHeaderView())
->setUser($viewer)
->setHeader($service->getName())
->setPolicyObject($service)
->setHeaderIcon('fa-plug');
$issue = null;
if ($service->isClusterService()) {
$issue = $this->addClusterMessage(
pht('This is a cluster service.'),
pht(
'This service is a cluster service. You do not have permission to '.
'edit cluster services, so you can not edit this service.'));
}
$bindings = $this->buildBindingList($service);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($service->getName());
$crumbs->setBorder(true);
$timeline = $this->buildTransactionTimeline(
$service,
new AlmanacServiceTransactionQuery());
$timeline->setShouldTerminate(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$issue,
$details,
$bindings,
$this->buildAlmanacPropertiesTable($service),
$timeline,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild($view);
}
private function buildPropertySection(
AlmanacService $service) {
$viewer = $this->getViewer();
$properties = id(new PHUIPropertyListView())
->setUser($viewer);
$properties->addProperty(
pht('Service Type'),
$service->getServiceImplementation()->getServiceTypeShortName());
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Details'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($properties);
}
private function buildCurtain(AlmanacService $service) {
$viewer = $this->getViewer();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$service,
PhabricatorPolicyCapability::CAN_EDIT);
$id = $service->getID();
$edit_uri = $this->getApplicationURI("service/edit/{$id}/");
$curtain = $this->newCurtainView($service);
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-pencil')
->setName(pht('Edit Service'))
->setHref($edit_uri)
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit));
return $curtain;
}
private function buildBindingList(AlmanacService $service) {
$viewer = $this->getViewer();
$id = $service->getID();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$service,
PhabricatorPolicyCapability::CAN_EDIT);
$bindings = id(new AlmanacBindingQuery())
->setViewer($viewer)
->withServicePHIDs(array($service->getPHID()))
->execute();
$table = id(new AlmanacBindingTableView())
->setNoDataString(
pht('This service has not been bound to any device interfaces yet.'))
->setUser($viewer)
->setBindings($bindings)
->setHideServiceColumn(true);
$header = id(new PHUIHeaderView())
->setHeader(pht('Service Bindings'))
->addActionLink(
id(new PHUIButtonView())
->setTag('a')
->setHref($this->getApplicationURI("binding/edit/?serviceID={$id}"))
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit)
->setText(pht('Add Binding'))
->setIcon('fa-plus'));
return id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($table);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacNamespaceListController.php | src/applications/almanac/controller/AlmanacNamespaceListController.php | <?php
final class AlmanacNamespaceListController
extends AlmanacNamespaceController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new AlmanacNamespaceSearchEngine())
->setController($this)
->buildResponse();
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
id(new AlmanacNamespaceEditEngine())
->setViewer($this->getViewer())
->addActionToCrumbs($crumbs);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacServiceListController.php | src/applications/almanac/controller/AlmanacServiceListController.php | <?php
final class AlmanacServiceListController
extends AlmanacServiceController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new AlmanacServiceSearchEngine())
->setController($this)
->buildResponse();
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
id(new AlmanacServiceEditEngine())
->setViewer($this->getViewer())
->addActionToCrumbs($crumbs);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacNetworkViewController.php | src/applications/almanac/controller/AlmanacNetworkViewController.php | <?php
final class AlmanacNetworkViewController
extends AlmanacNetworkController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$network = id(new AlmanacNetworkQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$network) {
return new Aphront404Response();
}
$title = pht('Network %s', $network->getName());
$curtain = $this->buildCurtain($network);
$header = id(new PHUIHeaderView())
->setUser($viewer)
->setHeader($network->getName())
->setHeaderIcon('fa-globe')
->setPolicyObject($network);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($network->getName());
$crumbs->setBorder(true);
$timeline = $this->buildTransactionTimeline(
$network,
new AlmanacNetworkTransactionQuery());
$timeline->setShouldTerminate(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$timeline,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild(
array(
$view,
));
}
private function buildCurtain(AlmanacNetwork $network) {
$viewer = $this->getViewer();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$network,
PhabricatorPolicyCapability::CAN_EDIT);
$id = $network->getID();
$edit_uri = $this->getApplicationURI("network/edit/{$id}/");
$curtain = $this->newCurtainView($network);
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-pencil')
->setName(pht('Edit Network'))
->setHref($edit_uri)
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit));
return $curtain;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacInterfaceEditController.php | src/applications/almanac/controller/AlmanacInterfaceEditController.php | <?php
final class AlmanacInterfaceEditController
extends AlmanacDeviceController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
$engine = id(new AlmanacInterfaceEditEngine())
->setController($this);
$id = $request->getURIData('id');
if (!$id) {
$device = id(new AlmanacDeviceQuery())
->setViewer($viewer)
->withIDs(array($request->getInt('deviceID')))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$device) {
return new Aphront404Response();
}
$engine
->addContextParameter('deviceID', $device->getID())
->setDevice($device);
}
return $engine->buildResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacBindingViewController.php | src/applications/almanac/controller/AlmanacBindingViewController.php | <?php
final class AlmanacBindingViewController
extends AlmanacServiceController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$binding = id(new AlmanacBindingQuery())
->setViewer($viewer)
->withIDs(array($id))
->needProperties(true)
->executeOne();
if (!$binding) {
return new Aphront404Response();
}
$service = $binding->getService();
$service_uri = $service->getURI();
$title = pht('Binding %s', $binding->getID());
$properties = $this->buildPropertyList($binding);
$details = $this->buildPropertySection($binding);
$curtain = $this->buildCurtain($binding);
$header = id(new PHUIHeaderView())
->setUser($viewer)
->setHeader($title)
->setPolicyObject($binding)
->setHeaderIcon('fa-object-group');
if ($binding->getIsDisabled()) {
$header->setStatus('fa-ban', 'red', pht('Disabled'));
}
$issue = null;
if ($binding->getService()->isClusterService()) {
$issue = $this->addClusterMessage(
pht('The service for this binding is a cluster service.'),
pht(
'The service for this binding is a cluster service. You do not '.
'have permission to manage cluster services, so this binding can '.
'not be edited.'));
}
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($service->getName(), $service_uri);
$crumbs->addTextCrumb($title);
$crumbs->setBorder(true);
$timeline = $this->buildTransactionTimeline(
$binding,
new AlmanacBindingTransactionQuery());
$timeline->setShouldTerminate(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(array(
$issue,
$this->buildAlmanacPropertiesTable($binding),
$timeline,
))
->addPropertySection(pht('Details'), $details);
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild(
array(
$view,
));
}
private function buildPropertySection(AlmanacBinding $binding) {
$viewer = $this->getViewer();
$properties = id(new PHUIPropertyListView())
->setUser($viewer);
$properties->addProperty(
pht('Service'),
$viewer->renderHandle($binding->getServicePHID()));
$properties->addProperty(
pht('Device'),
$viewer->renderHandle($binding->getDevicePHID()));
$properties->addProperty(
pht('Network'),
$viewer->renderHandle($binding->getInterface()->getNetworkPHID()));
$properties->addProperty(
pht('Interface'),
$binding->getInterface()->renderDisplayAddress());
return $properties;
}
private function buildPropertyList(AlmanacBinding $binding) {
$viewer = $this->getViewer();
$properties = id(new PHUIPropertyListView())
->setUser($viewer)
->setObject($binding);
$properties->invokeWillRenderEvent();
return $properties;
}
private function buildCurtain(AlmanacBinding $binding) {
$viewer = $this->getViewer();
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$binding,
PhabricatorPolicyCapability::CAN_EDIT);
$id = $binding->getID();
$edit_uri = $this->getApplicationURI("binding/edit/{$id}/");
$disable_uri = $this->getApplicationURI("binding/disable/{$id}/");
$curtain = $this->newCurtainView($binding);
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-pencil')
->setName(pht('Edit Binding'))
->setHref($edit_uri)
->setWorkflow(!$can_edit)
->setDisabled(!$can_edit));
if ($binding->getIsDisabled()) {
$disable_icon = 'fa-check';
$disable_text = pht('Enable Binding');
} else {
$disable_icon = 'fa-ban';
$disable_text = pht('Disable Binding');
}
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon($disable_icon)
->setName($disable_text)
->setHref($disable_uri)
->setWorkflow(true)
->setDisabled(!$can_edit));
return $curtain;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacNamespaceController.php | src/applications/almanac/controller/AlmanacNamespaceController.php | <?php
abstract class AlmanacNamespaceController extends AlmanacController {
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$list_uri = $this->getApplicationURI('namespace/');
$crumbs->addTextCrumb(pht('Namespaces'), $list_uri);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacNetworkEditController.php | src/applications/almanac/controller/AlmanacNetworkEditController.php | <?php
final class AlmanacNetworkEditController extends AlmanacNetworkController {
public function handleRequest(AphrontRequest $request) {
return id(new AlmanacNetworkEditEngine())
->setController($this)
->buildResponse();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacConsoleController.php | src/applications/almanac/controller/AlmanacConsoleController.php | <?php
final class AlmanacConsoleController extends AlmanacController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$menu = id(new PHUIObjectItemListView())
->setViewer($viewer)
->setBig(true);
$menu->addItem(
id(new PHUIObjectItemView())
->setHeader(pht('Devices'))
->setHref($this->getApplicationURI('device/'))
->setImageIcon('fa-server')
->setClickable(true)
->addAttribute(
pht(
'Create an inventory of physical and virtual hosts and '.
'devices.')));
$menu->addItem(
id(new PHUIObjectItemView())
->setHeader(pht('Services'))
->setHref($this->getApplicationURI('service/'))
->setImageIcon('fa-plug')
->setClickable(true)
->addAttribute(
pht(
'Create and update services, and map them to interfaces on '.
'devices.')));
$menu->addItem(
id(new PHUIObjectItemView())
->setHeader(pht('Networks'))
->setHref($this->getApplicationURI('network/'))
->setImageIcon('fa-globe')
->setClickable(true)
->addAttribute(
pht(
'Manage public and private networks.')));
$menu->addItem(
id(new PHUIObjectItemView())
->setHeader(pht('Namespaces'))
->setHref($this->getApplicationURI('namespace/'))
->setImageIcon('fa-asterisk')
->setClickable(true)
->addAttribute(
pht('Control who can create new named services and devices.')));
$docs_uri = PhabricatorEnv::getDoclink(
'Almanac User Guide');
$menu->addItem(
id(new PHUIObjectItemView())
->setHeader(pht('Documentation'))
->setHref($docs_uri)
->setImageIcon('fa-book')
->setClickable(true)
->addAttribute(pht('Browse documentation for Almanac.')));
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb(pht('Console'));
$crumbs->setBorder(true);
$box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Almanac Console'))
->setBackground(PHUIObjectBoxView::WHITE_CONFIG)
->setObjectList($menu);
$launcher_view = id(new PHUILauncherView())
->appendChild($box);
$view = id(new PHUITwoColumnView())
->setFooter($launcher_view);
return $this->newPage()
->setTitle(pht('Almanac Console'))
->setCrumbs($crumbs)
->appendChild($view);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacPropertyEditController.php | src/applications/almanac/controller/AlmanacPropertyEditController.php | <?php
final class AlmanacPropertyEditController
extends AlmanacPropertyController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$response = $this->loadPropertyObject();
if ($response) {
return $response;
}
$object = $this->getPropertyObject();
$cancel_uri = $object->getURI();
$property_key = $request->getStr('key');
if (!phutil_nonempty_string($property_key)) {
return $this->buildPropertyKeyResponse($cancel_uri, null);
} else {
$error = null;
try {
AlmanacNames::validateName($property_key);
} catch (Exception $ex) {
$error = $ex->getMessage();
}
// NOTE: If you enter an existing name, we're just treating it as an
// edit operation. This might be a little confusing.
if ($error !== null) {
if ($request->isFormPost()) {
// The user is creating a new property and picked a bad name. Give
// them an opportunity to fix it.
return $this->buildPropertyKeyResponse($cancel_uri, $error);
} else {
// The user is editing an invalid property.
return $this->newDialog()
->setTitle(pht('Invalid Property'))
->appendParagraph(
pht(
'The property name "%s" is invalid. This property can not '.
'be edited.',
$property_key))
->appendParagraph($error)
->addCancelButton($cancel_uri);
}
}
}
return $object->newAlmanacPropertyEditEngine()
->addContextParameter('objectPHID')
->addContextParameter('key')
->setTargetObject($object)
->setPropertyKey($property_key)
->setController($this)
->buildResponse();
}
private function buildPropertyKeyResponse($cancel_uri, $error) {
$viewer = $this->getViewer();
$request = $this->getRequest();
$v_key = $request->getStr('key');
if ($error !== null) {
$e_key = pht('Invalid');
} else {
$e_key = true;
}
$form = id(new AphrontFormView())
->setUser($viewer)
->appendChild(
id(new AphrontFormTextControl())
->setName('key')
->setLabel(pht('Name'))
->setValue($v_key)
->setError($e_key));
$errors = array();
if ($error !== null) {
$errors[] = $error;
}
return $this->newDialog()
->setTitle(pht('Add Property'))
->addHiddenInput('objectPHID', $request->getStr('objectPHID'))
->setErrors($errors)
->appendForm($form)
->addSubmitButton(pht('Continue'))
->addCancelButton($cancel_uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacNetworkListController.php | src/applications/almanac/controller/AlmanacNetworkListController.php | <?php
final class AlmanacNetworkListController
extends AlmanacNetworkController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$controller = id(new PhabricatorApplicationSearchController())
->setQueryKey($request->getURIData('queryKey'))
->setSearchEngine(new AlmanacNetworkSearchEngine())
->setNavigation($this->buildSideNavView());
return $this->delegateToController($controller);
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$can_create = $this->hasApplicationCapability(
AlmanacCreateNetworksCapability::CAPABILITY);
$crumbs->addAction(
id(new PHUIListItemView())
->setName(pht('Create Network'))
->setHref($this->getApplicationURI('network/edit/'))
->setIcon('fa-plus-square')
->setDisabled(!$can_create)
->setWorkflow(!$can_create));
return $crumbs;
}
public function buildSideNavView() {
$viewer = $this->getViewer();
$nav = new AphrontSideNavFilterView();
$nav->setBaseURI(new PhutilURI($this->getApplicationURI()));
id(new AlmanacNetworkSearchEngine())
->setViewer($viewer)
->addNavigationItems($nav->getMenu());
$nav->selectFilter(null);
return $nav;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacBindingDisableController.php | src/applications/almanac/controller/AlmanacBindingDisableController.php | <?php
final class AlmanacBindingDisableController
extends AlmanacServiceController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$binding = id(new AlmanacBindingQuery())
->setViewer($viewer)
->withIDs(array($id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$binding) {
return new Aphront404Response();
}
$id = $binding->getID();
$is_disable = !$binding->getIsDisabled();
$done_uri = $binding->getURI();
if ($is_disable) {
$disable_title = pht('Disable Binding');
$disable_body = pht('Disable this binding?');
$disable_button = pht('Disable Binding');
$v_disable = 1;
} else {
$disable_title = pht('Enable Binding');
$disable_body = pht('Enable this binding?');
$disable_button = pht('Enable Binding');
$v_disable = 0;
}
if ($request->isFormPost()) {
$type_disable = AlmanacBindingDisableTransaction::TRANSACTIONTYPE;
$xactions = array();
$xactions[] = id(new AlmanacBindingTransaction())
->setTransactionType($type_disable)
->setNewValue($v_disable);
$editor = id(new AlmanacBindingEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true);
$editor->applyTransactions($binding, $xactions);
return id(new AphrontRedirectResponse())->setURI($done_uri);
}
return $this->newDialog()
->setTitle($disable_title)
->appendParagraph($disable_body)
->addSubmitButton($disable_button)
->addCancelButton($done_uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacController.php | src/applications/almanac/controller/AlmanacController.php | <?php
abstract class AlmanacController
extends PhabricatorController {
protected function buildAlmanacPropertiesTable(
AlmanacPropertyInterface $object) {
$viewer = $this->getViewer();
$properties = $object->getAlmanacProperties();
$this->requireResource('almanac-css');
Javelin::initBehavior('phabricator-tooltips', array());
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$object,
PhabricatorPolicyCapability::CAN_EDIT);
$properties = $object->getAlmanacProperties();
$icon_builtin = id(new PHUIIconView())
->setIcon('fa-circle')
->addSigil('has-tooltip')
->setMetadata(
array(
'tip' => pht('Builtin Property'),
'align' => 'E',
));
$icon_custom = id(new PHUIIconView())
->setIcon('fa-circle-o grey')
->addSigil('has-tooltip')
->setMetadata(
array(
'tip' => pht('Custom Property'),
'align' => 'E',
));
$builtins = $object->getAlmanacPropertyFieldSpecifications();
$defaults = mpull($builtins, 'getValueForTransaction');
// Sort fields so builtin fields appear first, then fields are ordered
// alphabetically.
$properties = msort($properties, 'getFieldName');
$head = array();
$tail = array();
foreach ($properties as $property) {
$key = $property->getFieldName();
if (isset($builtins[$key])) {
$head[$key] = $property;
} else {
$tail[$key] = $property;
}
}
$properties = $head + $tail;
$delete_base = $this->getApplicationURI('property/delete/');
$edit_base = $this->getApplicationURI('property/update/');
$rows = array();
foreach ($properties as $key => $property) {
$value = $property->getFieldValue();
$is_builtin = isset($builtins[$key]);
$is_persistent = (bool)$property->getID();
$params = array(
'key' => $key,
'objectPHID' => $object->getPHID(),
);
$delete_uri = new PhutilURI($delete_base, $params);
$edit_uri = new PhutilURI($edit_base, $params);
$delete = javelin_tag(
'a',
array(
'class' => (($can_edit && $is_persistent)
? 'button button-grey small'
: 'button button-grey small disabled'),
'sigil' => 'workflow',
'href' => $delete_uri,
),
$is_builtin ? pht('Reset') : pht('Delete'));
$default = idx($defaults, $key);
$is_default = ($default !== null && $default === $value);
$display_value = PhabricatorConfigJSON::prettyPrintJSON($value);
if ($is_default) {
$display_value = phutil_tag(
'span',
array(
'class' => 'almanac-default-property-value',
),
$display_value);
}
$display_key = $key;
if ($can_edit) {
$display_key = javelin_tag(
'a',
array(
'href' => $edit_uri,
'sigil' => 'workflow',
),
$display_key);
}
$rows[] = array(
($is_builtin ? $icon_builtin : $icon_custom),
$display_key,
$display_value,
$delete,
);
}
$table = id(new AphrontTableView($rows))
->setNoDataString(pht('No properties.'))
->setHeaders(
array(
null,
pht('Name'),
pht('Value'),
null,
))
->setColumnClasses(
array(
null,
null,
'wide',
'action',
));
$phid = $object->getPHID();
$add_uri = id(new PhutilURI($edit_base))
->replaceQueryParam('objectPHID', $object->getPHID());
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$object,
PhabricatorPolicyCapability::CAN_EDIT);
$add_button = id(new PHUIButtonView())
->setTag('a')
->setHref($add_uri)
->setWorkflow(true)
->setDisabled(!$can_edit)
->setText(pht('Add Property'))
->setIcon('fa-plus');
$header = id(new PHUIHeaderView())
->setHeader(pht('Properties'))
->addActionLink($add_button);
return id(new PHUIObjectBoxView())
->setHeader($header)
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setTable($table);
}
protected function addClusterMessage(
$positive,
$negative) {
$can_manage = $this->hasApplicationCapability(
AlmanacManageClusterServicesCapability::CAPABILITY);
$doc_link = phutil_tag(
'a',
array(
'href' => PhabricatorEnv::getDoclink(
'Clustering Introduction'),
'target' => '_blank',
),
pht('Learn More'));
if ($can_manage) {
$severity = PHUIInfoView::SEVERITY_NOTICE;
$message = $positive;
} else {
$severity = PHUIInfoView::SEVERITY_WARNING;
$message = $negative;
}
$icon = id(new PHUIIconView())
->setIcon('fa-sitemap');
return id(new PHUIInfoView())
->setSeverity($severity)
->setErrors(
array(
array($icon, ' ', $message, ' ', $doc_link),
));
}
protected function getPropertyDeleteURI($object) {
return null;
}
protected function getPropertyUpdateURI($object) {
return null;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacInterfaceDeleteController.php | src/applications/almanac/controller/AlmanacInterfaceDeleteController.php | <?php
final class AlmanacInterfaceDeleteController
extends AlmanacDeviceController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$interface = id(new AlmanacInterfaceQuery())
->setViewer($viewer)
->withIDs(array($id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$interface) {
return new Aphront404Response();
}
$device = $interface->getDevice();
$device_uri = $device->getURI();
if ($interface->loadIsInUse()) {
return $this->newDialog()
->setTitle(pht('Interface In Use'))
->appendParagraph(
pht(
'You can not delete this interface because it is currently in '.
'use. One or more services are bound to it.'))
->addCancelButton($device_uri);
}
if ($request->isFormPost()) {
$type_destroy = AlmanacInterfaceDestroyTransaction::TRANSACTIONTYPE;
$xactions = array();
$xactions[] = $interface->getApplicationTransactionTemplate()
->setTransactionType($type_destroy)
->setNewValue(true);
$editor = id(new AlmanacInterfaceEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true);
$editor->applyTransactions($interface, $xactions);
return id(new AphrontRedirectResponse())->setURI($device_uri);
}
return $this->newDialog()
->setTitle(pht('Delete Interface'))
->appendParagraph(
pht(
'Remove interface %s on device %s?',
phutil_tag('strong', array(), $interface->renderDisplayAddress()),
phutil_tag('strong', array(), $device->getName())))
->addCancelButton($device_uri)
->addSubmitButton(pht('Delete Interface'));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacBindingEditController.php | src/applications/almanac/controller/AlmanacBindingEditController.php | <?php
final class AlmanacBindingEditController
extends AlmanacServiceController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
if ($id) {
$binding = id(new AlmanacBindingQuery())
->setViewer($viewer)
->withIDs(array($id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$binding) {
return new Aphront404Response();
}
$service = $binding->getService();
$is_new = false;
$service_uri = $service->getURI();
$cancel_uri = $binding->getURI();
$title = pht('Edit Binding');
$save_button = pht('Save Changes');
} else {
$service = id(new AlmanacServiceQuery())
->setViewer($viewer)
->withIDs(array($request->getStr('serviceID')))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
$binding = AlmanacBinding::initializeNewBinding($service);
$is_new = true;
$service_uri = $service->getURI();
$cancel_uri = $service_uri;
$title = pht('Create Binding');
$save_button = pht('Create Binding');
}
$v_interface = array();
if ($binding->getInterfacePHID()) {
$v_interface = array($binding->getInterfacePHID());
}
$e_interface = true;
$validation_exception = null;
if ($request->isFormPost()) {
$v_interface = $request->getArr('interfacePHIDs');
$type_interface = AlmanacBindingInterfaceTransaction::TRANSACTIONTYPE;
$xactions = array();
$xactions[] = id(new AlmanacBindingTransaction())
->setTransactionType($type_interface)
->setNewValue(head($v_interface));
$editor = id(new AlmanacBindingEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true);
try {
$editor->applyTransactions($binding, $xactions);
$binding_uri = $binding->getURI();
return id(new AphrontRedirectResponse())->setURI($binding_uri);
} catch (PhabricatorApplicationTransactionValidationException $ex) {
$validation_exception = $ex;
$e_interface = $ex->getShortMessage($type_interface);
}
}
$form = id(new AphrontFormView())
->setUser($viewer)
->appendControl(
id(new AphrontFormTokenizerControl())
->setName('interfacePHIDs')
->setLabel(pht('Interface'))
->setLimit(1)
->setDatasource(new AlmanacInterfaceDatasource())
->setValue($v_interface)
->setError($e_interface))
->appendChild(
id(new AphrontFormSubmitControl())
->addCancelButton($cancel_uri)
->setValue($save_button));
$box = id(new PHUIObjectBoxView())
->setValidationException($validation_exception)
->setHeaderText(pht('Binding'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($form);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($service->getName(), $service_uri);
if ($is_new) {
$crumbs->addTextCrumb(pht('Create Binding'));
$header = id(new PHUIHeaderView())
->setHeader(pht('Create Binding'))
->setHeaderIcon('fa-plus-square');
} else {
$crumbs->addTextCrumb(pht('Edit Binding'));
$header = id(new PHUIHeaderView())
->setHeader(pht('Create Binding'))
->setHeaderIcon('fa-pencil');
}
$crumbs->setBorder(true);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$box,
));
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->appendChild($view);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/controller/AlmanacDeviceController.php | src/applications/almanac/controller/AlmanacDeviceController.php | <?php
abstract class AlmanacDeviceController extends AlmanacController {
public function buildApplicationMenu() {
return $this->newApplicationMenu()
->setSearchEngine(new AlmanacDeviceSearchEngine());
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$list_uri = $this->getApplicationURI('device/');
$crumbs->addTextCrumb(pht('Devices'), $list_uri);
return $crumbs;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/engineextension/AlmanacPropertiesSearchEngineAttachment.php | src/applications/almanac/engineextension/AlmanacPropertiesSearchEngineAttachment.php | <?php
final class AlmanacPropertiesSearchEngineAttachment
extends AlmanacSearchEngineAttachment {
public function getAttachmentName() {
return pht('Almanac Properties');
}
public function getAttachmentDescription() {
return pht('Get Almanac properties for the object.');
}
public function willLoadAttachmentData($query, $spec) {
$query->needProperties(true);
}
public function getAttachmentForObject($object, $data, $spec) {
$properties = $this->getAlmanacPropertyList($object);
return array(
'properties' => $properties,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/engineextension/AlmanacPropertiesDestructionEngineExtension.php | src/applications/almanac/engineextension/AlmanacPropertiesDestructionEngineExtension.php | <?php
final class AlmanacPropertiesDestructionEngineExtension
extends PhabricatorDestructionEngineExtension {
const EXTENSIONKEY = 'almanac.properties';
public function getExtensionName() {
return pht('Almanac Properties');
}
public function canDestroyObject(
PhabricatorDestructionEngine $engine,
$object) {
return ($object instanceof AlmanacPropertyInterface);
}
public function destroyObject(
PhabricatorDestructionEngine $engine,
$object) {
$table = new AlmanacProperty();
$conn_w = $table->establishConnection('w');
queryfx(
$conn_w,
'DELETE FROM %T WHERE objectPHID = %s',
$table->getTableName(),
$object->getPHID());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/engineextension/AlmanacCacheEngineExtension.php | src/applications/almanac/engineextension/AlmanacCacheEngineExtension.php | <?php
final class AlmanacCacheEngineExtension
extends PhabricatorCacheEngineExtension {
const EXTENSIONKEY = 'almanac';
public function getExtensionName() {
return pht('Almanac Core Objects');
}
public function discoverLinkedObjects(
PhabricatorCacheEngine $engine,
array $objects) {
$viewer = $engine->getViewer();
$results = array();
foreach ($this->selectObjects($objects, 'AlmanacBinding') as $object) {
$results[] = $object->getServicePHID();
$results[] = $object->getDevicePHID();
$results[] = $object->getInterfacePHID();
}
$devices = $this->selectObjects($objects, 'AlmanacDevice');
if ($devices) {
$interfaces = id(new AlmanacInterfaceQuery())
->setViewer($viewer)
->withDevicePHIDs(mpull($devices, 'getPHID'))
->execute();
foreach ($interfaces as $interface) {
$results[] = $interface;
}
$bindings = id(new AlmanacBindingQuery())
->setViewer($viewer)
->withDevicePHIDs(mpull($devices, 'getPHID'))
->execute();
foreach ($bindings as $binding) {
$results[] = $binding;
}
}
foreach ($this->selectObjects($objects, 'AlmanacInterface') as $iface) {
$results[] = $iface->getDevicePHID();
$results[] = $iface->getNetworkPHID();
}
foreach ($this->selectObjects($objects, 'AlmanacProperty') as $object) {
$results[] = $object->getObjectPHID();
}
return $results;
}
public function deleteCaches(
PhabricatorCacheEngine $engine,
array $objects) {
return;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/engineextension/AlmanacBindingsSearchEngineAttachment.php | src/applications/almanac/engineextension/AlmanacBindingsSearchEngineAttachment.php | <?php
final class AlmanacBindingsSearchEngineAttachment
extends AlmanacSearchEngineAttachment {
private $isActive;
public function setIsActive($is_active) {
$this->isActive = $is_active;
return $this;
}
public function getIsActive() {
return $this->isActive;
}
public function getAttachmentName() {
return pht('Almanac Bindings');
}
public function getAttachmentDescription() {
return pht('Get Almanac bindings for the service.');
}
public function willLoadAttachmentData($query, $spec) {
$query->needProperties(true);
if ($this->getIsActive()) {
$query->needActiveBindings(true);
} else {
$query->needBindings(true);
}
}
public function getAttachmentForObject($object, $data, $spec) {
$bindings = array();
if ($this->getIsActive()) {
$service_bindings = $object->getActiveBindings();
} else {
$service_bindings = $object->getBindings();
}
foreach ($service_bindings as $binding) {
$bindings[] = $this->getAlmanacBindingDictionary($binding);
}
return array(
'bindings' => $bindings,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/engineextension/AlmanacPropertiesEditEngineExtension.php | src/applications/almanac/engineextension/AlmanacPropertiesEditEngineExtension.php | <?php
final class AlmanacPropertiesEditEngineExtension
extends PhabricatorEditEngineExtension {
const EXTENSIONKEY = 'almanac.properties';
public function isExtensionEnabled() {
return true;
}
public function getExtensionName() {
return pht('Almanac Properties');
}
public function supportsObject(
PhabricatorEditEngine $engine,
PhabricatorApplicationTransactionInterface $object) {
return ($object instanceof AlmanacPropertyInterface);
}
public function buildCustomEditFields(
PhabricatorEditEngine $engine,
PhabricatorApplicationTransactionInterface $object) {
return array(
id(new AlmanacSetPropertyEditField())
->setKey('property.set')
->setTransactionType($object->getAlmanacPropertySetTransactionType())
->setConduitDescription(
pht('Pass a map of values to set one or more properties.'))
->setConduitTypeDescription(pht('Map of property names to values.'))
->setIsFormField(false),
id(new AlmanacDeletePropertyEditField())
->setKey('property.delete')
->setTransactionType($object->getAlmanacPropertyDeleteTransactionType())
->setConduitDescription(
pht('Pass a list of property names to delete properties.'))
->setConduitTypeDescription(pht('List of property names.'))
->setIsFormField(false),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/engineextension/AlmanacSetPropertyEditField.php | src/applications/almanac/engineextension/AlmanacSetPropertyEditField.php | <?php
final class AlmanacSetPropertyEditField
extends PhabricatorEditField {
protected function newControl() {
return null;
}
protected function newHTTPParameterType() {
return null;
}
protected function newConduitParameterType() {
return new ConduitWildParameterType();
}
protected function newEditType() {
return new AlmanacSetPropertyEditType();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/almanac/engineextension/AlmanacSetPropertyEditType.php | src/applications/almanac/engineextension/AlmanacSetPropertyEditType.php | <?php
final class AlmanacSetPropertyEditType
extends PhabricatorEditType {
public function generateTransactions(
PhabricatorApplicationTransaction $template,
array $spec) {
$value = idx($spec, 'value');
if (!is_array($value)) {
throw new Exception(
pht(
'Transaction value when setting Almanac properties must be a map '.
'with property names as keys.'));
}
$xactions = array();
foreach ($value as $property_key => $property_value) {
$xactions[] = $this->newTransaction($template)
->setMetadataValue('almanac.property', $property_key)
->setNewValue($property_value);
}
return $xactions;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.