public function handleRequest(AphrontRequest $request)
 {
     $viewer = $this->getViewer();
     if (!$request->validateCSRF()) {
         return new Aphront403Response();
     }
     $task = id(new ManiphestTaskQuery())->setViewer($viewer)->withIDs(array($request->getInt('task')))->needProjectPHIDs(true)->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT))->executeOne();
     if (!$task) {
         return new Aphront404Response();
     }
     if ($request->getInt('after')) {
         $after_task = id(new ManiphestTaskQuery())->setViewer($viewer)->withIDs(array($request->getInt('after')))->executeOne();
         if (!$after_task) {
             return new Aphront404Response();
         }
         list($pri, $sub) = ManiphestTransactionEditor::getAdjacentSubpriority($after_task, $is_after = true);
     } else {
         list($pri, $sub) = ManiphestTransactionEditor::getEdgeSubpriority($request->getInt('priority'), $is_end = false);
     }
     $xactions = array();
     $xactions[] = id(new ManiphestTransaction())->setTransactionType(ManiphestTransaction::TYPE_PRIORITY)->setNewValue($pri);
     $xactions[] = id(new ManiphestTransaction())->setTransactionType(ManiphestTransaction::TYPE_SUBPRIORITY)->setNewValue($sub);
     $editor = id(new ManiphestTransactionEditor())->setActor($viewer)->setContinueOnMissingFields(true)->setContinueOnNoEffect(true)->setContentSourceFromRequest($request);
     $editor->applyTransactions($task, $xactions);
     return id(new AphrontAjaxResponse())->setContent(array('tasks' => $this->renderSingleTask($task)));
 }
 public function testRequestDataAccess()
 {
     $r = new AphrontRequest('http://example.com/', '/');
     $r->setRequestData(array('str_empty' => '', 'str' => 'derp', 'str_true' => 'true', 'str_false' => 'false', 'zero' => '0', 'one' => '1', 'arr_empty' => array(), 'arr_num' => array(1, 2, 3), 'comma' => ',', 'comma_1' => 'a, b', 'comma_2' => ' ,a ,, b ,,,, ,, ', 'comma_3' => '0', 'comma_4' => 'a, a, b, a', 'comma_5' => "a\nb, c\n\nd\n\n\n,\n"));
     $this->assertEqual(1, $r->getInt('one'));
     $this->assertEqual(0, $r->getInt('zero'));
     $this->assertEqual(null, $r->getInt('does-not-exist'));
     $this->assertEqual(0, $r->getInt('str_empty'));
     $this->assertEqual(true, $r->getBool('one'));
     $this->assertEqual(false, $r->getBool('zero'));
     $this->assertEqual(true, $r->getBool('str_true'));
     $this->assertEqual(false, $r->getBool('str_false'));
     $this->assertEqual(true, $r->getBool('str'));
     $this->assertEqual(null, $r->getBool('does-not-exist'));
     $this->assertEqual(false, $r->getBool('str_empty'));
     $this->assertEqual('derp', $r->getStr('str'));
     $this->assertEqual('', $r->getStr('str_empty'));
     $this->assertEqual(null, $r->getStr('does-not-exist'));
     $this->assertEqual(array(), $r->getArr('arr_empty'));
     $this->assertEqual(array(1, 2, 3), $r->getArr('arr_num'));
     $this->assertEqual(null, $r->getArr('str_empty', null));
     $this->assertEqual(null, $r->getArr('str_true', null));
     $this->assertEqual(null, $r->getArr('does-not-exist', null));
     $this->assertEqual(array(), $r->getArr('does-not-exist'));
     $this->assertEqual(array(), $r->getStrList('comma'));
     $this->assertEqual(array('a', 'b'), $r->getStrList('comma_1'));
     $this->assertEqual(array('a', 'b'), $r->getStrList('comma_2'));
     $this->assertEqual(array('0'), $r->getStrList('comma_3'));
     $this->assertEqual(array('a', 'a', 'b', 'a'), $r->getStrList('comma_4'));
     $this->assertEqual(array('a', 'b', 'c', 'd'), $r->getStrList('comma_5'));
     $this->assertEqual(array(), $r->getStrList('does-not-exist'));
     $this->assertEqual(null, $r->getStrList('does-not-exist', null));
     $this->assertEqual(true, $r->getExists('str'));
     $this->assertEqual(false, $r->getExists('does-not-exist'));
 }
 public function readFormValuesFromRequest(AphrontRequest $request)
 {
     $is_setup = $this->isSetup();
     if ($is_setup) {
         $name = $request->getStr(self::PROPERTY_JIRA_NAME);
     } else {
         $name = $this->getProviderDomain();
     }
     return array(self::PROPERTY_JIRA_NAME => $name, self::PROPERTY_JIRA_URI => $request->getStr(self::PROPERTY_JIRA_URI), self::PROPERTY_REPORT_LINK => $request->getInt(self::PROPERTY_REPORT_LINK, 0), self::PROPERTY_REPORT_COMMENT => $request->getInt(self::PROPERTY_REPORT_COMMENT, 0));
 }
 public function handleRequest(AphrontRequest $request)
 {
     $user = $request->getUser();
     $latest_conpherences = array();
     $latest_participant = id(new ConpherenceParticipantQuery())->withParticipantPHIDs(array($user->getPHID()))->setLimit(6)->execute();
     if ($latest_participant) {
         $conpherence_phids = mpull($latest_participant, 'getConpherencePHID');
         $latest_conpherences = id(new ConpherenceThreadQuery())->setViewer($user)->withPHIDs($conpherence_phids)->needCropPics(true)->needParticipantCache(true)->execute();
         $latest_conpherences = mpull($latest_conpherences, null, 'getPHID');
         $latest_conpherences = array_select_keys($latest_conpherences, $conpherence_phids);
     }
     $conpherence = null;
     $should_404 = false;
     if ($request->getInt('id')) {
         $conpherence = id(new ConpherenceThreadQuery())->setViewer($user)->withIDs(array($request->getInt('id')))->needCropPics(true)->needTransactions(true)->setTransactionLimit(ConpherenceThreadQuery::TRANSACTION_LIMIT)->executeOne();
         $should_404 = true;
     } else {
         if ($latest_participant) {
             $participant = head($latest_participant);
             $conpherence = id(new ConpherenceThreadQuery())->setViewer($user)->withPHIDs(array($participant->getConpherencePHID()))->needCropPics(true)->needTransactions(true)->setTransactionLimit(ConpherenceThreadQuery::TRANSACTION_LIMIT)->executeOne();
             $should_404 = true;
         }
     }
     $durable_column = id(new ConpherenceDurableColumnView())->setUser($user)->setVisible(true);
     if (!$conpherence) {
         if ($should_404) {
             return new Aphront404Response();
         }
         $conpherence_id = null;
         $conpherence_phid = null;
         $latest_transaction_id = null;
         $can_edit = false;
     } else {
         $this->setConpherence($conpherence);
         $participant = $conpherence->getParticipant($user->getPHID());
         $transactions = $conpherence->getTransactions();
         $latest_transaction = head($transactions);
         $write_guard = AphrontWriteGuard::beginScopedUnguardedWrites();
         $participant->markUpToDate($conpherence, $latest_transaction);
         unset($write_guard);
         $draft = PhabricatorDraft::newFromUserAndKey($user, $conpherence->getPHID());
         $durable_column->setDraft($draft)->setSelectedConpherence($conpherence)->setConpherences($latest_conpherences);
         $conpherence_id = $conpherence->getID();
         $conpherence_phid = $conpherence->getPHID();
         $latest_transaction_id = $latest_transaction->getID();
         $can_edit = PhabricatorPolicyFilter::hasCapability($user, $conpherence, PhabricatorPolicyCapability::CAN_EDIT);
     }
     $dropdown_query = id(new AphlictDropdownDataQuery())->setViewer($user);
     $dropdown_query->execute();
     $response = array('content' => hsprintf('%s', $durable_column), 'threadID' => $conpherence_id, 'threadPHID' => $conpherence_phid, 'latestTransactionID' => $latest_transaction_id, 'canEdit' => $can_edit, 'aphlictDropdownData' => array($dropdown_query->getNotificationData(), $dropdown_query->getConpherenceData()));
     return id(new AphrontAjaxResponse())->setContent($response);
 }
 /**
  * @phutil-external-symbol class PhabricatorStartup
  */
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     // NOTE: Throws if valid CSRF token is not present in the request.
     $request->validateCSRF();
     $name = $request->getStr('name');
     $file_phid = $request->getStr('phid');
     // If there's no explicit view policy, make it very restrictive by default.
     // This is the correct policy for files dropped onto objects during
     // creation, comment and edit flows.
     $view_policy = $request->getStr('viewPolicy');
     if (!$view_policy) {
         $view_policy = $viewer->getPHID();
     }
     $is_chunks = $request->getBool('querychunks');
     if ($is_chunks) {
         $params = array('filePHID' => $file_phid);
         $result = id(new ConduitCall('file.querychunks', $params))->setUser($viewer)->execute();
         return id(new AphrontAjaxResponse())->setContent($result);
     }
     $is_allocate = $request->getBool('allocate');
     if ($is_allocate) {
         $params = array('name' => $name, 'contentLength' => $request->getInt('length'), 'viewPolicy' => $view_policy);
         $result = id(new ConduitCall('file.allocate', $params))->setUser($viewer)->execute();
         $file_phid = $result['filePHID'];
         if ($file_phid) {
             $file = $this->loadFile($file_phid);
             $result += $file->getDragAndDropDictionary();
         }
         return id(new AphrontAjaxResponse())->setContent($result);
     }
     // Read the raw request data. We're either doing a chunk upload or a
     // vanilla upload, so we need it.
     $data = PhabricatorStartup::getRawInput();
     $is_chunk_upload = $request->getBool('uploadchunk');
     if ($is_chunk_upload) {
         $params = array('filePHID' => $file_phid, 'byteStart' => $request->getInt('byteStart'), 'data' => $data);
         $result = id(new ConduitCall('file.uploadchunk', $params))->setUser($viewer)->execute();
         $file = $this->loadFile($file_phid);
         if ($file->getIsPartial()) {
             $result = array();
         } else {
             $result = array('complete' => true) + $file->getDragAndDropDictionary();
         }
         return id(new AphrontAjaxResponse())->setContent($result);
     }
     $file = PhabricatorFile::newFromXHRUpload($data, array('name' => $request->getStr('name'), 'authorPHID' => $viewer->getPHID(), 'viewPolicy' => $view_policy, 'isExplicitUpload' => true));
     $result = $file->getDragAndDropDictionary();
     return id(new AphrontAjaxResponse())->setContent($result);
 }
 public function handleRequest(AphrontRequest $request)
 {
     $user = $request->getUser();
     $id = $request->getURIData('id');
     if ($id) {
         $post = id(new PhamePostQuery())->setViewer($user)->withIDs(array($id))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_EDIT))->executeOne();
         if (!$post) {
             return new Aphront404Response();
         }
         $cancel_uri = $this->getApplicationURI('/post/view/' . $id . '/');
         $submit_button = pht('Save Changes');
         $page_title = pht('Edit Post');
     } else {
         $blog = id(new PhameBlogQuery())->setViewer($user)->withIDs(array($request->getInt('blog')))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_JOIN))->executeOne();
         if (!$blog) {
             return new Aphront404Response();
         }
         $post = PhamePost::initializePost($user, $blog);
         $cancel_uri = $this->getApplicationURI('/blog/view/' . $blog->getID() . '/');
         $submit_button = pht('Save Draft');
         $page_title = pht('Create Post');
     }
     $title = $post->getTitle();
     $phame_title = $post->getPhameTitle();
     $body = $post->getBody();
     $comments_widget = $post->getCommentsWidget();
     $e_title = true;
     $e_phame_title = true;
     $validation_exception = null;
     if ($request->isFormPost()) {
         $title = $request->getStr('title');
         $phame_title = $request->getStr('phame_title');
         $phame_title = PhabricatorSlug::normalize($phame_title);
         $body = $request->getStr('body');
         $comments_widget = $request->getStr('comments_widget');
         $xactions = array(id(new PhamePostTransaction())->setTransactionType(PhamePostTransaction::TYPE_TITLE)->setNewValue($title), id(new PhamePostTransaction())->setTransactionType(PhamePostTransaction::TYPE_PHAME_TITLE)->setNewValue($phame_title), id(new PhamePostTransaction())->setTransactionType(PhamePostTransaction::TYPE_BODY)->setNewValue($body), id(new PhamePostTransaction())->setTransactionType(PhamePostTransaction::TYPE_COMMENTS_WIDGET)->setNewValue($comments_widget));
         $editor = id(new PhamePostEditor())->setActor($user)->setContentSourceFromRequest($request)->setContinueOnNoEffect(true);
         try {
             $editor->applyTransactions($post, $xactions);
             $uri = $this->getApplicationURI('/post/view/' . $post->getID() . '/');
             return id(new AphrontRedirectResponse())->setURI($uri);
         } catch (PhabricatorApplicationTransactionValidationException $ex) {
             $validation_exception = $ex;
             $e_title = $validation_exception->getShortMessage(PhamePostTransaction::TYPE_TITLE);
             $e_phame_title = $validation_exception->getShortMessage(PhamePostTransaction::TYPE_PHAME_TITLE);
         }
     }
     $handle = id(new PhabricatorHandleQuery())->setViewer($user)->withPHIDs(array($post->getBlogPHID()))->executeOne();
     $form = id(new AphrontFormView())->setUser($user)->addHiddenInput('blog', $request->getInt('blog'))->appendChild(id(new AphrontFormMarkupControl())->setLabel(pht('Blog'))->setValue($handle->renderLink()))->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Title'))->setName('title')->setValue($title)->setID('post-title')->setError($e_title))->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Phame Title'))->setName('phame_title')->setValue(rtrim($phame_title, '/'))->setID('post-phame-title')->setCaption(pht('Up to 64 alphanumeric characters ' . 'with underscores for spaces. ' . 'Formatting is enforced.'))->setError($e_phame_title))->appendChild(id(new PhabricatorRemarkupControl())->setLabel(pht('Body'))->setName('body')->setValue($body)->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_TALL)->setID('post-body')->setUser($user)->setDisableMacros(true))->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Comments Widget'))->setName('comments_widget')->setvalue($comments_widget)->setOptions($post->getCommentsWidgetOptionsForSelect()))->appendChild(id(new AphrontFormSubmitControl())->addCancelButton($cancel_uri)->setValue($submit_button));
     $loading = phutil_tag_div('aphront-panel-preview-loading-text', pht('Loading preview...'));
     $preview_panel = phutil_tag_div('aphront-panel-preview', array(phutil_tag_div('phame-post-preview-header', pht('Post Preview')), phutil_tag('div', array('id' => 'post-preview'), $loading)));
     require_celerity_resource('phame-css');
     Javelin::initBehavior('phame-post-preview', array('preview' => 'post-preview', 'body' => 'post-body', 'title' => 'post-title', 'phame_title' => 'post-phame-title', 'uri' => '/phame/post/preview/'));
     $form_box = id(new PHUIObjectBoxView())->setHeaderText($page_title)->setValidationException($validation_exception)->setForm($form);
     $crumbs = $this->buildApplicationCrumbs();
     $crumbs->addTextCrumb($page_title, $this->getApplicationURI('/post/view/' . $id . '/'));
     $nav = $this->renderSideNavFilterView(null);
     $nav->appendChild(array($crumbs, $form_box, $preview_panel));
     return $this->buildApplicationPage($nav, array('title' => $page_title));
 }
 public function processRequest(AphrontRequest $request)
 {
     $viewer = $this->getViewer();
     $preferences = $this->getPreferences();
     $notifications_key = PhabricatorDesktopNotificationsSetting::SETTINGKEY;
     $notifications_value = $preferences->getSettingValue($notifications_key);
     if ($request->isFormPost()) {
         $this->writeSetting($preferences, $notifications_key, $request->getInt($notifications_key));
         return id(new AphrontRedirectResponse())->setURI($this->getPanelURI('?saved=true'));
     }
     $title = pht('Desktop Notifications');
     $control_id = celerity_generate_unique_node_id();
     $status_id = celerity_generate_unique_node_id();
     $browser_status_id = celerity_generate_unique_node_id();
     $cancel_ask = pht('The dialog asking for permission to send desktop notifications was ' . 'closed without granting permission. Only application notifications ' . 'will be sent.');
     $accept_ask = pht('Click "Save Preference" to persist these changes.');
     $reject_ask = pht('Permission for desktop notifications was denied. Only application ' . 'notifications will be sent.');
     $no_support = pht('This web browser does not support desktop notifications. Only ' . 'application notifications will be sent for this browser regardless of ' . 'this preference.');
     $default_status = phutil_tag('span', array(), array(pht('This browser has not yet granted permission to send desktop ' . 'notifications for this Phabricator instance.'), phutil_tag('br'), phutil_tag('br'), javelin_tag('button', array('sigil' => 'desktop-notifications-permission-button', 'class' => 'green'), pht('Grant Permission'))));
     $granted_status = phutil_tag('span', array(), pht('This browser has been granted permission to send desktop ' . 'notifications for this Phabricator instance.'));
     $denied_status = phutil_tag('span', array(), pht('This browser has denied permission to send desktop notifications ' . 'for this Phabricator instance. Consult your browser settings / ' . 'documentation to figure out how to clear this setting, do so, ' . 'and then re-visit this page to grant permission.'));
     $status_box = id(new PHUIInfoView())->setSeverity(PHUIInfoView::SEVERITY_NOTICE)->setID($status_id)->setIsHidden(true)->appendChild($accept_ask);
     $control_config = array('controlID' => $control_id, 'statusID' => $status_id, 'browserStatusID' => $browser_status_id, 'defaultMode' => 0, 'desktopMode' => 1, 'cancelAsk' => $cancel_ask, 'grantedAsk' => $accept_ask, 'deniedAsk' => $reject_ask, 'defaultStatus' => $default_status, 'deniedStatus' => $denied_status, 'grantedStatus' => $granted_status, 'noSupport' => $no_support);
     $form = id(new AphrontFormView())->setUser($viewer)->appendChild(id(new AphrontFormSelectControl())->setLabel($title)->setControlID($control_id)->setName($notifications_key)->setValue($notifications_value)->setOptions(array(1 => pht('Send Desktop Notifications Too'), 0 => pht('Send Application Notifications Only')))->setCaption(pht('Should Phabricator send desktop notifications? These are sent ' . 'in addition to the notifications within the Phabricator ' . 'application.'))->initBehavior('desktop-notifications-control', $control_config))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Save Preference')));
     $test_button = id(new PHUIButtonView())->setTag('a')->setWorkflow(true)->setText(pht('Send Test Notification'))->setHref('/notification/test/')->setIcon('fa-exclamation-triangle');
     $form_box = id(new PHUIObjectBoxView())->setHeader(id(new PHUIHeaderView())->setHeader(pht('Desktop Notifications'))->addActionLink($test_button))->setForm($form)->setInfoView($status_box)->setFormSaved($request->getBool('saved'));
     $browser_status_box = id(new PHUIInfoView())->setID($browser_status_id)->setSeverity(PHUIInfoView::SEVERITY_NOTICE)->setIsHidden(true)->appendChild($default_status);
     return array($form_box, $browser_status_box);
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     $id = $request->getURIData('id');
     $blueprint = id(new DrydockBlueprintQuery())->setViewer($viewer)->withIDs(array($id))->executeOne();
     if (!$blueprint) {
         return new Aphront404Response();
     }
     $title = $blueprint->getBlueprintName();
     $header = id(new PHUIHeaderView())->setHeader($title)->setUser($viewer)->setPolicyObject($blueprint);
     $actions = $this->buildActionListView($blueprint);
     $properties = $this->buildPropertyListView($blueprint, $actions);
     $blueprint_uri = 'blueprint/' . $blueprint->getID() . '/';
     $blueprint_uri = $this->getApplicationURI($blueprint_uri);
     $resources = id(new DrydockResourceQuery())->withBlueprintPHIDs(array($blueprint->getPHID()))->setViewer($viewer)->execute();
     $resource_list = id(new DrydockResourceListView())->setUser($viewer)->setResources($resources)->render();
     $resource_list->setNoDataString(pht('This blueprint has no resources.'));
     $pager = new PHUIPagerView();
     $pager->setURI(new PhutilURI($blueprint_uri), 'offset');
     $pager->setOffset($request->getInt('offset'));
     $crumbs = $this->buildApplicationCrumbs();
     $crumbs->addTextCrumb(pht('Blueprint %d', $blueprint->getID()));
     $object_box = id(new PHUIObjectBoxView())->setHeader($header)->addPropertyList($properties);
     $field_list = PhabricatorCustomField::getObjectFields($blueprint, PhabricatorCustomField::ROLE_VIEW);
     $field_list->setViewer($viewer)->readFieldsFromStorage($blueprint);
     $field_list->appendFieldsToPropertyList($blueprint, $viewer, $properties);
     $timeline = $this->buildTransactionTimeline($blueprint, new DrydockBlueprintTransactionQuery());
     $timeline->setShouldTerminate(true);
     return $this->buildApplicationPage(array($crumbs, $object_box, $resource_list, $timeline), array('title' => $title));
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     if (!$request->isFormPost()) {
         return new Aphront400Response();
     }
     $question_id = $request->getInt('question_id');
     $question = id(new PonderQuestionQuery())->setViewer($viewer)->withIDs(array($question_id))->needAnswers(true)->executeOne();
     if (!$question) {
         return new Aphront404Response();
     }
     $content = $request->getStr('answer');
     if (!strlen(trim($content))) {
         $dialog = id(new AphrontDialogView())->setUser($viewer)->setTitle(pht('Empty Answer'))->appendChild(phutil_tag('p', array(), pht('Your answer must not be empty.')))->addCancelButton('/Q' . $question_id);
         return id(new AphrontDialogResponse())->setDialog($dialog);
     }
     $answer = PonderAnswer::initializeNewAnswer($viewer, $question);
     // Question Editor
     $xactions = array();
     $xactions[] = id(new PonderQuestionTransaction())->setTransactionType(PonderQuestionTransaction::TYPE_ANSWERS)->setNewValue(array('+' => array(array('answer' => $answer))));
     $editor = id(new PonderQuestionEditor())->setActor($viewer)->setContentSourceFromRequest($request);
     $editor->applyTransactions($question, $xactions);
     // Answer Editor
     $template = id(new PonderAnswerTransaction());
     $xactions = array();
     $xactions[] = id(clone $template)->setTransactionType(PonderAnswerTransaction::TYPE_QUESTION_ID)->setNewValue($question->getID());
     $xactions[] = id(clone $template)->setTransactionType(PonderAnswerTransaction::TYPE_CONTENT)->setNewValue($content);
     $editor = id(new PonderAnswerEditor())->setActor($viewer)->setContentSourceFromRequest($request)->setContinueOnNoEffect(true);
     $editor->applyTransactions($answer, $xactions);
     return id(new AphrontRedirectResponse())->setURI(id(new PhutilURI('/Q' . $question->getID())));
 }
 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);
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     $id = $request->getURIData('id');
     $post = id(new PhamePostQuery())->setViewer($viewer)->withIDs(array($id))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_EDIT, PhabricatorPolicyCapability::CAN_VIEW))->executeOne();
     if (!$post) {
         return new Aphront404Response();
     }
     $view_uri = '/post/view/' . $post->getID() . '/';
     $view_uri = $this->getApplicationURI($view_uri);
     if ($request->isFormPost()) {
         $blog = id(new PhameBlogQuery())->setViewer($viewer)->withIDs(array($request->getInt('blog')))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_EDIT))->executeOne();
         if ($blog) {
             $post->setBlogPHID($blog->getPHID());
             $post->save();
             return id(new AphrontRedirectResponse())->setURI($view_uri . '?moved=1');
         }
     }
     $blogs = id(new PhameBlogQuery())->setViewer($viewer)->requireCapabilities(array(PhabricatorPolicyCapability::CAN_EDIT))->execute();
     $options = mpull($blogs, 'getName', 'getID');
     asort($options);
     $selected_value = null;
     if ($post && $post->getBlog()) {
         $selected_value = $post->getBlog()->getID();
     }
     $form = id(new PHUIFormLayoutView())->setUser($viewer)->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Blog'))->setName('blog')->setOptions($options)->setValue($selected_value));
     return $this->newDialog()->setTitle(pht('Move Post'))->appendChild($form)->addSubmitButton(pht('Move Post'))->addCancelButton($view_uri);
 }
 public function handleRequest(AphrontRequest $request)
 {
     $user = $request->getUser();
     $nav = $this->renderSideNavFilterView(null);
     $filter = $request->getURIData('filter');
     $filter = $nav->selectFilter('blog/' . $filter, 'blog/user');
     $query = id(new PhameBlogQuery())->setViewer($user);
     switch ($filter) {
         case 'blog/all':
             $title = pht('All Blogs');
             $nodata = pht('No blogs have been created.');
             break;
         case 'blog/user':
             $title = pht('Joinable Blogs');
             $nodata = pht('There are no blogs you can contribute to.');
             $query->requireCapabilities(array(PhabricatorPolicyCapability::CAN_JOIN));
             break;
         default:
             throw new Exception(pht("Unknown filter '%s'!", $filter));
     }
     $pager = id(new AphrontPagerView())->setURI($request->getRequestURI(), 'offset')->setOffset($request->getInt('offset'));
     $blogs = $query->executeWithOffsetPager($pager);
     $blog_list = $this->renderBlogList($blogs, $user, $nodata);
     $blog_list->setPager($pager);
     $crumbs = $this->buildApplicationCrumbs();
     $crumbs->addTextCrumb($title, $this->getApplicationURI());
     $nav->appendChild(array($crumbs, $blog_list));
     return $this->buildApplicationPage($nav, array('title' => $title));
 }
 protected function processDiffusionRequest(AphrontRequest $request)
 {
     $limit = 500;
     $offset = $request->getInt('offset', 0);
     $drequest = $this->getDiffusionRequest();
     $branch = $drequest->loadBranch();
     $messages = $this->loadLintMessages($branch, $limit, $offset);
     $is_dir = substr('/' . $drequest->getPath(), -1) == '/';
     $authors = $this->loadViewerHandles(ipull($messages, 'authorPHID'));
     $rows = array();
     foreach ($messages as $message) {
         $path = phutil_tag('a', array('href' => $drequest->generateURI(array('action' => 'lint', 'path' => $message['path']))), substr($message['path'], strlen($drequest->getPath()) + 1));
         $line = phutil_tag('a', array('href' => $drequest->generateURI(array('action' => 'browse', 'path' => $message['path'], 'line' => $message['line'], 'commit' => $branch->getLintCommit()))), $message['line']);
         $author = $message['authorPHID'];
         if ($author && $authors[$author]) {
             $author = $authors[$author]->renderLink();
         }
         $rows[] = array($path, $line, $author, ArcanistLintSeverity::getStringForSeverity($message['severity']), $message['name'], $message['description']);
     }
     $table = id(new AphrontTableView($rows))->setHeaders(array(pht('Path'), pht('Line'), pht('Author'), pht('Severity'), pht('Name'), pht('Description')))->setColumnClasses(array('', 'n'))->setColumnVisibility(array($is_dir));
     $content = array();
     $pager = id(new AphrontPagerView())->setPageSize($limit)->setOffset($offset)->setHasMorePages(count($messages) >= $limit)->setURI($request->getRequestURI(), 'offset');
     $content[] = id(new PHUIObjectBoxView())->setHeaderText(pht('Lint Details'))->appendChild($table);
     $crumbs = $this->buildCrumbs(array('branch' => true, 'path' => true, 'view' => 'lint'));
     return $this->buildApplicationPage(array($crumbs, $content, $pager), array('title' => array(pht('Lint'), $drequest->getRepository()->getCallsign())));
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     $id = $request->getURIData('id');
     $resource = id(new DrydockResourceQuery())->setViewer($viewer)->withIDs(array($id))->executeOne();
     if (!$resource) {
         return new Aphront404Response();
     }
     $title = pht('Resource %s %s', $resource->getID(), $resource->getName());
     $header = id(new PHUIHeaderView())->setUser($viewer)->setPolicyObject($resource)->setHeader($title);
     $actions = $this->buildActionListView($resource);
     $properties = $this->buildPropertyListView($resource, $actions);
     $resource_uri = 'resource/' . $resource->getID() . '/';
     $resource_uri = $this->getApplicationURI($resource_uri);
     $pager = new PHUIPagerView();
     $pager->setURI(new PhutilURI($resource_uri), 'offset');
     $pager->setOffset($request->getInt('offset'));
     $logs = id(new DrydockLogQuery())->setViewer($viewer)->withResourceIDs(array($resource->getID()))->executeWithOffsetPager($pager);
     $log_table = id(new DrydockLogListView())->setUser($viewer)->setLogs($logs)->render();
     $log_table->appendChild($pager);
     $crumbs = $this->buildApplicationCrumbs();
     $crumbs->addTextCrumb(pht('Resource %d', $resource->getID()));
     $locks = $this->buildLocksTab($resource->getPHID());
     $commands = $this->buildCommandsTab($resource->getPHID());
     $object_box = id(new PHUIObjectBoxView())->setHeader($header)->addPropertyList($properties, pht('Properties'))->addPropertyList($locks, pht('Slot Locks'))->addPropertyList($commands, pht('Commands'));
     $lease_box = $this->buildLeaseBox($resource);
     $log_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Resource Logs'))->setTable($log_table);
     return $this->buildApplicationPage(array($crumbs, $object_box, $lease_box, $log_box), array('title' => $title));
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     $event = id(new PhabricatorCalendarEventQuery())->setViewer($viewer)->withIDs(array($request->getURIData('id')))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT))->executeOne();
     if (!$event) {
         return new Aphront404Response();
     }
     if (!$request->validateCSRF()) {
         return new Aphront400Response();
     }
     if ($event->getIsAllDay()) {
         return new Aphront400Response();
     }
     $xactions = array();
     $duration = $event->getDuration();
     $start = $request->getInt('start');
     $start_value = id(AphrontFormDateControlValue::newFromEpoch($viewer, $start));
     $end = $start + $duration;
     $end_value = id(AphrontFormDateControlValue::newFromEpoch($viewer, $end));
     $xactions[] = id(new PhabricatorCalendarEventTransaction())->setTransactionType(PhabricatorCalendarEventStartDateTransaction::TRANSACTIONTYPE)->setNewValue($start_value);
     $xactions[] = id(new PhabricatorCalendarEventTransaction())->setTransactionType(PhabricatorCalendarEventEndDateTransaction::TRANSACTIONTYPE)->setNewValue($end_value);
     $editor = id(new PhabricatorCalendarEventEditor())->setActor($viewer)->setContinueOnMissingFields(true)->setContentSourceFromRequest($request)->setContinueOnNoEffect(true);
     $xactions = $editor->applyTransactions($event, $xactions);
     return id(new AphrontReloadResponse());
 }
