private function buildCurtainView(PhortuneAccount $account, $invoices) { $viewer = $this->getViewer(); $can_edit = PhabricatorPolicyFilter::hasCapability($viewer, $account, PhabricatorPolicyCapability::CAN_EDIT); $edit_uri = $this->getApplicationURI('account/edit/' . $account->getID() . '/'); $curtain = $this->newCurtainView($account); $curtain->addAction(id(new PhabricatorActionView())->setName(pht('Edit Account'))->setIcon('fa-pencil')->setHref($edit_uri)->setDisabled(!$can_edit)->setWorkflow(!$can_edit)); $status_items = $this->getStatusItemsForAccount($account, $invoices); $status_view = new PHUIStatusListView(); foreach ($status_items as $item) { $status_view->addItem(id(new PHUIStatusItemView())->setIcon(idx($item, 'icon'), idx($item, 'color'), idx($item, 'label'))->setTarget(idx($item, 'target'))->setNote(idx($item, 'note'))); } $member_phids = $account->getMemberPHIDs(); $handles = $viewer->loadHandles($member_phids); $member_list = id(new PHUIObjectItemListView())->setSimple(true); foreach ($member_phids as $member_phid) { $image_uri = $handles[$member_phid]->getImageURI(); $image_href = $handles[$member_phid]->getURI(); $person = $handles[$member_phid]; $member = id(new PHUIObjectItemView())->setImageURI($image_uri)->setHref($image_href)->setHeader($person->getFullName()); $member_list->addItem($member); } $curtain->newPanel()->setHeaderText(pht('Status'))->appendChild($status_view); $curtain->newPanel()->setHeaderText(pht('Members'))->appendChild($member_list); return $curtain; }
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(); } }
public function render() { $rows = array(); $any_hidden = false; foreach ($this->rows as $row) { $style = idx($row, 'style'); switch ($style) { case 'section': $cells = phutil_render_tag('th', array('colspan' => 2), idx($row, 'name')); break; default: $name = phutil_render_tag('th', array(), idx($row, 'name')); $value = phutil_render_tag('td', array(), idx($row, 'value')); $cells = $name . $value; break; } $show = idx($row, 'show'); $rows[] = javelin_render_tag('tr', array('style' => $show ? null : 'display: none', 'sigil' => $show ? null : 'differential-results-row-toggle', 'class' => 'differential-results-row-' . $style), $cells); if (!$show) { $any_hidden = true; } } if ($any_hidden) { $show_more = javelin_render_tag('a', array('href' => '#', 'mustcapture' => true), $this->showMoreString); $hide_more = javelin_render_tag('a', array('href' => '#', 'mustcapture' => true), 'Hide'); $rows[] = javelin_render_tag('tr', array('class' => 'differential-results-row-show', 'sigil' => 'differential-results-row-show'), '<th colspan="2">' . $show_more . '</td>'); $rows[] = javelin_render_tag('tr', array('class' => 'differential-results-row-show', 'sigil' => 'differential-results-row-hide', 'style' => 'display: none'), '<th colspan="2">' . $hide_more . '</th>'); Javelin::initBehavior('differential-show-field-details'); } require_celerity_resource('differential-results-table-css'); return javelin_render_tag('table', array('class' => 'differential-results-table', 'sigil' => 'differential-results-table'), implode("\n", $rows)); }
public static function newFromString($string, $default = null) { $matches = null; $ok = preg_match('/^([-$]*(?:\\d+)?(?:[.]\\d{0,2})?)(?:\\s+([A-Z]+))?$/', trim($string), $matches); if (!$ok) { self::throwFormatException($string); } $value = $matches[1]; if (substr_count($value, '-') > 1) { self::throwFormatException($string); } if (substr_count($value, '$') > 1) { self::throwFormatException($string); } $value = str_replace('$', '', $value); $value = (double) $value; $value = (int) round(100 * $value); $currency = idx($matches, 2, $default); switch ($currency) { case 'USD': break; default: throw new Exception(pht("Unsupported currency '%s'!", $currency)); } return self::newFromValueAndCurrency($value, $currency); }
protected function buildQueryFromParameters(array $map) { $query = $this->newQuery(); if ($map['callsigns']) { $query->withCallsigns($map['callsigns']); } if ($map['status']) { $status = idx($this->getStatusValues(), $map['status']); if ($status) { $query->withStatus($status); } } if ($map['hosted']) { $hosted = idx($this->getHostedValues(), $map['hosted']); if ($hosted) { $query->withHosted($hosted); } } if ($map['types']) { $query->withTypes($map['types']); } if (strlen($map['name'])) { $query->withNameContains($map['name']); } return $query; }
protected function doWork() { $data = $this->getTaskData(); $viewer = PhabricatorUser::getOmnipotentUser(); $address = idx($data, 'address'); $author_phid = idx($data, 'authorPHID'); $author = id(new PhabricatorPeopleQuery())->setViewer($viewer)->withPHIDs(array($author_phid))->executeOne(); if (!$author) { throw new PhabricatorWorkerPermanentFailureException(pht('Invite has invalid author PHID ("%s").', $author_phid)); } $invite = id(new PhabricatorAuthInviteQuery())->setViewer($viewer)->withEmailAddresses(array($address))->executeOne(); if ($invite) { // If we're inviting a user who has already been invited, we just // regenerate their invite code. $invite->regenerateVerificationCode(); } else { // Otherwise, we're creating a new invite. $invite = id(new PhabricatorAuthInvite())->setEmailAddress($address); } // Whether this is a new invite or not, tag this most recent author as // the invite author. $invite->setAuthorPHID($author_phid); $code = $invite->getVerificationCode(); $invite_uri = '/auth/invite/' . $code . '/'; $invite_uri = PhabricatorEnv::getProductionURI($invite_uri); $template = idx($data, 'template'); $template = str_replace('{$INVITE_URI}', $invite_uri, $template); $invite->save(); $mail = id(new PhabricatorMetaMTAMail())->addRawTos(array($invite->getEmailAddress()))->setForceDelivery(true)->setSubject(pht('[Phabricator] %s has invited you to join Phabricator', $author->getFullName()))->setBody($template)->saveAndSend(); }
public function renderValueForRevisionView() { $diff = $this->getDiff(); $ustar = DifferentialRevisionUpdateHistoryView::renderDiffUnitStar($diff); $umsg = DifferentialRevisionUpdateHistoryView::getDiffUnitMessage($diff); $postponed_count = 0; $udata = $this->getDiffProperty('arc:unit'); $utail = null; if ($udata) { $unit_messages = array(); foreach ($udata as $test) { $name = idx($test, 'name'); $result = idx($test, 'result'); if ($result != DifferentialUnitTestResult::RESULT_POSTPONED && $result != DifferentialUnitTestResult::RESULT_PASS) { $engine = PhabricatorMarkupEngine::newDifferentialMarkupEngine(); $userdata = phutil_utf8_shorten(idx($test, 'userdata'), 512); $userdata = $engine->markupText($userdata); $unit_messages[] = '<li>' . '<span class="unit-result-' . phutil_escape_html($result) . '">' . phutil_escape_html(ucwords($result)) . '</span>' . ' ' . phutil_escape_html($name) . '<p>' . $userdata . '</p>' . '</li>'; } else { if ($result == DifferentialUnitTestResult::RESULT_POSTPONED) { $postponed_count++; } } } $uexcuse = $this->getUnitExcuse(); if ($unit_messages) { $utail = '<div class="differential-unit-block">' . $uexcuse . '<ul>' . implode("\n", $unit_messages) . '</ul>' . '</div>'; } } if ($postponed_count > 0 && $diff->getUnitStatus() == DifferentialUnitStatus::UNIT_POSTPONED) { $umsg = $postponed_count . ' ' . $umsg; } return $ustar . ' ' . $umsg . $utail; }
public function resolveBaseCommit(array $specs) { $specs += array('args' => '', 'local' => '', 'project' => '', 'global' => '', 'system' => ''); foreach ($specs as $source => $spec) { $specs[$source] = self::tokenizeBaseCommitSpecification($spec); } $this->try = array('args', 'local', 'project', 'global', 'system'); while ($this->try) { $source = head($this->try); if (!idx($specs, $source)) { $this->log("No rules left from source '{$source}'."); array_shift($this->try); continue; } $this->log("Trying rules from source '{$source}'."); $rules =& $specs[$source]; while ($rule = array_shift($rules)) { $this->log("Trying rule '{$rule}'."); $commit = $this->resolveRule($rule, $source); if ($commit === false) { // If a rule returns false, it means to go to the next ruleset. break; } else { if ($commit !== null) { $this->log("Resolved commit '{$commit}' from rule '{$rule}'."); return $commit; } } } } return null; }
public function willLintPaths(array $paths) { // Cleanup previous runs. $this->localExecx("rm -rf _build/_lint"); // Build compilation database. $lintable_paths = $this->getLintablePaths($paths); $interesting_paths = $this->getInterestingPaths($lintable_paths); if (!$lintable_paths) { return; } // Run lint. try { $this->localExecx("%C %C -p _build/dev/ %Ls", $this->getBinaryPath(), $this->getFilteredIssues(), $lintable_paths); } catch (CommandException $exception) { PhutilConsole::getConsole()->writeErr($exception->getMessage()); } // Load results. $result = id(new SQLite3($this->getProjectRoot() . '/_build/_lint/lint.db', SQLITE3_OPEN_READONLY))->query("SELECT * FROM raised_issues"); while ($issue = $result->fetchArray(SQLITE3_ASSOC)) { // Skip issues not part of the linted file. if (in_array($issue['file'], $interesting_paths)) { $this->addLintMessage(id(new ArcanistLintMessage())->setPath($issue['file'])->setLine($issue['line'])->setChar($issue['column'])->setCode('Howtoeven')->setSeverity($this->getSeverity($issue['severity']))->setName('Hte-' . $issue['name'])->setDescription(sprintf("%s\n\n%s", $issue['message'] ? $issue['message'] : $issue['description'], $issue['explanation']))->setOriginalText(idx($issue, 'original', ''))->setReplacementText(idx($issue, 'replacement', ''))); } } }
function testFields() { $dir = PhutilDirectoryFixture::newEmptyFixture(); $root = realpath($dir->getPath()); $watch = $this->watch($root); $this->assertFileList($root, array()); $this->watchmanCommand('log', 'debug', 'XXX: touch a'); touch("{$root}/a"); $this->assertFileList($root, array('a')); $query = $this->watchmanCommand('query', $root, array('fields' => array('name', 'exists', 'new', 'size', 'mode', 'uid', 'gid', 'mtime', 'mtime_ms', 'mtime_us', 'mtime_ns', 'mtime_f', 'ctime', 'ctime_ms', 'ctime_us', 'ctime_ns', 'ctime_f', 'ino', 'dev', 'nlink', 'oclock', 'cclock'), 'since' => 'n:foo')); $this->assertEqual(null, idx($query, 'error')); $this->assertEqual(1, count($query['files'])); $file = $query['files'][0]; $this->assertEqual('a', $file['name']); $this->assertEqual(true, $file['exists']); $this->assertEqual(true, $file['new']); $stat = stat("{$root}/a"); $compare_fields = array('size', 'mode', 'uid', 'gid', 'ino', 'dev', 'nlink'); foreach ($compare_fields as $field) { $this->assertEqual($stat[$field], $file[$field], $field); } $time_fields = array('mtime', 'ctime'); foreach ($time_fields as $field) { $this->assertTimeEqual($stat[$field], $file[$field], $file[$field . '_ms'], $file[$field . '_us'], $file[$field . '_ns'], $file[$field . '_f']); } $this->assertRegex('/^c:\\d+:\\d+:\\d+:\\d+$/', $file['cclock'], "cclock looks clocky"); $this->assertRegex('/^c:\\d+:\\d+:\\d+:\\d+$/', $file['oclock'], "oclock looks clocky"); }
private function renderSeverity($severity) { $names = ArcanistLintSeverity::getLintSeverities(); $name = idx($names, $severity, $severity); // TODO: Add some color here? return $name; }
public function markupText($text, $children) { $matches = array(); preg_match($this->getRegEx(), $text, $matches); if (idx($matches, 'showword')) { $word = $matches['showword']; $show = true; } else { $word = $matches['hideword']; $show = false; } $class_suffix = phutil_utf8_strtolower($word); // This is the "(IMPORTANT)" or "NOTE:" part. $word_part = rtrim(substr($text, 0, strlen($matches[0]))); // This is the actual text. $text_part = substr($text, strlen($matches[0])); $text_part = $this->applyRules(rtrim($text_part)); $text_mode = $this->getEngine()->isTextMode(); if ($text_mode) { return $word_part . ' ' . $text_part; } if ($show) { $content = array(phutil_tag('span', array('class' => 'remarkup-note-word'), $word_part), ' ', $text_part); } else { $content = $text_part; } return phutil_tag('div', array('class' => 'remarkup-' . $class_suffix), $content); }
public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $keys = $request->getStr('keys'); try { $keys = phutil_json_decode($keys); } catch (PhutilJSONParserException $ex) { return new Aphront400Response(); } // There have been at least two users asking for a keyboard shortcut to // close the dialog, so be explicit that escape works since it isn't // terribly discoverable. $keys[] = array('keys' => array('esc'), 'description' => pht('Close any dialog, including this one.')); $stroke_map = array('left' => "←", 'right' => "→", 'up' => "↑", 'down' => "↓", 'return' => "⏎", 'tab' => "⇥", 'delete' => "⌫"); $rows = array(); foreach ($keys as $shortcut) { $keystrokes = array(); foreach ($shortcut['keys'] as $stroke) { $stroke = idx($stroke_map, $stroke, $stroke); $keystrokes[] = phutil_tag('kbd', array(), $stroke); } $keystrokes = phutil_implode_html(' or ', $keystrokes); $rows[] = phutil_tag('tr', array(), array(phutil_tag('th', array(), $keystrokes), phutil_tag('td', array(), $shortcut['description']))); } $table = phutil_tag('table', array('class' => 'keyboard-shortcut-help'), $rows); return $this->newDialog()->setTitle(pht('Keyboard Shortcuts'))->appendChild($table)->addCancelButton('#', pht('Close')); }
public static function dispatchEvent(PhutilEvent $event) { $instance = self::getInstance(); $listeners = idx($instance->listeners, $event->getType(), array()); $global_listeners = idx($instance->listeners, PhutilEventType::TYPE_ALL, array()); // Merge and deduplicate listeners (we want to send the event to each // listener only once, even if it satisfies multiple criteria for the // event). $listeners = array_merge($listeners, $global_listeners); $listeners = mpull($listeners, null, 'getListenerID'); $profiler = PhutilServiceProfiler::getInstance(); $profiler_id = $profiler->beginServiceCall(array('type' => 'event', 'kind' => $event->getType(), 'count' => count($listeners))); $caught = null; try { foreach ($listeners as $listener) { if ($event->isStopped()) { // Do this first so if someone tries to dispatch a stopped event it // doesn't go anywhere. Silly but less surprising. break; } $listener->handleEvent($event); } } catch (Exception $ex) { $profiler->endServiceCall($profiler_id, array()); throw $ex; } $profiler->endServiceCall($profiler_id, array()); }
function phabricator_form(PhabricatorUser $user, $attributes, $content) { $body = array(); $http_method = idx($attributes, 'method'); $is_post = strcasecmp($http_method, 'POST') === 0; $http_action = idx($attributes, 'action'); $is_absolute_uri = preg_match('#^(https?:|//)#', $http_action); if ($is_post) { // NOTE: We only include CSRF tokens if a URI is a local URI on the same // domain. This is an important security feature and prevents forms which // submit to foreign sites from leaking CSRF tokens. // In some cases, we may construct a fully-qualified local URI. For example, // we can construct these for download links, depending on configuration. // These forms do not receive CSRF tokens, even though they safely could. // This can be confusing, if you're developing for Phabricator and // manage to construct a local form with a fully-qualified URI, since it // won't get CSRF tokens and you'll get an exception at the other end of // the request which is a bit disconnected from the actual root cause. // However, this is rare, and there are reasonable cases where this // construction occurs legitimately, and the simplest fix is to omit CSRF // tokens for these URIs in all cases. The error message you receive also // gives you some hints as to this potential source of error. if (!$is_absolute_uri) { $body[] = phutil_tag('input', array('type' => 'hidden', 'name' => AphrontRequest::getCSRFTokenName(), 'value' => $user->getCSRFToken())); $body[] = phutil_tag('input', array('type' => 'hidden', 'name' => '__form__', 'value' => true)); } } if (is_array($content)) { $body = array_merge($body, $content); } else { $body[] = $content; } return javelin_tag('form', $attributes, $body); }
public function render() { require_celerity_resource('differential-core-view-css'); require_celerity_resource('differential-revision-detail-css'); $revision = $this->revision; $rows = array(); foreach ($this->auxiliaryFields as $field) { $value = $field->renderValueForRevisionView(); if (strlen($value)) { $label = $field->renderLabelForRevisionView(); $rows[] = '<tr>' . '<th>' . $label . '</th>' . '<td>' . $value . '</td>' . '</tr>'; } } $properties = '<table class="differential-revision-properties">' . implode("\n", $rows) . '</table>'; $actions = array(); foreach ($this->actions as $action) { $obj = new AphrontHeadsupActionView(); $obj->setName($action['name']); $obj->setURI(idx($action, 'href')); $obj->setWorkflow(idx($action, 'sigil') == 'workflow'); $obj->setClass(idx($action, 'class')); $obj->setInstant(idx($action, 'instant')); $obj->setUser($this->user); $actions[] = $obj; } $action_list = new AphrontHeadsupActionListView(); $action_list->setActions($actions); return '<div class="differential-revision-detail differential-panel">' . $action_list->render() . '<div class="differential-keyboard-shortcuts">' . id(new AphrontKeyboardShortcutsAvailableView())->render() . '</div>' . '<div class="differential-revision-detail-core">' . '<h1>' . '<span class="aphront-headsup-object-name">' . phutil_escape_html('D' . $revision->getID()) . '</span>' . ' ' . phutil_escape_html($revision->getTitle()) . '</h1>' . $properties . '</div>' . '<div style="clear: both;"></div>' . '</div>'; }
private function resolvePHIDs(array $phids) { // If we have a function like `projects(alincoln)`, try to resolve the // username first. This won't happen normally, but can be passed in from // the query string. // The user might also give us an invalid username. In this case, we // preserve it and return it in-place so we get an "invalid" token rendered // in the UI. This shows the user where the issue is and best represents // the user's input. $usernames = array(); foreach ($phids as $key => $phid) { if (phid_get_type($phid) != PhabricatorPeopleUserPHIDType::TYPECONST) { $usernames[$key] = $phid; } } if ($usernames) { $users = id(new PhabricatorPeopleQuery())->setViewer($this->getViewer())->withUsernames($usernames)->execute(); $users = mpull($users, null, 'getUsername'); foreach ($usernames as $key => $username) { $user = idx($users, $username); if ($user) { $phids[$key] = $user->getPHID(); } } } return $phids; }
public function renderValidateFactorForm(PhabricatorAuthFactorConfig $config, AphrontFormView $form, PhabricatorUser $viewer, $validation_result) { if (!$validation_result) { $validation_result = array(); } $form->appendChild(id(new AphrontFormTextControl())->setName($this->getParameterName($config, 'totpcode'))->setLabel(pht('App Code'))->setCaption(pht('Factor Name: %s', $config->getFactorName()))->setValue(idx($validation_result, 'value'))->setError(idx($validation_result, 'error', true))); }
public static function loadSingle($viewer, $id) { if (!$viewer) { throw new Exception("Must set viewer when calling loadSingle"); } return idx(id(new PonderAnswerQuery())->withID($id)->execute(), $id); }
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 getAuxiliaryAttribute($key, $default = null) { if ($this->auxiliaryAttributes === null) { throw new Exception("Attach auxiliary attributes before getting them!"); } return idx($this->auxiliaryAttributes, $key, $default); }
public function render() { $drequest = $this->getDiffusionRequest(); $current_branch = $drequest->getBranch(); $rows = array(); $rowc = array(); foreach ($this->branches as $branch) { $commit = idx($this->commits, $branch->getHeadCommitIdentifier()); if ($commit) { $details = $commit->getCommitData()->getCommitMessage(); $details = idx(explode("\n", $details), 0); $details = substr($details, 0, 80); $datetime = phabricator_datetime($commit->getEpoch(), $this->user); } else { $datetime = null; $details = null; } $rows[] = array(phutil_render_tag('a', array('href' => $drequest->generateURI(array('action' => 'history', 'branch' => $branch->getName()))), 'History'), phutil_render_tag('a', array('href' => $drequest->generateURI(array('action' => 'browse', 'branch' => $branch->getName()))), phutil_escape_html($branch->getName())), self::linkCommit($drequest->getRepository(), $branch->getHeadCommitIdentifier()), $datetime, AphrontTableView::renderSingleDisplayLine(phutil_escape_html($details))); if ($branch->getName() == $current_branch) { $rowc[] = 'highlighted'; } else { $rowc[] = null; } } $view = new AphrontTableView($rows); $view->setHeaders(array('History', 'Branch', 'Head', 'Modified', 'Details')); $view->setColumnClasses(array('', 'pri', '', '', 'wide')); $view->setRowClasses($rowc); return $view->render(); }
protected function willFilterPage(array $comments) { if ($this->needReplyToComments) { $reply_phids = array(); foreach ($comments as $comment) { $reply_phid = $comment->getReplyToCommentPHID(); if ($reply_phid) { $reply_phids[] = $reply_phid; } } if ($reply_phids) { $reply_comments = newv(get_class($this), array())->setViewer($this->getViewer())->setParentQuery($this)->withPHIDs($reply_phids)->execute(); $reply_comments = mpull($reply_comments, null, 'getPHID'); } else { $reply_comments = array(); } foreach ($comments as $key => $comment) { $reply_phid = $comment->getReplyToCommentPHID(); if (!$reply_phid) { $comment->attachReplyToComment(null); continue; } $reply = idx($reply_comments, $reply_phid); if (!$reply) { $this->didRejectResult($comment); unset($comments[$key]); continue; } $comment->attachReplyToComment($reply); } } return $comments; }
public function run() { $srcdir = dirname(__FILE__) . '/../../'; $engine = new WatchmanIntegrationEngine(); $engine->setProjectRoot($srcdir); $paths = $this->getArgument('args'); $results = $engine->run($paths); $failed = 0; $colors = array('pass' => '<fg:green>OK</fg> ', 'fail' => '<fg:red>FAIL</fg>', 'skip' => '<fg:yellow>SKIP</fg>'); foreach ($results as $result) { $res = $result->getResult(); $status = idx($colors, $res, $res); echo phutil_console_format("{$status} %s (%.2fs)\n", $result->getName(), $result->getDuration()); if ($res == 'pass' || $res == 'skip') { continue; } echo $result->getUserData() . "\n"; $failed++; } if (!$failed) { echo phutil_console_format("\nAll %d tests passed/skipped :successkid:\n", count($results)); } else { echo phutil_console_format("\n%d of %d tests failed\n", $failed, count($results)); } return $failed ? 1 : 0; }
public function render() { $data = $this->getData(); $rows = array(); $details = ''; foreach ($data as $index => $row) { $file = $row['file']; $line = $row['line']; $tag = phutil_render_tag('a', array('onclick' => jsprintf('show_details(%d)', $index)), phutil_escape_html($row['str'] . ' at [' . basename($file) . ':' . $line . ']')); $rows[] = array($tag); $details .= '<div class="dark-console-panel-error-details" id="row-details-' . $index . '">' . phutil_escape_html($row['details']) . "\n" . 'Stack trace:' . "\n"; foreach ($row['trace'] as $key => $entry) { $line = ''; if (isset($entry['class'])) { $line .= $entry['class'] . '::'; } $line .= idx($entry, 'function', ''); $onclick = ''; if (isset($entry['file'])) { $line .= ' called at [' . $entry['file'] . ':' . $entry['line'] . ']'; $onclick = jsprintf('open_file(%s, %d)', $entry['file'], $entry['line']); } $details .= phutil_render_tag('a', array('onclick' => $onclick), phutil_escape_html($line)); $details .= "\n"; } $details .= '</div>'; } $table = new AphrontTableView($rows); $table->setClassName('error-log'); $table->setHeaders(array('Error')); $table->setNoDataString('No errors.'); return '<div>' . '<div>' . $table->render() . '</div>' . '<div class="dark-console-panel-error-separator"></div>' . '<pre class="PhabricatorMonospaced">' . $details . '</pre>' . '</div>'; }
private function getDefaultClosedStatus() { if ($this->statusData === null) { throw new Exception('loadStatusData first!'); } return idx($this->statusData, 'defaultClosedStatus'); }
public function handleRequest(AphrontRequest $request) { $viewer = $request->getUser(); $file = PhabricatorFile::initializeNewFile(); $e_file = true; $errors = array(); if ($request->isFormPost()) { $view_policy = $request->getStr('viewPolicy'); if (!$request->getFileExists('file')) { $e_file = pht('Required'); $errors[] = pht('You must select a file to upload.'); } else { $file = PhabricatorFile::newFromPHPUpload(idx($_FILES, 'file'), array('name' => $request->getStr('name'), 'authorPHID' => $viewer->getPHID(), 'viewPolicy' => $view_policy, 'isExplicitUpload' => true)); } if (!$errors) { return id(new AphrontRedirectResponse())->setURI($file->getInfoURI()); } $file->setViewPolicy($view_policy); } $support_id = celerity_generate_unique_node_id(); $instructions = id(new AphrontFormMarkupControl())->setControlID($support_id)->setControlStyle('display: none')->setValue(hsprintf('<br /><br /><strong>%s</strong> %s<br /><br />', pht('Drag and Drop:'), pht('You can also upload files by dragging and dropping them from your ' . 'desktop onto this page or the Phabricator home page.'))); $policies = id(new PhabricatorPolicyQuery())->setViewer($viewer)->setObject($file)->execute(); $form = id(new AphrontFormView())->setUser($viewer)->setEncType('multipart/form-data')->appendChild(id(new AphrontFormFileControl())->setLabel(pht('File'))->setName('file')->setError($e_file))->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Name'))->setName('name')->setValue($request->getStr('name')))->appendChild(id(new AphrontFormPolicyControl())->setUser($viewer)->setCapability(PhabricatorPolicyCapability::CAN_VIEW)->setPolicyObject($file)->setPolicies($policies)->setName('viewPolicy'))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Upload'))->addCancelButton('/file/'))->appendChild($instructions); $crumbs = $this->buildApplicationCrumbs(); $crumbs->addTextCrumb(pht('Upload'), $request->getRequestURI()); $crumbs->setBorder(true); $title = pht('Upload File'); $global_upload = id(new PhabricatorGlobalUploadTargetView())->setUser($viewer)->setShowIfSupportedID($support_id); $form_box = id(new PHUIObjectBoxView())->setHeaderText(pht('File'))->setFormErrors($errors)->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)->setForm($form); $header = id(new PHUIHeaderView())->setHeader($title)->setHeaderIcon('fa-upload'); $view = id(new PHUITwoColumnView())->setHeader($header)->setFooter(array($form_box, $global_upload)); return $this->newPage()->setTitle($title)->setCrumbs($crumbs)->appendChild($view); }
public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $pager = new PHUIPagerView(); $pager->setURI($request->getRequestURI(), 'page'); $pager->setOffset($request->getInt('page')); $query = id(new PhabricatorTokenReceiverQuery()); $objects = $query->setViewer($viewer)->executeWithOffsetPager($pager); $counts = $query->getTokenCounts(); $handles = array(); $phids = array(); if ($counts) { $phids = mpull($objects, 'getPHID'); $handles = id(new PhabricatorHandleQuery())->setViewer($viewer)->withPHIDs($phids)->execute(); } $list = new PHUIObjectItemListView(); foreach ($phids as $object) { $count = idx($counts, $object, 0); $item = id(new PHUIObjectItemView()); $handle = $handles[$object]; $item->setHeader($handle->getFullName()); $item->setHref($handle->getURI()); $item->addAttribute(pht('Tokens: %s', $count)); $list->addItem($item); } $title = pht('Token Leader Board'); $box = id(new PHUIObjectBoxView())->setHeaderText($title)->setObjectList($list); $nav = $this->buildSideNav(); $nav->setCrumbs($this->buildApplicationCrumbs()->addTextCrumb($title)); $nav->selectFilter('leaders/'); $nav->appendChild($box); $nav->appendChild($pager); return $this->newPage()->setTitle($title)->appendChild($nav); }
private function processBranchRefs(ConduitAPIRequest $request, array $refs) { $drequest = $this->getDiffusionRequest(); $repository = $drequest->getRepository(); $offset = $request->getValue('offset'); $limit = $request->getValue('limit'); foreach ($refs as $key => $ref) { if (!$repository->shouldTrackBranch($ref->getShortName())) { unset($refs[$key]); } } $with_closed = $request->getValue('closed'); if ($with_closed !== null) { foreach ($refs as $key => $ref) { $fields = $ref->getRawFields(); if (idx($fields, 'closed') != $with_closed) { unset($refs[$key]); } } } // NOTE: We can't apply the offset or limit until here, because we may have // filtered untrackable branches out of the result set. if ($offset) { $refs = array_slice($refs, $offset); } if ($limit) { $refs = array_slice($refs, 0, $limit); } return mpull($refs, 'toDictionary'); }
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; }