Page MenuHomestyx hydra

No OneTemporary

diff --git a/src/applications/celerity/CelerityStaticResourceResponse.php b/src/applications/celerity/CelerityStaticResourceResponse.php
index 3f34b7634f..7864515e11 100644
--- a/src/applications/celerity/CelerityStaticResourceResponse.php
+++ b/src/applications/celerity/CelerityStaticResourceResponse.php
@@ -1,314 +1,316 @@
<?php
/**
* Tracks and resolves dependencies the page declares with
* @{function:require_celerity_resource}, and then builds appropriate HTML or
* Ajax responses.
*/
final class CelerityStaticResourceResponse {
private $symbols = array();
private $needsResolve = true;
private $resolved;
private $packaged;
private $metadata = array();
private $metadataBlock = 0;
private $behaviors = array();
private $hasRendered = array();
public function __construct() {
if (isset($_REQUEST['__metablock__'])) {
$this->metadataBlock = (int)$_REQUEST['__metablock__'];
}
}
public function addMetadata($metadata) {
$id = count($this->metadata);
$this->metadata[$id] = $metadata;
return $this->metadataBlock.'_'.$id;
}
public function getMetadataBlock() {
return $this->metadataBlock;
}
/**
- * Register a behavior for initialization. NOTE: if $config is empty,
- * a behavior will execute only once even if it is initialized multiple times.
- * If $config is nonempty, the behavior will be invoked once for each config.
+ * Register a behavior for initialization.
+ *
+ * NOTE: If `$config` is empty, a behavior will execute only once even if it
+ * is initialized multiple times. If `$config` is nonempty, the behavior will
+ * be invoked once for each configuration.
*/
public function initBehavior(
$behavior,
array $config = array(),
- $source_name) {
+ $source_name = null) {
$this->requireResource('javelin-behavior-'.$behavior, $source_name);
if (empty($this->behaviors[$behavior])) {
$this->behaviors[$behavior] = array();
}
if ($config) {
$this->behaviors[$behavior][] = $config;
}
return $this;
}
public function requireResource($symbol, $source_name) {
if (isset($this->symbols[$source_name][$symbol])) {
return $this;
}
// Verify that the resource exists.
$map = CelerityResourceMap::getNamedInstance($source_name);
$name = $map->getResourceNameForSymbol($symbol);
if ($name === null) {
throw new Exception(
pht(
'No resource with symbol "%s" exists in source "%s"!',
$symbol,
$source_name));
}
$this->symbols[$source_name][$symbol] = true;
$this->needsResolve = true;
return $this;
}
private function resolveResources() {
if ($this->needsResolve) {
$this->packaged = array();
foreach ($this->symbols as $source_name => $symbols_map) {
$symbols = array_keys($symbols_map);
$map = CelerityResourceMap::getNamedInstance($source_name);
$packaged = $map->getPackagedNamesForSymbols($symbols);
$this->packaged[$source_name] = $packaged;
}
$this->needsResolve = false;
}
return $this;
}
public function renderSingleResource($symbol, $source_name) {
$map = CelerityResourceMap::getNamedInstance($source_name);
$packaged = $map->getPackagedNamesForSymbols(array($symbol));
return $this->renderPackagedResources($map, $packaged);
}
public function renderResourcesOfType($type) {
$this->resolveResources();
$result = array();
foreach ($this->packaged as $source_name => $resource_names) {
$map = CelerityResourceMap::getNamedInstance($source_name);
$resources_of_type = array();
foreach ($resource_names as $resource_name) {
$resource_type = $map->getResourceTypeForName($resource_name);
if ($resource_type == $type) {
$resources_of_type[] = $resource_name;
}
}
$result[] = $this->renderPackagedResources($map, $resources_of_type);
}
return phutil_implode_html('', $result);
}
private function renderPackagedResources(
CelerityResourceMap $map,
array $resources) {
$output = array();
foreach ($resources as $name) {
if (isset($this->hasRendered[$name])) {
continue;
}
$this->hasRendered[$name] = true;
$output[] = $this->renderResource($map, $name);
}
return $output;
}
private function renderResource(
CelerityResourceMap $map,
$name) {
$uri = $this->getURI($map, $name);
$type = $map->getResourceTypeForName($name);
$multimeter = MultimeterControl::getInstance();
if ($multimeter) {
$event_type = MultimeterEvent::TYPE_STATIC_RESOURCE;
$multimeter->newEvent($event_type, 'rsrc.'.$name, 1);
}
switch ($type) {
case 'css':
return phutil_tag(
'link',
array(
'rel' => 'stylesheet',
'type' => 'text/css',
'href' => $uri,
));
case 'js':
return phutil_tag(
'script',
array(
'type' => 'text/javascript',
'src' => $uri,
),
'');
}
throw new Exception(
pht(
'Unable to render resource "%s", which has unknown type "%s".',
$name,
$type));
}
public function renderHTMLFooter() {
$data = array();
if ($this->metadata) {
$json_metadata = AphrontResponse::encodeJSONForHTTPResponse(
$this->metadata);
$this->metadata = array();
} else {
$json_metadata = '{}';
}
// Even if there is no metadata on the page, Javelin uses the mergeData()
// call to start dispatching the event queue.
$data[] = 'JX.Stratcom.mergeData('.$this->metadataBlock.', '.
$json_metadata.');';
$onload = array();
if ($this->behaviors) {
$behaviors = $this->behaviors;
$this->behaviors = array();
$higher_priority_names = array(
'refresh-csrf',
'aphront-basic-tokenizer',
'dark-console',
'history-install',
);
$higher_priority_behaviors = array_select_keys(
$behaviors,
$higher_priority_names);
foreach ($higher_priority_names as $name) {
unset($behaviors[$name]);
}
$behavior_groups = array(
$higher_priority_behaviors,
$behaviors,
);
foreach ($behavior_groups as $group) {
if (!$group) {
continue;
}
$group_json = AphrontResponse::encodeJSONForHTTPResponse(
$group);
$onload[] = 'JX.initBehaviors('.$group_json.')';
}
}
if ($onload) {
foreach ($onload as $func) {
$data[] = 'JX.onload(function(){'.$func.'});';
}
}
if ($data) {
$data = implode("\n", $data);
return self::renderInlineScript($data);
} else {
return '';
}
}
public static function renderInlineScript($data) {
if (stripos($data, '</script>') !== false) {
throw new Exception(
'Literal </script> is not allowed inside inline script.');
}
if (strpos($data, '<!') !== false) {
throw new Exception('Literal <! is not allowed inside inline script.');
}
// We don't use <![CDATA[ ]]> because it is ignored by HTML parsers. We
// would need to send the document with XHTML content type.
return phutil_tag(
'script',
array('type' => 'text/javascript'),
phutil_safe_html($data));
}
public function buildAjaxResponse($payload, $error = null) {
$response = array(
'error' => $error,
'payload' => $payload,
);
if ($this->metadata) {
$response['javelin_metadata'] = $this->metadata;
$this->metadata = array();
}
if ($this->behaviors) {
$response['javelin_behaviors'] = $this->behaviors;
$this->behaviors = array();
}
$this->resolveResources();
$resources = array();
foreach ($this->packaged as $source_name => $resource_names) {
$map = CelerityResourceMap::getNamedInstance($source_name);
foreach ($resource_names as $resource_name) {
$resources[] = $this->getURI($map, $resource_name);
}
}
if ($resources) {
$response['javelin_resources'] = $resources;
}
return $response;
}
public function getURI(
CelerityResourceMap $map,
$name,
$use_primary_domain = false) {
$uri = $map->getURIForName($name);
// In developer mode, we dump file modification times into the URI. When a
// page is reloaded in the browser, any resources brought in by Ajax calls
// do not trigger revalidation, so without this it's very difficult to get
// changes to Ajaxed-in CSS to work (you must clear your cache or rerun
// the map script). In production, we can assume the map script gets run
// after changes, and safely skip this.
if (PhabricatorEnv::getEnvConfig('phabricator.developer-mode')) {
$mtime = $map->getModifiedTimeForName($name);
$uri = preg_replace('@^/res/@', '/res/'.$mtime.'T/', $uri);
}
if ($use_primary_domain) {
return PhabricatorEnv::getURI($uri);
} else {
return PhabricatorEnv::getCDNURI($uri);
}
}
}
diff --git a/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php b/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
index 43891d0d07..223d974541 100644
--- a/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
+++ b/src/applications/drydock/blueprint/DrydockBlueprintImplementation.php
@@ -1,469 +1,469 @@
<?php
/**
* @task lease Lease Acquisition
* @task resource Resource Allocation
* @task log Logging
*/
abstract class DrydockBlueprintImplementation {
private $activeResource;
private $activeLease;
private $instance;
abstract public function getType();
abstract public function getInterface(
DrydockResource $resource,
DrydockLease $lease,
$type);
abstract public function isEnabled();
abstract public function getBlueprintName();
abstract public function getDescription();
public function getBlueprintClass() {
return get_class($this);
}
protected function loadLease($lease_id) {
// TODO: Get rid of this?
$query = id(new DrydockLeaseQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withIDs(array($lease_id))
->execute();
$lease = idx($query, $lease_id);
if (!$lease) {
throw new Exception("No such lease '{$lease_id}'!");
}
return $lease;
}
protected function getInstance() {
if (!$this->instance) {
throw new Exception(
'Attach the blueprint instance to the implementation.');
}
return $this->instance;
}
public function attachInstance(DrydockBlueprint $instance) {
$this->instance = $instance;
return $this;
}
public function getFieldSpecifications() {
return array();
}
public function getDetail($key, $default = null) {
return $this->getInstance()->getDetail($key, $default);
}
/* -( Lease Acquisition )-------------------------------------------------- */
/**
* @task lease
*/
final public function filterResource(
DrydockResource $resource,
DrydockLease $lease) {
$scope = $this->pushActiveScope($resource, $lease);
return $this->canAllocateLease($resource, $lease);
}
/**
* Enforce basic checks on lease/resource compatibility. Allows resources to
* reject leases if they are incompatible, even if the resource types match.
*
* For example, if a resource represents a 32-bit host, this method might
* reject leases that need a 64-bit host. If a resource represents a working
* copy of repository "X", this method might reject leases which need a
* working copy of repository "Y". Generally, although the main types of
* a lease and resource may match (e.g., both "host"), it may not actually be
* possible to satisfy the lease with a specific resource.
*
* This method generally should not enforce limits or perform capacity
* checks. Perform those in @{method:shouldAllocateLease} instead. It also
* should not perform actual acquisition of the lease; perform that in
* @{method:executeAcquireLease} instead.
*
* @param DrydockResource Candidiate resource to allocate the lease on.
* @param DrydockLease Pending lease that wants to allocate here.
* @return bool True if the resource and lease are compatible.
* @task lease
*/
abstract protected function canAllocateLease(
DrydockResource $resource,
DrydockLease $lease);
/**
* @task lease
*/
final public function allocateLease(
DrydockResource $resource,
DrydockLease $lease) {
$scope = $this->pushActiveScope($resource, $lease);
$this->log('Trying to Allocate Lease');
$lease->setStatus(DrydockLeaseStatus::STATUS_ACQUIRING);
$lease->setResourceID($resource->getID());
$lease->attachResource($resource);
$ephemeral_lease = id(clone $lease)->makeEphemeral();
$allocated = false;
$allocation_exception = null;
$resource->openTransaction();
$resource->beginReadLocking();
$resource->reload();
// TODO: Policy stuff.
$other_leases = id(new DrydockLease())->loadAllWhere(
'status IN (%Ld) AND resourceID = %d',
array(
DrydockLeaseStatus::STATUS_ACQUIRING,
DrydockLeaseStatus::STATUS_ACTIVE,
),
$resource->getID());
try {
$allocated = $this->shouldAllocateLease(
$resource,
$ephemeral_lease,
$other_leases);
} catch (Exception $ex) {
$allocation_exception = $ex;
}
if ($allocated) {
$lease->save();
}
$resource->endReadLocking();
if ($allocated) {
$resource->saveTransaction();
$this->log('Allocated Lease');
} else {
$resource->killTransaction();
$this->log('Failed to Allocate Lease');
}
if ($allocation_exception) {
$this->logException($allocation_exception);
}
return $allocated;
}
/**
* Enforce lease limits on resources. Allows resources to reject leases if
* they would become over-allocated by accepting them.
*
* For example, if a resource represents disk space, this method might check
* how much space the lease is asking for (say, 200MB) and how much space is
* left unallocated on the resource. It could grant the lease (return true)
* if it has enough remaining space (more than 200MB), and reject the lease
* (return false) if it does not (less than 200MB).
*
* A resource might also allow only exclusive leases. In this case it could
* accept a new lease (return true) if there are no active leases, or reject
* the new lease (return false) if there any other leases.
*
* A lock is held on the resource while this method executes to prevent
* multiple processes from allocating leases on the resource simultaneously.
* However, this means you should implement the method as cheaply as possible.
* In particular, do not perform any actual acquisition or setup in this
* method.
*
* If allocation is permitted, the lease will be moved to `ACQUIRING` status
* and @{method:executeAcquireLease} will be called to actually perform
* acquisition.
*
* General compatibility checks unrelated to resource limits and capacity are
* better implemented in @{method:canAllocateLease}, which serves as a
* cheap filter before lock acquisition.
*
* @param DrydockResource Candidate resource to allocate the lease on.
* @param DrydockLease Pending lease that wants to allocate here.
* @param list<DrydockLease> Other allocated and acquired leases on the
* resource. The implementation can inspect them
* to verify it can safely add the new lease.
* @return bool True to allocate the lease on the resource;
* false to reject it.
* @task lease
*/
abstract protected function shouldAllocateLease(
DrydockResource $resource,
DrydockLease $lease,
array $other_leases);
/**
* @task lease
*/
final public function acquireLease(
DrydockResource $resource,
DrydockLease $lease) {
$scope = $this->pushActiveScope($resource, $lease);
$this->log('Acquiring Lease');
$lease->setStatus(DrydockLeaseStatus::STATUS_ACTIVE);
$lease->setResourceID($resource->getID());
$lease->attachResource($resource);
$ephemeral_lease = id(clone $lease)->makeEphemeral();
try {
$this->executeAcquireLease($resource, $ephemeral_lease);
} catch (Exception $ex) {
$this->logException($ex);
throw $ex;
}
$lease->setAttributes($ephemeral_lease->getAttributes());
$lease->save();
$this->log('Acquired Lease');
}
/**
* Acquire and activate an allocated lease. Allows resources to peform setup
* as leases are brought online.
*
* Following a successful call to @{method:canAllocateLease}, a lease is moved
* to `ACQUIRING` status and this method is called after resource locks are
* released. Nothing is locked while this method executes; the implementation
* is free to perform expensive operations like writing files and directories,
* executing commands, etc.
*
* After this method executes, the lease status is moved to `ACTIVE` and the
* original leasee may access it.
*
* If acquisition fails, throw an exception.
*
* @param DrydockResource Resource to acquire a lease on.
* @param DrydockLease Lease to acquire.
* @return void
*/
abstract protected function executeAcquireLease(
DrydockResource $resource,
DrydockLease $lease);
final public function releaseLease(
DrydockResource $resource,
DrydockLease $lease) {
$scope = $this->pushActiveScope(null, $lease);
$released = false;
$lease->openTransaction();
$lease->beginReadLocking();
$lease->reload();
if ($lease->getStatus() == DrydockLeaseStatus::STATUS_ACTIVE) {
$lease->setStatus(DrydockLeaseStatus::STATUS_RELEASED);
$lease->save();
$released = true;
}
$lease->endReadLocking();
$lease->saveTransaction();
if (!$released) {
throw new Exception('Unable to release lease: lease not active!');
}
}
/* -( Resource Allocation )------------------------------------------------ */
public function canAllocateMoreResources(array $pool) {
return true;
}
abstract protected function executeAllocateResource(DrydockLease $lease);
final public function allocateResource(DrydockLease $lease) {
$scope = $this->pushActiveScope(null, $lease);
$this->log(
pht(
"Blueprint '%s': Allocating Resource for '%s'",
$this->getBlueprintClass(),
$lease->getLeaseName()));
try {
$resource = $this->executeAllocateResource($lease);
$this->validateAllocatedResource($resource);
} catch (Exception $ex) {
$this->logException($ex);
throw $ex;
}
return $resource;
}
/* -( Logging )------------------------------------------------------------ */
/**
* @task log
*/
protected function logException(Exception $ex) {
$this->log($ex->getMessage());
}
/**
* @task log
*/
protected function log($message) {
self::writeLog(
$this->activeResource,
$this->activeLease,
$message);
}
/**
* @task log
*/
public static function writeLog(
DrydockResource $resource = null,
DrydockLease $lease = null,
- $message) {
+ $message = null) {
$log = id(new DrydockLog())
->setEpoch(time())
->setMessage($message);
if ($resource) {
$log->setResourceID($resource->getID());
}
if ($lease) {
$log->setLeaseID($lease->getID());
}
$log->save();
}
public static function getAllBlueprintImplementations() {
static $list = null;
if ($list === null) {
$blueprints = id(new PhutilSymbolLoader())
->setType('class')
->setAncestorClass(__CLASS__)
->setConcreteOnly(true)
->selectAndLoadSymbols();
$list = ipull($blueprints, 'name', 'name');
foreach ($list as $class_name => $ignored) {
$list[$class_name] = newv($class_name, array());
}
}
return $list;
}
public static function getAllBlueprintImplementationsForResource($type) {
static $groups = null;
if ($groups === null) {
$groups = mgroup(self::getAllBlueprintImplementations(), 'getType');
}
return idx($groups, $type, array());
}
public static function getNamedImplementation($class) {
return idx(self::getAllBlueprintImplementations(), $class);
}
protected function newResourceTemplate($name) {
$resource = id(new DrydockResource())
->setBlueprintPHID($this->getInstance()->getPHID())
->setBlueprintClass($this->getBlueprintClass())
->setType($this->getType())
->setStatus(DrydockResourceStatus::STATUS_PENDING)
->setName($name)
->save();
$this->activeResource = $resource;
$this->log(
pht(
"Blueprint '%s': Created New Template",
$this->getBlueprintClass()));
return $resource;
}
/**
* Sanity checks that the blueprint is implemented properly.
*/
private function validateAllocatedResource($resource) {
$blueprint = $this->getBlueprintClass();
if (!($resource instanceof DrydockResource)) {
throw new Exception(
"Blueprint '{$blueprint}' is not properly implemented: ".
"executeAllocateResource() must return an object of type ".
"DrydockResource or throw, but returned something else.");
}
$current_status = $resource->getStatus();
$req_status = DrydockResourceStatus::STATUS_OPEN;
if ($current_status != $req_status) {
$current_name = DrydockResourceStatus::getNameForStatus($current_status);
$req_name = DrydockResourceStatus::getNameForStatus($req_status);
throw new Exception(
"Blueprint '{$blueprint}' is not properly implemented: ".
"executeAllocateResource() must return a DrydockResource with ".
"status '{$req_name}', but returned one with status ".
"'{$current_name}'.");
}
}
private function pushActiveScope(
DrydockResource $resource = null,
DrydockLease $lease = null) {
if (($this->activeResource !== null) ||
($this->activeLease !== null)) {
throw new Exception('There is already an active resource or lease!');
}
$this->activeResource = $resource;
$this->activeLease = $lease;
return new DrydockBlueprintScopeGuard($this);
}
public function popActiveScope() {
$this->activeResource = null;
$this->activeLease = null;
}
}
diff --git a/src/applications/people/storage/PhabricatorUserLog.php b/src/applications/people/storage/PhabricatorUserLog.php
index acdd7b1efe..1f14a27e4c 100644
--- a/src/applications/people/storage/PhabricatorUserLog.php
+++ b/src/applications/people/storage/PhabricatorUserLog.php
@@ -1,211 +1,211 @@
<?php
final class PhabricatorUserLog extends PhabricatorUserDAO
implements PhabricatorPolicyInterface {
const ACTION_LOGIN = 'login';
const ACTION_LOGIN_PARTIAL = 'login-partial';
const ACTION_LOGIN_FULL = 'login-full';
const ACTION_LOGOUT = 'logout';
const ACTION_LOGIN_FAILURE = 'login-fail';
const ACTION_LOGIN_LEGALPAD = 'login-legalpad';
const ACTION_RESET_PASSWORD = 'reset-pass';
const ACTION_CREATE = 'create';
const ACTION_EDIT = 'edit';
const ACTION_ADMIN = 'admin';
const ACTION_SYSTEM_AGENT = 'system-agent';
const ACTION_DISABLE = 'disable';
const ACTION_APPROVE = 'approve';
const ACTION_DELETE = 'delete';
const ACTION_CONDUIT_CERTIFICATE = 'conduit-cert';
const ACTION_CONDUIT_CERTIFICATE_FAILURE = 'conduit-cert-fail';
const ACTION_EMAIL_PRIMARY = 'email-primary';
const ACTION_EMAIL_REMOVE = 'email-remove';
const ACTION_EMAIL_ADD = 'email-add';
const ACTION_EMAIL_VERIFY = 'email-verify';
const ACTION_EMAIL_REASSIGN = 'email-reassign';
const ACTION_CHANGE_PASSWORD = 'change-password';
const ACTION_CHANGE_USERNAME = 'change-username';
const ACTION_ENTER_HISEC = 'hisec-enter';
const ACTION_EXIT_HISEC = 'hisec-exit';
const ACTION_FAIL_HISEC = 'hisec-fail';
const ACTION_MULTI_ADD = 'multi-add';
const ACTION_MULTI_REMOVE = 'multi-remove';
protected $actorPHID;
protected $userPHID;
protected $action;
protected $oldValue;
protected $newValue;
protected $details = array();
protected $remoteAddr;
protected $session;
public static function getActionTypeMap() {
return array(
self::ACTION_LOGIN => pht('Login'),
self::ACTION_LOGIN_PARTIAL => pht('Login: Partial Login'),
self::ACTION_LOGIN_FULL => pht('Login: Upgrade to Full'),
self::ACTION_LOGIN_FAILURE => pht('Login: Failure'),
self::ACTION_LOGIN_LEGALPAD =>
pht('Login: Signed Required Legalpad Documents'),
self::ACTION_LOGOUT => pht('Logout'),
self::ACTION_RESET_PASSWORD => pht('Reset Password'),
self::ACTION_CREATE => pht('Create Account'),
self::ACTION_EDIT => pht('Edit Account'),
self::ACTION_ADMIN => pht('Add/Remove Administrator'),
self::ACTION_SYSTEM_AGENT => pht('Add/Remove System Agent'),
self::ACTION_DISABLE => pht('Enable/Disable'),
self::ACTION_APPROVE => pht('Approve Registration'),
self::ACTION_DELETE => pht('Delete User'),
self::ACTION_CONDUIT_CERTIFICATE
=> pht('Conduit: Read Certificate'),
self::ACTION_CONDUIT_CERTIFICATE_FAILURE
=> pht('Conduit: Read Certificate Failure'),
self::ACTION_EMAIL_PRIMARY => pht('Email: Change Primary'),
self::ACTION_EMAIL_ADD => pht('Email: Add Address'),
self::ACTION_EMAIL_REMOVE => pht('Email: Remove Address'),
self::ACTION_EMAIL_VERIFY => pht('Email: Verify'),
self::ACTION_EMAIL_REASSIGN => pht('Email: Reassign'),
self::ACTION_CHANGE_PASSWORD => pht('Change Password'),
self::ACTION_CHANGE_USERNAME => pht('Change Username'),
self::ACTION_ENTER_HISEC => pht('Hisec: Enter'),
self::ACTION_EXIT_HISEC => pht('Hisec: Exit'),
self::ACTION_FAIL_HISEC => pht('Hisec: Failed Attempt'),
self::ACTION_MULTI_ADD => pht('Multi-Factor: Add Factor'),
self::ACTION_MULTI_REMOVE => pht('Multi-Factor: Remove Factor'),
);
}
public static function initializeNewLog(
PhabricatorUser $actor = null,
- $object_phid,
- $action) {
+ $object_phid = null,
+ $action = null) {
$log = new PhabricatorUserLog();
if ($actor) {
$log->setActorPHID($actor->getPHID());
if ($actor->hasSession()) {
$session = $actor->getSession();
// NOTE: This is a hash of the real session value, so it's safe to
// store it directly in the logs.
$log->setSession($session->getSessionKey());
}
}
$log->setUserPHID((string)$object_phid);
$log->setAction($action);
$log->remoteAddr = idx($_SERVER, 'REMOTE_ADDR', '');
return $log;
}
public static function loadRecentEventsFromThisIP($action, $timespan) {
return id(new PhabricatorUserLog())->loadAllWhere(
'action = %s AND remoteAddr = %s AND dateCreated > %d
ORDER BY dateCreated DESC',
$action,
idx($_SERVER, 'REMOTE_ADDR'),
time() - $timespan);
}
public function save() {
$this->details['host'] = php_uname('n');
$this->details['user_agent'] = AphrontRequest::getHTTPHeader('User-Agent');
return parent::save();
}
protected function getConfiguration() {
return array(
self::CONFIG_SERIALIZATION => array(
'oldValue' => self::SERIALIZATION_JSON,
'newValue' => self::SERIALIZATION_JSON,
'details' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'actorPHID' => 'phid?',
'action' => 'text64',
'remoteAddr' => 'text64',
'session' => 'bytes40?',
),
self::CONFIG_KEY_SCHEMA => array(
'actorPHID' => array(
'columns' => array('actorPHID', 'dateCreated'),
),
'userPHID' => array(
'columns' => array('userPHID', 'dateCreated'),
),
'action' => array(
'columns' => array('action', 'dateCreated'),
),
'dateCreated' => array(
'columns' => array('dateCreated'),
),
'remoteAddr' => array(
'columns' => array('remoteAddr', 'dateCreated'),
),
'session' => array(
'columns' => array('session', 'dateCreated'),
),
),
) + parent::getConfiguration();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return PhabricatorPolicies::POLICY_NOONE;
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
if ($viewer->getIsAdmin()) {
return true;
}
$viewer_phid = $viewer->getPHID();
if ($viewer_phid) {
$user_phid = $this->getUserPHID();
if ($viewer_phid == $user_phid) {
return true;
}
$actor_phid = $this->getActorPHID();
if ($viewer_phid == $actor_phid) {
return true;
}
}
return false;
}
public function describeAutomaticCapability($capability) {
return array(
pht('Users can view their activity and activity that affects them.'),
pht('Administrators can always view all activity.'),
);
}
}
diff --git a/src/applications/phragment/storage/PhragmentFragment.php b/src/applications/phragment/storage/PhragmentFragment.php
index 574283d7a7..d58be033c0 100644
--- a/src/applications/phragment/storage/PhragmentFragment.php
+++ b/src/applications/phragment/storage/PhragmentFragment.php
@@ -1,351 +1,351 @@
<?php
final class PhragmentFragment extends PhragmentDAO
implements PhabricatorPolicyInterface {
protected $path;
protected $depth;
protected $latestVersionPHID;
protected $viewPolicy;
protected $editPolicy;
private $latestVersion = self::ATTACHABLE;
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_COLUMN_SCHEMA => array(
'path' => 'text128',
'depth' => 'uint32',
'latestVersionPHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_path' => array(
'columns' => array('path'),
'unique' => true,
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
PhragmentFragmentPHIDType::TYPECONST);
}
public function getURI() {
return '/phragment/browse/'.$this->getPath();
}
public function getName() {
return basename($this->path);
}
public function getFile() {
return $this->assertAttached($this->file);
}
public function attachFile(PhabricatorFile $file) {
return $this->file = $file;
}
public function isDirectory() {
return $this->latestVersionPHID === null;
}
public function isDeleted() {
return $this->getLatestVersion()->getFilePHID() === null;
}
public function getLatestVersion() {
if ($this->latestVersionPHID === null) {
return null;
}
return $this->assertAttached($this->latestVersion);
}
public function attachLatestVersion(PhragmentFragmentVersion $version) {
return $this->latestVersion = $version;
}
/* -( Updating ) --------------------------------------------------------- */
/**
* Create a new fragment from a file.
*/
public static function createFromFile(
PhabricatorUser $viewer,
PhabricatorFile $file = null,
- $path,
- $view_policy,
- $edit_policy) {
+ $path = null,
+ $view_policy = null,
+ $edit_policy = null) {
$fragment = id(new PhragmentFragment());
$fragment->setPath($path);
$fragment->setDepth(count(explode('/', $path)));
$fragment->setLatestVersionPHID(null);
$fragment->setViewPolicy($view_policy);
$fragment->setEditPolicy($edit_policy);
$fragment->save();
// Directory fragments have no versions associated with them, so we
// just return the fragment at this point.
if ($file === null) {
return $fragment;
}
if ($file->getMimeType() === 'application/zip') {
$fragment->updateFromZIP($viewer, $file);
} else {
$fragment->updateFromFile($viewer, $file);
}
return $fragment;
}
/**
* Set the specified file as the next version for the fragment.
*/
public function updateFromFile(
PhabricatorUser $viewer,
PhabricatorFile $file) {
$existing = id(new PhragmentFragmentVersionQuery())
->setViewer($viewer)
->withFragmentPHIDs(array($this->getPHID()))
->execute();
$sequence = count($existing);
$this->openTransaction();
$version = id(new PhragmentFragmentVersion());
$version->setSequence($sequence);
$version->setFragmentPHID($this->getPHID());
$version->setFilePHID($file->getPHID());
$version->save();
$this->setLatestVersionPHID($version->getPHID());
$this->save();
$this->saveTransaction();
$file->attachToObject($version->getPHID());
}
/**
* Apply the specified ZIP archive onto the fragment, removing
* and creating fragments as needed.
*/
public function updateFromZIP(
PhabricatorUser $viewer,
PhabricatorFile $file) {
if ($file->getMimeType() !== 'application/zip') {
throw new Exception("File must have mimetype 'application/zip'");
}
// First apply the ZIP as normal.
$this->updateFromFile($viewer, $file);
// Ensure we have ZIP support.
$zip = null;
try {
$zip = new ZipArchive();
} catch (Exception $e) {
// The server doesn't have php5-zip, so we can't do recursive updates.
return;
}
$temp = new TempFile();
Filesystem::writeFile($temp, $file->loadFileData());
if (!$zip->open($temp)) {
throw new Exception('Unable to open ZIP');
}
// Get all of the paths and their data from the ZIP.
$mappings = array();
for ($i = 0; $i < $zip->numFiles; $i++) {
$path = trim($zip->getNameIndex($i), '/');
$stream = $zip->getStream($path);
$data = null;
// If the stream is false, then it is a directory entry. We leave
// $data set to null for directories so we know not to create a
// version entry for them.
if ($stream !== false) {
$data = stream_get_contents($stream);
fclose($stream);
}
$mappings[$path] = $data;
}
// We need to detect any directories that are in the ZIP folder that
// aren't explicitly noted in the ZIP. This can happen if the file
// entries in the ZIP look like:
//
// * something/blah.png
// * something/other.png
// * test.png
//
// Where there is no explicit "something/" entry.
foreach ($mappings as $path_key => $data) {
if ($data === null) {
continue;
}
$directory = dirname($path_key);
while ($directory !== '.') {
if (!array_key_exists($directory, $mappings)) {
$mappings[$directory] = null;
}
if (dirname($directory) === $directory) {
// dirname() will not reduce this directory any further; to
// prevent infinite loop we just break out here.
break;
}
$directory = dirname($directory);
}
}
// Adjust the paths relative to this fragment so we can look existing
// fragments up in the DB.
$base_path = $this->getPath();
$paths = array();
foreach ($mappings as $p => $data) {
$paths[] = $base_path.'/'.$p;
}
// FIXME: What happens when a child exists, but the current user
// can't see it. We're going to create a new child with the exact
// same path and then bad things will happen.
$children = id(new PhragmentFragmentQuery())
->setViewer($viewer)
->needLatestVersion(true)
->withLeadingPath($this->getPath().'/')
->execute();
$children = mpull($children, null, 'getPath');
// Iterate over the existing fragments.
foreach ($children as $full_path => $child) {
$path = substr($full_path, strlen($base_path) + 1);
if (array_key_exists($path, $mappings)) {
if ($child->isDirectory() && $mappings[$path] === null) {
// Don't create a version entry for a directory
// (unless it's been converted into a file).
continue;
}
// The file is being updated.
$file = PhabricatorFile::newFromFileData(
$mappings[$path],
array('name' => basename($path)));
$child->updateFromFile($viewer, $file);
} else {
// The file is being deleted.
$child->deleteFile($viewer);
}
}
// Iterate over the mappings to find new files.
foreach ($mappings as $path => $data) {
if (!array_key_exists($base_path.'/'.$path, $children)) {
// The file is being created. If the data is null,
// then this is explicitly a directory being created.
$file = null;
if ($mappings[$path] !== null) {
$file = PhabricatorFile::newFromFileData(
$mappings[$path],
array('name' => basename($path)));
}
self::createFromFile(
$viewer,
$file,
$base_path.'/'.$path,
$this->getViewPolicy(),
$this->getEditPolicy());
}
}
}
/**
* Delete the contents of the specified fragment.
*/
public function deleteFile(PhabricatorUser $viewer) {
$existing = id(new PhragmentFragmentVersionQuery())
->setViewer($viewer)
->withFragmentPHIDs(array($this->getPHID()))
->execute();
$sequence = count($existing);
$this->openTransaction();
$version = id(new PhragmentFragmentVersion());
$version->setSequence($sequence);
$version->setFragmentPHID($this->getPHID());
$version->setFilePHID(null);
$version->save();
$this->setLatestVersionPHID($version->getPHID());
$this->save();
$this->saveTransaction();
}
/* -( Utility ) ---------------------------------------------------------- */
public function getFragmentMappings(
PhabricatorUser $viewer,
$base_path) {
$children = id(new PhragmentFragmentQuery())
->setViewer($viewer)
->needLatestVersion(true)
->withLeadingPath($this->getPath().'/')
->withDepths(array($this->getDepth() + 1))
->execute();
if (count($children) === 0) {
$path = substr($this->getPath(), strlen($base_path) + 1);
return array($path => $this);
} else {
$mappings = array();
foreach ($children as $child) {
$child_mappings = $child->getFragmentMappings(
$viewer,
$base_path);
foreach ($child_mappings as $key => $value) {
$mappings[$key] = $value;
}
}
return $mappings;
}
}
/* -( Policy Interface )--------------------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
switch ($capability) {
case PhabricatorPolicyCapability::CAN_VIEW:
return $this->getViewPolicy();
case PhabricatorPolicyCapability::CAN_EDIT:
return $this->getEditPolicy();
}
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
public function describeAutomaticCapability($capability) {
return null;
}
}
diff --git a/src/view/layout/AphrontSideNavFilterView.php b/src/view/layout/AphrontSideNavFilterView.php
index 4f4c0803b8..fe8025026b 100644
--- a/src/view/layout/AphrontSideNavFilterView.php
+++ b/src/view/layout/AphrontSideNavFilterView.php
@@ -1,331 +1,326 @@
<?php
/**
* Provides a navigation sidebar. For example:
*
* $nav = new AphrontSideNavFilterView();
* $nav
* ->setBaseURI($some_uri)
* ->addLabel('Cats')
* ->addFilter('meow', 'Meow')
* ->addFilter('purr', 'Purr')
* ->addLabel('Dogs')
* ->addFilter('woof', 'Woof')
* ->addFilter('bark', 'Bark');
* $valid_filter = $nav->selectFilter($user_selection, $default = 'meow');
*
*/
final class AphrontSideNavFilterView extends AphrontView {
private $items = array();
private $baseURI;
private $selectedFilter = false;
private $flexible;
private $collapsed = false;
private $active;
private $menu;
private $crumbs;
private $classes = array();
private $menuID;
private $iconNav;
public function setMenuID($menu_id) {
$this->menuID = $menu_id;
return $this;
}
public function getMenuID() {
return $this->menuID;
}
public function __construct() {
$this->menu = new PHUIListView();
}
public function addClass($class) {
$this->classes[] = $class;
return $this;
}
public static function newFromMenu(PHUIListView $menu) {
$object = new AphrontSideNavFilterView();
$object->setBaseURI(new PhutilURI('/'));
$object->menu = $menu;
return $object;
}
public function setCrumbs(PHUICrumbsView $crumbs) {
$this->crumbs = $crumbs;
return $this;
}
public function getCrumbs() {
return $this->crumbs;
}
public function setIconNav($nav) {
$this->iconNav = $nav;
return $this;
}
public function setActive($active) {
$this->active = $active;
return $this;
}
public function setFlexible($flexible) {
$this->flexible = $flexible;
return $this;
}
public function setCollapsed($collapsed) {
$this->collapsed = $collapsed;
return $this;
}
public function getMenuView() {
return $this->menu;
}
public function addMenuItem(PHUIListItemView $item) {
$this->menu->addMenuItem($item);
return $this;
}
public function getMenu() {
return $this->menu;
}
public function addFilter($key, $name, $uri = null) {
return $this->addThing(
$key, $name, $uri, PHUIListItemView::TYPE_LINK);
}
public function addIcon($key, $name, $icon, $image = null, $uri = null) {
if (!$uri) {
$href = clone $this->baseURI;
$href->setPath(rtrim($href->getPath().$key, '/').'/');
$href = (string)$href;
} else {
$href = $uri;
}
$item = id(new PHUIListItemView())
->setKey($key)
->setRenderNameAsTooltip(true)
->setType(PHUIListItemView::TYPE_ICON_NAV)
->setIcon($icon)
->setHref($href)
->setName($name)
->setProfileImage($image);
return $this->addMenuItem($item);
}
public function addButton($key, $name, $uri = null) {
return $this->addThing(
$key, $name, $uri, PHUIListItemView::TYPE_BUTTON);
}
- private function addThing(
- $key,
- $name,
- $uri = null,
- $type) {
-
+ private function addThing($key, $name, $uri, $type) {
$item = id(new PHUIListItemView())
->setName($name)
->setType($type);
if (strlen($key)) {
$item->setKey($key);
}
if ($uri) {
$item->setHref($uri);
} else {
$href = clone $this->baseURI;
$href->setPath(rtrim($href->getPath().$key, '/').'/');
$href = (string)$href;
$item->setHref($href);
}
return $this->addMenuItem($item);
}
public function addCustomBlock($block) {
$this->menu->addMenuItem(
id(new PHUIListItemView())
->setType(PHUIListItemView::TYPE_CUSTOM)
->appendChild($block));
return $this;
}
public function addLabel($name) {
return $this->addMenuItem(
id(new PHUIListItemView())
->setType(PHUIListItemView::TYPE_LABEL)
->setName($name));
}
public function setBaseURI(PhutilURI $uri) {
$this->baseURI = $uri;
return $this;
}
public function getBaseURI() {
return $this->baseURI;
}
public function selectFilter($key, $default = null) {
$this->selectedFilter = $default;
if ($this->menu->getItem($key) && strlen($key)) {
$this->selectedFilter = $key;
}
return $this->selectedFilter;
}
public function getSelectedFilter() {
return $this->selectedFilter;
}
public function render() {
if ($this->menu->getItems()) {
if (!$this->baseURI) {
throw new Exception(pht('Call setBaseURI() before render()!'));
}
if ($this->selectedFilter === false) {
throw new Exception(pht('Call selectFilter() before render()!'));
}
}
if ($this->selectedFilter !== null) {
$selected_item = $this->menu->getItem($this->selectedFilter);
if ($selected_item) {
$selected_item->addClass('phui-list-item-selected');
}
}
require_celerity_resource('phabricator-side-menu-view-css');
return $this->renderFlexNav();
}
private function renderFlexNav() {
$user = $this->user;
require_celerity_resource('phabricator-nav-view-css');
$nav_classes = array();
$nav_classes[] = 'phabricator-nav';
if ($this->iconNav) {
$nav_classes[] = 'phabricator-icon-nav';
}
$nav_id = null;
$drag_id = null;
$content_id = celerity_generate_unique_node_id();
$local_id = null;
$background_id = null;
$local_menu = null;
$main_id = celerity_generate_unique_node_id();
if ($this->flexible) {
$drag_id = celerity_generate_unique_node_id();
$flex_bar = phutil_tag(
'div',
array(
'class' => 'phabricator-nav-drag',
'id' => $drag_id,
),
'');
} else {
$flex_bar = null;
}
$nav_menu = null;
if ($this->menu->getItems()) {
$local_id = celerity_generate_unique_node_id();
$background_id = celerity_generate_unique_node_id();
if (!$this->collapsed) {
$nav_classes[] = 'has-local-nav';
}
$menu_background = phutil_tag(
'div',
array(
'class' => 'phabricator-nav-column-background',
'id' => $background_id,
),
'');
$local_menu = array(
$menu_background,
phutil_tag(
'div',
array(
'class' => 'phabricator-nav-local phabricator-side-menu',
'id' => $local_id,
),
$this->menu->setID($this->getMenuID())),
);
}
$crumbs = null;
if ($this->crumbs) {
$crumbs = $this->crumbs->render();
$nav_classes[] = 'has-crumbs';
}
if ($this->flexible) {
if (!$this->collapsed) {
$nav_classes[] = 'has-drag-nav';
}
Javelin::initBehavior(
'phabricator-nav',
array(
'mainID' => $main_id,
'localID' => $local_id,
'dragID' => $drag_id,
'contentID' => $content_id,
'backgroundID' => $background_id,
'collapsed' => $this->collapsed,
));
if ($this->active) {
Javelin::initBehavior(
'phabricator-active-nav',
array(
'localID' => $local_id,
));
}
}
$nav_classes = array_merge($nav_classes, $this->classes);
return phutil_tag(
'div',
array(
'class' => implode(' ', $nav_classes),
'id' => $main_id,
),
array(
$local_menu,
$flex_bar,
phutil_tag(
'div',
array(
'class' => 'phabricator-nav-content plb',
'id' => $content_id,
),
array(
$crumbs,
$this->renderChildren(),
)),
));
}
}

File Metadata

Mime Type
text/x-diff
Expires
Sun, Nov 30, 9:28 PM (12 h, 17 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
429824
Default Alt Text
(48 KB)

Event Timeline