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/subscriptions/events/PhabricatorSubscriptionsUIEventListener.php | src/applications/subscriptions/events/PhabricatorSubscriptionsUIEventListener.php | <?php
final class PhabricatorSubscriptionsUIEventListener
extends PhabricatorEventListener {
public function register() {
$this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS);
$this->listen(PhabricatorEventType::TYPE_UI_WILLRENDERPROPERTIES);
}
public function handleEvent(PhutilEvent $event) {
$object = $event->getValue('object');
switch ($event->getType()) {
case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS:
$this->handleActionEvent($event);
break;
case PhabricatorEventType::TYPE_UI_WILLRENDERPROPERTIES:
// Hacky solution so that property list view on Diffusion
// commits shows build status, but not Projects, Subscriptions,
// or Tokens.
if ($object instanceof PhabricatorRepositoryCommit) {
return;
}
$this->handlePropertyEvent($event);
break;
}
}
private function handleActionEvent($event) {
$user = $event->getUser();
$user_phid = $user->getPHID();
$object = $event->getValue('object');
if (!$object || !$object->getPHID()) {
// No object, or the object has no PHID yet. No way to subscribe.
return;
}
if (!($object instanceof PhabricatorSubscribableInterface)) {
// This object isn't subscribable.
return;
}
$src_phid = $object->getPHID();
$subscribed_type = PhabricatorObjectHasSubscriberEdgeType::EDGECONST;
$muted_type = PhabricatorMutedByEdgeType::EDGECONST;
$edges = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(array($src_phid))
->withEdgeTypes(
array(
$subscribed_type,
$muted_type,
))
->withDestinationPHIDs(array($user_phid))
->execute();
if ($user_phid) {
$is_subscribed = isset($edges[$src_phid][$subscribed_type][$user_phid]);
$is_muted = isset($edges[$src_phid][$muted_type][$user_phid]);
} else {
$is_subscribed = false;
$is_muted = false;
}
if ($user_phid && $object->isAutomaticallySubscribed($user_phid)) {
$sub_action = id(new PhabricatorActionView())
->setWorkflow(true)
->setDisabled(true)
->setRenderAsForm(true)
->setHref('/subscriptions/add/'.$object->getPHID().'/')
->setName(pht('Automatically Subscribed'))
->setIcon('fa-check-circle lightgreytext');
} else {
if ($is_subscribed) {
$sub_action = id(new PhabricatorActionView())
->setWorkflow(true)
->setRenderAsForm(true)
->setHref('/subscriptions/delete/'.$object->getPHID().'/')
->setName(pht('Unsubscribe'))
->setIcon('fa-minus-circle');
} else {
$sub_action = id(new PhabricatorActionView())
->setWorkflow(true)
->setRenderAsForm(true)
->setHref('/subscriptions/add/'.$object->getPHID().'/')
->setName(pht('Subscribe'))
->setIcon('fa-plus-circle');
}
if (!$user->isLoggedIn()) {
$sub_action->setDisabled(true);
}
}
$mute_action = id(new PhabricatorActionView())
->setWorkflow(true)
->setHref('/subscriptions/mute/'.$object->getPHID().'/')
->setDisabled(!$user_phid);
if (!$is_muted) {
$mute_action
->setName(pht('Mute Notifications'))
->setIcon('fa-volume-up');
} else {
$mute_action
->setName(pht('Unmute Notifications'))
->setIcon('fa-volume-off')
->setColor(PhabricatorActionView::RED);
}
$actions = $event->getValue('actions');
$actions[] = $sub_action;
$actions[] = $mute_action;
$event->setValue('actions', $actions);
}
private function handlePropertyEvent($event) {
$user = $event->getUser();
$object = $event->getValue('object');
if (!$object || !$object->getPHID()) {
// No object, or the object has no PHID yet..
return;
}
if (!($object instanceof PhabricatorSubscribableInterface)) {
// This object isn't subscribable.
return;
}
$subscribers = PhabricatorSubscribersQuery::loadSubscribersForPHID(
$object->getPHID());
if ($subscribers) {
$handles = id(new PhabricatorHandleQuery())
->setViewer($user)
->withPHIDs($subscribers)
->execute();
} else {
$handles = array();
}
$sub_view = id(new SubscriptionListStringBuilder())
->setObjectPHID($object->getPHID())
->setHandles($handles)
->buildPropertyString();
$view = $event->getValue('view');
$view->addProperty(pht('Subscribers'), $sub_view);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/subscriptions/view/SubscriptionListDialogBuilder.php | src/applications/subscriptions/view/SubscriptionListDialogBuilder.php | <?php
final class SubscriptionListDialogBuilder extends Phobject {
private $viewer;
private $handles;
private $objectPHID;
private $title;
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
public function getViewer() {
return $this->viewer;
}
public function setHandles(array $handles) {
assert_instances_of($handles, 'PhabricatorObjectHandle');
$this->handles = $handles;
return $this;
}
public function getHandles() {
return $this->handles;
}
public function setObjectPHID($object_phid) {
$this->objectPHID = $object_phid;
return $this;
}
public function getObjectPHID() {
return $this->objectPHID;
}
public function setTitle($title) {
$this->title = $title;
return $this;
}
public function getTitle() {
return $this->title;
}
public function buildDialog() {
$phid = $this->getObjectPHID();
$handles = $this->getHandles();
$object_handle = $handles[$phid];
unset($handles[$phid]);
return id(new AphrontDialogView())
->setUser($this->getViewer())
->setWidth(AphrontDialogView::WIDTH_FORM)
->setTitle($this->getTitle())
->setObjectList($this->buildBody($this->getViewer(), $handles))
->addCancelButton($object_handle->getURI(), pht('Close'));
}
private function buildBody(PhabricatorUser $viewer, $handles) {
$list = id(new PHUIObjectItemListView())
->setUser($viewer);
foreach ($handles as $handle) {
$item = id(new PHUIObjectItemView())
->setHeader($handle->getFullName())
->setHref($handle->getURI())
->setDisabled($handle->isDisabled());
if ($handle->getImageURI()) {
$item->setImageURI($handle->getImageURI());
}
$list->addItem($item);
}
return $list;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/subscriptions/view/SubscriptionListStringBuilder.php | src/applications/subscriptions/view/SubscriptionListStringBuilder.php | <?php
final class SubscriptionListStringBuilder extends Phobject {
private $handles;
private $objectPHID;
public function setHandles(array $handles) {
assert_instances_of($handles, 'PhabricatorObjectHandle');
$this->handles = $handles;
return $this;
}
public function getHandles() {
return $this->handles;
}
public function setObjectPHID($object_phid) {
$this->objectPHID = $object_phid;
return $this;
}
public function getObjectPHID() {
return $this->objectPHID;
}
public function buildTransactionString($change_type) {
$handles = $this->getHandles();
if (!$handles) {
return;
}
$list_uri = '/subscriptions/transaction/'.
$change_type.'/'.
$this->getObjectPHID().'/';
return $this->buildString($list_uri);
}
public function buildPropertyString() {
$handles = $this->getHandles();
if (!$handles) {
return phutil_tag('em', array(), pht('None'));
}
$list_uri = '/subscriptions/list/'.$this->getObjectPHID().'/';
return $this->buildString($list_uri);
}
private function buildString($list_uri) {
$handles = $this->getHandles();
// Always show this many subscribers.
$show_count = 3;
$subscribers_count = count($handles);
// It looks a bit silly to render "a, b, c, and 1 other", since we could
// have just put that other subscriber there in place of the "1 other"
// link. Instead, render "a, b, c, d" in this case, and then when we get one
// more render "a, b, c, and 2 others".
if ($subscribers_count <= ($show_count + 1)) {
return phutil_implode_html(', ', mpull($handles, 'renderHovercardLink'));
}
$show = array_slice($handles, 0, $show_count);
$show = array_values($show);
$not_shown_count = $subscribers_count - $show_count;
$not_shown_txt = pht('%d other(s)', $not_shown_count);
$not_shown_link = javelin_tag(
'a',
array(
'href' => $list_uri,
'sigil' => 'workflow',
),
$not_shown_txt);
return pht(
'%s, %s, %s and %s',
$show[0]->renderLink(),
$show[1]->renderLink(),
$show[2]->renderLink(),
$not_shown_link);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/subscriptions/herald/PhabricatorSubscriptionsAddSelfHeraldAction.php | src/applications/subscriptions/herald/PhabricatorSubscriptionsAddSelfHeraldAction.php | <?php
final class PhabricatorSubscriptionsAddSelfHeraldAction
extends PhabricatorSubscriptionsHeraldAction {
const ACTIONCONST = 'subscribers.self.add';
public function getHeraldActionName() {
return pht('Add me as a subscriber');
}
public function supportsRuleType($rule_type) {
return ($rule_type == HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
}
public function applyEffect($object, HeraldEffect $effect) {
$phid = $effect->getRule()->getAuthorPHID();
return $this->applySubscribe(array($phid), $is_add = true);
}
public function getHeraldActionStandardType() {
return self::STANDARD_NONE;
}
public function renderActionDescription($value) {
return pht('Add rule author as subscriber.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/subscriptions/herald/HeraldSubscribersField.php | src/applications/subscriptions/herald/HeraldSubscribersField.php | <?php
final class HeraldSubscribersField extends HeraldField {
const FIELDCONST = 'cc';
public function getHeraldFieldName() {
return pht('Subscribers');
}
public function getFieldGroupKey() {
return HeraldSupportFieldGroup::FIELDGROUPKEY;
}
public function supportsObject($object) {
return ($object instanceof PhabricatorSubscribableInterface);
}
public function getHeraldFieldValue($object) {
$phid = $object->getPHID();
return PhabricatorSubscribersQuery::loadSubscribersForPHID($phid);
}
protected function getHeraldFieldStandardType() {
return self::STANDARD_PHID_LIST;
}
protected function getDatasource() {
return new PhabricatorProjectOrUserDatasource();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/subscriptions/herald/PhabricatorSubscriptionsRemoveSubscribersHeraldAction.php | src/applications/subscriptions/herald/PhabricatorSubscriptionsRemoveSubscribersHeraldAction.php | <?php
final class PhabricatorSubscriptionsRemoveSubscribersHeraldAction
extends PhabricatorSubscriptionsHeraldAction {
const ACTIONCONST = 'subscribers.remove';
public function getHeraldActionName() {
return pht('Remove subscribers');
}
public function supportsRuleType($rule_type) {
return ($rule_type != HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
}
public function applyEffect($object, HeraldEffect $effect) {
return $this->applySubscribe($effect->getTarget(), $is_add = false);
}
public function getHeraldActionStandardType() {
return self::STANDARD_PHID_LIST;
}
protected function getDatasource() {
return new PhabricatorMetaMTAMailableDatasource();
}
public function renderActionDescription($value) {
return pht('Remove subscribers: %s.', $this->renderHandleList($value));
}
public function getPHIDsAffectedByAction(HeraldActionRecord $record) {
return $record->getTarget();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/subscriptions/herald/PhabricatorSubscriptionsAddSubscribersHeraldAction.php | src/applications/subscriptions/herald/PhabricatorSubscriptionsAddSubscribersHeraldAction.php | <?php
final class PhabricatorSubscriptionsAddSubscribersHeraldAction
extends PhabricatorSubscriptionsHeraldAction {
const ACTIONCONST = 'subscribers.add';
public function getHeraldActionName() {
return pht('Add subscribers');
}
public function supportsRuleType($rule_type) {
return ($rule_type != HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
}
public function applyEffect($object, HeraldEffect $effect) {
return $this->applySubscribe($effect->getTarget(), $is_add = true);
}
public function getHeraldActionStandardType() {
return self::STANDARD_PHID_LIST;
}
protected function getDatasource() {
return new PhabricatorMetaMTAMailableDatasource();
}
public function renderActionDescription($value) {
return pht('Add subscribers: %s.', $this->renderHandleList($value));
}
public function getPHIDsAffectedByAction(HeraldActionRecord $record) {
return $record->getTarget();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/subscriptions/herald/PhabricatorSubscriptionsRemoveSelfHeraldAction.php | src/applications/subscriptions/herald/PhabricatorSubscriptionsRemoveSelfHeraldAction.php | <?php
final class PhabricatorSubscriptionsRemoveSelfHeraldAction
extends PhabricatorSubscriptionsHeraldAction {
const ACTIONCONST = 'subscribers.self.remove';
public function getHeraldActionName() {
return pht('Remove me as a subscriber');
}
public function supportsRuleType($rule_type) {
return ($rule_type == HeraldRuleTypeConfig::RULE_TYPE_PERSONAL);
}
public function applyEffect($object, HeraldEffect $effect) {
$phid = $effect->getRule()->getAuthorPHID();
return $this->applySubscribe(array($phid), $is_add = false);
}
public function getHeraldActionStandardType() {
return self::STANDARD_NONE;
}
public function renderActionDescription($value) {
return pht('Remove rule author as subscriber.');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/subscriptions/herald/PhabricatorSubscriptionsHeraldAction.php | src/applications/subscriptions/herald/PhabricatorSubscriptionsHeraldAction.php | <?php
abstract class PhabricatorSubscriptionsHeraldAction
extends HeraldAction {
const DO_PREVIOUSLY_UNSUBSCRIBED = 'do.previously-unsubscribed';
const DO_AUTOSUBSCRIBED = 'do.autosubscribed';
const DO_SUBSCRIBED = 'do.subscribed';
const DO_UNSUBSCRIBED = 'do.unsubscribed';
public function getActionGroupKey() {
return HeraldSupportActionGroup::ACTIONGROUPKEY;
}
public function supportsObject($object) {
return ($object instanceof PhabricatorSubscribableInterface);
}
protected function applySubscribe(array $phids, $is_add) {
$adapter = $this->getAdapter();
$allowed_types = array(
PhabricatorPeopleUserPHIDType::TYPECONST,
PhabricatorProjectProjectPHIDType::TYPECONST,
);
// Evaluating "No Effect" is a bit tricky for this rule type, so just
// do it manually below.
$current = array();
$targets = $this->loadStandardTargets($phids, $allowed_types, $current);
if (!$targets) {
return;
}
$phids = array_fuse(array_keys($targets));
// The "Add Subscribers" rule only adds subscribers who haven't previously
// unsubscribed from the object explicitly. Filter these subscribers out
// before continuing.
if ($is_add) {
$unsubscribed = $adapter->loadEdgePHIDs(
PhabricatorObjectHasUnsubscriberEdgeType::EDGECONST);
foreach ($unsubscribed as $phid) {
if (isset($phids[$phid])) {
$unsubscribed[$phid] = $phid;
unset($phids[$phid]);
}
}
if ($unsubscribed) {
$this->logEffect(
self::DO_PREVIOUSLY_UNSUBSCRIBED,
array_values($unsubscribed));
}
}
if (!$phids) {
return;
}
$auto = array();
$object = $adapter->getObject();
foreach ($phids as $phid) {
if ($object->isAutomaticallySubscribed($phid)) {
$auto[$phid] = $phid;
unset($phids[$phid]);
}
}
if ($auto) {
$this->logEffect(self::DO_AUTOSUBSCRIBED, array_values($auto));
}
if (!$phids) {
return;
}
$current = $adapter->loadEdgePHIDs(
PhabricatorObjectHasSubscriberEdgeType::EDGECONST);
if ($is_add) {
$already = array();
foreach ($phids as $phid) {
if (isset($current[$phid])) {
$already[$phid] = $phid;
unset($phids[$phid]);
}
}
if ($already) {
$this->logEffect(self::DO_STANDARD_NO_EFFECT, $already);
}
} else {
$already = array();
foreach ($phids as $phid) {
if (empty($current[$phid])) {
$already[$phid] = $phid;
unset($phids[$phid]);
}
}
if ($already) {
$this->logEffect(self::DO_STANDARD_NO_EFFECT, $already);
}
}
if (!$phids) {
return;
}
if ($is_add) {
$kind = '+';
} else {
$kind = '-';
}
$xaction = $adapter->newTransaction()
->setTransactionType(PhabricatorTransactions::TYPE_SUBSCRIBERS)
->setNewValue(
array(
$kind => $phids,
));
$adapter->queueTransaction($xaction);
if ($is_add) {
$this->logEffect(self::DO_SUBSCRIBED, $phids);
} else {
$this->logEffect(self::DO_UNSUBSCRIBED, $phids);
}
}
protected function getActionEffectMap() {
return array(
self::DO_PREVIOUSLY_UNSUBSCRIBED => array(
'icon' => 'fa-minus-circle',
'color' => 'grey',
'name' => pht('Previously Unsubscribed'),
),
self::DO_AUTOSUBSCRIBED => array(
'icon' => 'fa-envelope',
'color' => 'grey',
'name' => pht('Automatically Subscribed'),
),
self::DO_SUBSCRIBED => array(
'icon' => 'fa-envelope',
'color' => 'green',
'name' => pht('Added Subscribers'),
),
self::DO_UNSUBSCRIBED => array(
'icon' => 'fa-minus-circle',
'color' => 'green',
'name' => pht('Removed Subscribers'),
),
);
}
protected function renderActionEffectDescription($type, $data) {
switch ($type) {
case self::DO_PREVIOUSLY_UNSUBSCRIBED:
return pht(
'Declined to resubscribe %s target(s) because they previously '.
'unsubscribed: %s.',
phutil_count($data),
$this->renderHandleList($data));
case self::DO_AUTOSUBSCRIBED:
return pht(
'%s automatically subscribed target(s) were not affected: %s.',
phutil_count($data),
$this->renderHandleList($data));
case self::DO_SUBSCRIBED:
return pht(
'Added %s subscriber(s): %s.',
phutil_count($data),
$this->renderHandleList($data));
case self::DO_UNSUBSCRIBED:
return pht(
'Removed %s subscriber(s): %s.',
phutil_count($data),
$this->renderHandleList($data));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/controller/PhabricatorXHPASTViewRunController.php | src/applications/phpast/controller/PhabricatorXHPASTViewRunController.php | <?php
final class PhabricatorXHPASTViewRunController
extends PhabricatorXHPASTViewController {
public function handleRequest(AphrontRequest $request) {
$viewer = $this->getViewer();
if ($request->isFormPost()) {
$source = $request->getStr('source');
$future = PhutilXHPASTBinary::getParserFuture($source);
$resolved = $future->resolve();
// This is just to let it throw exceptions if stuff is broken.
try {
XHPASTTree::newFromDataAndResolvedExecFuture($source, $resolved);
} catch (XHPASTSyntaxErrorException $ex) {
// This is possibly expected.
}
list($err, $stdout, $stderr) = $resolved;
$storage_tree = id(new PhabricatorXHPASTParseTree())
->setInput($source)
->setReturnCode($err)
->setStdout($stdout)
->setStderr($stderr)
->setAuthorPHID($viewer->getPHID())
->save();
return id(new AphrontRedirectResponse())
->setURI('/xhpast/view/'.$storage_tree->getID().'/');
}
$form = id(new AphrontFormView())
->setUser($viewer)
->appendChild(
id(new AphrontFormTextAreaControl())
->setLabel(pht('Source'))
->setName('source')
->setValue("<?php\n\n")
->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_TALL))
->appendChild(
id(new AphrontFormSubmitControl())
->setValue(pht('Parse')));
$form_box = id(new PHUIObjectBoxView())
->setHeaderText(pht('Generate XHP AST'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->setForm($form);
$title = pht('XHPAST View');
$header = id(new PHUIHeaderView())
->setHeader($title)
->setHeaderIcon('fa-ambulance');
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setFooter(array(
$form_box,
));
return $this->newPage()
->setTitle($title)
->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/phpast/controller/PhabricatorXHPASTViewInputController.php | src/applications/phpast/controller/PhabricatorXHPASTViewInputController.php | <?php
final class PhabricatorXHPASTViewInputController
extends PhabricatorXHPASTViewPanelController {
public function handleRequest(AphrontRequest $request) {
$input = $this->getStorageTree()->getInput();
return $this->buildXHPASTViewPanelResponse($input);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/controller/PhabricatorXHPASTViewTreeController.php | src/applications/phpast/controller/PhabricatorXHPASTViewTreeController.php | <?php
final class PhabricatorXHPASTViewTreeController
extends PhabricatorXHPASTViewPanelController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$storage = $this->getStorageTree();
$input = $storage->getInput();
$err = $storage->getReturnCode();
$stdout = $storage->getStdout();
$stderr = $storage->getStderr();
try {
$tree = XHPASTTree::newFromDataAndResolvedExecFuture(
$input,
array($err, $stdout, $stderr));
} catch (XHPASTSyntaxErrorException $ex) {
return $this->buildXHPASTViewPanelResponse($ex->getMessage());
}
$tree = phutil_tag('ul', array(), $this->buildTree($tree->getRootNode()));
return $this->buildXHPASTViewPanelResponse($tree);
}
protected function buildTree($root) {
try {
$name = $root->getTypeName();
$title = pht('Node %d: %s', $root->getID(), $name);
} catch (Exception $ex) {
$name = '???';
$title = '???';
}
$tree = array();
$tree[] = phutil_tag(
'li',
array(),
phutil_tag(
'span',
array(
'title' => $title,
),
$name));
foreach ($root->getChildren() as $child) {
$tree[] = phutil_tag('ul', array(), $this->buildTree($child));
}
return phutil_implode_html("\n", $tree);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/controller/PhabricatorXHPASTViewFrameController.php | src/applications/phpast/controller/PhabricatorXHPASTViewFrameController.php | <?php
final class PhabricatorXHPASTViewFrameController
extends PhabricatorXHPASTViewController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$id = $request->getURIData('id');
return $this->buildStandardPageResponse(
phutil_tag(
'iframe',
array(
'src' => "/xhpast/frameset/{$id}/",
'frameborder' => '0',
'style' => 'width: 100%; height: 800px;',
'',
)),
array(
'title' => pht('XHPAST View'),
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/controller/PhabricatorXHPASTViewPanelController.php | src/applications/phpast/controller/PhabricatorXHPASTViewPanelController.php | <?php
abstract class PhabricatorXHPASTViewPanelController
extends PhabricatorXHPASTViewController {
private $id;
private $storageTree;
public function shouldAllowPublic() {
return true;
}
public function willProcessRequest(array $data) {
$this->id = $data['id'];
$this->storageTree = id(new PhabricatorXHPASTParseTree())
->load($this->id);
if (!$this->storageTree) {
throw new Exception(pht('No such AST!'));
}
}
protected function getStorageTree() {
return $this->storageTree;
}
protected function buildXHPASTViewPanelResponse($content) {
$content = hsprintf(
'<!DOCTYPE html>'.
'<html>'.
'<head>'.
'<style type="text/css">
body {
white-space: pre;
font: 10px "Monaco";
cursor: pointer;
}
.token {
padding: 2px 4px;
margin: 2px 2px;
border: 1px solid #bbbbbb;
line-height: 24px;
}
ul {
margin: 0 0 0 1em;
padding: 0;
list-style: none;
line-height: 1em;
}
li {
margin: 0;
padding: 0;
}
li span {
background: #dddddd;
padding: 3px 6px;
}
</style>'.
'</head>'.
'<body>%s</body>'.
'</html>',
$content);
return id(new AphrontWebpageResponse())
->setFrameable(true)
->setContent($content);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/controller/PhabricatorXHPASTViewStreamController.php | src/applications/phpast/controller/PhabricatorXHPASTViewStreamController.php | <?php
final class PhabricatorXHPASTViewStreamController
extends PhabricatorXHPASTViewPanelController {
public function handleRequest(AphrontRequest $request) {
$storage = $this->getStorageTree();
$input = $storage->getInput();
$err = $storage->getReturnCode();
$stdout = $storage->getStdout();
$stderr = $storage->getStderr();
try {
$tree = XHPASTTree::newFromDataAndResolvedExecFuture(
$input,
array($err, $stdout, $stderr));
} catch (XHPASTSyntaxErrorException $ex) {
return $this->buildXHPASTViewPanelResponse($ex->getMessage());
}
$tokens = array();
foreach ($tree->getRawTokenStream() as $id => $token) {
$seq = $id;
$name = $token->getTypeName();
$title = pht('Token %d: %s', $seq, $name);
$tokens[] = phutil_tag(
'span',
array(
'title' => $title,
'class' => 'token',
),
$token->getValue());
}
return $this->buildXHPASTViewPanelResponse(
phutil_implode_html('', $tokens));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/controller/PhabricatorXHPASTViewController.php | src/applications/phpast/controller/PhabricatorXHPASTViewController.php | <?php
abstract class PhabricatorXHPASTViewController extends PhabricatorController {
public function buildStandardPageResponse($view, array $data) {
$page = $this->buildStandardPageView();
$page->setApplicationName('XHPASTView');
$page->setBaseURI('/xhpast/');
$page->setTitle(idx($data, 'title'));
$page->setGlyph("\xE2\x96\xA0");
$page->appendChild($view);
$response = new AphrontWebpageResponse();
return $response->setContent($page->render());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/controller/PhabricatorXHPASTViewFramesetController.php | src/applications/phpast/controller/PhabricatorXHPASTViewFramesetController.php | <?php
final class PhabricatorXHPASTViewFramesetController
extends PhabricatorXHPASTViewController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$id = $request->getURIData('id');
return id(new AphrontWebpageResponse())
->setFrameable(true)
->setContent(phutil_tag(
'frameset',
array('cols' => '33%, 34%, 33%'),
array(
phutil_tag('frame', array('src' => "/xhpast/input/{$id}/")),
phutil_tag('frame', array('src' => "/xhpast/tree/{$id}/")),
phutil_tag('frame', array('src' => "/xhpast/stream/{$id}/")),
)));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/storage/PhabricatorXHPASTParseTree.php | src/applications/phpast/storage/PhabricatorXHPASTParseTree.php | <?php
final class PhabricatorXHPASTParseTree extends PhabricatorXHPASTDAO {
protected $authorPHID;
protected $input;
protected $returnCode;
protected $stdout;
protected $stderr;
protected function getConfiguration() {
return array(
self::CONFIG_COLUMN_SCHEMA => array(
'authorPHID' => 'phid?',
'input' => 'text',
'returnCode' => 'sint32',
'stdout' => 'text',
'stderr' => 'text',
),
) + parent::getConfiguration();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/storage/PhabricatorXHPASTDAO.php | src/applications/phpast/storage/PhabricatorXHPASTDAO.php | <?php
abstract class PhabricatorXHPASTDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'xhpast';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phpast/application/PhabricatorPHPASTApplication.php | src/applications/phpast/application/PhabricatorPHPASTApplication.php | <?php
final class PhabricatorPHPASTApplication extends PhabricatorApplication {
public function getName() {
return pht('PHPAST');
}
public function getBaseURI() {
return '/xhpast/';
}
public function getIcon() {
return 'fa-ambulance';
}
public function getShortDescription() {
return pht('Visual PHP Parser');
}
public function getTitleGlyph() {
return "\xE2\x96\xA0";
}
public function getApplicationGroup() {
return self::GROUP_DEVELOPER;
}
public function getRoutes() {
return array(
'/xhpast/' => array(
'' => 'PhabricatorXHPASTViewRunController',
'view/(?P<id>[1-9]\d*)/'
=> 'PhabricatorXHPASTViewFrameController',
'frameset/(?P<id>[1-9]\d*)/'
=> 'PhabricatorXHPASTViewFramesetController',
'input/(?P<id>[1-9]\d*)/'
=> 'PhabricatorXHPASTViewInputController',
'tree/(?P<id>[1-9]\d*)/'
=> 'PhabricatorXHPASTViewTreeController',
'stream/(?P<id>[1-9]\d*)/'
=> 'PhabricatorXHPASTViewStreamController',
),
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/controller/PholioMockCommentController.php | src/applications/pholio/controller/PholioMockCommentController.php | <?php
final class PholioMockCommentController extends PholioController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
if (!$request->isFormPost()) {
return new Aphront400Response();
}
$mock = id(new PholioMockQuery())
->setViewer($viewer)
->withIDs(array($id))
->needImages(true)
->executeOne();
if (!$mock) {
return new Aphront404Response();
}
$is_preview = $request->isPreviewRequest();
$draft = PhabricatorDraft::buildFromRequest($request);
$mock_uri = $mock->getURI();
$comment = $request->getStr('comment');
$xactions = array();
$inline_comments = id(new PholioTransactionComment())->loadAllWhere(
'authorphid = %s AND transactionphid IS NULL AND imageid IN (%Ld)',
$viewer->getPHID(),
mpull($mock->getActiveImages(), 'getID'));
if (!$inline_comments || strlen($comment)) {
$xactions[] = id(new PholioTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)
->attachComment(
id(new PholioTransactionComment())
->setContent($comment));
}
foreach ($inline_comments as $inline_comment) {
$xactions[] = id(new PholioTransaction())
->setTransactionType(PholioMockInlineTransaction::TRANSACTIONTYPE)
->attachComment($inline_comment);
}
$editor = id(new PholioMockEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect($request->isContinueRequest())
->setIsPreview($is_preview);
try {
$xactions = $editor->applyTransactions($mock, $xactions);
} catch (PhabricatorApplicationTransactionNoEffectException $ex) {
return id(new PhabricatorApplicationTransactionNoEffectResponse())
->setCancelURI($mock_uri)
->setException($ex);
}
if ($draft) {
$draft->replaceOrDelete();
}
if ($request->isAjax() && $is_preview) {
return id(new PhabricatorApplicationTransactionResponse())
->setObject($mock)
->setViewer($viewer)
->setTransactions($xactions)
->setIsPreview($is_preview);
} else {
return id(new AphrontRedirectResponse())->setURI($mock_uri);
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/controller/PholioMockViewController.php | src/applications/pholio/controller/PholioMockViewController.php | <?php
final class PholioMockViewController extends PholioController {
private $maniphestTaskPHIDs = array();
private function setManiphestTaskPHIDs($maniphest_task_phids) {
$this->maniphestTaskPHIDs = $maniphest_task_phids;
return $this;
}
private function getManiphestTaskPHIDs() {
return $this->maniphestTaskPHIDs;
}
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$image_id = $request->getURIData('imageID');
$mock = id(new PholioMockQuery())
->setViewer($viewer)
->withIDs(array($id))
->needImages(true)
->needInlineComments(true)
->executeOne();
if (!$mock) {
return new Aphront404Response();
}
$phids = PhabricatorEdgeQuery::loadDestinationPHIDs(
$mock->getPHID(),
PholioMockHasTaskEdgeType::EDGECONST);
$this->setManiphestTaskPHIDs($phids);
$title = $mock->getName();
if ($mock->isClosed()) {
$header_icon = 'fa-ban';
$header_name = pht('Closed');
$header_color = 'dark';
} else {
$header_icon = 'fa-square-o';
$header_name = pht('Open');
$header_color = 'bluegrey';
}
$header = id(new PHUIHeaderView())
->setHeader($title)
->setUser($viewer)
->setStatus($header_icon, $header_color, $header_name)
->setPolicyObject($mock)
->setHeaderIcon('fa-camera-retro');
$timeline = $this->buildTransactionTimeline(
$mock,
new PholioTransactionQuery());
$timeline->setMock($mock);
$timeline->setQuoteRef($mock->getMonogram());
$curtain = $this->buildCurtainView($mock);
$details = $this->buildDescriptionView($mock);
require_celerity_resource('pholio-css');
require_celerity_resource('pholio-inline-comments-css');
$comment_form_id = celerity_generate_unique_node_id();
$mock_view = id(new PholioMockImagesView())
->setRequestURI($request->getRequestURI())
->setCommentFormID($comment_form_id)
->setUser($viewer)
->setMock($mock)
->setImageID($image_id);
$output = id(new PHUIObjectBoxView())
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($mock_view);
$add_comment = $this->buildAddCommentView($mock, $comment_form_id);
$add_comment->setTransactionTimeline($timeline);
$crumbs = $this->buildApplicationCrumbs();
$crumbs->addTextCrumb($mock->getMonogram(), $mock->getURI());
$crumbs->setBorder(true);
$thumb_grid = id(new PholioMockThumbGridView())
->setUser($viewer)
->setMock($mock);
$view = id(new PHUITwoColumnView())
->setHeader($header)
->setCurtain($curtain)
->setMainColumn(
array(
$output,
$thumb_grid,
$details,
$timeline,
$add_comment,
));
return $this->newPage()
->setTitle(pht('%s %s', $mock->getMonogram(), $title))
->setCrumbs($crumbs)
->setPageObjectPHIDs(array($mock->getPHID()))
->addQuicksandConfig(
array('mockViewConfig' => $mock_view->getBehaviorConfig()))
->appendChild($view);
}
private function buildCurtainView(PholioMock $mock) {
$viewer = $this->getViewer();
$curtain = $this->newCurtainView($mock);
$can_edit = PhabricatorPolicyFilter::hasCapability(
$viewer,
$mock,
PhabricatorPolicyCapability::CAN_EDIT);
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-pencil')
->setName(pht('Edit Mock'))
->setHref($this->getApplicationURI('/edit/'.$mock->getID().'/'))
->setDisabled(!$can_edit)
->setWorkflow(!$can_edit));
if ($mock->isClosed()) {
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-check')
->setName(pht('Open Mock'))
->setHref($this->getApplicationURI('/archive/'.$mock->getID().'/'))
->setDisabled(!$can_edit)
->setWorkflow(true));
} else {
$curtain->addAction(
id(new PhabricatorActionView())
->setIcon('fa-ban')
->setName(pht('Close Mock'))
->setHref($this->getApplicationURI('/archive/'.$mock->getID().'/'))
->setDisabled(!$can_edit)
->setWorkflow(true));
}
$relationship_list = PhabricatorObjectRelationshipList::newForObject(
$viewer,
$mock);
$relationship_submenu = $relationship_list->newActionMenu();
if ($relationship_submenu) {
$curtain->addAction($relationship_submenu);
}
if ($this->getManiphestTaskPHIDs()) {
$curtain->newPanel()
->setHeaderText(pht('Maniphest Tasks'))
->appendChild(
$viewer->renderHandleList($this->getManiphestTaskPHIDs()));
}
$curtain->newPanel()
->setHeaderText(pht('Authored By'))
->appendChild($this->buildAuthorPanel($mock));
return $curtain;
}
private function buildDescriptionView(PholioMock $mock) {
$viewer = $this->getViewer();
$properties = id(new PHUIPropertyListView())
->setUser($viewer);
$description = $mock->getDescription();
if (strlen($description)) {
$properties->addTextContent(
new PHUIRemarkupView($viewer, $description));
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Mock Description'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($properties);
}
return null;
}
private function buildAuthorPanel(PholioMock $mock) {
$viewer = $this->getViewer();
$author_phid = $mock->getAuthorPHID();
$handles = $viewer->loadHandles(array($author_phid));
$author_uri = $handles[$author_phid]->getImageURI();
$author_href = $handles[$author_phid]->getURI();
$author = $viewer->renderHandle($author_phid)->render();
$content = phutil_tag('strong', array(), $author);
$date = phabricator_date($mock->getDateCreated(), $viewer);
$content = pht('%s, %s', $content, $date);
$authored_by = id(new PHUIHeadThingView())
->setImage($author_uri)
->setImageHref($author_href)
->setContent($content);
return $authored_by;
}
private function buildAddCommentView(PholioMock $mock, $comment_form_id) {
$viewer = $this->getViewer();
$draft = PhabricatorDraft::newFromUserAndKey($viewer, $mock->getPHID());
$is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business');
$title = $is_serious
? pht('Add Comment')
: pht('History Beckons');
$form = id(new PhabricatorApplicationTransactionCommentView())
->setUser($viewer)
->setObjectPHID($mock->getPHID())
->setFormID($comment_form_id)
->setDraft($draft)
->setHeaderText($title)
->setSubmitButtonName(pht('Add Comment'))
->setAction($this->getApplicationURI('/comment/'.$mock->getID().'/'))
->setRequestURI($this->getRequest()->getRequestURI());
return $form;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/controller/PholioMockListController.php | src/applications/pholio/controller/PholioMockListController.php | <?php
final class PholioMockListController extends PholioController {
public function shouldAllowPublic() {
return true;
}
public function handleRequest(AphrontRequest $request) {
return id(new PholioMockSearchEngine())
->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/pholio/controller/PholioMockEditController.php | src/applications/pholio/controller/PholioMockEditController.php | <?php
final class PholioMockEditController extends PholioController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
if ($id) {
$mock = id(new PholioMockQuery())
->setViewer($viewer)
->needImages(true)
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->withIDs(array($id))
->executeOne();
if (!$mock) {
return new Aphront404Response();
}
$title = pht('Edit Mock: %s', $mock->getName());
$is_new = false;
$mock_images = $mock->getActiveImages();
$files = mpull($mock_images, 'getFile');
$mock_images = mpull($mock_images, null, 'getFilePHID');
} else {
$mock = PholioMock::initializeNewMock($viewer);
$title = pht('Create Mock');
$is_new = true;
$files = array();
$mock_images = array();
}
if ($is_new) {
$v_projects = array();
} else {
$v_projects = PhabricatorEdgeQuery::loadDestinationPHIDs(
$mock->getPHID(),
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST);
$v_projects = array_reverse($v_projects);
}
$e_name = true;
$e_images = count($mock_images) ? null : true;
$errors = array();
$posted_mock_images = array();
$v_name = $mock->getName();
$v_desc = $mock->getDescription();
$v_view = $mock->getViewPolicy();
$v_edit = $mock->getEditPolicy();
$v_cc = PhabricatorSubscribersQuery::loadSubscribersForPHID(
$mock->getPHID());
$v_space = $mock->getSpacePHID();
if ($request->isFormPost()) {
$xactions = array();
$type_name = PholioMockNameTransaction::TRANSACTIONTYPE;
$type_desc = PholioMockDescriptionTransaction::TRANSACTIONTYPE;
$type_view = PhabricatorTransactions::TYPE_VIEW_POLICY;
$type_edit = PhabricatorTransactions::TYPE_EDIT_POLICY;
$type_cc = PhabricatorTransactions::TYPE_SUBSCRIBERS;
$type_space = PhabricatorTransactions::TYPE_SPACE;
$v_name = $request->getStr('name');
$v_desc = $request->getStr('description');
$v_view = $request->getStr('can_view');
$v_edit = $request->getStr('can_edit');
$v_cc = $request->getArr('cc');
$v_projects = $request->getArr('projects');
$v_space = $request->getStr('spacePHID');
$mock_xactions = array();
$mock_xactions[$type_name] = $v_name;
$mock_xactions[$type_desc] = $v_desc;
$mock_xactions[$type_view] = $v_view;
$mock_xactions[$type_edit] = $v_edit;
$mock_xactions[$type_cc] = array('=' => $v_cc);
$mock_xactions[$type_space] = $v_space;
$file_phids = $request->getArr('file_phids');
if ($file_phids) {
$files = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs($file_phids)
->execute();
$files = mpull($files, null, 'getPHID');
$files = array_select_keys($files, $file_phids);
} else {
$files = array();
}
if (!$files) {
$e_images = pht('Required');
$errors[] = pht('You must add at least one image to the mock.');
} else {
$mock->setCoverPHID(head($files)->getPHID());
}
foreach ($mock_xactions as $type => $value) {
$xactions[$type] = id(new PholioTransaction())
->setTransactionType($type)
->setNewValue($value);
}
$order = $request->getStrList('imageOrder');
$sequence_map = array_flip($order);
$replaces = $request->getArr('replaces');
$replaces_map = array_flip($replaces);
/**
* Foreach file posted, check to see whether we are replacing an image,
* adding an image, or simply updating image metadata. Create
* transactions for these cases as appropos.
*/
foreach ($files as $file_phid => $file) {
$replaces_image_phid = null;
if (isset($replaces_map[$file_phid])) {
$old_file_phid = $replaces_map[$file_phid];
if ($old_file_phid != $file_phid) {
$old_image = idx($mock_images, $old_file_phid);
if ($old_image) {
$replaces_image_phid = $old_image->getPHID();
}
}
}
$existing_image = idx($mock_images, $file_phid);
$title = (string)$request->getStr('title_'.$file_phid);
$description = (string)$request->getStr('description_'.$file_phid);
$sequence = $sequence_map[$file_phid];
if ($replaces_image_phid) {
$replace_image = PholioImage::initializeNewImage()
->setAuthorPHID($viewer->getPHID())
->setReplacesImagePHID($replaces_image_phid)
->setFilePHID($file_phid)
->attachFile($file)
->setName(strlen($title) ? $title : $file->getName())
->setDescription($description)
->setSequence($sequence)
->save();
$xactions[] = id(new PholioTransaction())
->setTransactionType(PholioImageReplaceTransaction::TRANSACTIONTYPE)
->setNewValue($replace_image->getPHID());
$posted_mock_images[] = $replace_image;
} else if (!$existing_image) { // this is an add
$add_image = PholioImage::initializeNewImage()
->setAuthorPHID($viewer->getPHID())
->setFilePHID($file_phid)
->attachFile($file)
->setName(strlen($title) ? $title : $file->getName())
->setDescription($description)
->setSequence($sequence)
->save();
$xactions[] = id(new PholioTransaction())
->setTransactionType(PholioImageFileTransaction::TRANSACTIONTYPE)
->setNewValue(
array('+' => array($add_image->getPHID())));
$posted_mock_images[] = $add_image;
} else {
$xactions[] = id(new PholioTransaction())
->setTransactionType(PholioImageNameTransaction::TRANSACTIONTYPE)
->setNewValue(
array($existing_image->getPHID() => $title));
$xactions[] = id(new PholioTransaction())
->setTransactionType(
PholioImageDescriptionTransaction::TRANSACTIONTYPE)
->setNewValue(
array($existing_image->getPHID() => $description));
$xactions[] = id(new PholioTransaction())
->setTransactionType(
PholioImageSequenceTransaction::TRANSACTIONTYPE)
->setNewValue(
array($existing_image->getPHID() => $sequence));
$posted_mock_images[] = $existing_image;
}
}
foreach ($mock_images as $file_phid => $mock_image) {
if (!isset($files[$file_phid]) && !isset($replaces[$file_phid])) {
// this is an outright delete
$xactions[] = id(new PholioTransaction())
->setTransactionType(PholioImageFileTransaction::TRANSACTIONTYPE)
->setNewValue(
array('-' => array($mock_image->getPHID())));
}
}
if (!$errors) {
$proj_edge_type = PhabricatorProjectObjectHasProjectEdgeType::EDGECONST;
$xactions[] = id(new PholioTransaction())
->setTransactionType(PhabricatorTransactions::TYPE_EDGE)
->setMetadataValue('edge:type', $proj_edge_type)
->setNewValue(array('=' => array_fuse($v_projects)));
$editor = id(new PholioMockEditor())
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setActor($viewer);
$xactions = $editor->applyTransactions($mock, $xactions);
return id(new AphrontRedirectResponse())
->setURI('/M'.$mock->getID());
}
}
if ($id) {
$submit = id(new AphrontFormSubmitControl())
->addCancelButton('/M'.$id)
->setValue(pht('Save'));
} else {
$submit = id(new AphrontFormSubmitControl())
->addCancelButton($this->getApplicationURI())
->setValue(pht('Create'));
}
$policies = id(new PhabricatorPolicyQuery())
->setViewer($viewer)
->setObject($mock)
->execute();
// NOTE: Make this show up correctly on the rendered form.
$mock->setViewPolicy($v_view);
$mock->setEditPolicy($v_edit);
$image_elements = array();
if ($posted_mock_images) {
$display_mock_images = $posted_mock_images;
} else {
$display_mock_images = $mock_images;
}
foreach ($display_mock_images as $mock_image) {
$image_elements[] = id(new PholioUploadedImageView())
->setUser($viewer)
->setImage($mock_image)
->setReplacesPHID($mock_image->getFilePHID());
}
$list_id = celerity_generate_unique_node_id();
$drop_id = celerity_generate_unique_node_id();
$order_id = celerity_generate_unique_node_id();
$list_control = phutil_tag(
'div',
array(
'id' => $list_id,
'class' => 'pholio-edit-list',
),
$image_elements);
$drop_control = phutil_tag(
'a',
array(
'id' => $drop_id,
'class' => 'pholio-edit-drop',
),
pht('Click here, or drag and drop images to add them to the mock.'));
$order_control = phutil_tag(
'input',
array(
'type' => 'hidden',
'name' => 'imageOrder',
'id' => $order_id,
));
Javelin::initBehavior(
'pholio-mock-edit',
array(
'listID' => $list_id,
'dropID' => $drop_id,
'orderID' => $order_id,
'uploadURI' => '/file/dropupload/',
'renderURI' => $this->getApplicationURI('image/upload/'),
'pht' => array(
'uploading' => pht('Uploading Image...'),
'uploaded' => pht('Upload Complete...'),
'undo' => pht('Undo'),
'removed' => pht('This image will be removed from the mock.'),
),
));
require_celerity_resource('pholio-edit-css');
$form = id(new AphrontFormView())
->setUser($viewer)
->appendChild($order_control)
->appendChild(
id(new AphrontFormTextControl())
->setName('name')
->setValue($v_name)
->setLabel(pht('Name'))
->setError($e_name))
->appendChild(
id(new PhabricatorRemarkupControl())
->setName('description')
->setValue($v_desc)
->setLabel(pht('Description'))
->setUser($viewer))
->appendControl(
id(new AphrontFormTokenizerControl())
->setLabel(pht('Tags'))
->setName('projects')
->setValue($v_projects)
->setDatasource(new PhabricatorProjectDatasource()))
->appendControl(
id(new AphrontFormTokenizerControl())
->setLabel(pht('Subscribers'))
->setName('cc')
->setValue($v_cc)
->setUser($viewer)
->setDatasource(new PhabricatorMetaMTAMailableDatasource()))
->appendChild(
id(new AphrontFormPolicyControl())
->setUser($viewer)
->setCapability(PhabricatorPolicyCapability::CAN_VIEW)
->setPolicyObject($mock)
->setPolicies($policies)
->setSpacePHID($v_space)
->setName('can_view'))
->appendChild(
id(new AphrontFormPolicyControl())
->setUser($viewer)
->setCapability(PhabricatorPolicyCapability::CAN_EDIT)
->setPolicyObject($mock)
->setPolicies($policies)
->setName('can_edit'))
->appendChild(
id(new AphrontFormMarkupControl())
->setValue($list_control))
->appendChild(
id(new AphrontFormMarkupControl())
->setValue($drop_control)
->setError($e_images))
->appendChild($submit);
$form_box = id(new PHUIObjectBoxView())
->setHeaderText($title)
->setFormErrors($errors)
->setBackground(PHUIObjectBoxView::WHITE_CONFIG)
->setForm($form);
$crumbs = $this->buildApplicationCrumbs();
if (!$is_new) {
$crumbs->addTextCrumb($mock->getMonogram(), '/'.$mock->getMonogram());
}
$crumbs->addTextCrumb($title);
$crumbs->setBorder(true);
$view = id(new PHUITwoColumnView())
->setFooter($form_box);
return $this->newPage()
->setTitle($title)
->setCrumbs($crumbs)
->addQuicksandConfig(
array('mockEditConfig' => true))
->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/pholio/controller/PholioInlineController.php | src/applications/pholio/controller/PholioInlineController.php | <?php
final class PholioInlineController extends PholioController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
if ($id) {
$inline = id(new PholioTransactionComment())->load($id);
if (!$inline) {
return new Aphront404Response();
}
if ($inline->getTransactionPHID()) {
$mode = 'view';
} else {
if ($inline->getAuthorPHID() == $viewer->getPHID()) {
$mode = 'edit';
} else {
return new Aphront404Response();
}
}
} else {
$mock = id(new PholioMockQuery())
->setViewer($viewer)
->withIDs(array($request->getInt('mockID')))
->executeOne();
if (!$mock) {
return new Aphront404Response();
}
$inline = id(new PholioTransactionComment())
->setImageID($request->getInt('imageID'))
->setX($request->getInt('startX'))
->setY($request->getInt('startY'))
->setCommentVersion(1)
->setAuthorPHID($viewer->getPHID())
->setEditPolicy($viewer->getPHID())
->setViewPolicy(PhabricatorPolicies::POLICY_PUBLIC)
->setContentSourceFromRequest($request)
->setWidth($request->getInt('endX') - $request->getInt('startX'))
->setHeight($request->getInt('endY') - $request->getInt('startY'));
$mode = 'new';
}
$v_content = $inline->getContent();
// TODO: Not correct, but we don't always have a mock right now.
$mock_uri = '/';
if ($mode == 'view') {
require_celerity_resource('pholio-inline-comments-css');
$image = id(new PholioImageQuery())
->setViewer($viewer)
->withIDs(array($inline->getImageID()))
->executeOne();
$handles = $this->loadViewerHandles(array($inline->getAuthorPHID()));
$author_handle = $handles[$inline->getAuthorPHID()];
$file = $image->getFile();
if (!$file->isViewableImage()) {
throw new Exception(pht('File is not viewable.'));
}
$image_uri = $file->getBestURI();
$thumb = id(new PHUIImageMaskView())
->addClass('mrl')
->setImage($image_uri)
->setDisplayHeight(200)
->setDisplayWidth(498)
->withMask(true)
->centerViewOnPoint(
$inline->getX(), $inline->getY(),
$inline->getHeight(), $inline->getWidth());
$comment_head = phutil_tag(
'div',
array(
'class' => 'pholio-inline-comment-head',
),
$author_handle->renderLink());
$inline_content = new PHUIRemarkupView($viewer, $inline->getContent());
$comment_body = phutil_tag(
'div',
array(
'class' => 'pholio-inline-comment-body',
),
$inline_content);
return $this->newDialog()
->setTitle(pht('Inline Comment'))
->appendChild($thumb)
->appendChild($comment_head)
->appendChild($comment_body)
->addCancelButton($mock_uri, pht('Close'));
}
if ($request->isFormPost()) {
$v_content = $request->getStr('content');
if (strlen($v_content)) {
$inline->setContent($v_content);
$inline->save();
$dictionary = $inline->toDictionary();
} else if ($inline->getID()) {
$inline->delete();
$dictionary = array();
}
return id(new AphrontAjaxResponse())->setContent($dictionary);
}
switch ($mode) {
case 'edit':
$title = pht('Edit Inline Comment');
$submit_text = pht('Save Draft');
break;
case 'new':
$title = pht('New Inline Comment');
$submit_text = pht('Save Draft');
break;
}
$form = id(new AphrontFormView())
->setUser($viewer);
if ($mode == 'new') {
$params = array(
'mockID' => $request->getInt('mockID'),
'imageID' => $request->getInt('imageID'),
'startX' => $request->getInt('startX'),
'startY' => $request->getInt('startY'),
'endX' => $request->getInt('endX'),
'endY' => $request->getInt('endY'),
);
foreach ($params as $key => $value) {
$form->addHiddenInput($key, $value);
}
}
$form
->appendChild(
id(new PhabricatorRemarkupControl())
->setUser($viewer)
->setName('content')
->setLabel(pht('Comment'))
->setValue($v_content));
return $this->newDialog()
->setTitle($title)
->setWidth(AphrontDialogView::WIDTH_FORM)
->appendChild($form->buildLayoutView())
->addCancelButton($mock_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/pholio/controller/PholioMockArchiveController.php | src/applications/pholio/controller/PholioMockArchiveController.php | <?php
final class PholioMockArchiveController
extends PholioController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$mock = id(new PholioMockQuery())
->setViewer($viewer)
->withIDs(array($id))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$mock) {
return new Aphront404Response();
}
$view_uri = '/M'.$mock->getID();
if ($request->isFormPost()) {
if ($mock->isClosed()) {
$new_status = PholioMock::STATUS_OPEN;
} else {
$new_status = PholioMock::STATUS_CLOSED;
}
$xactions = array();
$xactions[] = id(new PholioTransaction())
->setTransactionType(PholioMockStatusTransaction::TRANSACTIONTYPE)
->setNewValue($new_status);
id(new PholioMockEditor())
->setActor($viewer)
->setContentSourceFromRequest($request)
->setContinueOnNoEffect(true)
->setContinueOnMissingFields(true)
->applyTransactions($mock, $xactions);
return id(new AphrontRedirectResponse())->setURI($view_uri);
}
if ($mock->isClosed()) {
$title = pht('Open Pholio Mock');
$body = pht('This mock will become open again.');
$button = pht('Open Mock');
} else {
$title = pht('Close Pholio Mock');
$body = pht('This mock will be closed.');
$button = pht('Close Mock');
}
return $this->newDialog()
->setTitle($title)
->appendChild($body)
->addCancelButton($view_uri)
->addSubmitButton($button);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/controller/PholioInlineListController.php | src/applications/pholio/controller/PholioInlineListController.php | <?php
final class PholioInlineListController extends PholioController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$id = $request->getURIData('id');
$image = id(new PholioImageQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
if (!$image) {
return new Aphront404Response();
}
$inline_comments = id(new PholioTransactionComment())->loadAllWhere(
'imageid = %d AND (transactionphid IS NOT NULL
OR (authorphid = %s AND transactionphid IS NULL))',
$id,
$viewer->getPHID());
$author_phids = mpull($inline_comments, 'getAuthorPHID');
$authors = $this->loadViewerHandles($author_phids);
$inlines = array();
foreach ($inline_comments as $inline_comment) {
$inlines[] = $inline_comment->toDictionary();
}
return id(new AphrontAjaxResponse())->setContent($inlines);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/controller/PholioImageUploadController.php | src/applications/pholio/controller/PholioImageUploadController.php | <?php
final class PholioImageUploadController extends PholioController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$phid = $request->getStr('filePHID');
$replaces_phid = $request->getStr('replacesPHID');
$title = $request->getStr('title');
$description = $request->getStr('description');
$file = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(array($phid))
->executeOne();
if (!$file) {
return new Aphront404Response();
}
if (!phutil_nonempty_string($title)) {
$title = $file->getName();
}
$image = PholioImage::initializeNewImage()
->setAuthorPHID($viewer->getPHID())
->attachFile($file)
->setName($title)
->setDescription($description)
->makeEphemeral();
$view = id(new PholioUploadedImageView())
->setUser($viewer)
->setImage($image)
->setReplacesPHID($replaces_phid);
$content = array(
'markup' => $view,
);
return id(new AphrontAjaxResponse())->setContent($content);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/controller/PholioController.php | src/applications/pholio/controller/PholioController.php | <?php
abstract class PholioController extends PhabricatorController {
public function buildApplicationMenu() {
return $this->newApplicationMenu()
->setSearchEngine(new PholioMockSearchEngine());
}
protected function buildApplicationCrumbs() {
$crumbs = parent::buildApplicationCrumbs();
$crumbs->addAction(
id(new PHUIListItemView())
->setName(pht('Create Mock'))
->setHref($this->getApplicationURI('create/'))
->setIcon('fa-plus-square'));
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/pholio/storage/PholioDAO.php | src/applications/pholio/storage/PholioDAO.php | <?php
abstract class PholioDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'pholio';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/storage/PholioImage.php | src/applications/pholio/storage/PholioImage.php | <?php
final class PholioImage extends PholioDAO
implements
PhabricatorPolicyInterface,
PhabricatorExtendedPolicyInterface {
protected $authorPHID;
protected $mockPHID;
protected $filePHID;
protected $name;
protected $description;
protected $sequence;
protected $isObsolete;
protected $replacesImagePHID = null;
private $inlineComments = self::ATTACHABLE;
private $file = self::ATTACHABLE;
private $mock = self::ATTACHABLE;
public static function initializeNewImage() {
return id(new self())
->setName('')
->setDescription('')
->setIsObsolete(0);
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_COLUMN_SCHEMA => array(
'mockPHID' => 'phid?',
'name' => 'text128',
'description' => 'text',
'sequence' => 'uint32',
'isObsolete' => 'bool',
'replacesImagePHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_mock' => array(
'columns' => array('mockPHID'),
),
),
) + parent::getConfiguration();
}
public function getPHIDType() {
return PholioImagePHIDType::TYPECONST;
}
public function attachFile(PhabricatorFile $file) {
$this->file = $file;
return $this;
}
public function getFile() {
return $this->assertAttached($this->file);
}
public function attachMock(PholioMock $mock) {
$this->mock = $mock;
return $this;
}
public function getMock() {
return $this->assertAttached($this->mock);
}
public function hasMock() {
return (bool)$this->getMockPHID();
}
public function attachInlineComments(array $inline_comments) {
assert_instances_of($inline_comments, 'PholioTransactionComment');
$this->inlineComments = $inline_comments;
return $this;
}
public function getInlineComments() {
$this->assertAttached($this->inlineComments);
return $this->inlineComments;
}
public function getURI() {
if ($this->hasMock()) {
$mock = $this->getMock();
$mock_uri = $mock->getURI();
$image_id = $this->getID();
return "{$mock_uri}/{$image_id}/";
}
// For now, standalone images have no URI. We could provide one at some
// point, although it's not clear that there's any motivation to do so.
return null;
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
);
}
public function getPolicy($capability) {
// If the image is attached to a mock, we use an extended policy to match
// the mock's permissions.
if ($this->hasMock()) {
return PhabricatorPolicies::getMostOpenPolicy();
}
// If the image is not attached to a mock, only the author can see it.
return $this->getAuthorPHID();
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
return false;
}
/* -( PhabricatorExtendedPolicyInterface )--------------------------------- */
public function getExtendedPolicy($capability, PhabricatorUser $viewer) {
if ($this->hasMock()) {
return array(
array(
$this->getMock(),
$capability,
),
);
}
return array();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/storage/PholioTransactionComment.php | src/applications/pholio/storage/PholioTransactionComment.php | <?php
final class PholioTransactionComment
extends PhabricatorApplicationTransactionComment {
protected $imageID;
protected $x;
protected $y;
protected $width;
protected $height;
protected $content;
public function getApplicationTransactionObject() {
return new PholioTransaction();
}
protected function getConfiguration() {
$config = parent::getConfiguration();
$config[self::CONFIG_COLUMN_SCHEMA] = array(
'imageID' => 'id?',
'x' => 'uint32?',
'y' => 'uint32?',
'width' => 'uint32?',
'height' => 'uint32?',
) + $config[self::CONFIG_COLUMN_SCHEMA];
$config[self::CONFIG_KEY_SCHEMA] = array(
'key_draft' => array(
'columns' => array('authorPHID', 'imageID', 'transactionPHID'),
'unique' => true,
),
) + $config[self::CONFIG_KEY_SCHEMA];
return $config;
}
public function toDictionary() {
return array(
'id' => $this->getID(),
'phid' => $this->getPHID(),
'transactionPHID' => $this->getTransactionPHID(),
'x' => $this->getX(),
'y' => $this->getY(),
'width' => $this->getWidth(),
'height' => $this->getHeight(),
);
}
public function shouldUseMarkupCache($field) {
// Only cache submitted comments.
return ($this->getTransactionPHID() != null);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/storage/PholioTransaction.php | src/applications/pholio/storage/PholioTransaction.php | <?php
final class PholioTransaction extends PhabricatorModularTransaction {
const MAILTAG_STATUS = 'pholio-status';
const MAILTAG_COMMENT = 'pholio-comment';
const MAILTAG_UPDATED = 'pholio-updated';
const MAILTAG_OTHER = 'pholio-other';
public function getApplicationName() {
return 'pholio';
}
public function getBaseTransactionClass() {
return 'PholioTransactionType';
}
public function getApplicationTransactionType() {
return PholioMockPHIDType::TYPECONST;
}
public function getApplicationTransactionCommentObject() {
return new PholioTransactionComment();
}
public function getMailTags() {
$tags = array();
switch ($this->getTransactionType()) {
case PholioMockInlineTransaction::TRANSACTIONTYPE:
case PhabricatorTransactions::TYPE_COMMENT:
$tags[] = self::MAILTAG_COMMENT;
break;
case PholioMockStatusTransaction::TRANSACTIONTYPE:
$tags[] = self::MAILTAG_STATUS;
break;
case PholioMockNameTransaction::TRANSACTIONTYPE:
case PholioMockDescriptionTransaction::TRANSACTIONTYPE:
case PholioImageNameTransaction::TRANSACTIONTYPE:
case PholioImageDescriptionTransaction::TRANSACTIONTYPE:
case PholioImageSequenceTransaction::TRANSACTIONTYPE:
case PholioImageFileTransaction::TRANSACTIONTYPE:
case PholioImageReplaceTransaction::TRANSACTIONTYPE:
$tags[] = self::MAILTAG_UPDATED;
break;
default:
$tags[] = self::MAILTAG_OTHER;
break;
}
return $tags;
}
public function isInlineCommentTransaction() {
switch ($this->getTransactionType()) {
case PholioMockInlineTransaction::TRANSACTIONTYPE:
return true;
}
return parent::isInlineCommentTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/storage/PholioSchemaSpec.php | src/applications/pholio/storage/PholioSchemaSpec.php | <?php
final class PholioSchemaSpec extends PhabricatorConfigSchemaSpec {
public function buildSchemata() {
$this->buildEdgeSchemata(new PholioMock());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/storage/PholioMock.php | src/applications/pholio/storage/PholioMock.php | <?php
final class PholioMock extends PholioDAO
implements
PhabricatorPolicyInterface,
PhabricatorSubscribableInterface,
PhabricatorTokenReceiverInterface,
PhabricatorFlaggableInterface,
PhabricatorApplicationTransactionInterface,
PhabricatorTimelineInterface,
PhabricatorProjectInterface,
PhabricatorDestructibleInterface,
PhabricatorSpacesInterface,
PhabricatorMentionableInterface,
PhabricatorFulltextInterface,
PhabricatorFerretInterface {
const STATUS_OPEN = 'open';
const STATUS_CLOSED = 'closed';
protected $authorPHID;
protected $viewPolicy;
protected $editPolicy;
protected $name;
protected $description;
protected $coverPHID;
protected $status;
protected $spacePHID;
private $images = self::ATTACHABLE;
private $coverFile = self::ATTACHABLE;
private $tokenCount = self::ATTACHABLE;
public static function initializeNewMock(PhabricatorUser $actor) {
$app = id(new PhabricatorApplicationQuery())
->setViewer($actor)
->withClasses(array('PhabricatorPholioApplication'))
->executeOne();
$view_policy = $app->getPolicy(PholioDefaultViewCapability::CAPABILITY);
$edit_policy = $app->getPolicy(PholioDefaultEditCapability::CAPABILITY);
return id(new PholioMock())
->setAuthorPHID($actor->getPHID())
->attachImages(array())
->setStatus(self::STATUS_OPEN)
->setViewPolicy($view_policy)
->setEditPolicy($edit_policy)
->setSpacePHID($actor->getDefaultSpacePHID());
}
public function getMonogram() {
return 'M'.$this->getID();
}
public function getURI() {
return '/'.$this->getMonogram();
}
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_COLUMN_SCHEMA => array(
'name' => 'text128',
'description' => 'text',
'status' => 'text12',
),
self::CONFIG_KEY_SCHEMA => array(
'authorPHID' => array(
'columns' => array('authorPHID'),
),
),
) + parent::getConfiguration();
}
public function getPHIDType() {
return PholioMockPHIDType::TYPECONST;
}
public function attachImages(array $images) {
assert_instances_of($images, 'PholioImage');
$images = mpull($images, null, 'getPHID');
$images = msort($images, 'getSequence');
$this->images = $images;
return $this;
}
public function getImages() {
return $this->assertAttached($this->images);
}
public function getActiveImages() {
$images = $this->getImages();
foreach ($images as $phid => $image) {
if ($image->getIsObsolete()) {
unset($images[$phid]);
}
}
return $images;
}
public function attachCoverFile(PhabricatorFile $file) {
$this->coverFile = $file;
return $this;
}
public function getCoverFile() {
$this->assertAttached($this->coverFile);
return $this->coverFile;
}
public function getTokenCount() {
$this->assertAttached($this->tokenCount);
return $this->tokenCount;
}
public function attachTokenCount($count) {
$this->tokenCount = $count;
return $this;
}
public function getImageHistorySet($image_id) {
$images = $this->getImages();
$images = mpull($images, null, 'getID');
$selected_image = $images[$image_id];
$replace_map = mpull($images, null, 'getReplacesImagePHID');
$phid_map = mpull($images, null, 'getPHID');
// find the earliest image
$image = $selected_image;
while (isset($phid_map[$image->getReplacesImagePHID()])) {
$image = $phid_map[$image->getReplacesImagePHID()];
}
// now build history moving forward
$history = array($image->getID() => $image);
while (isset($replace_map[$image->getPHID()])) {
$image = $replace_map[$image->getPHID()];
$history[$image->getID()] = $image;
}
return $history;
}
public function getStatuses() {
$options = array();
$options[self::STATUS_OPEN] = pht('Open');
$options[self::STATUS_CLOSED] = pht('Closed');
return $options;
}
public function isClosed() {
return ($this->getStatus() == 'closed');
}
/* -( PhabricatorSubscribableInterface Implementation )-------------------- */
public function isAutomaticallySubscribed($phid) {
return ($this->authorPHID == $phid);
}
/* -( PhabricatorPolicyInterface Implementation )-------------------------- */
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 ($viewer->getPHID() == $this->getAuthorPHID());
}
public function describeAutomaticCapability($capability) {
return pht("A mock's owner can always view and edit it.");
}
/* -( PhabricatorApplicationTransactionInterface )------------------------- */
public function getApplicationTransactionEditor() {
return new PholioMockEditor();
}
public function getApplicationTransactionTemplate() {
return new PholioTransaction();
}
/* -( PhabricatorTokenReceiverInterface )---------------------------------- */
public function getUsersToNotifyOfTokenGiven() {
return array(
$this->getAuthorPHID(),
);
}
/* -( PhabricatorDestructibleInterface )----------------------------------- */
public function destroyObjectPermanently(
PhabricatorDestructionEngine $engine) {
$this->openTransaction();
$images = id(new PholioImageQuery())
->setViewer($engine->getViewer())
->withMockPHIDs(array($this->getPHID()))
->execute();
foreach ($images as $image) {
$image->delete();
}
$this->delete();
$this->saveTransaction();
}
/* -( PhabricatorSpacesInterface )----------------------------------------- */
public function getSpacePHID() {
return $this->spacePHID;
}
/* -( PhabricatorFulltextInterface )--------------------------------------- */
public function newFulltextEngine() {
return new PholioMockFulltextEngine();
}
/* -( PhabricatorFerretInterface )----------------------------------------- */
public function newFerretEngine() {
return new PholioMockFerretEngine();
}
/* -( PhabricatorTimelineInterace )---------------------------------------- */
public function newTimelineEngine() {
return new PholioMockTimelineEngine();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/query/PholioImageQuery.php | src/applications/pholio/query/PholioImageQuery.php | <?php
final class PholioImageQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $mockPHIDs;
private $mocks;
private $needInlineComments;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withMocks(array $mocks) {
assert_instances_of($mocks, 'PholioMock');
$mocks = mpull($mocks, null, 'getPHID');
$this->mocks = $mocks;
$this->mockPHIDs = array_keys($mocks);
return $this;
}
public function withMockPHIDs(array $mock_phids) {
$this->mockPHIDs = $mock_phids;
return $this;
}
public function needInlineComments($need_inline_comments) {
$this->needInlineComments = $need_inline_comments;
return $this;
}
public function newResultObject() {
return new PholioImage();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->mockPHIDs !== null) {
$where[] = qsprintf(
$conn,
'mockPHID IN (%Ls)',
$this->mockPHIDs);
}
return $where;
}
protected function willFilterPage(array $images) {
assert_instances_of($images, 'PholioImage');
$mock_phids = array();
foreach ($images as $image) {
if (!$image->hasMock()) {
continue;
}
$mock_phids[] = $image->getMockPHID();
}
if ($mock_phids) {
if ($this->mocks) {
$mocks = $this->mocks;
} else {
$mocks = id(new PholioMockQuery())
->setViewer($this->getViewer())
->withPHIDs($mock_phids)
->execute();
}
$mocks = mpull($mocks, null, 'getPHID');
foreach ($images as $key => $image) {
if (!$image->hasMock()) {
continue;
}
$mock = idx($mocks, $image->getMockPHID());
if (!$mock) {
unset($images[$key]);
$this->didRejectResult($image);
continue;
}
$image->attachMock($mock);
}
}
return $images;
}
protected function didFilterPage(array $images) {
assert_instances_of($images, 'PholioImage');
$file_phids = mpull($images, 'getFilePHID');
$all_files = id(new PhabricatorFileQuery())
->setParentQuery($this)
->setViewer($this->getViewer())
->withPHIDs($file_phids)
->execute();
$all_files = mpull($all_files, null, 'getPHID');
if ($this->needInlineComments) {
// Only load inline comments the viewer has permission to see.
$all_inline_comments = id(new PholioTransactionComment())->loadAllWhere(
'imageID IN (%Ld)
AND (transactionPHID IS NOT NULL OR authorPHID = %s)',
mpull($images, 'getID'),
$this->getViewer()->getPHID());
$all_inline_comments = mgroup($all_inline_comments, 'getImageID');
}
foreach ($images as $image) {
$file = idx($all_files, $image->getFilePHID());
if (!$file) {
$file = PhabricatorFile::loadBuiltin($this->getViewer(), 'missing.png');
}
$image->attachFile($file);
if ($this->needInlineComments) {
$inlines = idx($all_inline_comments, $image->getID(), array());
$image->attachInlineComments($inlines);
}
}
return $images;
}
public function getQueryApplicationClass() {
return 'PhabricatorPholioApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/query/PholioMockQuery.php | src/applications/pholio/query/PholioMockQuery.php | <?php
final class PholioMockQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
private $ids;
private $phids;
private $authorPHIDs;
private $statuses;
private $needCoverFiles;
private $needImages;
private $needInlineComments;
private $needTokenCounts;
public function withIDs(array $ids) {
$this->ids = $ids;
return $this;
}
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withAuthorPHIDs(array $author_phids) {
$this->authorPHIDs = $author_phids;
return $this;
}
public function withStatuses(array $statuses) {
$this->statuses = $statuses;
return $this;
}
public function needCoverFiles($need_cover_files) {
$this->needCoverFiles = $need_cover_files;
return $this;
}
public function needImages($need_images) {
$this->needImages = $need_images;
return $this;
}
public function needInlineComments($need_inline_comments) {
$this->needInlineComments = $need_inline_comments;
return $this;
}
public function needTokenCounts($need) {
$this->needTokenCounts = $need;
return $this;
}
public function newResultObject() {
return new PholioMock();
}
protected function loadPage() {
if ($this->needInlineComments && !$this->needImages) {
throw new Exception(
pht(
'You can not query for inline comments without also querying for '.
'images.'));
}
return $this->loadStandardPage(new PholioMock());
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->ids !== null) {
$where[] = qsprintf(
$conn,
'mock.id IN (%Ld)',
$this->ids);
}
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'mock.phid IN (%Ls)',
$this->phids);
}
if ($this->authorPHIDs !== null) {
$where[] = qsprintf(
$conn,
'mock.authorPHID in (%Ls)',
$this->authorPHIDs);
}
if ($this->statuses !== null) {
$where[] = qsprintf(
$conn,
'mock.status IN (%Ls)',
$this->statuses);
}
return $where;
}
protected function didFilterPage(array $mocks) {
$viewer = $this->getViewer();
if ($this->needImages) {
$images = id(new PholioImageQuery())
->setViewer($viewer)
->withMocks($mocks)
->needInlineComments($this->needInlineComments)
->execute();
$image_groups = mgroup($images, 'getMockPHID');
foreach ($mocks as $mock) {
$images = idx($image_groups, $mock->getPHID(), array());
$mock->attachImages($images);
}
}
if ($this->needCoverFiles) {
$cover_files = id(new PhabricatorFileQuery())
->setViewer($viewer)
->withPHIDs(mpull($mocks, 'getCoverPHID'))
->execute();
$cover_files = mpull($cover_files, null, 'getPHID');
foreach ($mocks as $mock) {
$file = idx($cover_files, $mock->getCoverPHID());
if (!$file) {
$file = PhabricatorFile::loadBuiltin(
$viewer,
'missing.png');
}
$mock->attachCoverFile($file);
}
}
if ($this->needTokenCounts) {
$counts = id(new PhabricatorTokenCountQuery())
->withObjectPHIDs(mpull($mocks, 'getPHID'))
->execute();
foreach ($mocks as $mock) {
$token_count = idx($counts, $mock->getPHID(), 0);
$mock->attachTokenCount($token_count);
}
}
return $mocks;
}
public function getQueryApplicationClass() {
return 'PhabricatorPholioApplication';
}
protected function getPrimaryTableAlias() {
return 'mock';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/query/PholioTransactionQuery.php | src/applications/pholio/query/PholioTransactionQuery.php | <?php
final class PholioTransactionQuery
extends PhabricatorApplicationTransactionQuery {
public function getTemplateApplicationTransaction() {
return new PholioTransaction();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/query/PholioMockSearchEngine.php | src/applications/pholio/query/PholioMockSearchEngine.php | <?php
final class PholioMockSearchEngine extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Pholio Mocks');
}
public function getApplicationClassName() {
return 'PhabricatorPholioApplication';
}
public function newQuery() {
return id(new PholioMockQuery())
->needCoverFiles(true)
->needImages(true)
->needTokenCounts(true);
}
protected function buildCustomSearchFields() {
return array(
id(new PhabricatorUsersSearchField())
->setKey('authorPHIDs')
->setAliases(array('authors'))
->setLabel(pht('Authors')),
id(new PhabricatorSearchCheckboxesField())
->setKey('statuses')
->setLabel(pht('Status'))
->setOptions(
id(new PholioMock())
->getStatuses()),
);
}
protected function buildQueryFromParameters(array $map) {
$query = $this->newQuery();
if ($map['authorPHIDs']) {
$query->withAuthorPHIDs($map['authorPHIDs']);
}
if ($map['statuses']) {
$query->withStatuses($map['statuses']);
}
return $query;
}
protected function getURI($path) {
return '/pholio/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array(
'open' => pht('Open Mocks'),
'all' => pht('All Mocks'),
);
if ($this->requireViewer()->isLoggedIn()) {
$names['authored'] = pht('Authored');
}
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'open':
return $query->setParameter(
'statuses',
array('open'));
case 'all':
return $query;
case 'authored':
return $query->setParameter(
'authorPHIDs',
array($this->requireViewer()->getPHID()));
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $mocks,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($mocks, 'PholioMock');
$viewer = $this->requireViewer();
$handles = $viewer->loadHandles(mpull($mocks, 'getAuthorPHID'));
$xform = PhabricatorFileTransform::getTransformByKey(
PhabricatorFileThumbnailTransform::TRANSFORM_PINBOARD);
$board = new PHUIPinboardView();
foreach ($mocks as $mock) {
$image = $mock->getCoverFile();
$image_uri = $image->getURIForTransform($xform);
list($x, $y) = $xform->getTransformedDimensions($image);
$header = 'M'.$mock->getID().' '.$mock->getName();
$item = id(new PHUIPinboardItemView())
->setUser($viewer)
->setHeader($header)
->setObject($mock)
->setURI('/M'.$mock->getID())
->setImageURI($image_uri)
->setImageSize($x, $y)
->setDisabled($mock->isClosed())
->addIconCount('fa-picture-o', count($mock->getActiveImages()))
->addIconCount('fa-trophy', $mock->getTokenCount());
if ($mock->getAuthorPHID()) {
$author_handle = $handles[$mock->getAuthorPHID()];
$datetime = phabricator_date($mock->getDateCreated(), $viewer);
$item->appendChild(
pht('By %s on %s', $author_handle->renderLink(), $datetime));
}
$board->addItem($item);
}
$result = new PhabricatorApplicationSearchResultView();
$result->setContent($board);
return $result;
}
protected function getNewUserBody() {
$create_button = id(new PHUIButtonView())
->setTag('a')
->setText(pht('Create a Mock'))
->setHref('/pholio/create/')
->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('Upload sets of images for review with revision history and '.
'inline comments.'))
->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/pholio/mail/PholioMockMailReceiver.php | src/applications/pholio/mail/PholioMockMailReceiver.php | <?php
final class PholioMockMailReceiver extends PhabricatorObjectMailReceiver {
public function isEnabled() {
$app_class = 'PhabricatorPholioApplication';
return PhabricatorApplication::isClassInstalled($app_class);
}
protected function getObjectPattern() {
return 'M[1-9]\d*';
}
protected function loadObject($pattern, PhabricatorUser $viewer) {
$id = (int)substr($pattern, 1);
return id(new PholioMockQuery())
->setViewer($viewer)
->withIDs(array($id))
->executeOne();
}
protected function getTransactionReplyHandler() {
return new PholioReplyHandler();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/mail/PholioReplyHandler.php | src/applications/pholio/mail/PholioReplyHandler.php | <?php
final class PholioReplyHandler
extends PhabricatorApplicationTransactionReplyHandler {
public function validateMailReceiver($mail_receiver) {
if (!($mail_receiver instanceof PholioMock)) {
throw new Exception(pht('Mail receiver is not a %s!', 'PholioMock'));
}
}
public function getObjectPrefix() {
return 'M';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/editor/PholioMockEditor.php | src/applications/pholio/editor/PholioMockEditor.php | <?php
final class PholioMockEditor extends PhabricatorApplicationTransactionEditor {
private $images = array();
public function getEditorApplicationClass() {
return 'PhabricatorPholioApplication';
}
public function getEditorObjectsDescription() {
return pht('Pholio Mocks');
}
public function getCreateObjectTitle($author, $object) {
return pht('%s created this mock.', $author);
}
public function getCreateObjectTitleForFeed($author, $object) {
return pht('%s created %s.', $author, $object);
}
public function getTransactionTypes() {
$types = parent::getTransactionTypes();
$types[] = PhabricatorTransactions::TYPE_EDGE;
$types[] = PhabricatorTransactions::TYPE_COMMENT;
$types[] = PhabricatorTransactions::TYPE_VIEW_POLICY;
$types[] = PhabricatorTransactions::TYPE_EDIT_POLICY;
return $types;
}
protected function shouldSendMail(
PhabricatorLiskDAO $object,
array $xactions) {
return true;
}
protected function buildReplyHandler(PhabricatorLiskDAO $object) {
return id(new PholioReplyHandler())
->setMailReceiver($object);
}
protected function buildMailTemplate(PhabricatorLiskDAO $object) {
$monogram = $object->getMonogram();
$name = $object->getName();
return id(new PhabricatorMetaMTAMail())
->setSubject("{$monogram}: {$name}");
}
protected function getMailTo(PhabricatorLiskDAO $object) {
return array(
$object->getAuthorPHID(),
$this->requireActor()->getPHID(),
);
}
protected function buildMailBody(
PhabricatorLiskDAO $object,
array $xactions) {
$viewer = $this->requireActor();
$body = id(new PhabricatorMetaMTAMailBody())
->setViewer($viewer);
$mock_uri = $object->getURI();
$mock_uri = PhabricatorEnv::getProductionURI($mock_uri);
$this->addHeadersAndCommentsToMailBody(
$body,
$xactions,
pht('View Mock'),
$mock_uri);
$type_inline = PholioMockInlineTransaction::TRANSACTIONTYPE;
$inlines = array();
foreach ($xactions as $xaction) {
if ($xaction->getTransactionType() == $type_inline) {
$inlines[] = $xaction;
}
}
$this->appendInlineCommentsForMail($object, $inlines, $body);
$body->addLinkSection(
pht('MOCK DETAIL'),
PhabricatorEnv::getProductionURI($object->getURI()));
return $body;
}
private function appendInlineCommentsForMail(
$object,
array $inlines,
PhabricatorMetaMTAMailBody $body) {
if (!$inlines) {
return;
}
$viewer = $this->requireActor();
$header = pht('INLINE COMMENTS');
$body->addRawPlaintextSection($header);
$body->addRawHTMLSection(phutil_tag('strong', array(), $header));
$image_ids = array();
foreach ($inlines as $inline) {
$comment = $inline->getComment();
$image_id = $comment->getImageID();
$image_ids[$image_id] = $image_id;
}
$images = id(new PholioImageQuery())
->setViewer($viewer)
->withIDs($image_ids)
->execute();
$images = mpull($images, null, 'getID');
foreach ($inlines as $inline) {
$comment = $inline->getComment();
$content = $comment->getContent();
$image_id = $comment->getImageID();
$image = idx($images, $image_id);
if ($image) {
$image_name = $image->getName();
} else {
$image_name = pht('Unknown (ID %d)', $image_id);
}
$body->addRemarkupSection(
pht('Image "%s":', $image_name),
$content);
}
}
protected function getMailSubjectPrefix() {
return pht('[Pholio]');
}
public function getMailTagsMap() {
return array(
PholioTransaction::MAILTAG_STATUS =>
pht("A mock's status changes."),
PholioTransaction::MAILTAG_COMMENT =>
pht('Someone comments on a mock.'),
PholioTransaction::MAILTAG_UPDATED =>
pht('Mock images or descriptions change.'),
PholioTransaction::MAILTAG_OTHER =>
pht('Other mock activity not listed above occurs.'),
);
}
protected function shouldPublishFeedStory(
PhabricatorLiskDAO $object,
array $xactions) {
return true;
}
protected function supportsSearch() {
return true;
}
protected function shouldApplyHeraldRules(
PhabricatorLiskDAO $object,
array $xactions) {
return true;
}
protected function buildHeraldAdapter(
PhabricatorLiskDAO $object,
array $xactions) {
return id(new HeraldPholioMockAdapter())
->setMock($object);
}
protected function sortTransactions(array $xactions) {
$head = array();
$tail = array();
// Move inline comments to the end, so the comments precede them.
foreach ($xactions as $xaction) {
$type = $xaction->getTransactionType();
if ($type == PholioMockInlineTransaction::TRANSACTIONTYPE) {
$tail[] = $xaction;
} else {
$head[] = $xaction;
}
}
return array_values(array_merge($head, $tail));
}
protected function shouldImplyCC(
PhabricatorLiskDAO $object,
PhabricatorApplicationTransaction $xaction) {
switch ($xaction->getTransactionType()) {
case PholioMockInlineTransaction::TRANSACTIONTYPE:
return true;
}
return parent::shouldImplyCC($object, $xaction);
}
public function loadPholioImage($object, $phid) {
if (!isset($this->images[$phid])) {
$image = id(new PholioImageQuery())
->setViewer($this->getActor())
->withPHIDs(array($phid))
->executeOne();
if (!$image) {
throw new Exception(
pht(
'No image exists with PHID "%s".',
$phid));
}
$mock_phid = $image->getMockPHID();
if ($mock_phid) {
if ($mock_phid !== $object->getPHID()) {
throw new Exception(
pht(
'Image ("%s") belongs to the wrong object ("%s", expected "%s").',
$phid,
$mock_phid,
$object->getPHID()));
}
}
$this->images[$phid] = $image;
}
return $this->images[$phid];
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/xaction/PholioMockDescriptionTransaction.php | src/applications/pholio/xaction/PholioMockDescriptionTransaction.php | <?php
final class PholioMockDescriptionTransaction
extends PholioMockTransactionType {
const TRANSACTIONTYPE = 'description';
public function generateOldValue($object) {
return $object->getDescription();
}
public function applyInternalEffects($object, $value) {
$object->setDescription($value);
}
public function getTitle() {
return pht(
"%s updated the mock's description.",
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s updated the description for %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function shouldHide() {
$old = $this->getOldValue();
return ($old === null);
}
public function hasChangeDetailView() {
return true;
}
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/pholio/xaction/PholioMockInlineTransaction.php | src/applications/pholio/xaction/PholioMockInlineTransaction.php | <?php
final class PholioMockInlineTransaction
extends PholioMockTransactionType {
const TRANSACTIONTYPE = 'inline';
public function generateOldValue($object) {
return null;
}
public function getTitle() {
return pht(
'%s added inline comment(s).',
$this->renderAuthor());
}
public function getTitleForFeed() {
return pht(
'%s added an inline comment to %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getIcon() {
return 'fa-comment';
}
public function getTransactionHasEffect($object, $old, $new) {
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/pholio/xaction/PholioMockStatusTransaction.php | src/applications/pholio/xaction/PholioMockStatusTransaction.php | <?php
final class PholioMockStatusTransaction
extends PholioMockTransactionType {
const TRANSACTIONTYPE = 'status';
public function generateOldValue($object) {
return $object->getStatus();
}
public function applyInternalEffects($object, $value) {
$object->setStatus($value);
}
public function getTitle() {
$new = $this->getNewValue();
if ($new == PholioMock::STATUS_CLOSED) {
return pht(
'%s closed this mock.',
$this->renderAuthor());
} else {
return pht(
'%s opened this mock.',
$this->renderAuthor());
}
}
public function getTitleForFeed() {
$new = $this->getNewValue();
if ($new == PholioMock::STATUS_CLOSED) {
return pht(
'%s closed mock %s.',
$this->renderAuthor(),
$this->renderObject());
} else {
return pht(
'%s opened mock %s.',
$this->renderAuthor(),
$this->renderObject());
}
}
public function getIcon() {
$new = $this->getNewValue();
if ($new == PholioMock::STATUS_CLOSED) {
return 'fa-ban';
} else {
return 'fa-check';
}
}
public function getColor() {
$new = $this->getNewValue();
if ($new == PholioMock::STATUS_CLOSED) {
return PhabricatorTransactions::COLOR_INDIGO;
} else {
return PhabricatorTransactions::COLOR_GREEN;
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/xaction/PholioImageTransactionType.php | src/applications/pholio/xaction/PholioImageTransactionType.php | <?php
abstract class PholioImageTransactionType
extends PholioTransactionType {
protected function getImageForXaction(PholioMock $mock) {
$raw_new_value = $this->getNewValue();
$image_phid = head_key($raw_new_value);
$images = $mock->getImages();
foreach ($images as $image) {
if ($image->getPHID() == $image_phid) {
return $image;
}
}
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/pholio/xaction/PholioImageNameTransaction.php | src/applications/pholio/xaction/PholioImageNameTransaction.php | <?php
final class PholioImageNameTransaction
extends PholioImageTransactionType {
const TRANSACTIONTYPE = 'image-name';
public function generateOldValue($object) {
$name = null;
$phid = null;
$image = $this->getImageForXaction($object);
if ($image) {
$name = $image->getName();
$phid = $image->getPHID();
}
return array($phid => $name);
}
public function applyInternalEffects($object, $value) {
$image = $this->getImageForXaction($object);
$value = (string)head($this->getNewValue());
$image->setName($value);
$image->save();
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
return pht(
'%s renamed an image (%s) from %s to %s.',
$this->renderAuthor(),
$this->renderHandle(key($new)),
$this->renderValue($old),
$this->renderValue($new));
}
public function getTitleForFeed() {
return pht(
'%s updated the image names of %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function mergeTransactions(
$object,
PhabricatorApplicationTransaction $u,
PhabricatorApplicationTransaction $v) {
$raw_new_value_u = $u->getNewValue();
$raw_new_value_v = $v->getNewValue();
$phid_u = head_key($raw_new_value_u);
$phid_v = head_key($raw_new_value_v);
if ($phid_u == $phid_v) {
return $v;
}
return null;
}
public function shouldHide() {
$old = $this->getOldValue();
return ($old === array(null => null));
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$max_length = $object->getColumnMaximumByteLength('name');
foreach ($xactions as $xaction) {
$new_value = head(array_values($xaction->getNewValue()));
$new_length = strlen($new_value);
if ($new_length > $max_length) {
$errors[] = $this->newInvalidError(
pht(
'Mock image names must not be longer than %s character(s).',
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/pholio/xaction/PholioMockNameTransaction.php | src/applications/pholio/xaction/PholioMockNameTransaction.php | <?php
final class PholioMockNameTransaction
extends PholioMockTransactionType {
const TRANSACTIONTYPE = 'name';
public function generateOldValue($object) {
return $object->getName();
}
public function getActionStrength() {
return 140;
}
public function applyInternalEffects($object, $value) {
$object->setName($value);
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old === null) {
return pht(
'%s created %s.',
$this->renderAuthor(),
$this->renderValue($new));
} else {
return pht(
'%s renamed this mock from %s to %s.',
$this->renderAuthor(),
$this->renderValue($old),
$this->renderValue($new));
}
}
public function getTitleForFeed() {
$old = $this->getOldValue();
$new = $this->getNewValue();
if ($old === null) {
return pht(
'%s created %s.',
$this->renderAuthor(),
$this->renderObject());
} else {
return pht(
'%s renamed %s from %s to %s.',
$this->renderAuthor(),
$this->renderObject(),
$this->renderValue($old),
$this->renderValue($new));
}
}
public function getColor() {
$old = $this->getOldValue();
if ($old === null) {
return PhabricatorTransactions::COLOR_GREEN;
}
return parent::getColor();
}
public function validateTransactions($object, array $xactions) {
$errors = array();
if ($this->isEmptyTextTransaction($object->getName(), $xactions)) {
$errors[] = $this->newRequiredError(pht('Mocks must have a name.'));
}
$max_length = $object->getColumnMaximumByteLength('name');
foreach ($xactions as $xaction) {
$new_value = $xaction->getNewValue();
$new_length = strlen($new_value);
if ($new_length > $max_length) {
$errors[] = $this->newInvalidError(
pht(
'Mock names must not be longer than %s character(s).',
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/pholio/xaction/PholioMockTransactionType.php | src/applications/pholio/xaction/PholioMockTransactionType.php | <?php
abstract class PholioMockTransactionType
extends PholioTransactionType {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/xaction/PholioImageDescriptionTransaction.php | src/applications/pholio/xaction/PholioImageDescriptionTransaction.php | <?php
final class PholioImageDescriptionTransaction
extends PholioImageTransactionType {
const TRANSACTIONTYPE = 'image-description';
public function generateOldValue($object) {
$description = null;
$phid = null;
$image = $this->getImageForXaction($object);
if ($image) {
$description = $image->getDescription();
$phid = $image->getPHID();
}
return array($phid => $description);
}
public function applyInternalEffects($object, $value) {
$image = $this->getImageForXaction($object);
$value = (string)head($this->getNewValue());
$image->setDescription($value);
$image->save();
}
public function getTitle() {
$new = $this->getNewValue();
return pht(
'%s updated an image\'s (%s) description.',
$this->renderAuthor(),
$this->renderHandle(head_key($new)));
}
public function getTitleForFeed() {
return pht(
'%s updated image descriptions of %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function mergeTransactions(
$object,
PhabricatorApplicationTransaction $u,
PhabricatorApplicationTransaction $v) {
$raw_new_value_u = $u->getNewValue();
$raw_new_value_v = $v->getNewValue();
$phid_u = head_key($raw_new_value_u);
$phid_v = head_key($raw_new_value_v);
if ($phid_u == $phid_v) {
return $v;
}
return null;
}
public function shouldHide() {
$old = $this->getOldValue();
return ($old === array(null => null));
}
public function hasChangeDetailView() {
return true;
}
public function newChangeDetailView() {
$viewer = $this->getViewer();
return id(new PhabricatorApplicationTransactionTextDiffDetailView())
->setViewer($viewer)
->setOldText(head($this->getOldValue()))
->setNewText(head($this->getNewValue()));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/xaction/PholioImageSequenceTransaction.php | src/applications/pholio/xaction/PholioImageSequenceTransaction.php | <?php
final class PholioImageSequenceTransaction
extends PholioImageTransactionType {
const TRANSACTIONTYPE = 'image-sequence';
public function generateOldValue($object) {
$sequence = null;
$phid = null;
$image = $this->getImageForXaction($object);
if ($image) {
$sequence = $image->getSequence();
$phid = $image->getPHID();
}
return array($phid => $sequence);
}
public function applyInternalEffects($object, $value) {
$image = $this->getImageForXaction($object);
$value = (int)head($this->getNewValue());
$image->setSequence($value);
$image->save();
}
public function getTitle() {
$new = $this->getNewValue();
return pht(
'%s updated an image\'s (%s) sequence.',
$this->renderAuthor(),
$this->renderHandleLink(key($new)));
}
public function getTitleForFeed() {
return pht(
'%s updated image sequence of %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function shouldHide() {
// this is boring / silly to surface; changing sequence is NBD
return true;
}
public function mergeTransactions(
$object,
PhabricatorApplicationTransaction $u,
PhabricatorApplicationTransaction $v) {
$raw_new_value_u = $u->getNewValue();
$raw_new_value_v = $v->getNewValue();
$phid_u = key($raw_new_value_u);
$phid_v = key($raw_new_value_v);
if ($phid_u == $phid_v) {
return $v;
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/xaction/PholioImageFileTransaction.php | src/applications/pholio/xaction/PholioImageFileTransaction.php | <?php
final class PholioImageFileTransaction
extends PholioImageTransactionType {
const TRANSACTIONTYPE = 'image-file';
public function generateOldValue($object) {
$images = $object->getActiveImages();
return array_values(mpull($images, 'getPHID'));
}
public function generateNewValue($object, $value) {
$editor = $this->getEditor();
$old_value = $this->getOldValue();
$new_value = $value;
return $editor->getPHIDList($old_value, $new_value);
}
public function applyExternalEffects($object, $value) {
$old_map = array_fuse($this->getOldValue());
$new_map = array_fuse($this->getNewValue());
$add_map = array_diff_key($new_map, $old_map);
$rem_map = array_diff_key($old_map, $new_map);
$editor = $this->getEditor();
foreach ($rem_map as $phid) {
$editor->loadPholioImage($object, $phid)
->setIsObsolete(1)
->save();
}
foreach ($add_map as $phid) {
$editor->loadPholioImage($object, $phid)
->setMockPHID($object->getPHID())
->save();
}
}
public function getTitle() {
$old = $this->getOldValue();
$new = $this->getNewValue();
$add = array_diff($new, $old);
$rem = array_diff($old, $new);
if ($add && $rem) {
return pht(
'%s edited image(s), added %d: %s; removed %d: %s.',
$this->renderAuthor(),
count($add),
$this->renderHandleList($add),
count($rem),
$this->renderHandleList($rem));
} else if ($add) {
return pht(
'%s added %d image(s): %s.',
$this->renderAuthor(),
count($add),
$this->renderHandleList($add));
} else {
return pht(
'%s removed %d image(s): %s.',
$this->renderAuthor(),
count($rem),
$this->renderHandleList($rem));
}
}
public function getTitleForFeed() {
$old = $this->getOldValue();
$new = $this->getNewValue();
return pht(
'%s updated images of %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getIcon() {
return 'fa-picture-o';
}
public function getColor() {
$old = $this->getOldValue();
$new = $this->getNewValue();
$add = array_diff($new, $old);
$rem = array_diff($old, $new);
if ($add && $rem) {
return PhabricatorTransactions::COLOR_YELLOW;
} else if ($add) {
return PhabricatorTransactions::COLOR_GREEN;
} else {
return PhabricatorTransactions::COLOR_RED;
}
}
public function extractFilePHIDs($object, $value) {
$editor = $this->getEditor();
// NOTE: This method is a little weird (and includes ALL the file PHIDs,
// including old file PHIDs) because we currently don't have a storage
// object when called. This might change at some point.
$image_changes = $value;
$image_phids = array();
foreach ($image_changes as $change_type => $phids) {
foreach ($phids as $phid) {
$image_phids[$phid] = $phid;
}
}
$file_phids = array();
foreach ($image_phids as $image_phid) {
$file_phids[] = $editor->loadPholioImage($object, $image_phid)
->getFilePHID();
}
return $file_phids;
}
public function mergeTransactions(
$object,
PhabricatorApplicationTransaction $u,
PhabricatorApplicationTransaction $v) {
return $this->getEditor()->mergePHIDOrEdgeTransactions($u, $v);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/xaction/PholioImageReplaceTransaction.php | src/applications/pholio/xaction/PholioImageReplaceTransaction.php | <?php
final class PholioImageReplaceTransaction
extends PholioImageTransactionType {
const TRANSACTIONTYPE = 'image-replace';
public function generateOldValue($object) {
$editor = $this->getEditor();
$new_phid = $this->getNewValue();
return $editor->loadPholioImage($object, $new_phid)
->getReplacesImagePHID();
}
public function applyExternalEffects($object, $value) {
$editor = $this->getEditor();
$old_phid = $this->getOldValue();
$old_image = $editor->loadPholioImage($object, $old_phid)
->setIsObsolete(1)
->save();
$editor->loadPholioImage($object, $value)
->setMockPHID($object->getPHID())
->setSequence($old_image->getSequence())
->save();
}
public function getTitle() {
return pht(
'%s replaced %s with %s.',
$this->renderAuthor(),
$this->renderOldHandle(),
$this->renderNewHandle());
}
public function getTitleForFeed() {
return pht(
'%s updated images of %s.',
$this->renderAuthor(),
$this->renderObject());
}
public function getIcon() {
return 'fa-picture-o';
}
public function getColor() {
return PhabricatorTransactions::COLOR_YELLOW;
}
public function mergeTransactions(
$object,
PhabricatorApplicationTransaction $u,
PhabricatorApplicationTransaction $v) {
$u_phid = $u->getOldValue();
$v_phid = $v->getOldValue();
if ($u_phid === $v_phid) {
return $v;
}
return null;
}
public function extractFilePHIDs($object, $value) {
$editor = $this->getEditor();
$file_phid = $editor->loadPholioImage($object, $value)
->getFilePHID();
return array($file_phid);
}
public function validateTransactions($object, array $xactions) {
$errors = array();
$mock_phid = $object->getPHID();
$editor = $this->getEditor();
foreach ($xactions as $xaction) {
$new_phid = $xaction->getNewValue();
try {
$new_image = $editor->loadPholioImage($object, $new_phid);
} catch (Exception $ex) {
$errors[] = $this->newInvalidError(
pht(
'Unable to load replacement image ("%s"): %s',
$new_phid,
$ex->getMessage()),
$xaction);
continue;
}
$old_phid = $new_image->getReplacesImagePHID();
if (!$old_phid) {
$errors[] = $this->newInvalidError(
pht(
'Image ("%s") does not specify which image it replaces.',
$new_phid),
$xaction);
continue;
}
try {
$old_image = $editor->loadPholioImage($object, $old_phid);
} catch (Exception $ex) {
$errors[] = $this->newInvalidError(
pht(
'Unable to load replaced image ("%s"): %s',
$old_phid,
$ex->getMessage()),
$xaction);
continue;
}
if ($old_image->getMockPHID() !== $mock_phid) {
$errors[] = $this->newInvalidError(
pht(
'Replaced image ("%s") belongs to the wrong mock ("%s", expected '.
'"%s").',
$old_phid,
$old_image->getMockPHID(),
$mock_phid),
$xaction);
continue;
}
// TODO: You shouldn't be able to replace an image if it has already
// been replaced.
}
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/pholio/xaction/PholioTransactionType.php | src/applications/pholio/xaction/PholioTransactionType.php | <?php
abstract class PholioTransactionType
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/pholio/relationships/PholioMockHasTaskRelationship.php | src/applications/pholio/relationships/PholioMockHasTaskRelationship.php | <?php
final class PholioMockHasTaskRelationship
extends PholioMockRelationship {
const RELATIONSHIPKEY = 'mock.has-task';
public function getEdgeConstant() {
return PholioMockHasTaskEdgeType::EDGECONST;
}
protected function getActionName() {
return pht('Edit Tasks');
}
protected function getActionIcon() {
return 'fa-anchor';
}
public function canRelateObjects($src, $dst) {
return ($dst instanceof ManiphestTask);
}
public function getDialogTitleText() {
return pht('Edit Related Tasks');
}
public function getDialogHeaderText() {
return pht('Current Tasks');
}
public function getDialogButtonText() {
return pht('Save Related Tasks');
}
protected function newRelationshipSource() {
return new ManiphestTaskRelationshipSource();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/relationships/PholioMockRelationship.php | src/applications/pholio/relationships/PholioMockRelationship.php | <?php
abstract class PholioMockRelationship
extends PhabricatorObjectRelationship {
public function isEnabledForObject($object) {
$viewer = $this->getViewer();
$has_app = PhabricatorApplication::isClassInstalledForViewer(
'PhabricatorPholioApplication',
$viewer);
if (!$has_app) {
return false;
}
return ($object instanceof PholioMock);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/application/PhabricatorPholioApplication.php | src/applications/pholio/application/PhabricatorPholioApplication.php | <?php
final class PhabricatorPholioApplication extends PhabricatorApplication {
public function getName() {
return pht('Pholio');
}
public function getBaseURI() {
return '/pholio/';
}
public function getShortDescription() {
return pht('Review Mocks and Design');
}
public function getIcon() {
return 'fa-camera-retro';
}
public function getTitleGlyph() {
return "\xE2\x9D\xA6";
}
public function getFlavorText() {
return pht('Things before they were cool.');
}
public function getRemarkupRules() {
return array(
new PholioRemarkupRule(),
);
}
public function getRoutes() {
return array(
'/M(?P<id>[1-9]\d*)(?:/(?P<imageID>\d+)/)?' => 'PholioMockViewController',
'/pholio/' => array(
'(?:query/(?P<queryKey>[^/]+)/)?' => 'PholioMockListController',
'new/' => 'PholioMockEditController',
'create/' => 'PholioMockEditController',
'edit/(?P<id>\d+)/' => 'PholioMockEditController',
'archive/(?P<id>\d+)/' => 'PholioMockArchiveController',
'comment/(?P<id>\d+)/' => 'PholioMockCommentController',
'inline/' => array(
'(?:(?P<id>\d+)/)?' => 'PholioInlineController',
'list/(?P<id>\d+)/' => 'PholioInlineListController',
),
'image/' => array(
'upload/' => 'PholioImageUploadController',
),
),
);
}
protected function getCustomCapabilities() {
return array(
PholioDefaultViewCapability::CAPABILITY => array(
'template' => PholioMockPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_VIEW,
),
PholioDefaultEditCapability::CAPABILITY => array(
'template' => PholioMockPHIDType::TYPECONST,
'capability' => PhabricatorPolicyCapability::CAN_EDIT,
),
);
}
public function getMailCommandObjects() {
return array(
'mock' => array(
'name' => pht('Email Commands: Mocks'),
'header' => pht('Interacting with Pholio Mocks'),
'object' => new PholioMock(),
'summary' => pht(
'This page documents the commands you can use to interact with '.
'mocks in Pholio.'),
),
);
}
public function getApplicationSearchDocumentTypes() {
return array(
PholioMockPHIDType::TYPECONST,
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/lipsum/PhabricatorPholioMockTestDataGenerator.php | src/applications/pholio/lipsum/PhabricatorPholioMockTestDataGenerator.php | <?php
final class PhabricatorPholioMockTestDataGenerator
extends PhabricatorTestDataGenerator {
const GENERATORKEY = 'mocks';
public function getGeneratorName() {
return pht('Pholio Mocks');
}
public function generateObject() {
$author_phid = $this->loadPhabricatorUserPHID();
$author = id(new PhabricatorUser())
->loadOneWhere('phid = %s', $author_phid);
$mock = PholioMock::initializeNewMock($author);
$content_source = $this->getLipsumContentSource();
$template = id(new PholioTransaction())
->setContentSource($content_source);
// Accumulate Transactions
$changes = array();
$changes[PholioMockNameTransaction::TRANSACTIONTYPE] =
$this->generateTitle();
$changes[PholioMockDescriptionTransaction::TRANSACTIONTYPE] =
$this->generateDescription();
$changes[PhabricatorTransactions::TYPE_VIEW_POLICY] =
PhabricatorPolicies::POLICY_PUBLIC;
$changes[PhabricatorTransactions::TYPE_SUBSCRIBERS] =
array('=' => $this->getCCPHIDs());
// Get Files and make Images
$file_phids = $this->generateImages();
$files = id(new PhabricatorFileQuery())
->setViewer($author)
->withPHIDs($file_phids)
->execute();
$mock->setCoverPHID(head($files)->getPHID());
$sequence = 0;
$images = array();
foreach ($files as $file) {
$image = PholioImage::initializeNewImage()
->setAuthorPHID($author_phid)
->setFilePHID($file->getPHID())
->setSequence($sequence++)
->attachMock($mock);
$images[] = $image;
}
// Apply Transactions
$transactions = array();
foreach ($changes as $type => $value) {
$transaction = clone $template;
$transaction->setTransactionType($type);
$transaction->setNewValue($value);
$transactions[] = $transaction;
}
$mock->openTransaction();
$editor = id(new PholioMockEditor())
->setContentSource($content_source)
->setContinueOnNoEffect(true)
->setActor($author)
->applyTransactions($mock, $transactions);
foreach ($images as $image) {
$image->setMockPHID($mock->getPHID());
$image->save();
}
$mock->saveTransaction();
return $mock->save();
}
public function generateTitle() {
return id(new PhutilLipsumContextFreeGrammar())
->generate();
}
public function generateDescription() {
return id(new PhutilLipsumContextFreeGrammar())
->generateSeveral(rand(30, 40));
}
public function getCCPHIDs() {
$ccs = array();
for ($i = 0; $i < rand(1, 4);$i++) {
$ccs[] = $this->loadPhabricatorUserPHID();
}
return $ccs;
}
public function generateImages() {
$images = newv('PhabricatorFile', array())
->loadAllWhere('mimeType = %s', 'image/jpeg');
$rand_images = array();
$quantity = rand(2, 10);
$quantity = min($quantity, count($images));
if ($quantity) {
$random_images = $quantity === 1 ?
array(array_rand($images, $quantity)) :
array_rand($images, $quantity);
foreach ($random_images as $random) {
$rand_images[] = $images[$random]->getPHID();
}
}
// This means you don't have any JPEGs yet. We'll just use a built-in image.
if (empty($rand_images)) {
$default = PhabricatorFile::loadBuiltin(
PhabricatorUser::getOmnipotentUser(),
'profile.png');
$rand_images[] = $default->getPHID();
}
return $rand_images;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/view/PholioMockImagesView.php | src/applications/pholio/view/PholioMockImagesView.php | <?php
final class PholioMockImagesView extends AphrontView {
private $mock;
private $imageID;
private $requestURI;
private $commentFormID;
private $panelID;
private $viewportID;
private $behaviorConfig;
public function setCommentFormID($comment_form_id) {
$this->commentFormID = $comment_form_id;
return $this;
}
public function getCommentFormID() {
return $this->commentFormID;
}
public function setRequestURI(PhutilURI $request_uri) {
$this->requestURI = $request_uri;
return $this;
}
public function getRequestURI() {
return $this->requestURI;
}
public function setImageID($image_id) {
$this->imageID = $image_id;
return $this;
}
public function getImageID() {
return $this->imageID;
}
public function setMock(PholioMock $mock) {
$this->mock = $mock;
return $this;
}
public function getMock() {
return $this->mock;
}
public function __construct() {
$this->panelID = celerity_generate_unique_node_id();
$this->viewportID = celerity_generate_unique_node_id();
}
public function getBehaviorConfig() {
if (!$this->getMock()) {
throw new PhutilInvalidStateException('setMock');
}
if ($this->behaviorConfig === null) {
$this->behaviorConfig = $this->calculateBehaviorConfig();
}
return $this->behaviorConfig;
}
private function calculateBehaviorConfig() {
$mock = $this->getMock();
// TODO: We could maybe do a better job with tailoring this, which is the
// image shown on the review stage.
$viewer = $this->getUser();
$default = PhabricatorFile::loadBuiltin($viewer, 'image-100x100.png');
$images = array();
$current_set = 0;
foreach ($mock->getImages() as $image) {
$file = $image->getFile();
$metadata = $file->getMetadata();
$x = idx($metadata, PhabricatorFile::METADATA_IMAGE_WIDTH);
$y = idx($metadata, PhabricatorFile::METADATA_IMAGE_HEIGHT);
$is_obs = (bool)$image->getIsObsolete();
if (!$is_obs) {
$current_set++;
}
$description = $image->getDescription();
if (strlen($description)) {
$description = new PHUIRemarkupView($viewer, $description);
}
$history_uri = '/pholio/image/history/'.$image->getID().'/';
$images[] = array(
'id' => $image->getID(),
'fullURI' => $file->getBestURI(),
'stageURI' => ($file->isViewableImage()
? $file->getBestURI()
: $default->getBestURI()),
'pageURI' => $this->getImagePageURI($image, $mock),
'downloadURI' => $file->getDownloadURI(),
'historyURI' => $history_uri,
'width' => $x,
'height' => $y,
'title' => $image->getName(),
'descriptionMarkup' => hsprintf('%s', $description),
'isObsolete' => (bool)$image->getIsObsolete(),
'isImage' => $file->isViewableImage(),
'isViewable' => $file->isViewableInBrowser(),
);
}
$ids = mpull($mock->getActiveImages(), null, 'getID');
if ($this->imageID && isset($ids[$this->imageID])) {
$selected_id = $this->imageID;
} else {
$selected_id = head_key($ids);
}
$navsequence = array();
foreach ($mock->getActiveImages() as $image) {
$navsequence[] = $image->getID();
}
$full_icon = array(
javelin_tag('span', array('aural' => true), pht('View Raw File')),
id(new PHUIIconView())->setIcon('fa-file-image-o'),
);
$download_icon = array(
javelin_tag('span', array('aural' => true), pht('Download File')),
id(new PHUIIconView())->setIcon('fa-download'),
);
$login_uri = id(new PhutilURI('/login/'))
->replaceQueryParam('next', (string)$this->getRequestURI());
$config = array(
'mockID' => $mock->getID(),
'panelID' => $this->panelID,
'viewportID' => $this->viewportID,
'commentFormID' => $this->getCommentFormID(),
'images' => $images,
'selectedID' => $selected_id,
'loggedIn' => $this->getUser()->isLoggedIn(),
'logInLink' => (string)$login_uri,
'navsequence' => $navsequence,
'fullIcon' => hsprintf('%s', $full_icon),
'downloadIcon' => hsprintf('%s', $download_icon),
'currentSetSize' => $current_set,
);
return $config;
}
public function render() {
if (!$this->getMock()) {
throw new PhutilInvalidStateException('setMock');
}
$mock = $this->getMock();
require_celerity_resource('javelin-behavior-pholio-mock-view');
$panel_id = $this->panelID;
$viewport_id = $this->viewportID;
$config = $this->getBehaviorConfig();
Javelin::initBehavior(
'pholio-mock-view',
$this->getBehaviorConfig());
$mock_wrapper = javelin_tag(
'div',
array(
'id' => $this->viewportID,
'sigil' => 'mock-viewport',
'class' => 'pholio-mock-image-viewport',
),
'');
$image_header = javelin_tag(
'div',
array(
'id' => 'mock-image-header',
'class' => 'pholio-mock-image-header',
),
'');
$mock_wrapper = javelin_tag(
'div',
array(
'id' => $this->panelID,
'sigil' => 'mock-panel touchable',
'class' => 'pholio-mock-image-panel',
),
array(
$image_header,
$mock_wrapper,
));
$inline_comments_holder = javelin_tag(
'div',
array(
'id' => 'mock-image-description',
'sigil' => 'mock-image-description',
'class' => 'mock-image-description',
),
'');
return phutil_tag(
'div',
array(
'class' => 'pholio-mock-image-container',
'id' => 'pholio-mock-image-container',
),
array($mock_wrapper, $inline_comments_holder));
}
private function getImagePageURI(PholioImage $image, PholioMock $mock) {
$uri = '/M'.$mock->getID().'/'.$image->getID().'/';
return $uri;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/view/PholioTransactionView.php | src/applications/pholio/view/PholioTransactionView.php | <?php
final class PholioTransactionView
extends PhabricatorApplicationTransactionView {
private $mock;
public function setMock($mock) {
$this->mock = $mock;
return $this;
}
public function getMock() {
return $this->mock;
}
protected function shouldGroupTransactions(
PhabricatorApplicationTransaction $u,
PhabricatorApplicationTransaction $v) {
if ($u->getAuthorPHID() != $v->getAuthorPHID()) {
// Don't group transactions by different authors.
return false;
}
if (($v->getDateCreated() - $u->getDateCreated()) > 60) {
// Don't group if transactions happened more than 60s apart.
return false;
}
switch ($u->getTransactionType()) {
case PhabricatorTransactions::TYPE_COMMENT:
case PholioMockInlineTransaction::TRANSACTIONTYPE:
break;
default:
return false;
}
switch ($v->getTransactionType()) {
case PholioMockInlineTransaction::TRANSACTIONTYPE:
return true;
}
return parent::shouldGroupTransactions($u, $v);
}
protected function renderTransactionContent(
PhabricatorApplicationTransaction $xaction) {
$out = array();
$group = $xaction->getTransactionGroup();
$type = $xaction->getTransactionType();
if ($type == PholioMockInlineTransaction::TRANSACTIONTYPE) {
array_unshift($group, $xaction);
} else {
$out[] = parent::renderTransactionContent($xaction);
}
if (!$group) {
return $out;
}
$inlines = array();
foreach ($group as $xaction) {
switch ($xaction->getTransactionType()) {
case PholioMockInlineTransaction::TRANSACTIONTYPE:
$inlines[] = $xaction;
break;
default:
throw new Exception(pht('Unknown grouped transaction type!'));
}
}
if ($inlines) {
$icon = id(new PHUIIconView())
->setIcon('fa-comment bluegrey msr');
$header = phutil_tag(
'div',
array(
'class' => 'phabricator-transaction-subheader',
),
array($icon, pht('Inline Comments')));
$out[] = $header;
foreach ($inlines as $inline) {
if (!$inline->getComment()) {
continue;
}
$out[] = $this->renderInlineContent($inline);
}
}
return $out;
}
private function renderInlineContent(PholioTransaction $inline) {
$comment = $inline->getComment();
$mock = $this->getMock();
$images = $mock->getImages();
$images = mpull($images, null, 'getID');
$image = idx($images, $comment->getImageID());
if (!$image) {
throw new Exception(pht('No image attached!'));
}
$file = $image->getFile();
if (!$file->isViewableImage()) {
throw new Exception(pht('File is not viewable.'));
}
$image_uri = $file->getBestURI();
$thumb = id(new PHUIImageMaskView())
->addClass('mrl')
->setImage($image_uri)
->setDisplayHeight(100)
->setDisplayWidth(200)
->withMask(true)
->centerViewOnPoint(
$comment->getX(), $comment->getY(),
$comment->getHeight(), $comment->getWidth());
$link = phutil_tag(
'a',
array(
'href' => '#',
'class' => 'pholio-transaction-inline-image-anchor',
),
$thumb);
$inline_comment = parent::renderTransactionContent($inline);
return phutil_tag(
'div',
array('class' => 'pholio-transaction-inline-comment'),
array($link, $inline_comment));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/view/PholioUploadedImageView.php | src/applications/pholio/view/PholioUploadedImageView.php | <?php
final class PholioUploadedImageView extends AphrontView {
private $image;
private $replacesPHID;
public function setReplacesPHID($replaces_phid) {
$this->replacesPHID = $replaces_phid;
return $this;
}
public function setImage(PholioImage $image) {
$this->image = $image;
return $this;
}
public function render() {
require_celerity_resource('pholio-edit-css');
$image = $this->image;
$file = $image->getFile();
$phid = $file->getPHID();
$replaces_phid = $this->replacesPHID;
$remove = $this->renderRemoveElement();
$title = id(new AphrontFormTextControl())
->setName('title_'.$phid)
->setValue($image->getName())
->setSigil('image-title')
->setLabel(pht('Title'));
$description = id(new PhabricatorRemarkupControl())
->setUser($this->getUser())
->setName('description_'.$phid)
->setValue($image->getDescription())
->setSigil('image-description')
->setLabel(pht('Description'));
$xform = PhabricatorFileTransform::getTransformByKey(
PhabricatorFileThumbnailTransform::TRANSFORM_PINBOARD);
$thumbnail_uri = $file->getURIForTransform($xform);
$thumb_img = javelin_tag(
'img',
array(
'class' => 'pholio-thumb-img',
'src' => $thumbnail_uri,
'sigil' => 'pholio-uploaded-thumb',
));
$thumb_frame = phutil_tag(
'div',
array(
'class' => 'pholio-thumb-frame',
),
$thumb_img);
$handle = javelin_tag(
'div',
array(
'class' => 'pholio-drag-handle',
'sigil' => 'pholio-drag-handle',
));
$content = hsprintf(
'<div class="pholio-thumb-box">
<div class="pholio-thumb-title">
%s
<div class="pholio-thumb-name">%s</div>
</div>
%s
</div>
<div class="pholio-image-details">
%s
%s
</div>',
$remove,
$file->getName(),
$thumb_frame,
$title,
$description);
$input = phutil_tag(
'input',
array(
'type' => 'hidden',
'name' => 'file_phids[]',
'value' => $phid,
));
$replaces_input = phutil_tag(
'input',
array(
'type' => 'hidden',
'name' => 'replaces['.$replaces_phid.']',
'value' => $phid,
));
return javelin_tag(
'div',
array(
'class' => 'pholio-uploaded-image',
'sigil' => 'pholio-drop-image',
'meta' => array(
'filePHID' => $file->getPHID(),
'replacesPHID' => $replaces_phid,
),
),
array(
$handle,
$content,
$input,
$replaces_input,
));
}
private function renderRemoveElement() {
return javelin_tag(
'a',
array(
'class' => 'button button-grey',
'sigil' => 'pholio-drop-remove',
),
'X');
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/view/PholioMockThumbGridView.php | src/applications/pholio/view/PholioMockThumbGridView.php | <?php
final class PholioMockThumbGridView extends AphrontView {
private $mock;
public function setMock(PholioMock $mock) {
$this->mock = $mock;
return $this;
}
public function render() {
$mock = $this->mock;
$all_images = $mock->getImages();
$all_images = mpull($all_images, null, 'getPHID');
$history = mpull($all_images, 'getReplacesImagePHID', 'getPHID');
$replaced = array();
foreach ($history as $phid => $replaces_phid) {
if ($replaces_phid) {
$replaced[$replaces_phid] = true;
}
}
// Figure out the columns. Start with all the active images.
$images = mpull($mock->getActiveImages(), null, 'getPHID');
// Now, find deleted images: obsolete images which were not replaced.
foreach ($mock->getImages() as $image) {
if (!$image->getIsObsolete()) {
// Image is current.
continue;
}
if (isset($replaced[$image->getPHID()])) {
// Image was replaced.
continue;
}
// This is an obsolete image which was not replaced, so it must be
// a deleted image.
$images[$image->getPHID()] = $image;
}
$cols = array();
$depth = 0;
foreach ($images as $image) {
$phid = $image->getPHID();
$col = array();
// If this is a deleted image, null out the final column.
if ($image->getIsObsolete()) {
$col[] = null;
}
$col[] = $phid;
while ($phid && isset($history[$phid])) {
$col[] = $history[$phid];
$phid = $history[$phid];
}
$cols[] = $col;
$depth = max($depth, count($col));
}
$grid = array();
$jj = $depth;
for ($ii = 0; $ii < $depth; $ii++) {
$row = array();
if ($depth == $jj) {
$row[] = phutil_tag(
'th',
array(
'valign' => 'middle',
'class' => 'pholio-history-header',
),
pht('Current Revision'));
} else {
$row[] = phutil_tag('th', array(), null);
}
foreach ($cols as $col) {
if (empty($col[$ii])) {
$row[] = phutil_tag('td', array(), null);
} else {
$thumb = $this->renderThumbnail($all_images[$col[$ii]]);
$row[] = phutil_tag('td', array(), $thumb);
}
}
$grid[] = phutil_tag('tr', array(), $row);
$jj--;
}
$grid = phutil_tag(
'table',
array(
'id' => 'pholio-mock-thumb-grid',
'class' => 'pholio-mock-thumb-grid',
),
$grid);
$grid = id(new PHUIBoxView())
->addClass('pholio-mock-thumb-grid-container')
->appendChild($grid);
return id(new PHUIObjectBoxView())
->setHeaderText(pht('Mock History'))
->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)
->appendChild($grid);
}
private function renderThumbnail(PholioImage $image) {
$thumbfile = $image->getFile();
$preview_key = PhabricatorFileThumbnailTransform::TRANSFORM_THUMBGRID;
$xform = PhabricatorFileTransform::getTransformByKey($preview_key);
Javelin::initBehavior('phabricator-tooltips');
$attributes = array(
'class' => 'pholio-mock-thumb-grid-image',
'src' => $thumbfile->getURIForTransform($xform),
);
if ($image->getFile()->isViewableImage()) {
$dimensions = $xform->getTransformedDimensions($thumbfile);
if ($dimensions) {
list($x, $y) = $dimensions;
$attributes += array(
'width' => $x,
'height' => $y,
'style' => 'top: '.floor((100 - $y) / 2).'px',
);
}
} else {
// If this is a PDF or a text file or something, we'll end up using a
// generic thumbnail which is always sized correctly.
$attributes += array(
'width' => 100,
'height' => 100,
);
}
$tag = phutil_tag('img', $attributes);
$classes = array('pholio-mock-thumb-grid-item');
if ($image->getIsObsolete()) {
$classes[] = 'pholio-mock-thumb-grid-item-obsolete';
}
$inline_count = null;
if ($image->getInlineComments()) {
$inline_count[] = phutil_tag(
'span',
array(
'class' => 'pholio-mock-thumb-grid-comment-count',
),
pht('%s', phutil_count($image->getInlineComments())));
}
return javelin_tag(
'a',
array(
'sigil' => 'mock-thumbnail has-tooltip',
'class' => implode(' ', $classes),
'href' => '#',
'meta' => array(
'imageID' => $image->getID(),
'tip' => $image->getName(),
'align' => 'N',
),
),
array(
$tag,
$inline_count,
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/view/PholioMockEmbedView.php | src/applications/pholio/view/PholioMockEmbedView.php | <?php
final class PholioMockEmbedView extends AphrontView {
private $mock;
private $images = array();
public function setMock(PholioMock $mock) {
$this->mock = $mock;
return $this;
}
public function setImages(array $images) {
$this->images = $images;
return $this;
}
public function render() {
if (!$this->mock) {
throw new PhutilInvalidStateException('setMock');
}
$mock = $this->mock;
$images_to_show = array();
$thumbnail = null;
if (!empty($this->images)) {
$images_to_show = array_intersect_key(
$this->mock->getActiveImages(), array_flip($this->images));
}
$xform = PhabricatorFileTransform::getTransformByKey(
PhabricatorFileThumbnailTransform::TRANSFORM_PINBOARD);
if ($images_to_show) {
$image = head($images_to_show);
$thumbfile = $image->getFile();
$header = 'M'.$mock->getID().' '.$mock->getName().
' (#'.$image->getID().')';
$uri = '/M'.$this->mock->getID().'/'.$image->getID().'/';
} else {
$thumbfile = $mock->getCoverFile();
$header = 'M'.$mock->getID().' '.$mock->getName();
$uri = '/M'.$this->mock->getID();
}
$thumbnail = $thumbfile->getURIForTransform($xform);
list($x, $y) = $xform->getTransformedDimensions($thumbfile);
$item = id(new PHUIPinboardItemView())
->setUser($this->getUser())
->setObject($mock)
->setHeader($header)
->setURI($uri)
->setImageURI($thumbnail)
->setImageSize($x, $y)
->setDisabled($mock->isClosed())
->addIconCount('fa-picture-o', count($mock->getActiveImages()))
->addIconCount('fa-trophy', $mock->getTokenCount());
return $item;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/edge/PholioMockHasTaskEdgeType.php | src/applications/pholio/edge/PholioMockHasTaskEdgeType.php | <?php
final class PholioMockHasTaskEdgeType extends PhabricatorEdgeType {
const EDGECONST = 37;
public function getInverseEdgeConstant() {
return ManiphestTaskHasMockEdgeType::EDGECONST;
}
public function shouldWriteInverseTransactions() {
return true;
}
public function getTransactionAddString(
$actor,
$add_count,
$add_edges) {
return pht(
'%s added %s task(s): %s.',
$actor,
$add_count,
$add_edges);
}
public function getTransactionRemoveString(
$actor,
$rem_count,
$rem_edges) {
return pht(
'%s removed %s task(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 task(s), added %s: %s; removed %s: %s.',
$actor,
$add_count,
$add_edges,
$rem_count,
$rem_edges);
}
public function getFeedAddString(
$actor,
$object,
$add_count,
$add_edges) {
return pht(
'%s added %s task(s) for %s: %s.',
$actor,
$add_count,
$object,
$add_edges);
}
public function getFeedRemoveString(
$actor,
$object,
$rem_count,
$rem_edges) {
return pht(
'%s removed %s task(s) for %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 task(s) for %s, added %s: %s; removed %s: %s.',
$actor,
$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/pholio/phid/PholioMockPHIDType.php | src/applications/pholio/phid/PholioMockPHIDType.php | <?php
final class PholioMockPHIDType extends PhabricatorPHIDType {
const TYPECONST = 'MOCK';
public function getTypeName() {
return pht('Pholio Mock');
}
public function newObject() {
return new PholioMock();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorPholioApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PholioMockQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$mock = $objects[$phid];
$id = $mock->getID();
$name = $mock->getName();
$handle->setURI("/M{$id}");
$handle->setName("M{$id}");
$handle->setFullName("M{$id}: {$name}");
if ($mock->isClosed()) {
$handle->setStatus(PhabricatorObjectHandle::STATUS_CLOSED);
}
}
}
public function canLoadNamedObject($name) {
return preg_match('/^M\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 PholioMockQuery())
->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/pholio/phid/PholioImagePHIDType.php | src/applications/pholio/phid/PholioImagePHIDType.php | <?php
final class PholioImagePHIDType extends PhabricatorPHIDType {
const TYPECONST = 'PIMG';
public function getTypeName() {
return pht('Image');
}
public function newObject() {
return new PholioImage();
}
public function getPHIDTypeApplicationClass() {
return 'PhabricatorPholioApplication';
}
protected function buildQueryForObjects(
PhabricatorObjectQuery $query,
array $phids) {
return id(new PholioImageQuery())
->withPHIDs($phids);
}
public function loadHandles(
PhabricatorHandleQuery $query,
array $handles,
array $objects) {
foreach ($handles as $phid => $handle) {
$image = $objects[$phid];
$handle
->setName($image->getName())
->setURI($image->getURI());
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/herald/PholioMockDescriptionHeraldField.php | src/applications/pholio/herald/PholioMockDescriptionHeraldField.php | <?php
final class PholioMockDescriptionHeraldField
extends PholioMockHeraldField {
const FIELDCONST = 'pholio.mock.description';
public function getHeraldFieldName() {
return pht('Description');
}
public function getHeraldFieldValue($object) {
return $object->getDescription();
}
protected function getHeraldFieldStandardType() {
return self::STANDARD_TEXT;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/herald/PholioMockNameHeraldField.php | src/applications/pholio/herald/PholioMockNameHeraldField.php | <?php
final class PholioMockNameHeraldField
extends PholioMockHeraldField {
const FIELDCONST = 'pholio.mock.name';
public function getHeraldFieldName() {
return pht('Name');
}
public function getHeraldFieldValue($object) {
return $object->getName();
}
protected function getHeraldFieldStandardType() {
return self::STANDARD_TEXT;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/herald/PholioMockHeraldFieldGroup.php | src/applications/pholio/herald/PholioMockHeraldFieldGroup.php | <?php
final class PholioMockHeraldFieldGroup extends HeraldFieldGroup {
const FIELDGROUPKEY = 'pholio.mock';
public function getGroupLabel() {
return pht('Mock Fields');
}
protected function getGroupOrder() {
return 1000;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/herald/PholioMockHeraldField.php | src/applications/pholio/herald/PholioMockHeraldField.php | <?php
abstract class PholioMockHeraldField extends HeraldField {
public function supportsObject($object) {
return ($object instanceof PholioMock);
}
public function getFieldGroupKey() {
return PholioMockHeraldFieldGroup::FIELDGROUPKEY;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/herald/PholioMockAuthorHeraldField.php | src/applications/pholio/herald/PholioMockAuthorHeraldField.php | <?php
final class PholioMockAuthorHeraldField
extends PholioMockHeraldField {
const FIELDCONST = 'pholio.mock.author';
public function getHeraldFieldName() {
return pht('Author');
}
public function getHeraldFieldValue($object) {
return $object->getAuthorPHID();
}
protected function getHeraldFieldStandardType() {
return self::STANDARD_PHID;
}
protected function getDatasource() {
return new PhabricatorPeopleDatasource();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/herald/HeraldPholioMockAdapter.php | src/applications/pholio/herald/HeraldPholioMockAdapter.php | <?php
final class HeraldPholioMockAdapter extends HeraldAdapter {
private $mock;
public function getAdapterApplicationClass() {
return 'PhabricatorPholioApplication';
}
public function getAdapterContentDescription() {
return pht('React to mocks being created or updated.');
}
protected function initializeNewAdapter() {
$this->mock = $this->newObject();
}
protected function newObject() {
return new PholioMock();
}
public function isTestAdapterForObject($object) {
return ($object instanceof PholioMock);
}
public function getAdapterTestDescription() {
return pht(
'Test rules which run when a mock is created or updated.');
}
public function setObject($object) {
$this->mock = $object;
return $this;
}
public function getObject() {
return $this->mock;
}
public function setMock(PholioMock $mock) {
$this->mock = $mock;
return $this;
}
public function getMock() {
return $this->mock;
}
public function getAdapterContentName() {
return pht('Pholio Mocks');
}
public function supportsRuleType($rule_type) {
switch ($rule_type) {
case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL:
case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL:
return true;
case HeraldRuleTypeConfig::RULE_TYPE_OBJECT:
default:
return false;
}
}
public function getHeraldName() {
return 'M'.$this->getMock()->getID();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/search/PholioMockFerretEngine.php | src/applications/pholio/search/PholioMockFerretEngine.php | <?php
final class PholioMockFerretEngine
extends PhabricatorFerretEngine {
public function getApplicationName() {
return 'pholio';
}
public function getScopeName() {
return 'mock';
}
public function newSearchEngine() {
return new PholioMockSearchEngine();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/search/PholioMockFulltextEngine.php | src/applications/pholio/search/PholioMockFulltextEngine.php | <?php
final class PholioMockFulltextEngine
extends PhabricatorFulltextEngine {
protected function buildAbstractDocument(
PhabricatorSearchAbstractDocument $document,
$object) {
$mock = $object;
$document->setDocumentTitle($mock->getName());
$document->addField(
PhabricatorSearchDocumentFieldType::FIELD_BODY,
$mock->getDescription());
$document->addRelationship(
PhabricatorSearchRelationship::RELATIONSHIP_AUTHOR,
$mock->getAuthorPHID(),
PhabricatorPeopleUserPHIDType::TYPECONST,
$mock->getDateCreated());
$document->addRelationship(
$mock->isClosed()
? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED
: PhabricatorSearchRelationship::RELATIONSHIP_OPEN,
$mock->getPHID(),
PholioMockPHIDType::TYPECONST,
PhabricatorTime::getNow());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/engine/PholioMockTimelineEngine.php | src/applications/pholio/engine/PholioMockTimelineEngine.php | <?php
final class PholioMockTimelineEngine
extends PhabricatorTimelineEngine {
protected function newTimelineView() {
$viewer = $this->getViewer();
$object = $this->getObject();
$images = id(new PholioImageQuery())
->setViewer($viewer)
->withMocks(array($object))
->needInlineComments(true)
->execute();
$object->attachImages($images);
return id(new PholioTransactionView())
->setMock($object);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/pholio/capability/PholioDefaultEditCapability.php | src/applications/pholio/capability/PholioDefaultEditCapability.php | <?php
final class PholioDefaultEditCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'pholio.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/pholio/capability/PholioDefaultViewCapability.php | src/applications/pholio/capability/PholioDefaultViewCapability.php | <?php
final class PholioDefaultViewCapability extends PhabricatorPolicyCapability {
const CAPABILITY = 'pholio.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/pholio/remarkup/PholioRemarkupRule.php | src/applications/pholio/remarkup/PholioRemarkupRule.php | <?php
final class PholioRemarkupRule extends PhabricatorObjectRemarkupRule {
protected function getObjectNamePrefix() {
return 'M';
}
protected function getObjectIDPattern() {
// Match "M123", "M123/456", and "M123/456/". Users can hit the latter
// forms when clicking comment anchors on a mock page.
return '[1-9]\d*(?:/[1-9]\d*/?)?';
}
protected function getObjectHref(
$object,
PhabricatorObjectHandle $handle,
$id) {
$href = $handle->getURI();
// If the ID has a `M123/456` component, link to that specific image.
$id = explode('/', $id);
if (isset($id[1])) {
$href = $href.'/'.$id[1].'/';
}
if ($this->getEngine()->getConfig('uri.full')) {
$href = PhabricatorEnv::getURI($href);
}
return $href;
}
protected function loadObjects(array $ids) {
// Strip off any image ID components of the URI.
$map = array();
foreach ($ids as $id) {
$map[head(explode('/', $id))][] = $id;
}
$viewer = $this->getEngine()->getConfig('viewer');
$mocks = id(new PholioMockQuery())
->setViewer($viewer)
->needCoverFiles(true)
->needImages(true)
->needTokenCounts(true)
->withIDs(array_keys($map))
->execute();
$results = array();
foreach ($mocks as $mock) {
$ids = idx($map, $mock->getID(), array());
foreach ($ids as $id) {
$results[$id] = $mock;
}
}
return $results;
}
protected function renderObjectEmbed(
$object,
PhabricatorObjectHandle $handle,
$options) {
$viewer = $this->getEngine()->getConfig('viewer');
$embed_mock = id(new PholioMockEmbedView())
->setUser($viewer)
->setMock($object);
if (strlen($options)) {
$parser = new PhutilSimpleOptions();
$opts = $parser->parse(substr($options, 1));
if (isset($opts['image'])) {
$images = array_unique(
explode('&', preg_replace('/\s+/', '', $opts['image'])));
$embed_mock->setImages($images);
}
}
return $embed_mock->render();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/controller/DoorkeeperTagsController.php | src/applications/doorkeeper/controller/DoorkeeperTagsController.php | <?php
final class DoorkeeperTagsController extends PhabricatorController {
public function handleRequest(AphrontRequest $request) {
$viewer = $request->getViewer();
$tags = $request->getStr('tags');
try {
$tags = phutil_json_decode($tags);
} catch (PhutilJSONParserException $ex) {
$tags = array();
}
$refs = array();
foreach ($tags as $key => $tag_spec) {
$tag = $tag_spec['ref'];
$ref = id(new DoorkeeperObjectRef())
->setApplicationType($tag[0])
->setApplicationDomain($tag[1])
->setObjectType($tag[2])
->setObjectID($tag[3]);
$refs[$key] = $ref;
}
$refs = id(new DoorkeeperImportEngine())
->setViewer($viewer)
->setRefs($refs)
->setTimeout(15)
->execute();
$results = array();
foreach ($refs as $key => $ref) {
if (!$ref->getIsVisible()) {
continue;
}
$uri = $ref->getExternalObject()->getObjectURI();
if (!$uri) {
continue;
}
$tag_spec = $tags[$key];
$id = $tag_spec['id'];
$view = idx($tag_spec, 'view');
$is_short = ($view == 'short');
if ($is_short) {
$name = $ref->getShortName();
} else {
$name = $ref->getFullName();
}
$tag = id(new PHUITagView())
->setID($id)
->setName($name)
->setHref($uri)
->setType(PHUITagView::TYPE_OBJECT)
->setExternal(true)
->render();
$results[] = array(
'id' => $id,
'markup' => $tag,
);
}
return id(new AphrontAjaxResponse())->setContent(
array(
'tags' => $results,
));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/bridge/DoorkeeperBridgedObjectInterface.php | src/applications/doorkeeper/bridge/DoorkeeperBridgedObjectInterface.php | <?php
interface DoorkeeperBridgedObjectInterface {
public function getBridgedObject();
public function attachBridgedObject(DoorkeeperExternalObject $object = null);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/bridge/DoorkeeperBridge.php | src/applications/doorkeeper/bridge/DoorkeeperBridge.php | <?php
abstract class DoorkeeperBridge extends Phobject {
private $viewer;
private $context = array();
private $throwOnMissingLink;
private $timeout;
public function setTimeout($timeout) {
$this->timeout = $timeout;
return $this;
}
public function getTimeout() {
return $this->timeout;
}
public function setThrowOnMissingLink($throw_on_missing_link) {
$this->throwOnMissingLink = $throw_on_missing_link;
return $this;
}
final public function setViewer($viewer) {
$this->viewer = $viewer;
return $this;
}
final public function getViewer() {
return $this->viewer;
}
final public function setContext($context) {
$this->context = $context;
return $this;
}
final public function getContextProperty($key, $default = null) {
return idx($this->context, $key, $default);
}
public function isEnabled() {
return true;
}
abstract public function canPullRef(DoorkeeperObjectRef $ref);
abstract public function pullRefs(array $refs);
public function fillObjectFromData(DoorkeeperExternalObject $obj, $result) {
return;
}
public function didFailOnMissingLink() {
if ($this->throwOnMissingLink) {
throw new DoorkeeperMissingLinkException();
}
return null;
}
final protected function saveExternalObject(
DoorkeeperObjectRef $ref,
DoorkeeperExternalObject $obj) {
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
try {
$obj->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// In various cases, we may race another process importing the same
// data. If we do, we'll collide on the object key. Load the object
// the other process created and use that.
$obj = id(new DoorkeeperExternalObjectQuery())
->setViewer($this->getViewer())
->withObjectKeys(array($ref->getObjectKey()))
->executeOne();
if (!$obj) {
throw new PhutilProxyException(
pht('Failed to load external object after collision.'),
$ex);
}
$ref->attachExternalObject($obj);
}
unset($unguarded);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/bridge/DoorkeeperBridgeGitHubUser.php | src/applications/doorkeeper/bridge/DoorkeeperBridgeGitHubUser.php | <?php
final class DoorkeeperBridgeGitHubUser
extends DoorkeeperBridgeGitHub {
const OBJTYPE_GITHUB_USER = 'github.user';
public function canPullRef(DoorkeeperObjectRef $ref) {
if (!parent::canPullRef($ref)) {
return false;
}
if ($ref->getObjectType() !== self::OBJTYPE_GITHUB_USER) {
return false;
}
return true;
}
public function pullRefs(array $refs) {
$token = $this->getGitHubAccessToken();
if (!strlen($token)) {
return null;
}
$template = id(new PhutilGitHubFuture())
->setAccessToken($token);
$futures = array();
$id_map = mpull($refs, 'getObjectID', 'getObjectKey');
foreach ($id_map as $key => $id) {
// GitHub doesn't provide a way to query for users by ID directly, but we
// can list all users, ordered by ID, starting at some particular ID,
// with a page size of one, which will achieve the desired effect.
$one_less = ($id - 1);
$uri = "/users?since={$one_less}&per_page=1";
$data = array();
$futures[$key] = id(clone $template)
->setRawGitHubQuery($uri, $data);
}
$results = array();
$failed = array();
foreach (new FutureIterator($futures) as $key => $future) {
try {
$results[$key] = $future->resolve();
} catch (Exception $ex) {
if (($ex instanceof HTTPFutureResponseStatus) &&
($ex->getStatusCode() == 404)) {
// TODO: Do we end up here for deleted objects and invisible
// objects?
} else {
phlog($ex);
$failed[$key] = $ex;
}
}
}
$viewer = $this->getViewer();
foreach ($refs as $ref) {
$ref->setAttribute('name', pht('GitHub User %s', $ref->getObjectID()));
$did_fail = idx($failed, $ref->getObjectKey());
if ($did_fail) {
$ref->setSyncFailed(true);
continue;
}
$result = idx($results, $ref->getObjectKey());
if (!$result) {
continue;
}
$body = $result->getBody();
if (!is_array($body) || !count($body)) {
$ref->setSyncFailed(true);
continue;
}
$spec = head($body);
if (!is_array($spec)) {
$ref->setSyncFailed(true);
continue;
}
// Because we're using a paging query to load each user, if a user (say,
// user ID 123) does not exist for some reason, we might get the next
// user (say, user ID 124) back. Make sure the user we got back is really
// the user we expect.
$id = idx($spec, 'id');
if ($id !== $ref->getObjectID()) {
$ref->setSyncFailed(true);
continue;
}
$ref->setIsVisible(true);
$ref->setAttribute('api.raw', $spec);
$ref->setAttribute('name', $spec['login']);
$obj = $ref->getExternalObject();
$this->fillObjectFromData($obj, $spec);
$this->saveExternalObject($ref, $obj);
}
}
public function fillObjectFromData(DoorkeeperExternalObject $obj, $spec) {
$uri = $spec['html_url'];
$obj->setObjectURI($uri);
$login = $spec['login'];
$obj->setDisplayName(pht('%s <%s>', $login, pht('GitHub')));
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/bridge/DoorkeeperBridgeGitHub.php | src/applications/doorkeeper/bridge/DoorkeeperBridgeGitHub.php | <?php
abstract class DoorkeeperBridgeGitHub extends DoorkeeperBridge {
const APPTYPE_GITHUB = 'github';
const APPDOMAIN_GITHUB = 'github.com';
public function canPullRef(DoorkeeperObjectRef $ref) {
if ($ref->getApplicationType() != self::APPTYPE_GITHUB) {
return false;
}
if ($ref->getApplicationDomain() != self::APPDOMAIN_GITHUB) {
return false;
}
return true;
}
protected function getGitHubAccessToken() {
$context_token = $this->getContextProperty('github.token');
if ($context_token) {
return $context_token->openEnvelope();
}
// TODO: Do a bunch of work to fetch the viewer's linked account if
// they have one.
return $this->didFailOnMissingLink();
}
protected function parseGitHubIssueID($id) {
$matches = null;
if (!preg_match('(^([^/]+)/([^/]+)#([1-9]\d*)\z)', $id, $matches)) {
throw new Exception(
pht(
'GitHub Issue ID "%s" is not properly formatted. Expected an ID '.
'in the form "owner/repository#123".',
$id));
}
return array(
$matches[1],
$matches[2],
(int)$matches[3],
);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/bridge/DoorkeeperBridgeJIRA.php | src/applications/doorkeeper/bridge/DoorkeeperBridgeJIRA.php | <?php
final class DoorkeeperBridgeJIRA extends DoorkeeperBridge {
const APPTYPE_JIRA = 'jira';
const OBJTYPE_ISSUE = 'jira:issue';
public function canPullRef(DoorkeeperObjectRef $ref) {
if ($ref->getApplicationType() != self::APPTYPE_JIRA) {
return false;
}
$types = array(
self::OBJTYPE_ISSUE => true,
);
return isset($types[$ref->getObjectType()]);
}
public function pullRefs(array $refs) {
$id_map = mpull($refs, 'getObjectID', 'getObjectKey');
$viewer = $this->getViewer();
$provider = PhabricatorJIRAAuthProvider::getJIRAProvider();
if (!$provider) {
return;
}
$accounts = id(new PhabricatorExternalAccountQuery())
->setViewer($viewer)
->withUserPHIDs(array($viewer->getPHID()))
->withProviderConfigPHIDs(
array(
$provider->getProviderConfigPHID(),
))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->execute();
if (!$accounts) {
return $this->didFailOnMissingLink();
}
// TODO: When we support multiple JIRA instances, we need to disambiguate
// issues (perhaps with additional configuration) or cast a wide net
// (by querying all instances). For now, just query the one instance.
$account = head($accounts);
$timeout = $this->getTimeout();
$futures = array();
foreach ($id_map as $key => $id) {
$future = $provider->newJIRAFuture(
$account,
'rest/api/2/issue/'.phutil_escape_uri($id),
'GET');
if ($timeout !== null) {
$future->setTimeout($timeout);
}
$futures[$key] = $future;
}
$results = array();
$failed = array();
foreach (new FutureIterator($futures) as $key => $future) {
try {
$results[$key] = $future->resolveJSON();
} catch (Exception $ex) {
if (($ex instanceof HTTPFutureResponseStatus) &&
($ex->getStatusCode() == 404)) {
// This indicates that the object has been deleted (or never existed,
// or isn't visible to the current user) but it's a successful sync of
// an object which isn't visible.
} else {
// This is something else, so consider it a synchronization failure.
phlog($ex);
$failed[$key] = $ex;
}
}
}
foreach ($refs as $ref) {
$ref->setAttribute('name', pht('JIRA %s', $ref->getObjectID()));
$did_fail = idx($failed, $ref->getObjectKey());
if ($did_fail) {
$ref->setSyncFailed(true);
continue;
}
$result = idx($results, $ref->getObjectKey());
if (!$result) {
continue;
}
$fields = idx($result, 'fields', array());
$ref->setIsVisible(true);
$ref->setAttribute(
'fullname',
pht('JIRA %s %s', $result['key'], idx($fields, 'summary')));
$ref->setAttribute('title', idx($fields, 'summary'));
$ref->setAttribute('description', idx($result, 'description'));
$ref->setAttribute('shortname', $result['key']);
$obj = $ref->getExternalObject();
if ($obj->getID()) {
continue;
}
$this->fillObjectFromData($obj, $result);
$this->saveExternalObject($ref, $obj);
}
}
public function fillObjectFromData(DoorkeeperExternalObject $obj, $result) {
// Convert the "self" URI, which points at the REST endpoint, into a
// browse URI.
$self = idx($result, 'self');
$object_id = $obj->getObjectID();
$uri = self::getJIRAIssueBrowseURIFromJIRARestURI($self, $object_id);
if ($uri !== null) {
$obj->setObjectURI($uri);
}
}
public static function getJIRAIssueBrowseURIFromJIRARestURI(
$uri,
$object_id) {
$uri = new PhutilURI($uri);
// The JIRA install might not be at the domain root, so we may need to
// keep an initial part of the path, like "/jira/". Find the API specific
// part of the URI, strip it off, then replace it with the web version.
$path = $uri->getPath();
$pos = strrpos($path, 'rest/api/2/issue/');
if ($pos === false) {
return null;
}
$path = substr($path, 0, $pos);
$path = $path.'browse/'.$object_id;
$uri->setPath($path);
return (string)$uri;
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/bridge/DoorkeeperBridgeAsana.php | src/applications/doorkeeper/bridge/DoorkeeperBridgeAsana.php | <?php
final class DoorkeeperBridgeAsana extends DoorkeeperBridge {
const APPTYPE_ASANA = 'asana';
const APPDOMAIN_ASANA = 'asana.com';
const OBJTYPE_TASK = 'asana:task';
public function canPullRef(DoorkeeperObjectRef $ref) {
if ($ref->getApplicationType() != self::APPTYPE_ASANA) {
return false;
}
if ($ref->getApplicationDomain() != self::APPDOMAIN_ASANA) {
return false;
}
$types = array(
self::OBJTYPE_TASK => true,
);
return isset($types[$ref->getObjectType()]);
}
public function pullRefs(array $refs) {
$id_map = mpull($refs, 'getObjectID', 'getObjectKey');
$viewer = $this->getViewer();
$provider = PhabricatorAsanaAuthProvider::getAsanaProvider();
if (!$provider) {
return;
}
$accounts = id(new PhabricatorExternalAccountQuery())
->setViewer($viewer)
->withUserPHIDs(array($viewer->getPHID()))
->withProviderConfigPHIDs(
array(
$provider->getProviderConfigPHID(),
))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->execute();
if (!$accounts) {
return $this->didFailOnMissingLink();
}
// TODO: If the user has several linked Asana accounts, we just pick the
// first one arbitrarily. We might want to try using all of them or do
// something with more finesse. There's no UI way to link multiple accounts
// right now so this is currently moot.
$account = head($accounts);
$token = $provider->getOAuthAccessToken($account);
if (!$token) {
return;
}
$template = id(new PhutilAsanaFuture())
->setAccessToken($token);
$timeout = $this->getTimeout();
if ($timeout !== null) {
$template->setTimeout($timeout);
}
$futures = array();
foreach ($id_map as $key => $id) {
$futures[$key] = id(clone $template)
->setRawAsanaQuery("tasks/{$id}");
}
$results = array();
$failed = array();
foreach (new FutureIterator($futures) as $key => $future) {
try {
$results[$key] = $future->resolve();
} catch (Exception $ex) {
if (($ex instanceof HTTPFutureResponseStatus) &&
($ex->getStatusCode() == 404)) {
// This indicates that the object has been deleted (or never existed,
// or isn't visible to the current user) but it's a successful sync of
// an object which isn't visible.
} else {
// This is something else, so consider it a synchronization failure.
phlog($ex);
$failed[$key] = $ex;
}
}
}
foreach ($refs as $ref) {
$ref->setAttribute('name', pht('Asana Task %s', $ref->getObjectID()));
$did_fail = idx($failed, $ref->getObjectKey());
if ($did_fail) {
$ref->setSyncFailed(true);
continue;
}
$result = idx($results, $ref->getObjectKey());
if (!$result) {
continue;
}
$ref->setIsVisible(true);
$ref->setAttribute('asana.data', $result);
$ref->setAttribute('fullname', pht('Asana: %s', $result['name']));
$ref->setAttribute('title', $result['name']);
$ref->setAttribute('description', $result['notes']);
$obj = $ref->getExternalObject();
if ($obj->getID()) {
continue;
}
$this->fillObjectFromData($obj, $result);
$this->saveExternalObject($ref, $obj);
}
}
public function fillObjectFromData(DoorkeeperExternalObject $obj, $result) {
$gid = $result['gid'];
$uri = urisprintf(
'https://app.asana.com/0/%s/%s',
$gid,
$gid);
$obj->setObjectURI($uri);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/bridge/DoorkeeperBridgeGitHubIssue.php | src/applications/doorkeeper/bridge/DoorkeeperBridgeGitHubIssue.php | <?php
final class DoorkeeperBridgeGitHubIssue
extends DoorkeeperBridgeGitHub {
const OBJTYPE_GITHUB_ISSUE = 'github.issue';
public function canPullRef(DoorkeeperObjectRef $ref) {
if (!parent::canPullRef($ref)) {
return false;
}
if ($ref->getObjectType() !== self::OBJTYPE_GITHUB_ISSUE) {
return false;
}
return true;
}
public function pullRefs(array $refs) {
$token = $this->getGitHubAccessToken();
if (!strlen($token)) {
return null;
}
$template = id(new PhutilGitHubFuture())
->setAccessToken($token);
$futures = array();
$id_map = mpull($refs, 'getObjectID', 'getObjectKey');
foreach ($id_map as $key => $id) {
list($user, $repository, $number) = $this->parseGitHubIssueID($id);
$uri = "/repos/{$user}/{$repository}/issues/{$number}";
$data = array();
$futures[$key] = id(clone $template)
->setRawGitHubQuery($uri, $data);
}
$results = array();
$failed = array();
foreach (new FutureIterator($futures) as $key => $future) {
try {
$results[$key] = $future->resolve();
} catch (Exception $ex) {
if (($ex instanceof HTTPFutureResponseStatus) &&
($ex->getStatusCode() == 404)) {
// TODO: Do we end up here for deleted objects and invisible
// objects?
} else {
phlog($ex);
$failed[$key] = $ex;
}
}
}
$viewer = $this->getViewer();
foreach ($refs as $ref) {
$ref->setAttribute('name', pht('GitHub Issue %s', $ref->getObjectID()));
$did_fail = idx($failed, $ref->getObjectKey());
if ($did_fail) {
$ref->setSyncFailed(true);
continue;
}
$result = idx($results, $ref->getObjectKey());
if (!$result) {
continue;
}
$body = $result->getBody();
$ref->setIsVisible(true);
$ref->setAttribute('api.raw', $body);
$ref->setAttribute('name', $body['title']);
$obj = $ref->getExternalObject();
$this->fillObjectFromData($obj, $result);
$this->saveExternalObject($ref, $obj);
}
}
public function fillObjectFromData(DoorkeeperExternalObject $obj, $result) {
$body = $result->getBody();
$uri = $body['html_url'];
$obj->setObjectURI($uri);
$title = idx($body, 'title');
$description = idx($body, 'body');
$created = idx($body, 'created_at');
$created = strtotime($created);
$state = idx($body, 'state');
$obj->setProperty('task.title', $title);
$obj->setProperty('task.description', $description);
$obj->setProperty('task.created', $created);
$obj->setProperty('task.state', $state);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/bridge/__tests__/DoorkeeperBridgeJIRATestCase.php | src/applications/doorkeeper/bridge/__tests__/DoorkeeperBridgeJIRATestCase.php | <?php
final class DoorkeeperBridgeJIRATestCase extends PhabricatorTestCase {
public function testJIRABridgeRestAPIURIConversion() {
$map = array(
array(
// Installed at domain root.
'http://jira.example.com/rest/api/2/issue/1',
'TP-1',
'http://jira.example.com/browse/TP-1',
),
array(
// Installed on path.
'http://jira.example.com/jira/rest/api/2/issue/1',
'TP-1',
'http://jira.example.com/jira/browse/TP-1',
),
array(
// A URI we don't understand.
'http://jira.example.com/wake/cli/3/task/1',
'TP-1',
null,
),
);
foreach ($map as $inputs) {
list($rest_uri, $object_id, $expect) = $inputs;
$this->assertEqual(
$expect,
DoorkeeperBridgeJIRA::getJIRAIssueBrowseURIFromJIRARestURI(
$rest_uri,
$object_id));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/engineextension/DoorkeeperHyperlinkEngineExtension.php | src/applications/doorkeeper/engineextension/DoorkeeperHyperlinkEngineExtension.php | <?php
final class DoorkeeperHyperlinkEngineExtension
extends PhabricatorRemarkupHyperlinkEngineExtension {
const LINKENGINEKEY = 'doorkeeper';
public function processHyperlinks(array $hyperlinks) {
$engine = $this->getEngine();
$viewer = $engine->getConfig('viewer');
if (!$viewer) {
return;
}
$configs = id(new PhabricatorAuthProviderConfigQuery())
->setViewer($viewer)
->withIsEnabled(true)
->execute();
$providers = array();
foreach ($configs as $key => $config) {
$provider = $config->getProvider();
if (($provider instanceof DoorkeeperRemarkupURIInterface)) {
$providers[] = $provider;
}
}
if (!$providers) {
return;
}
$refs = array();
foreach ($hyperlinks as $hyperlink) {
$uri = $hyperlink->getURI();
$uri = new PhutilURI($uri);
foreach ($providers as $provider) {
$ref = $provider->getDoorkeeperURIRef($uri);
if (($ref !== null) && !($ref instanceof DoorkeeperURIRef)) {
throw new Exception(
pht(
'Expected "getDoorkeeperURIRef()" to return "null" or an '.
'object of type "DoorkeeperURIRef", but got %s from provider '.
'"%s".',
phutil_describe_type($ref),
get_class($provider)));
}
if ($ref === null) {
continue;
}
$tag_id = celerity_generate_unique_node_id();
$href = phutil_string_cast($ref->getURI());
$refs[] = array(
'id' => $tag_id,
'href' => $href,
'ref' => array(
$ref->getApplicationType(),
$ref->getApplicationDomain(),
$ref->getObjectType(),
$ref->getObjectID(),
),
'view' => $ref->getDisplayMode(),
);
$text = $ref->getText();
if ($text === null) {
$text = $href;
}
$view = id(new PHUITagView())
->setID($tag_id)
->setName($text)
->setHref($href)
->setType(PHUITagView::TYPE_OBJECT)
->setExternal(true);
$hyperlink->setResult($view);
break;
}
}
if ($refs) {
Javelin::initBehavior('doorkeeper-tag', array('tags' => $refs));
}
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/engineextension/DoorkeeperBridgedObjectCurtainExtension.php | src/applications/doorkeeper/engineextension/DoorkeeperBridgedObjectCurtainExtension.php | <?php
final class DoorkeeperBridgedObjectCurtainExtension
extends PHUICurtainExtension {
const EXTENSIONKEY = 'doorkeeper.bridged-object';
public function shouldEnableForObject($object) {
return ($object instanceof DoorkeeperBridgedObjectInterface);
}
public function getExtensionApplication() {
return new PhabricatorDoorkeeperApplication();
}
public function buildCurtainPanel($object) {
$xobj = $object->getBridgedObject();
if (!$xobj) {
return null;
}
$tag = id(new DoorkeeperTagView())
->setExternalObject($xobj);
return $this->newPanel()
->setHeaderText(pht('Imported From'))
->setOrder(5000)
->appendChild($tag);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/storage/DoorkeeperSchemaSpec.php | src/applications/doorkeeper/storage/DoorkeeperSchemaSpec.php | <?php
final class DoorkeeperSchemaSpec
extends PhabricatorConfigSchemaSpec {
public function buildSchemata() {
$this->buildEdgeSchemata(new DoorkeeperExternalObject());
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/storage/DoorkeeperDAO.php | src/applications/doorkeeper/storage/DoorkeeperDAO.php | <?php
abstract class DoorkeeperDAO extends PhabricatorLiskDAO {
public function getApplicationName() {
return 'doorkeeper';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/storage/DoorkeeperExternalObject.php | src/applications/doorkeeper/storage/DoorkeeperExternalObject.php | <?php
final class DoorkeeperExternalObject extends DoorkeeperDAO
implements PhabricatorPolicyInterface {
protected $objectKey;
protected $applicationType;
protected $applicationDomain;
protected $objectType;
protected $objectID;
protected $objectURI;
protected $importerPHID;
protected $properties = array();
protected $viewPolicy;
protected function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_SERIALIZATION => array(
'properties' => self::SERIALIZATION_JSON,
),
self::CONFIG_COLUMN_SCHEMA => array(
'objectKey' => 'bytes12',
'applicationType' => 'text32',
'applicationDomain' => 'text32',
'objectType' => 'text32',
'objectID' => 'text64',
'objectURI' => 'text128?',
'importerPHID' => 'phid?',
),
self::CONFIG_KEY_SCHEMA => array(
'key_object' => array(
'columns' => array('objectKey'),
'unique' => true,
),
'key_full' => array(
'columns' => array(
'applicationType',
'applicationDomain',
'objectType',
'objectID',
),
),
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID(
DoorkeeperExternalObjectPHIDType::TYPECONST);
}
public function getProperty($key, $default = null) {
return idx($this->properties, $key, $default);
}
public function setProperty($key, $value) {
$this->properties[$key] = $value;
return $this;
}
public function getObjectKey() {
$key = parent::getObjectKey();
if ($key === null) {
$key = $this->getRef()->getObjectKey();
}
return $key;
}
public function getRef() {
return id(new DoorkeeperObjectRef())
->setApplicationType($this->getApplicationType())
->setApplicationDomain($this->getApplicationDomain())
->setObjectType($this->getObjectType())
->setObjectID($this->getObjectID());
}
public function save() {
if (!$this->objectKey) {
$this->objectKey = $this->getObjectKey();
}
return parent::save();
}
public function setDisplayName($display_name) {
return $this->setProperty('xobj.name.display', $display_name);
}
public function getDisplayName() {
return $this->getProperty('xobj.name.display', pht('External Object'));
}
public function setDisplayFullName($full_name) {
return $this->setProperty('xobj.name.display-full', $full_name);
}
public function getDisplayFullName() {
$full_name = $this->getProperty('xobj.name.display-full');
if ($full_name !== null) {
return $full_name;
}
return $this->getDisplayName();
}
/* -( PhabricatorPolicyInterface )----------------------------------------- */
public function getCapabilities() {
return array(
PhabricatorPolicyCapability::CAN_VIEW,
);
}
public function getPolicy($capability) {
return $this->viewPolicy;
}
public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
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/doorkeeper/worker/DoorkeeperFeedWorker.php | src/applications/doorkeeper/worker/DoorkeeperFeedWorker.php | <?php
/**
* Publish events (like comments on a revision) to external objects which are
* linked through Doorkeeper (like a linked JIRA or Asana task).
*
* These workers are invoked by feed infrastructure during normal task queue
* operations. They read feed stories and publish information about them to
* external systems, generally mirroring comments and updates in Phabricator
* into remote systems by making API calls.
*
* @task publish Publishing Stories
* @task context Story Context
* @task internal Internals
*/
abstract class DoorkeeperFeedWorker extends FeedPushWorker {
private $publisher;
private $feedStory;
private $storyObject;
/* -( Publishing Stories )------------------------------------------------- */
/**
* Actually publish the feed story. Subclasses will generally make API calls
* to publish some version of the story into external systems.
*
* @return void
* @task publish
*/
abstract protected function publishFeedStory();
/**
* Enable or disable the worker. Normally, this checks configuration to
* see if Phabricator is linked to applicable external systems.
*
* @return bool True if this worker should try to publish stories.
* @task publish
*/
abstract public function isEnabled();
/* -( Story Context )------------------------------------------------------ */
/**
* Get the @{class:PhabricatorFeedStory} that should be published.
*
* @return PhabricatorFeedStory The story to publish.
* @task context
*/
protected function getFeedStory() {
if (!$this->feedStory) {
$story = $this->loadFeedStory();
$this->feedStory = $story;
}
return $this->feedStory;
}
/**
* Get the viewer for the act of publishing.
*
* NOTE: Publishing currently uses the omnipotent viewer because it depends
* on loading external accounts. Possibly we should tailor this. See T3732.
* Using the actor for most operations might make more sense.
*
* @return PhabricatorUser Viewer.
* @task context
*/
protected function getViewer() {
return PhabricatorUser::getOmnipotentUser();
}
/**
* Get the @{class:DoorkeeperFeedStoryPublisher} which handles this object.
*
* @return DoorkeeperFeedStoryPublisher Object publisher.
* @task context
*/
protected function getPublisher() {
return $this->publisher;
}
/**
* Get the primary object the story is about, like a
* @{class:DifferentialRevision} or @{class:ManiphestTask}.
*
* @return object Object which the story is about.
* @task context
*/
protected function getStoryObject() {
if (!$this->storyObject) {
$story = $this->getFeedStory();
try {
$object = $story->getPrimaryObject();
} catch (Exception $ex) {
throw new PhabricatorWorkerPermanentFailureException(
$ex->getMessage());
}
$this->storyObject = $object;
}
return $this->storyObject;
}
/* -( Internals )---------------------------------------------------------- */
/**
* Load the @{class:DoorkeeperFeedStoryPublisher} which corresponds to this
* object. Publishers provide a common API for pushing object updates into
* foreign systems.
*
* @return DoorkeeperFeedStoryPublisher Publisher for the story's object.
* @task internal
*/
private function loadPublisher() {
$story = $this->getFeedStory();
$viewer = $this->getViewer();
$object = $this->getStoryObject();
$publishers = id(new PhutilClassMapQuery())
->setAncestorClass('DoorkeeperFeedStoryPublisher')
->execute();
foreach ($publishers as $publisher) {
if (!$publisher->canPublishStory($story, $object)) {
continue;
}
$publisher
->setViewer($viewer)
->setFeedStory($story);
$object = $publisher->willPublishStory($object);
$this->storyObject = $object;
$this->publisher = $publisher;
break;
}
return $this->publisher;
}
/* -( Inherited )---------------------------------------------------------- */
/**
* Doorkeeper workers set up some context, then call
* @{method:publishFeedStory}.
*/
final protected function doWork() {
if (PhabricatorEnv::getEnvConfig('phabricator.silent')) {
$this->log("%s\n", pht('This software is running in silent mode.'));
return;
}
if (!$this->isEnabled()) {
$this->log(
"%s\n",
pht("Doorkeeper worker '%s' is not enabled.", get_class($this)));
return;
}
$publisher = $this->loadPublisher();
if (!$publisher) {
$this->log("%s\n", pht('Story is about an unsupported object type.'));
return;
} else {
$this->log("%s\n", pht("Using publisher '%s'.", get_class($publisher)));
}
$this->publishFeedStory();
}
/**
* By default, Doorkeeper workers perform a small number of retries with
* exponential backoff. A consideration in this policy is that many of these
* workers are laden with side effects.
*/
public function getMaximumRetryCount() {
return 4;
}
/**
* See @{method:getMaximumRetryCount} for a description of Doorkeeper
* retry defaults.
*/
public function getWaitBeforeRetry(PhabricatorWorkerTask $task) {
$count = $task->getFailureCount();
return (5 * 60) * pow(8, $count);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/worker/DoorkeeperJIRAFeedWorker.php | src/applications/doorkeeper/worker/DoorkeeperJIRAFeedWorker.php | <?php
/**
* Publishes feed stories into JIRA, using the "JIRA Issues" field to identify
* linked issues.
*/
final class DoorkeeperJIRAFeedWorker extends DoorkeeperFeedWorker {
private $provider;
/* -( Publishing Stories )------------------------------------------------- */
/**
* This worker is enabled when a JIRA authentication provider is active.
*/
public function isEnabled() {
return (bool)PhabricatorJIRAAuthProvider::getJIRAProvider();
}
/**
* Publishes stories into JIRA using the JIRA API.
*/
protected function publishFeedStory() {
$story = $this->getFeedStory();
$viewer = $this->getViewer();
$provider = $this->getProvider();
$object = $this->getStoryObject();
$publisher = $this->getPublisher();
$jira_issue_phids = PhabricatorEdgeQuery::loadDestinationPHIDs(
$object->getPHID(),
PhabricatorJiraIssueHasObjectEdgeType::EDGECONST);
if (!$jira_issue_phids) {
$this->log(
"%s\n",
pht('Story is about an object with no linked JIRA issues.'));
return;
}
$do_anything = ($this->shouldPostComment() || $this->shouldPostLink());
if (!$do_anything) {
$this->log(
"%s\n",
pht('JIRA integration is configured not to post anything.'));
return;
}
$xobjs = id(new DoorkeeperExternalObjectQuery())
->setViewer($viewer)
->withPHIDs($jira_issue_phids)
->execute();
if (!$xobjs) {
$this->log(
"%s\n",
pht('Story object has no corresponding external JIRA objects.'));
return;
}
$try_users = $this->findUsersToPossess();
if (!$try_users) {
$this->log(
"%s\n",
pht('No users to act on linked JIRA objects.'));
return;
}
$xobjs = mgroup($xobjs, 'getApplicationDomain');
foreach ($xobjs as $domain => $xobj_list) {
$accounts = id(new PhabricatorExternalAccountQuery())
->setViewer($viewer)
->withUserPHIDs($try_users)
->withProviderConfigPHIDs(
array(
$provider->getProviderConfigPHID(),
))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->execute();
// Reorder accounts in the original order.
// TODO: This needs to be adjusted if/when we allow you to link multiple
// accounts.
$accounts = mpull($accounts, null, 'getUserPHID');
$accounts = array_select_keys($accounts, $try_users);
foreach ($xobj_list as $xobj) {
foreach ($accounts as $account) {
try {
$jira_key = $xobj->getObjectID();
if ($this->shouldPostComment()) {
$this->postComment($account, $jira_key);
}
if ($this->shouldPostLink()) {
$this->postLink($account, $jira_key);
}
break;
} catch (HTTPFutureResponseStatus $ex) {
phlog($ex);
$this->log(
"%s\n",
pht(
'Failed to update object %s using user %s.',
$xobj->getObjectID(),
$account->getUserPHID()));
}
}
}
}
}
/* -( Internals )---------------------------------------------------------- */
/**
* Get the active JIRA provider.
*
* @return PhabricatorJIRAAuthProvider Active JIRA auth provider.
* @task internal
*/
private function getProvider() {
if (!$this->provider) {
$provider = PhabricatorJIRAAuthProvider::getJIRAProvider();
if (!$provider) {
throw new PhabricatorWorkerPermanentFailureException(
pht('No JIRA provider configured.'));
}
$this->provider = $provider;
}
return $this->provider;
}
/**
* Get a list of users to act as when publishing into JIRA.
*
* @return list<phid> Candidate user PHIDs to act as when publishing this
* story.
* @task internal
*/
private function findUsersToPossess() {
$object = $this->getStoryObject();
$publisher = $this->getPublisher();
$data = $this->getFeedStory()->getStoryData();
// Figure out all the users related to the object. Users go into one of
// four buckets. For JIRA integration, we don't care about which bucket
// a user is in, since we just want to publish an update to linked objects.
$owner_phid = $publisher->getOwnerPHID($object);
$active_phids = $publisher->getActiveUserPHIDs($object);
$passive_phids = $publisher->getPassiveUserPHIDs($object);
$follow_phids = $publisher->getCCUserPHIDs($object);
$all_phids = array_merge(
array($owner_phid),
$active_phids,
$passive_phids,
$follow_phids);
$all_phids = array_unique(array_filter($all_phids));
// Even if the actor isn't a reviewer, etc., try to use their account so
// we can post in the correct voice. If we miss, we'll try all the other
// related users.
$try_users = array_merge(
array($data->getAuthorPHID()),
$all_phids);
$try_users = array_filter($try_users);
return $try_users;
}
private function shouldPostComment() {
return $this->getProvider()->shouldCreateJIRAComment();
}
private function shouldPostLink() {
return $this->getProvider()->shouldCreateJIRALink();
}
private function postComment($account, $jira_key) {
$provider = $this->getProvider();
$provider->newJIRAFuture(
$account,
'rest/api/2/issue/'.$jira_key.'/comment',
'POST',
array(
'body' => $this->renderStoryText(),
))->resolveJSON();
}
private function renderStoryText() {
$object = $this->getStoryObject();
$publisher = $this->getPublisher();
$text = $publisher->getStoryText($object);
if ($this->shouldPostLink()) {
return $text;
} else {
// include the link in the comment
return $text."\n\n".$publisher->getObjectURI($object);
}
}
private function postLink($account, $jira_key) {
$provider = $this->getProvider();
$object = $this->getStoryObject();
$publisher = $this->getPublisher();
$icon_uri = celerity_get_resource_uri('rsrc/favicons/favicon-16x16.png');
$provider->newJIRAFuture(
$account,
'rest/api/2/issue/'.$jira_key.'/remotelink',
'POST',
// format documented at http://bit.ly/1K5T0Li
array(
'globalId' => $object->getPHID(),
'application' => array(
'type' => 'com.phacility.phabricator',
'name' => 'Phabricator',
),
'relationship' => 'implemented in',
'object' => array(
'url' => $publisher->getObjectURI($object),
'title' => $publisher->getObjectTitle($object),
'icon' => array(
'url16x16' => $icon_uri,
'title' => 'Phabricator',
),
'status' => array(
'resolved' => $publisher->isObjectClosed($object),
),
),
))->resolveJSON();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/worker/DoorkeeperAsanaFeedWorker.php | src/applications/doorkeeper/worker/DoorkeeperAsanaFeedWorker.php | <?php
/**
* Publishes tasks representing work that needs to be done into Asana, and
* updates the tasks as the corresponding Phabricator objects are updated.
*/
final class DoorkeeperAsanaFeedWorker extends DoorkeeperFeedWorker {
private $provider;
/* -( Publishing Stories )------------------------------------------------- */
/**
* This worker is enabled when an Asana workspace ID is configured with
* `asana.workspace-id`.
*/
public function isEnabled() {
return (bool)$this->getWorkspaceID();
}
/**
* Publish stories into Asana using the Asana API.
*/
protected function publishFeedStory() {
$story = $this->getFeedStory();
$data = $story->getStoryData();
$viewer = $this->getViewer();
$provider = $this->getProvider();
$workspace_id = $this->getWorkspaceID();
$object = $this->getStoryObject();
$src_phid = $object->getPHID();
$publisher = $this->getPublisher();
// Figure out all the users related to the object. Users go into one of
// four buckets:
//
// - Owner: the owner of the object. This user becomes the assigned owner
// of the parent task.
// - Active: users who are responsible for the object and need to act on
// it. For example, reviewers of a "needs review" revision.
// - Passive: users who are responsible for the object, but do not need
// to act on it right now. For example, reviewers of a "needs revision"
// revision.
// - Follow: users who are following the object; generally CCs.
$owner_phid = $publisher->getOwnerPHID($object);
$active_phids = $publisher->getActiveUserPHIDs($object);
$passive_phids = $publisher->getPassiveUserPHIDs($object);
$follow_phids = $publisher->getCCUserPHIDs($object);
$all_phids = array();
$all_phids = array_merge(
array($owner_phid),
$active_phids,
$passive_phids,
$follow_phids);
$all_phids = array_unique(array_filter($all_phids));
$phid_aid_map = $this->lookupAsanaUserIDs($all_phids);
if (!$phid_aid_map) {
throw new PhabricatorWorkerPermanentFailureException(
pht('No related users have linked Asana accounts.'));
}
$owner_asana_id = idx($phid_aid_map, $owner_phid);
$all_asana_ids = array_select_keys($phid_aid_map, $all_phids);
$all_asana_ids = array_values($all_asana_ids);
// Even if the actor isn't a reviewer, etc., try to use their account so
// we can post in the correct voice. If we miss, we'll try all the other
// related users.
$try_users = array_merge(
array($data->getAuthorPHID()),
array_keys($phid_aid_map));
$try_users = array_filter($try_users);
$access_info = $this->findAnyValidAsanaAccessToken($try_users);
list($possessed_user, $possessed_asana_id, $oauth_token) = $access_info;
if (!$oauth_token) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'Unable to find any Asana user with valid credentials to '.
'pull an OAuth token out of.'));
}
$etype_main = PhabricatorObjectHasAsanaTaskEdgeType::EDGECONST;
$etype_sub = PhabricatorObjectHasAsanaSubtaskEdgeType::EDGECONST;
$equery = id(new PhabricatorEdgeQuery())
->withSourcePHIDs(array($src_phid))
->withEdgeTypes(
array(
$etype_main,
$etype_sub,
))
->needEdgeData(true);
$edges = $equery->execute();
$main_edge = head($edges[$src_phid][$etype_main]);
$main_data = $this->getAsanaTaskData($object) + array(
'assignee' => $owner_asana_id,
);
$projects = $this->getAsanaProjectIDs();
$extra_data = array();
if ($main_edge) {
$extra_data = $main_edge['data'];
$refs = id(new DoorkeeperImportEngine())
->setViewer($possessed_user)
->withPHIDs(array($main_edge['dst']))
->execute();
$parent_ref = head($refs);
if (!$parent_ref) {
throw new PhabricatorWorkerPermanentFailureException(
pht('%s could not be loaded.', 'DoorkeeperExternalObject'));
}
if ($parent_ref->getSyncFailed()) {
throw new Exception(
pht('Synchronization of parent task from Asana failed!'));
} else if (!$parent_ref->getIsVisible()) {
$this->log(
"%s\n",
pht('Skipping main task update, object is no longer visible.'));
$extra_data['gone'] = true;
} else {
$edge_cursor = idx($main_edge['data'], 'cursor', 0);
// TODO: This probably breaks, very rarely, on 32-bit systems.
if ($edge_cursor <= $story->getChronologicalKey()) {
$this->log("%s\n", pht('Updating main task.'));
$task_id = $parent_ref->getObjectID();
$this->makeAsanaAPICall(
$oauth_token,
'tasks/'.$parent_ref->getObjectID(),
'PUT',
$main_data);
} else {
$this->log(
"%s\n",
pht('Skipping main task update, cursor is ahead of the story.'));
}
}
} else {
// If there are no followers (CCs), and no active or passive users
// (reviewers or auditors), and we haven't synchronized the object before,
// don't synchronize the object.
if (!$active_phids && !$passive_phids && !$follow_phids) {
$this->log(
"%s\n",
pht('Object has no followers or active/passive users.'));
return;
}
$parent = $this->makeAsanaAPICall(
$oauth_token,
'tasks',
'POST',
array(
'workspace' => $workspace_id,
'projects' => $projects,
// NOTE: We initially create parent tasks in the "Later" state but
// don't update it afterward, even if the corresponding object
// becomes actionable. The expectation is that users will prioritize
// tasks in responses to notifications of state changes, and that
// we should not overwrite their choices.
'assignee_status' => 'later',
) + $main_data);
$parent_ref = $this->newRefFromResult(
DoorkeeperBridgeAsana::OBJTYPE_TASK,
$parent);
$extra_data = array(
'workspace' => $workspace_id,
);
}
// Synchronize main task followers.
$task_id = $parent_ref->getObjectID();
// Reviewers are added as followers of the parent task silently, because
// they receive a notification when they are assigned as the owner of their
// subtask, so the follow notification is redundant / non-actionable.
$silent_followers = array_select_keys($phid_aid_map, $active_phids) +
array_select_keys($phid_aid_map, $passive_phids);
$silent_followers = array_values($silent_followers);
// CCs are added as followers of the parent task with normal notifications,
// since they won't get a secondary subtask notification.
$noisy_followers = array_select_keys($phid_aid_map, $follow_phids);
$noisy_followers = array_values($noisy_followers);
// To synchronize follower data, just add all the followers. The task might
// have additional followers, but we can't really tell how they got there:
// were they CC'd and then unsubscribed, or did they manually follow the
// task? Assume the latter since it's easier and less destructive and the
// former is rare. To be fully consistent, we should enumerate followers
// and remove unknown followers, but that's a fair amount of work for little
// benefit, and creates a wider window for race conditions.
// Add the silent followers first so that a user who is both a reviewer and
// a CC gets silently added and then implicitly skipped by then noisy add.
// They will get a subtask notification.
// We only do this if the task still exists.
if (empty($extra_data['gone'])) {
$this->addFollowers($oauth_token, $task_id, $silent_followers, true);
$this->addFollowers($oauth_token, $task_id, $noisy_followers);
// We're also going to synchronize project data here.
$this->addProjects($oauth_token, $task_id, $projects);
}
$dst_phid = $parent_ref->getExternalObject()->getPHID();
// Update the main edge.
$edge_data = array(
'cursor' => $story->getChronologicalKey(),
) + $extra_data;
$edge_options = array(
'data' => $edge_data,
);
id(new PhabricatorEdgeEditor())
->addEdge($src_phid, $etype_main, $dst_phid, $edge_options)
->save();
if (!$parent_ref->getIsVisible()) {
throw new PhabricatorWorkerPermanentFailureException(
pht(
'%s has no visible object on the other side; this '.
'likely indicates the Asana task has been deleted.',
'DoorkeeperExternalObject'));
}
// Now, handle the subtasks.
$sub_editor = new PhabricatorEdgeEditor();
// First, find all the object references in Phabricator for tasks that we
// know about and import their objects from Asana.
$sub_edges = $edges[$src_phid][$etype_sub];
$sub_refs = array();
$subtask_data = $this->getAsanaSubtaskData($object);
$have_phids = array();
if ($sub_edges) {
$refs = id(new DoorkeeperImportEngine())
->setViewer($possessed_user)
->withPHIDs(array_keys($sub_edges))
->execute();
foreach ($refs as $ref) {
if ($ref->getSyncFailed()) {
throw new Exception(
pht('Synchronization of child task from Asana failed!'));
}
if (!$ref->getIsVisible()) {
$ref->getExternalObject()->delete();
continue;
}
$have_phids[$ref->getExternalObject()->getPHID()] = $ref;
}
}
// Remove any edges in Phabricator which don't have valid tasks in Asana.
// These are likely tasks which have been deleted. We're going to respawn
// them.
foreach ($sub_edges as $sub_phid => $sub_edge) {
if (isset($have_phids[$sub_phid])) {
continue;
}
$this->log(
"%s\n",
pht(
'Removing subtask edge to %s, foreign object is not visible.',
$sub_phid));
$sub_editor->removeEdge($src_phid, $etype_sub, $sub_phid);
unset($sub_edges[$sub_phid]);
}
// For each active or passive user, we're looking for an existing, valid
// task. If we find one we're going to update it; if we don't, we'll
// create one. We ignore extra subtasks that we didn't create (we gain
// nothing by deleting them and might be nuking something important) and
// ignore subtasks which have been moved across workspaces or replanted
// under new parents (this stuff is too edge-casey to bother checking for
// and complicated to fix, as it needs extra API calls). However, we do
// clean up subtasks we created whose owners are no longer associated
// with the object.
$subtask_states = array_fill_keys($active_phids, false) +
array_fill_keys($passive_phids, true);
// Continue with only those users who have Asana credentials.
$subtask_states = array_select_keys(
$subtask_states,
array_keys($phid_aid_map));
$need_subtasks = $subtask_states;
$user_to_ref_map = array();
$nuke_refs = array();
foreach ($sub_edges as $sub_phid => $sub_edge) {
$user_phid = idx($sub_edge['data'], 'userPHID');
if (isset($need_subtasks[$user_phid])) {
unset($need_subtasks[$user_phid]);
$user_to_ref_map[$user_phid] = $have_phids[$sub_phid];
} else {
// This user isn't associated with the object anymore, so get rid
// of their task and edge.
$nuke_refs[$sub_phid] = $have_phids[$sub_phid];
}
}
// These are tasks we know about but which are no longer relevant -- for
// example, because a user has been removed as a reviewer. Remove them and
// their edges.
foreach ($nuke_refs as $sub_phid => $ref) {
$sub_editor->removeEdge($src_phid, $etype_sub, $sub_phid);
$this->makeAsanaAPICall(
$oauth_token,
'tasks/'.$ref->getObjectID(),
'DELETE',
array());
$ref->getExternalObject()->delete();
}
// For each user that we don't have a subtask for, create a new subtask.
foreach ($need_subtasks as $user_phid => $is_completed) {
$subtask = $this->makeAsanaAPICall(
$oauth_token,
'tasks',
'POST',
$subtask_data + array(
'assignee' => $phid_aid_map[$user_phid],
'completed' => (int)$is_completed,
'parent' => $parent_ref->getObjectID(),
));
$subtask_ref = $this->newRefFromResult(
DoorkeeperBridgeAsana::OBJTYPE_TASK,
$subtask);
$user_to_ref_map[$user_phid] = $subtask_ref;
// We don't need to synchronize this subtask's state because we just
// set it when we created it.
unset($subtask_states[$user_phid]);
// Add an edge to track this subtask.
$sub_editor->addEdge(
$src_phid,
$etype_sub,
$subtask_ref->getExternalObject()->getPHID(),
array(
'data' => array(
'userPHID' => $user_phid,
),
));
}
// Synchronize all the previously-existing subtasks.
foreach ($subtask_states as $user_phid => $is_completed) {
$this->makeAsanaAPICall(
$oauth_token,
'tasks/'.$user_to_ref_map[$user_phid]->getObjectID(),
'PUT',
$subtask_data + array(
'assignee' => $phid_aid_map[$user_phid],
'completed' => (int)$is_completed,
));
}
foreach ($user_to_ref_map as $user_phid => $ref) {
// For each subtask, if the acting user isn't the same user as the subtask
// owner, remove the acting user as a follower. Currently, the acting user
// will be added as a follower only when they create the task, but this
// may change in the future (e.g., closing the task may also mark them
// as a follower). Wipe every subtask to be sure. The intent here is to
// leave only the owner as a follower so that the acting user doesn't
// receive notifications about changes to subtask state. Note that
// removing followers is silent in all cases in Asana and never produces
// any kind of notification, so this isn't self-defeating.
if ($user_phid != $possessed_user->getPHID()) {
$this->makeAsanaAPICall(
$oauth_token,
'tasks/'.$ref->getObjectID().'/removeFollowers',
'POST',
array(
'followers' => array($possessed_asana_id),
));
}
}
// Update edges on our side.
$sub_editor->save();
// Don't publish the "create" story, since pushing the object into Asana
// naturally generates a notification which effectively serves the same
// purpose as the "create" story. Similarly, "close" stories generate a
// close notification.
if (!$publisher->isStoryAboutObjectCreation($object) &&
!$publisher->isStoryAboutObjectClosure($object)) {
// Post the feed story itself to the main Asana task. We do this last
// because everything else is idempotent, so this is the only effect we
// can't safely run more than once.
$text = $publisher
->setRenderWithImpliedContext(true)
->getStoryText($object);
$this->makeAsanaAPICall(
$oauth_token,
'tasks/'.$parent_ref->getObjectID().'/stories',
'POST',
array(
'text' => $text,
));
}
}
/* -( Internals )---------------------------------------------------------- */
private function getWorkspaceID() {
return PhabricatorEnv::getEnvConfig('asana.workspace-id');
}
private function getProvider() {
if (!$this->provider) {
$provider = PhabricatorAsanaAuthProvider::getAsanaProvider();
if (!$provider) {
throw new PhabricatorWorkerPermanentFailureException(
pht('No Asana provider configured.'));
}
$this->provider = $provider;
}
return $this->provider;
}
private function getAsanaTaskData($object) {
$publisher = $this->getPublisher();
$title = $publisher->getObjectTitle($object);
$uri = $publisher->getObjectURI($object);
$description = $publisher->getObjectDescription($object);
$is_completed = $publisher->isObjectClosed($object);
$notes = array(
$description,
$uri,
$this->getSynchronizationWarning(),
);
$notes = implode("\n\n", $notes);
return array(
'name' => $title,
'notes' => $notes,
'completed' => (int)$is_completed,
);
}
private function getAsanaSubtaskData($object) {
$publisher = $this->getPublisher();
$title = $publisher->getResponsibilityTitle($object);
$uri = $publisher->getObjectURI($object);
$description = $publisher->getObjectDescription($object);
$notes = array(
$description,
$uri,
$this->getSynchronizationWarning(),
);
$notes = implode("\n\n", $notes);
return array(
'name' => $title,
'notes' => $notes,
);
}
private function getSynchronizationWarning() {
return pht(
"\xE2\x9A\xA0 DO NOT EDIT THIS TASK \xE2\x9A\xA0\n".
"\xE2\x98\xA0 Your changes will not be reflected in %s.\n".
"\xE2\x98\xA0 Your changes will be destroyed the next time state ".
"is synchronized.",
PlatformSymbols::getPlatformServerName());
}
private function lookupAsanaUserIDs($all_phids) {
$phid_map = array();
$all_phids = array_unique(array_filter($all_phids));
if (!$all_phids) {
return $phid_map;
}
$accounts = $this->loadAsanaExternalAccounts($all_phids);
foreach ($accounts as $account) {
$phid_map[$account->getUserPHID()] = $this->getAsanaAccountID($account);
}
// Put this back in input order.
$phid_map = array_select_keys($phid_map, $all_phids);
return $phid_map;
}
private function loadAsanaExternalAccounts(array $user_phids) {
$provider = $this->getProvider();
$viewer = $this->getViewer();
if (!$user_phids) {
return array();
}
$accounts = id(new PhabricatorExternalAccountQuery())
->setViewer(PhabricatorUser::getOmnipotentUser())
->withUserPHIDs($user_phids)
->withProviderConfigPHIDs(
array(
$provider->getProviderConfigPHID(),
))
->needAccountIdentifiers(true)
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->execute();
return $accounts;
}
private function findAnyValidAsanaAccessToken(array $user_phids) {
$provider = $this->getProvider();
$viewer = $this->getViewer();
if (!$user_phids) {
return array(null, null, null);
}
$accounts = $this->loadAsanaExternalAccounts($user_phids);
// Reorder accounts in the original order.
// TODO: This needs to be adjusted if/when we allow you to link multiple
// accounts.
$accounts = mpull($accounts, null, 'getUserPHID');
$accounts = array_select_keys($accounts, $user_phids);
$workspace_id = $this->getWorkspaceID();
foreach ($accounts as $account) {
// Get a token if possible.
$token = $provider->getOAuthAccessToken($account);
if (!$token) {
continue;
}
// Verify we can actually make a call with the token, and that the user
// has access to the workspace in question.
try {
id(new PhutilAsanaFuture())
->setAccessToken($token)
->setRawAsanaQuery("workspaces/{$workspace_id}")
->resolve();
} catch (Exception $ex) {
// This token didn't make it through; try the next account.
continue;
}
$user = id(new PhabricatorPeopleQuery())
->setViewer($viewer)
->withPHIDs(array($account->getUserPHID()))
->executeOne();
if ($user) {
return array($user, $this->getAsanaAccountID($account), $token);
}
}
return array(null, null, null);
}
private function makeAsanaAPICall($token, $action, $method, array $params) {
foreach ($params as $key => $value) {
if ($value === null) {
unset($params[$key]);
} else if (is_array($value)) {
unset($params[$key]);
foreach ($value as $skey => $svalue) {
$params[$key.'['.$skey.']'] = $svalue;
}
}
}
return id(new PhutilAsanaFuture())
->setAccessToken($token)
->setMethod($method)
->setRawAsanaQuery($action, $params)
->resolve();
}
private function newRefFromResult($type, $result) {
$ref = id(new DoorkeeperObjectRef())
->setApplicationType(DoorkeeperBridgeAsana::APPTYPE_ASANA)
->setApplicationDomain(DoorkeeperBridgeAsana::APPDOMAIN_ASANA)
->setObjectType($type)
->setObjectID($result['gid'])
->setIsVisible(true);
$xobj = $ref->newExternalObject();
$ref->attachExternalObject($xobj);
$bridge = new DoorkeeperBridgeAsana();
$bridge->fillObjectFromData($xobj, $result);
$xobj->save();
return $ref;
}
private function addFollowers(
$oauth_token,
$task_id,
array $followers,
$silent = false) {
if (!$followers) {
return;
}
$data = array(
'followers' => $followers,
);
// NOTE: This uses a currently-undocumented API feature to suppress the
// follow notifications.
if ($silent) {
$data['silent'] = true;
}
$this->makeAsanaAPICall(
$oauth_token,
"tasks/{$task_id}/addFollowers",
'POST',
$data);
}
private function getAsanaProjectIDs() {
$project_ids = array();
$publisher = $this->getPublisher();
$config = PhabricatorEnv::getEnvConfig('asana.project-ids');
if (is_array($config)) {
$ids = idx($config, get_class($publisher));
if (is_array($ids)) {
foreach ($ids as $id) {
if (is_scalar($id)) {
$project_ids[] = $id;
}
}
}
}
return $project_ids;
}
private function addProjects(
$oauth_token,
$task_id,
array $project_ids) {
foreach ($project_ids as $project_id) {
$data = array('project' => $project_id);
$this->makeAsanaAPICall(
$oauth_token,
"tasks/{$task_id}/addProject",
'POST',
$data);
}
}
private function getAsanaAccountID(PhabricatorExternalAccount $account) {
$identifiers = $account->getAccountIdentifiers();
if (count($identifiers) !== 1) {
throw new Exception(
pht(
'Expected external Asana account to have exactly one external '.
'account identifier, found %s.',
phutil_count($identifiers)));
}
return head($identifiers)->getIdentifierRaw();
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/query/DoorkeeperExternalObjectQuery.php | src/applications/doorkeeper/query/DoorkeeperExternalObjectQuery.php | <?php
final class DoorkeeperExternalObjectQuery
extends PhabricatorCursorPagedPolicyAwareQuery {
protected $phids;
protected $objectKeys;
public function withPHIDs(array $phids) {
$this->phids = $phids;
return $this;
}
public function withObjectKeys(array $keys) {
$this->objectKeys = $keys;
return $this;
}
public function newResultObject() {
return new DoorkeeperExternalObject();
}
protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) {
$where = parent::buildWhereClauseParts($conn);
if ($this->phids !== null) {
$where[] = qsprintf(
$conn,
'phid IN (%Ls)',
$this->phids);
}
if ($this->objectKeys !== null) {
$where[] = qsprintf(
$conn,
'objectKey IN (%Ls)',
$this->objectKeys);
}
return $where;
}
public function getQueryApplicationClass() {
return 'PhabricatorDoorkeeperApplication';
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/interface/DoorkeeperRemarkupURIInterface.php | src/applications/doorkeeper/interface/DoorkeeperRemarkupURIInterface.php | <?php
interface DoorkeeperRemarkupURIInterface {
public function getDoorkeeperURIRef(PhutilURI $uri);
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/exception/DoorkeeperMissingLinkException.php | src/applications/doorkeeper/exception/DoorkeeperMissingLinkException.php | <?php
final class DoorkeeperMissingLinkException extends Exception {}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/option/PhabricatorAsanaConfigOptions.php | src/applications/doorkeeper/option/PhabricatorAsanaConfigOptions.php | <?php
final class PhabricatorAsanaConfigOptions
extends PhabricatorApplicationConfigOptions {
public function getName() {
return pht('Integration with Asana');
}
public function getDescription() {
return pht('Asana integration options.');
}
public function getIcon() {
return 'fa-exchange';
}
public function getGroup() {
return 'core';
}
public function getOptions() {
return array(
$this->newOption('asana.workspace-id', 'string', null)
->setSummary(pht('Asana Workspace ID to publish into.'))
->setDescription(
pht(
'To enable synchronization into Asana, enter an Asana Workspace '.
'ID here.'.
"\n\n".
"NOTE: This feature is new and experimental.")),
$this->newOption('asana.project-ids', 'wild', null)
->setSummary(pht('Optional Asana projects to use as application tags.'))
->setDescription(
pht(
'When %s creates tasks in Asana, it can add the tasks '.
'to Asana projects based on which application the corresponding '.
'object in %s comes from. For example, you can add code '.
'reviews in Asana to a "Differential" project.'.
"\n\n".
'NOTE: This feature is new and experimental.',
PlatformSymbols::getPlatformServerName(),
PlatformSymbols::getPlatformServerName())),
);
}
public function renderContextualDescription(
PhabricatorConfigOption $option,
AphrontRequest $request) {
switch ($option->getKey()) {
case 'asana.workspace-id':
break;
case 'asana.project-ids':
return $this->renderContextualProjectDescription($option, $request);
default:
return parent::renderContextualDescription($option, $request);
}
$viewer = $request->getUser();
$provider = PhabricatorAsanaAuthProvider::getAsanaProvider();
if (!$provider) {
return null;
}
$account = id(new PhabricatorExternalAccountQuery())
->setViewer($viewer)
->withUserPHIDs(array($viewer->getPHID()))
->withProviderConfigPHIDs(
array(
$provider->getProviderConfigPHID(),
))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->executeOne();
if (!$account) {
return null;
}
$token = $provider->getOAuthAccessToken($account);
if (!$token) {
return null;
}
try {
$workspaces = id(new PhutilAsanaFuture())
->setAccessToken($token)
->setRawAsanaQuery('workspaces')
->resolve();
} catch (Exception $ex) {
return null;
}
if (!$workspaces) {
return null;
}
$out = array();
$out[] = sprintf(
'| %s | %s |',
pht('Workspace ID'),
pht('Workspace Name'));
$out[] = '| ------------ | -------------- |';
foreach ($workspaces as $workspace) {
$out[] = sprintf(
'| `%s` | `%s` |',
$workspace['gid'],
$workspace['name']);
}
$out = implode("\n", $out);
$out = pht(
"The Asana Workspaces your linked account has access to are:\n\n%s",
$out);
return new PHUIRemarkupView($viewer, $out);
}
private function renderContextualProjectDescription(
PhabricatorConfigOption $option,
AphrontRequest $request) {
$viewer = $request->getUser();
$publishers = id(new PhutilClassMapQuery())
->setAncestorClass('DoorkeeperFeedStoryPublisher')
->execute();
$out = array();
$out[] = pht(
'To specify projects to add tasks to, enter a JSON map with publisher '.
'class names as keys and a list of project IDs as values. For example, '.
'to put Differential tasks into Asana projects with IDs `123` and '.
'`456`, enter:'.
"\n\n".
" lang=txt\n".
" {\n".
" \"DifferentialDoorkeeperRevisionFeedStoryPublisher\" : [123, 456]\n".
" }\n");
$out[] = pht('Available publishers class names are:');
foreach ($publishers as $publisher) {
$out[] = ' - `'.get_class($publisher).'`';
}
$out[] = pht(
'You can find an Asana project ID by clicking the project in Asana and '.
'then examining the URL:'.
"\n\n".
" lang=txt\n".
" https://app.asana.com/0/12345678901234567890/111111111111111111\n".
" ^^^^^^^^^^^^^^^^^^^^\n".
" This is the ID to use.\n");
$out = implode("\n", $out);
return new PHUIRemarkupView($viewer, $out);
}
}
| php | Apache-2.0 | 5720a38cfe95b00ca4be5016dd0d2f3195f4fa04 | 2026-01-04T15:03:23.651835Z | false |
phacility/phabricator | https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/doorkeeper/application/PhabricatorDoorkeeperApplication.php | src/applications/doorkeeper/application/PhabricatorDoorkeeperApplication.php | <?php
final class PhabricatorDoorkeeperApplication extends PhabricatorApplication {
public function canUninstall() {
return false;
}
public function isLaunchable() {
return false;
}
public function getName() {
return pht('Doorkeeper');
}
public function getIcon() {
return 'fa-recycle';
}
public function getShortDescription() {
return pht('Connect to Other Software');
}
public function getRoutes() {
return array(
'/doorkeeper/' => array(
'tags/' => 'DoorkeeperTagsController',
),
);
}
}
| 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.