Example #16
0
 public final function readFromRequest(AphrontRequest $request)
 {
     $this->uri = $request->getRequestURI();
     $this->pagingParameter = 'offset';
     $this->offset = $request->getInt($this->pagingParameter);
     return $this;
 }
 public function processControllerRequest(PhortuneProviderController $controller, AphrontRequest $request)
 {
     $cart = $controller->loadCart($request->getInt('cartID'));
     if (!$cart) {
         return new Aphront404Response();
     }
     switch ($controller->getAction()) {
         case 'checkout':
             $return_uri = $this->getControllerURI('charge', array('cartID' => $cart->getID()));
             $cancel_uri = $this->getControllerURI('cancel', array('cartID' => $cart->getID()));
             $total_in_cents = $cart->getTotalPriceInCents();
             $price = PhortuneCurrency::newFromUSDCents($total_in_cents);
             $result = $this->newPaypalAPICall()->setRawPayPalQuery('SetExpressCheckout', array('PAYMENTREQUEST_0_AMT' => $price->formatBareValue(), 'PAYMENTREQUEST_0_CURRENCYCODE' => $price->getCurrency(), 'RETURNURL' => $return_uri, 'CANCELURL' => $cancel_uri, 'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale'))->resolve();
             $uri = new PhutilURI('https://www.sandbox.paypal.com/cgi-bin/webscr');
             $uri->setQueryParams(array('cmd' => '_express-checkout', 'token' => $result['TOKEN']));
             return id(new AphrontRedirectResponse())->setIsExternal(true)->setURI($uri);
         case 'charge':
             var_dump($_REQUEST);
             break;
         case 'cancel':
             var_dump($_REQUEST);
             break;
     }
     throw new Exception("The rest of this isn't implemented yet.");
 }
 public function processRequest(AphrontRequest $request)
 {
     $viewer = $request->getUser();
     // TODO: It would be nice to simply disable this panel, but we can't do
     // viewer-based checks for enabled panels right now.
     $app_class = 'PhabricatorOAuthServerApplication';
     $installed = PhabricatorApplication::isClassInstalledForViewer($app_class, $viewer);
     if (!$installed) {
         $dialog = id(new AphrontDialogView())->setUser($viewer)->setTitle(pht('OAuth Not Available'))->appendParagraph(pht('You do not have access to OAuth authorizations.'))->addCancelButton('/settings/');
         return id(new AphrontDialogResponse())->setDialog($dialog);
     }
     $authorizations = id(new PhabricatorOAuthClientAuthorizationQuery())->setViewer($viewer)->withUserPHIDs(array($viewer->getPHID()))->execute();
     $authorizations = mpull($authorizations, null, 'getID');
     $panel_uri = $this->getPanelURI();
     $revoke = $request->getInt('revoke');
     if ($revoke) {
         if (empty($authorizations[$revoke])) {
             return new Aphront404Response();
         }
         if ($request->isFormPost()) {
             $authorizations[$revoke]->delete();
             return id(new AphrontRedirectResponse())->setURI($panel_uri);
         }
         $dialog = id(new AphrontDialogView())->setUser($viewer)->setTitle(pht('Revoke Authorization?'))->appendParagraph(pht('This application will no longer be able to access Phabricator ' . 'on your behalf.'))->addSubmitButton(pht('Revoke Authorization'))->addCancelButton($panel_uri);
         return id(new AphrontDialogResponse())->setDialog($dialog);
     }
     $highlight = $request->getInt('id');
     $rows = array();
     $rowc = array();
     foreach ($authorizations as $authorization) {
         if ($highlight == $authorization->getID()) {
             $rowc[] = 'highlighted';
         } else {
             $rowc[] = null;
         }
         $button = javelin_tag('a', array('href' => $this->getPanelURI('?revoke=' . $authorization->getID()), 'class' => 'small grey button', 'sigil' => 'workflow'), pht('Revoke'));
         $rows[] = array(phutil_tag('a', array('href' => $authorization->getClient()->getViewURI()), $authorization->getClient()->getName()), $authorization->getScopeString(), phabricator_datetime($authorization->getDateCreated(), $viewer), phabricator_datetime($authorization->getDateModified(), $viewer), $button);
     }
     $table = new AphrontTableView($rows);
     $table->setNoDataString(pht("You haven't authorized any OAuth applications."));
     $table->setRowClasses($rowc);
     $table->setHeaders(array(pht('Application'), pht('Scope'), pht('Created'), pht('Updated'), null));
     $table->setColumnClasses(array('pri', 'wide', 'right', 'right', 'action'));
     $header = id(new PHUIHeaderView())->setHeader(pht('OAuth Application Authorizations'));
     $panel = id(new PHUIObjectBoxView())->setHeader($header)->appendChild($table);
     return $panel;
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $this->getViewer();
     $id = $request->getURIData('id');
     $diff = id(new DifferentialDiffQuery())->setViewer($viewer)->withIDs(array($id))->executeOne();
     if (!$diff) {
         return new Aphront404Response();
     }
     if ($diff->getRevisionID()) {
         return id(new AphrontRedirectResponse())->setURI('/D' . $diff->getRevisionID() . '?id=' . $diff->getID());
     }
     $diff_phid = $diff->getPHID();
     $buildables = id(new HarbormasterBuildableQuery())->setViewer($viewer)->withBuildablePHIDs(array($diff_phid))->withManualBuildables(false)->needBuilds(true)->needTargets(true)->execute();
     $buildables = mpull($buildables, null, 'getBuildablePHID');
     $diff->attachBuildable(idx($buildables, $diff_phid));
     // TODO: implement optgroup support in AphrontFormSelectControl?
     $select = array();
     $select[] = hsprintf('<optgroup label="%s">', pht('Create New Revision'));
     $select[] = phutil_tag('option', array('value' => ''), pht('Create a new Revision...'));
     $select[] = hsprintf('</optgroup>');
     $selected_id = $request->getInt('revisionID');
     $revisions = $this->loadSelectableRevisions($viewer, $selected_id);
     if ($revisions) {
         $select[] = hsprintf('<optgroup label="%s">', pht('Update Existing Revision'));
         foreach ($revisions as $revision) {
             if ($selected_id == $revision->getID()) {
                 $selected = 'selected';
             } else {
                 $selected = null;
             }
             $select[] = phutil_tag('option', array('value' => $revision->getID(), 'selected' => $selected), id(new PhutilUTF8StringTruncator())->setMaximumGlyphs(128)->truncateString('D' . $revision->getID() . ' ' . $revision->getTitle()));
         }
         $select[] = hsprintf('</optgroup>');
     }
     $select = phutil_tag('select', array('name' => 'revisionID'), $select);
     $form = id(new AphrontFormView())->setUser($request->getUser())->setAction('/differential/revision/edit/')->addHiddenInput('diffID', $diff->getID())->addHiddenInput('viaDiffView', 1)->addHiddenInput(id(new DifferentialRepositoryField())->getFieldKey(), $diff->getRepositoryPHID())->appendRemarkupInstructions(pht('Review the diff for correctness. When you are satisfied, either ' . '**create a new revision** or **update an existing revision**.'))->appendChild(id(new AphrontFormMarkupControl())->setLabel(pht('Attach To'))->setValue($select))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Continue')));
     $props = id(new DifferentialDiffProperty())->loadAllWhere('diffID = %d', $diff->getID());
     $props = mpull($props, 'getData', 'getName');
     $property_head = id(new PHUIHeaderView())->setHeader(pht('Properties'));
     $property_view = new PHUIPropertyListView();
     $changesets = $diff->loadChangesets();
     $changesets = msort($changesets, 'getSortKey');
     $table_of_contents = $this->buildTableOfContents($changesets, $changesets, $diff->loadCoverageMap($viewer));
     $refs = array();
     foreach ($changesets as $changeset) {
         $refs[$changeset->getID()] = $changeset->getID();
     }
     $details = id(new DifferentialChangesetListView())->setChangesets($changesets)->setVisibleChangesets($changesets)->setRenderingReferences($refs)->setStandaloneURI('/differential/changeset/')->setDiff($diff)->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)->setTitle(pht('Diff %d', $diff->getID()))->setUser($request->getUser());
     $title = pht('Diff %d', $diff->getID());
     $crumbs = $this->buildApplicationCrumbs();
     $crumbs->addTextCrumb($title);
     $crumbs->setBorder(true);
     $header = id(new PHUIHeaderView())->setHeader($title);
     $prop_box = id(new PHUIObjectBoxView())->setHeader($property_head)->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)->addPropertyList($property_view)->setForm($form);
     $view = id(new PHUITwoColumnView())->setHeader($header)->setMainColumn(array())->setFooter(array($prop_box, $table_of_contents, $details));
     $page = $this->newPage()->setTitle(pht('Diff View'))->setCrumbs($crumbs)->appendChild($view);
     return $page;
 }
 protected function processDiffusionRequest(AphrontRequest $request)
 {
     $drequest = $this->diffusionRequest;
     $viewer = $request->getUser();
     $repository = $drequest->getRepository();
     $page_size = $request->getInt('pagesize', 100);
     $offset = $request->getInt('offset', 0);
     $params = array('commit' => $drequest->getCommit(), 'path' => $drequest->getPath(), 'offset' => $offset, 'limit' => $page_size + 1);
     if (!$request->getBool('copies')) {
         $params['needDirectChanges'] = true;
         $params['needChildChanges'] = true;
     }
     $history_results = $this->callConduitWithDiffusionRequest('diffusion.historyquery', $params);
     $history = DiffusionPathChange::newFromConduit($history_results['pathChanges']);
     $pager = new AphrontPagerView();
     $pager->setPageSize($page_size);
     $pager->setOffset($offset);
     $history = $pager->sliceResults($history);
     $pager->setURI($request->getRequestURI(), 'offset');
     $show_graph = !strlen($drequest->getPath());
     $content = array();
     $history_table = new DiffusionHistoryTableView();
     $history_table->setUser($request->getUser());
     $history_table->setDiffusionRequest($drequest);
     $history_table->setHistory($history);
     $history_table->loadRevisions();
     $phids = $history_table->getRequiredHandlePHIDs();
     $handles = $this->loadViewerHandles($phids);
     $history_table->setHandles($handles);
     if ($show_graph) {
         $history_table->setParents($history_results['parents']);
         $history_table->setIsHead($offset == 0);
     }
     $history_panel = new PHUIObjectBoxView();
     $history_panel->setHeaderText(pht('History'));
     $history_panel->appendChild($history_table);
     $content[] = $history_panel;
     $header = id(new PHUIHeaderView())->setUser($viewer)->setPolicyObject($repository)->setHeader($this->renderPathLinks($drequest, $mode = 'history'));
     $actions = $this->buildActionView($drequest);
     $properties = $this->buildPropertyView($drequest, $actions);
     $object_box = id(new PHUIObjectBoxView())->setHeader($header)->addPropertyList($properties);
     $crumbs = $this->buildCrumbs(array('branch' => true, 'path' => true, 'view' => 'history'));
     return $this->buildApplicationPage(array($crumbs, $object_box, $content, $pager), array('title' => array(pht('History'), pht('%s Repository', $drequest->getRepository()->getCallsign()))));
 }
 public function readValueFromRequest(AphrontRequest $request)
 {
     $day = $request->getInt($this->getDayInputName());
     $month = $request->getInt($this->getMonthInputName());
     $year = $request->getInt($this->getYearInputName());
     $time = $request->getStr($this->getTimeInputName());
     $enabled = $request->getBool($this->getCheckboxInputName());
     if ($this->allowNull && !$enabled) {
         $this->setError(null);
         $this->setValue(null);
         return;
     }
     $err = $this->getError();
     if ($day || $month || $year || $time) {
         $this->valueDay = $day;
         $this->valueMonth = $month;
         $this->valueYear = $year;
         $this->valueTime = $time;
         // Assume invalid.
         $err = 'Invalid';
         $zone = $this->getTimezone();
         try {
             $date = new DateTime("{$year}-{$month}-{$day} {$time}", $zone);
             $value = $date->format('U');
         } catch (Exception $ex) {
             $value = null;
         }
         if ($value) {
             $this->setValue($value);
             $err = null;
         } else {
             $this->setValue(null);
         }
     } else {
         $value = $this->getInitialValue();
         if ($value) {
             $this->setValue($value);
         } else {
             $this->setValue(null);
         }
     }
     $this->setError($err);
     return $this->getValue();
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     $view = $request->getURIData('view');
     if (!$view) {
         $view = 'all';
     }
     $pager = new PHUIPagerView();
     $pager->setOffset($request->getInt('page'));
     switch ($view) {
         case 'sampled':
             $clause = 'sampleRate > 0';
             $show_type = false;
             break;
         case 'my-runs':
             $clause = qsprintf(id(new PhabricatorXHProfSample())->establishConnection('r'), 'sampleRate = 0 AND userPHID = %s', $request->getUser()->getPHID());
             $show_type = false;
             break;
         case 'manual':
             $clause = 'sampleRate = 0';
             $show_type = false;
             break;
         case 'all':
         default:
             $clause = '1 = 1';
             $show_type = true;
             break;
     }
     $samples = id(new PhabricatorXHProfSample())->loadAllWhere('%Q ORDER BY id DESC LIMIT %d, %d', $clause, $pager->getOffset(), $pager->getPageSize() + 1);
     $samples = $pager->sliceResults($samples);
     $pager->setURI($request->getRequestURI(), 'page');
     $list = new PHUIObjectItemListView();
     foreach ($samples as $sample) {
         $file_phid = $sample->getFilePHID();
         $item = id(new PHUIObjectItemView())->setObjectName($sample->getID())->setHeader($sample->getRequestPath())->setHref($this->getApplicationURI('profile/' . $file_phid . '/'))->addAttribute(number_format($sample->getUsTotal()) . " μs");
         if ($sample->getController()) {
             $item->addAttribute($sample->getController());
         }
         $item->addAttribute($sample->getHostName());
         $rate = $sample->getSampleRate();
         if ($rate == 0) {
             $item->addIcon('flag-6', pht('Manual Run'));
         } else {
             $item->addIcon('flag-7', pht('Sampled (1/%d)', $rate));
         }
         $item->addIcon('none', phabricator_datetime($sample->getDateCreated(), $viewer));
         $list->addItem($item);
     }
     $list->setPager($pager);
     $list->setNoDataString(pht('There are no profiling samples.'));
     $crumbs = $this->buildApplicationCrumbs();
     $crumbs->addTextCrumb(pht('XHProf Samples'));
     $title = pht('XHProf Samples');
     return $this->newPage()->setTitle($title)->setCrumbs($crumbs)->appendChild($list);
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     $dblob = $request->getURIData('dblob');
     $parent = null;
     $parents = $this->loadParentFragments($dblob);
     if ($parents === null) {
         return new Aphront404Response();
     }
     if (count($parents) !== 0) {
         $parent = idx($parents, count($parents) - 1, null);
     }
     $parent_path = '';
     if ($parent !== null) {
         $parent_path = $parent->getPath();
     }
     $parent_path = trim($parent_path, '/');
     $fragment = id(new PhragmentFragment());
     $error_view = null;
     if ($request->isFormPost()) {
         $errors = array();
         $v_name = $request->getStr('name');
         $v_fileid = $request->getInt('fileID');
         $v_viewpolicy = $request->getStr('viewPolicy');
         $v_editpolicy = $request->getStr('editPolicy');
         if (strpos($v_name, '/') !== false) {
             $errors[] = pht("The fragment name can not contain '/'.");
         }
         $file = id(new PhabricatorFileQuery())->setViewer($viewer)->withIDs(array($v_fileid))->executeOne();
         if (!$file) {
             $errors[] = pht("The specified file doesn't exist.");
         }
         if (!count($errors)) {
             $depth = 1;
             if ($parent !== null) {
                 $depth = $parent->getDepth() + 1;
             }
             PhragmentFragment::createFromFile($viewer, $file, trim($parent_path . '/' . $v_name, '/'), $v_viewpolicy, $v_editpolicy);
             return id(new AphrontRedirectResponse())->setURI('/phragment/browse/' . trim($parent_path . '/' . $v_name, '/'));
         } else {
             $error_view = id(new PHUIInfoView())->setErrors($errors)->setTitle(pht('Errors while creating fragment'));
         }
     }
     $policies = id(new PhabricatorPolicyQuery())->setViewer($viewer)->setObject($fragment)->execute();
     $form = id(new AphrontFormView())->setUser($viewer)->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Parent Path'))->setDisabled(true)->setValue('/' . trim($parent_path . '/', '/')))->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Name'))->setName('name'))->appendChild(id(new AphrontFormTextControl())->setLabel(pht('File ID'))->setName('fileID'))->appendChild(id(new AphrontFormPolicyControl())->setUser($viewer)->setName('viewPolicy')->setPolicyObject($fragment)->setPolicies($policies)->setCapability(PhabricatorPolicyCapability::CAN_VIEW))->appendChild(id(new AphrontFormPolicyControl())->setUser($viewer)->setName('editPolicy')->setPolicyObject($fragment)->setPolicies($policies)->setCapability(PhabricatorPolicyCapability::CAN_EDIT))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Create Fragment'))->addCancelButton($this->getApplicationURI('browse/' . $parent_path)));
     $crumbs = $this->buildApplicationCrumbsWithPath($parents);
     $crumbs->addTextCrumb(pht('Create Fragment'));
     $box = id(new PHUIObjectBoxView())->setHeaderText(pht('Create Fragment'))->setForm($form);
     if ($error_view) {
         $box->setInfoView($error_view);
     }
     $title = pht('Create Fragments');
     $view = array($this->renderConfigurationWarningIfRequired(), $box);
     return $this->newPage()->setTitle($title)->setCrumbs($crumbs)->appendChild($view);
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     $id = $request->getURIData('id');
     $blog = id(new PhameBlogQuery())->setViewer($viewer)->withIDs(array($id))->needHeaderImage(true)->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT))->executeOne();
     if (!$blog) {
         return new Aphront404Response();
     }
     $blog_uri = '/phame/blog/manage/' . $id;
     $supported_formats = PhabricatorFile::getTransformableImageFormats();
     $e_file = true;
     $errors = array();
     $delete_header = $request->getInt('delete') == 1;
     if ($request->isFormPost()) {
         if ($request->getFileExists('header')) {
             $file = PhabricatorFile::newFromPHPUpload($_FILES['header'], array('authorPHID' => $viewer->getPHID(), 'canCDN' => true));
         } else {
             if (!$delete_header) {
                 $e_file = pht('Required');
                 $errors[] = pht('You must choose a file when uploading a new blog header.');
             }
         }
         if (!$errors && !$delete_header) {
             if (!$file->isTransformableImage()) {
                 $e_file = pht('Not Supported');
                 $errors[] = pht('This server only supports these image formats: %s.', implode(', ', $supported_formats));
             }
         }
         if (!$errors) {
             if ($delete_header) {
                 $new_value = null;
             } else {
                 $file->attachToObject($blog->getPHID());
                 $new_value = $file->getPHID();
             }
             $xactions = array();
             $xactions[] = id(new PhameBlogTransaction())->setTransactionType(PhameBlogTransaction::TYPE_HEADERIMAGE)->setNewValue($new_value);
             $editor = id(new PhameBlogEditor())->setActor($viewer)->setContentSourceFromRequest($request)->setContinueOnMissingFields(true)->setContinueOnNoEffect(true);
             $editor->applyTransactions($blog, $xactions);
             return id(new AphrontRedirectResponse())->setURI($blog_uri);
         }
     }
     $title = pht('Edit Blog Header');
     $upload_form = id(new AphrontFormView())->setUser($viewer)->setEncType('multipart/form-data')->appendChild(id(new AphrontFormFileControl())->setName('header')->setLabel(pht('Upload Header'))->setError($e_file)->setCaption(pht('Supported formats: %s', implode(', ', $supported_formats))))->appendChild(id(new AphrontFormCheckboxControl())->setName('delete')->setLabel(pht('Delete Header'))->addCheckbox('delete', 1, null, null))->appendChild(id(new AphrontFormSubmitControl())->addCancelButton($blog_uri)->setValue(pht('Upload Header')));
     $upload_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Upload New Header'))->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)->setForm($upload_form);
     $crumbs = $this->buildApplicationCrumbs();
     $crumbs->addTextCrumb(pht('Blogs'), $this->getApplicationURI('blog/'));
     $crumbs->addTextCrumb($blog->getName(), $this->getApplicationURI('blog/view/' . $id));
     $crumbs->addTextCrumb(pht('Blog Header'));
     $crumbs->setBorder(true);
     $header = id(new PHUIHeaderView())->setHeader(pht('Edit Blog Header'))->setHeaderIcon('fa-camera');
     $view = id(new PHUITwoColumnView())->setHeader($header)->setFooter(array($upload_box));
     return $this->newPage()->setTitle($title)->setCrumbs($crumbs)->appendChild(array($view));
 }
 public function handlePanelRequest(AphrontRequest $request, PhabricatorController $controller)
 {
     $viewer = $request->getViewer();
     $application = $this->getApplication();
     $path = $request->getURIData('path');
     if (strlen($path)) {
         return new Aphront404Response();
     }
     $uri = $request->getRequestURI();
     $uri->setQueryParams(array());
     $new = $request->getStr('new');
     $edit = $request->getInt('edit');
     $delete = $request->getInt('delete');
     if ($new) {
         return $this->returnNewAddressResponse($request, $uri, $application);
     }
     if ($edit) {
         return $this->returnEditAddressResponse($request, $uri, $edit);
     }
     if ($delete) {
         return $this->returnDeleteAddressResponse($request, $uri, $delete);
     }
     $table = $this->buildEmailTable($is_edit = true, $request->getInt('id'));
     $form = id(new AphrontFormView())->setUser($viewer);
     $crumbs = $controller->buildPanelCrumbs($this);
     $crumbs->addTextCrumb(pht('Edit Application Emails'));
     $crumbs->setBorder(true);
     $header = id(new PHUIHeaderView())->setHeader(pht('Edit Application Emails: %s', $application->getName()))->setSubheader($application->getAppEmailBlurb())->setHeaderIcon('fa-pencil');
     $icon = id(new PHUIIconView())->setIcon('fa-plus');
     $button = new PHUIButtonView();
     $button->setText(pht('Add New Address'));
     $button->setTag('a');
     $button->setHref($uri->alter('new', 'true'));
     $button->setIcon($icon);
     $button->addSigil('workflow');
     $header->addActionLink($button);
     $object_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Emails'))->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)->setTable($table);
     $title = $application->getName();
     $view = id(new PHUITwoColumnView())->setHeader($header)->setFooter($object_box);
     return $controller->buildPanelPage($this, $title, $crumbs, $view);
 }
 public function handleRequest(AphrontRequest $request)
 {
     $user = $request->getUser();
     $id = $request->getURIData('id');
     $post = null;
     $view_uri = null;
     if ($id) {
         $post = id(new PhamePostQuery())->setViewer($user)->withIDs(array($id))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_EDIT))->executeOne();
         if (!$post) {
             return new Aphront404Response();
         }
         $view_uri = '/post/view/' . $post->getID() . '/';
         $view_uri = $this->getApplicationURI($view_uri);
         if ($request->isFormPost()) {
             $blog = id(new PhameBlogQuery())->setViewer($user)->withIDs(array($request->getInt('blog')))->requireCapabilities(array(PhabricatorPolicyCapability::CAN_JOIN))->executeOne();
             if ($blog) {
                 $post->setBlogPHID($blog->getPHID());
                 $post->save();
                 return id(new AphrontRedirectResponse())->setURI($view_uri);
             }
         }
         $title = pht('Move Post');
     } else {
         $title = pht('Create Post');
         $view_uri = $this->getApplicationURI('/post/new');
     }
     $blogs = id(new PhameBlogQuery())->setViewer($user)->requireCapabilities(array(PhabricatorPolicyCapability::CAN_JOIN))->execute();
     $nav = $this->renderSideNavFilterView();
     $nav->selectFilter('post/new');
     $crumbs = $this->buildApplicationCrumbs();
     $crumbs->addTextCrumb($title, $view_uri);
     $nav->appendChild($crumbs);
     if (!$blogs) {
         $notification = id(new PHUIInfoView())->setSeverity(PHUIInfoView::SEVERITY_NODATA)->appendChild(pht('You do not have permission to join any blogs. Create a blog ' . 'first, then you can post to it.'));
         $nav->appendChild($notification);
     } else {
         $options = mpull($blogs, 'getName', 'getID');
         asort($options);
         $selected_value = null;
         if ($post && $post->getBlog()) {
             $selected_value = $post->getBlog()->getID();
         }
         $form = id(new AphrontFormView())->setUser($user)->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Blog'))->setName('blog')->setOptions($options)->setValue($selected_value));
         if ($post) {
             $form->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Move Post'))->addCancelButton($view_uri));
         } else {
             $form->setAction($this->getApplicationURI('post/edit/'))->setMethod('GET')->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Continue')));
         }
         $form_box = id(new PHUIObjectBoxView())->setHeaderText($title)->setForm($form);
         $nav->appendChild($form_box);
     }
     return $this->buildApplicationPage($nav, array('title' => $title));
 }
 public function handleRequest(AphrontRequest $request)
 {
     $query = $request->getStr('q');
     $repo_id = $request->getInt('repo');
     $since = $request->getInt('since');
     $limit = $request->getInt('limit');
     $now = time();
     $data = array();
     // Dummy instances used for getting connections, table names, etc.
     $pr_commit = new PhabricatorRepositoryCommit();
     $pr_commit_data = new PhabricatorRepositoryCommitData();
     $conn = $pr_commit->establishConnection('r');
     $rows = queryfx_all($conn, 'SELECT
     rc.phid as commitPHID,
     rc.authorPHID,
     rcd.authorName,
     SUBSTRING(rcd.commitMessage, 1, 100) AS shortMessage,
     rc.commitIdentifier,
     rc.epoch
     FROM %T rc
     INNER JOIN %T rcd ON rcd.commitID = rc.id
     WHERE repositoryID = %d
     AND rc.epoch >= %d
     AND (
       rcd.commitMessage LIKE %~
       OR
       rc.commitIdentifier LIKE %~
     )
     ORDER BY rc.epoch DESC
     LIMIT %d', $pr_commit->getTableName(), $pr_commit_data->getTableName(), $repo_id, $since, $query, $query, $limit);
     foreach ($rows as $row) {
         $full_commit_id = $row['commitIdentifier'];
         $short_commit_id = substr($full_commit_id, 0, 12);
         $first_line = $this->getFirstLine($row['shortMessage']);
         $data[] = array($full_commit_id, $short_commit_id, $row['authorName'], phutil_format_relative_time($now - $row['epoch']), $first_line);
     }
     return id(new AphrontAjaxResponse())->setContent($data);
 }
 public function processRequest(AphrontRequest $request)
 {
     $user = $request->getUser();
     $preferences = $user->loadPreferences();
     $pref = PhabricatorUserPreferences::PREFERENCE_CONPH_NOTIFICATIONS;
     if ($request->isFormPost()) {
         $notifications = $request->getInt($pref);
         $preferences->setPreference($pref, $notifications);
         $preferences->save();
         return id(new AphrontRedirectResponse())->setURI($this->getPanelURI('?saved=true'));
     }
     $form = id(new AphrontFormView())->setUser($user)->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Conpherence Notifications'))->setName($pref)->setValue($preferences->getPreference($pref))->setOptions(array(ConpherenceSettings::EMAIL_ALWAYS => pht('Email Always'), ConpherenceSettings::NOTIFICATIONS_ONLY => pht('Notifications Only')))->setCaption(pht('Should Conpherence send emails for updates or ' . 'notifications only? This global setting can be overridden ' . 'on a per-thread basis within Conpherence.')))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Save Preferences')));
     $form_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Conpherence Preferences'))->setForm($form)->setFormSaved($request->getBool('saved'));
     return array($form_box);
 }
 public function readValueFromRequest(AphrontRequest $request)
 {
     $day = $request->getInt($this->getDayInputName());
     $month = $request->getInt($this->getMonthInputName());
     $year = $request->getInt($this->getYearInputName());
     $err = $this->getError();
     if ($day || $month || $year) {
         // Assume invalid.
         $err = 'Invalid';
         $tz = new DateTimeZone('UTC');
         try {
             $date = new DateTime("{$year}-{$month}-{$day} 12:00:00 AM", $tz);
             $value = $date->format('Y-m-d');
             if ($value) {
                 $this->setValue($value);
                 $err = null;
             }
         } catch (Exception $ex) {
             // Ignore, already handled.
         }
     }
     $this->setError($err);
     return $err;
 }
 /**
  * @phutil-external-symbol class WePay
  */
 public function processControllerRequest(PhortuneProviderController $controller, AphrontRequest $request)
 {
     $viewer = $request->getUser();
     $cart = $controller->loadCart($request->getInt('cartID'));
     if (!$cart) {
         return new Aphront404Response();
     }
     $cart_uri = '/phortune/cart/' . $cart->getID() . '/';
     $root = dirname(phutil_get_library_root('phabricator'));
     require_once $root . '/externals/wepay/wepay.php';
     WePay::useStaging($this->getWePayClientID(), $this->getWePayClientSecret());
     $wepay = new WePay($this->getWePayAccessToken());
     switch ($controller->getAction()) {
         case 'checkout':
             $return_uri = $this->getControllerURI('charge', array('cartID' => $cart->getID()));
             $cancel_uri = $this->getControllerURI('cancel', array('cartID' => $cart->getID()));
             $total_in_cents = $cart->getTotalPriceInCents();
             $price = PhortuneCurrency::newFromUSDCents($total_in_cents);
             $params = array('account_id' => $this->getWePayAccountID(), 'short_description' => 'Services', 'type' => 'SERVICE', 'amount' => $price->formatBareValue(), 'long_description' => 'Services', 'reference_id' => $cart->getPHID(), 'app_fee' => 0, 'fee_payer' => 'Payee', 'redirect_uri' => $return_uri, 'fallback_uri' => $cancel_uri, 'auto_capture' => true, 'require_shipping' => 0, 'shipping_fee' => 0, 'charge_tax' => 0, 'mode' => 'regular', 'funding_sources' => 'bank,cc');
             $result = $wepay->request('checkout/create', $params);
             // TODO: We must store "$result->checkout_id" on the Cart since the
             // user might not end up back here. Really this needs a bunch of junk.
             $uri = new PhutilURI($result->checkout_uri);
             return id(new AphrontRedirectResponse())->setIsExternal(true)->setURI($uri);
         case 'charge':
             $checkout_id = $request->getInt('checkout_id');
             $params = array('checkout_id' => $checkout_id);
             $checkout = $wepay->request('checkout', $params);
             if ($checkout->reference_id != $cart->getPHID()) {
                 throw new Exception(pht('Checkout reference ID does not match cart PHID!'));
             }
             switch ($checkout->state) {
                 case 'authorized':
                 case 'reserved':
                 case 'captured':
                     break;
                 default:
                     throw new Exception(pht('Checkout is in bad state "%s"!', $result->state));
             }
             $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
             $charge = id(new PhortuneCharge())->setAmountInCents((int) $checkout->gross * 100)->setAccountPHID($cart->getAccount()->getPHID())->setAuthorPHID($viewer->getPHID())->setPaymentProviderKey($this->getProviderKey())->setCartPHID($cart->getPHID())->setStatus(PhortuneCharge::STATUS_CHARGING)->save();
             $cart->openTransaction();
             $charge->setStatus(PhortuneCharge::STATUS_CHARGED);
             $charge->save();
             $cart->setStatus(PhortuneCart::STATUS_PURCHASED);
             $cart->save();
             $cart->saveTransaction();
             unset($unguarded);
             return id(new AphrontRedirectResponse())->setIsExternal(true)->setURI($cart_uri);
         case 'cancel':
             var_dump($_REQUEST);
             break;
     }
     throw new Exception("The rest of this isn't implemented yet.");
 }