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/conpherence/conduit/ConpherenceConduitAPIMethod.php
src/applications/conpherence/conduit/ConpherenceConduitAPIMethod.php
<?php abstract class ConpherenceConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass( 'PhabricatorConpherenceApplication'); } final protected function getConpherenceURI(ConpherenceThread $conpherence) { $id = $conpherence->getID(); return PhabricatorEnv::getProductionURI( $this->getApplication()->getApplicationURI($id)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/conpherence/conduit/ConpherenceQueryTransactionConduitAPIMethod.php
src/applications/conpherence/conduit/ConpherenceQueryTransactionConduitAPIMethod.php
<?php final class ConpherenceQueryTransactionConduitAPIMethod extends ConpherenceConduitAPIMethod { public function getAPIMethodName() { return 'conpherence.querytransaction'; } public function getMethodDescription() { return pht( 'Query for transactions for the logged in user within a specific '. 'Conpherence room. You can specify the room by ID or PHID. '. 'Otherwise, specify limit and offset to query the most recent '. 'transactions within the Conpherence room for the logged in user.'); } protected function defineParamTypes() { return array( 'roomID' => 'optional int', 'roomPHID' => 'optional phid', 'limit' => 'optional int', 'offset' => 'optional int', ); } protected function defineReturnType() { return 'nonempty dict'; } protected function defineErrorTypes() { return array( 'ERR_USAGE_NO_ROOM_ID' => pht( 'You must specify a room id or room PHID to query transactions '. 'from.'), ); } protected function execute(ConduitAPIRequest $request) { $user = $request->getUser(); $room_id = $request->getValue('roomID'); $room_phid = $request->getValue('roomPHID'); $limit = $request->getValue('limit'); $offset = $request->getValue('offset'); $query = id(new ConpherenceThreadQuery()) ->setViewer($user); if ($room_id) { $query->withIDs(array($room_id)); } else if ($room_phid) { $query->withPHIDs(array($room_phid)); } else { throw new ConduitException('ERR_USAGE_NO_ROOM_ID'); } $conpherence = $query->executeOne(); $query = id(new ConpherenceTransactionQuery()) ->setViewer($user) ->withObjectPHIDs(array($conpherence->getPHID())) ->setLimit($limit) ->setOffset($offset); $transactions = $query->execute(); $data = array(); foreach ($transactions as $transaction) { $comment = null; $comment_obj = $transaction->getComment(); if ($comment_obj) { $comment = $comment_obj->getContent(); } $title = null; $title_obj = $transaction->getTitle(); if ($title_obj) { $title = $title_obj->getHTMLContent(); } $id = $transaction->getID(); $data[$id] = array( 'transactionID' => $id, 'transactionType' => $transaction->getTransactionType(), 'transactionTitle' => $title, 'transactionComment' => $comment, 'transactionOldValue' => $transaction->getOldValue(), 'transactionNewValue' => $transaction->getNewValue(), 'transactionMetadata' => $transaction->getMetadata(), 'authorPHID' => $transaction->getAuthorPHID(), 'dateCreated' => $transaction->getDateCreated(), 'roomID' => $conpherence->getID(), 'roomPHID' => $conpherence->getPHID(), ); } return $data; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/conpherence/conduit/ConpherenceCreateThreadConduitAPIMethod.php
src/applications/conpherence/conduit/ConpherenceCreateThreadConduitAPIMethod.php
<?php final class ConpherenceCreateThreadConduitAPIMethod extends ConpherenceConduitAPIMethod { public function getAPIMethodName() { return 'conpherence.createthread'; } public function getMethodDescription() { return pht('Create a new conpherence thread.'); } public function getMethodStatus() { return self::METHOD_STATUS_FROZEN; } public function getMethodStatusDescription() { return pht( 'This method is frozen and will eventually be deprecated. New code '. 'should use "conpherence.edit" instead.'); } protected function defineParamTypes() { return array( 'title' => 'required string', 'topic' => 'optional string', 'message' => 'optional string', 'participantPHIDs' => 'required list<phids>', ); } protected function defineReturnType() { return 'nonempty dict'; } protected function defineErrorTypes() { return array( 'ERR_EMPTY_PARTICIPANT_PHIDS' => pht( 'You must specify participant phids.'), 'ERR_EMPTY_TITLE' => pht( 'You must specify a title.'), ); } protected function execute(ConduitAPIRequest $request) { $participant_phids = $request->getValue('participantPHIDs', array()); $message = $request->getValue('message'); $title = $request->getValue('title'); $topic = $request->getValue('topic'); list($errors, $conpherence) = ConpherenceEditor::createThread( $request->getUser(), $participant_phids, $title, $message, $request->newContentSource(), $topic); if ($errors) { foreach ($errors as $error_code) { switch ($error_code) { case ConpherenceEditor::ERROR_EMPTY_PARTICIPANTS: throw new ConduitException('ERR_EMPTY_PARTICIPANT_PHIDS'); break; } } } return array( 'conpherenceID' => $conpherence->getID(), 'conpherencePHID' => $conpherence->getPHID(), 'conpherenceURI' => $this->getConpherenceURI($conpherence), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/conpherence/conduit/ConpherenceQueryThreadConduitAPIMethod.php
src/applications/conpherence/conduit/ConpherenceQueryThreadConduitAPIMethod.php
<?php final class ConpherenceQueryThreadConduitAPIMethod extends ConpherenceConduitAPIMethod { public function getAPIMethodName() { return 'conpherence.querythread'; } public function getMethodDescription() { return pht( 'Query for Conpherence threads for the logged in user. You can query '. 'by IDs or PHIDs for specific Conpherence threads. Otherwise, specify '. 'limit and offset to query the most recently updated Conpherences for '. 'the logged in user.'); } protected function defineParamTypes() { return array( 'ids' => 'optional array<int>', 'phids' => 'optional array<phids>', 'limit' => 'optional int', 'offset' => 'optional int', ); } protected function defineReturnType() { return 'nonempty dict'; } protected function execute(ConduitAPIRequest $request) { $user = $request->getUser(); $ids = $request->getValue('ids', array()); $phids = $request->getValue('phids', array()); $limit = $request->getValue('limit'); $offset = $request->getValue('offset'); $query = id(new ConpherenceThreadQuery()) ->setViewer($user); if ($ids) { $conpherences = $query ->withIDs($ids) ->setLimit($limit) ->setOffset($offset) ->execute(); } else if ($phids) { $conpherences = $query ->withPHIDs($phids) ->setLimit($limit) ->setOffset($offset) ->execute(); } else { $participation = id(new ConpherenceParticipantQuery()) ->withParticipantPHIDs(array($user->getPHID())) ->setLimit($limit) ->setOffset($offset) ->execute(); $conpherence_phids = mpull($participation, 'getConpherencePHID'); $query->withPHIDs($conpherence_phids); $conpherences = $query->execute(); $conpherences = array_select_keys($conpherences, $conpherence_phids); } $data = array(); foreach ($conpherences as $conpherence) { $id = $conpherence->getID(); $data[$id] = array( 'conpherenceID' => $id, 'conpherencePHID' => $conpherence->getPHID(), 'conpherenceTitle' => $conpherence->getTitle(), 'messageCount' => $conpherence->getMessageCount(), 'conpherenceURI' => $this->getConpherenceURI($conpherence), ); } return $data; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/conpherence/conduit/ConpherenceEditConduitAPIMethod.php
src/applications/conpherence/conduit/ConpherenceEditConduitAPIMethod.php
<?php final class ConpherenceEditConduitAPIMethod extends PhabricatorEditEngineAPIMethod { public function getAPIMethodName() { return 'conpherence.edit'; } public function newEditEngine() { return new ConpherenceEditEngine(); } public function getMethodSummary() { return pht( 'Apply transactions to create a new room or edit an existing one.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/conpherence/conduit/ConpherenceUpdateThreadConduitAPIMethod.php
src/applications/conpherence/conduit/ConpherenceUpdateThreadConduitAPIMethod.php
<?php final class ConpherenceUpdateThreadConduitAPIMethod extends ConpherenceConduitAPIMethod { public function getAPIMethodName() { return 'conpherence.updatethread'; } public function getMethodDescription() { return pht('Update an existing conpherence room.'); } public function getMethodStatus() { return self::METHOD_STATUS_FROZEN; } public function getMethodStatusDescription() { return pht( 'This method is frozen and will eventually be deprecated. New code '. 'should use "conpherence.edit" instead.'); } protected function defineParamTypes() { return array( 'id' => 'optional int', 'phid' => 'optional phid', 'title' => 'optional string', 'message' => 'optional string', 'addParticipantPHIDs' => 'optional list<phids>', 'removeParticipantPHID' => 'optional phid', ); } protected function defineReturnType() { return 'bool'; } protected function defineErrorTypes() { return array( 'ERR_USAGE_NO_ROOM_ID' => pht( 'You must specify a room ID or room PHID to query transactions from.'), 'ERR_USAGE_ROOM_NOT_FOUND' => pht( 'Room does not exist or logged in user can not see it.'), 'ERR_USAGE_ONLY_SELF_REMOVE' => pht( 'Only a user can remove themselves from a room.'), 'ERR_USAGE_NO_UPDATES' => pht( 'You must specify data that actually updates the Conpherence.'), ); } protected function execute(ConduitAPIRequest $request) { $user = $request->getUser(); $id = $request->getValue('id'); $phid = $request->getValue('phid'); $query = id(new ConpherenceThreadQuery()) ->setViewer($user); if ($id) { $query->withIDs(array($id)); } else if ($phid) { $query->withPHIDs(array($phid)); } else { throw new ConduitException('ERR_USAGE_NO_ROOM_ID'); } $conpherence = $query->executeOne(); if (!$conpherence) { throw new ConduitException('ERR_USAGE_ROOM_NOT_FOUND'); } $source = $request->newContentSource(); $editor = id(new ConpherenceEditor()) ->setContentSource($source) ->setActor($user); $xactions = array(); $add_participant_phids = $request->getValue('addParticipantPHIDs', array()); $remove_participant_phid = $request->getValue('removeParticipantPHID'); $message = $request->getValue('message'); $title = $request->getValue('title'); if ($add_participant_phids) { $xactions[] = id(new ConpherenceTransaction()) ->setTransactionType( ConpherenceThreadParticipantsTransaction::TRANSACTIONTYPE) ->setNewValue(array('+' => $add_participant_phids)); } if ($remove_participant_phid) { if ($remove_participant_phid != $user->getPHID()) { throw new ConduitException('ERR_USAGE_ONLY_SELF_REMOVE'); } $xactions[] = id(new ConpherenceTransaction()) ->setTransactionType( ConpherenceThreadParticipantsTransaction::TRANSACTIONTYPE) ->setNewValue(array('-' => array($remove_participant_phid))); } if ($title) { $xactions[] = id(new ConpherenceTransaction()) ->setTransactionType( ConpherenceThreadTitleTransaction::TRANSACTIONTYPE) ->setNewValue($title); } if ($message) { $xactions = array_merge( $xactions, $editor->generateTransactionsFromText( $user, $conpherence, $message)); } try { $xactions = $editor->applyTransactions($conpherence, $xactions); } catch (PhabricatorApplicationTransactionNoEffectException $ex) { throw new ConduitException('ERR_USAGE_NO_UPDATES'); } 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/conpherence/typeahead/ConpherenceThreadDatasource.php
src/applications/conpherence/typeahead/ConpherenceThreadDatasource.php
<?php final class ConpherenceThreadDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Room'); } public function getPlaceholderText() { return pht('Type a room title...'); } public function getDatasourceApplicationClass() { return 'PhabricatorConpherenceApplication'; } public function loadResults() { $viewer = $this->getViewer(); $raw_query = $this->getRawQuery(); $rooms = id(new ConpherenceThreadQuery()) ->setViewer($viewer) ->withTitleNgrams($raw_query) ->needParticipants(true) ->execute(); $results = array(); foreach ($rooms as $room) { if (strlen($room->getTopic())) { $topic = $room->getTopic(); } else { $topic = phutil_tag('em', array(), pht('No topic set')); } $token = id(new PhabricatorTypeaheadResult()) ->setName($room->getTitle()) ->setPHID($room->getPHID()) ->addAttribute($topic); $results[] = $token; } 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/conpherence/remarkup/ConpherenceThreadRemarkupRule.php
src/applications/conpherence/remarkup/ConpherenceThreadRemarkupRule.php
<?php final class ConpherenceThreadRemarkupRule extends PhabricatorObjectRemarkupRule { protected function getObjectNamePrefix() { return 'Z'; } protected function loadObjects(array $ids) { $viewer = $this->getEngine()->getConfig('viewer'); $threads = id(new ConpherenceThreadQuery()) ->setViewer($viewer) ->withIDs($ids) ->execute(); return mpull($threads, null, 'getID'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/conpherence/constants/ConpherenceRoomSettings.php
src/applications/conpherence/constants/ConpherenceRoomSettings.php
<?php final class ConpherenceRoomSettings extends ConpherenceConstants { const SOUND_RECEIVE = 'receive'; const SOUND_MENTION = 'mention'; const DEFAULT_RECEIVE_SOUND = 'tap'; const DEFAULT_MENTION_SOUND = 'alert'; const DEFAULT_NO_SOUND = 'none'; const COLOR_LIGHT = 'light'; const COLOR_BLUE = 'blue'; const COLOR_INDIGO = 'indigo'; const COLOR_PEACH = 'peach'; const COLOR_GREEN = 'green'; const COLOR_PINK = 'pink'; public static function getSoundMap() { return array( 'none' => array( 'name' => pht('No Sound'), 'rsrc' => '', ), 'alert' => array( 'name' => pht('Alert'), 'rsrc' => celerity_get_resource_uri('/rsrc/audio/basic/alert.mp3'), ), 'bing' => array( 'name' => pht('Bing'), 'rsrc' => celerity_get_resource_uri('/rsrc/audio/basic/bing.mp3'), ), 'pock' => array( 'name' => pht('Pock'), 'rsrc' => celerity_get_resource_uri('/rsrc/audio/basic/pock.mp3'), ), 'tap' => array( 'name' => pht('Tap'), 'rsrc' => celerity_get_resource_uri('/rsrc/audio/basic/tap.mp3'), ), 'ting' => array( 'name' => pht('Ting'), 'rsrc' => celerity_get_resource_uri('/rsrc/audio/basic/ting.mp3'), ), ); } public static function getDropdownSoundMap() { $map = self::getSoundMap(); return ipull($map, 'name'); } public static function getThemeMap() { return array( self::COLOR_LIGHT => pht('Light'), self::COLOR_BLUE => pht('Blue'), self::COLOR_INDIGO => pht('Indigo'), self::COLOR_PEACH => pht('Peach'), self::COLOR_GREEN => pht('Green'), self::COLOR_PINK => pht('Pink'), ); } public static function getThemeClass($theme) { return 'conpherence-theme-'.$theme; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/conpherence/constants/ConpherenceConstants.php
src/applications/conpherence/constants/ConpherenceConstants.php
<?php abstract class ConpherenceConstants extends Phobject {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/conpherence/constants/ConpherenceUpdateActions.php
src/applications/conpherence/constants/ConpherenceUpdateActions.php
<?php final class ConpherenceUpdateActions extends ConpherenceConstants { const MESSAGE = 'message'; const DRAFT = 'draft'; const JOIN_ROOM = 'join_room'; const ADD_PERSON = 'add_person'; const REMOVE_PERSON = 'remove_person'; const ADD_STATUS = 'add_status'; const LOAD = 'load'; }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/controller/PhabricatorNotificationPanelController.php
src/applications/notification/controller/PhabricatorNotificationPanelController.php
<?php final class PhabricatorNotificationPanelController extends PhabricatorNotificationController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $unread_count = $viewer->getUnreadNotificationCount(); $warning = $this->prunePhantomNotifications($unread_count); $query = id(new PhabricatorNotificationQuery()) ->setViewer($viewer) ->withUserPHIDs(array($viewer->getPHID())) ->setLimit(10); $stories = $query->execute(); $clear_ui_class = 'phabricator-notification-clear-all'; $clear_uri = id(new PhutilURI('/notification/clear/')); if ($stories) { $builder = id(new PhabricatorNotificationBuilder($stories)) ->setUser($viewer); $notifications_view = $builder->buildView(); $content = $notifications_view->render(); $clear_uri->replaceQueryParam( 'chronoKey', head($stories)->getChronologicalKey()); } else { $content = phutil_tag_div( 'phabricator-notification no-notifications', pht('You have no notifications.')); $clear_ui_class .= ' disabled'; } $clear_ui = javelin_tag( 'a', array( 'sigil' => 'workflow', 'href' => (string)$clear_uri, 'class' => $clear_ui_class, ), pht('Mark All Read')); $notifications_link = phutil_tag( 'a', array( 'href' => '/notification/', ), pht('Notifications')); $connection_status = new PhabricatorNotificationStatusView(); $connection_ui = phutil_tag( 'div', array( 'class' => 'phabricator-notification-footer', ), $connection_status); $header = phutil_tag( 'div', array( 'class' => 'phabricator-notification-header', ), array( $notifications_link, $clear_ui, )); $content = hsprintf( '%s%s%s%s', $header, $warning, $content, $connection_ui); $json = array( 'content' => $content, 'number' => (int)$unread_count, ); return id(new AphrontAjaxResponse())->setContent($json); } private function prunePhantomNotifications($unread_count) { // See T8953. If you have an unread notification about an object you // do not have permission to view, it isn't possible to clear it by // visiting the object. Identify these notifications and mark them as // read. $viewer = $this->getViewer(); if (!$unread_count) { return null; } $table = new PhabricatorFeedStoryNotification(); $conn = $table->establishConnection('r'); $rows = queryfx_all( $conn, 'SELECT chronologicalKey, primaryObjectPHID FROM %T WHERE userPHID = %s AND hasViewed = 0', $table->getTableName(), $viewer->getPHID()); if (!$rows) { return null; } $map = array(); foreach ($rows as $row) { $map[$row['primaryObjectPHID']][] = $row['chronologicalKey']; } $handles = $viewer->loadHandles(array_keys($map)); $purge_keys = array(); foreach ($handles as $handle) { $phid = $handle->getPHID(); if ($handle->isComplete()) { continue; } foreach ($map[$phid] as $chronological_key) { $purge_keys[] = $chronological_key; } } if (!$purge_keys) { return null; } $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $conn = $table->establishConnection('w'); queryfx( $conn, 'UPDATE %T SET hasViewed = 1 WHERE userPHID = %s AND chronologicalKey IN (%Ls)', $table->getTableName(), $viewer->getPHID(), $purge_keys); PhabricatorUserCache::clearCache( PhabricatorUserNotificationCountCacheType::KEY_COUNT, $viewer->getPHID()); unset($unguarded); return phutil_tag( 'div', array( 'class' => 'phabricator-notification phabricator-notification-warning', ), pht( '%s notification(s) about objects which no longer exist or which '. 'you can no longer see were discarded.', phutil_count($purge_keys))); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/controller/PhabricatorNotificationClearController.php
src/applications/notification/controller/PhabricatorNotificationClearController.php
<?php final class PhabricatorNotificationClearController extends PhabricatorNotificationController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $chrono_key = $request->getStr('chronoKey'); if ($request->isDialogFormPost()) { $should_clear = true; } else { $should_clear = $request->hasCSRF(); } if ($should_clear) { $table = new PhabricatorFeedStoryNotification(); queryfx( $table->establishConnection('w'), 'UPDATE %T SET hasViewed = 1 '. 'WHERE userPHID = %s AND hasViewed = 0 and chronologicalKey <= %s', $table->getTableName(), $viewer->getPHID(), $chrono_key); PhabricatorUserCache::clearCache( PhabricatorUserNotificationCountCacheType::KEY_COUNT, $viewer->getPHID()); return id(new AphrontReloadResponse()) ->setURI('/notification/'); } $dialog = new AphrontDialogView(); $dialog->setUser($viewer); $dialog->addCancelButton('/notification/'); if ($chrono_key) { $dialog->setTitle(pht('Really mark all notifications as read?')); $dialog->addHiddenInput('chronoKey', $chrono_key); $is_serious = PhabricatorEnv::getEnvConfig('phabricator.serious-business'); if ($is_serious) { $dialog->appendChild( pht( 'All unread notifications will be marked as read. You can not '. 'undo this action.')); } else { $dialog->appendChild( pht( "You can't ignore your problems forever, you know.")); } $dialog->addSubmitButton(pht('Mark All Read')); } else { $dialog->setTitle(pht('No notifications to mark as read.')); $dialog->appendChild(pht('You have no unread notifications.')); } return id(new AphrontDialogResponse())->setDialog($dialog); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/controller/PhabricatorNotificationController.php
src/applications/notification/controller/PhabricatorNotificationController.php
<?php abstract class PhabricatorNotificationController extends PhabricatorController {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/controller/PhabricatorNotificationIndividualController.php
src/applications/notification/controller/PhabricatorNotificationIndividualController.php
<?php final class PhabricatorNotificationIndividualController extends PhabricatorNotificationController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $stories = id(new PhabricatorNotificationQuery()) ->setViewer($viewer) ->withUserPHIDs(array($viewer->getPHID())) ->withKeys(array($request->getStr('key'))) ->execute(); if (!$stories) { return $this->buildEmptyResponse(); } $story = head($stories); if ($story->getAuthorPHID() === $viewer->getPHID()) { // Don't show the user individual notifications about their own // actions. Primarily, this stops pages from showing notifications // immediately after you click "Submit" on a comment form if the // notification server returns faster than the web server. // TODO: It would be nice to retain the "page updated" bubble on copies // of the page that are open in other tabs, but there isn't an obvious // way to do this easily. return $this->buildEmptyResponse(); } $builder = id(new PhabricatorNotificationBuilder(array($story))) ->setUser($viewer) ->setShowTimestamps(false); $content = $builder->buildView()->render(); $dict = $builder->buildDict(); $data = $dict[0]; $response = $data + array( 'pertinent' => true, 'primaryObjectPHID' => $story->getPrimaryObjectPHID(), 'content' => hsprintf('%s', $content), 'uniqueID' => 'story/'.$story->getChronologicalKey(), ); return id(new AphrontAjaxResponse())->setContent($response); } private function buildEmptyResponse() { return id(new AphrontAjaxResponse())->setContent( array( 'pertinent' => false, )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/controller/PhabricatorNotificationTestController.php
src/applications/notification/controller/PhabricatorNotificationTestController.php
<?php final class PhabricatorNotificationTestController extends PhabricatorNotificationController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); if ($request->validateCSRF()) { $message_text = pht( 'This is a test notification, sent at %s.', phabricator_datetime(time(), $viewer)); // NOTE: Currently, the FeedStoryPublisher explicitly filters out // notifications about your own actions. Send this notification from // a different actor to get around this. $application_phid = id(new PhabricatorNotificationsApplication()) ->getPHID(); $xactions = array(); $xactions[] = id(new PhabricatorUserTransaction()) ->setTransactionType( PhabricatorUserNotifyTransaction::TRANSACTIONTYPE) ->setNewValue($message_text) ->setForceNotifyPHIDs(array($viewer->getPHID())); $editor = id(new PhabricatorUserTransactionEditor()) ->setActor($viewer) ->setActingAsPHID($application_phid) ->setContentSourceFromRequest($request); $editor->applyTransactions($viewer, $xactions); } return id(new AphrontAjaxResponse()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/controller/PhabricatorNotificationListController.php
src/applications/notification/controller/PhabricatorNotificationListController.php
<?php final class PhabricatorNotificationListController extends PhabricatorNotificationController { public function handleRequest(AphrontRequest $request) { $querykey = $request->getURIData('queryKey'); $controller = id(new PhabricatorApplicationSearchController()) ->setQueryKey($querykey) ->setSearchEngine(new PhabricatorNotificationSearchEngine()) ->setNavigation($this->buildSideNavView()); return $this->delegateToController($controller); } public function buildSideNavView() { $viewer = $this->getViewer(); $nav = new AphrontSideNavFilterView(); $nav->setBaseURI(new PhutilURI($this->getApplicationURI())); id(new PhabricatorNotificationSearchEngine()) ->setViewer($viewer) ->addNavigationItems($nav->getMenu()); $nav->selectFilter(null); return $nav; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/engineextension/PhabricatorNotificationDestructionEngineExtension.php
src/applications/notification/engineextension/PhabricatorNotificationDestructionEngineExtension.php
<?php final class PhabricatorNotificationDestructionEngineExtension extends PhabricatorDestructionEngineExtension { const EXTENSIONKEY = 'notifications'; public function getExtensionName() { return pht('Notifications'); } public function destroyObject( PhabricatorDestructionEngine $engine, $object) { $table = new PhabricatorFeedStoryNotification(); $conn_w = $table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE primaryObjectPHID = %s', $table->getTableName(), $object->getPHID()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/storage/PhabricatorFeedStoryNotification.php
src/applications/notification/storage/PhabricatorFeedStoryNotification.php
<?php final class PhabricatorFeedStoryNotification extends PhabricatorFeedDAO { protected $userPHID; protected $primaryObjectPHID; protected $chronologicalKey; protected $hasViewed; protected function getConfiguration() { return array( self::CONFIG_IDS => self::IDS_MANUAL, self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'chronologicalKey' => 'uint64', 'hasViewed' => 'bool', 'id' => null, ), self::CONFIG_KEY_SCHEMA => array( 'PRIMARY' => null, 'userPHID' => array( 'columns' => array('userPHID', 'chronologicalKey'), 'unique' => true, ), 'userPHID_2' => array( 'columns' => array('userPHID', 'hasViewed', 'primaryObjectPHID'), ), 'key_object' => array( 'columns' => array('primaryObjectPHID'), ), 'key_chronological' => array( 'columns' => array('chronologicalKey'), ), ), ) + parent::getConfiguration(); } public static function updateObjectNotificationViews( PhabricatorUser $user, $object_phid) { if (PhabricatorEnv::isReadOnly()) { return; } $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites(); $notification_table = new PhabricatorFeedStoryNotification(); $conn = $notification_table->establishConnection('w'); queryfx( $conn, 'UPDATE %T SET hasViewed = 1 WHERE userPHID = %s AND primaryObjectPHID = %s AND hasViewed = 0', $notification_table->getTableName(), $user->getPHID(), $object_phid); unset($unguarded); $count_key = PhabricatorUserNotificationCountCacheType::KEY_COUNT; PhabricatorUserCache::clearCache($count_key, $user->getPHID()); $user->clearCacheData($count_key); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/query/PhabricatorNotificationSearchEngine.php
src/applications/notification/query/PhabricatorNotificationSearchEngine.php
<?php final class PhabricatorNotificationSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Notifications'); } public function getApplicationClassName() { return 'PhabricatorNotificationsApplication'; } public function buildSavedQueryFromRequest(AphrontRequest $request) { $saved = new PhabricatorSavedQuery(); $saved->setParameter( 'unread', $this->readBoolFromRequest($request, 'unread')); return $saved; } public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) { $query = id(new PhabricatorNotificationQuery()) ->withUserPHIDs(array($this->requireViewer()->getPHID())); if ($saved->getParameter('unread')) { $query->withUnread(true); } return $query; } public function buildSearchForm( AphrontFormView $form, PhabricatorSavedQuery $saved) { $unread = $saved->getParameter('unread'); $form->appendChild( id(new AphrontFormCheckboxControl()) ->setLabel(pht('Unread')) ->addCheckbox( 'unread', 1, pht('Show only unread notifications.'), $unread)); } protected function getURI($path) { return '/notification/'.$path; } protected function getBuiltinQueryNames() { $names = array( 'all' => pht('All Notifications'), 'unread' => pht('Unread Notifications'), ); return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; case 'unread': return $query->setParameter('unread', true); } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $notifications, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($notifications, 'PhabricatorFeedStory'); $viewer = $this->requireViewer(); $image = id(new PHUIIconView()) ->setIcon('fa-bell-o'); $button = id(new PHUIButtonView()) ->setTag('a') ->addSigil('workflow') ->setColor(PHUIButtonView::GREY) ->setIcon($image) ->setText(pht('Mark All Read')); switch ($query->getQueryKey()) { case 'unread': $header = pht('Unread Notifications'); $no_data = pht('You have no unread notifications.'); break; default: $header = pht('Notifications'); $no_data = pht('You have no notifications.'); break; } $clear_uri = id(new PhutilURI('/notification/clear/')); if ($notifications) { $builder = id(new PhabricatorNotificationBuilder($notifications)) ->setUser($viewer); $view = $builder->buildView(); $clear_uri->replaceQueryParam( 'chronoKey', head($notifications)->getChronologicalKey()); } else { $view = phutil_tag_div( 'phabricator-notification no-notifications', $no_data); $button->setDisabled(true); } $button->setHref((string)$clear_uri); $view = id(new PHUIBoxView()) ->addPadding(PHUI::PADDING_MEDIUM) ->addClass('phabricator-notification-list') ->appendChild($view); $result = new PhabricatorApplicationSearchResultView(); $result->addAction($button); $result->setContent($view); return $result; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/query/PhabricatorNotificationQuery.php
src/applications/notification/query/PhabricatorNotificationQuery.php
<?php /** * @task config Configuring the Query * @task exec Query Execution */ final class PhabricatorNotificationQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $userPHIDs; private $keys; private $unread; /* -( Configuring the Query )---------------------------------------------- */ public function withUserPHIDs(array $user_phids) { $this->userPHIDs = $user_phids; return $this; } public function withKeys(array $keys) { $this->keys = $keys; return $this; } /** * Filter results by read/unread status. Note that `true` means to return * only unread notifications, while `false` means to return only //read// * notifications. The default is `null`, which returns both. * * @param mixed True or false to filter results by read status. Null to remove * the filter. * @return this * @task config */ public function withUnread($unread) { $this->unread = $unread; return $this; } /* -( Query Execution )---------------------------------------------------- */ protected function loadPage() { $story_table = new PhabricatorFeedStoryData(); $notification_table = new PhabricatorFeedStoryNotification(); $conn = $story_table->establishConnection('r'); $data = queryfx_all( $conn, 'SELECT story.*, notification.hasViewed FROM %R notification JOIN %R story ON notification.chronologicalKey = story.chronologicalKey %Q ORDER BY notification.chronologicalKey DESC %Q', $notification_table, $story_table, $this->buildWhereClause($conn), $this->buildLimitClause($conn)); return $data; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->userPHIDs !== null) { $where[] = qsprintf( $conn, 'notification.userPHID IN (%Ls)', $this->userPHIDs); } if ($this->unread !== null) { $where[] = qsprintf( $conn, 'notification.hasViewed = %d', (int)!$this->unread); } if ($this->keys !== null) { $where[] = qsprintf( $conn, 'notification.chronologicalKey IN (%Ls)', $this->keys); } return $where; } protected function willFilterPage(array $rows) { // See T13623. The policy model here is outdated and awkward. // Users may have notifications about objects they can no longer see. // Two ways this can arise: destroy an object; or change an object's // view policy to exclude a user. // "PhabricatorFeedStory::loadAllFromRows()" does its own policy filtering. // This doesn't align well with modern query sequencing, but we should be // able to get away with it by loading here. // See T13623. Although most queries for notifications return unique // stories, this isn't a guarantee. $story_map = ipull($rows, null, 'chronologicalKey'); $viewer = $this->getViewer(); $stories = PhabricatorFeedStory::loadAllFromRows($story_map, $viewer); $stories = mpull($stories, null, 'getChronologicalKey'); $results = array(); foreach ($rows as $row) { $story_key = $row['chronologicalKey']; $has_viewed = $row['hasViewed']; if (!isset($stories[$story_key])) { // NOTE: We can't call "didRejectResult()" here because we don't have // a policy object to pass. continue; } $story = id(clone $stories[$story_key]) ->setHasViewed($has_viewed); if (!$story->isVisibleInNotifications()) { continue; } $results[] = $story; } return $results; } protected function getDefaultOrderVector() { return array('key'); } public function getBuiltinOrders() { return array( 'newest' => array( 'vector' => array('key'), 'name' => pht('Creation (Newest First)'), 'aliases' => array('created'), ), 'oldest' => array( 'vector' => array('-key'), 'name' => pht('Creation (Oldest First)'), ), ); } public function getOrderableColumns() { return array( 'key' => array( 'table' => 'notification', 'column' => 'chronologicalKey', 'type' => 'string', 'unique' => true, ), ); } protected function applyExternalCursorConstraintsToQuery( PhabricatorCursorPagedPolicyAwareQuery $subquery, $cursor) { $subquery ->withKeys(array($cursor)) ->setLimit(1); } protected function newExternalCursorStringForResult($object) { return $object->getChronologicalKey(); } protected function newPagingMapFromPartialObject($object) { return array( 'key' => $object['chronologicalKey'], ); } protected function getPrimaryTableAlias() { return 'notification'; } public function getQueryApplicationClass() { return 'PhabricatorNotificationsApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/builder/PhabricatorNotificationBuilder.php
src/applications/notification/builder/PhabricatorNotificationBuilder.php
<?php final class PhabricatorNotificationBuilder extends Phobject { private $stories; private $parsedStories; private $user = null; private $showTimestamps = true; public function __construct(array $stories) { assert_instances_of($stories, 'PhabricatorFeedStory'); $this->stories = $stories; } public function setUser($user) { $this->user = $user; return $this; } public function setShowTimestamps($show_timestamps) { $this->showTimestamps = $show_timestamps; return $this; } public function getShowTimestamps() { return $this->showTimestamps; } private function parseStories() { if ($this->parsedStories) { return $this->parsedStories; } $stories = $this->stories; $stories = mpull($stories, null, 'getChronologicalKey'); // Aggregate notifications. Generally, we can aggregate notifications only // by object, e.g. "a updated T123" and "b updated T123" can become // "a and b updated T123", but we can't combine "a updated T123" and // "a updated T234" into "a updated T123 and T234" because there would be // nowhere sensible for the notification to link to, and no reasonable way // to unambiguously clear it. // Build up a map of all the possible aggregations. $chronokey_map = array(); $aggregation_map = array(); $agg_types = array(); foreach ($stories as $chronokey => $story) { $chronokey_map[$chronokey] = $story->getNotificationAggregations(); foreach ($chronokey_map[$chronokey] as $key => $type) { $agg_types[$key] = $type; $aggregation_map[$key]['keys'][$chronokey] = true; } } // Repeatedly select the largest available aggregation until none remain. $aggregated_stories = array(); while ($aggregation_map) { // Count the size of each aggregation, removing any which will consume // fewer than 2 stories. foreach ($aggregation_map as $key => $dict) { $size = count($dict['keys']); if ($size > 1) { $aggregation_map[$key]['size'] = $size; } else { unset($aggregation_map[$key]); } } // If we're out of aggregations, break out. if (!$aggregation_map) { break; } // Select the aggregation we're going to make, and remove it from the // map. $aggregation_map = isort($aggregation_map, 'size'); $agg_info = idx(last($aggregation_map), 'keys'); $agg_key = last_key($aggregation_map); unset($aggregation_map[$agg_key]); // Select all the stories it aggregates, and remove them from the master // list of stories and from all other possible aggregations. $sub_stories = array(); foreach ($agg_info as $chronokey => $ignored) { $sub_stories[$chronokey] = $stories[$chronokey]; unset($stories[$chronokey]); foreach ($chronokey_map[$chronokey] as $key => $type) { unset($aggregation_map[$key]['keys'][$chronokey]); } unset($chronokey_map[$chronokey]); } // Build the aggregate story. krsort($sub_stories); $story_class = $agg_types[$agg_key]; $conv = array(head($sub_stories)->getStoryData()); $new_story = newv($story_class, $conv); $new_story->setAggregateStories($sub_stories); $aggregated_stories[] = $new_story; } // Combine the aggregate stories back into the list of stories. $stories = array_merge($stories, $aggregated_stories); $stories = mpull($stories, null, 'getChronologicalKey'); krsort($stories); $this->parsedStories = $stories; return $stories; } public function buildView() { $stories = $this->parseStories(); $null_view = new AphrontNullView(); foreach ($stories as $story) { try { $view = $story->renderView(); } catch (Exception $ex) { // TODO: Render a nice debuggable notice instead? continue; } $view->setShowTimestamp($this->getShowTimestamps()); $null_view->appendChild($view->renderNotification($this->user)); } return $null_view; } public function buildDict() { $stories = $this->parseStories(); $dict = array(); $viewer = $this->user; $key = PhabricatorNotificationsSetting::SETTINGKEY; $setting = $viewer->getUserSetting($key); $desktop_ready = PhabricatorNotificationsSetting::desktopReady($setting); $web_ready = PhabricatorNotificationsSetting::webReady($setting); foreach ($stories as $story) { if ($story instanceof PhabricatorApplicationTransactionFeedStory) { $dict[] = array( 'showAnyNotification' => $web_ready, 'showDesktopNotification' => $desktop_ready, 'title' => $story->renderText(), 'body' => $story->renderTextBody(), 'href' => $story->getURI(), 'icon' => $story->getImageURI(), ); } else { $dict[] = array( 'showWebNotification' => false, 'showDesktopNotification' => false, 'title' => null, 'body' => null, 'href' => null, 'icon' => null, ); } } return $dict; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/application/PhabricatorNotificationsApplication.php
src/applications/notification/application/PhabricatorNotificationsApplication.php
<?php final class PhabricatorNotificationsApplication extends PhabricatorApplication { public function getName() { return pht('Notifications'); } public function getBaseURI() { return '/notification/'; } public function getShortDescription() { return pht('Real-Time Updates and Alerts'); } public function getIcon() { return 'fa-bell'; } public function getRoutes() { return array( '/notification/' => array( '(?:query/(?P<queryKey>[^/]+)/)?' => 'PhabricatorNotificationListController', 'panel/' => 'PhabricatorNotificationPanelController', 'individual/' => 'PhabricatorNotificationIndividualController', 'clear/' => 'PhabricatorNotificationClearController', 'test/' => 'PhabricatorNotificationTestController', ), ); } public function isLaunchable() { 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/notification/garbagecollector/FeedStoryNotificationGarbageCollector.php
src/applications/notification/garbagecollector/FeedStoryNotificationGarbageCollector.php
<?php final class FeedStoryNotificationGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'feed.notifications'; public function getCollectorName() { return pht('Notifications'); } public function getDefaultRetentionPolicy() { return phutil_units('90 days in seconds'); } protected function collectGarbage() { $table = new PhabricatorFeedStoryNotification(); $conn_w = $table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE chronologicalKey < (%d << 32) ORDER BY chronologicalKey ASC LIMIT 100', $table->getTableName(), $this->getGarbageEpoch()); return ($conn_w->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/view/PhabricatorNotificationStatusView.php
src/applications/notification/view/PhabricatorNotificationStatusView.php
<?php final class PhabricatorNotificationStatusView extends AphrontTagView { protected function getTagAttributes() { if (!$this->getID()) { $this->setID(celerity_generate_unique_node_id()); } Javelin::initBehavior( 'aphlict-status', array( 'nodeID' => $this->getID(), 'pht' => array( 'setup' => pht('Setting Up Client'), 'open' => pht('Connected'), 'closed' => pht('Disconnected'), ), 'icon' => array( 'open' => array( 'icon' => 'fa-circle', 'color' => 'green', ), 'setup' => array( 'icon' => 'fa-circle', 'color' => 'yellow', ), 'closed' => array( 'icon' => 'fa-circle', 'color' => 'red', ), ), )); return array( 'class' => 'aphlict-connection-status', ); } protected function getTagContent() { $have = PhabricatorEnv::getEnvConfig('notification.servers'); if ($have) { $icon = id(new PHUIIconView()) ->setIcon('fa-circle-o yellow'); $text = pht('Connecting...'); return phutil_tag( 'span', array( 'class' => 'connection-status-text '. 'aphlict-connection-status-connecting', ), array( $icon, $text, )); } else { $text = pht('Notification server not enabled'); $icon = id(new PHUIIconView()) ->setIcon('fa-circle-o grey'); return phutil_tag( 'span', array( 'class' => 'connection-status-text '. 'aphlict-connection-status-notenabled', ), array( $icon, $text, )); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/setup/PhabricatorAphlictSetupCheck.php
src/applications/notification/setup/PhabricatorAphlictSetupCheck.php
<?php final class PhabricatorAphlictSetupCheck extends PhabricatorSetupCheck { protected function executeChecks() { try { PhabricatorNotificationClient::tryAnyConnection(); } catch (Exception $ex) { $message = pht( "This server is configured to use a notification server, but is ". "unable to connect to it. You should resolve this issue or disable ". "the notification server. It may be helpful to double check your ". "configuration or restart the server using the command below.\n\n%s", phutil_tag( 'pre', array(), array( get_class($ex), "\n", $ex->getMessage(), ))); $this->newIssue('aphlict.connect') ->setShortName(pht('Notification Server Down')) ->setName(pht('Unable to Connect to Notification Server')) ->setSummary( pht( 'This server is configured to use a notification server, '. 'but is not able to connect to it.')) ->setMessage($message) ->addRelatedPhabricatorConfig('notification.servers') ->addCommand( pht( "(To start the server, run this command.)\n%s", '$ ./bin/aphlict start')); return; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/config/PhabricatorNotificationServersConfigType.php
src/applications/notification/config/PhabricatorNotificationServersConfigType.php
<?php final class PhabricatorNotificationServersConfigType extends PhabricatorJSONConfigType { const TYPEKEY = 'cluster.notifications'; public function validateStoredValue( PhabricatorConfigOption $option, $value) { foreach ($value as $index => $spec) { if (!is_array($spec)) { throw $this->newException( pht( 'Notification server configuration is not valid: each entry in '. 'the list must be a dictionary describing a service, but '. 'the value with index "%s" is not a dictionary.', $index)); } } $has_admin = false; $has_client = false; $map = array(); foreach ($value as $index => $spec) { try { PhutilTypeSpec::checkMap( $spec, array( 'type' => 'string', 'host' => 'string', 'port' => 'int', 'protocol' => 'string', 'path' => 'optional string', 'disabled' => 'optional bool', )); } catch (Exception $ex) { throw $this->newException( pht( 'Notification server configuration has an invalid service '. 'specification (at index "%s"): %s.', $index, $ex->getMessage())); } $type = $spec['type']; $host = $spec['host']; $port = $spec['port']; $protocol = $spec['protocol']; $disabled = idx($spec, 'disabled'); switch ($type) { case 'admin': if (!$disabled) { $has_admin = true; } break; case 'client': if (!$disabled) { $has_client = true; } break; default: throw $this->newException( pht( 'Notification server configuration describes an invalid '. 'host ("%s", at index "%s") with an unrecognized type ("%s"). '. 'Valid types are "%s" or "%s".', $host, $index, $type, 'admin', 'client')); } switch ($protocol) { case 'http': case 'https': break; default: throw $this->newException( pht( 'Notification server configuration describes an invalid '. 'host ("%s", at index "%s") with an invalid protocol ("%s"). '. 'Valid protocols are "%s" or "%s".', $host, $index, $protocol, 'http', 'https')); } $path = idx($spec, 'path'); if ($type == 'admin' && $path !== null && strlen($path)) { throw $this->newException( pht( 'Notification server configuration describes an invalid host '. '("%s", at index "%s"). This is an "admin" service but it has a '. '"path" property. This property is only valid for "client" '. 'services.', $host, $index)); } // We can't guarantee that you didn't just give the same host two // different names in DNS, but this check can catch silly copy/paste // mistakes. $key = "{$host}:{$port}"; if (isset($map[$key])) { throw $this->newException( pht( 'Notification server configuration is invalid: it describes the '. 'same host and port ("%s") multiple times. Each host and port '. 'combination should appear only once in the list.', $key)); } $map[$key] = true; } if ($value) { if (!$has_admin) { throw $this->newException( pht( 'Notification server configuration is invalid: it does not '. 'specify any enabled servers with type "admin". Notifications '. 'require at least one active "admin" server.')); } if (!$has_client) { throw $this->newException( pht( 'Notification server configuration is invalid: it does not '. 'specify any enabled servers with type "client". Notifications '. 'require at least one active "client" server.')); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/client/PhabricatorNotificationClient.php
src/applications/notification/client/PhabricatorNotificationClient.php
<?php final class PhabricatorNotificationClient extends Phobject { public static function tryAnyConnection() { $servers = PhabricatorNotificationServerRef::getEnabledAdminServers(); if (!$servers) { return; } foreach ($servers as $server) { $server->loadServerStatus(); return; } return; } public static function tryToPostMessage(array $data) { $unique_id = Filesystem::readRandomCharacters(32); $data = $data + array( 'uniqueID' => $unique_id, ); $servers = PhabricatorNotificationServerRef::getEnabledAdminServers(); shuffle($servers); foreach ($servers as $server) { try { $server->postMessage($data); return; } catch (Exception $ex) { // Just ignore any issues here. } } } public static function isEnabled() { return (bool)PhabricatorNotificationServerRef::getEnabledAdminServers(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/notification/client/PhabricatorNotificationServerRef.php
src/applications/notification/client/PhabricatorNotificationServerRef.php
<?php final class PhabricatorNotificationServerRef extends Phobject { private $type; private $host; private $port; private $protocol; private $path; private $isDisabled; const KEY_REFS = 'notification.refs'; public function setType($type) { $this->type = $type; return $this; } public function getType() { return $this->type; } public function setHost($host) { $this->host = $host; return $this; } public function getHost() { return $this->host; } public function setPort($port) { $this->port = $port; return $this; } public function getPort() { return $this->port; } public function setProtocol($protocol) { $this->protocol = $protocol; return $this; } public function getProtocol() { return $this->protocol; } public function setPath($path) { $this->path = $path; return $this; } public function getPath() { return $this->path; } public function setIsDisabled($is_disabled) { $this->isDisabled = $is_disabled; return $this; } public function getIsDisabled() { return $this->isDisabled; } public static function getLiveServers() { $cache = PhabricatorCaches::getRequestCache(); $refs = $cache->getKey(self::KEY_REFS); if (!$refs) { $refs = self::newRefs(); $cache->setKey(self::KEY_REFS, $refs); } return $refs; } public static function newRefs() { $configs = PhabricatorEnv::getEnvConfig('notification.servers'); $refs = array(); foreach ($configs as $config) { $ref = id(new self()) ->setType($config['type']) ->setHost($config['host']) ->setPort($config['port']) ->setProtocol($config['protocol']) ->setPath(idx($config, 'path')) ->setIsDisabled(idx($config, 'disabled', false)); $refs[] = $ref; } return $refs; } public static function getEnabledServers() { $servers = self::getLiveServers(); foreach ($servers as $key => $server) { if ($server->getIsDisabled()) { unset($servers[$key]); } } return array_values($servers); } public static function getEnabledAdminServers() { $servers = self::getEnabledServers(); foreach ($servers as $key => $server) { if (!$server->isAdminServer()) { unset($servers[$key]); } } return array_values($servers); } public static function getEnabledClientServers($with_protocol) { $servers = self::getEnabledServers(); foreach ($servers as $key => $server) { if ($server->isAdminServer()) { unset($servers[$key]); continue; } $protocol = $server->getProtocol(); if ($protocol != $with_protocol) { unset($servers[$key]); continue; } } return array_values($servers); } public function isAdminServer() { return ($this->type == 'admin'); } public function getURI($to_path = null) { if ($to_path === null || !strlen($to_path)) { $to_path = ''; } else { $to_path = ltrim($to_path, '/'); } $base_path = $this->getPath(); if ($base_path === null || !strlen($base_path)) { $base_path = ''; } else { $base_path = rtrim($base_path, '/'); } $full_path = $base_path.'/'.$to_path; $uri = id(new PhutilURI('http://'.$this->getHost())) ->setProtocol($this->getProtocol()) ->setPort($this->getPort()) ->setPath($full_path); $instance = PhabricatorEnv::getEnvConfig('cluster.instance'); if ($instance !== null && strlen($instance)) { $uri->replaceQueryParam('instance', $instance); } return $uri; } public function getWebsocketURI($to_path = null) { $instance = PhabricatorEnv::getEnvConfig('cluster.instance'); if ($instance !== null && strlen($instance)) { $to_path = $to_path.'~'.$instance.'/'; } $uri = $this->getURI($to_path); if ($this->getProtocol() == 'https') { $uri->setProtocol('wss'); } else { $uri->setProtocol('ws'); } return $uri; } public function testClient() { if ($this->isAdminServer()) { throw new Exception( pht('Unable to test client on an admin server!')); } $server_uri = $this->getURI(); try { id(new HTTPSFuture($server_uri)) ->setTimeout(2) ->resolvex(); } catch (HTTPFutureHTTPResponseStatus $ex) { // This is what we expect when things are working correctly. if ($ex->getStatusCode() == 501) { return true; } throw $ex; } throw new Exception( pht('Got HTTP 200, but expected HTTP 501 (WebSocket Upgrade)!')); } public function loadServerStatus() { if (!$this->isAdminServer()) { throw new Exception( pht( 'Unable to load server status: this is not an admin server!')); } $server_uri = $this->getURI('/status/'); list($body) = $this->newFuture($server_uri) ->resolvex(); return phutil_json_decode($body); } public function postMessage(array $data) { if (!$this->isAdminServer()) { throw new Exception( pht('Unable to post message: this is not an admin server!')); } $server_uri = $this->getURI('/'); $payload = phutil_json_encode($data); $this->newFuture($server_uri, $payload) ->setMethod('POST') ->resolvex(); } private function newFuture($uri, $data = null) { if ($data === null) { $future = new HTTPSFuture($uri); } else { $future = new HTTPSFuture($uri, $data); } $future->setTimeout(2); // At one point, a HackerOne researcher reported a "Location:" redirect // attack here (if the attacker can gain control of the notification // server or the configuration). // Although this attack is not particularly concerning, we don't expect // Aphlict to ever issue a "Location:" header, so receiving one indicates // something is wrong and declining to follow the header may make debugging // easier. $future->setFollowLocation(false); return $future; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/controller/PhabricatorPasteRawController.php
src/applications/paste/controller/PhabricatorPasteRawController.php
<?php /** * Redirect to the current raw contents of a Paste. * * This controller provides a stable URI for getting the current contents of * a paste, and slightly simplifies the view controller. */ final class PhabricatorPasteRawController extends PhabricatorPasteController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $paste = id(new PhabricatorPasteQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); if (!$paste) { return new Aphront404Response(); } $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($paste->getFilePHID())) ->executeOne(); if (!$file) { return new Aphront400Response(); } return $file->getRedirectResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/controller/PhabricatorPasteViewController.php
src/applications/paste/controller/PhabricatorPasteViewController.php
<?php final class PhabricatorPasteViewController extends PhabricatorPasteController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $paste = id(new PhabricatorPasteQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->needContent(true) ->needRawContent(true) ->executeOne(); if (!$paste) { return new Aphront404Response(); } $lines = $request->getURILineRange('lines', 1000); if ($lines) { $map = range($lines[0], $lines[1]); } else { $map = array(); } $header = $this->buildHeaderView($paste); $curtain = $this->buildCurtain($paste); $subheader = $this->buildSubheaderView($paste); $source_code = $this->buildSourceCodeView($paste, $map); require_celerity_resource('paste-css'); $monogram = $paste->getMonogram(); $crumbs = $this->buildApplicationCrumbs() ->addTextCrumb($monogram) ->setBorder(true); $timeline = $this->buildTransactionTimeline( $paste, new PhabricatorPasteTransactionQuery()); $comment_view = id(new PhabricatorPasteEditEngine()) ->setViewer($viewer) ->buildEditEngineCommentView($paste); $timeline->setQuoteRef($monogram); $comment_view->setTransactionTimeline($timeline); $recommendation_view = $this->newDocumentRecommendationView($paste); $paste_view = id(new PHUITwoColumnView()) ->setHeader($header) ->setSubheader($subheader) ->setMainColumn( array( $recommendation_view, $source_code, $timeline, $comment_view, )) ->setCurtain($curtain); return $this->newPage() ->setTitle($paste->getFullName()) ->setCrumbs($crumbs) ->setPageObjectPHIDs( array( $paste->getPHID(), )) ->appendChild($paste_view); } private function buildHeaderView(PhabricatorPaste $paste) { $title = (nonempty($paste->getTitle())) ? $paste->getTitle() : pht('(An Untitled Masterwork)'); if ($paste->isArchived()) { $header_icon = 'fa-ban'; $header_name = pht('Archived'); $header_color = 'dark'; } else { $header_icon = 'fa-check'; $header_name = pht('Active'); $header_color = 'bluegrey'; } $header = id(new PHUIHeaderView()) ->setHeader($title) ->setUser($this->getRequest()->getUser()) ->setStatus($header_icon, $header_color, $header_name) ->setPolicyObject($paste) ->setHeaderIcon('fa-clipboard'); return $header; } private function buildCurtain(PhabricatorPaste $paste) { $viewer = $this->getViewer(); $curtain = $this->newCurtainView($paste); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $paste, PhabricatorPolicyCapability::CAN_EDIT); $id = $paste->getID(); $edit_uri = $this->getApplicationURI("edit/{$id}/"); $archive_uri = $this->getApplicationURI("archive/{$id}/"); $raw_uri = $this->getApplicationURI("raw/{$id}/"); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Paste')) ->setIcon('fa-pencil') ->setDisabled(!$can_edit) ->setHref($edit_uri)); if ($paste->isArchived()) { $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Activate Paste')) ->setIcon('fa-check') ->setDisabled(!$can_edit) ->setWorkflow($can_edit) ->setHref($archive_uri)); } else { $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Archive Paste')) ->setIcon('fa-ban') ->setDisabled(!$can_edit) ->setWorkflow($can_edit) ->setHref($archive_uri)); } $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('View Raw File')) ->setIcon('fa-file-text-o') ->setHref($raw_uri)); return $curtain; } private function buildSubheaderView( PhabricatorPaste $paste) { $viewer = $this->getViewer(); $author = $viewer->renderHandle($paste->getAuthorPHID())->render(); $date = phabricator_datetime($paste->getDateCreated(), $viewer); $author = phutil_tag('strong', array(), $author); $author_info = id(new PhabricatorPeopleQuery()) ->setViewer($viewer) ->withPHIDs(array($paste->getAuthorPHID())) ->needProfileImage(true) ->executeOne(); $image_uri = $author_info->getProfileImageURI(); $image_href = '/p/'.$author_info->getUsername(); $content = pht('Authored by %s on %s.', $author, $date); return id(new PHUIHeadThingView()) ->setImage($image_uri) ->setImageHref($image_href) ->setContent($content); } private function newDocumentRecommendationView(PhabricatorPaste $paste) { $viewer = $this->getViewer(); // See PHI1703. If a viewer is looking at a document in Paste which has // a good rendering via a DocumentEngine, suggest they view the content // in Files instead so they can see it rendered. $ref = id(new PhabricatorDocumentRef()) ->setName($paste->getTitle()) ->setData($paste->getRawContent()); $engines = PhabricatorDocumentEngine::getEnginesForRef($viewer, $ref); if (!$engines) { return null; } $engine = head($engines); if (!$engine->shouldSuggestEngine($ref)) { return null; } $file = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($paste->getFilePHID())) ->executeOne(); if (!$file) { return null; } $file_ref = id(new PhabricatorDocumentRef()) ->setFile($file); $view_uri = id(new PhabricatorFileDocumentRenderingEngine()) ->getRefViewURI($file_ref, $engine); $view_as_label = $engine->getViewAsLabel($file_ref); $view_as_hint = pht( 'This content can be rendered as a document in Files.'); return id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->addButton( id(new PHUIButtonView()) ->setTag('a') ->setText($view_as_label) ->setHref($view_uri) ->setColor('grey')) ->setErrors( array( $view_as_hint, )); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/controller/PhabricatorPasteListController.php
src/applications/paste/controller/PhabricatorPasteListController.php
<?php final class PhabricatorPasteListController extends PhabricatorPasteController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { return id(new PhabricatorPasteSearchEngine()) ->setController($this) ->buildResponse(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); id(new PhabricatorPasteEditEngine()) ->setViewer($this->getViewer()) ->addActionToCrumbs($crumbs); return $crumbs; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/controller/PhabricatorPasteArchiveController.php
src/applications/paste/controller/PhabricatorPasteArchiveController.php
<?php final class PhabricatorPasteArchiveController extends PhabricatorPasteController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $paste = id(new PhabricatorPasteQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$paste) { return new Aphront404Response(); } $view_uri = $paste->getURI(); if ($request->isFormPost()) { if ($paste->isArchived()) { $new_status = PhabricatorPaste::STATUS_ACTIVE; } else { $new_status = PhabricatorPaste::STATUS_ARCHIVED; } $xactions = array(); $xactions[] = id(new PhabricatorPasteTransaction()) ->setTransactionType(PhabricatorPasteStatusTransaction::TRANSACTIONTYPE) ->setNewValue($new_status); id(new PhabricatorPasteEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->applyTransactions($paste, $xactions); return id(new AphrontRedirectResponse())->setURI($view_uri); } if ($paste->isArchived()) { $title = pht('Activate Paste'); $body = pht('This paste will become consumable again.'); $button = pht('Activate Paste'); } else { $title = pht('Archive Paste'); $body = pht('This paste will be marked as expired.'); $button = pht('Archive Paste'); } 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/paste/controller/PhabricatorPasteEditController.php
src/applications/paste/controller/PhabricatorPasteEditController.php
<?php final class PhabricatorPasteEditController extends PhabricatorPasteController { public function handleRequest(AphrontRequest $request) { return id(new PhabricatorPasteEditEngine()) ->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/paste/controller/PhabricatorPasteController.php
src/applications/paste/controller/PhabricatorPasteController.php
<?php abstract class PhabricatorPasteController extends PhabricatorController { public function buildApplicationMenu() { return $this->newApplicationMenu() ->setSearchEngine(new PhabricatorPasteSearchEngine()); } public function buildSourceCodeView( PhabricatorPaste $paste, $highlights = array()) { $lines = phutil_split_lines($paste->getContent()); return id(new PhabricatorSourceCodeView()) ->setLines($lines) ->setHighlights($highlights) ->setURI(new PhutilURI($paste->getURI())); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/engineextension/PhabricatorPasteContentSearchEngineAttachment.php
src/applications/paste/engineextension/PhabricatorPasteContentSearchEngineAttachment.php
<?php final class PhabricatorPasteContentSearchEngineAttachment extends PhabricatorSearchEngineAttachment { public function getAttachmentName() { return pht('Paste Content'); } public function getAttachmentDescription() { return pht('Get the full content for each paste.'); } public function willLoadAttachmentData($query, $spec) { $query->needRawContent(true); } public function getAttachmentForObject($object, $data, $spec) { return array( 'content' => $object->getRawContent(), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/storage/PhabricatorPaste.php
src/applications/paste/storage/PhabricatorPaste.php
<?php final class PhabricatorPaste extends PhabricatorPasteDAO implements PhabricatorSubscribableInterface, PhabricatorTokenReceiverInterface, PhabricatorFlaggableInterface, PhabricatorMentionableInterface, PhabricatorPolicyInterface, PhabricatorProjectInterface, PhabricatorDestructibleInterface, PhabricatorApplicationTransactionInterface, PhabricatorSpacesInterface, PhabricatorConduitResultInterface, PhabricatorFerretInterface, PhabricatorFulltextInterface { protected $title; protected $authorPHID; protected $filePHID; protected $language; protected $parentPHID; protected $viewPolicy; protected $editPolicy; protected $mailKey; protected $status; protected $spacePHID; const STATUS_ACTIVE = 'active'; const STATUS_ARCHIVED = 'archived'; private $content = self::ATTACHABLE; private $rawContent = self::ATTACHABLE; private $snippet = self::ATTACHABLE; public static function initializeNewPaste(PhabricatorUser $actor) { $app = id(new PhabricatorApplicationQuery()) ->setViewer($actor) ->withClasses(array('PhabricatorPasteApplication')) ->executeOne(); $view_policy = $app->getPolicy(PasteDefaultViewCapability::CAPABILITY); $edit_policy = $app->getPolicy(PasteDefaultEditCapability::CAPABILITY); return id(new PhabricatorPaste()) ->setTitle('') ->setStatus(self::STATUS_ACTIVE) ->setAuthorPHID($actor->getPHID()) ->setViewPolicy($view_policy) ->setEditPolicy($edit_policy) ->setSpacePHID($actor->getDefaultSpacePHID()) ->attachRawContent(null); } public static function getStatusNameMap() { return array( self::STATUS_ACTIVE => pht('Active'), self::STATUS_ARCHIVED => pht('Archived'), ); } public function getURI() { return '/'.$this->getMonogram(); } public function getMonogram() { return 'P'.$this->getID(); } protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_COLUMN_SCHEMA => array( 'status' => 'text32', 'title' => 'text255', 'language' => 'text64?', 'mailKey' => 'bytes20', 'parentPHID' => 'phid?', // T6203/NULLABILITY // Pastes should always have a view policy. 'viewPolicy' => 'policy?', ), self::CONFIG_KEY_SCHEMA => array( 'parentPHID' => array( 'columns' => array('parentPHID'), ), 'authorPHID' => array( 'columns' => array('authorPHID'), ), 'key_dateCreated' => array( 'columns' => array('dateCreated'), ), 'key_language' => array( 'columns' => array('language'), ), ), ) + parent::getConfiguration(); } public function generatePHID() { return PhabricatorPHID::generateNewPHID( PhabricatorPastePastePHIDType::TYPECONST); } public function isArchived() { return ($this->getStatus() == self::STATUS_ARCHIVED); } public function save() { if (!$this->getMailKey()) { $this->setMailKey(Filesystem::readRandomCharacters(20)); } return parent::save(); } public function getFullName() { $title = $this->getTitle(); if (!$title) { $title = pht('(An Untitled Masterwork)'); } return 'P'.$this->getID().' '.$title; } public function getContent() { return $this->assertAttached($this->content); } public function attachContent($content) { $this->content = $content; return $this; } public function getRawContent() { return $this->assertAttached($this->rawContent); } public function attachRawContent($raw_content) { $this->rawContent = $raw_content; return $this; } public function getSnippet() { return $this->assertAttached($this->snippet); } public function attachSnippet(PhabricatorPasteSnippet $snippet) { $this->snippet = $snippet; return $this; } /* -( PhabricatorSubscribableInterface )----------------------------------- */ public function isAutomaticallySubscribed($phid) { return ($this->authorPHID == $phid); } /* -( PhabricatorTokenReceiverInterface )---------------------------------- */ public function getUsersToNotifyOfTokenGiven() { return array( $this->getAuthorPHID(), ); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { if ($capability == PhabricatorPolicyCapability::CAN_VIEW) { return $this->viewPolicy; } else if ($capability == PhabricatorPolicyCapability::CAN_EDIT) { return $this->editPolicy; } return PhabricatorPolicies::POLICY_NOONE; } public function hasAutomaticCapability($capability, PhabricatorUser $user) { return ($user->getPHID() == $this->getAuthorPHID()); } public function describeAutomaticCapability($capability) { return pht('The author of a paste can always view and edit it.'); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { if ($this->filePHID) { $file = id(new PhabricatorFileQuery()) ->setViewer($engine->getViewer()) ->withPHIDs(array($this->filePHID)) ->executeOne(); if ($file) { $engine->destroyObject($file); } } $this->delete(); } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhabricatorPasteEditor(); } public function getApplicationTransactionTemplate() { return new PhabricatorPasteTransaction(); } /* -( PhabricatorSpacesInterface )----------------------------------------- */ public function getSpacePHID() { return $this->spacePHID; } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('title') ->setType('string') ->setDescription(pht('The title of the paste.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('uri') ->setType('uri') ->setDescription(pht('View URI for the paste.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('authorPHID') ->setType('phid') ->setDescription(pht('User PHID of the author.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('language') ->setType('string?') ->setDescription(pht('Language to use for syntax highlighting.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('status') ->setType('string') ->setDescription(pht('Active or archived status of the paste.')), ); } public function getFieldValuesForConduit() { return array( 'title' => $this->getTitle(), 'uri' => PhabricatorEnv::getURI($this->getURI()), 'authorPHID' => $this->getAuthorPHID(), 'language' => nonempty($this->getLanguage(), null), 'status' => $this->getStatus(), ); } public function getConduitSearchAttachments() { return array( id(new PhabricatorPasteContentSearchEngineAttachment()) ->setAttachmentKey('content'), ); } /* -( PhabricatorFerretInterface )----------------------------------------- */ public function newFerretEngine() { return new PhabricatorPasteFerretEngine(); } /* -( PhabricatorFulltextInterface )--------------------------------------- */ public function newFulltextEngine() { return new PhabricatorPasteFulltextEngine(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/storage/PhabricatorPasteSchemaSpec.php
src/applications/paste/storage/PhabricatorPasteSchemaSpec.php
<?php final class PhabricatorPasteSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new PhabricatorPaste()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/storage/PhabricatorPasteDAO.php
src/applications/paste/storage/PhabricatorPasteDAO.php
<?php abstract class PhabricatorPasteDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'paste'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/storage/PhabricatorPasteTransactionComment.php
src/applications/paste/storage/PhabricatorPasteTransactionComment.php
<?php final class PhabricatorPasteTransactionComment extends PhabricatorApplicationTransactionComment { protected $lineNumber; protected $lineLength; public function getApplicationTransactionObject() { return new PhabricatorPasteTransaction(); } public function shouldUseMarkupCache($field) { // Only cache submitted comments. return ($this->getTransactionPHID() != null); } protected function getConfiguration() { $config = parent::getConfiguration(); $config[self::CONFIG_COLUMN_SCHEMA] = array( 'lineNumber' => 'uint32?', 'lineLength' => 'uint32?', ) + $config[self::CONFIG_COLUMN_SCHEMA]; return $config; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/storage/PhabricatorPasteTransaction.php
src/applications/paste/storage/PhabricatorPasteTransaction.php
<?php final class PhabricatorPasteTransaction extends PhabricatorModularTransaction { const MAILTAG_CONTENT = 'paste-content'; const MAILTAG_OTHER = 'paste-other'; const MAILTAG_COMMENT = 'paste-comment'; public function getApplicationName() { return 'paste'; } public function getApplicationTransactionType() { return PhabricatorPastePastePHIDType::TYPECONST; } public function getApplicationTransactionCommentObject() { return new PhabricatorPasteTransactionComment(); } public function getBaseTransactionClass() { return 'PhabricatorPasteTransactionType'; } public function getMailTags() { $tags = array(); switch ($this->getTransactionType()) { case PhabricatorPasteTitleTransaction::TRANSACTIONTYPE: case PhabricatorPasteContentTransaction::TRANSACTIONTYPE: case PhabricatorPasteLanguageTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_CONTENT; break; case PhabricatorTransactions::TYPE_COMMENT: $tags[] = self::MAILTAG_COMMENT; break; default: $tags[] = self::MAILTAG_OTHER; break; } return $tags; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/query/PhabricatorPasteQuery.php
src/applications/paste/query/PhabricatorPasteQuery.php
<?php final class PhabricatorPasteQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $authorPHIDs; private $parentPHIDs; private $needContent; private $needRawContent; private $needSnippets; private $languages; private $includeNoLanguage; private $dateCreatedAfter; private $dateCreatedBefore; private $statuses; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withAuthorPHIDs(array $phids) { $this->authorPHIDs = $phids; return $this; } public function withParentPHIDs(array $phids) { $this->parentPHIDs = $phids; return $this; } public function needContent($need_content) { $this->needContent = $need_content; return $this; } public function needRawContent($need_raw_content) { $this->needRawContent = $need_raw_content; return $this; } public function needSnippets($need_snippets) { $this->needSnippets = $need_snippets; return $this; } public function withLanguages(array $languages) { $this->includeNoLanguage = false; foreach ($languages as $key => $language) { if ($language === null) { $languages[$key] = ''; continue; } } $this->languages = $languages; return $this; } public function withDateCreatedBefore($date_created_before) { $this->dateCreatedBefore = $date_created_before; return $this; } public function withDateCreatedAfter($date_created_after) { $this->dateCreatedAfter = $date_created_after; return $this; } public function withStatuses(array $statuses) { $this->statuses = $statuses; return $this; } public function newResultObject() { return new PhabricatorPaste(); } protected function didFilterPage(array $pastes) { if ($this->needRawContent) { $pastes = $this->loadRawContent($pastes); } if ($this->needContent) { $pastes = $this->loadContent($pastes); } if ($this->needSnippets) { $pastes = $this->loadSnippets($pastes); } return $pastes; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'paste.id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'paste.phid IN (%Ls)', $this->phids); } if ($this->authorPHIDs !== null) { $where[] = qsprintf( $conn, 'paste.authorPHID IN (%Ls)', $this->authorPHIDs); } if ($this->parentPHIDs !== null) { $where[] = qsprintf( $conn, 'paste.parentPHID IN (%Ls)', $this->parentPHIDs); } if ($this->languages !== null) { $where[] = qsprintf( $conn, 'paste.language IN (%Ls)', $this->languages); } if ($this->dateCreatedAfter !== null) { $where[] = qsprintf( $conn, 'paste.dateCreated >= %d', $this->dateCreatedAfter); } if ($this->dateCreatedBefore !== null) { $where[] = qsprintf( $conn, 'paste.dateCreated <= %d', $this->dateCreatedBefore); } if ($this->statuses !== null) { $where[] = qsprintf( $conn, 'paste.status IN (%Ls)', $this->statuses); } return $where; } protected function getPrimaryTableAlias() { return 'paste'; } private function getContentCacheKey(PhabricatorPaste $paste) { return implode( ':', array( 'P'.$paste->getID(), $paste->getFilePHID(), $paste->getLanguage(), PhabricatorHash::digestForIndex($paste->getTitle()), )); } private function getSnippetCacheKey(PhabricatorPaste $paste) { return implode( ':', array( 'P'.$paste->getID(), $paste->getFilePHID(), $paste->getLanguage(), 'snippet', 'v2.1', PhabricatorHash::digestForIndex($paste->getTitle()), )); } private function loadRawContent(array $pastes) { $file_phids = mpull($pastes, 'getFilePHID'); $files = id(new PhabricatorFileQuery()) ->setParentQuery($this) ->setViewer($this->getViewer()) ->withPHIDs($file_phids) ->execute(); $files = mpull($files, null, 'getPHID'); foreach ($pastes as $key => $paste) { $file = idx($files, $paste->getFilePHID()); if (!$file) { unset($pastes[$key]); continue; } try { $paste->attachRawContent($file->loadFileData()); } catch (Exception $ex) { // We can hit various sorts of file storage issues here. Just drop the // paste if the file is dead. unset($pastes[$key]); continue; } } return $pastes; } private function loadContent(array $pastes) { $cache = new PhabricatorKeyValueDatabaseCache(); $cache = new PhutilKeyValueCacheProfiler($cache); $cache->setProfiler(PhutilServiceProfiler::getInstance()); $keys = array(); foreach ($pastes as $paste) { $keys[] = $this->getContentCacheKey($paste); } $caches = $cache->getKeys($keys); $need_raw = array(); $have_cache = array(); foreach ($pastes as $paste) { $key = $this->getContentCacheKey($paste); if (isset($caches[$key])) { $paste->attachContent(phutil_safe_html($caches[$key])); $have_cache[$paste->getPHID()] = true; } else { $need_raw[$key] = $paste; } } if (!$need_raw) { return $pastes; } $write_data = array(); $have_raw = $this->loadRawContent($need_raw); $have_raw = mpull($have_raw, null, 'getPHID'); foreach ($pastes as $key => $paste) { $paste_phid = $paste->getPHID(); if (isset($have_cache[$paste_phid])) { continue; } if (empty($have_raw[$paste_phid])) { unset($pastes[$key]); continue; } $content = $this->buildContent($paste); $paste->attachContent($content); $write_data[$this->getContentCacheKey($paste)] = (string)$content; } if ($write_data) { $cache->setKeys($write_data); } return $pastes; } private function loadSnippets(array $pastes) { $cache = new PhabricatorKeyValueDatabaseCache(); $cache = new PhutilKeyValueCacheProfiler($cache); $cache->setProfiler(PhutilServiceProfiler::getInstance()); $keys = array(); foreach ($pastes as $paste) { $keys[] = $this->getSnippetCacheKey($paste); } $caches = $cache->getKeys($keys); $need_raw = array(); $have_cache = array(); foreach ($pastes as $paste) { $key = $this->getSnippetCacheKey($paste); if (isset($caches[$key])) { $snippet_data = phutil_json_decode($caches[$key]); $snippet = new PhabricatorPasteSnippet( phutil_safe_html($snippet_data['content']), $snippet_data['type'], $snippet_data['contentLineCount']); $paste->attachSnippet($snippet); $have_cache[$paste->getPHID()] = true; } else { $need_raw[$key] = $paste; } } if (!$need_raw) { return $pastes; } $write_data = array(); $have_raw = $this->loadRawContent($need_raw); $have_raw = mpull($have_raw, null, 'getPHID'); foreach ($pastes as $key => $paste) { $paste_phid = $paste->getPHID(); if (isset($have_cache[$paste_phid])) { continue; } if (empty($have_raw[$paste_phid])) { unset($pastes[$key]); continue; } $snippet = $this->buildSnippet($paste); $paste->attachSnippet($snippet); $snippet_data = array( 'content' => (string)$snippet->getContent(), 'type' => (string)$snippet->getType(), 'contentLineCount' => $snippet->getContentLineCount(), ); $write_data[$this->getSnippetCacheKey($paste)] = phutil_json_encode( $snippet_data); } if ($write_data) { $cache->setKeys($write_data); } return $pastes; } private function buildContent(PhabricatorPaste $paste) { return $this->highlightSource( $paste->getRawContent(), $paste->getTitle(), $paste->getLanguage()); } private function buildSnippet(PhabricatorPaste $paste) { $snippet_type = PhabricatorPasteSnippet::FULL; $snippet = $paste->getRawContent(); $lines = phutil_split_lines($snippet); $line_count = count($lines); if (strlen($snippet) > 1024) { $snippet_type = PhabricatorPasteSnippet::FIRST_BYTES; $snippet = id(new PhutilUTF8StringTruncator()) ->setMaximumBytes(1024) ->setTerminator('') ->truncateString($snippet); } if ($line_count > 5) { $snippet_type = PhabricatorPasteSnippet::FIRST_LINES; $snippet = implode('', array_slice($lines, 0, 5)); } return new PhabricatorPasteSnippet( $this->highlightSource( $snippet, $paste->getTitle(), $paste->getLanguage()), $snippet_type, $line_count); } private function highlightSource($source, $title, $language) { if (empty($language)) { return PhabricatorSyntaxHighlighter::highlightWithFilename( $title, $source); } else { return PhabricatorSyntaxHighlighter::highlightWithLanguage( $language, $source); } } public function getQueryApplicationClass() { return 'PhabricatorPasteApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/query/PhabricatorPasteSearchEngine.php
src/applications/paste/query/PhabricatorPasteSearchEngine.php
<?php final class PhabricatorPasteSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Pastes'); } public function getApplicationClassName() { return 'PhabricatorPasteApplication'; } public function newQuery() { return id(new PhabricatorPasteQuery()) ->needSnippets(true); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['authorPHIDs']) { $query->withAuthorPHIDs($map['authorPHIDs']); } if ($map['languages']) { $query->withLanguages($map['languages']); } if ($map['createdStart']) { $query->withDateCreatedAfter($map['createdStart']); } if ($map['createdEnd']) { $query->withDateCreatedBefore($map['createdEnd']); } if ($map['statuses']) { $query->withStatuses($map['statuses']); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorUsersSearchField()) ->setAliases(array('authors')) ->setKey('authorPHIDs') ->setConduitKey('authors') ->setLabel(pht('Authors')) ->setDescription( pht('Search for pastes with specific authors.')), id(new PhabricatorSearchStringListField()) ->setKey('languages') ->setLabel(pht('Languages')) ->setDescription( pht('Search for pastes highlighted in specific languages.')), id(new PhabricatorSearchDateField()) ->setKey('createdStart') ->setLabel(pht('Created After')) ->setDescription( pht('Search for pastes created after a given time.')), id(new PhabricatorSearchDateField()) ->setKey('createdEnd') ->setLabel(pht('Created Before')) ->setDescription( pht('Search for pastes created before a given time.')), id(new PhabricatorSearchCheckboxesField()) ->setKey('statuses') ->setLabel(pht('Status')) ->setDescription( pht('Search for archived or active pastes.')) ->setOptions( id(new PhabricatorPaste()) ->getStatusNameMap()), ); } protected function getDefaultFieldOrder() { return array( '...', 'createdStart', 'createdEnd', ); } protected function getURI($path) { return '/paste/'.$path; } protected function getBuiltinQueryNames() { $names = array( 'active' => pht('Active Pastes'), 'all' => pht('All Pastes'), ); 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 'active': return $query->setParameter( 'statuses', array( PhabricatorPaste::STATUS_ACTIVE, )); case 'all': return $query; case 'authored': return $query->setParameter( 'authorPHIDs', array($this->requireViewer()->getPHID())); } return parent::buildSavedQueryFromBuiltin($query_key); } protected function getRequiredHandlePHIDsForResultList( array $pastes, PhabricatorSavedQuery $query) { return mpull($pastes, 'getAuthorPHID'); } protected function renderResultList( array $pastes, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($pastes, 'PhabricatorPaste'); $viewer = $this->requireViewer(); $lang_map = PhabricatorEnv::getEnvConfig('pygments.dropdown-choices'); $list = new PHUIObjectItemListView(); $list->setUser($viewer); foreach ($pastes as $paste) { $created = phabricator_date($paste->getDateCreated(), $viewer); $author = $handles[$paste->getAuthorPHID()]->renderLink(); $snippet_type = $paste->getSnippet()->getType(); $lines = phutil_split_lines($paste->getSnippet()->getContent()); $preview = id(new PhabricatorSourceCodeView()) ->setLines($lines) ->setTruncatedFirstBytes( $snippet_type == PhabricatorPasteSnippet::FIRST_BYTES) ->setTruncatedFirstLines( $snippet_type == PhabricatorPasteSnippet::FIRST_LINES) ->setURI(new PhutilURI($paste->getURI())); $source_code = phutil_tag( 'div', array( 'class' => 'phabricator-source-code-summary', ), $preview); $created = phabricator_datetime($paste->getDateCreated(), $viewer); $line_count = $paste->getSnippet()->getContentLineCount(); $line_count = pht( '%s Line(s)', new PhutilNumber($line_count)); $title = nonempty($paste->getTitle(), pht('(An Untitled Masterwork)')); $item = id(new PHUIObjectItemView()) ->setObjectName('P'.$paste->getID()) ->setHeader($title) ->setHref('/P'.$paste->getID()) ->setObject($paste) ->addByline(pht('Author: %s', $author)) ->addIcon('none', $created) ->addIcon('none', $line_count) ->appendChild($source_code); if ($paste->isArchived()) { $item->setDisabled(true); } $lang_name = $paste->getLanguage(); if ($lang_name) { $lang_name = idx($lang_map, $lang_name, $lang_name); $item->addIcon('none', $lang_name); } $list->addItem($item); } $result = new PhabricatorApplicationSearchResultView(); $result->setObjectList($list); $result->setNoDataString(pht('No pastes found.')); return $result; } protected function getNewUserBody() { $viewer = $this->requireViewer(); $create_button = id(new PhabricatorPasteEditEngine()) ->setViewer($viewer) ->newNUXButton(pht('Create a Paste')); $icon = $this->getApplication()->getIcon(); $app_name = $this->getApplication()->getName(); $view = id(new PHUIBigInfoView()) ->setIcon($icon) ->setTitle(pht('Welcome to %s', $app_name)) ->setDescription( pht('Store, share, and embed snippets of code.')) ->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/paste/query/PhabricatorPasteTransactionQuery.php
src/applications/paste/query/PhabricatorPasteTransactionQuery.php
<?php final class PhabricatorPasteTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhabricatorPasteTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/mail/PasteReplyHandler.php
src/applications/paste/mail/PasteReplyHandler.php
<?php final class PasteReplyHandler extends PhabricatorApplicationTransactionReplyHandler { public function validateMailReceiver($mail_receiver) { if (!($mail_receiver instanceof PhabricatorPaste)) { throw new Exception( pht('Mail receiver is not a %s.', 'PhabricatorPaste')); } } public function getObjectPrefix() { return 'P'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/mail/PasteCreateMailReceiver.php
src/applications/paste/mail/PasteCreateMailReceiver.php
<?php final class PasteCreateMailReceiver extends PhabricatorApplicationMailReceiver { protected function newApplication() { return new PhabricatorPasteApplication(); } protected function processReceivedMail( PhabricatorMetaMTAReceivedMail $mail, PhutilEmailAddress $target) { $author = $this->getAuthor(); $title = $mail->getSubject(); if (!$title) { $title = pht('Email Paste'); } $xactions = array(); $xactions[] = id(new PhabricatorPasteTransaction()) ->setTransactionType(PhabricatorPasteContentTransaction::TRANSACTIONTYPE) ->setNewValue($mail->getCleanTextBody()); $xactions[] = id(new PhabricatorPasteTransaction()) ->setTransactionType(PhabricatorPasteTitleTransaction::TRANSACTIONTYPE) ->setNewValue($title); $paste = PhabricatorPaste::initializeNewPaste($author); $content_source = $mail->newContentSource(); $editor = id(new PhabricatorPasteEditor()) ->setActor($author) ->setContentSource($content_source) ->setContinueOnNoEffect(true); $xactions = $editor->applyTransactions($paste, $xactions); $mail->setRelatedPHID($paste->getPHID()); $sender = $this->getSender(); if (!$sender) { return; } $subject_prefix = pht('[Paste]'); $subject = pht('You successfully created a paste.'); $paste_uri = PhabricatorEnv::getProductionURI($paste->getURI()); $body = new PhabricatorMetaMTAMailBody(); $body->addRawSection($subject); $body->addTextSection(pht('PASTE LINK'), $paste_uri); id(new PhabricatorMetaMTAMail()) ->addTos(array($sender->getPHID())) ->setSubject($subject) ->setSubjectPrefix($subject_prefix) ->setFrom($sender->getPHID()) ->setRelatedPHID($paste->getPHID()) ->setBody($body->render()) ->saveAndSend(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/mail/PasteMailReceiver.php
src/applications/paste/mail/PasteMailReceiver.php
<?php final class PasteMailReceiver extends PhabricatorObjectMailReceiver { public function isEnabled() { $app_class = 'PhabricatorPasteApplication'; return PhabricatorApplication::isClassInstalled($app_class); } protected function getObjectPattern() { return 'P[1-9]\d*'; } protected function loadObject($pattern, PhabricatorUser $viewer) { $id = (int)substr($pattern, 1); return id(new PhabricatorPasteQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->executeOne(); } protected function getTransactionReplyHandler() { return new PasteReplyHandler(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/editor/PhabricatorPasteEditor.php
src/applications/paste/editor/PhabricatorPasteEditor.php
<?php final class PhabricatorPasteEditor extends PhabricatorApplicationTransactionEditor { private $newPasteTitle; public function getNewPasteTitle() { return $this->newPasteTitle; } public function getEditorApplicationClass() { return 'PhabricatorPasteApplication'; } public function getEditorObjectsDescription() { return pht('Pastes'); } public function getCreateObjectTitle($author, $object) { return pht('%s created this paste.', $author); } public function getCreateObjectTitleForFeed($author, $object) { return pht('%s created %s.', $author, $object); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY; $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY; $types[] = PhabricatorTransactions::TYPE_COMMENT; return $types; } protected function expandTransactions( PhabricatorLiskDAO $object, array $xactions) { $new_title = $object->getTitle(); foreach ($xactions as $xaction) { $type = $xaction->getTransactionType(); if ($type === PhabricatorPasteTitleTransaction::TRANSACTIONTYPE) { $new_title = $xaction->getNewValue(); } } $this->newPasteTitle = $new_title; return parent::expandTransactions($object, $xactions); } protected function shouldSendMail( PhabricatorLiskDAO $object, array $xactions) { if ($this->getIsNewObject()) { return false; } return true; } protected function getMailSubjectPrefix() { return pht('[Paste]'); } protected function getMailTo(PhabricatorLiskDAO $object) { return array( $object->getAuthorPHID(), $this->getActingAsPHID(), ); } public function getMailTagsMap() { return array( PhabricatorPasteTransaction::MAILTAG_CONTENT => pht('Paste title, language or text changes.'), PhabricatorPasteTransaction::MAILTAG_COMMENT => pht('Someone comments on a paste.'), PhabricatorPasteTransaction::MAILTAG_OTHER => pht('Other paste activity not listed above occurs.'), ); } protected function buildReplyHandler(PhabricatorLiskDAO $object) { return id(new PasteReplyHandler()) ->setMailReceiver($object); } protected function buildMailTemplate(PhabricatorLiskDAO $object) { $id = $object->getID(); $name = $object->getTitle(); return id(new PhabricatorMetaMTAMail()) ->setSubject("P{$id}: {$name}"); } protected function buildMailBody( PhabricatorLiskDAO $object, array $xactions) { $body = parent::buildMailBody($object, $xactions); $body->addLinkSection( pht('PASTE DETAIL'), PhabricatorEnv::getProductionURI('/P'.$object->getID())); return $body; } protected function shouldPublishFeedStory( PhabricatorLiskDAO $object, array $xactions) { return true; } protected function supportsSearch() { 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/paste/editor/PhabricatorPasteEditEngine.php
src/applications/paste/editor/PhabricatorPasteEditEngine.php
<?php final class PhabricatorPasteEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'paste.paste'; public function getEngineName() { return pht('Pastes'); } public function getSummaryHeader() { return pht('Configure Paste Forms'); } public function getSummaryText() { return pht('Configure creation and editing forms in Paste.'); } public function getEngineApplicationClass() { return 'PhabricatorPasteApplication'; } protected function newEditableObject() { return PhabricatorPaste::initializeNewPaste($this->getViewer()); } protected function newObjectQuery() { return id(new PhabricatorPasteQuery()) ->needRawContent(true); } protected function getObjectCreateTitleText($object) { return pht('Create New Paste'); } protected function getObjectEditTitleText($object) { return pht('Edit Paste: %s', $object->getTitle()); } protected function getObjectEditShortText($object) { return $object->getMonogram(); } protected function getObjectCreateShortText() { return pht('Create Paste'); } protected function getObjectName() { return pht('Paste'); } protected function getCommentViewHeaderText($object) { return pht('Eat Paste'); } protected function getCommentViewButtonText($object) { return pht('Nom Nom Nom Nom Nom'); } protected function getObjectViewURI($object) { return '/P'.$object->getID(); } protected function buildCustomEditFields($object) { return array( id(new PhabricatorTextEditField()) ->setKey('title') ->setLabel(pht('Title')) ->setTransactionType(PhabricatorPasteTitleTransaction::TRANSACTIONTYPE) ->setDescription(pht('The title of the paste.')) ->setConduitDescription(pht('Retitle the paste.')) ->setConduitTypeDescription(pht('New paste title.')) ->setValue($object->getTitle()), id(new PhabricatorDatasourceEditField()) ->setKey('language') ->setLabel(pht('Language')) ->setTransactionType( PhabricatorPasteLanguageTransaction::TRANSACTIONTYPE) ->setAliases(array('lang')) ->setIsCopyable(true) ->setDatasource(new PasteLanguageSelectDatasource()) ->setDescription( pht( 'Language used for syntax highlighting. By default, inferred '. 'from the title.')) ->setConduitDescription( pht('Change language used for syntax highlighting.')) ->setConduitTypeDescription(pht('New highlighting language.')) ->setSingleValue($object->getLanguage()), id(new PhabricatorTextAreaEditField()) ->setKey('text') ->setLabel(pht('Text')) ->setTransactionType( PhabricatorPasteContentTransaction::TRANSACTIONTYPE) ->setMonospaced(true) ->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_TALL) ->setDescription(pht('The main body text of the paste.')) ->setConduitDescription(pht('Change the paste content.')) ->setConduitTypeDescription(pht('New body content.')) ->setValue($object->getRawContent()), id(new PhabricatorSelectEditField()) ->setKey('status') ->setLabel(pht('Status')) ->setTransactionType( PhabricatorPasteStatusTransaction::TRANSACTIONTYPE) ->setIsFormField(false) ->setOptions(PhabricatorPaste::getStatusNameMap()) ->setDescription(pht('Active or archived status.')) ->setConduitDescription(pht('Active or archive the paste.')) ->setConduitTypeDescription(pht('New paste status constant.')) ->setValue($object->getStatus()), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/xaction/PhabricatorPasteTitleTransaction.php
src/applications/paste/xaction/PhabricatorPasteTitleTransaction.php
<?php final class PhabricatorPasteTitleTransaction extends PhabricatorPasteTransactionType { const TRANSACTIONTYPE = 'paste.title'; public function generateOldValue($object) { return $object->getTitle(); } public function applyInternalEffects($object, $value) { $object->setTitle($value); } public function getTitle() { $old = $this->getOldValue(); $new = $this->getNewValue(); if (strlen($old) && strlen($new)) { return pht( '%s changed the title of this paste from %s to %s.', $this->renderAuthor(), $this->renderOldValue(), $this->renderNewValue()); } else if (strlen($new)) { return pht( '%s changed the title of this paste from untitled to %s.', $this->renderAuthor(), $this->renderNewValue()); } else { return pht( '%s changed the title of this paste from %s to untitled.', $this->renderAuthor(), $this->renderOldValue()); } } public function getTitleForFeed() { $old = $this->getOldValue(); $new = $this->getNewValue(); if (strlen($old) && strlen($new)) { return pht( '%s updated the title for %s from %s to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderOldValue(), $this->renderNewValue()); } else if (strlen($new)) { return pht( '%s updated the title for %s from untitled to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderNewValue()); } else { return pht( '%s updated the title for %s from %s to untitled.', $this->renderAuthor(), $this->renderObject(), $this->renderOldValue()); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/xaction/PhabricatorPasteContentTransaction.php
src/applications/paste/xaction/PhabricatorPasteContentTransaction.php
<?php final class PhabricatorPasteContentTransaction extends PhabricatorPasteTransactionType { const TRANSACTIONTYPE = 'paste.create'; private $filePHID; public function generateOldValue($object) { return $object->getFilePHID(); } public function applyInternalEffects($object, $value) { $object->setFilePHID($value); } public function extractFilePHIDs($object, $value) { $file_phid = $this->getFilePHID($object, $value); return array($file_phid); } public function validateTransactions($object, array $xactions) { if ($object->getFilePHID() || $xactions) { return array(); } $error = $this->newError( pht('Required'), pht('You must provide content to create a paste.')); $error->setIsMissingFieldError(true); return array($error); } public function generateNewValue($object, $value) { return $this->getFilePHID($object, $value); } private function getFilePHID($object, $value) { if ($this->filePHID === null) { $this->filePHID = $this->newFilePHID($object, $value); } return $this->filePHID; } private function newFilePHID($object, $value) { // If this transaction does not really change the paste content, return // the current file PHID so this transaction no-ops. $old_content = $object->getRawContent(); if ($value === $old_content) { $file_phid = $object->getFilePHID(); if ($file_phid) { return $file_phid; } } $editor = $this->getEditor(); $actor = $editor->getActor(); $file = $this->newFileForPaste($actor, $value); return $file->getPHID(); } private function newFileForPaste(PhabricatorUser $actor, $data) { $editor = $this->getEditor(); $file_name = $editor->getNewPasteTitle(); if (!strlen($file_name)) { $file_name = 'raw-paste-data.txt'; } return PhabricatorFile::newFromFileData( $data, array( 'name' => $file_name, 'mime-type' => 'text/plain; charset=utf-8', 'authorPHID' => $actor->getPHID(), 'viewPolicy' => PhabricatorPolicies::POLICY_NOONE, )); } public function getIcon() { return 'fa-plus'; } public function getTitle() { return pht( '%s edited the content of this paste.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s edited %s.', $this->renderAuthor(), $this->renderObject()); } public function hasChangeDetailView() { return true; } public function getMailDiffSectionHeader() { return pht('CHANGES TO PASTE CONTENT'); } public function newChangeDetailView() { $viewer = $this->getViewer(); $old = $this->getOldValue(); $new = $this->getNewValue(); $files = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withPHIDs(array($old, $new)) ->execute(); $files = mpull($files, null, 'getPHID'); $old_text = ''; if (idx($files, $old)) { $old_text = $files[$old]->loadFileData(); } $new_text = ''; if (idx($files, $new)) { $new_text = $files[$new]->loadFileData(); } return id(new PhabricatorApplicationTransactionTextDiffDetailView()) ->setViewer($viewer) ->setOldText($old_text) ->setNewText($new_text); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/xaction/PhabricatorPasteLanguageTransaction.php
src/applications/paste/xaction/PhabricatorPasteLanguageTransaction.php
<?php final class PhabricatorPasteLanguageTransaction extends PhabricatorPasteTransactionType { const TRANSACTIONTYPE = 'paste.language'; public function generateOldValue($object) { return $object->getLanguage(); } public function applyInternalEffects($object, $value) { $object->setLanguage($value); } private function renderLanguageValue($value) { if (!strlen($value)) { return $this->renderValue(pht('autodetect')); } else { return $this->renderValue($value); } } public function getTitle() { return pht( "%s updated the paste's language from %s to %s.", $this->renderAuthor(), $this->renderLanguageValue($this->getOldValue()), $this->renderLanguageValue($this->getNewValue())); } public function getTitleForFeed() { return pht( '%s updated the language for %s from %s to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderLanguageValue($this->getOldValue()), $this->renderLanguageValue($this->getNewValue())); } public function validateTransactions($object, array $xactions) { $errors = array(); foreach ($xactions as $xaction) { $new = $xaction->getNewValue(); if ($new !== null && !strlen($new)) { $errors[] = $this->newInvalidError( pht('Paste language must be null or a nonempty string.'), $xaction); } } 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/paste/xaction/PhabricatorPasteStatusTransaction.php
src/applications/paste/xaction/PhabricatorPasteStatusTransaction.php
<?php final class PhabricatorPasteStatusTransaction extends PhabricatorPasteTransactionType { const TRANSACTIONTYPE = 'paste.status'; public function generateOldValue($object) { return $object->getStatus(); } public function applyInternalEffects($object, $value) { $object->setStatus($value); } private function isActivate() { return ($this->getNewValue() == PhabricatorPaste::STATUS_ACTIVE); } public function getIcon() { if ($this->isActivate()) { return 'fa-check'; } else { return 'fa-ban'; } } public function getColor() { if ($this->isActivate()) { return 'green'; } else { return 'indigo'; } } public function getTitle() { if ($this->isActivate()) { return pht( '%s activated this paste.', $this->renderAuthor()); } else { return pht( '%s archived this paste.', $this->renderAuthor()); } } public function getTitleForFeed() { if ($this->isActivate()) { return pht( '%s activated %s.', $this->renderAuthor(), $this->renderObject()); } else { return pht( '%s archived %s.', $this->renderAuthor(), $this->renderObject()); } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/xaction/PhabricatorPasteTransactionType.php
src/applications/paste/xaction/PhabricatorPasteTransactionType.php
<?php abstract class PhabricatorPasteTransactionType 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/paste/application/PhabricatorPasteApplication.php
src/applications/paste/application/PhabricatorPasteApplication.php
<?php final class PhabricatorPasteApplication extends PhabricatorApplication { public function getName() { return pht('Paste'); } public function getBaseURI() { return '/paste/'; } public function getIcon() { return 'fa-paste'; } public function getTitleGlyph() { return "\xE2\x9C\x8E"; } public function getApplicationGroup() { return self::GROUP_UTILITIES; } public function getShortDescription() { return pht('Share Text Snippets'); } public function getRemarkupRules() { return array( new PhabricatorPasteRemarkupRule(), ); } public function getRoutes() { return array( '/P(?P<id>[1-9]\d*)(?:\$(?P<lines>\d+(?:-\d+)?))?' => 'PhabricatorPasteViewController', '/paste/' => array( '(query/(?P<queryKey>[^/]+)/)?' => 'PhabricatorPasteListController', $this->getEditRoutePattern('edit/') => 'PhabricatorPasteEditController', 'raw/(?P<id>[1-9]\d*)/' => 'PhabricatorPasteRawController', 'archive/(?P<id>[1-9]\d*)/' => 'PhabricatorPasteArchiveController', ), ); } public function supportsEmailIntegration() { return true; } public function getAppEmailBlurb() { return pht( 'Send email to these addresses to create pastes. %s', phutil_tag( 'a', array( 'href' => $this->getInboundEmailSupportLink(), ), pht('Learn More'))); } protected function getCustomCapabilities() { return array( PasteDefaultViewCapability::CAPABILITY => array( 'caption' => pht('Default view policy for newly created pastes.'), 'template' => PhabricatorPastePastePHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_VIEW, ), PasteDefaultEditCapability::CAPABILITY => array( 'caption' => pht('Default edit policy for newly created pastes.'), 'template' => PhabricatorPastePastePHIDType::TYPECONST, 'capability' => PhabricatorPolicyCapability::CAN_EDIT, ), ); } public function getMailCommandObjects() { return array( 'paste' => array( 'name' => pht('Email Commands: Pastes'), 'header' => pht('Interacting with Pastes'), 'object' => new PhabricatorPaste(), 'summary' => pht( 'This page documents the commands you can use to interact with '. 'pastes.'), ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/lipsum/PhabricatorPasteFilenameContextFreeGrammar.php
src/applications/paste/lipsum/PhabricatorPasteFilenameContextFreeGrammar.php
<?php final class PhabricatorPasteFilenameContextFreeGrammar extends PhutilContextFreeGrammar { protected function getRules() { return array( 'start' => array( '[scripty]', ), 'scripty' => array( '[thing]', '[thing]', '[thing]_[tail]', '[action]_[thing]', '[action]_[thing]', '[action]_[thing]_[tail]', '[scripty]_and_[scripty]', ), 'tail' => array( 'script', 'helper', 'backup', 'pro', '[tail]_[tail]', ), 'thing' => array( '[thingnoun]', '[thingadjective]_[thingnoun]', '[thingadjective]_[thingadjective]_[thingnoun]', ), 'thingnoun' => array( 'backup', 'backups', 'database', 'databases', 'table', 'tables', 'memory', 'disk', 'disks', 'user', 'users', 'account', 'accounts', 'shard', 'shards', 'node', 'nodes', 'host', 'hosts', 'account', 'accounts', ), 'thingadjective' => array( 'backup', 'database', 'memory', 'disk', 'user', 'account', 'forgotten', 'lost', 'elder', 'ancient', 'legendary', ), 'action' => array( 'manage', 'update', 'compact', 'quick', 'probe', 'sync', 'undo', 'administrate', 'assess', 'purge', 'cancel', 'entomb', 'accelerate', 'plan', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/lipsum/PhabricatorPasteTestDataGenerator.php
src/applications/paste/lipsum/PhabricatorPasteTestDataGenerator.php
<?php final class PhabricatorPasteTestDataGenerator extends PhabricatorTestDataGenerator { const GENERATORKEY = 'pastes'; public function getGeneratorName() { return pht('Pastes'); } public function generateObject() { $author = $this->loadRandomUser(); list($name, $language, $content) = $this->newPasteContent(); $paste = PhabricatorPaste::initializeNewPaste($author); $xactions = array(); $xactions[] = $this->newTransaction( PhabricatorPasteTitleTransaction::TRANSACTIONTYPE, $name); if (strlen($language) > 0) { $xactions[] = $this->newTransaction( PhabricatorPasteLanguageTransaction::TRANSACTIONTYPE, $language); } $xactions[] = $this->newTransaction( PhabricatorPasteContentTransaction::TRANSACTIONTYPE, $content); $editor = id(new PhabricatorPasteEditor()) ->setActor($author) ->setContentSource($this->getLipsumContentSource()) ->setContinueOnNoEffect(true) ->applyTransactions($paste, $xactions); return $paste; } protected function newEmptyTransaction() { return new PhabricatorPasteTransaction(); } public function getSupportedLanguages() { return array( 'php' => array( 'content' => 'PhutilPHPCodeSnippetContextFreeGrammar', ), 'java' => array( 'content' => 'PhutilJavaCodeSnippetContextFreeGrammar', ), ); } public function generateContent($spec) { $content_generator = idx($spec, 'content'); if (!$content_generator) { $content_generator = 'PhutilLipsumContextFreeGrammar'; } return newv($content_generator, array()) ->generateSeveral($this->roll(4, 12, 10)); } private function newPasteContent() { $languages = $this->getSupportedLanguages(); $language = array_rand($languages); $spec = $languages[$language]; $title_generator = idx($spec, 'title'); if (!$title_generator) { $title_generator = 'PhabricatorPasteFilenameContextFreeGrammar'; } $title = newv($title_generator, array()) ->generate(); $content = $this->generateContent($spec); // Usually add the language as a suffix. if ($this->roll(1, 20) > 2) { $title = $title.'.'.$language; } switch ($this->roll(1, 20)) { case 1: // On critical miss, set a different, random language. $highlight_as = array_rand($languages); break; case 18: case 19: case 20: // Sometimes set it to the correct language. $highlight_as = $language; break; default: // Usually leave it as autodetect. $highlight_as = ''; break; } return array($title, $highlight_as, $content); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/view/PasteEmbedView.php
src/applications/paste/view/PasteEmbedView.php
<?php final class PasteEmbedView extends AphrontView { private $paste; private $handle; private $highlights = array(); private $lines = 24; public function setPaste(PhabricatorPaste $paste) { $this->paste = $paste; return $this; } public function setHandle(PhabricatorObjectHandle $handle) { $this->handle = $handle; return $this; } public function setHighlights(array $highlights) { $this->highlights = $highlights; return $this; } public function setLines($lines) { $this->lines = $lines; return $this; } public function render() { if (!$this->paste) { throw new PhutilInvalidStateException('setPaste'); } $lines = phutil_split_lines($this->paste->getContent()); require_celerity_resource('paste-css'); $link = phutil_tag( 'a', array( 'href' => '/P'.$this->paste->getID(), ), $this->handle->getFullName()); $head = phutil_tag( 'div', array( 'class' => 'paste-embed-head', ), $link); $body_attributes = array('class' => 'paste-embed-body'); if ($this->lines != null) { $body_attributes['style'] = 'max-height: '.$this->lines * (1.15).'em;'; } $body = phutil_tag( 'div', $body_attributes, id(new PhabricatorSourceCodeView()) ->setLines($lines) ->setHighlights($this->highlights) ->disableHighlightOnClick()); return phutil_tag( 'div', array('class' => 'paste-embed'), array($head, $body)); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/phid/PhabricatorPastePastePHIDType.php
src/applications/paste/phid/PhabricatorPastePastePHIDType.php
<?php final class PhabricatorPastePastePHIDType extends PhabricatorPHIDType { const TYPECONST = 'PSTE'; public function getTypeName() { return pht('Paste'); } public function newObject() { return new PhabricatorPaste(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorPasteApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhabricatorPasteQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $paste = $objects[$phid]; $id = $paste->getID(); $name = $paste->getFullName(); $handle->setName("P{$id}"); $handle->setFullName($name); $handle->setURI("/P{$id}"); } } public function canLoadNamedObject($name) { return preg_match('/^P\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 PhabricatorPasteQuery()) ->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/paste/snippet/PhabricatorPasteSnippet.php
src/applications/paste/snippet/PhabricatorPasteSnippet.php
<?php final class PhabricatorPasteSnippet extends Phobject { const FULL = 'full'; const FIRST_LINES = 'first_lines'; const FIRST_BYTES = 'first_bytes'; private $content; private $type; private $contentLineCount; public function __construct($content, $type, $content_line_count) { $this->content = $content; $this->type = $type; $this->contentLineCount = $content_line_count; } public function getContent() { return $this->content; } public function getType() { return $this->type; } public function getContentLineCount() { return $this->contentLineCount; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/conduit/PasteSearchConduitAPIMethod.php
src/applications/paste/conduit/PasteSearchConduitAPIMethod.php
<?php final class PasteSearchConduitAPIMethod extends PhabricatorSearchEngineAPIMethod { public function getAPIMethodName() { return 'paste.search'; } public function newSearchEngine() { return new PhabricatorPasteSearchEngine(); } public function getMethodSummary() { return pht('Read information about pastes.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/conduit/PasteInfoConduitAPIMethod.php
src/applications/paste/conduit/PasteInfoConduitAPIMethod.php
<?php final class PasteInfoConduitAPIMethod extends PasteConduitAPIMethod { public function getAPIMethodName() { return 'paste.info'; } public function getMethodStatus() { return self::METHOD_STATUS_DEPRECATED; } public function getMethodStatusDescription() { return pht("Replaced by '%s'.", 'paste.query'); } public function getMethodDescription() { return pht('Retrieve an array of information about a paste.'); } protected function defineParamTypes() { return array( 'paste_id' => 'required id', ); } protected function defineReturnType() { return 'nonempty dict'; } protected function defineErrorTypes() { return array( 'ERR_BAD_PASTE' => pht('No such paste exists.'), ); } protected function execute(ConduitAPIRequest $request) { $paste_id = $request->getValue('paste_id'); $paste = id(new PhabricatorPasteQuery()) ->setViewer($request->getUser()) ->withIDs(array($paste_id)) ->needRawContent(true) ->executeOne(); if (!$paste) { throw new ConduitException('ERR_BAD_PASTE'); } return $this->buildPasteInfoDictionary($paste); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/conduit/PasteQueryConduitAPIMethod.php
src/applications/paste/conduit/PasteQueryConduitAPIMethod.php
<?php final class PasteQueryConduitAPIMethod extends PasteConduitAPIMethod { public function getAPIMethodName() { return 'paste.query'; } public function getMethodDescription() { return pht('Query Pastes.'); } public function getMethodStatus() { return self::METHOD_STATUS_FROZEN; } public function getMethodStatusDescription() { return pht( 'This method is frozen and will eventually be deprecated. New code '. 'should use "paste.search" instead.'); } protected function defineParamTypes() { return array( 'ids' => 'optional list<int>', 'phids' => 'optional list<phid>', 'authorPHIDs' => 'optional list<phid>', 'after' => 'optional int', 'limit' => 'optional int, default = 100', ); } protected function defineReturnType() { return 'list<dict>'; } protected function execute(ConduitAPIRequest $request) { $query = id(new PhabricatorPasteQuery()) ->setViewer($request->getUser()) ->needRawContent(true); if ($request->getValue('ids')) { $query->withIDs($request->getValue('ids')); } if ($request->getValue('phids')) { $query->withPHIDs($request->getValue('phids')); } if ($request->getValue('authorPHIDs')) { $query->withAuthorPHIDs($request->getValue('authorPHIDs')); } if ($request->getValue('after')) { $query->setAfterID($request->getValue('after')); } $limit = $request->getValue('limit', 100); if ($limit) { $query->setLimit($limit); } $pastes = $query->execute(); $results = array(); foreach ($pastes as $paste) { $results[$paste->getPHID()] = $this->buildPasteInfoDictionary($paste); } 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/paste/conduit/PasteConduitAPIMethod.php
src/applications/paste/conduit/PasteConduitAPIMethod.php
<?php abstract class PasteConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass('PhabricatorPasteApplication'); } protected function buildPasteInfoDictionary(PhabricatorPaste $paste) { return array( 'id' => $paste->getID(), 'objectName' => 'P'.$paste->getID(), 'phid' => $paste->getPHID(), 'authorPHID' => $paste->getAuthorPHID(), 'filePHID' => $paste->getFilePHID(), 'title' => $paste->getTitle(), 'dateCreated' => $paste->getDateCreated(), 'language' => $paste->getLanguage(), 'uri' => PhabricatorEnv::getProductionURI('/P'.$paste->getID()), 'parentPHID' => $paste->getParentPHID(), 'content' => $paste->getRawContent(), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/conduit/PasteEditConduitAPIMethod.php
src/applications/paste/conduit/PasteEditConduitAPIMethod.php
<?php final class PasteEditConduitAPIMethod extends PhabricatorEditEngineAPIMethod { public function getAPIMethodName() { return 'paste.edit'; } public function newEditEngine() { return new PhabricatorPasteEditEngine(); } public function getMethodSummary() { return pht( 'Apply transactions to create a new paste or edit an existing one.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/conduit/PasteCreateConduitAPIMethod.php
src/applications/paste/conduit/PasteCreateConduitAPIMethod.php
<?php final class PasteCreateConduitAPIMethod extends PasteConduitAPIMethod { public function getAPIMethodName() { return 'paste.create'; } public function getMethodDescription() { return pht('Create a new paste.'); } public function getMethodStatus() { return self::METHOD_STATUS_FROZEN; } public function getMethodStatusDescription() { return pht( 'This method is frozen and will eventually be deprecated. New code '. 'should use "paste.edit" instead.'); } protected function defineParamTypes() { return array( 'content' => 'required string', 'title' => 'optional string', 'language' => 'optional string', ); } protected function defineReturnType() { return 'nonempty dict'; } protected function defineErrorTypes() { return array( 'ERR-NO-PASTE' => pht('Paste may not be empty.'), ); } protected function execute(ConduitAPIRequest $request) { $content = $request->getValue('content'); $title = $request->getValue('title'); $language = $request->getValue('language'); if ($content === null || !strlen($content)) { throw new ConduitException('ERR-NO-PASTE'); } $title = nonempty($title, pht('Masterwork From Distant Lands')); $language = nonempty($language, ''); $viewer = $request->getUser(); $paste = PhabricatorPaste::initializeNewPaste($viewer); $xactions = array(); $xactions[] = id(new PhabricatorPasteTransaction()) ->setTransactionType(PhabricatorPasteContentTransaction::TRANSACTIONTYPE) ->setNewValue($content); $xactions[] = id(new PhabricatorPasteTransaction()) ->setTransactionType(PhabricatorPasteTitleTransaction::TRANSACTIONTYPE) ->setNewValue($title); if (strlen($language)) { $xactions[] = id(new PhabricatorPasteTransaction()) ->setTransactionType( PhabricatorPasteLanguageTransaction::TRANSACTIONTYPE) ->setNewValue($language); } $editor = id(new PhabricatorPasteEditor()) ->setActor($viewer) ->setContinueOnNoEffect(true) ->setContentSource($request->newContentSource()); $xactions = $editor->applyTransactions($paste, $xactions); $paste->attachRawContent($content); return $this->buildPasteInfoDictionary($paste); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/engine/PhabricatorPasteFulltextEngine.php
src/applications/paste/engine/PhabricatorPasteFulltextEngine.php
<?php final class PhabricatorPasteFulltextEngine extends PhabricatorFulltextEngine { protected function buildAbstractDocument( PhabricatorSearchAbstractDocument $document, $object) { $paste = id(new PhabricatorPasteQuery()) ->setViewer($this->getViewer()) ->withPHIDs(array($object->getPHID())) ->needContent(true) ->executeOne(); $document->setDocumentTitle($paste->getTitle()); $document->addRelationship( $paste->isArchived() ? PhabricatorSearchRelationship::RELATIONSHIP_CLOSED : PhabricatorSearchRelationship::RELATIONSHIP_OPEN, $paste->getPHID(), PhabricatorPastePastePHIDType::TYPECONST, PhabricatorTime::getNow()); $document->addField( PhabricatorSearchDocumentFieldType::FIELD_BODY, $paste->getContent()); $document->addRelationship( PhabricatorSearchRelationship::RELATIONSHIP_AUTHOR, $paste->getAuthorPHID(), PhabricatorPeopleUserPHIDType::TYPECONST, $paste->getDateCreated()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/engine/PhabricatorPasteFerretEngine.php
src/applications/paste/engine/PhabricatorPasteFerretEngine.php
<?php final class PhabricatorPasteFerretEngine extends PhabricatorFerretEngine { public function getApplicationName() { return 'paste'; } public function getScopeName() { return 'paste'; } public function newSearchEngine() { return new PhabricatorPasteSearchEngine(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/paste/typeahead/PasteLanguageSelectDatasource.php
src/applications/paste/typeahead/PasteLanguageSelectDatasource.php
<?php final class PasteLanguageSelectDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Languages'); } public function getPlaceholderText() { return pht('Type a language name or leave blank to auto-detect...'); } public function getDatasourceApplicationClass() { return 'PhabricatorPasteApplication'; } public function loadResults() { $results = $this->buildResults(); return $this->filterResultsAgainstTokens($results); } protected function renderSpecialTokens(array $values) { return $this->renderTokensFromResults($this->buildResults(), $values); } private function buildResults() { $results = array(); $languages = PhabricatorEnv::getEnvConfig('pygments.dropdown-choices'); foreach ($languages as $value => $name) { $result = id(new PhabricatorTypeaheadResult()) ->setPHID($value) ->setName($name); $results[$value] = $result; } 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/paste/capability/PasteDefaultViewCapability.php
src/applications/paste/capability/PasteDefaultViewCapability.php
<?php final class PasteDefaultViewCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'paste.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/paste/capability/PasteDefaultEditCapability.php
src/applications/paste/capability/PasteDefaultEditCapability.php
<?php final class PasteDefaultEditCapability extends PhabricatorPolicyCapability { const CAPABILITY = 'paste.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/paste/remarkup/PhabricatorPasteRemarkupRule.php
src/applications/paste/remarkup/PhabricatorPasteRemarkupRule.php
<?php final class PhabricatorPasteRemarkupRule extends PhabricatorObjectRemarkupRule { protected function getObjectNamePrefix() { return 'P'; } protected function loadObjects(array $ids) { $viewer = $this->getEngine()->getConfig('viewer'); return id(new PhabricatorPasteQuery()) ->setViewer($viewer) ->withIDs($ids) ->needContent(true) ->execute(); } protected function renderObjectEmbed( $object, PhabricatorObjectHandle $handle, $options) { $embed_paste = id(new PasteEmbedView()) ->setPaste($object) ->setHandle($handle); if (strlen($options)) { $parser = new PhutilSimpleOptions(); $opts = $parser->parse(substr($options, 1)); foreach ($opts as $key => $value) { if ($key == 'lines') { $embed_paste->setLines(preg_replace('/[^0-9]/', '', $value)); } else if ($key == 'highlight') { $highlights = preg_split('/,|&/', preg_replace('/\s+/', '', $value)); $to_highlight = array(); foreach ($highlights as $highlight) { $highlight = explode('-', $highlight); if (!empty($highlight)) { sort($highlight); $to_highlight = array_merge( $to_highlight, range(head($highlight), last($highlight))); } } $embed_paste->setHighlights(array_unique($to_highlight)); } } } return $embed_paste; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/favorites/controller/PhabricatorFavoritesController.php
src/applications/favorites/controller/PhabricatorFavoritesController.php
<?php abstract class PhabricatorFavoritesController extends PhabricatorController {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/favorites/controller/PhabricatorFavoritesMenuItemController.php
src/applications/favorites/controller/PhabricatorFavoritesMenuItemController.php
<?php final class PhabricatorFavoritesMenuItemController extends PhabricatorFavoritesController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $application = 'PhabricatorFavoritesApplication'; $favorites = id(new PhabricatorApplicationQuery()) ->setViewer($viewer) ->withClasses(array($application)) ->withInstalled(true) ->executeOne(); $engine = id(new PhabricatorFavoritesProfileMenuEngine()) ->setProfileObject($favorites) ->setCustomPHID($viewer->getPHID()) ->setController($this); return $engine->buildResponse(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/favorites/engineextension/PhabricatorFavoritesMainMenuBarExtension.php
src/applications/favorites/engineextension/PhabricatorFavoritesMainMenuBarExtension.php
<?php final class PhabricatorFavoritesMainMenuBarExtension extends PhabricatorMainMenuBarExtension { const MAINMENUBARKEY = 'favorites'; public function isExtensionEnabledForViewer(PhabricatorUser $viewer) { return PhabricatorApplication::isClassInstalledForViewer( 'PhabricatorFavoritesApplication', $viewer); } public function getExtensionOrder() { return 1100; } public function buildMainMenus() { $viewer = $this->getViewer(); $dropdown = $this->newDropdown($viewer); if (!$dropdown) { return array(); } $favorites_menu = id(new PHUIButtonView()) ->setTag('a') ->setHref('#') ->setIcon('fa-bookmark') ->addClass('phabricator-core-user-menu') ->setNoCSS(true) ->setDropdown(true) ->setDropdownMenu($dropdown) ->setAuralLabel(pht('Favorites Menu')); return array( $favorites_menu, ); } private function newDropdown(PhabricatorUser $viewer) { $applications = id(new PhabricatorApplicationQuery()) ->setViewer($viewer) ->withClasses(array('PhabricatorFavoritesApplication')) ->withInstalled(true) ->execute(); $favorites = head($applications); if (!$favorites) { return null; } $menu_engine = id(new PhabricatorFavoritesProfileMenuEngine()) ->setViewer($viewer) ->setProfileObject($favorites) ->setCustomPHID($viewer->getPHID()); $controller = $this->getController(); if ($controller) { $menu_engine->setController($controller); } $filter_view = $menu_engine->newProfileMenuItemViewList() ->newNavigationView(); $menu_view = $filter_view->getMenu(); $item_views = $menu_view->getItems(); $view = id(new PhabricatorActionListView()) ->setViewer($viewer); foreach ($item_views as $item) { $action = id(new PhabricatorActionView()) ->setName($item->getName()) ->setHref($item->getHref()) ->setIcon($item->getIcon()) ->setType($item->getType()); $view->addAction($action); } 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/favorites/application/PhabricatorFavoritesApplication.php
src/applications/favorites/application/PhabricatorFavoritesApplication.php
<?php final class PhabricatorFavoritesApplication extends PhabricatorApplication { public function getBaseURI() { return '/favorites/'; } public function getName() { return pht('Favorites'); } public function getShortDescription() { return pht('Favorite Items'); } public function getIcon() { return 'fa-bookmark'; } public function getRoutes() { return array( '/favorites/' => array( '' => 'PhabricatorFavoritesMenuItemController', 'menu/' => $this->getProfileMenuRouting( 'PhabricatorFavoritesMenuItemController'), ), ); } public function isLaunchable() { 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/favorites/engine/PhabricatorFavoritesProfileMenuEngine.php
src/applications/favorites/engine/PhabricatorFavoritesProfileMenuEngine.php
<?php final class PhabricatorFavoritesProfileMenuEngine extends PhabricatorProfileMenuEngine { protected function isMenuEngineConfigurable() { return true; } public function getItemURI($path) { return "/favorites/menu/{$path}"; } protected function getBuiltinProfileItems($object) { $items = array(); $viewer = $this->getViewer(); $engines = PhabricatorEditEngine::getAllEditEngines(); $engines = msortv($engines, 'getQuickCreateOrderVector'); foreach ($engines as $engine) { foreach ($engine->getDefaultQuickCreateFormKeys() as $form_key) { $form_hash = PhabricatorHash::digestForIndex($form_key); $builtin_key = "editengine.form({$form_hash})"; $properties = array( 'name' => null, 'formKey' => $form_key, ); $items[] = $this->newItem() ->setBuiltinKey($builtin_key) ->setMenuItemKey(PhabricatorEditEngineProfileMenuItem::MENUITEMKEY) ->setMenuItemProperties($properties); } } $items[] = $this->newDividerItem('tail'); $items[] = $this->newManageItem() ->setMenuItemProperty('name', pht('Edit Favorites')); return $items; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/xhprof/controller/PhabricatorXHProfController.php
src/applications/xhprof/controller/PhabricatorXHProfController.php
<?php abstract class PhabricatorXHProfController extends PhabricatorController { }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/xhprof/controller/PhabricatorXHProfProfileController.php
src/applications/xhprof/controller/PhabricatorXHProfProfileController.php
<?php final class PhabricatorXHProfProfileController extends PhabricatorXHProfController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $phid = $request->getURIData('phid'); $file = id(new PhabricatorFileQuery()) ->setViewer($request->getUser()) ->withPHIDs(array($phid)) ->executeOne(); if (!$file) { return new Aphront404Response(); } $data = $file->loadFileData(); try { $data = phutil_json_decode($data); } catch (PhutilJSONParserException $ex) { throw new PhutilProxyException( pht('Failed to unserialize XHProf profile!'), $ex); } $symbol = $request->getStr('symbol'); $is_framed = $request->getBool('frame'); if ($symbol) { $view = new PhabricatorXHProfProfileSymbolView(); $view->setSymbol($symbol); } else { $view = new PhabricatorXHProfProfileTopLevelView(); $view->setFile($file); $view->setLimit(100); } $view->setBaseURI($request->getRequestURI()->getPath()); $view->setIsFramed($is_framed); $view->setProfileData($data); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb(pht('%s Profile', $symbol)); $title = pht('Profile'); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->setFrameable(true) ->setShowChrome(false) ->setDisableConsole(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/xhprof/controller/PhabricatorXHProfDropController.php
src/applications/xhprof/controller/PhabricatorXHProfDropController.php
<?php final class PhabricatorXHProfDropController extends PhabricatorXHProfController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); if (!$request->validateCSRF()) { return new Aphront400Response(); } $cancel_uri = $this->getApplicationURI(); $ids = $request->getStrList('h'); if ($ids) { $files = id(new PhabricatorFileQuery()) ->setViewer($viewer) ->withIDs($ids) ->setRaisePolicyExceptions(true) ->execute(); } else { $files = array(); } if (!$files) { return $this->newDialog() ->setTitle(pht('Nothing Uploaded')) ->appendParagraph( pht('Drag and drop .xhprof files to import them.')) ->addCancelButton($cancel_uri, pht('Done')); } $samples = array(); foreach ($files as $file) { $sample = PhabricatorXHProfSample::initializeNewSample() ->setFilePHID($file->getPHID()) ->setUserPHID($viewer->getPHID()) ->save(); $samples[] = $sample; } if (count($samples) == 1) { $event = head($samples); $next_uri = $event->getURI(); } else { $next_uri = $this->getApplicationURI(); } return id(new AphrontRedirectResponse())->setURI($next_uri); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/xhprof/controller/PhabricatorXHProfSampleListController.php
src/applications/xhprof/controller/PhabricatorXHProfSampleListController.php
<?php final class PhabricatorXHProfSampleListController extends PhabricatorXHProfController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { return id(new PhabricatorXHProfSampleSearchEngine()) ->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/xhprof/storage/PhabricatorXHProfDAO.php
src/applications/xhprof/storage/PhabricatorXHProfDAO.php
<?php abstract class PhabricatorXHProfDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'xhprof'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/xhprof/storage/PhabricatorXHProfSample.php
src/applications/xhprof/storage/PhabricatorXHProfSample.php
<?php final class PhabricatorXHProfSample extends PhabricatorXHProfDAO implements PhabricatorPolicyInterface { protected $filePHID; protected $usTotal; protected $sampleRate; protected $hostname; protected $requestPath; protected $controller; protected $userPHID; public static function initializeNewSample() { return id(new self()) ->setUsTotal(0) ->setSampleRate(0); } protected function getConfiguration() { return array( self::CONFIG_COLUMN_SCHEMA => array( 'sampleRate' => 'uint32', 'usTotal' => 'uint64', 'hostname' => 'text255?', 'requestPath' => 'text255?', 'controller' => 'text255?', 'userPHID' => 'phid?', ), self::CONFIG_KEY_SCHEMA => array( 'filePHID' => array( 'columns' => array('filePHID'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function getURI() { return '/xhprof/profile/'.$this->getFilePHID().'/'; } public function getDisplayName() { $request_path = $this->getRequestPath(); if (strlen($request_path)) { return $request_path; } return pht('Unnamed Sample'); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return PhabricatorPolicies::getMostOpenPolicy(); } } 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/xhprof/query/PhabricatorXHProfSampleSearchEngine.php
src/applications/xhprof/query/PhabricatorXHProfSampleSearchEngine.php
<?php final class PhabricatorXHProfSampleSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('XHProf Samples'); } public function getApplicationClassName() { return 'PhabricatorXHProfApplication'; } public function newQuery() { return id(new PhabricatorXHProfSampleQuery()); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); return $query; } protected function buildCustomSearchFields() { return array(); } protected function getURI($path) { return '/xhprof/'.$path; } protected function getBuiltinQueryNames() { $names = array( 'all' => pht('All Samples'), ); return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; } return parent::buildSavedQueryFromBuiltin($query_key); } protected function renderResultList( array $samples, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($samples, 'PhabricatorXHProfSample'); $viewer = $this->requireViewer(); $list = new PHUIObjectItemListView(); foreach ($samples as $sample) { $file_phid = $sample->getFilePHID(); $item = id(new PHUIObjectItemView()) ->setObjectName($sample->getID()) ->setHeader($sample->getDisplayName()) ->setHref($sample->getURI()); $us_total = $sample->getUsTotal(); if ($us_total) { $item->addAttribute(pht("%s \xCE\xBCs", new PhutilNumber($us_total))); } if ($sample->getController()) { $item->addAttribute($sample->getController()); } $item->addAttribute($sample->getHostName()); $rate = $sample->getSampleRate(); if ($rate == 0) { $item->addIcon('flag-6', pht('Manual Run')); } else { $item->addIcon('flag-7', pht('Sampled (1/%d)', $rate)); } $item->addIcon( 'none', phabricator_datetime($sample->getDateCreated(), $viewer)); $list->addItem($item); } return $this->newResultView() ->setObjectList($list); } private function newResultView($content = null) { // If we aren't rendering a dashboard panel, activate global drag-and-drop // so you can import profiles by dropping them into the list. if (!$this->isPanelContext()) { $drop_upload = id(new PhabricatorGlobalUploadTargetView()) ->setViewer($this->requireViewer()) ->setHintText("\xE2\x87\xAA ".pht('Drop .xhprof Files to Import')) ->setSubmitURI('/xhprof/import/drop/') ->setViewPolicy(PhabricatorPolicies::POLICY_NOONE); $content = array( $drop_upload, $content, ); } return id(new PhabricatorApplicationSearchResultView()) ->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/xhprof/query/PhabricatorXHProfSampleQuery.php
src/applications/xhprof/query/PhabricatorXHProfSampleQuery.php
<?php final class PhabricatorXHProfSampleQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function newResultObject() { return new PhabricatorXHProfSample(); } 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); } return $where; } public function getQueryApplicationClass() { return 'PhabricatorXHProfApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/xhprof/application/PhabricatorXHProfApplication.php
src/applications/xhprof/application/PhabricatorXHProfApplication.php
<?php final class PhabricatorXHProfApplication extends PhabricatorApplication { public function getBaseURI() { return '/xhprof/'; } public function getName() { return pht('XHProf'); } public function getShortDescription() { return pht('PHP Profiling Tool'); } public function getIcon() { return 'fa-stethoscope'; } public function getTitleGlyph() { return "\xE2\x98\x84"; } public function getApplicationGroup() { return self::GROUP_DEVELOPER; } public function getRoutes() { return array( '/xhprof/' => array( '' => 'PhabricatorXHProfSampleListController', 'list/(?P<view>[^/]+)/' => 'PhabricatorXHProfSampleListController', 'profile/(?P<phid>[^/]+)/' => 'PhabricatorXHProfProfileController', 'import/drop/' => 'PhabricatorXHProfDropController', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/xhprof/view/PhabricatorXHProfProfileTopLevelView.php
src/applications/xhprof/view/PhabricatorXHProfProfileTopLevelView.php
<?php /** * @phutil-external-symbol function xhprof_compute_flat_info */ final class PhabricatorXHProfProfileTopLevelView extends PhabricatorXHProfProfileView { private $profileData; private $limit; private $file; public function setProfileData(array $data) { $this->profileData = $data; return $this; } public function setLimit($limit) { $this->limit = $limit; return $this; } public function setFile(PhabricatorFile $file) { $this->file = $file; return $this; } public function render() { DarkConsoleXHProfPluginAPI::includeXHProfLib(); $GLOBALS['display_calls'] = true; $totals = array(); $flat = xhprof_compute_flat_info($this->profileData, $totals); unset($GLOBALS['display_calls']); $aggregated = array(); foreach ($flat as $call => $counters) { $parts = explode('@', $call, 2); $agg_call = reset($parts); if (empty($aggregated[$agg_call])) { $aggregated[$agg_call] = $counters; } else { foreach ($aggregated[$agg_call] as $key => $val) { if ($key != 'wt') { $aggregated[$agg_call][$key] += $counters[$key]; } } } } $flat = $aggregated; $flat = isort($flat, 'wt'); $flat = array_reverse($flat); $rows = array(); $rows[] = array( pht('Total'), number_format($totals['ct']), number_format($totals['wt']).' us', '100.0%', number_format($totals['wt']).' us', '100.0%', ); if ($this->limit) { $flat = array_slice($flat, 0, $this->limit); } foreach ($flat as $call => $counters) { $rows[] = array( $this->renderSymbolLink($call), number_format($counters['ct']), number_format($counters['wt']).' us', sprintf('%.1f%%', 100 * $counters['wt'] / $totals['wt']), number_format($counters['excl_wt']).' us', sprintf('%.1f%%', 100 * $counters['excl_wt'] / $totals['wt']), ); } Javelin::initBehavior('phabricator-tooltips'); $table = new AphrontTableView($rows); $table->setHeaders( array( pht('Symbol'), pht('Count'), javelin_tag( 'span', array( 'sigil' => 'has-tooltip', 'meta' => array( 'tip' => pht( 'Total wall time spent in this function and all of '. 'its children (children are other functions it called '. 'while executing).'), 'size' => 200, ), ), pht('Wall Time (Inclusive)')), '%', javelin_tag( 'span', array( 'sigil' => 'has-tooltip', 'meta' => array( 'tip' => pht( 'Wall time spent in this function, excluding time '. 'spent in children (children are other functions it '. 'called while executing).'), 'size' => 200, ), ), pht('Wall Time (Exclusive)')), '%', )); $table->setColumnClasses( array( 'wide pri', 'n', 'n', 'n', 'n', 'n', )); $panel = new PHUIObjectBoxView(); $header = id(new PHUIHeaderView()) ->setHeader(pht('XHProf Profile')); if ($this->file) { $button = id(new PHUIButtonView()) ->setHref($this->file->getBestURI()) ->setText(pht('Download %s Profile', '.xhprof')) ->setTag('a'); $header->addActionLink($button); } $panel->setHeader($header); $panel->setTable($table); return $panel->render(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/xhprof/view/PhabricatorXHProfProfileSymbolView.php
src/applications/xhprof/view/PhabricatorXHProfProfileSymbolView.php
<?php /** * @phutil-external-symbol function xhprof_compute_flat_info */ final class PhabricatorXHProfProfileSymbolView extends PhabricatorXHProfProfileView { private $profileData; private $symbol; public function setProfileData(array $data) { $this->profileData = $data; return $this; } public function setSymbol($symbol) { $this->symbol = $symbol; return $this; } public function render() { DarkConsoleXHProfPluginAPI::includeXHProfLib(); $data = $this->profileData; $GLOBALS['display_calls'] = true; $totals = array(); $flat = xhprof_compute_flat_info($data, $totals); unset($GLOBALS['display_calls']); $symbol = $this->symbol; $children = array(); $parents = array(); foreach ($this->profileData as $key => $counters) { if (strpos($key, '==>') !== false) { list($parent, $child) = explode('==>', $key, 2); } else { continue; } if ($parent == $symbol) { $children[$key] = $child; } else if ($child == $symbol) { $parents[$key] = $parent; } } $rows = array(); $rows[] = array( pht('Metrics for this Call'), '', '', '', ); $rows[] = $this->formatRow( array( $symbol, $flat[$symbol]['ct'], $flat[$symbol]['wt'], 1.0, )); $rows[] = array( pht('Parent Calls'), '', '', '', ); foreach ($parents as $key => $name) { $rows[] = $this->formatRow( array( $name, $data[$key]['ct'], $data[$key]['wt'], '', )); } $rows[] = array( pht('Child Calls'), '', '', '', ); $child_rows = array(); foreach ($children as $key => $name) { $child_rows[] = array( $name, $data[$key]['ct'], $data[$key]['wt'], $data[$key]['wt'] / $flat[$symbol]['wt'], ); } $child_rows = isort($child_rows, 2); $child_rows = array_reverse($child_rows); $rows = array_merge( $rows, array_map(array($this, 'formatRow'), $child_rows)); $table = new AphrontTableView($rows); $table->setHeaders( array( pht('Symbol'), pht('Count'), pht('Wall Time'), '%', )); $table->setColumnClasses( array( 'wide pri', 'n', 'n', 'n', )); $panel = new PHUIObjectBoxView(); $panel->setHeaderText(pht('XHProf Profile')); $panel->setTable($table); return $panel->render(); } private function formatRow(array $row) { return array( $this->renderSymbolLink($row[0]), number_format($row[1]), number_format($row[2]).' us', ($row[3] != '' ? sprintf('%.1f%%', 100 * $row[3]) : ''), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/xhprof/view/PhabricatorXHProfProfileView.php
src/applications/xhprof/view/PhabricatorXHProfProfileView.php
<?php abstract class PhabricatorXHProfProfileView extends AphrontView { private $baseURI; private $isFramed; public function setIsFramed($is_framed) { $this->isFramed = $is_framed; return $this; } public function setBaseURI($uri) { $this->baseURI = $uri; return $this; } protected function renderSymbolLink($symbol) { return phutil_tag( 'a', array( 'href' => $this->baseURI.'?symbol='.$symbol, 'target' => $this->isFramed ? '_top' : null, ), $symbol); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/multimeter/controller/MultimeterController.php
src/applications/multimeter/controller/MultimeterController.php
<?php abstract class MultimeterController extends PhabricatorController { private $dimensions = array(); protected function loadDimensions(array $rows) { if (!$rows) { return; } $map = array( 'eventLabelID' => new MultimeterLabel(), 'eventViewerID' => new MultimeterViewer(), 'eventHostID' => new MultimeterHost(), 'eventContextID' => new MultimeterContext(), ); $ids = array(); foreach ($map as $key => $object) { foreach ($rows as $row) { $ids[$key][] = $row[$key]; } } foreach ($ids as $key => $list) { $object = $map[$key]; if (empty($this->dimensions[$key])) { $this->dimensions[$key] = array(); } $this->dimensions[$key] += $object->loadAllWhere( 'id IN (%Ld)', $list); } } protected function getLabelDimension($id) { if (empty($this->dimensions['eventLabelID'][$id])) { return $this->newMissingDimension(new MultimeterLabel(), $id); } return $this->dimensions['eventLabelID'][$id]; } protected function getViewerDimension($id) { if (empty($this->dimensions['eventViewerID'][$id])) { return $this->newMissingDimension(new MultimeterViewer(), $id); } return $this->dimensions['eventViewerID'][$id]; } protected function getHostDimension($id) { if (empty($this->dimensions['eventHostID'][$id])) { return $this->newMissingDimension(new MultimeterHost(), $id); } return $this->dimensions['eventHostID'][$id]; } protected function getContextDimension($id) { if (empty($this->dimensions['eventContextID'][$id])) { return $this->newMissingDimension(new MultimeterContext(), $id); } return $this->dimensions['eventContextID'][$id]; } private function newMissingDimension(MultimeterDimension $dim, $id) { $dim->setName('<missing:'.$id.'>'); return $dim; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/multimeter/controller/MultimeterSampleController.php
src/applications/multimeter/controller/MultimeterSampleController.php
<?php final class MultimeterSampleController extends MultimeterController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $group_map = $this->getColumnMap(); $group = explode('.', $request->getStr('group')); $group = array_intersect($group, array_keys($group_map)); $group = array_fuse($group); if (empty($group['type'])) { $group['type'] = 'type'; } $now = PhabricatorTime::getNow(); $ago = ($now - phutil_units('24 hours in seconds')); $table = new MultimeterEvent(); $conn = $table->establishConnection('r'); $where = array(); $where[] = qsprintf( $conn, 'epoch >= %d AND epoch <= %d', $ago, $now); $with = array(); foreach ($group_map as $key => $column) { // Don't let non-admins filter by viewers, this feels a little too // invasive of privacy. if ($key == 'viewer') { if (!$viewer->getIsAdmin()) { continue; } } $with[$key] = $request->getStrList($key); if ($with[$key]) { $where[] = qsprintf( $conn, '%T IN (%Ls)', $column, $with[$key]); } } $data = queryfx_all( $conn, 'SELECT *, count(*) AS N, SUM(sampleRate * resourceCost) AS totalCost, SUM(sampleRate * resourceCost) / SUM(sampleRate) AS averageCost FROM %T WHERE %LA GROUP BY %LC ORDER BY totalCost DESC, MAX(id) DESC LIMIT 100', $table->getTableName(), $where, array_select_keys($group_map, $group)); $this->loadDimensions($data); $phids = array(); foreach ($data as $row) { $viewer_name = $this->getViewerDimension($row['eventViewerID']) ->getName(); $viewer_phid = $this->getEventViewerPHID($viewer_name); if ($viewer_phid) { $phids[] = $viewer_phid; } } $handles = $viewer->loadHandles($phids); $rows = array(); foreach ($data as $row) { if ($row['N'] == 1) { $events_col = $row['id']; } else { $events_col = $this->renderGroupingLink( $group, 'id', pht('%s Event(s)', new PhutilNumber($row['N']))); } if (isset($group['request'])) { $request_col = $row['requestKey']; if (!$with['request']) { $request_col = $this->renderSelectionLink( 'request', $row['requestKey'], $request_col); } } else { $request_col = $this->renderGroupingLink($group, 'request'); } if (isset($group['viewer'])) { if ($viewer->getIsAdmin()) { $viewer_col = $this->getViewerDimension($row['eventViewerID']) ->getName(); $viewer_phid = $this->getEventViewerPHID($viewer_col); if ($viewer_phid) { $viewer_col = $handles[$viewer_phid]->getName(); } if (!$with['viewer']) { $viewer_col = $this->renderSelectionLink( 'viewer', $row['eventViewerID'], $viewer_col); } } else { $viewer_col = phutil_tag('em', array(), pht('(Masked)')); } } else { $viewer_col = $this->renderGroupingLink($group, 'viewer'); } if (isset($group['context'])) { $context_col = $this->getContextDimension($row['eventContextID']) ->getName(); if (!$with['context']) { $context_col = $this->renderSelectionLink( 'context', $row['eventContextID'], $context_col); } } else { $context_col = $this->renderGroupingLink($group, 'context'); } if (isset($group['host'])) { $host_col = $this->getHostDimension($row['eventHostID']) ->getName(); if (!$with['host']) { $host_col = $this->renderSelectionLink( 'host', $row['eventHostID'], $host_col); } } else { $host_col = $this->renderGroupingLink($group, 'host'); } if (isset($group['label'])) { $label_col = $this->getLabelDimension($row['eventLabelID']) ->getName(); if (!$with['label']) { $label_col = $this->renderSelectionLink( 'label', $row['eventLabelID'], $label_col); } } else { $label_col = $this->renderGroupingLink($group, 'label'); } if ($with['type']) { $type_col = MultimeterEvent::getEventTypeName($row['eventType']); } else { $type_col = $this->renderSelectionLink( 'type', $row['eventType'], MultimeterEvent::getEventTypeName($row['eventType'])); } $rows[] = array( $events_col, $request_col, $viewer_col, $context_col, $host_col, $type_col, $label_col, MultimeterEvent::formatResourceCost( $viewer, $row['eventType'], $row['averageCost']), MultimeterEvent::formatResourceCost( $viewer, $row['eventType'], $row['totalCost']), ($row['N'] == 1) ? $row['sampleRate'] : '-', phabricator_datetime($row['epoch'], $viewer), ); } $table = id(new AphrontTableView($rows)) ->setHeaders( array( pht('ID'), pht('Request'), pht('Viewer'), pht('Context'), pht('Host'), pht('Type'), pht('Label'), pht('Avg'), pht('Cost'), pht('Rate'), pht('Epoch'), )) ->setColumnClasses( array( null, null, null, null, null, null, 'wide', 'n', 'n', 'n', null, )); $box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Samples')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setTable($table); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb( pht('Samples'), $this->getGroupURI(array(), true)); $crumbs->setBorder(true); $crumb_map = array( 'host' => pht('By Host'), 'context' => pht('By Context'), 'viewer' => pht('By Viewer'), 'request' => pht('By Request'), 'label' => pht('By Label'), 'id' => pht('By ID'), ); $parts = array(); foreach ($group as $item) { if ($item == 'type') { continue; } $parts[$item] = $item; $crumbs->addTextCrumb( idx($crumb_map, $item, $item), $this->getGroupURI($parts, true)); } $header = id(new PHUIHeaderView()) ->setHeader( pht( 'Samples (%s - %s)', phabricator_datetime($ago, $viewer), phabricator_datetime($now, $viewer))) ->setHeaderIcon('fa-motorcycle'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter($box); return $this->newPage() ->setTitle(pht('Samples')) ->setCrumbs($crumbs) ->appendChild($view); } private function renderGroupingLink(array $group, $key, $name = null) { $group[] = $key; $uri = $this->getGroupURI($group); if ($name === null) { $name = pht('(All)'); } return phutil_tag( 'a', array( 'href' => $uri, 'style' => 'font-weight: bold', ), $name); } private function getGroupURI(array $group, $wipe = false) { unset($group['type']); $uri = clone $this->getRequest()->getRequestURI(); $group = implode('.', $group); if (!strlen($group)) { $uri->removeQueryParam('group'); } else { $uri->replaceQueryParam('group', $group); } if ($wipe) { foreach ($this->getColumnMap() as $key => $column) { $uri->removeQueryParam($key); } } return $uri; } private function renderSelectionLink($key, $value, $link_text) { $value = (array)$value; $uri = clone $this->getRequest()->getRequestURI(); $uri->replaceQueryParam($key, implode(',', $value)); return phutil_tag( 'a', array( 'href' => $uri, ), $link_text); } private function getColumnMap() { return array( 'type' => 'eventType', 'host' => 'eventHostID', 'context' => 'eventContextID', 'viewer' => 'eventViewerID', 'request' => 'requestKey', 'label' => 'eventLabelID', 'id' => 'id', ); } private function getEventViewerPHID($viewer_name) { if (!strncmp($viewer_name, 'user.', 5)) { return substr($viewer_name, 5); } 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/multimeter/storage/MultimeterDimension.php
src/applications/multimeter/storage/MultimeterDimension.php
<?php abstract class MultimeterDimension extends MultimeterDAO { protected $name; protected $nameHash; public function setName($name) { $this->nameHash = PhabricatorHash::digestForIndex($name); return parent::setName($name); } protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'name' => 'text', 'nameHash' => 'bytes12', ), self::CONFIG_KEY_SCHEMA => array( 'key_hash' => array( 'columns' => array('nameHash'), 'unique' => true, ), ), ) + 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/multimeter/storage/MultimeterViewer.php
src/applications/multimeter/storage/MultimeterViewer.php
<?php final class MultimeterViewer extends MultimeterDimension {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/multimeter/storage/MultimeterContext.php
src/applications/multimeter/storage/MultimeterContext.php
<?php final class MultimeterContext extends MultimeterDimension {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/multimeter/storage/MultimeterHost.php
src/applications/multimeter/storage/MultimeterHost.php
<?php final class MultimeterHost extends MultimeterDimension {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/multimeter/storage/MultimeterLabel.php
src/applications/multimeter/storage/MultimeterLabel.php
<?php final class MultimeterLabel extends MultimeterDimension {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/multimeter/storage/MultimeterEvent.php
src/applications/multimeter/storage/MultimeterEvent.php
<?php final class MultimeterEvent extends MultimeterDAO { const TYPE_STATIC_RESOURCE = 0; const TYPE_REQUEST_TIME = 1; const TYPE_EXEC_TIME = 2; protected $eventType; protected $eventLabelID; protected $resourceCost; protected $sampleRate; protected $eventContextID; protected $eventHostID; protected $eventViewerID; protected $epoch; protected $requestKey; private $eventLabel; public function setEventLabel($event_label) { $this->eventLabel = $event_label; return $this; } public function getEventLabel() { return $this->eventLabel; } public static function getEventTypeName($type) { switch ($type) { case self::TYPE_STATIC_RESOURCE: return pht('Static Resource'); case self::TYPE_REQUEST_TIME: return pht('Web Request'); case self::TYPE_EXEC_TIME: return pht('Subprocesses'); } return pht('Unknown ("%s")', $type); } public static function formatResourceCost( PhabricatorUser $viewer, $type, $cost) { switch ($type) { case self::TYPE_STATIC_RESOURCE: return pht('%s Req', new PhutilNumber($cost)); case self::TYPE_REQUEST_TIME: case self::TYPE_EXEC_TIME: return pht('%s us', new PhutilNumber($cost)); } return pht('%s Unit(s)', new PhutilNumber($cost)); } protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'eventType' => 'uint32', 'resourceCost' => 'sint64', 'sampleRate' => 'uint32', 'requestKey' => 'bytes12', ), self::CONFIG_KEY_SCHEMA => array( 'key_request' => array( 'columns' => array('requestKey'), ), 'key_type' => array( 'columns' => array('eventType', 'epoch'), ), ), ) + 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/multimeter/storage/MultimeterDAO.php
src/applications/multimeter/storage/MultimeterDAO.php
<?php abstract class MultimeterDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'multimeter'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/multimeter/application/PhabricatorMultimeterApplication.php
src/applications/multimeter/application/PhabricatorMultimeterApplication.php
<?php final class PhabricatorMultimeterApplication extends PhabricatorApplication { public function getName() { return pht('Multimeter'); } public function getBaseURI() { return '/multimeter/'; } public function getIcon() { return 'fa-motorcycle'; } public function isPrototype() { return true; } public function getTitleGlyph() { return "\xE2\x8F\xB3"; } public function getApplicationGroup() { return self::GROUP_DEVELOPER; } public function getShortDescription() { return pht('Performance Sampler'); } public function getRemarkupRules() { return array(); } public function getRoutes() { return array( '/multimeter/' => array( '' => 'MultimeterSampleController', ), ); } public function getHelpDocumentationArticles(PhabricatorUser $viewer) { return array( array( 'name' => pht('Multimeter User Guide'), 'href' => PhabricatorEnv::getDoclink('Multimeter User Guide'), ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/multimeter/garbagecollector/MultimeterEventGarbageCollector.php
src/applications/multimeter/garbagecollector/MultimeterEventGarbageCollector.php
<?php final class MultimeterEventGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'multimeter.events'; public function getCollectorName() { return pht('Multimeter Events'); } public function getDefaultRetentionPolicy() { return phutil_units('90 days in seconds'); } protected function collectGarbage() { $table = new MultimeterEvent(); $conn_w = $table->establishConnection('w'); queryfx( $conn_w, 'DELETE FROM %T WHERE epoch < %d LIMIT 100', $table->getTableName(), $this->getGarbageEpoch()); return ($conn_w->getAffectedRows() == 100); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false