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/infrastructure/markup/syntax/highlighter/pygments/PhutilDefaultSyntaxHighlighterEnginePygmentsFuture.php
src/infrastructure/markup/syntax/highlighter/pygments/PhutilDefaultSyntaxHighlighterEnginePygmentsFuture.php
<?php final class PhutilDefaultSyntaxHighlighterEnginePygmentsFuture extends FutureProxy { private $source; private $scrub; public function __construct(Future $proxied, $source, $scrub = false) { parent::__construct($proxied); $this->source = $source; $this->scrub = $scrub; } protected function didReceiveResult($result) { list($err, $stdout, $stderr) = $result; if (!$err && strlen($stdout)) { // Strip off fluff Pygments adds. $stdout = preg_replace( '@^<div class="highlight"><pre>(.*)</pre></div>\s*$@s', '\1', $stdout); if ($this->scrub) { $stdout = preg_replace('/^.*\n/', '', $stdout); } return phutil_safe_html($stdout); } throw new PhutilSyntaxHighlighterException($stderr, $err); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/remarkup/PhutilRemarkupEngine.php
src/infrastructure/markup/remarkup/PhutilRemarkupEngine.php
<?php final class PhutilRemarkupEngine extends PhutilMarkupEngine { const MODE_DEFAULT = 0; const MODE_TEXT = 1; const MODE_HTML_MAIL = 2; const MAX_CHILD_DEPTH = 32; private $blockRules = array(); private $config = array(); private $mode; private $metadata = array(); private $states = array(); private $postprocessRules = array(); private $storage; public function setConfig($key, $value) { $this->config[$key] = $value; return $this; } public function getConfig($key, $default = null) { return idx($this->config, $key, $default); } public function setMode($mode) { $this->mode = $mode; return $this; } public function isTextMode() { return $this->mode & self::MODE_TEXT; } public function isAnchorMode() { return $this->getState('toc'); } public function isHTMLMailMode() { return $this->mode & self::MODE_HTML_MAIL; } public function getQuoteDepth() { return $this->getConfig('runtime.quote.depth', 0); } public function setQuoteDepth($depth) { return $this->setConfig('runtime.quote.depth', $depth); } public function setBlockRules(array $rules) { assert_instances_of($rules, 'PhutilRemarkupBlockRule'); $rules = msortv($rules, 'getPriorityVector'); $this->blockRules = $rules; foreach ($this->blockRules as $rule) { $rule->setEngine($this); } $post_rules = array(); foreach ($this->blockRules as $block_rule) { foreach ($block_rule->getMarkupRules() as $rule) { $key = $rule->getPostprocessKey(); if ($key !== null) { $post_rules[$key] = $rule; } } } $this->postprocessRules = $post_rules; return $this; } public function getTextMetadata($key, $default = null) { if (isset($this->metadata[$key])) { return $this->metadata[$key]; } return idx($this->metadata, $key, $default); } public function setTextMetadata($key, $value) { $this->metadata[$key] = $value; return $this; } public function storeText($text) { if ($this->isTextMode()) { $text = phutil_safe_html($text); } return $this->storage->store($text); } public function overwriteStoredText($token, $new_text) { if ($this->isTextMode()) { $new_text = phutil_safe_html($new_text); } $this->storage->overwrite($token, $new_text); return $this; } public function markupText($text) { return $this->postprocessText($this->preprocessText($text)); } public function pushState($state) { if (empty($this->states[$state])) { $this->states[$state] = 0; } $this->states[$state]++; return $this; } public function popState($state) { if (empty($this->states[$state])) { throw new Exception(pht("State '%s' pushed more than popped!", $state)); } $this->states[$state]--; if (!$this->states[$state]) { unset($this->states[$state]); } return $this; } public function getState($state) { return !empty($this->states[$state]); } public function preprocessText($text) { $this->metadata = array(); $this->storage = new PhutilRemarkupBlockStorage(); $blocks = $this->splitTextIntoBlocks($text); $output = array(); foreach ($blocks as $block) { $output[] = $this->markupBlock($block); } $output = $this->flattenOutput($output); $map = $this->storage->getMap(); $this->storage = null; $metadata = $this->metadata; return array( 'output' => $output, 'storage' => $map, 'metadata' => $metadata, ); } private function splitTextIntoBlocks($text, $depth = 0) { // Apply basic block and paragraph normalization to the text. NOTE: We don't // strip trailing whitespace because it is semantic in some contexts, // notably inlined diffs that the author intends to show as a code block. $text = phutil_split_lines($text, true); $block_rules = $this->blockRules; $blocks = array(); $cursor = 0; $can_merge = array(); foreach ($block_rules as $key => $block_rule) { if ($block_rule instanceof PhutilRemarkupDefaultBlockRule) { $can_merge[$key] = true; } } $last_block = null; $last_block_key = -1; // See T13487. For very large inputs, block separation can dominate // runtime. This is written somewhat clumsily to attempt to handle // very large inputs as gracefully as is practical. while (isset($text[$cursor])) { $starting_cursor = $cursor; foreach ($block_rules as $block_key => $block_rule) { $num_lines = $block_rule->getMatchingLineCount($text, $cursor); if ($num_lines) { $current_block = array( 'start' => $cursor, 'num_lines' => $num_lines, 'rule' => $block_rule, 'empty' => self::isEmptyBlock($text, $cursor, $num_lines), 'children' => array(), 'merge' => isset($can_merge[$block_key]), ); $should_merge = self::shouldMergeParagraphBlocks( $text, $last_block, $current_block); if ($should_merge) { $last_block['num_lines'] = ($last_block['num_lines'] + $current_block['num_lines']); $last_block['empty'] = ($last_block['empty'] && $current_block['empty']); $blocks[$last_block_key] = $last_block; } else { $blocks[] = $current_block; $last_block = $current_block; $last_block_key++; } $cursor += $num_lines; break; } } if ($starting_cursor === $cursor) { throw new Exception(pht('Block in text did not match any block rule.')); } } // See T13487. It's common for blocks to be small, and this loop seems to // measure as faster if we manually concatenate blocks than if we // "array_slice()" and "implode()" blocks. This is a bit muddy. foreach ($blocks as $key => $block) { $min = $block['start']; $max = $min + $block['num_lines']; $lines = ''; for ($ii = $min; $ii < $max; $ii++) { if (isset($text[$ii])) { $lines .= $text[$ii]; } } $blocks[$key]['text'] = $lines; } // Stop splitting child blocks apart if we get too deep. This arrests // any blocks which have looping child rules, and stops the stack from // exploding if someone writes a hilarious comment with 5,000 levels of // quoted text. if ($depth < self::MAX_CHILD_DEPTH) { foreach ($blocks as $key => $block) { $rule = $block['rule']; if (!$rule->supportsChildBlocks()) { continue; } list($parent_text, $child_text) = $rule->extractChildText( $block['text']); $blocks[$key]['text'] = $parent_text; $blocks[$key]['children'] = $this->splitTextIntoBlocks( $child_text, $depth + 1); } } return $blocks; } private function markupBlock(array $block) { $rule = $block['rule']; $rule->willMarkupChildBlocks(); $children = array(); foreach ($block['children'] as $child) { $children[] = $this->markupBlock($child); } $rule->didMarkupChildBlocks(); if ($children) { $children = $this->flattenOutput($children); } else { $children = null; } return $rule->markupText($block['text'], $children); } private function flattenOutput(array $output) { if ($this->isTextMode()) { $output = implode("\n\n", $output)."\n"; } else { $output = phutil_implode_html("\n\n", $output); } return $output; } private static function shouldMergeParagraphBlocks( $text, $last_block, $current_block) { // If we're at the beginning of the input, we can't merge. if ($last_block === null) { return false; } // If the previous block wasn't a default block, we can't merge. if (!$last_block['merge']) { return false; } // If the current block isn't a default block, we can't merge. if (!$current_block['merge']) { return false; } // If the last block was empty, we definitely want to merge. if ($last_block['empty']) { return true; } // If this block is empty, we definitely want to merge. if ($current_block['empty']) { return true; } // Check if the last line of the previous block or the first line of this // block have any non-whitespace text. If they both do, we're going to // merge. // If either of them are a blank line or a line with only whitespace, we // do not merge: this means we've found a paragraph break. $tail = $text[$current_block['start'] - 1]; $head = $text[$current_block['start']]; if (strlen(trim($tail)) && strlen(trim($head))) { return true; } return false; } private static function isEmptyBlock($text, $start, $num_lines) { for ($cursor = $start; $cursor < $start + $num_lines; $cursor++) { if (strlen(trim($text[$cursor]))) { return false; } } return true; } public function postprocessText(array $dict) { $this->metadata = idx($dict, 'metadata', array()); $this->storage = new PhutilRemarkupBlockStorage(); $this->storage->setMap(idx($dict, 'storage', array())); foreach ($this->blockRules as $block_rule) { $block_rule->postprocess(); } foreach ($this->postprocessRules as $rule) { $rule->didMarkupText(); } return $this->restoreText(idx($dict, 'output')); } public function restoreText($text) { return $this->storage->restore($text, $this->isTextMode()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/remarkup/__tests__/PhutilRemarkupEngineTestCase.php
src/infrastructure/markup/remarkup/__tests__/PhutilRemarkupEngineTestCase.php
<?php /** * Test cases for @{class:PhutilRemarkupEngine}. */ final class PhutilRemarkupEngineTestCase extends PhutilTestCase { public function testEngine() { $root = dirname(__FILE__).'/remarkup/'; foreach (Filesystem::listDirectory($root, $hidden = false) as $file) { $this->markupText($root.$file); } } private function markupText($markup_file) { $contents = Filesystem::readFile($markup_file); $file = basename($markup_file); $parts = explode("\n~~~~~~~~~~\n", $contents); $this->assertEqual(3, count($parts), $markup_file); list($input_remarkup, $expected_output, $expected_text) = $parts; $input_remarkup = $this->unescapeTrailingWhitespace($input_remarkup); $expected_output = $this->unescapeTrailingWhitespace($expected_output); $expected_text = $this->unescapeTrailingWhitespace($expected_text); $engine = $this->buildNewTestEngine(); switch ($file) { case 'raw-escape.txt': // NOTE: Here, we want to test PhutilRemarkupEscapeRemarkupRule and // PhutilRemarkupBlockStorage, which are triggered by "\1". In the // test, "~" is used as a placeholder for "\1" since it's hard to type // "\1". $input_remarkup = str_replace('~', "\1", $input_remarkup); $expected_output = str_replace('~', "\1", $expected_output); $expected_text = str_replace('~', "\1", $expected_text); break; case 'toc.txt': $engine->setConfig('header.generate-toc', true); break; case 'link-same-window.txt': $engine->setConfig('uri.same-window', true); break; case 'link-square.txt': $engine->setConfig('uri.base', 'http://www.example.com/'); $engine->setConfig('uri.here', 'http://www.example.com/page/'); break; } $actual_output = (string)$engine->markupText($input_remarkup); switch ($file) { case 'toc.txt': $table_of_contents = PhutilRemarkupHeaderBlockRule::renderTableOfContents($engine); $actual_output = $table_of_contents."\n\n".$actual_output; break; } $this->assertEqual( $expected_output, $actual_output, pht("Failed to markup HTML in file '%s'.", $file)); $engine->setMode(PhutilRemarkupEngine::MODE_TEXT); $actual_output = (string)$engine->markupText($input_remarkup); $this->assertEqual( $expected_text, $actual_output, pht("Failed to markup text in file '%s'.", $file)); } private function buildNewTestEngine() { $engine = new PhutilRemarkupEngine(); $engine->setConfig( 'uri.allowed-protocols', array( 'http' => true, 'mailto' => true, 'tel' => true, )); $rules = array(); $rules[] = new PhutilRemarkupEscapeRemarkupRule(); $rules[] = new PhutilRemarkupMonospaceRule(); $rules[] = new PhutilRemarkupDocumentLinkRule(); $rules[] = new PhutilRemarkupHyperlinkRule(); $rules[] = new PhutilRemarkupBoldRule(); $rules[] = new PhutilRemarkupItalicRule(); $rules[] = new PhutilRemarkupDelRule(); $rules[] = new PhutilRemarkupUnderlineRule(); $rules[] = new PhutilRemarkupHighlightRule(); $blocks = array(); $blocks[] = new PhutilRemarkupQuotesBlockRule(); $blocks[] = new PhutilRemarkupReplyBlockRule(); $blocks[] = new PhutilRemarkupHeaderBlockRule(); $blocks[] = new PhutilRemarkupHorizontalRuleBlockRule(); $blocks[] = new PhutilRemarkupCodeBlockRule(); $blocks[] = new PhutilRemarkupLiteralBlockRule(); $blocks[] = new PhutilRemarkupNoteBlockRule(); $blocks[] = new PhutilRemarkupTableBlockRule(); $blocks[] = new PhutilRemarkupSimpleTableBlockRule(); $blocks[] = new PhutilRemarkupDefaultBlockRule(); $blocks[] = new PhutilRemarkupListBlockRule(); $blocks[] = new PhutilRemarkupInterpreterBlockRule(); foreach ($blocks as $block) { if (!($block instanceof PhutilRemarkupCodeBlockRule)) { $block->setMarkupRules($rules); } } $engine->setBlockRules($blocks); return $engine; } private function unescapeTrailingWhitespace($input) { // Remove up to one "~" at the end of each line so trailing whitespace may // be written in tests as " ~". return preg_replace('/~$/m', '', $input); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/interpreter/PhabricatorRemarkupCowsayBlockInterpreter.php
src/infrastructure/markup/interpreter/PhabricatorRemarkupCowsayBlockInterpreter.php
<?php final class PhabricatorRemarkupCowsayBlockInterpreter extends PhutilRemarkupBlockInterpreter { public function getInterpreterName() { return 'cowsay'; } public function markupContent($content, array $argv) { $action = idx($argv, 'think') ? 'think' : 'say'; $eyes = idx($argv, 'eyes', 'oo'); $tongue = idx($argv, 'tongue', ' '); $map = self::getCowMap(); $cow = idx($argv, 'cow'); $cow = ($cow === null ? '' : $cow); $cow = phutil_utf8_strtolower($cow); if (empty($map[$cow])) { $cow = 'default'; } $result = id(new PhutilCowsay()) ->setTemplate($map[$cow]) ->setAction($action) ->setEyes($eyes) ->setTongue($tongue) ->setText($content) ->renderCow(); $engine = $this->getEngine(); if ($engine->isTextMode()) { return $result; } if ($engine->isHTMLMailMode()) { return phutil_tag('pre', array(), $result); } return phutil_tag( 'div', array( 'class' => 'PhabricatorMonospaced remarkup-cowsay', ), $result); } private static function getCowMap() { $root = dirname(phutil_get_library_root('phabricator')); $directories = array( $root.'/externals/cowsay/cows/', $root.'/resources/cows/builtin/', $root.'/resources/cows/custom/', ); $map = array(); foreach ($directories as $directory) { foreach (Filesystem::listDirectory($directory, false) as $cow_file) { $matches = null; if (!preg_match('/^(.*)\.cow\z/', $cow_file, $matches)) { continue; } $cow_name = $matches[1]; $cow_name = phutil_utf8_strtolower($cow_name); $map[$cow_name] = Filesystem::readFile($directory.$cow_file); } } return $map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/infrastructure/markup/interpreter/PhabricatorRemarkupFigletBlockInterpreter.php
src/infrastructure/markup/interpreter/PhabricatorRemarkupFigletBlockInterpreter.php
<?php final class PhabricatorRemarkupFigletBlockInterpreter extends PhutilRemarkupBlockInterpreter { public function getInterpreterName() { return 'figlet'; } /** * @phutil-external-symbol class Text_Figlet */ public function markupContent($content, array $argv) { $map = self::getFigletMap(); $font = idx($argv, 'font'); $font = ($font === null ? '' : $font); $font = phutil_utf8_strtolower($font); if (empty($map[$font])) { $font = 'standard'; } $root = dirname(phutil_get_library_root('phabricator')); require_once $root.'/externals/pear-figlet/Text/Figlet.php'; $figlet = new Text_Figlet(); $figlet->loadFont($map[$font]); $result = $figlet->lineEcho($content); $engine = $this->getEngine(); if ($engine->isTextMode()) { return $result; } if ($engine->isHTMLMailMode()) { return phutil_tag('pre', array(), $result); } return phutil_tag( 'div', array( 'class' => 'PhabricatorMonospaced remarkup-figlet', ), $result); } private static function getFigletMap() { $root = dirname(phutil_get_library_root('phabricator')); $dirs = array( $root.'/externals/figlet/fonts/', $root.'/externals/pear-figlet/fonts/', $root.'/resources/figlet/custom/', ); $map = array(); foreach ($dirs as $dir) { foreach (Filesystem::listDirectory($dir, false) as $file) { if (preg_match('/\.flf\z/', $file)) { $name = phutil_utf8_strtolower($file); $name = preg_replace('/\.flf\z/', '', $name); $map[$name] = $dir.$file; } } } return $map; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionDeleteController.php
src/applications/phriction/controller/PhrictionDeleteController.php
<?php final class PhrictionDeleteController extends PhrictionController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->needContent(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_EDIT, PhabricatorPolicyCapability::CAN_VIEW, )) ->executeOne(); if (!$document) { return new Aphront404Response(); } $document_uri = PhrictionDocument::getSlugURI($document->getSlug()); $e_text = null; if ($request->isFormPost()) { $xactions = array(); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentDeleteTransaction::TRANSACTIONTYPE) ->setNewValue(true); $editor = id(new PhrictionTransactionEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true); try { $editor->applyTransactions($document, $xactions); return id(new AphrontRedirectResponse())->setURI($document_uri); } catch (PhabricatorApplicationTransactionValidationException $ex) { $e_text = phutil_implode_html("\n", $ex->getErrorMessages()); } } if ($e_text) { $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->setTitle(pht('Can Not Delete Document!')) ->appendChild($e_text) ->addCancelButton($document_uri); } else { $dialog = id(new AphrontDialogView()) ->setUser($viewer) ->setTitle(pht('Delete Document?')) ->appendChild( pht('Really delete this document? You can recover it later by '. 'reverting to a previous version.')) ->addSubmitButton(pht('Delete')) ->addCancelButton($document_uri); } 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/phriction/controller/PhrictionDiffController.php
src/applications/phriction/controller/PhrictionDiffController.php
<?php final class PhrictionDiffController extends PhrictionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->needContent(true) ->executeOne(); if (!$document) { return new Aphront404Response(); } $current = $document->getContent(); $l = $request->getInt('l'); $r = $request->getInt('r'); $ref = $request->getStr('ref'); if ($ref) { list($l, $r) = explode(',', $ref); } $content = id(new PhrictionContentQuery()) ->setViewer($viewer) ->withDocumentPHIDs(array($document->getPHID())) ->withVersions(array($l, $r)) ->execute(); $content = mpull($content, null, 'getVersion'); $content_l = idx($content, $l, null); $content_r = idx($content, $r, null); if (!$content_l || !$content_r) { return new Aphront404Response(); } $text_l = $content_l->getContent(); $text_r = $content_r->getContent(); $diff_view = id(new PhabricatorApplicationTransactionTextDiffDetailView()) ->setOldText($text_l) ->setNewText($text_r); $changes = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Content Changes')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild( phutil_tag( 'div', array( 'class' => 'prose-diff-frame', ), $diff_view)); require_celerity_resource('phriction-document-css'); $slug = $document->getSlug(); $revert_l = $this->renderRevertButton($document, $content_l, $current); $revert_r = $this->renderRevertButton($document, $content_r, $current); $crumbs = $this->buildApplicationCrumbs(); $crumb_views = $this->renderBreadcrumbs($slug); foreach ($crumb_views as $view) { $crumbs->addCrumb($view); } $crumbs->addTextCrumb( pht('History'), PhrictionDocument::getSlugURI($slug, 'history')); $title = pht('Version %s vs %s', $l, $r); $header = id(new PHUIHeaderView()) ->setHeader($title) ->setHeaderIcon('fa-history'); $crumbs->addTextCrumb($title, $request->getRequestURI()); $comparison_table = $this->renderComparisonTable( array( $content_r, $content_l, )); $navigation_table = null; if ($l + 1 == $r) { $nav_l = ($l > 1); $nav_r = ($r != $document->getMaxVersion()); $uri = $request->getRequestURI(); if ($nav_l) { $link_l = phutil_tag( 'a', array( 'href' => $uri->alter('l', $l - 1)->alter('r', $r - 1), 'class' => 'button button-grey', ), pht("\xC2\xAB Previous Change")); } else { $link_l = phutil_tag( 'a', array( 'href' => '#', 'class' => 'button button-grey disabled', ), pht('Original Change')); } $link_r = null; if ($nav_r) { $link_r = phutil_tag( 'a', array( 'href' => $uri->alter('l', $l + 1)->alter('r', $r + 1), 'class' => 'button button-grey', ), pht("Next Change \xC2\xBB")); } else { $link_r = phutil_tag( 'a', array( 'href' => '#', 'class' => 'button button-grey disabled', ), pht('Most Recent Change')); } $navigation_table = phutil_tag( 'table', array('class' => 'phriction-history-nav-table'), phutil_tag('tr', array(), array( phutil_tag('td', array('class' => 'nav-prev'), $link_l), phutil_tag('td', array('class' => 'nav-next'), $link_r), ))); } $output = hsprintf( '<div class="phriction-document-history-diff">'. '%s%s'. '<table class="phriction-revert-table">'. '<tr><td>%s</td><td>%s</td>'. '</table>'. '</div>', $comparison_table->render(), $navigation_table, $revert_l, $revert_r); $object_box = id(new PHUIObjectBoxView()) ->setHeaderText(pht('Edits')) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->appendChild($output); $crumbs->setBorder(true); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $object_box, $changes, )); return $this->newPage() ->setTitle(pht('Document History')) ->setCrumbs($crumbs) ->appendChild($view); } private function renderRevertButton( PhrictionDocument $document, PhrictionContent $content, PhrictionContent $current) { $document_id = $document->getID(); $version = $content->getVersion(); $hidden_statuses = array( PhrictionChangeType::CHANGE_DELETE => true, // Silly PhrictionChangeType::CHANGE_MOVE_AWAY => true, // Plain silly PhrictionChangeType::CHANGE_STUB => true, // Utterly silly ); if (isset($hidden_statuses[$content->getChangeType()])) { // Don't show an edit/revert button for changes which deleted, moved or // stubbed the content since it's silly. return null; } if ($version == $current->getVersion()) { $label = pht('Edit Current Version %s...', new PhutilNumber($version)); } else if ($version < $current->getVersion()) { $label = pht('Edit Older Version %s...', new PhutilNumber($version)); } else { $label = pht('Edit Draft Version %s...', new PhutilNumber($version)); } return phutil_tag( 'a', array( 'href' => '/phriction/edit/'.$document_id.'/?revert='.$version, 'class' => 'button button-grey', ), $label); } private function renderComparisonTable(array $content) { assert_instances_of($content, 'PhrictionContent'); $viewer = $this->getViewer(); $phids = mpull($content, 'getAuthorPHID'); $handles = $this->loadViewerHandles($phids); $list = new PHUIObjectItemListView(); $first = true; foreach ($content as $c) { $author = $handles[$c->getAuthorPHID()]->renderLink(); $item = id(new PHUIObjectItemView()) ->setHeader(pht('%s by %s, %s', PhrictionChangeType::getChangeTypeLabel($c->getChangeType()), $author, pht('Version %s', $c->getVersion()))) ->addAttribute(pht('%s %s', phabricator_date($c->getDateCreated(), $viewer), phabricator_time($c->getDateCreated(), $viewer))); if ($c->getDescription()) { $item->addAttribute($c->getDescription()); } if ($first == true) { $item->setStatusIcon('fa-file green'); $first = false; } else { $item->setStatusIcon('fa-file red'); } $list->addItem($item); } return $list; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionEditEngineController.php
src/applications/phriction/controller/PhrictionEditEngineController.php
<?php final class PhrictionEditEngineController extends PhrictionController { public function handleRequest(AphrontRequest $request) { // NOTE: For now, this controller is only used to handle comments. return id(new PhrictionDocumentEditEngine()) ->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/phriction/controller/PhrictionEditController.php
src/applications/phriction/controller/PhrictionEditController.php
<?php final class PhrictionEditController extends PhrictionController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); $max_version = null; if ($id) { $is_new = false; $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->needContent(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$document) { return new Aphront404Response(); } $max_version = $document->getMaxVersion(); $revert = $request->getInt('revert'); if ($revert) { $content = id(new PhrictionContentQuery()) ->setViewer($viewer) ->withDocumentPHIDs(array($document->getPHID())) ->withVersions(array($revert)) ->executeOne(); if (!$content) { return new Aphront404Response(); } } else { $content = id(new PhrictionContentQuery()) ->setViewer($viewer) ->withDocumentPHIDs(array($document->getPHID())) ->setLimit(1) ->executeOne(); } } else { $slug = $request->getStr('slug'); $slug = PhabricatorSlug::normalize($slug); if (!$slug) { return new Aphront404Response(); } $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withSlugs(array($slug)) ->needContent(true) ->executeOne(); if ($document) { $content = id(new PhrictionContentQuery()) ->setViewer($viewer) ->withDocumentPHIDs(array($document->getPHID())) ->setLimit(1) ->executeOne(); $max_version = $document->getMaxVersion(); $is_new = false; } else { $document = PhrictionDocument::initializeNewDocument($viewer, $slug); $content = $document->getContent(); $is_new = true; } } require_celerity_resource('phriction-document-css'); $e_title = true; $e_content = true; $validation_exception = null; $notes = null; $title = $content->getTitle(); $overwrite = false; $v_cc = PhabricatorSubscribersQuery::loadSubscribersForPHID( $document->getPHID()); if ($is_new) { $v_projects = array(); } else { $v_projects = PhabricatorEdgeQuery::loadDestinationPHIDs( $document->getPHID(), PhabricatorProjectObjectHasProjectEdgeType::EDGECONST); $v_projects = array_reverse($v_projects); } $v_space = $document->getSpacePHID(); $content_text = $content->getContent(); $is_draft_mode = ($document->getContent()->getVersion() != $max_version); $default_view = $document->getViewPolicy(); $default_edit = $document->getEditPolicy(); $default_space = $document->getSpacePHID(); if ($request->isFormPost()) { if ($is_new) { $save_as_draft = false; } else { $save_as_draft = ($is_draft_mode || $request->getExists('draft')); } $title = $request->getStr('title'); $content_text = $request->getStr('content'); $notes = $request->getStr('description'); $max_version = $request->getInt('contentVersion'); $v_view = $request->getStr('viewPolicy'); $v_edit = $request->getStr('editPolicy'); $v_cc = $request->getArr('cc'); $v_projects = $request->getArr('projects'); $v_space = $request->getStr('spacePHID'); if ($save_as_draft) { $edit_type = PhrictionDocumentDraftTransaction::TRANSACTIONTYPE; } else { $edit_type = PhrictionDocumentContentTransaction::TRANSACTIONTYPE; } $xactions = array(); if ($is_new) { $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_CREATE); } $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhrictionDocumentTitleTransaction::TRANSACTIONTYPE) ->setNewValue($title); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType($edit_type) ->setNewValue($content_text); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY) ->setNewValue($v_view) ->setIsDefaultTransaction($is_new && ($v_view === $default_view)); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDIT_POLICY) ->setNewValue($v_edit) ->setIsDefaultTransaction($is_new && ($v_edit === $default_edit)); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_SPACE) ->setNewValue($v_space) ->setIsDefaultTransaction($is_new && ($v_space === $default_space)); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_SUBSCRIBERS) ->setNewValue(array('=' => $v_cc)); $proj_edge_type = PhabricatorProjectObjectHasProjectEdgeType::EDGECONST; $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDGE) ->setMetadataValue('edge:type', $proj_edge_type) ->setNewValue(array('=' => array_fuse($v_projects))); $editor = id(new PhrictionTransactionEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setDescription($notes) ->setProcessContentVersionError(!$request->getBool('overwrite')) ->setContentVersion($max_version); try { $editor->applyTransactions($document, $xactions); $uri = PhrictionDocument::getSlugURI($document->getSlug()); $uri = new PhutilURI($uri); // If the user clicked "Save as Draft", take them to the draft, not // to the current published page. if ($save_as_draft) { $uri = $uri->alter('v', $document->getMaxVersion()); } return id(new AphrontRedirectResponse())->setURI($uri); } catch (PhabricatorApplicationTransactionValidationException $ex) { $validation_exception = $ex; $e_title = nonempty( $ex->getShortMessage( PhrictionDocumentTitleTransaction::TRANSACTIONTYPE), true); $e_content = nonempty( $ex->getShortMessage( PhrictionDocumentContentTransaction::TRANSACTIONTYPE), true); // if we're not supposed to process the content version error, then // overwrite that content...! if (!$editor->getProcessContentVersionError()) { $overwrite = true; } $document->setViewPolicy($v_view); $document->setEditPolicy($v_edit); $document->setSpacePHID($v_space); } } if ($document->getID()) { $page_title = pht('Edit Document: %s', $content->getTitle()); if ($overwrite) { $submit_button = pht('Overwrite Changes'); } else { $submit_button = pht('Save and Publish'); } } else { $submit_button = pht('Create Document'); $page_title = pht('Create Document'); } $uri = $document->getSlug(); $uri = PhrictionDocument::getSlugURI($uri); $uri = PhabricatorEnv::getProductionURI($uri); $cancel_uri = PhrictionDocument::getSlugURI($document->getSlug()); $policies = id(new PhabricatorPolicyQuery()) ->setViewer($viewer) ->setObject($document) ->execute(); $view_capability = PhabricatorPolicyCapability::CAN_VIEW; $edit_capability = PhabricatorPolicyCapability::CAN_EDIT; $form = id(new AphrontFormView()) ->setUser($viewer) ->addHiddenInput('slug', $document->getSlug()) ->addHiddenInput('contentVersion', $max_version) ->addHiddenInput('overwrite', $overwrite) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Title')) ->setValue($title) ->setError($e_title) ->setName('title')) ->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('URI')) ->setValue($uri)) ->appendChild( id(new PhabricatorRemarkupControl()) ->setLabel(pht('Content')) ->setValue($content_text) ->setError($e_content) ->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_TALL) ->setName('content') ->setID('document-textarea') ->setUser($viewer)) ->appendControl( id(new AphrontFormTokenizerControl()) ->setLabel(pht('Tags')) ->setName('projects') ->setValue($v_projects) ->setDatasource(new PhabricatorProjectDatasource())) ->appendControl( id(new AphrontFormTokenizerControl()) ->setLabel(pht('Subscribers')) ->setName('cc') ->setValue($v_cc) ->setUser($viewer) ->setDatasource(new PhabricatorMetaMTAMailableDatasource())) ->appendChild( id(new AphrontFormPolicyControl()) ->setViewer($viewer) ->setName('viewPolicy') ->setSpacePHID($v_space) ->setPolicyObject($document) ->setCapability($view_capability) ->setPolicies($policies)) ->appendChild( id(new AphrontFormPolicyControl()) ->setName('editPolicy') ->setPolicyObject($document) ->setCapability($edit_capability) ->setPolicies($policies)) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Edit Notes')) ->setValue($notes) ->setError(null) ->setName('description')); if ($is_draft_mode) { $form->appendControl( id(new AphrontFormSubmitControl()) ->addCancelButton($cancel_uri) ->setValue(pht('Save Draft'))); } else { $submit = id(new AphrontFormSubmitControl()); if (!$is_new) { $draft_button = id(new PHUIButtonView()) ->setTag('input') ->setName('draft') ->setText(pht('Save as Draft')) ->setColor(PHUIButtonView::GREEN); $submit->addButton($draft_button); } $submit ->addCancelButton($cancel_uri) ->setValue($submit_button); $form->appendControl($submit); } $form_box = id(new PHUIObjectBoxView()) ->setHeaderText($page_title) ->setValidationException($validation_exception) ->setBackground(PHUIObjectBoxView::WHITE_CONFIG) ->setForm($form); $preview_uri = '/phriction/preview/'; $preview_uri = new PhutilURI( $preview_uri, array( 'slug' => $document->getSlug(), )); $preview_uri = phutil_string_cast($preview_uri); $preview = id(new PHUIRemarkupPreviewPanel()) ->setHeader($content->getTitle()) ->setPreviewURI($preview_uri) ->setControlID('document-textarea') ->setPreviewType(PHUIRemarkupPreviewPanel::DOCUMENT); $crumbs = $this->buildApplicationCrumbs(); if ($document->getID()) { $crumbs->addTextCrumb( $content->getTitle(), PhrictionDocument::getSlugURI($document->getSlug())); $crumbs->addTextCrumb(pht('Edit')); } else { $crumbs->addTextCrumb(pht('Create')); } $crumbs->setBorder(true); $view = id(new PHUITwoColumnView()) ->setFooter( array( $form_box, $preview, )); return $this->newPage() ->setTitle($page_title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionMarkupPreviewController.php
src/applications/phriction/controller/PhrictionMarkupPreviewController.php
<?php final class PhrictionMarkupPreviewController extends PhabricatorController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $text = $request->getStr('text'); $slug = $request->getStr('slug'); $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withSlugs(array($slug)) ->needContent(true) ->executeOne(); if (!$document) { $document = PhrictionDocument::initializeNewDocument( $viewer, $slug); $content = id(new PhrictionContent()) ->setSlug($slug); $document ->setPHID($document->generatePHID()) ->attachContent($content); } $output = PhabricatorMarkupEngine::renderOneObject( id(new PhabricatorMarkupOneOff()) ->setPreserveLinebreaks(true) ->setDisableCache(true) ->setContent($text), 'default', $viewer, $document); return id(new AphrontAjaxResponse()) ->setContent($output); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionDocumentController.php
src/applications/phriction/controller/PhrictionDocumentController.php
<?php final class PhrictionDocumentController extends PhrictionController { private $slug; public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $this->slug = $request->getURIData('slug'); $slug = PhabricatorSlug::normalize($this->slug); if ($slug != $this->slug) { $uri = PhrictionDocument::getSlugURI($slug); // Canonicalize pages to their one true URI. return id(new AphrontRedirectResponse())->setURI($uri); } $version_note = null; $core_content = ''; $move_notice = ''; $properties = null; $content = null; $toc = null; $is_draft = false; $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withSlugs(array($slug)) ->needContent(true) ->executeOne(); if (!$document) { $document = PhrictionDocument::initializeNewDocument($viewer, $slug); if ($slug == '/') { $title = pht('Welcome to Phriction'); $subtitle = pht('Phriction is a simple and easy to use wiki for '. 'keeping track of documents and their changes.'); $page_title = pht('Welcome'); $create_text = pht('Edit this Document'); $this->setShowingWelcomeDocument(true); } else { $title = pht('No Document Here'); $subtitle = pht('There is no document here, but you may create it.'); $page_title = pht('Page Not Found'); $create_text = pht('Create this Document'); } $create_uri = '/phriction/edit/?slug='.$slug; $create_button = id(new PHUIButtonView()) ->setTag('a') ->setText($create_text) ->setHref($create_uri) ->setColor(PHUIButtonView::GREEN); $core_content = id(new PHUIBigInfoView()) ->setIcon('fa-book') ->setTitle($title) ->setDescription($subtitle) ->addAction($create_button); } else { $max_version = (int)$document->getMaxVersion(); $version = $request->getInt('v'); if ($version) { $content = id(new PhrictionContentQuery()) ->setViewer($viewer) ->withDocumentPHIDs(array($document->getPHID())) ->withVersions(array($version)) ->executeOne(); if (!$content) { return new Aphront404Response(); } // When the "v" parameter exists, the user is in history mode so we // show this header even if they're looking at the current version // of the document. This keeps the next/previous links working. $view_version = (int)$content->getVersion(); $published_version = (int)$document->getContent()->getVersion(); if ($view_version < $published_version) { $version_note = pht( 'You are viewing an older version of this document, as it '. 'appeared on %s.', phabricator_datetime($content->getDateCreated(), $viewer)); } else if ($view_version > $published_version) { $is_draft = true; $version_note = pht( 'You are viewing an unpublished draft of this document.'); } else { $version_note = pht( 'You are viewing the current published version of this document.'); } $version_note = array( phutil_tag( 'strong', array(), pht('Version %d of %d: ', $view_version, $max_version)), ' ', $version_note, ); $version_note = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->appendChild($version_note); $document_uri = new PhutilURI($document->getURI()); if ($view_version > 1) { $previous_uri = $document_uri->alter('v', ($view_version - 1)); } else { $previous_uri = null; } if ($view_version !== $published_version) { $current_uri = $document_uri->alter('v', $published_version); } else { $current_uri = null; } if ($view_version < $max_version) { $next_uri = $document_uri->alter('v', ($view_version + 1)); } else { $next_uri = null; } if ($view_version !== $max_version) { $draft_uri = $document_uri->alter('v', $max_version); } else { $draft_uri = null; } $button_bar = id(new PHUIButtonBarView()) ->addButton( id(new PHUIButtonView()) ->setTag('a') ->setColor('grey') ->setIcon('fa-backward') ->setDisabled(!$previous_uri) ->setHref($previous_uri) ->setText(pht('Previous'))) ->addButton( id(new PHUIButtonView()) ->setTag('a') ->setColor('grey') ->setIcon('fa-file-o') ->setDisabled(!$current_uri) ->setHref($current_uri) ->setText(pht('Published'))) ->addButton( id(new PHUIButtonView()) ->setTag('a') ->setColor('grey') ->setIcon('fa-forward', false) ->setDisabled(!$next_uri) ->setHref($next_uri) ->setText(pht('Next'))) ->addButton( id(new PHUIButtonView()) ->setTag('a') ->setColor('grey') ->setIcon('fa-fast-forward', false) ->setDisabled(!$draft_uri) ->setHref($draft_uri) ->setText(pht('Draft'))); require_celerity_resource('phui-document-view-css'); $version_note = array( $version_note, phutil_tag( 'div', array( 'class' => 'phui-document-version-navigation', ), $button_bar), ); } else { $content = $document->getContent(); if ($content->getVersion() < $document->getMaxVersion()) { $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $document, PhabricatorPolicyCapability::CAN_EDIT); if ($can_edit) { $document_uri = new PhutilURI($document->getURI()); $draft_uri = $document_uri->alter('v', $document->getMaxVersion()); $draft_link = phutil_tag( 'a', array( 'href' => $draft_uri, ), pht('View Draft Version')); $draft_link = phutil_tag('strong', array(), $draft_link); $version_note = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE) ->appendChild( array( pht('This document has unpublished draft changes.'), ' ', $draft_link, )); } } } $page_title = $content->getTitle(); $properties = $this ->buildPropertyListView($document, $content, $slug); $doc_status = $document->getStatus(); $current_status = $content->getChangeType(); if ($current_status == PhrictionChangeType::CHANGE_EDIT || $current_status == PhrictionChangeType::CHANGE_MOVE_HERE) { $remarkup_view = $content->newRemarkupView($viewer); $core_content = $remarkup_view->render(); $toc = $remarkup_view->getTableOfContents(); $toc = $this->getToc($toc); } else if ($current_status == PhrictionChangeType::CHANGE_DELETE) { $notice = new PHUIInfoView(); $notice->setSeverity(PHUIInfoView::SEVERITY_NOTICE); $notice->setTitle(pht('Document Deleted')); $notice->appendChild( pht('This document has been deleted. You can edit it to put new '. 'content here, or use history to revert to an earlier version.')); $core_content = $notice->render(); } else if ($current_status == PhrictionChangeType::CHANGE_STUB) { $notice = new PHUIInfoView(); $notice->setSeverity(PHUIInfoView::SEVERITY_NOTICE); $notice->setTitle(pht('Empty Document')); $notice->appendChild( pht('This document is empty. You can edit it to put some proper '. 'content here.')); $core_content = $notice->render(); } else if ($current_status == PhrictionChangeType::CHANGE_MOVE_AWAY) { $new_doc_id = $content->getChangeRef(); $slug_uri = null; // If the new document exists and the viewer can see it, provide a link // to it. Otherwise, render a generic message. $new_docs = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withIDs(array($new_doc_id)) ->execute(); if ($new_docs) { $new_doc = head($new_docs); $slug_uri = PhrictionDocument::getSlugURI($new_doc->getSlug()); } $notice = id(new PHUIInfoView()) ->setSeverity(PHUIInfoView::SEVERITY_NOTICE); if ($slug_uri) { $notice->appendChild( phutil_tag( 'p', array(), pht( 'This document has been moved to %s. You can edit it to put '. 'new content here, or use history to revert to an earlier '. 'version.', phutil_tag('a', array('href' => $slug_uri), $slug_uri)))); } else { $notice->appendChild( phutil_tag( 'p', array(), pht( 'This document has been moved. You can edit it to put new '. 'content here, or use history to revert to an earlier '. 'version.'))); } $core_content = $notice->render(); } else { throw new Exception(pht("Unknown document status '%s'!", $doc_status)); } } $children = $this->renderDocumentChildren($slug); $curtain = null; if ($document->getID()) { $curtain = $this->buildCurtain($document, $content); } $crumbs = $this->buildApplicationCrumbs(); $crumbs->setBorder(true); $crumb_views = $this->renderBreadcrumbs($slug); foreach ($crumb_views as $view) { $crumbs->addCrumb($view); } $header = id(new PHUIHeaderView()) ->setUser($viewer) ->setPolicyObject($document) ->setHeader($page_title); if ($is_draft) { $draft_tag = id(new PHUITagView()) ->setName(pht('Draft')) ->setIcon('fa-spinner') ->setColor('pink') ->setType(PHUITagView::TYPE_SHADE); $header->addTag($draft_tag); } else if ($content) { $header->setEpoch($content->getDateCreated()); } $prop_list = null; if ($properties) { $prop_list = new PHUIPropertyGroupView(); $prop_list->addPropertyList($properties); } $prop_list = phutil_tag_div('phui-document-view-pro-box', $prop_list); $page_content = id(new PHUIDocumentView()) ->setBanner($version_note) ->setHeader($header) ->setToc($toc) ->appendChild( array( $move_notice, $core_content, )); if ($curtain) { $page_content->setCurtain($curtain); } if ($document->getPHID()) { $timeline = $this->buildTransactionTimeline( $document, new PhrictionTransactionQuery()); $edit_engine = id(new PhrictionDocumentEditEngine()) ->setViewer($viewer) ->setTargetObject($document); $comment_view = $edit_engine ->buildEditEngineCommentView($document); } else { $timeline = null; $comment_view = null; } return $this->newPage() ->setTitle($page_title) ->setCrumbs($crumbs) ->setPageObjectPHIDs(array($document->getPHID())) ->appendChild( array( $page_content, $prop_list, phutil_tag( 'div', array( 'class' => 'phui-document-view-pro-box', ), array( $children, $timeline, $comment_view, )), )); } private function buildPropertyListView( PhrictionDocument $document, PhrictionContent $content, $slug) { $viewer = $this->getViewer(); $view = id(new PHUIPropertyListView()) ->setUser($viewer); $view->addProperty( pht('Last Author'), $viewer->renderHandle($content->getAuthorPHID())); $view->addProperty( pht('Last Edited'), phabricator_dual_datetime($content->getDateCreated(), $viewer)); return $view; } private function buildCurtain( PhrictionDocument $document, PhrictionContent $content) { $viewer = $this->getViewer(); $can_edit = PhabricatorPolicyFilter::hasCapability( $viewer, $document, PhabricatorPolicyCapability::CAN_EDIT); $slug = PhabricatorSlug::normalize($this->slug); $id = $document->getID(); $curtain = $this->newCurtainView($document); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Edit Document')) ->setDisabled(!$can_edit) ->setIcon('fa-pencil') ->setHref('/phriction/edit/'.$document->getID().'/')); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('View History')) ->setIcon('fa-history') ->setHref(PhrictionDocument::getSlugURI($slug, 'history'))); $is_current = false; $content_id = null; $is_draft = false; if ($content) { if ($content->getPHID() == $document->getContentPHID()) { $is_current = true; } $content_id = $content->getID(); $current_version = $document->getContent()->getVersion(); $is_draft = ($content->getVersion() >= $current_version); } $can_publish = ($can_edit && $content && !$is_current); if ($is_draft) { $publish_name = pht('Publish Draft'); } else { $publish_name = pht('Publish Older Version'); } // If you're looking at the current version; and it's an unpublished // draft; and you can publish it, add a UI hint that this might be an // interesting action to take. $hint_publish = false; if ($is_draft) { if ($can_publish) { if ($document->getMaxVersion() == $content->getVersion()) { $hint_publish = true; } } } $publish_uri = "/phriction/publish/{$id}/{$content_id}/"; $curtain->addAction( id(new PhabricatorActionView()) ->setName($publish_name) ->setIcon('fa-upload') ->setSelected($hint_publish) ->setDisabled(!$can_publish) ->setWorkflow(true) ->setHref($publish_uri)); if ($document->getStatus() == PhrictionDocumentStatus::STATUS_EXISTS) { $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Move Document')) ->setDisabled(!$can_edit) ->setIcon('fa-arrows') ->setHref('/phriction/move/'.$document->getID().'/') ->setWorkflow(true)); $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Delete Document')) ->setDisabled(!$can_edit) ->setIcon('fa-times') ->setHref('/phriction/delete/'.$document->getID().'/') ->setWorkflow(true)); } $print_uri = PhrictionDocument::getSlugURI($slug).'?__print__=1'; $curtain->addAction( id(new PhabricatorActionView()) ->setName(pht('Printable Page')) ->setIcon('fa-print') ->setOpenInNewWindow(true) ->setHref($print_uri)); return $curtain; } private function renderDocumentChildren($slug) { $d_child = PhabricatorSlug::getDepth($slug) + 1; $d_grandchild = PhabricatorSlug::getDepth($slug) + 2; $limit = 250; $query = id(new PhrictionDocumentQuery()) ->setViewer($this->getRequest()->getUser()) ->withDepths(array($d_child, $d_grandchild)) ->withSlugPrefix($slug == '/' ? '' : $slug) ->withStatuses(array( PhrictionDocumentStatus::STATUS_EXISTS, PhrictionDocumentStatus::STATUS_STUB, )) ->setLimit($limit) ->setOrder(PhrictionDocumentQuery::ORDER_HIERARCHY) ->needContent(true); $children = $query->execute(); if (!$children) { return; } // We're going to render in one of three modes to try to accommodate // different information scales: // // - If we found fewer than $limit rows, we know we have all the children // and grandchildren and there aren't all that many. We can just render // everything. // - If we found $limit rows but the results included some grandchildren, // we just throw them out and render only the children, as we know we // have them all. // - If we found $limit rows and the results have no grandchildren, we // have a ton of children. Render them and then let the user know that // this is not an exhaustive list. if (count($children) == $limit) { $more_children = true; foreach ($children as $child) { if ($child->getDepth() == $d_grandchild) { $more_children = false; } } $show_grandchildren = false; } else { $show_grandchildren = true; $more_children = false; } $children_dicts = array(); $grandchildren_dicts = array(); foreach ($children as $key => $child) { $child_dict = array( 'slug' => $child->getSlug(), 'depth' => $child->getDepth(), 'title' => $child->getContent()->getTitle(), ); if ($child->getDepth() == $d_child) { $children_dicts[] = $child_dict; continue; } else { unset($children[$key]); if ($show_grandchildren) { $ancestors = PhabricatorSlug::getAncestry($child->getSlug()); $grandchildren_dicts[end($ancestors)][] = $child_dict; } } } // Fill in any missing children. $known_slugs = mpull($children, null, 'getSlug'); foreach ($grandchildren_dicts as $slug => $ignored) { if (empty($known_slugs[$slug])) { $children_dicts[] = array( 'slug' => $slug, 'depth' => $d_child, 'title' => PhabricatorSlug::getDefaultTitle($slug), 'empty' => true, ); } } $children_dicts = isort($children_dicts, 'title'); $list = array(); foreach ($children_dicts as $child) { $list[] = hsprintf('<li class="remarkup-list-item">'); $list[] = $this->renderChildDocumentLink($child); $grand = idx($grandchildren_dicts, $child['slug'], array()); if ($grand) { $list[] = hsprintf('<ul class="remarkup-list">'); foreach ($grand as $grandchild) { $list[] = hsprintf('<li class="remarkup-list-item">'); $list[] = $this->renderChildDocumentLink($grandchild); $list[] = hsprintf('</li>'); } $list[] = hsprintf('</ul>'); } $list[] = hsprintf('</li>'); } if ($more_children) { $list[] = phutil_tag( 'li', array( 'class' => 'remarkup-list-item', ), pht('More...')); } $header = id(new PHUIHeaderView()) ->setHeader(pht('Document Hierarchy')); $box = id(new PHUIObjectBoxView()) ->setHeader($header) ->appendChild(phutil_tag( 'div', array( 'class' => 'phabricator-remarkup mlt mlb', ), phutil_tag( 'ul', array( 'class' => 'remarkup-list', ), $list))); return $box; } private function renderChildDocumentLink(array $info) { $title = nonempty($info['title'], pht('(Untitled Document)')); $item = phutil_tag( 'a', array( 'href' => PhrictionDocument::getSlugURI($info['slug']), ), $title); if (isset($info['empty'])) { $item = phutil_tag('em', array(), $item); } return $item; } protected function getDocumentSlug() { return $this->slug; } protected function getToc($toc) { if ($toc) { $toc = phutil_tag_div('phui-document-toc-content', array( phutil_tag_div( 'phui-document-toc-header', pht('Contents')), $toc, )); } return $toc; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionListController.php
src/applications/phriction/controller/PhrictionListController.php
<?php final class PhrictionListController extends PhrictionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $querykey = $request->getURIData('queryKey'); $controller = id(new PhabricatorApplicationSearchController()) ->setQueryKey($querykey) ->setSearchEngine(new PhrictionDocumentSearchEngine()) ->setNavigation($this->buildSideNavView()); return $this->delegateToController($controller); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionPublishController.php
src/applications/phriction/controller/PhrictionPublishController.php
<?php final class PhrictionPublishController extends PhrictionController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('documentID'); $content_id = $request->getURIData('contentID'); $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withIDs(array($id)) ->needContent(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_EDIT, PhabricatorPolicyCapability::CAN_VIEW, )) ->executeOne(); if (!$document) { return new Aphront404Response(); } $document_uri = $document->getURI(); $content = id(new PhrictionContentQuery()) ->setViewer($viewer) ->withIDs(array($content_id)) ->executeOne(); if (!$content) { return new Aphront404Response(); } if ($content->getPHID() == $document->getContentPHID()) { return $this->newDialog() ->setTitle(pht('Already Published')) ->appendChild( pht( 'This version of the document is already the published '. 'version.')) ->addCancelButton($document_uri); } $content_uri = $document_uri.'?v='.$content->getVersion(); if ($request->isFormPost()) { $xactions = array(); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentPublishTransaction::TRANSACTIONTYPE) ->setNewValue($content->getPHID()); id(new PhrictionTransactionEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->applyTransactions($document, $xactions); return id(new AphrontRedirectResponse())->setURI($document_uri); } if ($content->getVersion() < $document->getContent()->getVersion()) { $title = pht('Publish Older Version?'); $body = pht( 'Revert the published version of this document to an older '. 'version?'); $button = pht('Revert'); } else { $title = pht('Publish Draft?'); $body = pht( 'Update the published version of this document to this newer '. 'version?'); $button = pht('Publish'); } return $this->newDialog() ->setTitle($title) ->appendChild($body) ->addSubmitButton($button) ->addCancelButton($content_uri); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionController.php
src/applications/phriction/controller/PhrictionController.php
<?php abstract class PhrictionController extends PhabricatorController { private $showingWelcomeDocument = false; public function setShowingWelcomeDocument($show_welcome) { $this->showingWelcomeDocument = $show_welcome; return $this; } public function buildSideNavView($for_app = false) { $user = $this->getRequest()->getUser(); $nav = new AphrontSideNavFilterView(); $nav->setBaseURI(new PhutilURI($this->getApplicationURI())); if ($for_app) { $nav->addFilter('create', pht('New Document')); $nav->addFilter('/phriction/', pht('Index')); } id(new PhrictionDocumentSearchEngine()) ->setViewer($user) ->addNavigationItems($nav->getMenu()); $nav->selectFilter(null); return $nav; } public function buildApplicationMenu() { return $this->buildSideNavView(true)->getMenu(); } protected function buildApplicationCrumbs() { $crumbs = parent::buildApplicationCrumbs(); if (get_class($this) != 'PhrictionListController') { $crumbs->addAction( id(new PHUIListItemView()) ->setName(pht('Index')) ->setHref('/phriction/') ->setIcon('fa-home')); } if (!$this->showingWelcomeDocument) { $crumbs->addAction( id(new PHUIListItemView()) ->setName(pht('New Document')) ->setHref('/phriction/new/?slug='.$this->getDocumentSlug()) ->setWorkflow(true) ->setIcon('fa-plus-square')); } return $crumbs; } public function renderBreadcrumbs($slug) { $ancestor_handles = array(); $ancestral_slugs = PhabricatorSlug::getAncestry($slug); $ancestral_slugs[] = $slug; if ($ancestral_slugs) { $empty_slugs = array_fill_keys($ancestral_slugs, null); $ancestors = id(new PhrictionDocumentQuery()) ->setViewer($this->getRequest()->getUser()) ->withSlugs($ancestral_slugs) ->execute(); $ancestors = mpull($ancestors, null, 'getSlug'); $ancestor_phids = mpull($ancestors, 'getPHID'); $handles = array(); if ($ancestor_phids) { $handles = $this->loadViewerHandles($ancestor_phids); } $ancestor_handles = array(); foreach ($ancestral_slugs as $slug) { if (isset($ancestors[$slug])) { $ancestor_handles[] = $handles[$ancestors[$slug]->getPHID()]; } else { $handle = new PhabricatorObjectHandle(); $handle->setName(PhabricatorSlug::getDefaultTitle($slug)); $handle->setURI(PhrictionDocument::getSlugURI($slug)); $ancestor_handles[] = $handle; } } } $breadcrumbs = array(); foreach ($ancestor_handles as $ancestor_handle) { $breadcrumbs[] = id(new PHUICrumbView()) ->setName($ancestor_handle->getName()) ->setHref($ancestor_handle->getUri()); } return $breadcrumbs; } protected function getDocumentSlug() { return ''; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionHistoryController.php
src/applications/phriction/controller/PhrictionHistoryController.php
<?php final class PhrictionHistoryController extends PhrictionController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $slug = $request->getURIData('slug'); $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withSlugs(array(PhabricatorSlug::normalize($slug))) ->needContent(true) ->executeOne(); if (!$document) { return new Aphront404Response(); } $current = $document->getContent(); $pager = id(new AphrontCursorPagerView()) ->readFromRequest($request); $history = id(new PhrictionContentQuery()) ->setViewer($viewer) ->withDocumentPHIDs(array($document->getPHID())) ->executeWithCursorPager($pager); $author_phids = mpull($history, 'getAuthorPHID'); $handles = $viewer->loadHandles($author_phids); $max_version = (int)$document->getMaxVersion(); $current_version = $document->getContent()->getVersion(); $list = new PHUIObjectItemListView(); $list->setFlush(true); foreach ($history as $content) { $slug_uri = PhrictionDocument::getSlugURI($document->getSlug()); $version = $content->getVersion(); $base_uri = new PhutilURI('/phriction/diff/'.$document->getID().'/'); $change_type = PhrictionChangeType::getChangeTypeLabel( $content->getChangeType()); switch ($content->getChangeType()) { case PhrictionChangeType::CHANGE_DELETE: $color = 'red'; break; case PhrictionChangeType::CHANGE_EDIT: $color = 'lightbluetext'; break; case PhrictionChangeType::CHANGE_MOVE_HERE: $color = 'yellow'; break; case PhrictionChangeType::CHANGE_MOVE_AWAY: $color = 'orange'; break; case PhrictionChangeType::CHANGE_STUB: $color = 'green'; break; default: $color = 'indigo'; break; } $version_uri = $slug_uri.'?v='.$version; $item = id(new PHUIObjectItemView()) ->setHref($version_uri); if ($version > $current_version) { $icon = 'fa-spinner'; $color = 'pink'; $header = pht('Draft %d', $version); } else { $icon = 'fa-file-o'; $header = pht('Version %d', $version); } if ($version == $current_version) { $item->setEffect('selected'); } $item ->setHeader($header) ->setStatusIcon($icon.' '.$color); $description = $content->getDescription(); if (strlen($description)) { $item->addAttribute($description); } $item->addIcon( null, phabricator_datetime($content->getDateCreated(), $viewer)); $author_phid = $content->getAuthorPHID(); $item->addByline($viewer->renderHandle($author_phid)); $diff_uri = null; if ($version > 1) { $diff_uri = $base_uri ->alter('l', $version - 1) ->alter('r', $version); } else { $diff_uri = null; } if ($content->getVersion() != $max_version) { $compare_uri = $base_uri ->alter('l', $version) ->alter('r', $max_version); } else { $compare_uri = null; } $button_bar = id(new PHUIButtonBarView()) ->addButton( id(new PHUIButtonView()) ->setTag('a') ->setColor('grey') ->setIcon('fa-chevron-down') ->setDisabled(!$diff_uri) ->setHref($diff_uri) ->setText(pht('Diff'))) ->addButton( id(new PHUIButtonView()) ->setTag('a') ->setColor('grey') ->setIcon('fa-chevron-circle-up') ->setDisabled(!$compare_uri) ->setHref($compare_uri) ->setText(pht('Compare'))); $item->setSideColumn($button_bar); $list->addItem($item); } $crumbs = $this->buildApplicationCrumbs(); $crumb_views = $this->renderBreadcrumbs($document->getSlug()); foreach ($crumb_views as $view) { $crumbs->addCrumb($view); } $crumbs->addTextCrumb( pht('History'), PhrictionDocument::getSlugURI($document->getSlug(), 'history')); $crumbs->setBorder(true); $header = new PHUIHeaderView(); $header->setHeader(phutil_tag( 'a', array('href' => PhrictionDocument::getSlugURI($document->getSlug())), head($history)->getTitle())); $header->setSubheader(pht('Document History')); $obj_box = id(new PHUIObjectBoxView()) ->setBackground(PHUIObjectBoxView::BLUE_PROPERTY) ->setObjectList($list); $pager = id(new PHUIBoxView()) ->addClass('ml') ->appendChild($pager); $header = id(new PHUIHeaderView()) ->setHeader(pht('Document History: %s', head($history)->getTitle())) ->setHeaderIcon('fa-history'); $view = id(new PHUITwoColumnView()) ->setHeader($header) ->setFooter(array( $obj_box, $pager, )); $title = pht('Document History'); return $this->newPage() ->setTitle($title) ->setCrumbs($crumbs) ->appendChild($view); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionMoveController.php
src/applications/phriction/controller/PhrictionMoveController.php
<?php final class PhrictionMoveController extends PhrictionController { public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withIDs(array($request->getURIData('id'))) ->needContent(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$document) { return new Aphront404Response(); } $slug = $document->getSlug(); $cancel_uri = PhrictionDocument::getSlugURI($slug); $v_slug = $slug; $e_slug = null; $v_note = ''; $validation_exception = null; if ($request->isFormPost()) { $v_note = $request->getStr('description'); $v_slug = $request->getStr('slug'); $normal_slug = PhabricatorSlug::normalize($v_slug); // If what the user typed isn't what we're actually using, warn them // about it. if (strlen($v_slug)) { $no_slash_slug = rtrim($normal_slug, '/'); if ($normal_slug !== $v_slug && $no_slash_slug !== $v_slug) { return $this->newDialog() ->setTitle(pht('Adjust Path')) ->appendParagraph( pht( 'The path you entered (%s) is not a valid wiki document '. 'path. Paths may not contain spaces or special characters.', phutil_tag('strong', array(), $v_slug))) ->appendParagraph( pht( 'Would you like to use the path %s instead?', phutil_tag('strong', array(), $normal_slug))) ->addHiddenInput('slug', $normal_slug) ->addHiddenInput('description', $v_note) ->addCancelButton($cancel_uri) ->addSubmitButton(pht('Accept Path')); } } $editor = id(new PhrictionTransactionEditor()) ->setActor($viewer) ->setContentSourceFromRequest($request) ->setContinueOnNoEffect(true) ->setContinueOnMissingFields(true) ->setDescription($v_note); $xactions = array(); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentMoveToTransaction::TRANSACTIONTYPE) ->setNewValue($document); $target_document = id(new PhrictionDocumentQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withSlugs(array($normal_slug)) ->needContent(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$target_document) { $target_document = PhrictionDocument::initializeNewDocument( $viewer, $v_slug); } try { $editor->applyTransactions($target_document, $xactions); $redir_uri = PhrictionDocument::getSlugURI( $target_document->getSlug()); return id(new AphrontRedirectResponse())->setURI($redir_uri); } catch (PhabricatorApplicationTransactionValidationException $ex) { $validation_exception = $ex; $e_slug = $ex->getShortMessage( PhrictionDocumentMoveToTransaction::TRANSACTIONTYPE); } } $form = id(new AphrontFormView()) ->setUser($viewer) ->appendChild( id(new AphrontFormStaticControl()) ->setLabel(pht('Title')) ->setValue($document->getContent()->getTitle())) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Current Path')) ->setDisabled(true) ->setValue($slug)) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('New Path')) ->setValue($v_slug) ->setError($e_slug) ->setName('slug')) ->appendChild( id(new AphrontFormTextControl()) ->setLabel(pht('Edit Notes')) ->setValue($v_note) ->setName('description')); return $this->newDialog() ->setTitle(pht('Move Document')) ->setValidationException($validation_exception) ->appendForm($form) ->addSubmitButton(pht('Move Document')) ->addCancelButton($cancel_uri); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/controller/PhrictionNewController.php
src/applications/phriction/controller/PhrictionNewController.php
<?php final class PhrictionNewController extends PhrictionController { public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $slug = PhabricatorSlug::normalize($request->getStr('slug')); if ($request->isFormPost()) { $document = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withSlugs(array($slug)) ->executeOne(); $prompt = $request->getStr('prompt', 'no'); $document_exists = $document && $document->getStatus() == PhrictionDocumentStatus::STATUS_EXISTS; if ($document_exists && $prompt == 'no') { return $this->newDialog() ->setSubmitURI('/phriction/new/') ->setTitle(pht('Edit Existing Document?')) ->setUser($viewer) ->appendChild(pht( 'The document %s already exists. Do you want to edit it instead?', phutil_tag('tt', array(), $slug))) ->addHiddenInput('slug', $slug) ->addHiddenInput('prompt', 'yes') ->addCancelButton('/w/') ->addSubmitButton(pht('Edit Document')); } $uri = '/phriction/edit/?slug='.$slug; return id(new AphrontRedirectResponse()) ->setURI($uri); } if ($slug == '/') { $slug = ''; } $view = id(new PHUIFormLayoutView()) ->appendChild(id(new AphrontFormTextControl()) ->setLabel('/w/') ->setValue($slug) ->setName('slug')); return $this->newDialog() ->setTitle(pht('New Document')) ->setSubmitURI('/phriction/new/') ->appendChild(phutil_tag('p', array(), pht('Create a new document at'))) ->appendChild($view) ->addSubmitButton(pht('Create')) ->addCancelButton('/w/'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/engineextension/PhrictionDatasourceEngineExtension.php
src/applications/phriction/engineextension/PhrictionDatasourceEngineExtension.php
<?php final class PhrictionDatasourceEngineExtension extends PhabricatorDatasourceEngineExtension { public function newQuickSearchDatasources() { return array( new PhrictionDocumentDatasource(), ); } public function newJumpURI($query) { $viewer = $this->getViewer(); // Send "w" to Phriction. if (preg_match('/^w\z/i', $query)) { return '/w/'; } // Send "w <string>" to a search for similar wiki documents. $matches = null; if (preg_match('/^w\s+(.+)\z/i', $query, $matches)) { $raw_query = $matches[1]; $engine = id(new PhrictionDocument()) ->newFerretEngine(); $compiler = id(new PhutilSearchQueryCompiler()) ->setEnableFunctions(true); $raw_tokens = $compiler->newTokens($raw_query); $fulltext_tokens = array(); foreach ($raw_tokens as $raw_token) { $fulltext_token = id(new PhabricatorFulltextToken()) ->setToken($raw_token); $fulltext_tokens[] = $fulltext_token; } $documents = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withFerretConstraint($engine, $fulltext_tokens) ->execute(); if (count($documents) == 1) { return head($documents)->getURI(); } else { // More than one match, jump to search. return urisprintf( '/phriction/?order=relevance&query=%s#R', $raw_query); } } 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/phriction/engineextension/PhrictionContentSearchEngineAttachment.php
src/applications/phriction/engineextension/PhrictionContentSearchEngineAttachment.php
<?php final class PhrictionContentSearchEngineAttachment extends PhabricatorSearchEngineAttachment { public function getAttachmentName() { return pht('Document Content'); } public function getAttachmentDescription() { return pht('Get the content of documents or document histories.'); } public function getAttachmentForObject($object, $data, $spec) { if ($object instanceof PhrictionDocument) { $content = $object->getContent(); } else { $content = $object; } return array( 'title' => $content->getTitle(), 'path' => $content->getSlug(), 'authorPHID' => $content->getAuthorPHID(), 'content' => array( 'raw' => $content->getContent(), ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/storage/PhrictionTransaction.php
src/applications/phriction/storage/PhrictionTransaction.php
<?php final class PhrictionTransaction extends PhabricatorModularTransaction { const MAILTAG_TITLE = 'phriction-title'; const MAILTAG_CONTENT = 'phriction-content'; const MAILTAG_DELETE = 'phriction-delete'; const MAILTAG_SUBSCRIBERS = 'phriction-subscribers'; const MAILTAG_OTHER = 'phriction-other'; public function getApplicationName() { return 'phriction'; } public function getApplicationTransactionType() { return PhrictionDocumentPHIDType::TYPECONST; } public function getApplicationTransactionCommentObject() { return new PhrictionTransactionComment(); } public function getBaseTransactionClass() { return 'PhrictionDocumentTransactionType'; } public function getRequiredHandlePHIDs() { $phids = parent::getRequiredHandlePHIDs(); $new = $this->getNewValue(); switch ($this->getTransactionType()) { case PhrictionDocumentMoveToTransaction::TRANSACTIONTYPE: case PhrictionDocumentMoveAwayTransaction::TRANSACTIONTYPE: $phids[] = $new['phid']; break; case PhrictionDocumentTitleTransaction::TRANSACTIONTYPE: if ($this->getMetadataValue('stub:create:phid')) { $phids[] = $this->getMetadataValue('stub:create:phid'); } break; } return $phids; } public function shouldHideForMail(array $xactions) { switch ($this->getTransactionType()) { case PhrictionDocumentMoveToTransaction::TRANSACTIONTYPE: case PhrictionDocumentMoveAwayTransaction::TRANSACTIONTYPE: return true; case PhrictionDocumentTitleTransaction::TRANSACTIONTYPE: return $this->getMetadataValue('stub:create:phid', false); } return parent::shouldHideForMail($xactions); } public function getMailTags() { $tags = array(); switch ($this->getTransactionType()) { case PhrictionDocumentTitleTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_TITLE; break; case PhrictionDocumentContentTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_CONTENT; break; case PhrictionDocumentDeleteTransaction::TRANSACTIONTYPE: $tags[] = self::MAILTAG_DELETE; break; case PhabricatorTransactions::TYPE_SUBSCRIBERS: $tags[] = self::MAILTAG_SUBSCRIBERS; 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/phriction/storage/PhrictionDocument.php
src/applications/phriction/storage/PhrictionDocument.php
<?php final class PhrictionDocument extends PhrictionDAO implements PhabricatorPolicyInterface, PhabricatorSubscribableInterface, PhabricatorFlaggableInterface, PhabricatorTokenReceiverInterface, PhabricatorDestructibleInterface, PhabricatorFulltextInterface, PhabricatorFerretInterface, PhabricatorProjectInterface, PhabricatorApplicationTransactionInterface, PhabricatorConduitResultInterface, PhabricatorPolicyCodexInterface, PhabricatorSpacesInterface { protected $slug; protected $depth; protected $contentPHID; protected $status; protected $viewPolicy; protected $editPolicy; protected $spacePHID; protected $editedEpoch; protected $maxVersion; private $contentObject = self::ATTACHABLE; private $ancestors = array(); protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'slug' => 'sort128', 'depth' => 'uint32', 'status' => 'text32', 'editedEpoch' => 'epoch', 'maxVersion' => 'uint32', ), self::CONFIG_KEY_SCHEMA => array( 'slug' => array( 'columns' => array('slug'), 'unique' => true, ), 'depth' => array( 'columns' => array('depth', 'slug'), 'unique' => true, ), ), ) + parent::getConfiguration(); } public function getPHIDType() { return PhrictionDocumentPHIDType::TYPECONST; } public static function initializeNewDocument(PhabricatorUser $actor, $slug) { $document = id(new self()) ->setSlug($slug); $content = id(new PhrictionContent()) ->setSlug($slug); $default_title = PhabricatorSlug::getDefaultTitle($slug); $content->setTitle($default_title); $document->attachContent($content); $parent_doc = null; $ancestral_slugs = PhabricatorSlug::getAncestry($slug); if ($ancestral_slugs) { $parent = end($ancestral_slugs); $parent_doc = id(new PhrictionDocumentQuery()) ->setViewer($actor) ->withSlugs(array($parent)) ->executeOne(); } if ($parent_doc) { $space_phid = PhabricatorSpacesNamespaceQuery::getObjectSpacePHID( $parent_doc); $document ->setViewPolicy($parent_doc->getViewPolicy()) ->setEditPolicy($parent_doc->getEditPolicy()) ->setSpacePHID($space_phid); } else { $default_view_policy = PhabricatorPolicies::getMostOpenPolicy(); $document ->setViewPolicy($default_view_policy) ->setEditPolicy(PhabricatorPolicies::POLICY_USER) ->setSpacePHID($actor->getDefaultSpacePHID()); } $document->setEditedEpoch(PhabricatorTime::getNow()); $document->setMaxVersion(0); return $document; } public static function getSlugURI($slug, $type = 'document') { static $types = array( 'document' => '/w/', 'history' => '/phriction/history/', ); if (empty($types[$type])) { throw new Exception(pht("Unknown URI type '%s'!", $type)); } $prefix = $types[$type]; if ($slug == '/') { return $prefix; } else { // NOTE: The effect here is to escape non-latin characters, since modern // browsers deal with escaped UTF8 characters in a reasonable way (showing // the user a readable URI) but older programs may not. $slug = phutil_escape_uri($slug); return $prefix.$slug; } } public function setSlug($slug) { $this->slug = PhabricatorSlug::normalize($slug); $this->depth = PhabricatorSlug::getDepth($slug); return $this; } public function attachContent(PhrictionContent $content) { $this->contentObject = $content; return $this; } public function getContent() { return $this->assertAttached($this->contentObject); } public function getAncestors() { return $this->ancestors; } public function getAncestor($slug) { return $this->assertAttachedKey($this->ancestors, $slug); } public function attachAncestor($slug, $ancestor) { $this->ancestors[$slug] = $ancestor; return $this; } public function getURI() { return self::getSlugURI($this->getSlug()); } /* -( Status )------------------------------------------------------------- */ public function getStatusObject() { return PhrictionDocumentStatus::newStatusObject($this->getStatus()); } public function getStatusIcon() { return $this->getStatusObject()->getIcon(); } public function getStatusColor() { return $this->getStatusObject()->getColor(); } public function getStatusDisplayName() { return $this->getStatusObject()->getDisplayName(); } public function isActive() { return $this->getStatusObject()->isActive(); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, ); } public function getPolicy($capability) { switch ($capability) { case PhabricatorPolicyCapability::CAN_VIEW: return $this->getViewPolicy(); case PhabricatorPolicyCapability::CAN_EDIT: return $this->getEditPolicy(); } } public function hasAutomaticCapability($capability, PhabricatorUser $user) { return false; } /* -( PhabricatorSpacesInterface )----------------------------------------- */ public function getSpacePHID() { return $this->spacePHID; } /* -( PhabricatorSubscribableInterface )----------------------------------- */ public function isAutomaticallySubscribed($phid) { return false; } /* -( PhabricatorApplicationTransactionInterface )------------------------- */ public function getApplicationTransactionEditor() { return new PhrictionTransactionEditor(); } public function getApplicationTransactionTemplate() { return new PhrictionTransaction(); } /* -( PhabricatorTokenReceiverInterface )---------------------------------- */ public function getUsersToNotifyOfTokenGiven() { return PhabricatorSubscribersQuery::loadSubscribersForPHID($this->phid); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->openTransaction(); $contents = id(new PhrictionContentQuery()) ->setViewer($engine->getViewer()) ->withDocumentPHIDs(array($this->getPHID())) ->execute(); foreach ($contents as $content) { $engine->destroyObject($content); } $this->delete(); $this->saveTransaction(); } /* -( PhabricatorFulltextInterface )--------------------------------------- */ public function newFulltextEngine() { return new PhrictionDocumentFulltextEngine(); } /* -( PhabricatorFerretInterface )----------------------------------------- */ public function newFerretEngine() { return new PhrictionDocumentFerretEngine(); } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('path') ->setType('string') ->setDescription(pht('The path to the document.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('status') ->setType('map<string, wild>') ->setDescription(pht('Status information about the document.')), ); } public function getFieldValuesForConduit() { $status = array( 'value' => $this->getStatus(), 'name' => $this->getStatusDisplayName(), ); return array( 'path' => $this->getSlug(), 'status' => $status, ); } public function getConduitSearchAttachments() { return array( id(new PhrictionContentSearchEngineAttachment()) ->setAttachmentKey('content'), ); } /* -( PhabricatorPolicyCodexInterface )------------------------------------ */ public function newPolicyCodex() { return new PhrictionDocumentPolicyCodex(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/storage/PhrictionSchemaSpec.php
src/applications/phriction/storage/PhrictionSchemaSpec.php
<?php final class PhrictionSchemaSpec extends PhabricatorConfigSchemaSpec { public function buildSchemata() { $this->buildEdgeSchemata(new PhrictionDocument()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/storage/PhrictionContent.php
src/applications/phriction/storage/PhrictionContent.php
<?php final class PhrictionContent extends PhrictionDAO implements PhabricatorPolicyInterface, PhabricatorDestructibleInterface, PhabricatorConduitResultInterface { protected $documentPHID; protected $version; protected $authorPHID; protected $title; protected $slug; protected $content; protected $description; protected $changeType; protected $changeRef; private $document = self::ATTACHABLE; protected function getConfiguration() { return array( self::CONFIG_AUX_PHID => true, self::CONFIG_COLUMN_SCHEMA => array( 'version' => 'uint32', 'title' => 'sort', 'slug' => 'text128', 'content' => 'text', 'changeType' => 'uint32', 'changeRef' => 'uint32?', 'description' => 'text', ), self::CONFIG_KEY_SCHEMA => array( 'key_version' => array( 'columns' => array('documentPHID', 'version'), 'unique' => true, ), 'authorPHID' => array( 'columns' => array('authorPHID'), ), 'slug' => array( 'columns' => array('slug'), ), ), ) + parent::getConfiguration(); } public function getPHIDType() { return PhrictionContentPHIDType::TYPECONST; } public function newRemarkupView(PhabricatorUser $viewer) { return id(new PHUIRemarkupView($viewer, $this->getContent())) ->setContextObject($this) ->setRemarkupOption(PHUIRemarkupView::OPTION_GENERATE_TOC, true) ->setGenerateTableOfContents(true); } public function attachDocument(PhrictionDocument $document) { $this->document = $document; return $this; } public function getDocument() { return $this->assertAttached($this->document); } /* -( PhabricatorPolicyInterface )----------------------------------------- */ public function getCapabilities() { return array( PhabricatorPolicyCapability::CAN_VIEW, ); } public function getPolicy($capability) { return PhabricatorPolicies::getMostOpenPolicy(); } public function hasAutomaticCapability($capability, PhabricatorUser $viewer) { return false; } /* -( PhabricatorExtendedPolicyInterface )--------------------------------- */ public function getExtendedPolicy($capability, PhabricatorUser $viewer) { return array( array($this->getDocument(), PhabricatorPolicyCapability::CAN_VIEW), ); } /* -( PhabricatorDestructibleInterface )----------------------------------- */ public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { $this->delete(); } /* -( PhabricatorConduitResultInterface )---------------------------------- */ public function getFieldSpecificationsForConduit() { return array( id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('documentPHID') ->setType('phid') ->setDescription(pht('Document this content is for.')), id(new PhabricatorConduitSearchFieldSpecification()) ->setKey('version') ->setType('int') ->setDescription(pht('Content version.')), ); } public function getFieldValuesForConduit() { return array( 'documentPHID' => $this->getDocument()->getPHID(), 'version' => (int)$this->getVersion(), ); } public function getConduitSearchAttachments() { return array( id(new PhrictionContentSearchEngineAttachment()) ->setAttachmentKey('content'), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/storage/PhrictionTransactionComment.php
src/applications/phriction/storage/PhrictionTransactionComment.php
<?php final class PhrictionTransactionComment extends PhabricatorApplicationTransactionComment { public function getApplicationTransactionObject() { return new PhrictionTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/storage/PhrictionDAO.php
src/applications/phriction/storage/PhrictionDAO.php
<?php abstract class PhrictionDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'phriction'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/query/PhrictionContentSearchEngine.php
src/applications/phriction/query/PhrictionContentSearchEngine.php
<?php final class PhrictionContentSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Phriction Document Content'); } public function getApplicationClassName() { return 'PhabricatorPhrictionApplication'; } public function newQuery() { return new PhrictionContentQuery(); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['documentPHIDs']) { $query->withDocumentPHIDs($map['documentPHIDs']); } if ($map['versions']) { $query->withVersions($map['versions']); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorPHIDsSearchField()) ->setKey('documentPHIDs') ->setAliases(array('document', 'documents', 'documentPHID')) ->setLabel(pht('Documents')), id(new PhabricatorIDsSearchField()) ->setKey('versions') ->setAliases(array('version')), ); } protected function getURI($path) { // There's currently no web UI for this search interface, it exists purely // to power the Conduit API. throw new PhutilMethodNotImplementedException(); } protected function getBuiltinQueryNames() { return array( 'all' => pht('All Content'), ); } 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 $contents, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($contents, 'PhrictionContent'); throw new PhutilMethodNotImplementedException(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/query/PhrictionDocumentSearchEngine.php
src/applications/phriction/query/PhrictionDocumentSearchEngine.php
<?php final class PhrictionDocumentSearchEngine extends PhabricatorApplicationSearchEngine { public function getResultTypeDescription() { return pht('Wiki Documents'); } public function getApplicationClassName() { return 'PhabricatorPhrictionApplication'; } public function newQuery() { return id(new PhrictionDocumentQuery()) ->needContent(true); } protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['statuses']) { $query->withStatuses($map['statuses']); } if ($map['paths']) { $query->withSlugs($map['paths']); } if ($map['parentPaths']) { $query->withParentPaths($map['parentPaths']); } if ($map['ancestorPaths']) { $query->withAncestorPaths($map['ancestorPaths']); } return $query; } protected function buildCustomSearchFields() { return array( id(new PhabricatorSearchCheckboxesField()) ->setKey('statuses') ->setLabel(pht('Status')) ->setOptions(PhrictionDocumentStatus::getStatusMap()), id(new PhabricatorSearchStringListField()) ->setKey('paths') ->setIsHidden(true) ->setLabel(pht('Paths')), id(new PhabricatorSearchStringListField()) ->setKey('parentPaths') ->setIsHidden(true) ->setLabel(pht('Parent Paths')), id(new PhabricatorSearchStringListField()) ->setKey('ancestorPaths') ->setIsHidden(true) ->setLabel(pht('Ancestor Paths')), ); } protected function getURI($path) { return '/phriction/'.$path; } protected function getBuiltinQueryNames() { $names = array( 'active' => pht('Active'), 'all' => pht('All'), ); return $names; } public function buildSavedQueryFromBuiltin($query_key) { $query = $this->newSavedQuery(); $query->setQueryKey($query_key); switch ($query_key) { case 'all': return $query; case 'active': return $query->setParameter( 'statuses', array( PhrictionDocumentStatus::STATUS_EXISTS, )); } return parent::buildSavedQueryFromBuiltin($query_key); } protected function getRequiredHandlePHIDsForResultList( array $documents, PhabricatorSavedQuery $query) { $phids = array(); foreach ($documents as $document) { $content = $document->getContent(); $phids[] = $content->getAuthorPHID(); } return $phids; } protected function renderResultList( array $documents, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($documents, 'PhrictionDocument'); $viewer = $this->requireViewer(); $list = new PHUIObjectItemListView(); $list->setUser($viewer); foreach ($documents as $document) { $content = $document->getContent(); $slug = $document->getSlug(); $author_phid = $content->getAuthorPHID(); $slug_uri = PhrictionDocument::getSlugURI($slug); $byline = pht( 'Edited by %s', $handles[$author_phid]->renderLink()); $updated = phabricator_datetime( $content->getDateCreated(), $viewer); $item = id(new PHUIObjectItemView()) ->setHeader($content->getTitle()) ->setObject($document) ->setHref($slug_uri) ->addByline($byline) ->addIcon('none', $updated); $item->addAttribute($slug_uri); $icon = $document->getStatusIcon(); $color = $document->getStatusColor(); $label = $document->getStatusDisplayName(); $item->setStatusIcon("{$icon} {$color}", $label); if (!$document->isActive()) { $item->setDisabled(true); } $list->addItem($item); } $result = new PhabricatorApplicationSearchResultView(); $result->setObjectList($list); $result->setNoDataString(pht('No documents found.')); 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/phriction/query/PhrictionTransactionQuery.php
src/applications/phriction/query/PhrictionTransactionQuery.php
<?php final class PhrictionTransactionQuery extends PhabricatorApplicationTransactionQuery { public function getTemplateApplicationTransaction() { return new PhrictionTransaction(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/query/PhrictionContentQuery.php
src/applications/phriction/query/PhrictionContentQuery.php
<?php final class PhrictionContentQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $documentPHIDs; private $versions; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withDocumentPHIDs(array $phids) { $this->documentPHIDs = $phids; return $this; } public function withVersions(array $versions) { $this->versions = $versions; return $this; } public function newResultObject() { return new PhrictionContent(); } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'c.id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'c.phid IN (%Ls)', $this->phids); } if ($this->versions !== null) { $where[] = qsprintf( $conn, 'version IN (%Ld)', $this->versions); } if ($this->documentPHIDs !== null) { $where[] = qsprintf( $conn, 'd.phid IN (%Ls)', $this->documentPHIDs); } return $where; } protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) { $joins = parent::buildJoinClauseParts($conn); if ($this->shouldJoinDocumentTable()) { $joins[] = qsprintf( $conn, 'JOIN %T d ON d.phid = c.documentPHID', id(new PhrictionDocument())->getTableName()); } return $joins; } protected function willFilterPage(array $contents) { $document_phids = mpull($contents, 'getDocumentPHID'); $documents = id(new PhrictionDocumentQuery()) ->setViewer($this->getViewer()) ->setParentQuery($this) ->withPHIDs($document_phids) ->execute(); $documents = mpull($documents, null, 'getPHID'); foreach ($contents as $key => $content) { $document_phid = $content->getDocumentPHID(); $document = idx($documents, $document_phid); if (!$document) { unset($contents[$key]); $this->didRejectResult($content); continue; } $content->attachDocument($document); } return $contents; } private function shouldJoinDocumentTable() { if ($this->documentPHIDs !== null) { return true; } return false; } protected function getPrimaryTableAlias() { return 'c'; } public function getQueryApplicationClass() { return 'PhabricatorPhrictionApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/query/PhrictionDocumentQuery.php
src/applications/phriction/query/PhrictionDocumentQuery.php
<?php final class PhrictionDocumentQuery extends PhabricatorCursorPagedPolicyAwareQuery { private $ids; private $phids; private $slugs; private $depths; private $slugPrefix; private $statuses; private $parentPaths; private $ancestorPaths; private $needContent; const ORDER_HIERARCHY = 'hierarchy'; public function withIDs(array $ids) { $this->ids = $ids; return $this; } public function withPHIDs(array $phids) { $this->phids = $phids; return $this; } public function withSlugs(array $slugs) { $this->slugs = $slugs; return $this; } public function withDepths(array $depths) { $this->depths = $depths; return $this; } public function withSlugPrefix($slug_prefix) { $this->slugPrefix = $slug_prefix; return $this; } public function withStatuses(array $statuses) { $this->statuses = $statuses; return $this; } public function withParentPaths(array $paths) { $this->parentPaths = $paths; return $this; } public function withAncestorPaths(array $paths) { $this->ancestorPaths = $paths; return $this; } public function needContent($need_content) { $this->needContent = $need_content; return $this; } public function newResultObject() { return new PhrictionDocument(); } protected function willFilterPage(array $documents) { if ($documents) { $ancestor_slugs = array(); foreach ($documents as $key => $document) { $document_slug = $document->getSlug(); foreach (PhabricatorSlug::getAncestry($document_slug) as $ancestor) { $ancestor_slugs[$ancestor][] = $key; } } if ($ancestor_slugs) { $table = new PhrictionDocument(); $conn_r = $table->establishConnection('r'); $ancestors = queryfx_all( $conn_r, 'SELECT * FROM %T WHERE slug IN (%Ls)', $document->getTableName(), array_keys($ancestor_slugs)); $ancestors = $table->loadAllFromArray($ancestors); $ancestors = mpull($ancestors, null, 'getSlug'); foreach ($ancestor_slugs as $ancestor_slug => $document_keys) { $ancestor = idx($ancestors, $ancestor_slug); foreach ($document_keys as $document_key) { $documents[$document_key]->attachAncestor( $ancestor_slug, $ancestor); } } } } // To view a Phriction document, you must also be able to view all of the // ancestor documents. Filter out documents which have ancestors that are // not visible. $document_map = array(); foreach ($documents as $document) { $document_map[$document->getSlug()] = $document; foreach ($document->getAncestors() as $key => $ancestor) { if ($ancestor) { $document_map[$key] = $ancestor; } } } $filtered_map = $this->applyPolicyFilter( $document_map, array(PhabricatorPolicyCapability::CAN_VIEW)); // Filter all of the documents where a parent is not visible. foreach ($documents as $document_key => $document) { // If the document itself is not visible, filter it. if (!isset($filtered_map[$document->getSlug()])) { $this->didRejectResult($documents[$document_key]); unset($documents[$document_key]); continue; } // If an ancestor exists but is not visible, filter the document. foreach ($document->getAncestors() as $ancestor_key => $ancestor) { if (!$ancestor) { continue; } if (!isset($filtered_map[$ancestor_key])) { $this->didRejectResult($documents[$document_key]); unset($documents[$document_key]); break; } } } if (!$documents) { return $documents; } if ($this->needContent) { $contents = id(new PhrictionContentQuery()) ->setViewer($this->getViewer()) ->setParentQuery($this) ->withPHIDs(mpull($documents, 'getContentPHID')) ->execute(); $contents = mpull($contents, null, 'getPHID'); foreach ($documents as $key => $document) { $content_phid = $document->getContentPHID(); if (empty($contents[$content_phid])) { unset($documents[$key]); continue; } $document->attachContent($contents[$content_phid]); } } return $documents; } protected function buildSelectClauseParts(AphrontDatabaseConnection $conn) { $select = parent::buildSelectClauseParts($conn); if ($this->shouldJoinContentTable()) { $select[] = qsprintf($conn, 'c.title'); } return $select; } protected function buildJoinClauseParts(AphrontDatabaseConnection $conn) { $joins = parent::buildJoinClauseParts($conn); if ($this->shouldJoinContentTable()) { $content_dao = new PhrictionContent(); $joins[] = qsprintf( $conn, 'JOIN %T c ON d.contentPHID = c.phid', $content_dao->getTableName()); } return $joins; } private function shouldJoinContentTable() { if ($this->getOrderVector()->containsKey('title')) { return true; } return false; } protected function buildWhereClauseParts(AphrontDatabaseConnection $conn) { $where = parent::buildWhereClauseParts($conn); if ($this->ids !== null) { $where[] = qsprintf( $conn, 'd.id IN (%Ld)', $this->ids); } if ($this->phids !== null) { $where[] = qsprintf( $conn, 'd.phid IN (%Ls)', $this->phids); } if ($this->slugs !== null) { $where[] = qsprintf( $conn, 'd.slug IN (%Ls)', $this->slugs); } if ($this->statuses !== null) { $where[] = qsprintf( $conn, 'd.status IN (%Ls)', $this->statuses); } if ($this->slugPrefix !== null) { $where[] = qsprintf( $conn, 'd.slug LIKE %>', $this->slugPrefix); } if ($this->depths !== null) { $where[] = qsprintf( $conn, 'd.depth IN (%Ld)', $this->depths); } if ($this->parentPaths !== null || $this->ancestorPaths !== null) { $sets = array( array( 'paths' => $this->parentPaths, 'parents' => true, ), array( 'paths' => $this->ancestorPaths, 'parents' => false, ), ); $paths = array(); foreach ($sets as $set) { $set_paths = $set['paths']; if ($set_paths === null) { continue; } if (!$set_paths) { throw new PhabricatorEmptyQueryException( pht('No parent/ancestor paths specified.')); } $is_parents = $set['parents']; foreach ($set_paths as $path) { $path_normal = PhabricatorSlug::normalize($path); if ($path !== $path_normal) { throw new Exception( pht( 'Document path "%s" is not a valid path. The normalized '. 'form of this path is "%s".', $path, $path_normal)); } $depth = PhabricatorSlug::getDepth($path_normal); if ($is_parents) { $min_depth = $depth + 1; $max_depth = $depth + 1; } else { $min_depth = $depth + 1; $max_depth = null; } $paths[] = array( $path_normal, $min_depth, $max_depth, ); } } $path_clauses = array(); foreach ($paths as $path) { $parts = array(); list($prefix, $min, $max) = $path; // If we're getting children or ancestors of the root document, they // aren't actually stored with the leading "/" in the database, so // just skip this part of the clause. if ($prefix !== '/') { $parts[] = qsprintf( $conn, 'd.slug LIKE %>', $prefix); } if ($min !== null) { $parts[] = qsprintf( $conn, 'd.depth >= %d', $min); } if ($max !== null) { $parts[] = qsprintf( $conn, 'd.depth <= %d', $max); } if ($parts) { $path_clauses[] = qsprintf($conn, '%LA', $parts); } } if ($path_clauses) { $where[] = qsprintf($conn, '%LO', $path_clauses); } } return $where; } public function getBuiltinOrders() { return parent::getBuiltinOrders() + array( self::ORDER_HIERARCHY => array( 'vector' => array('depth', 'title', 'updated', 'id'), 'name' => pht('Hierarchy'), ), ); } public function getOrderableColumns() { return parent::getOrderableColumns() + array( 'depth' => array( 'table' => 'd', 'column' => 'depth', 'reverse' => true, 'type' => 'int', ), 'title' => array( 'table' => 'c', 'column' => 'title', 'reverse' => true, 'type' => 'string', ), 'updated' => array( 'table' => 'd', 'column' => 'editedEpoch', 'type' => 'int', 'unique' => false, ), ); } protected function newPagingMapFromCursorObject( PhabricatorQueryCursor $cursor, array $keys) { $document = $cursor->getObject(); $map = array( 'id' => (int)$document->getID(), 'depth' => $document->getDepth(), 'updated' => (int)$document->getEditedEpoch(), ); if (isset($keys['title'])) { $map['title'] = $cursor->getRawRowProperty('title'); } return $map; } protected function getPrimaryTableAlias() { return 'd'; } public function getQueryApplicationClass() { return 'PhabricatorPhrictionApplication'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/mail/PhrictionReplyHandler.php
src/applications/phriction/mail/PhrictionReplyHandler.php
<?php final class PhrictionReplyHandler extends PhabricatorApplicationTransactionReplyHandler { public function validateMailReceiver($mail_receiver) { if (!($mail_receiver instanceof PhrictionDocument)) { throw new Exception( pht('Mail receiver is not a %s!', 'PhrictionDocument')); } } public function getObjectPrefix() { return PhrictionDocumentPHIDType::TYPECONST; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/editor/PhrictionDocumentEditEngine.php
src/applications/phriction/editor/PhrictionDocumentEditEngine.php
<?php final class PhrictionDocumentEditEngine extends PhabricatorEditEngine { const ENGINECONST = 'phriction.document'; public function isEngineConfigurable() { return false; } public function getEngineName() { return pht('Phriction Document'); } public function getSummaryHeader() { return pht('Edit Phriction Document Configurations'); } public function getSummaryText() { return pht('This engine is used to edit Phriction documents.'); } public function getEngineApplicationClass() { return 'PhabricatorPhrictionApplication'; } protected function newEditableObject() { $viewer = $this->getViewer(); return PhrictionDocument::initializeNewDocument( $viewer, '/'); } protected function newObjectQuery() { return id(new PhrictionDocumentQuery()) ->needContent(true); } protected function getObjectCreateTitleText($object) { return pht('Create Document'); } protected function getObjectCreateButtonText($object) { return pht('Create Document'); } protected function getObjectEditTitleText($object) { return pht('Edit Document: %s', $object->getContent()->getTitle()); } protected function getObjectEditShortText($object) { return pht('Edit Document'); } protected function getObjectCreateShortText() { return pht('Create Document'); } protected function getObjectName() { return pht('Document'); } protected function getEditorURI() { return '/phriction/document/edit/'; } protected function getObjectCreateCancelURI($object) { return '/phriction/document/'; } protected function getObjectViewURI($object) { return $object->getURI(); } protected function getCreateNewObjectPolicy() { // NOTE: For now, this engine is only to support commenting. return PhabricatorPolicies::POLICY_NOONE; } protected function buildCustomEditFields($object) { return array(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/editor/PhrictionTransactionEditor.php
src/applications/phriction/editor/PhrictionTransactionEditor.php
<?php final class PhrictionTransactionEditor extends PhabricatorApplicationTransactionEditor { const VALIDATE_CREATE_ANCESTRY = 'create'; const VALIDATE_MOVE_ANCESTRY = 'move'; private $description; private $oldContent; private $newContent; private $moveAwayDocument; private $skipAncestorCheck; private $contentVersion; private $processContentVersionError = true; private $contentDiffURI; public function setDescription($description) { $this->description = $description; return $this; } private function getDescription() { return $this->description; } private function setOldContent(PhrictionContent $content) { $this->oldContent = $content; return $this; } public function getOldContent() { return $this->oldContent; } private function setNewContent(PhrictionContent $content) { $this->newContent = $content; return $this; } public function getNewContent() { return $this->newContent; } public function setSkipAncestorCheck($bool) { $this->skipAncestorCheck = $bool; return $this; } public function getSkipAncestorCheck() { return $this->skipAncestorCheck; } public function setContentVersion($version) { $this->contentVersion = $version; return $this; } public function getContentVersion() { return $this->contentVersion; } public function setProcessContentVersionError($process) { $this->processContentVersionError = $process; return $this; } public function getProcessContentVersionError() { return $this->processContentVersionError; } public function setMoveAwayDocument(PhrictionDocument $document) { $this->moveAwayDocument = $document; return $this; } public function setShouldPublishContent( PhrictionDocument $object, $publish) { if ($publish) { $content_phid = $this->getNewContent()->getPHID(); } else { $content_phid = $this->getOldContent()->getPHID(); } $object->setContentPHID($content_phid); return $this; } public function getEditorApplicationClass() { return 'PhabricatorPhrictionApplication'; } public function getEditorObjectsDescription() { return pht('Phriction Documents'); } public function getTransactionTypes() { $types = parent::getTransactionTypes(); $types[] = PhabricatorTransactions::TYPE_EDGE; $types[] = PhabricatorTransactions::TYPE_COMMENT; $types[] = PhabricatorTransactions::TYPE_VIEW_POLICY; $types[] = PhabricatorTransactions::TYPE_EDIT_POLICY; return $types; } protected function expandTransactions( PhabricatorLiskDAO $object, array $xactions) { $this->setOldContent($object->getContent()); return parent::expandTransactions($object, $xactions); } protected function expandTransaction( PhabricatorLiskDAO $object, PhabricatorApplicationTransaction $xaction) { $xactions = parent::expandTransaction($object, $xaction); switch ($xaction->getTransactionType()) { case PhrictionDocumentContentTransaction::TRANSACTIONTYPE: if ($this->getIsNewObject()) { break; } $content = $xaction->getNewValue(); if ($content === '') { $xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentDeleteTransaction::TRANSACTIONTYPE) ->setNewValue(true) ->setMetadataValue('contentDelete', true); } break; case PhrictionDocumentMoveToTransaction::TRANSACTIONTYPE: $document = $xaction->getNewValue(); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY) ->setNewValue($document->getViewPolicy()); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDIT_POLICY) ->setNewValue($document->getEditPolicy()); break; default: break; } return $xactions; } protected function applyFinalEffects( PhabricatorLiskDAO $object, array $xactions) { if ($this->hasNewDocumentContent()) { $content = $this->getNewDocumentContent($object); $content ->setDocumentPHID($object->getPHID()) ->save(); } if ($this->getIsNewObject() && !$this->getSkipAncestorCheck()) { // Stub out empty parent documents if they don't exist $ancestral_slugs = PhabricatorSlug::getAncestry($object->getSlug()); if ($ancestral_slugs) { $ancestors = id(new PhrictionDocumentQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withSlugs($ancestral_slugs) ->needContent(true) ->execute(); $ancestors = mpull($ancestors, null, 'getSlug'); $stub_type = PhrictionChangeType::CHANGE_STUB; foreach ($ancestral_slugs as $slug) { $ancestor_doc = idx($ancestors, $slug); // We check for change type to prevent near-infinite recursion if (!$ancestor_doc && $content->getChangeType() != $stub_type) { $ancestor_doc = PhrictionDocument::initializeNewDocument( $this->getActor(), $slug); $stub_xactions = array(); $stub_xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentTitleTransaction::TRANSACTIONTYPE) ->setNewValue(PhabricatorSlug::getDefaultTitle($slug)) ->setMetadataValue('stub:create:phid', $object->getPHID()); $stub_xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentContentTransaction::TRANSACTIONTYPE) ->setNewValue('') ->setMetadataValue('stub:create:phid', $object->getPHID()); $stub_xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_VIEW_POLICY) ->setNewValue($object->getViewPolicy()); $stub_xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhabricatorTransactions::TYPE_EDIT_POLICY) ->setNewValue($object->getEditPolicy()); $sub_editor = id(new PhrictionTransactionEditor()) ->setActor($this->getActor()) ->setContentSource($this->getContentSource()) ->setContinueOnNoEffect($this->getContinueOnNoEffect()) ->setSkipAncestorCheck(true) ->setDescription(pht('Empty Parent Document')) ->applyTransactions($ancestor_doc, $stub_xactions); } } } } if ($this->moveAwayDocument !== null) { $move_away_xactions = array(); $move_away_xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentMoveAwayTransaction::TRANSACTIONTYPE) ->setNewValue($object); $sub_editor = id(new PhrictionTransactionEditor()) ->setActor($this->getActor()) ->setContentSource($this->getContentSource()) ->setContinueOnNoEffect($this->getContinueOnNoEffect()) ->setDescription($this->getDescription()) ->applyTransactions($this->moveAwayDocument, $move_away_xactions); } // Compute the content diff URI for the publishing phase. foreach ($xactions as $xaction) { switch ($xaction->getTransactionType()) { case PhrictionDocumentContentTransaction::TRANSACTIONTYPE: $params = array( 'l' => $this->getOldContent()->getVersion(), 'r' => $this->getNewContent()->getVersion(), ); $path = '/phriction/diff/'.$object->getID().'/'; $uri = new PhutilURI($path, $params); $this->contentDiffURI = (string)$uri; break 2; default: break; } } return $xactions; } protected function shouldSendMail( PhabricatorLiskDAO $object, array $xactions) { return true; } protected function getMailSubjectPrefix() { return '[Phriction]'; } protected function getMailTo(PhabricatorLiskDAO $object) { return array( $this->getActingAsPHID(), ); } public function getMailTagsMap() { return array( PhrictionTransaction::MAILTAG_TITLE => pht("A document's title changes."), PhrictionTransaction::MAILTAG_CONTENT => pht("A document's content changes."), PhrictionTransaction::MAILTAG_DELETE => pht('A document is deleted.'), PhrictionTransaction::MAILTAG_SUBSCRIBERS => pht('A document\'s subscribers change.'), PhrictionTransaction::MAILTAG_OTHER => pht('Other document activity not listed above occurs.'), ); } protected function buildReplyHandler(PhabricatorLiskDAO $object) { return id(new PhrictionReplyHandler()) ->setMailReceiver($object); } protected function buildMailTemplate(PhabricatorLiskDAO $object) { $title = $object->getContent()->getTitle(); return id(new PhabricatorMetaMTAMail()) ->setSubject($title); } protected function buildMailBody( PhabricatorLiskDAO $object, array $xactions) { $body = parent::buildMailBody($object, $xactions); if ($this->getIsNewObject()) { $body->addRemarkupSection( pht('DOCUMENT CONTENT'), $object->getContent()->getContent()); } else if ($this->contentDiffURI) { $body->addLinkSection( pht('DOCUMENT DIFF'), PhabricatorEnv::getProductionURI($this->contentDiffURI)); } $description = $object->getContent()->getDescription(); if ($description !== null && strlen($description)) { $body->addTextSection( pht('EDIT NOTES'), $description); } $body->addLinkSection( pht('DOCUMENT DETAIL'), PhabricatorEnv::getProductionURI( PhrictionDocument::getSlugURI($object->getSlug()))); return $body; } protected function shouldPublishFeedStory( PhabricatorLiskDAO $object, array $xactions) { return $this->shouldSendMail($object, $xactions); } protected function getFeedRelatedPHIDs( PhabricatorLiskDAO $object, array $xactions) { $phids = parent::getFeedRelatedPHIDs($object, $xactions); foreach ($xactions as $xaction) { switch ($xaction->getTransactionType()) { case PhrictionDocumentMoveToTransaction::TRANSACTIONTYPE: $dict = $xaction->getNewValue(); $phids[] = $dict['phid']; break; } } return $phids; } protected function validateTransaction( PhabricatorLiskDAO $object, $type, array $xactions) { $errors = parent::validateTransaction($object, $type, $xactions); foreach ($xactions as $xaction) { switch ($type) { case PhrictionDocumentContentTransaction::TRANSACTIONTYPE: if ($xaction->getMetadataValue('stub:create:phid')) { break; } if ($this->getProcessContentVersionError()) { $error = $this->validateContentVersion($object, $type, $xaction); if ($error) { $this->setProcessContentVersionError(false); $errors[] = $error; } } if ($this->getIsNewObject()) { $ancestry_errors = $this->validateAncestry( $object, $type, $xaction, self::VALIDATE_CREATE_ANCESTRY); if ($ancestry_errors) { $errors = array_merge($errors, $ancestry_errors); } } break; case PhrictionDocumentMoveToTransaction::TRANSACTIONTYPE: $source_document = $xaction->getNewValue(); $ancestry_errors = $this->validateAncestry( $object, $type, $xaction, self::VALIDATE_MOVE_ANCESTRY); if ($ancestry_errors) { $errors = array_merge($errors, $ancestry_errors); } $target_document = id(new PhrictionDocumentQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withSlugs(array($object->getSlug())) ->needContent(true) ->executeOne(); // Prevent overwrites and no-op moves. $exists = PhrictionDocumentStatus::STATUS_EXISTS; if ($target_document) { $message = null; if ($target_document->getSlug() == $source_document->getSlug()) { $message = pht( 'You can not move a document to its existing location. '. 'Choose a different location to move the document to.'); } else if ($target_document->getStatus() == $exists) { $message = pht( 'You can not move this document there, because it would '. 'overwrite an existing document which is already at that '. 'location. Move or delete the existing document first.'); } if ($message !== null) { $error = new PhabricatorApplicationTransactionValidationError( $type, pht('Invalid'), $message, $xaction); $errors[] = $error; } } break; } } return $errors; } public function validateAncestry( PhabricatorLiskDAO $object, $type, PhabricatorApplicationTransaction $xaction, $verb) { $errors = array(); // NOTE: We use the omnipotent user for these checks because policy // doesn't matter; existence does. $other_doc_viewer = PhabricatorUser::getOmnipotentUser(); $ancestral_slugs = PhabricatorSlug::getAncestry($object->getSlug()); if ($ancestral_slugs) { $ancestors = id(new PhrictionDocumentQuery()) ->setViewer($other_doc_viewer) ->withSlugs($ancestral_slugs) ->execute(); $ancestors = mpull($ancestors, null, 'getSlug'); foreach ($ancestral_slugs as $slug) { $ancestor_doc = idx($ancestors, $slug); if (!$ancestor_doc) { $create_uri = '/phriction/edit/?slug='.$slug; $create_link = phutil_tag( 'a', array( 'href' => $create_uri, ), $slug); switch ($verb) { case self::VALIDATE_MOVE_ANCESTRY: $message = pht( 'Can not move document because the parent document with '. 'slug %s does not exist!', $create_link); break; case self::VALIDATE_CREATE_ANCESTRY: $message = pht( 'Can not create document because the parent document with '. 'slug %s does not exist!', $create_link); break; } $error = new PhabricatorApplicationTransactionValidationError( $type, pht('Missing Ancestor'), $message, $xaction); $errors[] = $error; } } } return $errors; } private function validateContentVersion( PhabricatorLiskDAO $object, $type, PhabricatorApplicationTransaction $xaction) { $error = null; if ($this->getContentVersion() && ($object->getMaxVersion() != $this->getContentVersion())) { $error = new PhabricatorApplicationTransactionValidationError( $type, pht('Edit Conflict'), pht( 'Another user made changes to this document after you began '. 'editing it. Do you want to overwrite their changes? '. '(If you choose to overwrite their changes, you should review '. 'the document edit history to see what you overwrote, and '. 'then make another edit to merge the changes if necessary.)'), $xaction); } return $error; } protected function supportsSearch() { return true; } protected function shouldApplyHeraldRules( PhabricatorLiskDAO $object, array $xactions) { return true; } protected function buildHeraldAdapter( PhabricatorLiskDAO $object, array $xactions) { return id(new PhrictionDocumentHeraldAdapter()) ->setDocument($object); } private function hasNewDocumentContent() { return (bool)$this->newContent; } public function getNewDocumentContent(PhrictionDocument $document) { if (!$this->hasNewDocumentContent()) { $content = $this->newDocumentContent($document); // Generate a PHID now so we can populate "contentPHID" before saving // the document to the database: the column is not nullable so we need // a value. $content_phid = $content->generatePHID(); $content->setPHID($content_phid); $document->setContentPHID($content_phid); $document->attachContent($content); $document->setEditedEpoch(PhabricatorTime::getNow()); $document->setMaxVersion($content->getVersion()); $this->newContent = $content; } return $this->newContent; } private function newDocumentContent(PhrictionDocument $document) { $content = id(new PhrictionContent()) ->setSlug($document->getSlug()) ->setAuthorPHID($this->getActingAsPHID()) ->setChangeType(PhrictionChangeType::CHANGE_EDIT) ->setTitle($this->getOldContent()->getTitle()) ->setContent($this->getOldContent()->getContent()) ->setDescription(''); if ($this->getDescription() !== null && strlen($this->getDescription())) { $content->setDescription($this->getDescription()); } $content->setVersion($document->getMaxVersion() + 1); return $content; } protected function getCustomWorkerState() { return array( 'contentDiffURI' => $this->contentDiffURI, ); } protected function loadCustomWorkerState(array $state) { $this->contentDiffURI = idx($state, 'contentDiffURI'); return $this; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/xaction/PhrictionDocumentVersionTransaction.php
src/applications/phriction/xaction/PhrictionDocumentVersionTransaction.php
<?php abstract class PhrictionDocumentVersionTransaction extends PhrictionDocumentTransactionType { protected function getNewDocumentContent($object) { return $this->getEditor()->getNewDocumentContent($object); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/xaction/PhrictionDocumentEditTransaction.php
src/applications/phriction/xaction/PhrictionDocumentEditTransaction.php
<?php abstract class PhrictionDocumentEditTransaction extends PhrictionDocumentVersionTransaction { public function generateOldValue($object) { if ($this->getEditor()->getIsNewObject()) { return null; } // NOTE: We want to get the newest version of the content here, regardless // of whether it's published or not. $actor = $this->getActor(); return id(new PhrictionContentQuery()) ->setViewer($actor) ->withDocumentPHIDs(array($object->getPHID())) ->setOrder('newest') ->setLimit(1) ->executeOne() ->getContent(); } public function generateNewValue($object, $value) { return $value; } public function applyInternalEffects($object, $value) { $content = $this->getNewDocumentContent($object); $content->setContent($value); } public function getActionStrength() { return 130; } public function getActionName() { return pht('Edited'); } public function getTitle() { return pht( '%s edited the content of this document.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s edited the content of %s.', $this->renderAuthor(), $this->renderObject()); } public function getMailDiffSectionHeader() { return pht('CHANGES TO DOCUMENT CONTENT'); } public function hasChangeDetailView() { return true; } public function newChangeDetailView() { $viewer = $this->getViewer(); return id(new PhabricatorApplicationTransactionTextDiffDetailView()) ->setViewer($viewer) ->setOldText($this->getOldValue()) ->setNewText($this->getNewValue()); } public function newRemarkupChanges() { $changes = array(); $changes[] = $this->newRemarkupChange() ->setOldValue($this->getOldValue()) ->setNewValue($this->getNewValue()); return $changes; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/xaction/PhrictionDocumentContentTransaction.php
src/applications/phriction/xaction/PhrictionDocumentContentTransaction.php
<?php final class PhrictionDocumentContentTransaction extends PhrictionDocumentEditTransaction { const TRANSACTIONTYPE = 'content'; public function applyInternalEffects($object, $value) { parent::applyInternalEffects($object, $value); $object->setStatus(PhrictionDocumentStatus::STATUS_EXISTS); $this->getEditor()->setShouldPublishContent($object, true); } public function validateTransactions($object, array $xactions) { $errors = array(); // NOTE: This is slightly different from the draft validation. Here, // we're validating that: you can't edit away a document; and you can't // create an empty document. $content = $object->getContent()->getContent(); if ($this->isEmptyTextTransaction($content, $xactions)) { $errors[] = $this->newRequiredError( pht('Documents must have content.')); } 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/phriction/xaction/PhrictionDocumentTransactionType.php
src/applications/phriction/xaction/PhrictionDocumentTransactionType.php
<?php abstract class PhrictionDocumentTransactionType 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/phriction/xaction/PhrictionDocumentDraftTransaction.php
src/applications/phriction/xaction/PhrictionDocumentDraftTransaction.php
<?php final class PhrictionDocumentDraftTransaction extends PhrictionDocumentEditTransaction { const TRANSACTIONTYPE = 'draft'; public function applyInternalEffects($object, $value) { parent::applyInternalEffects($object, $value); $this->getEditor()->setShouldPublishContent($object, false); } public function shouldHideForFeed() { return true; } public function validateTransactions($object, array $xactions) { $errors = array(); // NOTE: We're only validating that you can't edit a document down to // nothing in a draft transaction. Alone, this doesn't prevent you from // creating a document with no content. The content transaction has // validation for that. if (!$xactions) { return $errors; } $content = $object->getContent()->getContent(); if ($this->isEmptyTextTransaction($content, $xactions)) { $errors[] = $this->newRequiredError( pht('Documents must have content.')); } 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/phriction/xaction/PhrictionDocumentPublishTransaction.php
src/applications/phriction/xaction/PhrictionDocumentPublishTransaction.php
<?php final class PhrictionDocumentPublishTransaction extends PhrictionDocumentTransactionType { const TRANSACTIONTYPE = 'publish'; public function generateOldValue($object) { return $object->getContentPHID(); } public function applyInternalEffects($object, $value) { $object->setContentPHID($value); } public function getActionName() { return pht('Published'); } public function getTitle() { return pht( '%s published a new version of this document.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s published a new version of %s.', $this->renderAuthor(), $this->renderObject()); } public function validateTransactions($object, array $xactions) { $actor = $this->getActor(); $errors = array(); foreach ($xactions as $xaction) { $content_phid = $xaction->getNewValue(); // If this isn't changing anything, skip it. if ($content_phid === $object->getContentPHID()) { continue; } $content = id(new PhrictionContentQuery()) ->setViewer($actor) ->withPHIDs(array($content_phid)) ->executeOne(); if (!$content) { $errors[] = $this->newInvalidError( pht( 'Unable to load Content object with PHID "%s".', $content_phid), $xaction); continue; } if ($content->getDocumentPHID() !== $object->getPHID()) { $errors[] = $this->newInvalidError( pht( 'Content object "%s" can not be published because it belongs '. 'to a different document.', $content_phid)); continue; } } 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/phriction/xaction/PhrictionDocumentMoveToTransaction.php
src/applications/phriction/xaction/PhrictionDocumentMoveToTransaction.php
<?php final class PhrictionDocumentMoveToTransaction extends PhrictionDocumentVersionTransaction { const TRANSACTIONTYPE = 'move-to'; public function generateOldValue($object) { return null; } public function generateNewValue($object, $value) { $document = $value; $dict = array( 'id' => $document->getID(), 'phid' => $document->getPHID(), 'content' => $document->getContent()->getContent(), 'title' => $document->getContent()->getTitle(), ); $editor = $this->getEditor(); $editor->setMoveAwayDocument($document); return $dict; } public function applyInternalEffects($object, $value) { $object->setStatus(PhrictionDocumentStatus::STATUS_EXISTS); $content = $this->getNewDocumentContent($object); $content->setContent($value['content']); $content->setTitle($value['title']); $content->setChangeType(PhrictionChangeType::CHANGE_MOVE_HERE); $content->setChangeRef($value['id']); } public function getActionStrength() { return 100; } public function getActionName() { return pht('Moved'); } public function getTitle() { $old = $this->getOldValue(); $new = $this->getNewValue(); return pht( '%s moved this document from %s.', $this->renderAuthor(), $this->renderHandle($new['phid'])); } public function getTitleForFeed() { $old = $this->getOldValue(); $new = $this->getNewValue(); return pht( '%s moved %s from %s', $this->renderAuthor(), $this->renderObject(), $this->renderHandle($new['phid'])); } public function validateTransactions($object, array $xactions) { $errors = array(); $e_text = null; foreach ($xactions as $xaction) { $source_document = $xaction->getNewValue(); switch ($source_document->getStatus()) { case PhrictionDocumentStatus::STATUS_DELETED: $e_text = pht('A deleted document can not be moved.'); break; case PhrictionDocumentStatus::STATUS_MOVED: $e_text = pht('A moved document can not be moved again.'); break; case PhrictionDocumentStatus::STATUS_STUB: $e_text = pht('A stub document can not be moved.'); break; default: $e_text = null; break; } if ($e_text !== null) { $errors[] = $this->newInvalidError($e_text); } } // TODO: Move Ancestry validation here once all types are converted. return $errors; } public function getIcon() { return 'fa-arrows'; } public function shouldHideForFeed() { 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/phriction/xaction/PhrictionDocumentDeleteTransaction.php
src/applications/phriction/xaction/PhrictionDocumentDeleteTransaction.php
<?php final class PhrictionDocumentDeleteTransaction extends PhrictionDocumentVersionTransaction { const TRANSACTIONTYPE = 'delete'; public function generateOldValue($object) { return null; } public function applyInternalEffects($object, $value) { $object->setStatus(PhrictionDocumentStatus::STATUS_DELETED); $content = $this->getNewDocumentContent($object); $content->setContent(''); $content->setChangeType(PhrictionChangeType::CHANGE_DELETE); } public function getActionStrength() { return 150; } public function getActionName() { return pht('Deleted'); } public function getTitle() { return pht( '%s deleted this document.', $this->renderAuthor()); } public function getTitleForFeed() { return pht( '%s deleted %s.', $this->renderAuthor(), $this->renderObject()); } public function validateTransactions($object, array $xactions) { $errors = array(); $e_text = null; foreach ($xactions as $xaction) { switch ($object->getStatus()) { case PhrictionDocumentStatus::STATUS_DELETED: if ($xaction->getMetadataValue('contentDelete')) { $e_text = pht( 'This document is already deleted. You must specify '. 'content to re-create the document and make further edits.'); } else { $e_text = pht( 'An already deleted document can not be deleted.'); } break; case PhrictionDocumentStatus::STATUS_MOVED: $e_text = pht('A moved document can not be deleted.'); break; case PhrictionDocumentStatus::STATUS_STUB: $e_text = pht('A stub document can not be deleted.'); break; default: break; } if ($e_text !== null) { $errors[] = $this->newInvalidError($e_text); } } return $errors; } public function getIcon() { return 'fa-trash-o'; } public function getColor() { return 'red'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/xaction/PhrictionDocumentMoveAwayTransaction.php
src/applications/phriction/xaction/PhrictionDocumentMoveAwayTransaction.php
<?php final class PhrictionDocumentMoveAwayTransaction extends PhrictionDocumentVersionTransaction { const TRANSACTIONTYPE = 'move-away'; public function generateOldValue($object) { return null; } public function generateNewValue($object, $value) { $document = $value; $dict = array( 'id' => $document->getID(), 'phid' => $document->getPHID(), 'content' => $document->getContent()->getContent(), 'title' => $document->getContent()->getTitle(), ); return $dict; } public function applyInternalEffects($object, $value) { $object->setStatus(PhrictionDocumentStatus::STATUS_MOVED); $content = $this->getNewDocumentContent($object); $content->setContent(''); $content->setChangeType(PhrictionChangeType::CHANGE_MOVE_AWAY); $content->setChangeRef($value['id']); } public function getActionName() { return pht('Moved Away'); } public function getTitle() { $new = $this->getNewValue(); return pht( '%s moved this document to %s.', $this->renderAuthor(), $this->renderObject($new['phid'])); } public function getTitleForFeed() { $new = $this->getNewValue(); return pht( '%s moved %s to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderObject($new['phid'])); } public function getIcon() { return 'fa-arrows'; } public function shouldHideForFeed() { 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/phriction/xaction/PhrictionDocumentTitleTransaction.php
src/applications/phriction/xaction/PhrictionDocumentTitleTransaction.php
<?php final class PhrictionDocumentTitleTransaction extends PhrictionDocumentVersionTransaction { const TRANSACTIONTYPE = 'title'; public function generateOldValue($object) { if ($this->isNewObject()) { return null; } return $this->getEditor()->getOldContent()->getTitle(); } public function applyInternalEffects($object, $value) { $object->setStatus(PhrictionDocumentStatus::STATUS_EXISTS); $content = $this->getNewDocumentContent($object); $content->setTitle($value); } public function getActionStrength() { return 140; } public function getActionName() { $old = $this->getOldValue(); $new = $this->getNewValue(); if ($old === null) { if ($this->getMetadataValue('stub:create:phid')) { return pht('Stubbed'); } else { return pht('Created'); } } return pht('Retitled'); } public function getTitle() { $old = $this->getOldValue(); $new = $this->getNewValue(); if ($old === null) { if ($this->getMetadataValue('stub:create:phid')) { return pht( '%s stubbed out this document when creating %s.', $this->renderAuthor(), $this->renderHandleLink( $this->getMetadataValue('stub:create:phid'))); } else { return pht( '%s created this document.', $this->renderAuthor()); } } return pht( '%s changed the title from %s to %s.', $this->renderAuthor(), $this->renderOldValue(), $this->renderNewValue()); } public function getTitleForFeed() { $old = $this->getOldValue(); $new = $this->getNewValue(); if ($old === null) { return pht( '%s created %s.', $this->renderAuthor(), $this->renderObject()); } return pht( '%s renamed %s from %s to %s.', $this->renderAuthor(), $this->renderObject(), $this->renderOldValue(), $this->renderNewValue()); } public function validateTransactions($object, array $xactions) { $errors = array(); $title = $object->getContent()->getTitle(); if ($this->isEmptyTextTransaction($title, $xactions)) { $errors[] = $this->newRequiredError( pht('Documents must have a title.')); } if ($this->isNewObject()) { // No ancestral slugs is "/". No ancestry checks apply when creating the // root document. $ancestral_slugs = PhabricatorSlug::getAncestry($object->getSlug()); if ($ancestral_slugs) { // You must be able to view and edit the parent document to create a new // child. $parent_document = id(new PhrictionDocumentQuery()) ->setViewer($this->getActor()) ->withSlugs(array(last($ancestral_slugs))) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$parent_document) { $errors[] = $this->newInvalidError( pht('You can not create a document which does not have a parent.')); } } } 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/phriction/application/PhabricatorPhrictionApplication.php
src/applications/phriction/application/PhabricatorPhrictionApplication.php
<?php final class PhabricatorPhrictionApplication extends PhabricatorApplication { public function getName() { return pht('Phriction'); } public function getShortDescription() { return pht('Wiki Documents'); } public function getBaseURI() { return '/w/'; } public function getIcon() { return 'fa-book'; } public function isPinnedByDefault(PhabricatorUser $viewer) { return true; } public function getHelpDocumentationArticles(PhabricatorUser $viewer) { return array( array( 'name' => pht('Phriction User Guide'), 'href' => PhabricatorEnv::getDoclink('Phriction User Guide'), ), ); } public function getTitleGlyph() { return "\xE2\x9A\xA1"; } public function getRemarkupRules() { return array( new PhrictionRemarkupRule(), ); } public function getRoutes() { return array( // Match "/w/" with slug "/". '/w(?P<slug>/)' => 'PhrictionDocumentController', // Match "/w/x/y/z/" with slug "x/y/z/". '/w/(?P<slug>.+/)' => 'PhrictionDocumentController', '/phriction/' => array( '(?:query/(?P<queryKey>[^/]+)/)?' => 'PhrictionListController', 'history(?P<slug>/)' => 'PhrictionHistoryController', 'history/(?P<slug>.+/)' => 'PhrictionHistoryController', 'edit/(?:(?P<id>[1-9]\d*)/)?' => 'PhrictionEditController', 'delete/(?P<id>[1-9]\d*)/' => 'PhrictionDeleteController', 'publish/(?P<documentID>[1-9]\d*)/(?P<contentID>[1-9]\d*)/' => 'PhrictionPublishController', 'new/' => 'PhrictionNewController', 'move/(?P<id>[1-9]\d*)/' => 'PhrictionMoveController', 'preview/' => 'PhrictionMarkupPreviewController', 'diff/(?P<id>[1-9]\d*)/' => 'PhrictionDiffController', $this->getEditRoutePattern('document/edit/') => 'PhrictionEditEngineController', ), ); } public function getApplicationOrder() { return 0.140; } public function getApplicationSearchDocumentTypes() { return array( PhrictionDocumentPHIDType::TYPECONST, ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/phid/PhrictionDocumentPHIDType.php
src/applications/phriction/phid/PhrictionDocumentPHIDType.php
<?php final class PhrictionDocumentPHIDType extends PhabricatorPHIDType { const TYPECONST = 'WIKI'; public function getTypeName() { return pht('Phriction Wiki Document'); } public function newObject() { return new PhrictionDocument(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorPhrictionApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhrictionDocumentQuery()) ->withPHIDs($phids) ->needContent(true); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $document = $objects[$phid]; $content = $document->getContent(); $title = $content->getTitle(); $slug = $document->getSlug(); $status = $document->getStatus(); $handle->setName($title); $handle->setURI(PhrictionDocument::getSlugURI($slug)); if ($status != PhrictionDocumentStatus::STATUS_EXISTS) { $handle->setStatus(PhabricatorObjectHandle::STATUS_CLOSED); } } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/phid/PhrictionContentPHIDType.php
src/applications/phriction/phid/PhrictionContentPHIDType.php
<?php final class PhrictionContentPHIDType extends PhabricatorPHIDType { const TYPECONST = 'WRDS'; public function getTypeName() { return pht('Phriction Content'); } public function newObject() { return new PhrictionContent(); } public function getPHIDTypeApplicationClass() { return 'PhabricatorPhrictionApplication'; } protected function buildQueryForObjects( PhabricatorObjectQuery $query, array $phids) { return id(new PhrictionContentQuery()) ->withPHIDs($phids); } public function loadHandles( PhabricatorHandleQuery $query, array $handles, array $objects) { foreach ($handles as $phid => $handle) { $content = $objects[$phid]; } } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/herald/PhrictionDocumentHeraldField.php
src/applications/phriction/herald/PhrictionDocumentHeraldField.php
<?php abstract class PhrictionDocumentHeraldField extends HeraldField { public function supportsObject($object) { return ($object instanceof PhrictionDocument); } public function getFieldGroupKey() { return PhrictionDocumentHeraldFieldGroup::FIELDGROUPKEY; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/herald/PhrictionDocumentTitleHeraldField.php
src/applications/phriction/herald/PhrictionDocumentTitleHeraldField.php
<?php final class PhrictionDocumentTitleHeraldField extends PhrictionDocumentHeraldField { const FIELDCONST = 'phriction.document.title'; public function getHeraldFieldName() { return pht('Title'); } public function getHeraldFieldValue($object) { return $object->getContent()->getTitle(); } protected function getHeraldFieldStandardType() { return self::STANDARD_TEXT; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/herald/PhrictionDocumentPathHeraldField.php
src/applications/phriction/herald/PhrictionDocumentPathHeraldField.php
<?php final class PhrictionDocumentPathHeraldField extends PhrictionDocumentHeraldField { const FIELDCONST = 'path'; public function getHeraldFieldName() { return pht('Path'); } public function getHeraldFieldValue($object) { return $object->getcontent()->getSlug(); } protected function getHeraldFieldStandardType() { return self::STANDARD_TEXT; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/herald/PhrictionDocumentHeraldAdapter.php
src/applications/phriction/herald/PhrictionDocumentHeraldAdapter.php
<?php final class PhrictionDocumentHeraldAdapter extends HeraldAdapter { private $document; public function getAdapterApplicationClass() { return 'PhabricatorPhrictionApplication'; } public function getAdapterContentDescription() { return pht('React to wiki documents being created or updated.'); } protected function initializeNewAdapter() { $this->document = $this->newObject(); } protected function newObject() { return new PhrictionDocument(); } public function isTestAdapterForObject($object) { return ($object instanceof PhrictionDocument); } public function getAdapterTestDescription() { return pht( 'Test rules which run when a wiki document is created or updated.'); } public function setObject($object) { $this->document = $object; return $this; } public function getObject() { return $this->document; } public function setDocument(PhrictionDocument $document) { $this->document = $document; return $this; } public function getDocument() { return $this->document; } public function getAdapterContentName() { return pht('Phriction Documents'); } public function supportsRuleType($rule_type) { switch ($rule_type) { case HeraldRuleTypeConfig::RULE_TYPE_GLOBAL: case HeraldRuleTypeConfig::RULE_TYPE_PERSONAL: return true; case HeraldRuleTypeConfig::RULE_TYPE_OBJECT: default: return false; } } public function getHeraldName() { return pht('Wiki Document %d', $this->getDocument()->getID()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/herald/PhrictionDocumentContentHeraldField.php
src/applications/phriction/herald/PhrictionDocumentContentHeraldField.php
<?php final class PhrictionDocumentContentHeraldField extends PhrictionDocumentHeraldField { const FIELDCONST = 'phriction.document.content'; public function getHeraldFieldName() { return pht('Content'); } public function getHeraldFieldValue($object) { return $object->getContent()->getContent(); } protected function getHeraldFieldStandardType() { return self::STANDARD_TEXT; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/herald/PhrictionDocumentPublishedHeraldField.php
src/applications/phriction/herald/PhrictionDocumentPublishedHeraldField.php
<?php final class PhrictionDocumentPublishedHeraldField extends PhrictionDocumentHeraldField { const FIELDCONST = 'phriction.document.published'; public function getHeraldFieldName() { return pht('Published document changed'); } public function getFieldGroupKey() { return HeraldTransactionsFieldGroup::FIELDGROUPKEY; } public function getHeraldFieldValue($object) { // The published document changes if we apply a "publish" transaction // (which points the published document pointer at new content) or if we // apply a "content" transaction. // When a change affects only the draft document, it applies as a "draft" // transaction. $type_content = PhrictionDocumentContentTransaction::TRANSACTIONTYPE; $type_publish = PhrictionDocumentPublishTransaction::TRANSACTIONTYPE; if ($this->hasAppliedTransactionOfType($type_content)) { return true; } if ($this->hasAppliedTransactionOfType($type_publish)) { return true; } return false; } protected function getHeraldFieldStandardType() { return self::STANDARD_BOOL; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/herald/PhrictionDocumentAuthorHeraldField.php
src/applications/phriction/herald/PhrictionDocumentAuthorHeraldField.php
<?php final class PhrictionDocumentAuthorHeraldField extends PhrictionDocumentHeraldField { const FIELDCONST = 'phriction.document.author'; public function getHeraldFieldName() { return pht('Author'); } public function getHeraldFieldValue($object) { return $object->getContent()->getAuthorPHID(); } protected function getHeraldFieldStandardType() { return self::STANDARD_PHID; } protected function getDatasource() { return new PhabricatorPeopleDatasource(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/herald/PhrictionDocumentHeraldFieldGroup.php
src/applications/phriction/herald/PhrictionDocumentHeraldFieldGroup.php
<?php final class PhrictionDocumentHeraldFieldGroup extends HeraldFieldGroup { const FIELDGROUPKEY = 'phriction.document'; public function getGroupLabel() { return pht('Document Fields'); } protected function getGroupOrder() { return 1000; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/conduit/PhrictionDocumentSearchConduitAPIMethod.php
src/applications/phriction/conduit/PhrictionDocumentSearchConduitAPIMethod.php
<?php final class PhrictionDocumentSearchConduitAPIMethod extends PhabricatorSearchEngineAPIMethod { public function getAPIMethodName() { return 'phriction.document.search'; } public function newSearchEngine() { return new PhrictionDocumentSearchEngine(); } public function getMethodSummary() { return pht('Read information about Phriction documents.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/conduit/PhrictionEditConduitAPIMethod.php
src/applications/phriction/conduit/PhrictionEditConduitAPIMethod.php
<?php final class PhrictionEditConduitAPIMethod extends PhrictionConduitAPIMethod { public function getAPIMethodName() { return 'phriction.edit'; } public function getMethodDescription() { return pht('Update a Phriction document.'); } protected function defineParamTypes() { return array( 'slug' => 'required string', 'title' => 'optional string', 'content' => 'optional string', 'description' => 'optional string', ); } protected function defineReturnType() { return 'nonempty dict'; } protected function execute(ConduitAPIRequest $request) { $slug = $request->getValue('slug'); if ($slug === null || !strlen($slug)) { throw new Exception(pht('Field "slug" must be non-empty.')); } $doc = id(new PhrictionDocumentQuery()) ->setViewer($request->getUser()) ->withSlugs(array(PhabricatorSlug::normalize($slug))) ->needContent(true) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if (!$doc) { throw new Exception(pht('No such document.')); } $xactions = array(); if ($request->getValue('title')) { $xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentTitleTransaction::TRANSACTIONTYPE) ->setNewValue($request->getValue('title')); } if ($request->getValue('content')) { $xactions[] = id(new PhrictionTransaction()) ->setTransactionType( PhrictionDocumentContentTransaction::TRANSACTIONTYPE) ->setNewValue($request->getValue('content')); } $editor = id(new PhrictionTransactionEditor()) ->setActor($request->getUser()) ->setContentSource($request->newContentSource()) ->setContinueOnNoEffect(true) ->setDescription((string)$request->getValue('description')); try { $editor->applyTransactions($doc, $xactions); } catch (PhabricatorApplicationTransactionValidationException $ex) { // TODO - some magical hotness via T5873 throw $ex; } return $this->buildDocumentInfoDictionary($doc); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/conduit/PhrictionConduitAPIMethod.php
src/applications/phriction/conduit/PhrictionConduitAPIMethod.php
<?php abstract class PhrictionConduitAPIMethod extends ConduitAPIMethod { final public function getApplication() { return PhabricatorApplication::getByClass( 'PhabricatorPhrictionApplication'); } final protected function buildDocumentInfoDictionary(PhrictionDocument $doc) { $content = $doc->getContent(); return $this->buildDocumentContentDictionary($doc, $content); } final protected function buildDocumentContentDictionary( PhrictionDocument $doc, PhrictionContent $content) { $uri = PhrictionDocument::getSlugURI($content->getSlug()); $uri = PhabricatorEnv::getProductionURI($uri); $doc_status = $doc->getStatus(); return array( 'phid' => $doc->getPHID(), 'uri' => $uri, 'slug' => $content->getSlug(), 'version' => $content->getVersion(), 'authorPHID' => $content->getAuthorPHID(), 'title' => $content->getTitle(), 'content' => $content->getContent(), 'status' => PhrictionDocumentStatus::getConduitConstant($doc_status), 'description' => $content->getDescription(), 'dateCreated' => $content->getDateCreated(), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/conduit/PhrictionCreateConduitAPIMethod.php
src/applications/phriction/conduit/PhrictionCreateConduitAPIMethod.php
<?php final class PhrictionCreateConduitAPIMethod extends PhrictionConduitAPIMethod { public function getAPIMethodName() { return 'phriction.create'; } public function getMethodDescription() { return pht('Create a Phriction document.'); } protected function defineParamTypes() { return array( 'slug' => 'required string', 'title' => 'required string', 'content' => 'required string', 'description' => 'optional string', ); } protected function defineReturnType() { return 'nonempty dict'; } protected function execute(ConduitAPIRequest $request) { $slug = $request->getValue('slug'); if ($slug === null || !strlen($slug)) { throw new Exception(pht('Field "slug" must be non-empty.')); } $doc = id(new PhrictionDocumentQuery()) ->setViewer($request->getUser()) ->withSlugs(array(PhabricatorSlug::normalize($slug))) ->requireCapabilities( array( PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT, )) ->executeOne(); if ($doc) { throw new Exception(pht('Document already exists!')); } $doc = PhrictionDocument::initializeNewDocument( $request->getUser(), $slug); $xactions = array(); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhrictionDocumentTitleTransaction::TRANSACTIONTYPE) ->setNewValue($request->getValue('title')); $xactions[] = id(new PhrictionTransaction()) ->setTransactionType(PhrictionDocumentContentTransaction::TRANSACTIONTYPE) ->setNewValue($request->getValue('content')); $editor = id(new PhrictionTransactionEditor()) ->setActor($request->getUser()) ->setContentSource($request->newContentSource()) ->setContinueOnNoEffect(true) ->setDescription((string)$request->getValue('description')); try { $editor->applyTransactions($doc, $xactions); } catch (PhabricatorApplicationTransactionValidationException $ex) { // TODO - some magical hotness via T5873 throw $ex; } return $this->buildDocumentInfoDictionary($doc); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/conduit/PhrictionHistoryConduitAPIMethod.php
src/applications/phriction/conduit/PhrictionHistoryConduitAPIMethod.php
<?php final class PhrictionHistoryConduitAPIMethod extends PhrictionConduitAPIMethod { public function getAPIMethodName() { return 'phriction.history'; } public function getMethodDescription() { return pht('Retrieve history about a Phriction document.'); } 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 "phriction.content.search" instead.'); } protected function defineParamTypes() { return array( 'slug' => 'required string', ); } protected function defineReturnType() { return 'nonempty list'; } protected function defineErrorTypes() { return array( 'ERR-BAD-DOCUMENT' => pht('No such document exists.'), ); } protected function execute(ConduitAPIRequest $request) { $slug = $request->getValue('slug'); if ($slug === null || !strlen($slug)) { throw new Exception(pht('Field "slug" must be non-empty.')); } $doc = id(new PhrictionDocumentQuery()) ->setViewer($request->getUser()) ->withSlugs(array(PhabricatorSlug::normalize($slug))) ->executeOne(); if (!$doc) { throw new ConduitException('ERR-BAD-DOCUMENT'); } $content = id(new PhrictionContent())->loadAllWhere( 'documentID = %d ORDER BY version DESC', $doc->getID()); $results = array(); foreach ($content as $version) { $results[] = $this->buildDocumentContentDictionary( $doc, $version); } 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/phriction/conduit/PhrictionContentSearchConduitAPIMethod.php
src/applications/phriction/conduit/PhrictionContentSearchConduitAPIMethod.php
<?php final class PhrictionContentSearchConduitAPIMethod extends PhabricatorSearchEngineAPIMethod { public function getAPIMethodName() { return 'phriction.content.search'; } public function newSearchEngine() { return new PhrictionContentSearchEngine(); } public function getMethodSummary() { return pht('Read information about Phriction document history.'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/conduit/PhrictionInfoConduitAPIMethod.php
src/applications/phriction/conduit/PhrictionInfoConduitAPIMethod.php
<?php final class PhrictionInfoConduitAPIMethod extends PhrictionConduitAPIMethod { public function getAPIMethodName() { return 'phriction.info'; } public function getMethodDescription() { return pht('Retrieve information about a Phriction document.'); } 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 "phriction.document.search" instead.'); } protected function defineParamTypes() { return array( 'slug' => 'required string', ); } protected function defineReturnType() { return 'nonempty dict'; } protected function defineErrorTypes() { return array( 'ERR-BAD-DOCUMENT' => pht('No such document exists.'), ); } protected function execute(ConduitAPIRequest $request) { $slug = $request->getValue('slug'); if ($slug === null || !strlen($slug)) { throw new Exception(pht('Field "slug" must be non-empty.')); } $document = id(new PhrictionDocumentQuery()) ->setViewer($request->getUser()) ->withSlugs(array(PhabricatorSlug::normalize($slug))) ->needContent(true) ->executeOne(); if (!$document) { throw new ConduitException('ERR-BAD-DOCUMENT'); } return $this->buildDocumentInfoDictionary($document); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/search/PhrictionDocumentFerretEngine.php
src/applications/phriction/search/PhrictionDocumentFerretEngine.php
<?php final class PhrictionDocumentFerretEngine extends PhabricatorFerretEngine { public function getApplicationName() { return 'phriction'; } public function getScopeName() { return 'document'; } public function newSearchEngine() { return new PhrictionDocumentSearchEngine(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/search/PhrictionDocumentFulltextEngine.php
src/applications/phriction/search/PhrictionDocumentFulltextEngine.php
<?php final class PhrictionDocumentFulltextEngine extends PhabricatorFulltextEngine { protected function buildAbstractDocument( PhabricatorSearchAbstractDocument $document, $object) { $wiki = id(new PhrictionDocumentQuery()) ->setViewer($this->getViewer()) ->withPHIDs(array($document->getPHID())) ->needContent(true) ->executeOne(); $content = $wiki->getContent(); $document->setDocumentTitle($content->getTitle()); // TODO: These are not quite correct, but we don't currently store the // proper dates in a way that's easy to get to. $document ->setDocumentCreated($content->getDateCreated()) ->setDocumentModified($content->getDateModified()); $document->addField( PhabricatorSearchDocumentFieldType::FIELD_BODY, $content->getContent()); $document->addRelationship( PhabricatorSearchRelationship::RELATIONSHIP_AUTHOR, $content->getAuthorPHID(), PhabricatorPeopleUserPHIDType::TYPECONST, $content->getDateCreated()); $document->addRelationship( ($wiki->getStatus() == PhrictionDocumentStatus::STATUS_EXISTS) ? PhabricatorSearchRelationship::RELATIONSHIP_OPEN : PhabricatorSearchRelationship::RELATIONSHIP_CLOSED, $wiki->getPHID(), PhrictionDocumentPHIDType::TYPECONST, PhabricatorTime::getNow()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/typeahead/PhrictionDocumentDatasource.php
src/applications/phriction/typeahead/PhrictionDocumentDatasource.php
<?php final class PhrictionDocumentDatasource extends PhabricatorTypeaheadDatasource { public function getBrowseTitle() { return pht('Browse Documents'); } public function getPlaceholderText() { return pht('Type a document name...'); } public function getDatasourceApplicationClass() { return 'PhabricatorPhrictionApplication'; } public function loadResults() { $viewer = $this->getViewer(); $query = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->needContent(true); $this->applyFerretConstraints( $query, id(new PhrictionDocument())->newFerretEngine(), 'title', $this->getRawQuery()); $documents = $query->execute(); $results = array(); foreach ($documents as $document) { $content = $document->getContent(); if (!$document->isActive()) { $closed = $document->getStatusDisplayName(); } else { $closed = null; } $slug = $document->getSlug(); $title = $content->getTitle(); $sprite = 'phabricator-search-icon phui-font-fa phui-icon-view fa-book'; $autocomplete = '[[ '.$slug.' ]]'; $result = id(new PhabricatorTypeaheadResult()) ->setName($title) ->setDisplayName($title) ->setURI($document->getURI()) ->setPHID($document->getPHID()) ->setDisplayType($slug) ->setPriorityType('wiki') ->setImageSprite($sprite) ->setAutocomplete($autocomplete) ->setClosed($closed); $results[] = $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/phriction/codex/PhrictionDocumentPolicyCodex.php
src/applications/phriction/codex/PhrictionDocumentPolicyCodex.php
<?php final class PhrictionDocumentPolicyCodex extends PhabricatorPolicyCodex { public function getPolicySpecialRuleDescriptions() { $object = $this->getObject(); $strongest_policy = $this->getStrongestPolicy(); $rules = array(); $rules[] = $this->newRule() ->setDescription( pht('To view a wiki document, you must also be able to view all '. 'of its ancestors. The most-restrictive view policy of this '. 'document\'s ancestors is "%s".', $strongest_policy->getShortName())) ->setCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW)); $rules[] = $this->newRule() ->setDescription( pht('To edit a wiki document, you must also be able to view all '. 'of its ancestors.')) ->setCapabilities(array(PhabricatorPolicyCapability::CAN_EDIT)); return $rules; } public function getDefaultPolicy() { $ancestors = $this->getObject()->getAncestors(); if ($ancestors) { $root = head($ancestors); } else { $root = $this->getObject(); } $root_policy_phid = $root->getPolicy($this->getCapability()); return id(new PhabricatorPolicyQuery()) ->setViewer($this->getViewer()) ->withPHIDs(array($root_policy_phid)) ->executeOne(); } private function getStrongestPolicy() { $ancestors = $this->getObject()->getAncestors(); $ancestors[] = $this->getObject(); $strongest_policy = $this->getDefaultPolicy(); foreach ($ancestors as $ancestor) { $ancestor_policy_phid = $ancestor->getPolicy($this->getCapability()); $ancestor_policy = id(new PhabricatorPolicyQuery()) ->setViewer($this->getViewer()) ->withPHIDs(array($ancestor_policy_phid)) ->executeOne(); if ($ancestor_policy->isStrongerThan($strongest_policy)) { $strongest_policy = $ancestor_policy; } } return $strongest_policy; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/constants/PhrictionChangeType.php
src/applications/phriction/constants/PhrictionChangeType.php
<?php final class PhrictionChangeType extends PhrictionConstants { const CHANGE_EDIT = 0; const CHANGE_DELETE = 1; const CHANGE_MOVE_HERE = 2; const CHANGE_MOVE_AWAY = 3; const CHANGE_STUB = 4; public static function getChangeTypeLabel($const) { $map = array( self::CHANGE_EDIT => pht('Edit'), self::CHANGE_DELETE => pht('Delete'), self::CHANGE_MOVE_HERE => pht('Move Here'), self::CHANGE_MOVE_AWAY => pht('Move Away'), self::CHANGE_STUB => pht('Created through child'), ); return idx($map, $const, pht('Unknown')); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/constants/PhrictionDocumentStatus.php
src/applications/phriction/constants/PhrictionDocumentStatus.php
<?php final class PhrictionDocumentStatus extends PhabricatorObjectStatus { const STATUS_EXISTS = 'active'; const STATUS_DELETED = 'deleted'; const STATUS_MOVED = 'moved'; const STATUS_STUB = 'stub'; public static function getConduitConstant($const) { static $map = array( self::STATUS_EXISTS => 'exists', self::STATUS_DELETED => 'deleted', self::STATUS_MOVED => 'moved', self::STATUS_STUB => 'stubbed', ); return idx($map, $const, 'unknown'); } public static function newStatusObject($key) { return new self($key, id(new self())->getStatusSpecification($key)); } public static function getStatusMap() { $map = id(new self())->getStatusSpecifications(); return ipull($map, 'name', 'key'); } public function isActive() { return ($this->getKey() == self::STATUS_EXISTS); } protected function newStatusSpecifications() { return array( array( 'key' => self::STATUS_EXISTS, 'name' => pht('Active'), 'icon' => 'fa-file-text-o', 'color' => 'bluegrey', ), array( 'key' => self::STATUS_DELETED, 'name' => pht('Deleted'), 'icon' => 'fa-file-text-o', 'color' => 'grey', ), array( 'key' => self::STATUS_MOVED, 'name' => pht('Moved'), 'icon' => 'fa-arrow-right', 'color' => 'grey', ), array( 'key' => self::STATUS_STUB, 'name' => pht('Stub'), 'icon' => 'fa-file-text-o', 'color' => 'grey', ), ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/phriction/constants/PhrictionConstants.php
src/applications/phriction/constants/PhrictionConstants.php
<?php abstract class PhrictionConstants 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/phriction/markup/PhrictionRemarkupRule.php
src/applications/phriction/markup/PhrictionRemarkupRule.php
<?php final class PhrictionRemarkupRule extends PhutilRemarkupRule { const KEY_RULE_PHRICTION_LINK = 'phriction.link'; public function getPriority() { return 175.0; } public function apply($text) { return preg_replace_callback( '@\B\\[\\[([^|\\]]+)(?:\\|([^\\]]+))?\\]\\]\B@U', array($this, 'markupDocumentLink'), $text); } public function markupDocumentLink(array $matches) { $name = trim(idx($matches, 2, '')); if (empty($matches[2])) { $name = null; } $path = trim($matches[1]); if (!$this->isFlatText($name)) { return $matches[0]; } if (!$this->isFlatText($path)) { return $matches[0]; } // If the link contains an anchor, separate that off first. $parts = explode('#', $path, 2); if (count($parts) == 2) { $link = $parts[0]; $anchor = $parts[1]; } else { $link = $parts[0]; $anchor = null; } // Handle relative links. if ((substr($link, 0, 2) === './') || (substr($link, 0, 3) === '../')) { $base = $this->getRelativeBaseURI(); if ($base !== null) { $base_parts = explode('/', rtrim($base, '/')); $rel_parts = explode('/', rtrim($link, '/')); foreach ($rel_parts as $part) { if ($part === '.') { // Consume standalone dots in a relative path, and do // nothing with them. } else if ($part === '..') { if (count($base_parts) > 0) { array_pop($base_parts); } } else { array_push($base_parts, $part); } } $link = implode('/', $base_parts).'/'; } } // Link is now used for slug detection, so append a slash if one // is needed. $link = rtrim($link, '/').'/'; $engine = $this->getEngine(); $token = $engine->storeText('x'); $metadata = $engine->getTextMetadata( self::KEY_RULE_PHRICTION_LINK, array()); $metadata[] = array( 'token' => $token, 'link' => $link, 'anchor' => $anchor, 'explicitName' => $name, ); $engine->setTextMetadata(self::KEY_RULE_PHRICTION_LINK, $metadata); return $token; } public function didMarkupText() { $engine = $this->getEngine(); $metadata = $engine->getTextMetadata( self::KEY_RULE_PHRICTION_LINK, array()); if (!$metadata) { return; } $viewer = $engine->getConfig('viewer'); $slugs = ipull($metadata, 'link'); $load_map = array(); foreach ($slugs as $key => $raw_slug) { $lookup = PhabricatorSlug::normalize($raw_slug); $load_map[$lookup][] = $key; // Also try to lookup the slug with URL decoding applied. The right // way to link to a page titled "$cash" is to write "[[ $cash ]]" (and // not the URL encoded form "[[ %24cash ]]"), but users may reasonably // have copied URL encoded variations out of their browser location // bar or be skeptical that "[[ $cash ]]" will actually work. $lookup = phutil_unescape_uri_path_component($raw_slug); $lookup = phutil_utf8ize($lookup); $lookup = PhabricatorSlug::normalize($lookup); $load_map[$lookup][] = $key; } $visible_documents = id(new PhrictionDocumentQuery()) ->setViewer($viewer) ->withSlugs(array_keys($load_map)) ->needContent(true) ->execute(); $visible_documents = mpull($visible_documents, null, 'getSlug'); $document_map = array(); foreach ($load_map as $lookup => $keys) { $visible = idx($visible_documents, $lookup); if (!$visible) { continue; } foreach ($keys as $key) { $document_map[$key] = array( 'visible' => true, 'document' => $visible, ); } unset($load_map[$lookup]); } // For each document we found, remove all remaining requests for it from // the load map. If we remove all requests for a slug, remove the slug. // This stops us from doing unnecessary lookups on alternate names for // documents we already found. foreach ($load_map as $lookup => $keys) { foreach ($keys as $lookup_key => $key) { if (isset($document_map[$key])) { unset($keys[$lookup_key]); } } if (!$keys) { unset($load_map[$lookup]); continue; } $load_map[$lookup] = $keys; } // If we still have links we haven't found a document for, do another // query with the omnipotent viewer so we can distinguish between pages // which do not exist and pages which exist but which the viewer does not // have permission to see. if ($load_map) { $existent_documents = id(new PhrictionDocumentQuery()) ->setViewer(PhabricatorUser::getOmnipotentUser()) ->withSlugs(array_keys($load_map)) ->execute(); $existent_documents = mpull($existent_documents, null, 'getSlug'); foreach ($load_map as $lookup => $keys) { $existent = idx($existent_documents, $lookup); if (!$existent) { continue; } foreach ($keys as $key) { $document_map[$key] = array( 'visible' => false, 'document' => null, ); } } } foreach ($metadata as $key => $spec) { $link = $spec['link']; $slug = PhabricatorSlug::normalize($link); $name = $spec['explicitName']; $class = 'phriction-link'; // If the name is something meaningful to humans, we'll render this // in text as: "Title" <link>. Otherwise, we'll just render: <link>. $is_interesting_name = (bool)strlen($name); $target = idx($document_map, $key, null); if ($target === null) { // The target document doesn't exist. if ($name === null) { $name = explode('/', trim($link, '/')); $name = end($name); } $class = 'phriction-link-missing'; } else if (!$target['visible']) { // The document exists, but the user can't see it. if ($name === null) { $name = explode('/', trim($link, '/')); $name = end($name); } $class = 'phriction-link-lock'; } else { if ($name === null) { // Use the title of the document if no name is set. $name = $target['document'] ->getContent() ->getTitle(); $is_interesting_name = true; } } $uri = new PhutilURI($link); $slug = $uri->getPath(); $slug = PhabricatorSlug::normalize($slug); $slug = PhrictionDocument::getSlugURI($slug); $anchor = idx($spec, 'anchor'); $href = (string)id(new PhutilURI($slug))->setFragment($anchor); $text_mode = $this->getEngine()->isTextMode(); $mail_mode = $this->getEngine()->isHTMLMailMode(); if ($this->getEngine()->getState('toc')) { $text = $name; } else if ($text_mode || $mail_mode) { $href = PhabricatorEnv::getProductionURI($href); if ($is_interesting_name) { $text = pht('"%s" <%s>', $name, $href); } else { $text = pht('<%s>', $href); } } else { if ($class === 'phriction-link-lock') { $name = array( $this->newTag( 'i', array( 'class' => 'phui-icon-view phui-font-fa fa-lock', ), ''), ' ', $name, ); } $text = $this->newTag( 'a', array( 'href' => $href, 'class' => $class, ), $name); } $this->getEngine()->overwriteStoredText($spec['token'], $text); } } private function getRelativeBaseURI() { $context = $this->getEngine()->getConfig('contextObject'); if (!$context) { return null; } if ($context instanceof PhrictionContent) { return $context->getSlug(); } if ($context instanceof PhrictionDocument) { return $context->getContent()->getSlug(); } 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/system/controller/PhabricatorSystemSelectHighlightController.php
src/applications/system/controller/PhabricatorSystemSelectHighlightController.php
<?php final class PhabricatorSystemSelectHighlightController extends PhabricatorController { public function shouldRequireLogin() { return false; } public function processRequest() { $request = $this->getRequest(); if ($request->isFormPost()) { $result = array('highlight' => $request->getStr('highlight')); return id(new AphrontAjaxResponse())->setContent($result); } $languages = array( '' => pht('(Use Default)'), ) + PhabricatorEnv::getEnvConfig('pygments.dropdown-choices'); $form = id(new AphrontFormView()) ->setUser($this->getRequest()->getUser()) ->appendRemarkupInstructions(pht('Choose a syntax highlighting to use.')) ->appendChild( id(new AphrontFormSelectControl()) ->setLabel(pht('Highlighting')) ->setName('highlight') ->setValue($request->getStr('highlight')) ->setOptions($languages)); return $this->newDialog() ->setTitle(pht('Select Syntax Highlighting')) ->appendChild($form->buildLayoutView()) ->addSubmitButton(pht('Choose Highlighting')) ->addCancelButton('/'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/PhabricatorDebugController.php
src/applications/system/controller/PhabricatorDebugController.php
<?php /** * This controller eases debugging of application problems that don't repro * locally by allowing installs to add arbitrary debugging code easily. To use * it: * * - Write some diagnostic script. * - Instruct the user to install it in `/support/debug.php`. * - Tell them to visit `/debug/`. */ final class PhabricatorDebugController extends PhabricatorController { public function shouldRequireLogin() { return false; } public function processRequest() { if (!Filesystem::pathExists($this->getDebugFilePath())) { return new Aphront404Response(); } $request = $this->getRequest(); $user = $request->getUser(); ob_start(); require_once $this->getDebugFilePath(); $out = ob_get_clean(); $response = new AphrontWebpageResponse(); $response->setContent(phutil_tag('pre', array(), $out)); return $response; } private function getDebugFilePath() { $root = dirname(phutil_get_library_root('phabricator')); return $root.'/support/debug.php'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/PhabricatorStatusController.php
src/applications/system/controller/PhabricatorStatusController.php
<?php final class PhabricatorStatusController extends PhabricatorController { public function shouldRequireLogin() { return false; } public function processRequest() { $response = new AphrontWebpageResponse(); $response->setContent("ALIVE\n"); return $response; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/PhabricatorSystemSelectViewAsController.php
src/applications/system/controller/PhabricatorSystemSelectViewAsController.php
<?php final class PhabricatorSystemSelectViewAsController extends PhabricatorController { public function shouldRequireLogin() { return false; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $v_engine = $request->getStr('engine'); if ($request->isFormPost()) { $result = array('engine' => $v_engine); return id(new AphrontAjaxResponse())->setContent($result); } $engines = PhabricatorDocumentEngine::getAllEngines(); $options = $request->getStrList('options'); $options = array_fuse($options); // TODO: This controller is a bit rough because it isn't really using the // file ref to figure out which engines should work. See also T13513. // Callers can pass a list of "options" to control which options are // presented, at least. $ref = new PhabricatorDocumentRef(); $map = array(); foreach ($engines as $engine) { $key = $engine->getDocumentEngineKey(); if ($options && !isset($options[$key])) { continue; } $label = $engine->getViewAsLabel($ref); if (!strlen($label)) { continue; } $map[$key] = $label; } asort($map); $map = array( '' => pht('(Use Default)'), ) + $map; $form = id(new AphrontFormView()) ->setViewer($viewer) ->appendRemarkupInstructions(pht('Choose a document engine to use.')) ->appendChild( id(new AphrontFormSelectControl()) ->setLabel(pht('View As')) ->setName('engine') ->setValue($v_engine) ->setOptions($map)); return $this->newDialog() ->setTitle(pht('Select Document Engine')) ->appendForm($form) ->addSubmitButton(pht('Choose Engine')) ->addCancelButton('/'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/PhabricatorSystemObjectController.php
src/applications/system/controller/PhabricatorSystemObjectController.php
<?php final class PhabricatorSystemObjectController extends PhabricatorController { public function shouldAllowPublic() { return true; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $name = $request->getURIData('name'); $object = id(new PhabricatorObjectQuery()) ->setViewer($viewer) ->withNames(array($name)) ->executeOne(); if (!$object) { return new Aphront404Response(); } $phid = $object->getPHID(); $handles = $viewer->loadHandles(array($phid)); $handle = $handles[$phid]; $object_uri = $handle->getURI(); if (!strlen($object_uri)) { return $this->newDialog() ->setTitle(pht('No Object URI')) ->appendParagraph( pht( 'Object "%s" exists, but does not have a URI to redirect to.', $name)) ->addCancelButton('/', pht('Done')); } return id(new AphrontRedirectResponse())->setURI($object_uri); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/PhabricatorFaviconController.php
src/applications/system/controller/PhabricatorFaviconController.php
<?php final class PhabricatorFaviconController extends PhabricatorController { public function shouldRequireLogin() { return false; } public function handleRequest(AphrontRequest $request) { // See PHI1719. Phabricator uses "<link /"> tags in the document body // to direct user agents to icons, like this: // // <link rel="icon" href="..." /> // // However, some software requests the hard-coded path "/favicon.ico" // directly. To tidy the logs, serve some reasonable response rather than // a 404. // NOTE: Right now, this only works for the "PhabricatorPlatformSite". // Other sites (like custom Phame blogs) won't currently route this // path. $ref = id(new PhabricatorFaviconRef()) ->setWidth(64) ->setHeight(64); id(new PhabricatorFaviconRefQuery()) ->withRefs(array($ref)) ->execute(); return id(new AphrontRedirectResponse()) ->setIsExternal(true) ->setURI($ref->getURI()); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/PhabricatorSystemSelectEncodingController.php
src/applications/system/controller/PhabricatorSystemSelectEncodingController.php
<?php final class PhabricatorSystemSelectEncodingController extends PhabricatorController { public function shouldRequireLogin() { return false; } public function processRequest() { $request = $this->getRequest(); if (!function_exists('mb_list_encodings')) { return $this->newDialog() ->setTitle(pht('No Encoding Support')) ->appendParagraph( pht( 'This system does not have the "%s" extension installed, '. 'so character encodings are not supported. Install "%s" to '. 'enable support.', 'mbstring', 'mbstring')) ->addCancelButton('/'); } if ($request->isFormPost()) { $result = array('encoding' => $request->getStr('encoding')); return id(new AphrontAjaxResponse())->setContent($result); } $encodings = mb_list_encodings(); $encodings = array_fuse($encodings); asort($encodings); unset($encodings['pass']); unset($encodings['auto']); $encodings = array( '' => pht('(Use Default)'), ) + $encodings; $form = id(new AphrontFormView()) ->setUser($this->getRequest()->getUser()) ->appendRemarkupInstructions(pht('Choose a text encoding to use.')) ->appendChild( id(new AphrontFormSelectControl()) ->setLabel(pht('Encoding')) ->setName('encoding') ->setValue($request->getStr('encoding')) ->setOptions($encodings)); return $this->newDialog() ->setTitle(pht('Select Character Encoding')) ->appendChild($form->buildLayoutView()) ->addSubmitButton(pht('Choose Encoding')) ->addCancelButton('/'); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/PhabricatorSystemReadOnlyController.php
src/applications/system/controller/PhabricatorSystemReadOnlyController.php
<?php final class PhabricatorSystemReadOnlyController extends PhabricatorController { public function shouldRequireLogin() { return false; } public function handleRequest(AphrontRequest $request) { $viewer = $this->getViewer(); $reason = $request->getURIData('reason'); $body = array(); switch ($reason) { case PhabricatorEnv::READONLY_CONFIG: $title = pht('Administrative Read-Only Mode'); $body[] = pht( 'An administrator has placed this server into read-only mode.'); $body[] = pht( 'This mode may be used to perform temporary maintenance, test '. 'configuration, or archive an installation permanently.'); $body[] = pht( 'Read-only mode was enabled by the explicit action of a human '. 'administrator, so you can get more information about why it '. 'has been turned on by rolling your chair away from your desk and '. 'yelling "Hey! Why is %s in read-only mode??!" using '. 'your very loudest outside voice.', PlatformSymbols::getPlatformServerSymbol()); $body[] = pht( 'This mode is active because it is enabled in the configuration '. 'option "%s".', phutil_tag('tt', array(), 'cluster.read-only')); $button = pht('Wait Patiently'); break; case PhabricatorEnv::READONLY_MASTERLESS: $title = pht('No Writable Database'); $body[] = pht( 'This server is currently configured with no writable ("master") '. 'database, so it can not write new information anywhere. '. 'This server will run in read-only mode until an administrator '. 'reconfigures it with a writable database.'); $body[] = pht( 'This usually occurs when an administrator is actively working on '. 'fixing a temporary configuration or deployment problem.'); $body[] = pht( 'This mode is active because no database has a "%s" role in '. 'the configuration option "%s".', phutil_tag('tt', array(), 'master'), phutil_tag('tt', array(), 'cluster.databases')); $button = pht('Wait Patiently'); break; case PhabricatorEnv::READONLY_UNREACHABLE: $title = pht('Unable to Reach Master'); $body[] = pht( 'This server was unable to connect to the writable ("master") '. 'database while handling this request, and automatically degraded '. 'into read-only mode.'); $body[] = pht( 'This may happen if there is a temporary network anomaly on the '. 'server side, like cosmic radiation or spooky ghosts. If this '. 'failure was caused by a transient service interruption, '. 'this server will recover momentarily.'); $body[] = pht( 'This may also indicate that a more serious failure has occurred. '. 'If this interruption does not resolve on its own, this server '. 'will soon detect the persistent disruption and degrade into '. 'read-only mode until the issue is resolved.'); $button = pht('Quite Unsettling'); break; case PhabricatorEnv::READONLY_SEVERED: $title = pht('Severed From Master'); $body[] = pht( 'This server has consistently been unable to reach the writable '. '("master") database while processing recent requests.'); $body[] = pht( 'This likely indicates a severe misconfiguration or major service '. 'interruption.'); $body[] = pht( 'This server will periodically retry the connection and recover '. 'once service is restored. Most causes of persistent service '. 'interruption will require administrative intervention in order '. 'to restore service.'); $body[] = pht( 'Although this may be the result of a misconfiguration or '. 'operational error, this is also the state you reach if a '. 'meteor recently obliterated a datacenter.'); $button = pht('Panic!'); break; default: return new Aphront404Response(); } switch ($reason) { case PhabricatorEnv::READONLY_UNREACHABLE: case PhabricatorEnv::READONLY_SEVERED: $body[] = pht( 'This request was served from a replica database. Replica '. 'databases may lag behind the master, so very recent activity '. 'may not be reflected in the UI. This data will be restored if '. 'the master database is restored, but may have been lost if the '. 'master database has been reduced to a pile of ash.'); break; } $body[] = pht( 'In read-only mode you can read existing information, but you will not '. 'be able to edit objects or create new objects until this mode is '. 'disabled.'); if ($viewer->getIsAdmin()) { $body[] = pht( 'As an administrator, you can review status information from the '. '%s control panel. This may provide more information about the '. 'current state of affairs.', phutil_tag( 'a', array( 'href' => '/config/cluster/databases/', ), pht('Cluster Database Status'))); } $dialog = $this->newDialog() ->setTitle($title) ->setWidth(AphrontDialogView::WIDTH_FORM) ->addCancelButton('/', $button); foreach ($body as $paragraph) { $dialog->appendParagraph($paragraph); } return $dialog; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/robots/PhabricatorRobotsBlogController.php
src/applications/system/controller/robots/PhabricatorRobotsBlogController.php
<?php final class PhabricatorRobotsBlogController extends PhabricatorRobotsController { protected function newRobotsRules() { $out = array(); // Allow everything on blog domains to be indexed. $out[] = 'User-Agent: *'; $out[] = 'Crawl-delay: 1'; return $out; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/robots/PhabricatorRobotsShortController.php
src/applications/system/controller/robots/PhabricatorRobotsShortController.php
<?php final class PhabricatorRobotsShortController extends PhabricatorRobotsController { protected function newRobotsRules() { $out = array(); // See T13636. Prevent indexing of any content on short domains. $out[] = 'User-Agent: *'; $out[] = 'Disallow: /'; $out[] = 'Crawl-delay: 1'; return $out; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/robots/PhabricatorRobotsResourceController.php
src/applications/system/controller/robots/PhabricatorRobotsResourceController.php
<?php final class PhabricatorRobotsResourceController extends PhabricatorRobotsController { protected function newRobotsRules() { $out = array(); // See T13636. Prevent indexing of any content on resource domains. $out[] = 'User-Agent: *'; $out[] = 'Disallow: /'; $out[] = 'Crawl-delay: 1'; return $out; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/robots/PhabricatorRobotsPlatformController.php
src/applications/system/controller/robots/PhabricatorRobotsPlatformController.php
<?php final class PhabricatorRobotsPlatformController extends PhabricatorRobotsController { protected function newRobotsRules() { $out = array(); // Prevent indexing of '/diffusion/', since the content is not generally // useful to index, web spiders get stuck scraping the history of every // file, and much of the content is Ajaxed in anyway so spiders won't even // see it. These pages are also relatively expensive to generate. // Note that this still allows commits (at '/rPxxxxx') to be indexed. // They're probably not hugely useful, but suffer fewer of the problems // Diffusion suffers and are hard to omit with 'robots.txt'. $out[] = 'User-Agent: *'; $out[] = 'Disallow: /diffusion/'; $out[] = 'Disallow: /source/'; // Add a small crawl delay (number of seconds between requests) for spiders // which respect it. The intent here is to prevent spiders from affecting // performance for users. The possible cost is slower indexing, but that // seems like a reasonable tradeoff, since most Phabricator installs are // probably not hugely concerned about cutting-edge SEO. $out[] = 'Crawl-delay: 1'; return $out; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/controller/robots/PhabricatorRobotsController.php
src/applications/system/controller/robots/PhabricatorRobotsController.php
<?php abstract class PhabricatorRobotsController extends PhabricatorController { public function shouldRequireLogin() { return false; } final public function processRequest() { $out = $this->newRobotsRules(); $content = implode("\n", $out)."\n"; return id(new AphrontPlainTextResponse()) ->setContent($content) ->setCacheDurationInSeconds(phutil_units('2 hours in seconds')) ->setCanCDN(true); } abstract protected function newRobotsRules(); }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/storage/PhabricatorSystemActionLog.php
src/applications/system/storage/PhabricatorSystemActionLog.php
<?php final class PhabricatorSystemActionLog extends PhabricatorSystemDAO { protected $actorHash; protected $actorIdentity; protected $action; protected $score; protected $epoch; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'actorHash' => 'bytes12', 'actorIdentity' => 'text255', 'action' => 'text32', 'score' => 'double', ), self::CONFIG_KEY_SCHEMA => array( 'key_epoch' => array( 'columns' => array('epoch'), ), 'key_action' => array( 'columns' => array('actorHash', 'action', 'epoch'), ), ), ) + parent::getConfiguration(); } public function setActorIdentity($identity) { $this->setActorHash(PhabricatorHash::digestForIndex($identity)); return parent::setActorIdentity($identity); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/storage/PhabricatorSystemDestructionLog.php
src/applications/system/storage/PhabricatorSystemDestructionLog.php
<?php final class PhabricatorSystemDestructionLog extends PhabricatorSystemDAO { protected $objectClass; protected $rootLogID; protected $objectPHID; protected $objectMonogram; protected $epoch; protected function getConfiguration() { return array( self::CONFIG_TIMESTAMPS => false, self::CONFIG_COLUMN_SCHEMA => array( 'objectClass' => 'text128', 'rootLogID' => 'id?', 'objectPHID' => 'phid?', 'objectMonogram' => 'text64?', ), self::CONFIG_KEY_SCHEMA => array( 'key_epoch' => array( 'columns' => array('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/system/storage/PhabricatorSystemDAO.php
src/applications/system/storage/PhabricatorSystemDAO.php
<?php abstract class PhabricatorSystemDAO extends PhabricatorLiskDAO { public function getApplicationName() { return 'system'; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/management/PhabricatorSystemRemoveWorkflow.php
src/applications/system/management/PhabricatorSystemRemoveWorkflow.php
<?php abstract class PhabricatorSystemRemoveWorkflow extends PhabricatorManagementWorkflow {}
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/management/PhabricatorSystemRemoveDestroyWorkflow.php
src/applications/system/management/PhabricatorSystemRemoveDestroyWorkflow.php
<?php final class PhabricatorSystemRemoveDestroyWorkflow extends PhabricatorSystemRemoveWorkflow { protected function didConstruct() { $this ->setName('destroy') ->setSynopsis(pht('Permanently destroy objects.')) ->setExamples('**destroy** [__options__] __object__ ...') ->setArguments( array( array( 'name' => 'force', 'help' => pht('Destroy objects without prompting.'), ), array( 'name' => 'objects', 'wildcard' => true, ), )); } public function execute(PhutilArgumentParser $args) { $console = PhutilConsole::getConsole(); $object_names = $args->getArg('objects'); if (!$object_names) { throw new PhutilArgumentUsageException( pht('Specify one or more objects to destroy.')); } $object_query = id(new PhabricatorObjectQuery()) ->setViewer($this->getViewer()) ->withNames($object_names); $object_query->execute(); $named_objects = $object_query->getNamedResults(); foreach ($object_names as $object_name) { if (empty($named_objects[$object_name])) { throw new PhutilArgumentUsageException( pht('No such object "%s" exists!', $object_name)); } } foreach ($named_objects as $object_name => $object) { if (!($object instanceof PhabricatorDestructibleInterface)) { throw new PhutilArgumentUsageException( pht( 'Object "%s" can not be destroyed (it does not implement %s).', $object_name, 'PhabricatorDestructibleInterface')); } } $banner = <<<EOBANNER uuuuuuu uu###########uu uu#################uu u#####################u u#######################u u#########################u u#########################u u######" "###" "######u "####" u#u ####" ###u u#u u### ###u u###u u### "####uu### ###uu####" "#######" "#######" u#######u#######u u#"#"#"#"#"#"#u uuu ##u# # # # #u## uuu u#### #####u#u#u### u#### #####uu "#########" uu###### u###########uu """"" uuuu########## ####"""##########uuu uu#########"""###" """ ""###########uu ""#""" uuuu ""##########uuu u###uuu#########uu ""###########uuu### ##########"""" ""###########" "#####" ""####"" ###" ####" EOBANNER; $console->writeOut("\n\n<fg:red>%s</fg>\n\n", $banner); $console->writeOut( "<bg:red>** %s **</bg> %s\n\n%s\n\n". "<bg:red>** %s **</bg> %s\n\n%s\n\n", pht('IMPORTANT'), pht('DATA WILL BE PERMANENTLY DESTROYED'), phutil_console_wrap( pht( 'Objects will be permanently destroyed. There is no way to '. 'undo this operation or ever retrieve this data unless you '. 'maintain external backups.')), pht('IMPORTANT'), pht('DELETING OBJECTS OFTEN BREAKS THINGS'), phutil_console_wrap( pht( 'Destroying objects may cause related objects to stop working, '. 'and may leave scattered references to objects which no longer '. 'exist. In most cases, it is much better to disable or archive '. 'objects instead of destroying them. This risk is greatest when '. 'deleting complex or highly connected objects like repositories, '. 'projects and users.'. "\n\n". 'These tattered edges are an expected consequence of destroying '. 'objects, and the upstream will not help you fix them. We '. 'strongly recommend disabling or archiving objects instead.'))); $phids = mpull($named_objects, 'getPHID'); $handles = PhabricatorUser::getOmnipotentUser()->loadHandles($phids); $console->writeOut( pht( 'These %s object(s) will be destroyed forever:', phutil_count($named_objects))."\n\n"); foreach ($named_objects as $object_name => $object) { $phid = $object->getPHID(); $console->writeOut( " - %s (%s) %s\n", $object_name, get_class($object), $handles[$phid]->getFullName()); } $force = $args->getArg('force'); if (!$force) { $ok = $console->confirm( pht( 'Are you absolutely certain you want to destroy these %s object(s)?', phutil_count($named_objects))); if (!$ok) { throw new PhutilArgumentUsageException( pht('Aborted, your objects are safe.')); } } $console->writeOut("%s\n", pht('Destroying objects...')); $notes = array(); foreach ($named_objects as $object_name => $object) { $console->writeOut( pht( "Destroying %s **%s**...\n", get_class($object), $object_name)); $engine = id(new PhabricatorDestructionEngine()) ->setCollectNotes(true); $engine->destroyObject($object); foreach ($engine->getNotes() as $note) { $notes[] = $note; } } $console->writeOut( "%s\n", pht( 'Permanently destroyed %s object(s).', phutil_count($named_objects))); if ($notes) { id(new PhutilConsoleList()) ->addItems($notes) ->draw(); } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/management/PhabricatorSystemRemoveLogWorkflow.php
src/applications/system/management/PhabricatorSystemRemoveLogWorkflow.php
<?php final class PhabricatorSystemRemoveLogWorkflow extends PhabricatorSystemRemoveWorkflow { protected function didConstruct() { $this ->setName('log') ->setSynopsis(pht('Show a log of permanently destroyed objects.')) ->setExamples('**log**') ->setArguments(array()); } public function execute(PhutilArgumentParser $args) { $console = PhutilConsole::getConsole(); $table = new PhabricatorSystemDestructionLog(); foreach (new LiskMigrationIterator($table) as $row) { $console->writeOut( "[%s]\t%s %s\t%s\t%s\n", phabricator_datetime($row->getEpoch(), $this->getViewer()), ($row->getRootLogID() ? ' ' : '*'), $row->getObjectClass(), $row->getObjectPHID(), $row->getObjectMonogram()); } return 0; } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/interface/PhabricatorDestructibleCodexInterface.php
src/applications/system/interface/PhabricatorDestructibleCodexInterface.php
<?php interface PhabricatorDestructibleCodexInterface { public function newDestructibleCodex(); } // TEMPLATE IMPLEMENTATION ///////////////////////////////////////////////////// /* -( PhabricatorDestructibleCodexInterface )------------------------------ */ /* public function newDestructibleCodex() { return new <<...>>DestructibleCodex(); } */
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/interface/PhabricatorDestructibleInterface.php
src/applications/system/interface/PhabricatorDestructibleInterface.php
<?php interface PhabricatorDestructibleInterface { public function destroyObjectPermanently( PhabricatorDestructionEngine $engine); } // TEMPLATE IMPLEMENTATION ///////////////////////////////////////////////////// /* -( PhabricatorDestructibleInterface )----------------------------------- */ /* public function destroyObjectPermanently( PhabricatorDestructionEngine $engine) { <<<$this->nuke();>>> } */
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/interface/PhabricatorUnlockableInterface.php
src/applications/system/interface/PhabricatorUnlockableInterface.php
<?php interface PhabricatorUnlockableInterface { public function newUnlockEngine(); } // TEMPLATE IMPLEMENTATION ///////////////////////////////////////////////////// /* -( PhabricatorUnlockableInterface )------------------------------------- */ /* public function newUnlockEngine() { return new <<<...>>>UnlockEngine(); } */
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/action/PhabricatorSystemAction.php
src/applications/system/action/PhabricatorSystemAction.php
<?php abstract class PhabricatorSystemAction extends Phobject { final public function getActionConstant() { return $this->getPhobjectClassConstant('TYPECONST', 32); } abstract public function getScoreThreshold(); public function shouldBlockActor($actor, $score) { return ($score > $this->getScoreThreshold()); } public function getLimitExplanation() { return pht('You are performing too many actions too quickly.'); } public function getRateExplanation($score) { return pht( 'The maximum allowed rate for this action is %s. You are taking '. 'actions at a rate of %s.', $this->formatRate($this->getScoreThreshold()), $this->formatRate($score)); } protected function formatRate($rate) { if ($rate > 10) { $str = pht('%d / second', $rate); } else { $rate *= 60; if ($rate > 10) { $str = pht('%d / minute', $rate); } else { $rate *= 60; $str = pht('%d / hour', $rate); } } return phutil_tag('strong', array(), $str); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/exception/PhabricatorSystemActionRateLimitException.php
src/applications/system/exception/PhabricatorSystemActionRateLimitException.php
<?php final class PhabricatorSystemActionRateLimitException extends Exception { private $action; private $score; public function __construct(PhabricatorSystemAction $action, $score) { $this->action = $action; $this->score = $score; parent::__construct($action->getLimitExplanation()); } public function getRateExplanation() { return $this->action->getRateExplanation($this->score); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/application/PhabricatorSystemApplication.php
src/applications/system/application/PhabricatorSystemApplication.php
<?php final class PhabricatorSystemApplication extends PhabricatorApplication { public function getName() { return pht('System'); } public function canUninstall() { return false; } public function isUnlisted() { return true; } public function getEventListeners() { return array( new PhabricatorSystemDebugUIEventListener(), ); } public function getRoutes() { return array( '/status/' => 'PhabricatorStatusController', '/debug/' => 'PhabricatorDebugController', '/favicon.ico' => 'PhabricatorFaviconController', '/robots.txt' => 'PhabricatorRobotsPlatformController', '/services/' => array( 'encoding/' => 'PhabricatorSystemSelectEncodingController', 'highlight/' => 'PhabricatorSystemSelectHighlightController', 'viewas/' => 'PhabricatorSystemSelectViewAsController', ), '/readonly/' => array( '(?P<reason>[^/]+)/' => 'PhabricatorSystemReadOnlyController', ), '/object/(?P<name>[^/]+)/' => 'PhabricatorSystemObjectController', ); } public function getResourceRoutes() { return array( '/status/' => 'PhabricatorStatusController', '/favicon.ico' => 'PhabricatorFaviconController', '/robots.txt' => 'PhabricatorRobotsResourceController', ); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/events/PhabricatorSystemDebugUIEventListener.php
src/applications/system/events/PhabricatorSystemDebugUIEventListener.php
<?php final class PhabricatorSystemDebugUIEventListener extends PhabricatorEventListener { public function register() { $this->listen(PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS); } public function handleEvent(PhutilEvent $event) { switch ($event->getType()) { case PhabricatorEventType::TYPE_UI_DIDRENDERACTIONS: $this->handleActionEvent($event); break; } } private function handleActionEvent($event) { $viewer = $event->getUser(); $object = $event->getValue('object'); if (!PhabricatorEnv::getEnvConfig('phabricator.developer-mode')) { return; } if (!$object || !$object->getPHID()) { // If we have no object, or the object doesn't have a PHID, we can't // do anything useful. return; } $phid = $object->getPHID(); $submenu = array(); $submenu[] = id(new PhabricatorActionView()) ->setIcon('fa-asterisk') ->setName(pht('View Handle')) ->setHref(urisprintf('/search/handle/%s/', $phid)) ->setWorkflow(true); $submenu[] = id(new PhabricatorActionView()) ->setIcon('fa-address-card-o') ->setName(pht('View Hovercard')) ->setHref(urisprintf('/search/hovercard/?names=%s', $phid)); if ($object instanceof DifferentialRevision) { $submenu[] = id(new PhabricatorActionView()) ->setIcon('fa-database') ->setName(pht('View Affected Path Index')) ->setHref( urisprintf( '/differential/revision/paths/%s/', $object->getID())); } $developer_action = id(new PhabricatorActionView()) ->setName(pht('Advanced/Developer...')) ->setIcon('fa-magic') ->setOrder(9001) ->setSubmenu($submenu); $actions = $event->getValue('actions'); $actions[] = $developer_action; $event->setValue('actions', $actions); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/garbagecollector/PhabricatorSystemDestructionGarbageCollector.php
src/applications/system/garbagecollector/PhabricatorSystemDestructionGarbageCollector.php
<?php final class PhabricatorSystemDestructionGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'system.destruction.logs'; public function getCollectorName() { return pht('Destruction Logs'); } public function getDefaultRetentionPolicy() { return phutil_units('90 days in seconds'); } protected function collectGarbage() { $table = new PhabricatorSystemDestructionLog(); $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
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/garbagecollector/PhabricatorSystemActionGarbageCollector.php
src/applications/system/garbagecollector/PhabricatorSystemActionGarbageCollector.php
<?php final class PhabricatorSystemActionGarbageCollector extends PhabricatorGarbageCollector { const COLLECTORCONST = 'system.actions'; public function getCollectorName() { return pht('Rate Limiting Actions'); } public function getDefaultRetentionPolicy() { return phutil_units('3 days in seconds'); } protected function collectGarbage() { $table = new PhabricatorSystemActionLog(); $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
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/engine/PhabricatorDestructionEngine.php
src/applications/system/engine/PhabricatorDestructionEngine.php
<?php final class PhabricatorDestructionEngine extends Phobject { private $rootLogID; private $collectNotes; private $notes = array(); private $depth = 0; private $destroyedObjects = array(); private $waitToFinalizeDestruction = false; public function setCollectNotes($collect_notes) { $this->collectNotes = $collect_notes; return $this; } public function getNotes() { return $this->notes; } public function getViewer() { return PhabricatorUser::getOmnipotentUser(); } public function setWaitToFinalizeDestruction($wait) { $this->waitToFinalizeDestruction = $wait; return $this; } public function getWaitToFinalizeDestruction() { return $this->waitToFinalizeDestruction; } public function destroyObject(PhabricatorDestructibleInterface $object) { $this->depth++; $log = id(new PhabricatorSystemDestructionLog()) ->setEpoch(PhabricatorTime::getNow()) ->setObjectClass(get_class($object)); if ($this->rootLogID) { $log->setRootLogID($this->rootLogID); } $object_phid = $this->getObjectPHID($object); if ($object_phid) { $log->setObjectPHID($object_phid); } if (method_exists($object, 'getMonogram')) { try { $log->setObjectMonogram($object->getMonogram()); } catch (Exception $ex) { // Ignore. } } $log->save(); if (!$this->rootLogID) { $this->rootLogID = $log->getID(); } if ($this->collectNotes) { if ($object instanceof PhabricatorDestructibleCodexInterface) { $codex = PhabricatorDestructibleCodex::newFromObject( $object, $this->getViewer()); foreach ($codex->getDestructionNotes() as $note) { $this->notes[] = $note; } } } $object->destroyObjectPermanently($this); if ($object_phid) { $extensions = PhabricatorDestructionEngineExtension::getAllExtensions(); foreach ($extensions as $key => $extension) { if (!$extension->canDestroyObject($this, $object)) { unset($extensions[$key]); continue; } } foreach ($extensions as $key => $extension) { $extension->destroyObject($this, $object); } $this->destroyedObjects[] = $object; } $this->depth--; // If this is a root-level invocation of "destroyObject()", flush the // queue of destroyed objects and fire "didDestroyObject()" hooks. This // hook allows extensions to do things like queue cache updates which // might race if we fire them during object destruction. if (!$this->depth) { if (!$this->getWaitToFinalizeDestruction()) { $this->finalizeDestruction(); } } return $this; } public function finalizeDestruction() { $extensions = PhabricatorDestructionEngineExtension::getAllExtensions(); foreach ($this->destroyedObjects as $object) { foreach ($extensions as $extension) { if (!$extension->canDestroyObject($this, $object)) { continue; } $extension->didDestroyObject($this, $object); } } $this->destroyedObjects = array(); return $this; } private function getObjectPHID($object) { if (!is_object($object)) { return null; } if (!method_exists($object, 'getPHID')) { return null; } try { return $object->getPHID(); } catch (Exception $ex) { 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/system/engine/PhabricatorUnlockEngine.php
src/applications/system/engine/PhabricatorUnlockEngine.php
<?php abstract class PhabricatorUnlockEngine extends Phobject { final public static function newUnlockEngineForObject($object) { if (!($object instanceof PhabricatorApplicationTransactionInterface)) { throw new Exception( pht( 'Object ("%s") does not implement interface "%s", so this type '. 'of object can not be unlocked.', phutil_describe_type($object), 'PhabricatorApplicationTransactionInterface')); } if ($object instanceof PhabricatorUnlockableInterface) { $engine = $object->newUnlockEngine(); } else { $engine = new PhabricatorDefaultUnlockEngine(); } return $engine; } public function newUnlockViewTransactions($object, $user) { $type_view = PhabricatorTransactions::TYPE_VIEW_POLICY; if (!$this->canApplyTransactionType($object, $type_view)) { throw new Exception( pht( 'Object view policy can not be unlocked because this object '. 'does not have a mutable view policy.')); } return array( $this->newTransaction($object) ->setTransactionType($type_view) ->setNewValue($user->getPHID()), ); } public function newUnlockEditTransactions($object, $user) { $type_edit = PhabricatorTransactions::TYPE_EDIT_POLICY; if (!$this->canApplyTransactionType($object, $type_edit)) { throw new Exception( pht( 'Object edit policy can not be unlocked because this object '. 'does not have a mutable edit policy.')); } return array( $this->newTransaction($object) ->setTransactionType($type_edit) ->setNewValue($user->getPHID()), ); } public function newUnlockOwnerTransactions($object, $user) { throw new Exception( pht( 'Object owner can not be unlocked: the unlocking engine ("%s") for '. 'this object does not implement an owner unlocking mechanism.', get_class($this))); } final protected function canApplyTransactionType($object, $type) { $xaction_types = $object->getApplicationTransactionEditor() ->getTransactionTypesForObject($object); $xaction_types = array_fuse($xaction_types); return isset($xaction_types[$type]); } final protected function newTransaction($object) { return $object->getApplicationTransactionTemplate(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false
phacility/phabricator
https://github.com/phacility/phabricator/blob/5720a38cfe95b00ca4be5016dd0d2f3195f4fa04/src/applications/system/engine/PhabricatorDestructionEngineExtension.php
src/applications/system/engine/PhabricatorDestructionEngineExtension.php
<?php abstract class PhabricatorDestructionEngineExtension extends Phobject { final public function getExtensionKey() { return $this->getPhobjectClassConstant('EXTENSIONKEY'); } abstract public function getExtensionName(); public function canDestroyObject( PhabricatorDestructionEngine $engine, $object) { return true; } public function destroyObject( PhabricatorDestructionEngine $engine, $object) { return null; } public function didDestroyObject( PhabricatorDestructionEngine $engine, $object) { return null; } final public static function getAllExtensions() { return id(new PhutilClassMapQuery()) ->setAncestorClass(__CLASS__) ->setUniqueMethod('getExtensionKey') ->execute(); } }
php
Apache-2.0
5720a38cfe95b00ca4be5016dd0d2f3195f4fa04
2026-01-04T15:03:23.651835Z
false