protected function execute(ConduitAPIRequest $request) { $corpus = $request->getValue('corpus'); $aux_fields = DifferentialFieldSelector::newSelector()->getFieldSpecifications(); foreach ($aux_fields as $key => $aux_field) { if (!$aux_field->shouldAppearOnCommitMessage()) { unset($aux_fields[$key]); } } $aux_fields = mpull($aux_fields, null, 'getCommitMessageKey'); // Build a map from labels (like "Test Plan") to field keys // (like "testPlan"). $label_map = $this->buildLabelMap($aux_fields); $field_map = $this->parseCommitMessage($corpus, $label_map); $fields = array(); $errors = array(); foreach ($field_map as $field_key => $field_value) { $field = $aux_fields[$field_key]; try { $fields[$field_key] = $field->parseValueFromCommitMessage($field_value); } catch (DifferentialFieldParseException $ex) { $field_label = $field->renderLabelForCommitMessage(); $errors[] = "Error parsing field '{$field_label}': " . $ex->getMessage(); } } // TODO: This is for backcompat only, remove once Arcanist gets updated. $error = head($errors); return array('error' => $error, 'errors' => $errors, 'fields' => $fields); }
private function processMailCommands(PhabricatorMetaMTAReceivedMail $mail, array $command_list) { $viewer = $this->getActor(); $object = $this->getMailReceiver(); $list = MetaMTAEmailTransactionCommand::getAllCommandsForObject($object); $map = MetaMTAEmailTransactionCommand::getCommandMap($list); $xactions = array(); foreach ($command_list as $command_argv) { $command = head($command_argv); $argv = array_slice($command_argv, 1); $handler = idx($map, phutil_utf8_strtolower($command)); if ($handler) { $results = $handler->buildTransactions($viewer, $object, $mail, $command, $argv); foreach ($results as $result) { $xactions[] = $result; } } else { $valid_commands = array(); foreach ($list as $valid_command) { $aliases = $valid_command->getCommandAliases(); if ($aliases) { foreach ($aliases as $key => $alias) { $aliases[$key] = '!' . $alias; } $aliases = implode(', ', $aliases); $valid_commands[] = pht('!%s (or %s)', $valid_command->getCommand(), $aliases); } else { $valid_commands[] = '!' . $valid_command->getCommand(); } } throw new Exception(pht('The command "!%s" is not a supported mail command. Valid ' . 'commands for this object are: %s.', $command, implode(', ', $valid_commands))); } } return $xactions; }
public function execute(PhutilArgumentParser $args) { $emails = $args->getArg('email'); if (!$emails) { throw new PhutilArgumentUsageException(pht('You must specify the email to verify.')); } else { if (count($emails) > 1) { throw new PhutilArgumentUsageException(pht('You can only verify one address at a time.')); } } $address = head($emails); $email = id(new PhabricatorUserEmail())->loadOneWhere('address = %s', $address); if (!$email) { throw new PhutilArgumentUsageException(pht('No email exists with address "%s"!', $address)); } $viewer = $this->getViewer(); $user = id(new PhabricatorPeopleQuery())->setViewer($viewer)->withPHIDs(array($email->getUserPHID()))->executeOne(); if (!$user) { throw new Exception(pht('Email record has invalid user PHID!')); } $editor = id(new PhabricatorUserEditor())->setActor($viewer)->verifyEmail($user, $email); $console = PhutilConsole::getConsole(); $console->writeOut("%s\n", pht('Done.')); return 0; }
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; }
protected function doLock($wait) { $conn = $this->conn; if (!$conn) { // Try to reuse a connection from the connection pool. $conn = array_pop(self::$pool); } if (!$conn) { // NOTE: Using the 'repository' database somewhat arbitrarily, mostly // because the first client of locks is the repository daemons. We must // always use the same database for all locks, but don't access any // tables so we could use any valid database. We could build a // database-free connection instead, but that's kind of messy and we // might forget about it in the future if we vertically partition the // application. $dao = new PhabricatorRepository(); // NOTE: Using "force_new" to make sure each lock is on its own // connection. $conn = $dao->establishConnection('w', $force_new = true); // NOTE: Since MySQL will disconnect us if we're idle for too long, we set // the wait_timeout to an enormous value, to allow us to hold the // connection open indefinitely (or, at least, for 24 days). $max_allowed_timeout = 2147483; queryfx($conn, 'SET wait_timeout = %d', $max_allowed_timeout); } $result = queryfx_one($conn, 'SELECT GET_LOCK(%s, %f)', 'phabricator:' . $this->lockname, $wait); $ok = head($result); if (!$ok) { throw new PhutilLockException($this->getName()); } $this->conn = $conn; }
/** * Get the route information for a given route. * * @param \Illuminate\Routing\Route $route * @return array */ protected function getRouteInformation($route) { if (!is_a($route, 'Illuminate\\Routing\\Route')) { return array(); } $uri = head($route->methods()) . ' ' . $route->uri(); $action = $route->getAction(); $result = array('uri' => $uri ?: '-'); $result = array_merge($result, $action); if (isset($action['controller']) && strpos($action['controller'], '@') !== false) { list($controller, $method) = explode('@', $action['controller']); if (class_exists($controller) && method_exists($controller, $method)) { $reflector = new \ReflectionMethod($controller, $method); } unset($result['uses']); } elseif (isset($action['uses']) && $action['uses'] instanceof \Closure) { $reflector = new \ReflectionFunction($action['uses']); $result['uses'] = $this->formatVar($result['uses']); } if (isset($reflector)) { $filename = ltrim(str_replace(base_path(), '', $reflector->getFileName()), '/'); $result['file'] = $filename . ':' . $reflector->getStartLine() . '-' . $reflector->getEndLine(); } if ($before = $this->getBeforeFilters($route)) { $result['before'] = $before; } if ($after = $this->getAfterFilters($route)) { $result['after'] = $after; } return $result; }
public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $stories = id(new PhabricatorNotificationQuery())->setViewer($viewer)->withUserPHIDs(array($viewer->getPHID()))->withKeys(array($request->getStr('key')))->execute(); if (!$stories) { return $this->buildEmptyResponse(); } $story = head($stories); if ($story->getAuthorPHID() === $viewer->getPHID()) { // Don't show the user individual notifications about their own // actions. Primarily, this stops pages from showing notifications // immediately after you click "Submit" on a comment form if the // notification server returns faster than the web server. // TODO: It would be nice to retain the "page updated" bubble on copies // of the page that are open in other tabs, but there isn't an obvious // way to do this easily. return $this->buildEmptyResponse(); } $builder = id(new PhabricatorNotificationBuilder(array($story)))->setUser($viewer)->setShowTimestamps(false); $content = $builder->buildView()->render(); $dict = $builder->buildDict(); $data = $dict[0]; $response = array('pertinent' => true, 'primaryObjectPHID' => $story->getPrimaryObjectPHID(), 'desktopReady' => $data['desktopReady'], 'href' => $data['href'], 'icon' => $data['icon'], 'title' => $data['title'], 'body' => $data['body'], 'content' => hsprintf('%s', $content)); return id(new AphrontAjaxResponse())->setContent($response); }
public function execute(HarbormasterBuild $build, HarbormasterBuildTarget $build_target) { // We can only wait when building against commits. $buildable = $build->getBuildable(); $object = $buildable->getBuildableObject(); if (!$object instanceof PhabricatorRepositoryCommit) { return; } // Block until all previous builds of the same build plan have // finished. $plan = $build->getBuildPlan(); $existing_logs = id(new HarbormasterBuildLogQuery())->setViewer(PhabricatorUser::getOmnipotentUser())->withBuildTargetPHIDs(array($build_target->getPHID()))->execute(); if ($existing_logs) { $log = head($existing_logs); } else { $log = $build->createLog($build_target, 'waiting', 'blockers'); } $blockers = $this->getBlockers($object, $plan, $build); if ($blockers) { $log->start(); $log->append(pht("Blocked by: %s\n", implode(',', $blockers))); $log->finalize(); } if ($blockers) { throw new PhabricatorWorkerYieldException(15); } }
public function execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $argv = $args->getArg('argv'); if (count($argv) !== 2) { throw new PhutilArgumentUsageException(pht('Specify a commit and a revision to attach it to.')); } $commit_name = head($argv); $revision_name = last($argv); $commit = id(new DiffusionCommitQuery())->setViewer($viewer)->withIdentifiers(array($commit_name))->executeOne(); if (!$commit) { throw new PhutilArgumentUsageException(pht('Commit "%s" does not exist.', $commit_name)); } $revision = id(new PhabricatorObjectQuery())->setViewer($viewer)->withNames(array($revision_name))->executeOne(); if (!$revision) { throw new PhutilArgumentUsageException(pht('Revision "%s" does not exist.', $revision_name)); } if (!$revision instanceof DifferentialRevision) { throw new PhutilArgumentUsageException(pht('Object "%s" must be a Differential revision.', $revision_name)); } // Reload the revision to get the active diff. $revision = id(new DifferentialRevisionQuery())->setViewer($viewer)->withIDs(array($revision->getID()))->needActiveDiffs(true)->executeOne(); $differential_phid = id(new PhabricatorDifferentialApplication())->getPHID(); $extraction_engine = id(new DifferentialDiffExtractionEngine())->setViewer($viewer)->setAuthorPHID($differential_phid); $content_source = PhabricatorContentSource::newForSource(PhabricatorContentSource::SOURCE_CONSOLE, array()); $extraction_engine->updateRevisionWithCommit($revision, $commit, array(), $content_source); echo tsprintf("%s\n", pht('Attached "%s" to "%s".', $commit->getMonogram(), $revision->getMonogram())); }
public function reduceProxyResponse() { if ($this->transactionView) { $view = $this->transactionView; } else { if ($this->getTransactions()) { $view = head($this->getTransactions())->getApplicationTransactionViewObject(); } else { $view = new PhabricatorApplicationTransactionView(); } } $view->setUser($this->getViewer())->setTransactions($this->getTransactions())->setIsPreview($this->isPreview); if ($this->isPreview) { $xactions = mpull($view->buildEvents(), 'render'); } else { $xactions = mpull($view->buildEvents(), 'render', 'getTransactionPHID'); } // Force whatever the underlying views built to render into HTML for // the Javascript. foreach ($xactions as $key => $xaction) { $xactions[$key] = hsprintf('%s', $xaction); } $content = array('xactions' => $xactions, 'spacer' => PHUITimelineView::renderSpacer()); return $this->getProxy()->setContent($content); }
/** * Bind data to the view. * * @param View $view * * @return void */ public function compose(View $view) { $data = $view->getData(); if (Auth::check()) { $notifications = Auth::user()->notifications()->with('user')->orderBy('created_at', 'desc')->take(15)->get(); $view->with('notifications', $notifications); $unreadCount = Auth::user()->notifications()->wherePivot('read', false)->count(); $view->with('newNotificationsCount', $unreadCount); } // Get object from which we can extract name to use as page title $currentGroup = head(array_only($data, ['group', 'folder', 'fakeGroup'])); $view->with('currentGroup', $currentGroup); if (isset($currentGroup) && isset($currentGroup->name)) { $pageTitle = $currentGroup->name; // Homepage title shall always be Strimoid.pl if ($currentGroup->urlname == 'all' && !Setting::get('homepage_subscribed', false)) { $pageTitle = 'Strimoid'; } if ($currentGroup->urlname == 'subscribed' && Setting::get('homepage_subscribed', false)) { $pageTitle = 'Strimoid'; } } else { $pageTitle = 'Strimoid'; } $view->with('pageTitle', $pageTitle); // Needed by top bar with groups $popularGroups = Cache::remember('popularGroups', 60, function () { return Group::orderBy('subscribers_count', 'desc', true)->take(30)->get(['id', 'name', 'urlname']); }); $view->with('popularGroups', $popularGroups); }
/** * Sort the middlewares by the given priority map. * * Each call to this method makes one discrete middleware movement if necessary. * * @param array $priorityMap * @param array $middlewares * @return array */ protected function sortMiddleware($priorityMap, $middlewares) { $lastIndex = 0; foreach ($middlewares as $index => $middleware) { if (!is_string($middleware)) { continue; } $stripped = head(explode(':', $middleware)); if (in_array($stripped, $priorityMap)) { $priorityIndex = array_search($stripped, $priorityMap); // This middleware is in the priority map. If we have encountered another middleware // that was also in the priority map and was at a lower priority than the current // middleware, we will move this middleware to be above the previous encounter. if (isset($lastPriorityIndex) && $priorityIndex < $lastPriorityIndex) { return $this->sortMiddleware($priorityMap, array_values($this->moveMiddleware($middlewares, $index, $lastIndex))); // This middleware is in the priority map; but, this is the first middleware we have // encountered from the map thus far. We'll save its current index plus its index // from the priority map so we can compare against them on the next iterations. } else { $lastIndex = $index; $lastPriorityIndex = $priorityIndex; } } } return array_values(array_unique($middlewares, SORT_REGULAR)); }
/** * It's magic! * * @param string $method * @param array $arguments * * @throws \Exception * * @return array|string */ public function __call(string $method, array $arguments) { if (in_array($httpMethod = strtoupper($method), $this->methodMap)) { return $this->request($httpMethod, head($arguments)); } throw new \Exception('Method "' . $method . '" does not exist.'); }
protected function setCommonVariable() { // Achieve that segment $this->accessUrl = config('cmsharenjoy.access_url'); // Get the action name $routeArray = Str::parseCallback(Route::currentRouteAction(), null); if (last($routeArray) != null) { // Remove 'controller' from the controller name. $controller = str_replace('Controller', '', class_basename(head($routeArray))); // Take out the method from the action. $action = str_replace(['get', 'post', 'patch', 'put', 'delete'], '', last($routeArray)); // post, report $this->onController = strtolower($controller); session()->put('onController', $this->onController); view()->share('onController', $this->onController); // get-create, post-create $this->onMethod = Str::slug(Request::method() . '-' . $action); session()->put('onMethod', $this->onMethod); view()->share('onMethod', $this->onMethod); // create, update $this->onAction = strtolower($action); session()->put('onAction', $this->onAction); view()->share('onAction', $this->onAction); } // Brand name from setting $this->brandName = Setting::get('brand_name'); // Share some variables to views view()->share('brandName', $this->brandName); view()->share('langLocales', config('cmsharenjoy.locales')); view()->share('activeLanguage', session('sharenjoy.backEndLanguage')); // Set the theme // $this->theme = Theme::uses('front'); // Message view()->share('messages', Message::getMessageBag()); }
protected function buildBareRepository($callsign) { $existing_repository = id(new PhabricatorRepositoryQuery())->withCallsigns(array($callsign))->setViewer(PhabricatorUser::getOmnipotentUser())->executeOne(); if ($existing_repository) { $existing_repository->delete(); } $data_dir = dirname(__FILE__) . '/data/'; $types = array('svn' => PhabricatorRepositoryType::REPOSITORY_TYPE_SVN, 'hg' => PhabricatorRepositoryType::REPOSITORY_TYPE_MERCURIAL, 'git' => PhabricatorRepositoryType::REPOSITORY_TYPE_GIT); $hits = array(); foreach ($types as $type => $const) { $path = $data_dir . $callsign . '.' . $type . '.tgz'; if (Filesystem::pathExists($path)) { $hits[$const] = $path; } } if (!$hits) { throw new Exception("No test data for callsign '{$callsign}'. Expected an archive " . "like '{$callsign}.git.tgz' in '{$data_dir}'."); } if (count($hits) > 1) { throw new Exception("Expected exactly one archive matching callsign '{$callsign}', " . "found too many: " . implode(', ', $hits)); } $path = head($hits); $vcs_type = head_key($hits); $dir = PhutilDirectoryFixture::newFromArchive($path); $local = new TempFile('.ignore'); $user = $this->generateNewTestUser(); $repo = PhabricatorRepository::initializeNewRepository($user)->setCallsign($callsign)->setName(pht('Test Repo "%s"', $callsign))->setVersionControlSystem($vcs_type)->setDetail('local-path', dirname($local) . '/' . $callsign)->setDetail('remote-uri', 'file://' . $dir->getPath() . '/'); $this->didConstructRepository($repo); $repo->save(); $repo->makeEphemeral(); // Keep the disk resources around until we exit. $this->dirs[] = $dir; $this->dirs[] = $local; return $repo; }
public static function summarizeCommitMessage($message) { $summary = phutil_split_lines($message, $retain_endings = false); $summary = head($summary); $summary = id(new PhutilUTF8StringTruncator())->setMaximumBytes(self::SUMMARY_MAX_LENGTH)->truncateString($summary); return $summary; }
/** * Get the world type. * * @return string */ public function type() { if (!isset($this->types[$type = $this->typeId()])) { return head($this->types); } return $this->types[$type]; }
/** * Determine if current rule is relevant based on an action and resource * * @param string|array $action Action in question * @param string|mixed $resource Name of resource or instance of object * @return boolean */ public function isRelevant($action, $resource) { // Nested resources can be passed through a associative array, this way conditions which are // dependent upon the association will work when using a class. $resource = is_array($resource) ? head(array_keys($resource)) : $resource; return parent::isRelevant($action, $resource); }
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 execute(PhutilArgumentParser $args) { $viewer = $this->getViewer(); $names = $args->getArg('buildable'); if (count($names) != 1) { throw new PhutilArgumentUsageException(pht('Specify exactly one buildable object, by object name.')); } $name = head($names); $buildable = id(new PhabricatorObjectQuery())->setViewer($viewer)->withNames($names)->executeOne(); if (!$buildable) { throw new PhutilArgumentUsageException(pht('No such buildable "%s"!', $name)); } if (!$buildable instanceof HarbormasterBuildableInterface) { throw new PhutilArgumentUsageException(pht('Object "%s" is not a buildable!', $name)); } $plan_id = $args->getArg('plan'); if (!$plan_id) { throw new PhutilArgumentUsageException(pht('Use --plan to specify a build plan to run.')); } $plan = id(new HarbormasterBuildPlanQuery())->setViewer($viewer)->withIDs(array($plan_id))->executeOne(); if (!$plan) { throw new PhutilArgumentUsageException(pht('Build plan "%s" does not exist.', $plan_id)); } $console = PhutilConsole::getConsole(); $buildable = HarbormasterBuildable::initializeNewBuildable($viewer)->setIsManualBuildable(true)->setBuildablePHID($buildable->getHarbormasterBuildablePHID())->setContainerPHID($buildable->getHarbormasterContainerPHID())->save(); $console->writeOut("%s\n", pht('Applying plan %s to new buildable %s...', $plan->getID(), 'B' . $buildable->getID())); $console->writeOut("\n %s\n\n", PhabricatorEnv::getProductionURI('/B' . $buildable->getID())); PhabricatorWorker::setRunAllTasksInProcess(true); $buildable->applyPlan($plan); $console->writeOut("%s\n", pht('Done.')); return 0; }
public function processRequest() { $request = $this->getRequest(); $user = $request->getUser(); $query = id(new PhabricatorNotificationQuery())->setViewer($user)->withUserPHIDs(array($user->getPHID()))->setLimit(15); $stories = $query->execute(); $clear_ui_class = 'phabricator-notification-clear-all'; $clear_uri = id(new PhutilURI('/notification/clear/')); if ($stories) { $builder = new PhabricatorNotificationBuilder($stories); $notifications_view = $builder->buildView(); $content = $notifications_view->render(); $clear_uri->setQueryParam('chronoKey', head($stories)->getChronologicalKey()); } else { $content = phutil_tag_div('phabricator-notification no-notifications', pht('You have no notifications.')); $clear_ui_class .= ' disabled'; } $clear_ui = javelin_tag('a', array('sigil' => 'workflow', 'href' => (string) $clear_uri, 'class' => $clear_ui_class), pht('Mark All Read')); $notifications_link = phutil_tag('a', array('href' => '/notification/'), pht('Notifications')); if (PhabricatorEnv::getEnvConfig('notification.enabled')) { $connection_status = new PhabricatorNotificationStatusView(); } else { $connection_status = phutil_tag('a', array('href' => PhabricatorEnv::getDoclink('Notifications User Guide: Setup and Configuration')), pht('Notification Server not enabled.')); } $connection_ui = phutil_tag('div', array('class' => 'phabricator-notification-footer'), $connection_status); $header = phutil_tag('div', array('class' => 'phabricator-notification-header'), array($notifications_link, $clear_ui)); $content = hsprintf('%s%s%s', $header, $content, $connection_ui); $unread_count = id(new PhabricatorFeedStoryNotification())->countUnread($user); $json = array('content' => $content, 'number' => (int) $unread_count); return id(new AphrontAjaxResponse())->setContent($json); }
function verifyUser($email, $code, $DATABASE) { $db = new DB(); $exists = $db->select("SELECT * \n\t FROM " . $DATABASE . ".users \n\t WHERE email = " . $db->quote($email) . " AND activation = " . $db->quote($code)); if (empty($exists[0])) { error("Invalid Verification", "Your verification is invalid. You might already be verified."); } else { //TODO this is copied into preferences for updateing email if (preg_match("/((@uw\\.edu)|(@u\\.washington\\.edu))/i", $exists[0]["email"])) { $netid = substr($exists[0]["email"], 0, strpos($exists[0]["email"], "@")); $db->query("UPDATE " . $DATABASE . ".users\n\t\t\t SET activation = '1', netid = " . $db->quote($netid) . " WHERE email = " . $db->quote($email)); } else { $db->query("UPDATE " . $DATABASE . ".users\n\t\t\t SET activation = '1', netid = NULL\n\t\t\t WHERE email = " . $db->quote($email)); } head(); ?> <section class="content"> <div class="container"> <h1>Success!</h1> <p>You are now verified with the Experimental College! Sign up for some classes!</p> </div> </section> <?php tail(); } }
protected function renderResultList(array $notifications, PhabricatorSavedQuery $query, array $handles) { assert_instances_of($notifications, 'PhabricatorFeedStory'); $viewer = $this->requireViewer(); $image = id(new PHUIIconView())->setIconFont('fa-eye-slash'); $button = id(new PHUIButtonView())->setTag('a')->addSigil('workflow')->setColor(PHUIButtonView::SIMPLE)->setIcon($image)->setText(pht('Mark All Read')); switch ($query->getQueryKey()) { case 'unread': $header = pht('Unread Notifications'); $no_data = pht('You have no unread notifications.'); break; default: $header = pht('Notifications'); $no_data = pht('You have no notifications.'); break; } $clear_uri = id(new PhutilURI('/notification/clear/')); if ($notifications) { $builder = id(new PhabricatorNotificationBuilder($notifications))->setUser($viewer); $view = $builder->buildView(); $clear_uri->setQueryParam('chronoKey', head($notifications)->getChronologicalKey()); } else { $view = phutil_tag_div('phabricator-notification no-notifications', $no_data); $button->setDisabled(true); } $button->setHref((string) $clear_uri); $view = id(new PHUIBoxView())->addPadding(PHUI::PADDING_MEDIUM)->addClass('phabricator-notification-list')->appendChild($view); $result = new PhabricatorApplicationSearchResultView(); $result->addAction($button); $result->setContent($view); return $result; }
/** * Set the application environment from command-line arguments. * * @param \Closure $callback * @param array $args * * @return string */ protected function detectConsoleEnvironment(Closure $callback, array $args) { if (!is_null($value = $this->getEnvironmentArgument($args))) { return head(array_slice(explode('=', $value), 1)); } return $this->detectWebEnvironment($callback); }
public function execute(PhutilArgumentParser $args) { $can_recover = id(new PhabricatorPeopleQuery())->setViewer($this->getViewer())->withIsAdmin(true)->execute(); if (!$can_recover) { throw new PhutilArgumentUsageException(pht('This Phabricator installation has no recoverable administrator ' . 'accounts. You can use `bin/accountadmin` to create a new ' . 'administrator account or make an existing user an administrator.')); } $can_recover = mpull($can_recover, 'getUsername'); sort($can_recover); $can_recover = implode(', ', $can_recover); $usernames = $args->getArg('username'); if (!$usernames) { throw new PhutilArgumentUsageException(pht('You must specify the username of the account to recover.')); } else { if (count($usernames) > 1) { throw new PhutilArgumentUsageException(pht('You can only recover the username for one account.')); } } $username = head($usernames); $user = id(new PhabricatorPeopleQuery())->setViewer($this->getViewer())->withUsernames(array($username))->executeOne(); if (!$user) { throw new PhutilArgumentUsageException(pht('No such user "%s". Recoverable administrator accounts are: %s.', $username, $can_recover)); } if (!$user->getIsAdmin()) { throw new PhutilArgumentUsageException(pht('You can only recover administrator accounts, but %s is not an ' . 'administrator. Recoverable administrator accounts are: %s.', $username, $can_recover)); } $engine = new PhabricatorAuthSessionEngine(); $onetime_uri = $engine->getOneTimeLoginURI($user, null, PhabricatorAuthSessionEngine::ONETIME_RECOVER); $console = PhutilConsole::getConsole(); $console->writeOut(pht('Use this link to recover access to the "%s" account from the web ' . 'interface:', $username)); $console->writeOut("\n\n"); $console->writeOut(' %s', $onetime_uri); $console->writeOut("\n\n"); $console->writeOut(pht('After logging in, you can use the "Auth" application to add or ' . 'restore authentication providers and allow normal logins to ' . 'succeed.') . "\n"); return 0; }
public function handleRequest(AphrontRequest $request) { $viewer = $request->getViewer(); $id = $request->getURIData('id'); if ($id) { $post = id(new PhamePostQuery())->setViewer($viewer)->withIDs(array($id))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT))->executeOne(); if (!$post) { return new Aphront404Response(); } $blog_id = $post->getBlog()->getID(); } else { $blog_id = head($request->getArr('blog')); if (!$blog_id) { $blog_id = $request->getStr('blog'); } } $query = id(new PhameBlogQuery())->setViewer($viewer)->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT)); if (ctype_digit($blog_id)) { $query->withIDs(array($blog_id)); } else { $query->withPHIDs(array($blog_id)); } $blog = $query->executeOne(); if (!$blog) { return new Aphront404Response(); } $this->setBlog($blog); return id(new PhamePostEditEngine())->setController($this)->setBlog($blog)->buildResponse(); }
/** * Print a concise, human readable representation of a value. * * @param wild Any value. * @return string Human-readable short representation of the value. * @task print */ public static function printShort($value) { if (is_object($value)) { return 'Object ' . get_class($value); } else { if (is_array($value)) { $str = 'Array '; if ($value) { if (count($value) > 1) { $str .= 'of size ' . count($value) . ' starting with: '; } reset($value); // Prevent key() from giving warning message in HPHP. $str .= '{ ' . self::printShort(key($value)) . ' => ' . self::printShort(head($value)) . ' }'; } return $str; } else { // NOTE: Avoid PhutilUTF8StringTruncator here since the data may not be // UTF8 anyway, it's slow for large inputs, and it might not be loaded // yet. $limit = 1024; $str = self::printableValue($value); if (strlen($str) > $limit) { if (is_string($value)) { $str = "'" . substr($str, 1, $limit) . "...'"; } else { $str = substr($str, 0, $limit) . '...'; } } return $str; } } }
public function resolve(array $arguments, $resolved = null) { if ($resolved) { // We don't need to do any post processing on urls. return $resolved; } if ($arguments) { $page = head($arguments); } if (isset($page) && $page instanceof \Concrete\Core\Page\Page) { if ($externalUrl = $page->getCollectionPointerExternalLink()) { return $externalUrl; } if ($path = $page->getCollectionPath()) { return $this->resolveWithResolver($path, $arguments); } // if there's no path but it's the home page if ($page->isHomePage()) { return $this->resolveWithResolver("/", $arguments); } // otherwise, it's a page object with no path yet, which happens when pages aren't yet approved return $this->resolveWithResolver('/?cID=' . $page->getCollectionID(), $arguments); } return null; }
public function processRequest() { $request = $this->getRequest(); $viewer = $request->getUser(); if ($this->id) { $user = id(new PhabricatorPeopleQuery())->setViewer($viewer)->withIDs(array($this->id))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT))->executeOne(); if (!$user) { return new Aphront404Response(); } $this->user = $user; } else { $this->user = $viewer; } $panels = $this->buildPanels(); $nav = $this->renderSideNav($panels); $key = $nav->selectFilter($this->key, head($panels)->getPanelKey()); $panel = $panels[$key]; $panel->setUser($this->getUser()); $panel->setViewer($viewer); $response = $panel->processRequest($request); if ($response instanceof AphrontResponse) { return $response; } $crumbs = $this->buildApplicationCrumbs(); if (!$this->isSelf()) { $crumbs->addTextCrumb($this->getUser()->getUsername(), '/p/' . $this->getUser()->getUsername() . '/'); } $crumbs->addTextCrumb($panel->getPanelName()); $nav->appendChild(array($crumbs, $response)); return $this->buildApplicationPage($nav, array('title' => $panel->getPanelName())); }
function error($str) { head("PHP news : error"); echo "<blockquote><strong>Error:</strong> {$str}</blockquote>\n"; foot(); die; }