public function render()
 {
     $application = $this->application;
     require_celerity_resource('phabricator-application-launch-view-css');
     $content = array();
     $content[] = phutil_render_tag('span', array('class' => 'phabricator-application-launch-name'), phutil_escape_html($application->getName()));
     $content[] = phutil_render_tag('span', array('class' => 'phabricator-application-launch-description'), phutil_escape_html($application->getShortDescription()));
     $count = 0;
     if ($this->status) {
         $content[] = '<span class="phabricator-application-status-block">';
         foreach ($this->status as $status) {
             $count += $status->getCount();
             $content[] = $status;
         }
         $content[] = '</span>';
     }
     if ($count) {
         $content[] = phutil_render_tag('span', array('class' => 'phabricator-application-launch-attention'), phutil_escape_html($count));
     }
     $classes = array();
     $classes[] = 'phabricator-application-launch-icon';
     $styles = array();
     if ($application->getIconURI()) {
         $styles[] = 'background-image: url(' . $application->getIconURI() . ')';
     } else {
         $autosprite = $application->getAutospriteName();
         $classes[] = 'autosprite';
         $classes[] = 'app-' . $autosprite . '-full';
     }
     $icon = phutil_render_tag('span', array('class' => implode(' ', $classes), 'style' => nonempty(implode('; ', $styles), null)), '');
     return phutil_render_tag('a', array('class' => 'phabricator-application-launch-container', 'href' => $application->getBaseURI()), $icon . $this->renderSingleView($content));
 }
 public static function getLog()
 {
     if (!self::$log) {
         $path = PhabricatorEnv::getEnvConfig('log.ssh.path');
         $format = PhabricatorEnv::getEnvConfig('log.ssh.format');
         $format = nonempty($format, "[%D]\t%p\t%h\t%r\t%s\t%S\t%u\t%C\t%U\t%c\t%T\t%i\t%o");
         // NOTE: Path may be null. We still create the log, it just won't write
         // anywhere.
         $data = array('D' => date('r'), 'h' => php_uname('n'), 'p' => getmypid(), 'e' => time());
         $sudo_user = PhabricatorEnv::getEnvConfig('phd.user');
         if (strlen($sudo_user)) {
             $data['S'] = $sudo_user;
         }
         if (function_exists('posix_geteuid')) {
             $system_uid = posix_geteuid();
             $system_info = posix_getpwuid($system_uid);
             $data['s'] = idx($system_info, 'name');
         }
         $client = getenv('SSH_CLIENT');
         if (strlen($client)) {
             $remote_address = head(explode(' ', $client));
             $data['r'] = $remote_address;
         }
         $log = id(new PhutilDeferredLog($path, $format))->setFailQuietly(true)->setData($data);
         self::$log = $log;
     }
     return self::$log;
 }
 public function execute(HarbormasterBuild $build, HarbormasterBuildTarget $build_target)
 {
     $viewer = PhabricatorUser::getOmnipotentUser();
     $settings = $this->getSettings();
     $variables = $build_target->getVariables();
     $uri = $this->mergeVariables('vurisprintf', $settings['uri'], $variables);
     $method = nonempty(idx($settings, 'method'), 'POST');
     $future = id(new HTTPSFuture($uri))->setMethod($method)->setTimeout(60);
     $credential_phid = $this->getSetting('credential');
     if ($credential_phid) {
         $key = PassphrasePasswordKey::loadFromPHID($credential_phid, $viewer);
         $future->setHTTPBasicAuthCredentials($key->getUsernameEnvelope()->openEnvelope(), $key->getPasswordEnvelope());
     }
     $this->resolveFutures($build, $build_target, array($future));
     list($status, $body, $headers) = $future->resolve();
     $header_lines = array();
     // TODO: We don't currently preserve the entire "HTTP" response header, but
     // should. Once we do, reproduce it here faithfully.
     $status_code = $status->getStatusCode();
     $header_lines[] = "HTTP {$status_code}";
     foreach ($headers as $header) {
         list($head, $tail) = $header;
         $header_lines[] = "{$head}: {$tail}";
     }
     $header_lines = implode("\n", $header_lines);
     $build_target->newLog($uri, 'http.head')->append($header_lines);
     $build_target->newLog($uri, 'http.body')->append($body);
     if ($status->isError()) {
         throw new HarbormasterBuildFailureException();
     }
 }
 protected function validateTransaction(PhabricatorLiskDAO $object, $type, array $xactions)
 {
     $errors = parent::validateTransaction($object, $type, $xactions);
     switch ($type) {
         case PhortuneAccountTransaction::TYPE_NAME:
             $missing = $this->validateIsEmptyTextField($object->getName(), $xactions);
             if ($missing) {
                 $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('Account name is required.'), nonempty(last($xactions), null));
                 $error->setIsMissingFieldError(true);
                 $errors[] = $error;
             }
             break;
         case PhabricatorTransactions::TYPE_EDGE:
             foreach ($xactions as $xaction) {
                 switch ($xaction->getMetadataValue('edge:type')) {
                     case PhortuneAccountHasMemberEdgeType::EDGECONST:
                         // TODO: This is a bit cumbersome, but validation happens before
                         // transaction normalization. Maybe provide a cleaner attack on
                         // this eventually? There's no way to generate "+" or "-"
                         // transactions right now.
                         $new = $xaction->getNewValue();
                         $set = idx($new, '=', array());
                         if (empty($set[$this->requireActor()->getPHID()])) {
                             $error = new PhabricatorApplicationTransactionValidationError($type, pht('Invalid'), pht('You can not remove yourself as an account member.'), $xaction);
                             $errors[] = $error;
                         }
                         break;
                 }
             }
             break;
     }
     return $errors;
 }
 protected function getTagContent()
 {
     if ($this->previewURI === null) {
         throw new PhutilInvalidStateException('setPreviewURI');
     }
     if ($this->controlID === null) {
         throw new PhutilInvalidStateException('setControlID');
     }
     $preview_id = celerity_generate_unique_node_id();
     require_celerity_resource('phui-remarkup-preview-css');
     Javelin::initBehavior('remarkup-preview', array('previewID' => $preview_id, 'controlID' => $this->controlID, 'uri' => $this->previewURI));
     $loading = phutil_tag('div', array('class' => 'phui-preview-loading-text'), nonempty($this->loadingText, pht('Loading preview...')));
     $header = null;
     if ($this->header) {
         $header = phutil_tag('div', array('class' => 'phui-preview-header'), $this->header);
     }
     $preview = phutil_tag('div', array('id' => $preview_id, 'class' => 'phabricator-remarkup'), $loading);
     $content = array($header, $preview);
     switch ($this->skin) {
         case 'document':
             $content = id(new PHUIDocumentView())->appendChild($content)->setFontKit(PHUIDocumentView::FONT_SOURCE_SANS);
             break;
         default:
             $content = id(new PHUIBoxView())->appendChild($content)->setBorder(true)->addMargin(PHUI::MARGIN_LARGE)->addPadding(PHUI::PADDING_LARGE)->addClass('phui-panel-preview');
             break;
     }
     return $content;
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $viewer = $request->getUser();
     $query = $request->getStr('q');
     // Default this to the query string to make debugging a little bit easier.
     $raw_query = nonempty($request->getStr('raw'), $query);
     // This makes form submission easier in the debug view.
     $this->class = nonempty($request->getStr('class'), $this->class);
     $sources = id(new PhutilSymbolLoader())->setAncestorClass('PhabricatorTypeaheadDatasource')->loadObjects();
     if (isset($sources[$this->class])) {
         $source = $sources[$this->class];
         $source->setParameters($request->getRequestData());
         $composite = new PhabricatorTypeaheadRuntimeCompositeDatasource();
         $composite->addDatasource($source);
         $composite->setViewer($viewer)->setQuery($query)->setRawQuery($raw_query);
         $results = $composite->loadResults();
     } else {
         $results = array();
     }
     $content = mpull($results, 'getWireFormat');
     if ($request->isAjax()) {
         return id(new AphrontAjaxResponse())->setContent($content);
     }
     // If there's a non-Ajax request to this endpoint, show results in a tabular
     // format to make it easier to debug typeahead output.
     $options = array_fuse(array_keys($sources));
     asort($options);
     $form = id(new AphrontFormView())->setUser($viewer)->setAction('/typeahead/class/')->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Source Class'))->setName('class')->setValue($this->class)->setOptions($options))->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Query'))->setName('q')->setValue($request->getStr('q')))->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Raw Query'))->setName('raw')->setValue($request->getStr('raw')))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Query')));
     $form_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Token Query'))->setForm($form);
     $table = new AphrontTableView($content);
     $table->setHeaders(array(pht('Name'), pht('URI'), pht('PHID'), pht('Priority'), pht('Display Name'), pht('Display Type'), pht('Image URI'), pht('Priority Type'), pht('Icon'), pht('Closed'), pht('Sprite')));
     $result_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Token Results (%s)', $this->class))->appendChild($table);
     return $this->buildApplicationPage(array($form_box, $result_box), array('title' => pht('Typeahead Results'), 'device' => false));
 }
 public final function render()
 {
     require_celerity_resource('aphront-error-view-css');
     $errors = $this->errors;
     if ($errors) {
         $list = array();
         foreach ($errors as $error) {
             $list[] = phutil_render_tag('li', array(), phutil_escape_html($error));
         }
         $list = '<ul>' . implode("\n", $list) . '</ul>';
     } else {
         $list = null;
     }
     $title = $this->title;
     if (strlen($title)) {
         $title = '<h1>' . phutil_escape_html($title) . '</h1>';
     } else {
         $title = null;
     }
     $this->severity = nonempty($this->severity, self::SEVERITY_ERROR);
     $this->width = nonempty($this->width, self::WIDTH_DEFAULT);
     $more_classes = array();
     $more_classes[] = 'aphront-error-severity-' . $this->severity;
     $more_classes[] = 'aphront-error-width-' . $this->width;
     $more_classes = implode(' ', $more_classes);
     return phutil_render_tag('div', array('id' => $this->id, 'class' => 'aphront-error-view ' . $more_classes), $title . $this->renderChildren() . $list);
 }
 public function processRequest()
 {
     if (!PhabricatorEnv::getEnvConfig('files.enable-proxy')) {
         return new Aphront400Response();
     }
     $request = $this->getRequest();
     $uri = $request->getStr('uri');
     $proxy = id(new PhabricatorFileProxyImage())->loadOneWhere('uri = %s', $uri);
     if (!$proxy) {
         // This write is fine to skip CSRF checks for, we're just building a
         // cache of some remote image.
         $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
         $file = PhabricatorFile::newFromFileDownload($uri, nonempty(basename($uri), 'proxied-file'));
         if ($file) {
             $proxy = new PhabricatorFileProxyImage();
             $proxy->setURI($uri);
             $proxy->setFilePHID($file->getPHID());
             $proxy->save();
         }
         unset($unguarded);
     }
     if ($proxy) {
         $file = id(new PhabricatorFile())->loadOneWhere('phid = %s', $proxy->getFilePHID());
         if ($file) {
             $view_uri = $file->getBestURI();
         } else {
             $bad_phid = $proxy->getFilePHID();
             throw new Exception("Unable to load file with phid {$bad_phid}.");
         }
         return id(new AphrontRedirectResponse())->setURI($view_uri);
     }
     return new Aphront400Response();
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $user = $request->getUser();
     $nav = $this->buildSideNav('resource');
     $pager = new AphrontPagerView();
     $pager->setURI(new PhutilURI('/drydock/resource/'), 'page');
     $data = id(new DrydockResource())->loadAllWhere('1 = 1 ORDER BY id DESC LIMIT %d, %d', $pager->getOffset(), $pager->getPageSize() + 1);
     $data = $pager->sliceResults($data);
     $phids = mpull($data, 'getOwnerPHID');
     $handles = $this->loadViewerHandles($phids);
     $rows = array();
     foreach ($data as $resource) {
         $rows[] = array($resource->getID(), $resource->getOwnerPHID() ? $handles[$resource->getOwnerPHID()]->renderLink() : null, phutil_escape_html($resource->getType()), DrydockResourceStatus::getNameForStatus($resource->getStatus()), phutil_escape_html(nonempty($resource->getName(), 'Unnamed')), phabricator_datetime($resource->getDateCreated(), $user));
     }
     $table = new AphrontTableView($rows);
     $table->setHeaders(array('ID', 'Owner', 'Type', 'Status', 'Resource', 'Created'));
     $table->setColumnClasses(array('', '', '', '', 'pri wide', 'right'));
     $panel = new AphrontPanelView();
     $panel->setHeader('Drydock Resources');
     $panel->addButton(phutil_render_tag('a', array('href' => '/drydock/resource/allocate/', 'class' => 'green button'), 'Allocate Resource'));
     $panel->appendChild($table);
     $panel->appendChild($pager);
     $nav->appendChild($panel);
     return $this->buildStandardPageResponse($nav, array('title' => 'Resources'));
 }
 protected function validateTransaction(PhabricatorLiskDAO $object, $type, array $xactions)
 {
     $errors = parent::validateTransaction($object, $type, $xactions);
     switch ($type) {
         case AlmanacBindingTransaction::TYPE_INTERFACE:
             $missing = $this->validateIsEmptyTextField($object->getInterfacePHID(), $xactions);
             if ($missing) {
                 $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('Bindings must specify an interface.'), nonempty(last($xactions), null));
                 $error->setIsMissingFieldError(true);
                 $errors[] = $error;
             } else {
                 if ($xactions) {
                     foreach ($xactions as $xaction) {
                         $interfaces = id(new AlmanacInterfaceQuery())->setViewer($this->requireActor())->withPHIDs(array($xaction->getNewValue()))->execute();
                         if (!$interfaces) {
                             $error = new PhabricatorApplicationTransactionValidationError($type, pht('Invalid'), pht('You can not bind a service to an invalid or restricted ' . 'interface.'), $xaction);
                             $errors[] = $error;
                         }
                     }
                     $final_value = last($xactions)->getNewValue();
                     $binding = id(new AlmanacBindingQuery())->setViewer(PhabricatorUser::getOmnipotentUser())->withServicePHIDs(array($object->getServicePHID()))->withInterfacePHIDs(array($final_value))->executeOne();
                     if ($binding && $binding->getID() != $object->getID()) {
                         $error = new PhabricatorApplicationTransactionValidationError($type, pht('Already Bound'), pht('You can not bind a service to the same interface multiple ' . 'times.'), last($xactions));
                         $errors[] = $error;
                     }
                 }
             }
             break;
     }
     return $errors;
 }
 public function receiveMessage(PhabricatorBotMessage $message)
 {
     switch ($message->getCommand()) {
         case 'MESSAGE':
             $text = $message->getBody();
             $matches = null;
             if (!preg_match('/where(?: in the world)? is (\\S+?)\\?/i', $text, $matches)) {
                 break;
             }
             $symbol = $matches[1];
             $results = $this->getConduit()->callMethodSynchronous('diffusion.findsymbols', array('name' => $symbol));
             $default_uri = $this->getURI('/diffusion/symbol/' . $symbol . '/');
             if (count($results) > 1) {
                 $response = "Multiple symbols named '{$symbol}': {$default_uri}";
             } else {
                 if (count($results) == 1) {
                     $result = head($results);
                     $response = $result['type'] . ' ' . $result['name'] . ' ' . '(' . $result['language'] . '): ' . nonempty($result['uri'], $default_uri);
                 } else {
                     $response = "No symbol '{$symbol}' found anywhere.";
                 }
             }
             $this->replyTo($message, $response);
             break;
     }
 }
 public function render()
 {
     require_celerity_resource('aphront-tokenizer-control-css');
     $id = $this->id;
     $name = $this->getName();
     $tokens = nonempty($this->getValue(), array());
     $input = javelin_tag('input', array('mustcapture' => true, 'name' => $name, 'class' => 'jx-tokenizer-input', 'sigil' => 'tokenizer-input', 'style' => 'width: 0px;', 'disabled' => 'disabled', 'type' => 'text'));
     $content = $tokens;
     $content[] = $input;
     $content[] = phutil_tag('div', array('style' => 'clear: both;'), '');
     $container = javelin_tag('div', array('id' => $id, 'class' => 'jx-tokenizer-container', 'sigil' => 'tokenizer-container'), $content);
     $icon = id(new PHUIIconView())->setIcon('fa-search');
     $browse = id(new PHUIButtonView())->setTag('a')->setIcon($icon)->addClass('tokenizer-browse-button')->setColor(PHUIButtonView::GREY)->addSigil('tokenizer-browse');
     $classes = array();
     $classes[] = 'jx-tokenizer-frame';
     if ($this->browseURI) {
         $classes[] = 'has-browse';
     }
     $initial = array();
     $initial_value = $this->getInitialValue();
     if ($initial_value) {
         foreach ($this->getInitialValue() as $value) {
             $initial[] = phutil_tag('input', array('type' => 'hidden', 'name' => $name . '.initial[]', 'value' => $value));
         }
     }
     $frame = javelin_tag('div', array('class' => implode(' ', $classes), 'sigil' => 'tokenizer-frame'), array($container, $browse, $initial));
     return $frame;
 }
 protected function validateTransaction(PhabricatorLiskDAO $object, $type, array $xactions)
 {
     $errors = parent::validateTransaction($object, $type, $xactions);
     switch ($type) {
         case PhabricatorCountdownTransaction::TYPE_TITLE:
             $missing = $this->validateIsEmptyTextField($object->getTitle(), $xactions);
             if ($missing) {
                 $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('You must give the countdown a name.'), nonempty(last($xactions), null));
                 $error->setIsMissingFieldError(true);
                 $errors[] = $error;
             }
             break;
         case PhabricatorCountdownTransaction::TYPE_EPOCH:
             if (!$object->getEpoch() && !$xactions) {
                 $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('You must give the countdown an end date.'), null);
                 $error->setIsMissingFieldError(true);
                 $errors[] = $error;
             }
             foreach ($xactions as $xaction) {
                 $value = $xaction->getNewValue();
                 if (!$value->isValid()) {
                     $error = new PhabricatorApplicationTransactionValidationError($type, pht('Invalid'), pht('You must give the countdown a valid end date.'), $xaction);
                     $errors[] = $error;
                 }
             }
             break;
     }
     return $errors;
 }
 protected function validateTransaction(PhabricatorLiskDAO $object, $type, array $xactions)
 {
     $errors = parent::validateTransaction($object, $type, $xactions);
     switch ($type) {
         case PhabricatorOAuthServerTransaction::TYPE_NAME:
             $missing = $this->validateIsEmptyTextField($object->getName(), $xactions);
             if ($missing) {
                 $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('OAuth applications must have a name.'), nonempty(last($xactions), null));
                 $error->setIsMissingFieldError(true);
                 $errors[] = $error;
             }
             break;
         case PhabricatorOAuthServerTransaction::TYPE_REDIRECT_URI:
             $missing = $this->validateIsEmptyTextField($object->getRedirectURI(), $xactions);
             if ($missing) {
                 $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('OAuth applications must have a valid redirect URI.'), nonempty(last($xactions), null));
                 $error->setIsMissingFieldError(true);
                 $errors[] = $error;
             } else {
                 foreach ($xactions as $xaction) {
                     $redirect_uri = $xaction->getNewValue();
                     try {
                         $server = new PhabricatorOAuthServer();
                         $server->assertValidRedirectURI($redirect_uri);
                     } catch (Exception $ex) {
                         $errors[] = new PhabricatorApplicationTransactionValidationError($type, pht('Invalid'), $ex->getMessage(), $xaction);
                     }
                 }
             }
             break;
     }
     return $errors;
 }
 public function __toString()
 {
     $prefix = null;
     if ($this->protocol || $this->domain || $this->port) {
         $protocol = nonempty($this->protocol, 'http');
         $auth = '';
         if (strlen($this->user) && strlen($this->pass)) {
             $auth = phutil_escape_uri($this->user) . ':' . phutil_escape_uri($this->pass) . '@';
         } else {
             if (strlen($this->user)) {
                 $auth = phutil_escape_uri($this->user) . '@';
             }
         }
         $prefix = $protocol . '://' . $auth . $this->domain;
         if ($this->port) {
             $prefix .= ':' . $this->port;
         }
     }
     if ($this->query) {
         $query = '?' . http_build_query($this->query);
     } else {
         $query = null;
     }
     if (strlen($this->getFragment())) {
         $fragment = '#' . $this->getFragment();
     } else {
         $fragment = null;
     }
     return $prefix . $this->getPath() . $query . $fragment;
 }
 public function setFormErrors(array $errors, $title = null)
 {
     if (nonempty($errors)) {
         $this->formErrors = id(new AphrontErrorView())->setTitle($title)->setErrors($errors);
     }
     return $this;
 }
 protected function renderResultList(array $pastes, PhabricatorSavedQuery $query, array $handles)
 {
     assert_instances_of($pastes, 'PhabricatorPaste');
     $viewer = $this->requireViewer();
     $lang_map = PhabricatorEnv::getEnvConfig('pygments.dropdown-choices');
     $list = new PHUIObjectItemListView();
     $list->setUser($viewer);
     foreach ($pastes as $paste) {
         $created = phabricator_date($paste->getDateCreated(), $viewer);
         $author = $handles[$paste->getAuthorPHID()]->renderLink();
         $lines = phutil_split_lines($paste->getContent());
         $preview = id(new PhabricatorSourceCodeView())->setLimit(5)->setLines($lines)->setURI(new PhutilURI($paste->getURI()));
         $source_code = phutil_tag('div', array('class' => 'phabricator-source-code-summary'), $preview);
         $created = phabricator_datetime($paste->getDateCreated(), $viewer);
         $line_count = count($lines);
         $line_count = pht('%s Line(s)', new PhutilNumber($line_count));
         $title = nonempty($paste->getTitle(), pht('(An Untitled Masterwork)'));
         $item = id(new PHUIObjectItemView())->setObjectName('P' . $paste->getID())->setHeader($title)->setHref('/P' . $paste->getID())->setObject($paste)->addByline(pht('Author: %s', $author))->addIcon('none', $created)->addIcon('none', $line_count)->appendChild($source_code);
         $lang_name = $paste->getLanguage();
         if ($lang_name) {
             $lang_name = idx($lang_map, $lang_name, $lang_name);
             $item->addIcon('none', $lang_name);
         }
         $list->addItem($item);
     }
     $result = new PhabricatorApplicationSearchResultView();
     $result->setObjectList($list);
     $result->setNoDataString(pht('No pastes found.'));
     return $result;
 }
 public function renderTextChange($range_start, $range_len, $rows)
 {
     $out = array();
     $primitives = $this->buildPrimitives($range_start, $range_len);
     foreach ($primitives as $p) {
         $type = $p['type'];
         switch ($type) {
             case 'old':
             case 'new':
                 $num = nonempty($p['line'], '-');
                 $render = $p['render'];
                 $htype = nonempty($p['htype'], '.');
                 // TODO: This should probably happen earlier, whenever we deal with
                 // \r and \t normalization?
                 $render = rtrim($render, "\r\n");
                 $t = $type == 'old' ? 'O' : 'N';
                 $out[] = "{$t} {$num} {$htype} {$render}~";
                 break;
             default:
                 $out[] = $type;
                 break;
         }
     }
     $out = implode("\n", $out) . "\n";
     return $out;
 }
 protected function getTagContent()
 {
     if ($this->previewURI === null) {
         throw new PhutilInvalidStateException('setPreviewURI');
     }
     if ($this->controlID === null) {
         throw new PhutilInvalidStateException('setControlID');
     }
     $preview_id = celerity_generate_unique_node_id();
     require_celerity_resource('phui-remarkup-preview-css');
     Javelin::initBehavior('remarkup-preview', array('previewID' => $preview_id, 'controlID' => $this->controlID, 'uri' => $this->previewURI));
     $loading = phutil_tag('div', array('class' => 'phui-preview-loading-text'), nonempty($this->loadingText, pht('Loading preview...')));
     $preview = phutil_tag('div', array('id' => $preview_id, 'class' => 'phabricator-remarkup phui-preview-body'), $loading);
     if (!$this->previewType) {
         $header = null;
         if ($this->header) {
             $header = phutil_tag('div', array('class' => 'phui-preview-header'), $this->header);
         }
         $content = array($header, $preview);
     } else {
         if ($this->previewType == self::DOCUMENT) {
             $header = id(new PHUIHeaderView())->setHeader(pht('%s (Preview)', $this->header));
             $content = id(new PHUIDocumentViewPro())->setHeader($header)->appendChild($preview);
         }
     }
     return id(new PHUIObjectBoxView())->appendChild($content)->setCollapsed(true);
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     if ($request->isFormPost()) {
         $uri = $request->getRequestURI();
         $project = head($request->getArr('set_project'));
         $project = nonempty($project, null);
         $uri = $uri->alter('project', $project);
         $window = $request->getStr('set_window');
         $uri = $uri->alter('window', $window);
         return id(new AphrontRedirectResponse())->setURI($uri);
     }
     $nav = $this->buildNavMenu();
     $this->view = $nav->selectFilter($this->view, 'List');
     switch ($this->view) {
         case 'list':
         case 'user':
         case 'project':
             $core = id(new SprintReportOpenTasksView())->setUser($viewer)->setRequest($request)->setView($this->view);
             break;
         case 'burn':
             $core = id(new SprintReportBurnUpView())->setUser($viewer)->setRequest($request);
             break;
         case 'history':
             $core = id(new SprintHistoryTableView())->setUser($viewer)->setRequest($request);
             break;
         default:
             return new Aphront404Response();
     }
     $can_create = $this->hasApplicationCapability(ProjectCreateProjectsCapability::CAPABILITY);
     $nav->appendChild($core);
     $nav->setCrumbs($this->buildSprintApplicationCrumbs($can_create)->setBorder(true)->addTextCrumb(pht('Reports')));
     return $this->buildApplicationPage($nav, array('title' => pht('Sprint Reports'), 'device' => false));
 }
 protected function validateTransaction(PhabricatorLiskDAO $object, $type, array $xactions)
 {
     $errors = parent::validateTransaction($object, $type, $xactions);
     switch ($type) {
         case PhamePostTransaction::TYPE_TITLE:
             $missing = $this->validateIsEmptyTextField($object->getTitle(), $xactions);
             if ($missing) {
                 $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('Title is required.'), nonempty(last($xactions), null));
                 $error->setIsMissingFieldError(true);
                 $errors[] = $error;
             }
             break;
         case PhamePostTransaction::TYPE_BLOG:
             if ($this->getIsNewObject()) {
                 if (!$xactions) {
                     $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('When creating a post, you must specify which blog it ' . 'should belong to.'), null);
                     $error->setIsMissingFieldError(true);
                     $errors[] = $error;
                     break;
                 }
             }
             foreach ($xactions as $xaction) {
                 $new_phid = $xaction->getNewValue();
                 $blog = id(new PhameBlogQuery())->setViewer($this->getActor())->withPHIDs(array($new_phid))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT))->execute();
                 if ($blog) {
                     continue;
                 }
                 $errors[] = new PhabricatorApplicationTransactionValidationError($type, pht('Invalid'), pht('The specified blog PHID ("%s") is not valid. You can only ' . 'create a post on (or move a post into) a blog which you ' . 'have permission to see and edit.', $new_phid), $xaction);
             }
             break;
     }
     return $errors;
 }
 protected function renderInput()
 {
     $name = $this->getName();
     $values = nonempty($this->getValue(), array());
     if ($this->getID()) {
         $id = $this->getID();
     } else {
         $id = celerity_generate_unique_node_id();
     }
     $placeholder = null;
     if (!$this->placeholder) {
         $placeholder = $this->getDefaultPlaceholder();
     }
     $template = new AphrontTokenizerTemplateView();
     $template->setName($name);
     $template->setID($id);
     $template->setValue($values);
     $username = null;
     if ($this->user) {
         $username = $this->user->getUsername();
     }
     if (!$this->disableBehavior) {
         Javelin::initBehavior('aphront-basic-tokenizer', array('id' => $id, 'src' => $this->datasource, 'value' => $values, 'limit' => $this->limit, 'ondemand' => PhabricatorEnv::getEnvConfig('tokenizer.ondemand'), 'username' => $username, 'placeholder' => $placeholder));
     }
     return $template->render();
 }
 protected function executeQuery()
 {
     $drequest = $this->getRequest();
     $repository = $drequest->getRepository();
     $commit = $this->getAnchorCommit();
     $options = array('-M', '-C', '--no-ext-diff', '--no-color', '--src-prefix=a/', '--dst-prefix=b/', '-U' . (int) $this->getLinesOfContext());
     $options = implode(' ', $options);
     $against = $this->getAgainstCommit();
     if ($against === null) {
         $against = $commit . '^';
     }
     // If there's no path, get the entire raw diff.
     $path = nonempty($drequest->getPath(), '.');
     $future = $repository->getLocalCommandFuture('diff %C %s %s -- %s', $options, $against, $commit, $path);
     $this->configureFuture($future);
     try {
         list($raw_diff) = $future->resolvex();
     } catch (CommandException $ex) {
         // Check if this is the root commit by seeing if it has parents.
         list($parents) = $repository->execxLocalCommand('log --format=%s %s --', '%P', $commit);
         if (strlen(trim($parents))) {
             throw $ex;
         }
         // No parents means we're looking at the root revision. Diff against
         // the empty tree hash instead, since there is no parent so "^" does
         // not work. See ArcanistGitAPI for more discussion.
         $future = $repository->getLocalCommandFuture('diff %C %s %s -- %s', $options, ArcanistGitAPI::GIT_MAGIC_ROOT_COMMIT, $commit, $drequest->getPath());
         $this->configureFuture($future);
         list($raw_diff) = $future->resolvex();
     }
     return $raw_diff;
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $this->getViewer();
     $phid = $request->getURIData('phid');
     $capability = $request->getURIData('capability');
     $object = id(new PhabricatorObjectQuery())->setViewer($viewer)->withPHIDs(array($phid))->executeOne();
     if (!$object) {
         return new Aphront404Response();
     }
     $policies = PhabricatorPolicyQuery::loadPolicies($viewer, $object);
     $policy = idx($policies, $capability);
     if (!$policy) {
         return new Aphront404Response();
     }
     $handle = id(new PhabricatorHandleQuery())->setViewer($viewer)->withPHIDs(array($phid))->executeOne();
     $object_name = $handle->getName();
     $object_uri = nonempty($handle->getURI(), '/');
     $dialog = id(new AphrontDialogView())->setUser($viewer)->setClass('aphront-access-dialog aphront-policy-explain-dialog')->setTitle(pht('Policy Details: %s', $object_name))->addCancelButton($object_uri, pht('Done'));
     $space_section = $this->buildSpaceSection($object, $policy, $capability);
     $extended_section = $this->buildExtendedSection($object, $capability);
     $exceptions_section = $this->buildExceptionsSection($object, $capability);
     $object_section = $this->buildObjectSection($object, $policy, $capability, $handle);
     $dialog->appendChild(array($space_section, $extended_section, $exceptions_section, $object_section));
     return $dialog;
 }
 public static function newFromPHPUpload($spec, array $params = array())
 {
     $file_data = self::readUploadedFileData($spec);
     $file_name = nonempty(idx($params, 'name'), idx($spec, 'name'));
     $params = array('name' => $file_name) + $params;
     return self::newFromFileData($file_data, $params);
 }
 public function render()
 {
     $handle = $this->handle;
     $type_name = nonempty($handle->getTypeName(), 'Document');
     require_celerity_resource('phabricator-search-results-css');
     $link = phutil_render_tag('a', array('href' => $handle->getURI()), PhabricatorEnv::getProductionURI($handle->getURI()));
     $img = $handle->getImageURI();
     if ($img) {
         $img = phutil_render_tag('div', array('class' => 'result-image', 'style' => "background-image: url('{$img}');"), '');
     }
     switch ($handle->getType()) {
         case PhabricatorPHIDConstants::PHID_TYPE_CMIT:
             $object_name = $handle->getName();
             if ($this->object) {
                 $data = $this->object->getCommitData();
                 $summary = $data->getSummary();
                 if (strlen($summary)) {
                     $object_name = $handle->getName() . ': ' . $data->getSummary();
                 }
             }
             break;
         default:
             $object_name = $handle->getFullName();
             break;
     }
     return '<div class="phabricator-search-result">' . $img . '<div class="result-desc">' . phutil_render_tag('a', array('class' => 'result-name', 'href' => $handle->getURI()), $this->emboldenQuery($object_name)) . '<div class="result-type">' . $type_name . ' &middot; ' . $link . '</div>' . '</div>' . '<div style="clear: both;"></div>' . '</div>';
 }
 public final function render()
 {
     require_celerity_resource('aphront-error-view-css');
     $errors = $this->errors;
     if ($errors) {
         $list = array();
         foreach ($errors as $error) {
             $list[] = phutil_tag('li', array(), $error);
         }
         $list = phutil_tag('ul', array('class' => 'aphront-error-view-list'), $list);
     } else {
         $list = null;
     }
     $title = $this->title;
     if (strlen($title)) {
         $title = phutil_tag('h1', array('class' => 'aphront-error-view-head'), $title);
     } else {
         $title = null;
     }
     $this->severity = nonempty($this->severity, self::SEVERITY_ERROR);
     $classes = array();
     $classes[] = 'aphront-error-view';
     $classes[] = 'aphront-error-severity-' . $this->severity;
     $classes = implode(' ', $classes);
     $children = $this->renderChildren();
     $children[] = $list;
     return phutil_tag('div', array('id' => $this->id, 'class' => $classes), array($title, phutil_tag('div', array('class' => 'aphront-error-view-body'), $children)));
 }
 protected function getTagContent()
 {
     $viewer = $this->getUser();
     require_celerity_resource('phui-object-item-list-view-css');
     $header = null;
     if (strlen($this->header)) {
         $header = phutil_tag('h1', array('class' => 'phui-object-item-list-header'), $this->header);
     }
     if ($this->items) {
         if ($viewer) {
             foreach ($this->items as $item) {
                 $item->setUser($viewer);
             }
         }
         $items = $this->items;
     } else {
         if ($this->allowEmptyList) {
             $items = null;
         } else {
             $string = nonempty($this->noDataString, pht('No data.'));
             $string = id(new PHUIInfoView())->setSeverity(PHUIInfoView::SEVERITY_NODATA)->appendChild($string);
             $items = phutil_tag('li', array('class' => 'phui-object-item-empty'), $string);
         }
     }
     $pager = null;
     if ($this->pager) {
         $pager = $this->pager;
     }
     return array($header, $items, $pager, $this->renderChildren());
 }
 protected function validateTransaction(PhabricatorLiskDAO $object, $type, array $xactions)
 {
     $errors = parent::validateTransaction($object, $type, $xactions);
     switch ($type) {
         case PhabricatorMetaMTAApplicationEmailTransaction::TYPE_ADDRESS:
             foreach ($xactions as $xaction) {
                 $email = $xaction->getNewValue();
                 if (!strlen($email)) {
                     // We'll deal with this below.
                     continue;
                 }
                 if (!PhabricatorUserEmail::isValidAddress($email)) {
                     $errors[] = new PhabricatorApplicationTransactionValidationError($type, pht('Invalid'), pht('Email address is not formatted properly.'));
                 }
             }
             $missing = $this->validateIsEmptyTextField($object->getAddress(), $xactions);
             if ($missing) {
                 $error = new PhabricatorApplicationTransactionValidationError($type, pht('Required'), pht('You must provide an email address.'), nonempty(last($xactions), null));
                 $error->setIsMissingFieldError(true);
                 $errors[] = $error;
             }
             break;
     }
     return $errors;
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $pager = new AphrontPagerView();
     $pager->setOffset($request->getInt('page'));
     $pastes = id(new PhabricatorPaste())->loadAllWhere('1 = 1 ORDER BY id DESC LIMIT %d, %d', $pager->getOffset(), $pager->getPageSize() + 1);
     $pastes = $pager->sliceResults($pastes);
     $pager->setURI($request->getRequestURI(), 'page');
     $phids = mpull($pastes, 'getAuthorPHID');
     $handles = array();
     if ($phids) {
         $handles = id(new PhabricatorObjectHandleData($phids))->loadHandles();
     }
     $rows = array();
     foreach ($pastes as $paste) {
         $handle = $handles[$paste->getAuthorPHID()];
         $rows[] = array(phutil_escape_html('P' . $paste->getID()), phutil_render_tag('a', array('href' => '/p/' . $handle->getName() . '/'), phutil_escape_html($handle->getName())), phutil_escape_html($paste->getLanguage()), phutil_render_tag('a', array('href' => '/P' . $paste->getID()), phutil_escape_html(nonempty($paste->getTitle(), 'Untitled Masterwork P' . $paste->getID()))), phutil_render_tag('a', array('href' => PhabricatorFileURI::getViewURIForPHID($paste->getFilePHID())), phutil_escape_html($paste->getFilePHID())));
     }
     $table = new AphrontTableView($rows);
     $table->setHeaders(array('Paste ID', 'Author', 'Language', 'Title', 'File'));
     $table->setColumnClasses(array(null, null, null, 'wide pri', null));
     $panel = new AphrontPanelView();
     $panel->setWidth(AphrontPanelView::WIDTH_FULL);
     $panel->setHeader("Paste");
     $panel->setCreateButton('Paste Something', '/paste/');
     $panel->appendChild($table);
     $panel->appendChild($pager);
     return $this->buildStandardPageResponse($panel, array('title' => 'Paste List', 'tab' => 'list'));
 }