public function processAddFactorForm(AphrontFormView $form, AphrontRequest $request, PhabricatorUser $user)
 {
     $totp_token_type = PhabricatorAuthTOTPKeyTemporaryTokenType::TOKENTYPE;
     $key = $request->getStr('totpkey');
     if (strlen($key)) {
         // If the user is providing a key, make sure it's a key we generated.
         // This raises the barrier to theoretical attacks where an attacker might
         // provide a known key (such attacks are already prevented by CSRF, but
         // this is a second barrier to overcome).
         // (We store and verify the hash of the key, not the key itself, to limit
         // how useful the data in the table is to an attacker.)
         $temporary_token = id(new PhabricatorAuthTemporaryTokenQuery())->setViewer($user)->withTokenResources(array($user->getPHID()))->withTokenTypes(array($totp_token_type))->withExpired(false)->withTokenCodes(array(PhabricatorHash::digest($key)))->executeOne();
         if (!$temporary_token) {
             // If we don't have a matching token, regenerate the key below.
             $key = null;
         }
     }
     if (!strlen($key)) {
         $key = self::generateNewTOTPKey();
         // Mark this key as one we generated, so the user is allowed to submit
         // a response for it.
         $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
         id(new PhabricatorAuthTemporaryToken())->setTokenResource($user->getPHID())->setTokenType($totp_token_type)->setTokenExpires(time() + phutil_units('1 hour in seconds'))->setTokenCode(PhabricatorHash::digest($key))->save();
         unset($unguarded);
     }
     $code = $request->getStr('totpcode');
     $e_code = true;
     if ($request->getExists('totp')) {
         $okay = self::verifyTOTPCode($user, new PhutilOpaqueEnvelope($key), $code);
         if ($okay) {
             $config = $this->newConfigForUser($user)->setFactorName(pht('Mobile App (TOTP)'))->setFactorSecret($key);
             return $config;
         } else {
             if (!strlen($code)) {
                 $e_code = pht('Required');
             } else {
                 $e_code = pht('Invalid');
             }
         }
     }
     $form->addHiddenInput('totp', true);
     $form->addHiddenInput('totpkey', $key);
     $form->appendRemarkupInstructions(pht('First, download an authenticator application on your phone. Two ' . 'applications which work well are **Authy** and **Google ' . 'Authenticator**, but any other TOTP application should also work.'));
     $form->appendInstructions(pht('Launch the application on your phone, and add a new entry for ' . 'this Phabricator install. When prompted, scan the QR code or ' . 'manually enter the key shown below into the application.'));
     $prod_uri = new PhutilURI(PhabricatorEnv::getProductionURI('/'));
     $issuer = $prod_uri->getDomain();
     $uri = urisprintf('otpauth://totp/%s:%s?secret=%s&issuer=%s', $issuer, $user->getUsername(), $key, $issuer);
     $qrcode = $this->renderQRCode($uri);
     $form->appendChild($qrcode);
     $form->appendChild(id(new AphrontFormStaticControl())->setLabel(pht('Key'))->setValue(phutil_tag('strong', array(), $key)));
     $form->appendInstructions(pht('(If given an option, select that this key is "Time Based", not ' . '"Counter Based".)'));
     $form->appendInstructions(pht('After entering the key, the application should display a numeric ' . 'code. Enter that code below to confirm that you have configured ' . 'the authenticator correctly:'));
     $form->appendChild(id(new PHUIFormNumberControl())->setLabel(pht('TOTP Code'))->setName('totpcode')->setValue($code)->setError($e_code));
 }
 private function prepareAuthForm(AphrontFormView $form)
 {
     $provider = $this->provider;
     $auth_uri = $provider->getAuthURI();
     $client_id = $provider->getClientID();
     $redirect_uri = $provider->getRedirectURI();
     $minimum_scope = $provider->getMinimumScope();
     $form->setAction($auth_uri)->setMethod('GET')->addHiddenInput('redirect_uri', $redirect_uri)->addHiddenInput('client_id', $client_id)->addHiddenInput('scope', $minimum_scope);
     foreach ($provider->getExtraAuthParameters() as $key => $value) {
         $form->addHiddenInput($key, $value);
     }
     return $form;
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $this->getViewer();
     $id = $request->getURIData('id');
     if (!$id) {
         $id = $request->getInt('revisionID');
     }
     if ($id) {
         $revision = id(new DifferentialRevisionQuery())->setViewer($viewer)->withIDs(array($id))->needRelationships(true)->needReviewerStatus(true)->needActiveDiffs(true)->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT))->executeOne();
         if (!$revision) {
             return new Aphront404Response();
         }
     } else {
         $revision = DifferentialRevision::initializeNewRevision($viewer);
         $revision->attachReviewerStatus(array());
     }
     $diff_id = $request->getInt('diffID');
     if ($diff_id) {
         $diff = id(new DifferentialDiffQuery())->setViewer($viewer)->withIDs(array($diff_id))->executeOne();
         if (!$diff) {
             return new Aphront404Response();
         }
         if ($diff->getRevisionID()) {
             // TODO: Redirect?
             throw new Exception(pht('This diff is already attached to a revision!'));
         }
     } else {
         $diff = null;
     }
     if (!$diff) {
         if (!$revision->getID()) {
             throw new Exception(pht('You can not create a new revision without a diff!'));
         }
     } else {
         // TODO: It would be nice to show the diff being attached in the UI.
     }
     $field_list = PhabricatorCustomField::getObjectFields($revision, PhabricatorCustomField::ROLE_EDIT);
     $field_list->setViewer($viewer)->readFieldsFromStorage($revision);
     if ($request->getStr('viaDiffView') && $diff) {
         $repo_key = id(new DifferentialRepositoryField())->getFieldKey();
         $repository_field = idx($field_list->getFields(), $repo_key);
         if ($repository_field) {
             $repository_field->setValue($request->getStr($repo_key));
         }
         $view_policy_key = id(new DifferentialViewPolicyField())->getFieldKey();
         $view_policy_field = idx($field_list->getFields(), $view_policy_key);
         if ($view_policy_field) {
             $view_policy_field->setValue($diff->getViewPolicy());
         }
     }
     $validation_exception = null;
     if ($request->isFormPost() && !$request->getStr('viaDiffView')) {
         $editor = id(new DifferentialTransactionEditor())->setActor($viewer)->setContentSourceFromRequest($request)->setContinueOnNoEffect(true);
         $xactions = $field_list->buildFieldTransactionsFromRequest(new DifferentialTransaction(), $request);
         if ($diff) {
             $repository_phid = null;
             $repository_tokenizer = $request->getArr(id(new DifferentialRepositoryField())->getFieldKey());
             if ($repository_tokenizer) {
                 $repository_phid = reset($repository_tokenizer);
             }
             $xactions[] = id(new DifferentialTransaction())->setTransactionType(DifferentialTransaction::TYPE_UPDATE)->setNewValue($diff->getPHID());
             $editor->setRepositoryPHIDOverride($repository_phid);
         }
         $comments = $request->getStr('comments');
         if (strlen($comments)) {
             $xactions[] = id(new DifferentialTransaction())->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)->attachComment(id(new DifferentialTransactionComment())->setContent($comments));
         }
         try {
             $editor->applyTransactions($revision, $xactions);
             $revision_uri = '/D' . $revision->getID();
             return id(new AphrontRedirectResponse())->setURI($revision_uri);
         } catch (PhabricatorApplicationTransactionValidationException $ex) {
             $validation_exception = $ex;
         }
     }
     $form = new AphrontFormView();
     $form->setUser($request->getUser());
     if ($diff) {
         $form->addHiddenInput('diffID', $diff->getID());
     }
     if ($revision->getID()) {
         $form->setAction('/differential/revision/edit/' . $revision->getID() . '/');
     } else {
         $form->setAction('/differential/revision/edit/');
     }
     if ($diff && $revision->getID()) {
         $form->appendChild(id(new AphrontFormTextAreaControl())->setLabel(pht('Comments'))->setName('comments')->setCaption(pht("Explain what's new in this diff."))->setValue($request->getStr('comments')))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Save')))->appendChild(id(new AphrontFormDividerControl()));
     }
     $field_list->appendFieldsToForm($form);
     $submit = id(new AphrontFormSubmitControl())->setValue('Save');
     if ($diff) {
         $submit->addCancelButton('/differential/diff/' . $diff->getID() . '/');
     } else {
         $submit->addCancelButton('/D' . $revision->getID());
     }
     $form->appendChild($submit);
     $crumbs = $this->buildApplicationCrumbs();
     if ($revision->getID()) {
         if ($diff) {
             $header_icon = 'fa-upload';
             $title = pht('Update Revision');
             $crumbs->addTextCrumb('D' . $revision->getID(), '/differential/diff/' . $diff->getID() . '/');
         } else {
             $header_icon = 'fa-pencil';
             $title = pht('Edit Revision: %s', $revision->getTitle());
             $crumbs->addTextCrumb('D' . $revision->getID(), '/D' . $revision->getID());
         }
     } else {
         $header_icon = 'fa-plus-square';
         $title = pht('Create New Differential Revision');
     }
     $form_box = id(new PHUIObjectBoxView())->setHeaderText('Revision')->setValidationException($validation_exception)->setBackground(PHUIObjectBoxView::BLUE_PROPERTY)->setForm($form);
     $crumbs->addTextCrumb($title);
     $crumbs->setBorder(true);
     $header = id(new PHUIHeaderView())->setHeader($title)->setHeaderIcon($header_icon);
     $view = id(new PHUITwoColumnView())->setHeader($header)->setFooter($form_box);
     return $this->newPage()->setTitle($title)->setCrumbs($crumbs)->appendChild($view);
 }
 public function processRequest()
 {
     $provider = $this->getOAuthProvider();
     $oauth_info = $this->getOAuthInfo();
     $request = $this->getRequest();
     $errors = array();
     $e_username = true;
     $e_email = true;
     $e_realname = true;
     $user = new PhabricatorUser();
     $user->setUsername($provider->retrieveUserAccountName());
     $user->setRealName($provider->retrieveUserRealName());
     $user->setEmail($provider->retrieveUserEmail());
     if ($request->isFormPost()) {
         $user->setUsername($request->getStr('username'));
         $username = $user->getUsername();
         if (!strlen($user->getUsername())) {
             $e_username = '******';
             $errors[] = 'Username is required.';
         } else {
             if (!PhabricatorUser::validateUsername($username)) {
                 $e_username = '******';
                 $errors[] = 'Username must consist of only numbers and letters.';
             } else {
                 $e_username = null;
             }
         }
         if ($user->getEmail() === null) {
             $user->setEmail($request->getStr('email'));
             if (!strlen($user->getEmail())) {
                 $e_email = 'Required';
                 $errors[] = 'Email is required.';
             } else {
                 $e_email = null;
             }
         }
         if (!strlen($user->getRealName())) {
             $user->setRealName($request->getStr('realname'));
             if (!strlen($user->getRealName())) {
                 $e_realname = 'Required';
                 $errors[] = 'Real name is required.';
             } else {
                 $e_realname = null;
             }
         }
         if (!$errors) {
             $image = $provider->retrieveUserProfileImage();
             if ($image) {
                 $file = PhabricatorFile::newFromFileData($image, array('name' => $provider->getProviderKey() . '-profile.jpg', 'authorPHID' => $user->getPHID()));
                 $user->setProfileImagePHID($file->getPHID());
             }
             try {
                 $user->save();
                 $oauth_info->setUserID($user->getID());
                 $oauth_info->save();
                 $session_key = $user->establishSession('web');
                 $request->setCookie('phusr', $user->getUsername());
                 $request->setCookie('phsid', $session_key);
                 return id(new AphrontRedirectResponse())->setURI('/');
             } catch (AphrontQueryDuplicateKeyException $exception) {
                 $same_username = id(new PhabricatorUser())->loadOneWhere('userName = %s', $user->getUserName());
                 $same_email = id(new PhabricatorUser())->loadOneWhere('email = %s', $user->getEmail());
                 if ($same_username) {
                     $e_username = '******';
                     $errors[] = 'That username or email is not unique.';
                 } else {
                     if ($same_email) {
                         $e_email = 'Duplicate';
                         $errors[] = 'That email is not unique.';
                     } else {
                         throw $exception;
                     }
                 }
             }
         }
     }
     $error_view = null;
     if ($errors) {
         $error_view = new AphrontErrorView();
         $error_view->setTitle('Registration Failed');
         $error_view->setErrors($errors);
     }
     // Strip the URI down to the path, because otherwise we'll trigger
     // external CSRF protection (by having a protocol in the form "action")
     // and generate a form with no CSRF token.
     $action_uri = new PhutilURI($provider->getRedirectURI());
     $action_path = $action_uri->getPath();
     $form = new AphrontFormView();
     $form->addHiddenInput('token', $provider->getAccessToken())->addHiddenInput('expires', $oauth_info->getTokenExpires())->addHiddenInput('state', $this->getOAuthState())->setUser($request->getUser())->setAction($action_path)->appendChild(id(new AphrontFormTextControl())->setLabel('Username')->setName('username')->setValue($user->getUsername())->setError($e_username));
     if ($provider->retrieveUserEmail() === null) {
         $form->appendChild(id(new AphrontFormTextControl())->setLabel('Email')->setName('email')->setValue($request->getStr('email'))->setError($e_email));
     }
     if ($provider->retrieveUserRealName() === null) {
         $form->appendChild(id(new AphrontFormTextControl())->setLabel('Real Name')->setName('realname')->setValue($request->getStr('realname'))->setError($e_realname));
     }
     $form->appendChild(id(new AphrontFormSubmitControl())->setValue('Create Account'));
     $panel = new AphrontPanelView();
     $panel->setHeader('Create New Account');
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     $panel->appendChild($form);
     return $this->buildStandardPageResponse(array($error_view, $panel), array('title' => 'Create New Account'));
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     if (!$this->id) {
         $this->id = $request->getInt('revisionID');
     }
     if ($this->id) {
         $revision = id(new DifferentialRevision())->load($this->id);
         if (!$revision) {
             return new Aphront404Response();
         }
     } else {
         $revision = new DifferentialRevision();
     }
     $revision->loadRelationships();
     $aux_fields = $this->loadAuxiliaryFields($revision);
     $diff_id = $request->getInt('diffID');
     if ($diff_id) {
         $diff = id(new DifferentialDiff())->load($diff_id);
         if (!$diff) {
             return new Aphront404Response();
         }
         if ($diff->getRevisionID()) {
             // TODO: Redirect?
             throw new Exception("This diff is already attached to a revision!");
         }
     } else {
         $diff = null;
     }
     $errors = array();
     if ($request->isFormPost() && !$request->getStr('viaDiffView')) {
         $user_phid = $request->getUser()->getPHID();
         foreach ($aux_fields as $aux_field) {
             $aux_field->setValueFromRequest($request);
             try {
                 $aux_field->validateField();
             } catch (DifferentialFieldValidationException $ex) {
                 $errors[] = $ex->getMessage();
             }
         }
         if (!$errors) {
             $editor = new DifferentialRevisionEditor($revision, $user_phid);
             if ($diff) {
                 $editor->addDiff($diff, $request->getStr('comments'));
             }
             $editor->setAuxiliaryFields($aux_fields);
             $editor->save();
             return id(new AphrontRedirectResponse())->setURI('/D' . $revision->getID());
         }
     }
     $aux_phids = array();
     foreach ($aux_fields as $key => $aux_field) {
         $aux_phids[$key] = $aux_field->getRequiredHandlePHIDsForRevisionEdit();
     }
     $phids = array_mergev($aux_phids);
     $phids = array_unique($phids);
     $handles = id(new PhabricatorObjectHandleData($phids))->loadHandles();
     foreach ($aux_fields as $key => $aux_field) {
         $aux_field->setHandles(array_select_keys($handles, $aux_phids[$key]));
     }
     $form = new AphrontFormView();
     $form->setUser($request->getUser());
     if ($diff) {
         $form->addHiddenInput('diffID', $diff->getID());
     }
     if ($revision->getID()) {
         $form->setAction('/differential/revision/edit/' . $revision->getID() . '/');
     } else {
         $form->setAction('/differential/revision/edit/');
     }
     $error_view = null;
     if ($errors) {
         $error_view = id(new AphrontErrorView())->setTitle('Form Errors')->setErrors($errors);
     }
     if ($diff && $revision->getID()) {
         $form->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Comments')->setName('comments')->setCaption("Explain what's new in this diff.")->setValue($request->getStr('comments')))->appendChild(id(new AphrontFormSubmitControl())->setValue('Save'))->appendChild(id(new AphrontFormDividerControl()));
     }
     foreach ($aux_fields as $aux_field) {
         $control = $aux_field->renderEditControl();
         if ($control) {
             $form->appendChild($control);
         }
     }
     $submit = id(new AphrontFormSubmitControl())->setValue('Save');
     if ($diff) {
         $submit->addCancelButton('/differential/diff/' . $diff->getID() . '/');
     } else {
         $submit->addCancelButton('/D' . $revision->getID());
     }
     $form->appendChild($submit);
     $panel = new AphrontPanelView();
     if ($revision->getID()) {
         if ($diff) {
             $panel->setHeader('Update Differential Revision');
         } else {
             $panel->setHeader('Edit Differential Revision');
         }
     } else {
         $panel->setHeader('Create New Differential Revision');
     }
     $panel->appendChild($form);
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     return $this->buildStandardPageResponse(array($error_view, $panel), array('title' => 'Edit Differential Revision'));
 }
 public function processRequest()
 {
     $this->requireApplicationCapability(PhabricatorMacroManageCapability::CAPABILITY);
     $request = $this->getRequest();
     $user = $request->getUser();
     if ($this->id) {
         $macro = id(new PhabricatorMacroQuery())->setViewer($user)->withIDs(array($this->id))->needFiles(true)->executeOne();
         if (!$macro) {
             return new Aphront404Response();
         }
     } else {
         $macro = new PhabricatorFileImageMacro();
         $macro->setAuthorPHID($user->getPHID());
     }
     $errors = array();
     $e_name = true;
     $e_file = null;
     $file = null;
     $can_fetch = PhabricatorEnv::getEnvConfig('security.allow-outbound-http');
     if ($request->isFormPost()) {
         $original = clone $macro;
         $new_name = null;
         if ($request->getBool('name_form') || !$macro->getID()) {
             $new_name = $request->getStr('name');
             $macro->setName($new_name);
             if (!strlen($macro->getName())) {
                 $errors[] = pht('Macro name is required.');
                 $e_name = pht('Required');
             } else {
                 if (!preg_match('/^[a-z0-9:_-]{3,}\\z/', $macro->getName())) {
                     $errors[] = pht('Macro must be at least three characters long and contain only ' . 'lowercase letters, digits, hyphens, colons and underscores.');
                     $e_name = pht('Invalid');
                 } else {
                     $e_name = null;
                 }
             }
         }
         $file = null;
         if ($request->getFileExists('file')) {
             $file = PhabricatorFile::newFromPHPUpload($_FILES['file'], array('name' => $request->getStr('name'), 'authorPHID' => $user->getPHID(), 'isExplicitUpload' => true, 'canCDN' => true));
         } else {
             if ($request->getStr('url')) {
                 try {
                     $file = PhabricatorFile::newFromFileDownload($request->getStr('url'), array('name' => $request->getStr('name'), 'authorPHID' => $user->getPHID(), 'isExplicitUpload' => true, 'canCDN' => true));
                 } catch (Exception $ex) {
                     $errors[] = pht('Could not fetch URL: %s', $ex->getMessage());
                 }
             } else {
                 if ($request->getStr('phid')) {
                     $file = id(new PhabricatorFileQuery())->setViewer($user)->withPHIDs(array($request->getStr('phid')))->executeOne();
                 }
             }
         }
         if ($file) {
             if (!$file->isViewableInBrowser()) {
                 $errors[] = pht('You must upload an image.');
                 $e_file = pht('Invalid');
             } else {
                 $macro->setFilePHID($file->getPHID());
                 $macro->attachFile($file);
                 $e_file = null;
             }
         }
         if (!$macro->getID() && !$file) {
             $errors[] = pht('You must upload an image to create a macro.');
             $e_file = pht('Required');
         }
         if (!$errors) {
             try {
                 $xactions = array();
                 if ($new_name !== null) {
                     $xactions[] = id(new PhabricatorMacroTransaction())->setTransactionType(PhabricatorMacroTransactionType::TYPE_NAME)->setNewValue($new_name);
                 }
                 if ($file) {
                     $xactions[] = id(new PhabricatorMacroTransaction())->setTransactionType(PhabricatorMacroTransactionType::TYPE_FILE)->setNewValue($file->getPHID());
                 }
                 $editor = id(new PhabricatorMacroEditor())->setActor($user)->setContinueOnNoEffect(true)->setContentSourceFromRequest($request);
                 $xactions = $editor->applyTransactions($original, $xactions);
                 $view_uri = $this->getApplicationURI('/view/' . $original->getID() . '/');
                 return id(new AphrontRedirectResponse())->setURI($view_uri);
             } catch (AphrontDuplicateKeyQueryException $ex) {
                 throw $ex;
                 $errors[] = pht('Macro name is not unique!');
                 $e_name = pht('Duplicate');
             }
         }
     }
     $current_file = null;
     if ($macro->getFilePHID()) {
         $current_file = $macro->getFile();
     }
     $form = new AphrontFormView();
     $form->addHiddenInput('name_form', 1);
     $form->setUser($request->getUser());
     $form->setEncType('multipart/form-data')->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Name'))->setName('name')->setValue($macro->getName())->setCaption(pht('This word or phrase will be replaced with the image.'))->setError($e_name));
     if (!$macro->getID()) {
         if ($current_file) {
             $current_file_view = id(new PhabricatorFileLinkView())->setFilePHID($current_file->getPHID())->setFileName($current_file->getName())->setFileViewable(true)->setFileViewURI($current_file->getBestURI())->render();
             $form->addHiddenInput('phid', $current_file->getPHID());
             $form->appendChild(id(new AphrontFormMarkupControl())->setLabel(pht('Selected File'))->setValue($current_file_view));
             $other_label = pht('Change File');
         } else {
             $other_label = pht('File');
         }
         if ($can_fetch) {
             $form->appendChild(id(new AphrontFormTextControl())->setLabel(pht('URL'))->setName('url')->setValue($request->getStr('url'))->setError($request->getFileExists('file') ? false : $e_file));
         }
         $form->appendChild(id(new AphrontFormFileControl())->setLabel($other_label)->setName('file')->setError($request->getStr('url') ? false : $e_file));
     }
     $view_uri = $this->getApplicationURI('/view/' . $macro->getID() . '/');
     if ($macro->getID()) {
         $cancel_uri = $view_uri;
     } else {
         $cancel_uri = $this->getApplicationURI();
     }
     $form->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Save Image Macro'))->addCancelButton($cancel_uri));
     $crumbs = $this->buildApplicationCrumbs();
     if ($macro->getID()) {
         $title = pht('Edit Image Macro');
         $crumb = pht('Edit Macro');
         $crumbs->addTextCrumb(pht('Macro "%s"', $macro->getName()), $view_uri);
     } else {
         $title = pht('Create Image Macro');
         $crumb = pht('Create Macro');
     }
     $crumbs->addTextCrumb($crumb, $request->getRequestURI());
     $upload = null;
     if ($macro->getID()) {
         $upload_form = id(new AphrontFormView())->setEncType('multipart/form-data')->setUser($request->getUser());
         if ($can_fetch) {
             $upload_form->appendChild(id(new AphrontFormTextControl())->setLabel(pht('URL'))->setName('url')->setValue($request->getStr('url')));
         }
         $upload_form->appendChild(id(new AphrontFormFileControl())->setLabel(pht('File'))->setName('file'))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Upload File')));
         $upload = id(new PHUIObjectBoxView())->setHeaderText(pht('Upload New File'))->setForm($upload_form);
     }
     $form_box = id(new PHUIObjectBoxView())->setHeaderText($title)->setFormErrors($errors)->setForm($form);
     return $this->buildApplicationPage(array($crumbs, $form_box, $upload), array('title' => $title));
 }
 public function handleRequest(AphrontRequest $request)
 {
     $viewer = $request->getViewer();
     $id = $request->getURIData('id');
     $this->requireApplicationCapability(PhabricatorMacroManageCapability::CAPABILITY);
     if ($id) {
         $macro = id(new PhabricatorMacroQuery())->setViewer($viewer)->withIDs(array($id))->needFiles(true)->executeOne();
         if (!$macro) {
             return new Aphront404Response();
         }
     } else {
         $macro = new PhabricatorFileImageMacro();
         $macro->setAuthorPHID($viewer->getPHID());
     }
     $errors = array();
     $e_name = true;
     $e_file = null;
     $file = null;
     if ($request->isFormPost()) {
         $original = clone $macro;
         $new_name = null;
         if ($request->getBool('name_form') || !$macro->getID()) {
             $new_name = $request->getStr('name');
             $macro->setName($new_name);
             if (!strlen($macro->getName())) {
                 $errors[] = pht('Macro name is required.');
                 $e_name = pht('Required');
             } else {
                 if (!preg_match('/^[a-z0-9:_-]{3,}\\z/', $macro->getName())) {
                     $errors[] = pht('Macro must be at least three characters long and contain only ' . 'lowercase letters, digits, hyphens, colons and underscores.');
                     $e_name = pht('Invalid');
                 } else {
                     $e_name = null;
                 }
             }
         }
         $uri = $request->getStr('url');
         $engine = new PhabricatorDestructionEngine();
         $file = null;
         if ($request->getFileExists('file')) {
             $file = PhabricatorFile::newFromPHPUpload($_FILES['file'], array('name' => $request->getStr('name'), 'authorPHID' => $viewer->getPHID(), 'isExplicitUpload' => true, 'canCDN' => true));
         } else {
             if ($uri) {
                 try {
                     // Rate limit outbound fetches to make this mechanism less useful for
                     // scanning networks and ports.
                     PhabricatorSystemActionEngine::willTakeAction(array($viewer->getPHID()), new PhabricatorFilesOutboundRequestAction(), 1);
                     $file = PhabricatorFile::newFromFileDownload($uri, array('name' => $request->getStr('name'), 'viewPolicy' => PhabricatorPolicies::POLICY_NOONE, 'isExplicitUpload' => true, 'canCDN' => true));
                     if (!$file->isViewableInBrowser()) {
                         $mime_type = $file->getMimeType();
                         $engine->destroyObject($file);
                         $file = null;
                         throw new Exception(pht('The URI "%s" does not correspond to a valid image file, got ' . 'a file with MIME type "%s". You must specify the URI of a ' . 'valid image file.', $uri, $mime_type));
                     } else {
                         $file->setAuthorPHID($viewer->getPHID())->save();
                     }
                 } catch (HTTPFutureHTTPResponseStatus $status) {
                     $errors[] = pht('The URI "%s" could not be loaded, got %s error.', $uri, $status->getStatusCode());
                 } catch (Exception $ex) {
                     $errors[] = $ex->getMessage();
                 }
             } else {
                 if ($request->getStr('phid')) {
                     $file = id(new PhabricatorFileQuery())->setViewer($viewer)->withPHIDs(array($request->getStr('phid')))->executeOne();
                 }
             }
         }
         if ($file) {
             if (!$file->isViewableInBrowser()) {
                 $errors[] = pht('You must upload an image.');
                 $e_file = pht('Invalid');
             } else {
                 $macro->setFilePHID($file->getPHID());
                 $macro->attachFile($file);
                 $e_file = null;
             }
         }
         if (!$macro->getID() && !$file) {
             $errors[] = pht('You must upload an image to create a macro.');
             $e_file = pht('Required');
         }
         if (!$errors) {
             try {
                 $xactions = array();
                 if ($new_name !== null) {
                     $xactions[] = id(new PhabricatorMacroTransaction())->setTransactionType(PhabricatorMacroTransaction::TYPE_NAME)->setNewValue($new_name);
                 }
                 if ($file) {
                     $xactions[] = id(new PhabricatorMacroTransaction())->setTransactionType(PhabricatorMacroTransaction::TYPE_FILE)->setNewValue($file->getPHID());
                 }
                 $editor = id(new PhabricatorMacroEditor())->setActor($viewer)->setContinueOnNoEffect(true)->setContentSourceFromRequest($request);
                 $xactions = $editor->applyTransactions($original, $xactions);
                 $view_uri = $this->getApplicationURI('/view/' . $original->getID() . '/');
                 return id(new AphrontRedirectResponse())->setURI($view_uri);
             } catch (AphrontDuplicateKeyQueryException $ex) {
                 throw $ex;
                 $errors[] = pht('Macro name is not unique!');
                 $e_name = pht('Duplicate');
             }
         }
     }
     $current_file = null;
     if ($macro->getFilePHID()) {
         $current_file = $macro->getFile();
     }
     $form = new AphrontFormView();
     $form->addHiddenInput('name_form', 1);
     $form->setUser($request->getUser());
     $form->setEncType('multipart/form-data')->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Name'))->setName('name')->setValue($macro->getName())->setCaption(pht('This word or phrase will be replaced with the image.'))->setError($e_name));
     if (!$macro->getID()) {
         if ($current_file) {
             $current_file_view = id(new PhabricatorFileLinkView())->setFilePHID($current_file->getPHID())->setFileName($current_file->getName())->setFileViewable(true)->setFileViewURI($current_file->getBestURI())->render();
             $form->addHiddenInput('phid', $current_file->getPHID());
             $form->appendChild(id(new AphrontFormMarkupControl())->setLabel(pht('Selected File'))->setValue($current_file_view));
             $other_label = pht('Change File');
         } else {
             $other_label = pht('File');
         }
         $form->appendChild(id(new AphrontFormTextControl())->setLabel(pht('URL'))->setName('url')->setValue($request->getStr('url'))->setError($request->getFileExists('file') ? false : $e_file));
         $form->appendChild(id(new AphrontFormFileControl())->setLabel($other_label)->setName('file')->setError($request->getStr('url') ? false : $e_file));
     }
     $view_uri = $this->getApplicationURI('/view/' . $macro->getID() . '/');
     if ($macro->getID()) {
         $cancel_uri = $view_uri;
     } else {
         $cancel_uri = $this->getApplicationURI();
     }
     $form->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Save Image Macro'))->addCancelButton($cancel_uri));
     $crumbs = $this->buildApplicationCrumbs();
     if ($macro->getID()) {
         $title = pht('Edit Image Macro');
         $crumb = pht('Edit Macro');
         $crumbs->addTextCrumb(pht('Macro "%s"', $macro->getName()), $view_uri);
     } else {
         $title = pht('Create Image Macro');
         $crumb = pht('Create Macro');
     }
     $crumbs->addTextCrumb($crumb, $request->getRequestURI());
     $upload = null;
     if ($macro->getID()) {
         $upload_form = id(new AphrontFormView())->setEncType('multipart/form-data')->setUser($request->getUser());
         $upload_form->appendChild(id(new AphrontFormTextControl())->setLabel(pht('URL'))->setName('url')->setValue($request->getStr('url')));
         $upload_form->appendChild(id(new AphrontFormFileControl())->setLabel(pht('File'))->setName('file'))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Upload File')));
         $upload = id(new PHUIObjectBoxView())->setHeaderText(pht('Upload New File'))->setForm($upload_form);
     }
     $form_box = id(new PHUIObjectBoxView())->setHeaderText($title)->setFormErrors($errors)->setForm($form);
     return $this->buildApplicationPage(array($crumbs, $form_box, $upload), array('title' => $title));
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     if ($request->getUser()->getPHID()) {
         // Kick the user out if they're already logged in.
         return id(new AphrontRedirectResponse())->setURI('/');
     }
     $next_uri = $this->getRequest()->getPath();
     $request->setCookie('next_uri', $next_uri);
     if ($next_uri == '/login/' && !$request->isFormPost()) {
         // The user went straight to /login/, so presumably they want to go
         // to the dashboard upon logging in. Because, you know, that's logical.
         // And people are logical. Sometimes... Fine, no they're not.
         // We check for POST here because getPath() would get reset to /login/.
         $request->setCookie('next_uri', '/');
     }
     // Always use $request->getCookie('next_uri', '/') after the above.
     $password_auth = PhabricatorEnv::getEnvConfig('auth.password-auth-enabled');
     $forms = array();
     $error_view = null;
     if ($password_auth) {
         $error = false;
         $username_or_email = $request->getCookie('phusr');
         if ($request->isFormPost()) {
             $username_or_email = $request->getStr('username_or_email');
             $user = id(new PhabricatorUser())->loadOneWhere('username = %s', $username_or_email);
             if (!$user) {
                 $user = id(new PhabricatorUser())->loadOneWhere('email = %s', $username_or_email);
             }
             $okay = false;
             if ($user) {
                 if ($user->comparePassword($request->getStr('password'))) {
                     $session_key = $user->establishSession('web');
                     $request->setCookie('phusr', $user->getUsername());
                     $request->setCookie('phsid', $session_key);
                     return id(new AphrontRedirectResponse())->setURI($request->getCookie('next_uri', '/'));
                 } else {
                     $log = PhabricatorUserLog::newLog(null, $user, PhabricatorUserLog::ACTION_LOGIN_FAILURE);
                     $log->save();
                 }
             }
             if (!$okay) {
                 $request->clearCookie('phusr');
                 $request->clearCookie('phsid');
             }
             $error = true;
         }
         if ($error) {
             $error_view = new AphrontErrorView();
             $error_view->setTitle('Bad username/password.');
         }
         $form = new AphrontFormView();
         $form->setUser($request->getUser())->setAction('/login/')->appendChild(id(new AphrontFormTextControl())->setLabel('Username/Email')->setName('username_or_email')->setValue($username_or_email))->appendChild(id(new AphrontFormPasswordControl())->setLabel('Password')->setName('password')->setCaption('<a href="/login/email/">' . 'Forgot your password? / Email Login</a>'))->appendChild(id(new AphrontFormSubmitControl())->setValue('Login'));
         //    $panel->setCreateButton('Register New Account', '/login/register/');
         $forms['Phabricator Login'] = $form;
     }
     $providers = PhabricatorOAuthProvider::getAllProviders();
     foreach ($providers as $provider) {
         $enabled = $provider->isProviderEnabled();
         if (!$enabled) {
             continue;
         }
         $auth_uri = $provider->getAuthURI();
         $redirect_uri = $provider->getRedirectURI();
         $client_id = $provider->getClientID();
         $provider_name = $provider->getProviderName();
         $minimum_scope = $provider->getMinimumScope();
         $extra_auth = $provider->getExtraAuthParameters();
         // TODO: In theory we should use 'state' to prevent CSRF, but the total
         // effect of the CSRF attack is that an attacker can cause a user to login
         // to Phabricator if they're already logged into some OAuth provider. This
         // does not seem like the most severe threat in the world, and generating
         // CSRF for logged-out users is vaugely tricky.
         if ($provider->isProviderRegistrationEnabled()) {
             $title = "Login or Register with {$provider_name}";
             $body = "Login or register for Phabricator using your " . "{$provider_name} account.";
             $button = "Login or Register with {$provider_name}";
         } else {
             $title = "Login with {$provider_name}";
             $body = "Login to your existing Phabricator account using your " . "{$provider_name} account.<br /><br /><strong>You can not use " . "{$provider_name} to register a new account.</strong>";
             $button = "Login with {$provider_name}";
         }
         $auth_form = new AphrontFormView();
         $auth_form->setAction($auth_uri)->addHiddenInput('client_id', $client_id)->addHiddenInput('redirect_uri', $redirect_uri)->addHiddenInput('scope', $minimum_scope);
         foreach ($extra_auth as $key => $value) {
             $auth_form->addHiddenInput($key, $value);
         }
         $auth_form->setUser($request->getUser())->setMethod('GET')->appendChild('<p class="aphront-form-instructions">' . $body . '</p>')->appendChild(id(new AphrontFormSubmitControl())->setValue("{$button} »"));
         $forms[$title] = $auth_form;
     }
     $panel = new AphrontPanelView();
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     foreach ($forms as $name => $form) {
         $panel->appendChild('<h1>' . $name . '</h1>');
         $panel->appendChild($form);
         $panel->appendChild('<br />');
     }
     return $this->buildStandardPageResponse(array($error_view, $panel), array('title' => 'Login'));
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $user = $request->getUser();
     $files = array();
     $parent_task = null;
     $template_id = null;
     if ($this->id) {
         $task = id(new ManiphestTask())->load($this->id);
         if (!$task) {
             return new Aphront404Response();
         }
     } else {
         $task = new ManiphestTask();
         $task->setPriority(ManiphestTaskPriority::PRIORITY_TRIAGE);
         $task->setAuthorPHID($user->getPHID());
         // These allow task creation with defaults.
         if (!$request->isFormPost()) {
             $task->setTitle($request->getStr('title'));
             $default_projects = $request->getStr('projects');
             if ($default_projects) {
                 $task->setProjectPHIDs(explode(';', $default_projects));
             }
         }
         $file_phids = $request->getArr('files', array());
         if (!$file_phids) {
             // Allow a single 'file' key instead, mostly since Mac OS X urlencodes
             // square brackets in URLs when passed to 'open', so you can't 'open'
             // a URL like '?files[]=xyz' and have PHP interpret it correctly.
             $phid = $request->getStr('file');
             if ($phid) {
                 $file_phids = array($phid);
             }
         }
         if ($file_phids) {
             $files = id(new PhabricatorFile())->loadAllWhere('phid IN (%Ls)', $file_phids);
         }
         $template_id = $request->getInt('template');
         // You can only have a parent task if you're creating a new task.
         $parent_id = $request->getInt('parent');
         if ($parent_id) {
             $parent_task = id(new ManiphestTask())->load($parent_id);
         }
     }
     $errors = array();
     $e_title = true;
     $extensions = ManiphestTaskExtensions::newExtensions();
     $aux_fields = $extensions->getAuxiliaryFieldSpecifications();
     if ($request->isFormPost()) {
         $changes = array();
         $new_title = $request->getStr('title');
         $new_desc = $request->getStr('description');
         $new_status = $request->getStr('status');
         $workflow = '';
         if ($task->getID()) {
             if ($new_title != $task->getTitle()) {
                 $changes[ManiphestTransactionType::TYPE_TITLE] = $new_title;
             }
             if ($new_desc != $task->getDescription()) {
                 $changes[ManiphestTransactionType::TYPE_DESCRIPTION] = $new_desc;
             }
             if ($new_status != $task->getStatus()) {
                 $changes[ManiphestTransactionType::TYPE_STATUS] = $new_status;
             }
         } else {
             $task->setTitle($new_title);
             $task->setDescription($new_desc);
             $changes[ManiphestTransactionType::TYPE_STATUS] = ManiphestTaskStatus::STATUS_OPEN;
             $workflow = 'create';
         }
         $owner_tokenizer = $request->getArr('assigned_to');
         $owner_phid = reset($owner_tokenizer);
         if (!strlen($new_title)) {
             $e_title = 'Required';
             $errors[] = 'Title is required.';
         }
         foreach ($aux_fields as $aux_field) {
             $aux_field->setValueFromRequest($request);
             if ($aux_field->isRequired() && !strlen($aux_field->getValue())) {
                 $errors[] = $aux_field->getLabel() . ' is required.';
                 $aux_field->setError('Required');
             }
             if (strlen($aux_field->getValue())) {
                 try {
                     $aux_field->validate();
                 } catch (Exception $e) {
                     $errors[] = $e->getMessage();
                     $aux_field->setError('Invalid');
                 }
             }
         }
         if ($errors) {
             $task->setPriority($request->getInt('priority'));
             $task->setOwnerPHID($owner_phid);
             $task->setCCPHIDs($request->getArr('cc'));
             $task->setProjectPHIDs($request->getArr('projects'));
         } else {
             if ($request->getInt('priority') != $task->getPriority()) {
                 $changes[ManiphestTransactionType::TYPE_PRIORITY] = $request->getInt('priority');
             }
             if ($owner_phid != $task->getOwnerPHID()) {
                 $changes[ManiphestTransactionType::TYPE_OWNER] = $owner_phid;
             }
             if ($request->getArr('cc') != $task->getCCPHIDs()) {
                 $changes[ManiphestTransactionType::TYPE_CCS] = $request->getArr('cc');
             }
             $new_proj_arr = $request->getArr('projects');
             $new_proj_arr = array_values($new_proj_arr);
             sort($new_proj_arr);
             $cur_proj_arr = $task->getProjectPHIDs();
             $cur_proj_arr = array_values($cur_proj_arr);
             sort($cur_proj_arr);
             if ($new_proj_arr != $cur_proj_arr) {
                 $changes[ManiphestTransactionType::TYPE_PROJECTS] = $new_proj_arr;
             }
             if ($files) {
                 $file_map = mpull($files, 'getPHID');
                 $file_map = array_fill_keys($file_map, array());
                 $changes[ManiphestTransactionType::TYPE_ATTACH] = array(PhabricatorPHIDConstants::PHID_TYPE_FILE => $file_map);
             }
             $content_source = PhabricatorContentSource::newForSource(PhabricatorContentSource::SOURCE_WEB, array('ip' => $request->getRemoteAddr()));
             $template = new ManiphestTransaction();
             $template->setAuthorPHID($user->getPHID());
             $template->setContentSource($content_source);
             $transactions = array();
             foreach ($changes as $type => $value) {
                 $transaction = clone $template;
                 $transaction->setTransactionType($type);
                 $transaction->setNewValue($value);
                 $transactions[] = $transaction;
             }
             if ($aux_fields) {
                 $task->loadAndAttachAuxiliaryAttributes();
                 foreach ($aux_fields as $aux_field) {
                     $transaction = clone $template;
                     $transaction->setTransactionType(ManiphestTransactionType::TYPE_AUXILIARY);
                     $aux_key = $aux_field->getAuxiliaryKey();
                     $transaction->setMetadataValue('aux:key', $aux_key);
                     $transaction->setNewValue($aux_field->getValueForStorage());
                     $transactions[] = $transaction;
                 }
             }
             if ($transactions) {
                 $is_new = !$task->getID();
                 $event = new PhabricatorEvent(PhabricatorEventType::TYPE_MANIPHEST_WILLEDITTASK, array('task' => $task, 'new' => $is_new, 'transactions' => $transactions));
                 $event->setUser($user);
                 $event->setAphrontRequest($request);
                 PhutilEventEngine::dispatchEvent($event);
                 $task = $event->getValue('task');
                 $transactions = $event->getValue('transactions');
                 $editor = new ManiphestTransactionEditor();
                 $editor->setAuxiliaryFields($aux_fields);
                 $editor->applyTransactions($task, $transactions);
                 $event = new PhabricatorEvent(PhabricatorEventType::TYPE_MANIPHEST_DIDEDITTASK, array('task' => $task, 'new' => $is_new, 'transactions' => $transactions));
                 $event->setUser($user);
                 $event->setAphrontRequest($request);
                 PhutilEventEngine::dispatchEvent($event);
             }
             if ($parent_task) {
                 $type_task = PhabricatorPHIDConstants::PHID_TYPE_TASK;
                 // NOTE: It's safe to simply apply this transaction without doing
                 // cycle detection because we know the new task has no children.
                 $new_value = $parent_task->getAttached();
                 $new_value[$type_task][$task->getPHID()] = array();
                 $parent_xaction = clone $template;
                 $attach_type = ManiphestTransactionType::TYPE_ATTACH;
                 $parent_xaction->setTransactionType($attach_type);
                 $parent_xaction->setNewValue($new_value);
                 $editor = new ManiphestTransactionEditor();
                 $editor->setAuxiliaryFields($aux_fields);
                 $editor->applyTransactions($parent_task, array($parent_xaction));
                 $workflow = $parent_task->getID();
             }
             $redirect_uri = '/T' . $task->getID();
             if ($workflow) {
                 $redirect_uri .= '?workflow=' . $workflow;
             }
             return id(new AphrontRedirectResponse())->setURI($redirect_uri);
         }
     } else {
         if (!$task->getID()) {
             $task->setCCPHIDs(array($user->getPHID()));
             if ($template_id) {
                 $template_task = id(new ManiphestTask())->load($template_id);
                 if ($template_task) {
                     $task->setCCPHIDs($template_task->getCCPHIDs());
                     $task->setProjectPHIDs($template_task->getProjectPHIDs());
                     $task->setOwnerPHID($template_task->getOwnerPHID());
                 }
             }
         }
     }
     $phids = array_merge(array($task->getOwnerPHID()), $task->getCCPHIDs(), $task->getProjectPHIDs());
     if ($parent_task) {
         $phids[] = $parent_task->getPHID();
     }
     $phids = array_filter($phids);
     $phids = array_unique($phids);
     $handles = id(new PhabricatorObjectHandleData($phids))->loadHandles($phids);
     $tvalues = mpull($handles, 'getFullName', 'getPHID');
     $error_view = null;
     if ($errors) {
         $error_view = new AphrontErrorView();
         $error_view->setErrors($errors);
         $error_view->setTitle('Form Errors');
     }
     $priority_map = ManiphestTaskPriority::getTaskPriorityMap();
     if ($task->getOwnerPHID()) {
         $assigned_value = array($task->getOwnerPHID() => $handles[$task->getOwnerPHID()]->getFullName());
     } else {
         $assigned_value = array();
     }
     if ($task->getCCPHIDs()) {
         $cc_value = array_select_keys($tvalues, $task->getCCPHIDs());
     } else {
         $cc_value = array();
     }
     if ($task->getProjectPHIDs()) {
         $projects_value = array_select_keys($tvalues, $task->getProjectPHIDs());
     } else {
         $projects_value = array();
     }
     $cancel_id = nonempty($task->getID(), $template_id);
     if ($cancel_id) {
         $cancel_uri = '/T' . $cancel_id;
     } else {
         $cancel_uri = '/maniphest/';
     }
     if ($task->getID()) {
         $button_name = 'Save Task';
         $header_name = 'Edit Task';
     } else {
         if ($parent_task) {
             $cancel_uri = '/T' . $parent_task->getID();
             $button_name = 'Create Task';
             $header_name = 'Create New Subtask';
         } else {
             $button_name = 'Create Task';
             $header_name = 'Create New Task';
         }
     }
     require_celerity_resource('maniphest-task-edit-css');
     $project_tokenizer_id = celerity_generate_unique_node_id();
     $form = new AphrontFormView();
     $form->setUser($user)->setAction($request->getRequestURI()->getPath())->addHiddenInput('template', $template_id);
     if ($parent_task) {
         $form->appendChild(id(new AphrontFormStaticControl())->setLabel('Parent Task')->setValue($handles[$parent_task->getPHID()]->getFullName()))->addHiddenInput('parent', $parent_task->getID());
     }
     $form->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Title')->setName('title')->setError($e_title)->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_SHORT)->setValue($task->getTitle()));
     if ($task->getID()) {
         // Only show this in "edit" mode, not "create" mode, since creating a
         // non-open task is kind of silly and it would just clutter up the
         // "create" interface.
         $form->appendChild(id(new AphrontFormSelectControl())->setLabel('Status')->setName('status')->setValue($task->getStatus())->setOptions(ManiphestTaskStatus::getTaskStatusMap()));
     }
     $form->appendChild(id(new AphrontFormTokenizerControl())->setLabel('Assigned To')->setName('assigned_to')->setValue($assigned_value)->setUser($user)->setDatasource('/typeahead/common/users/')->setLimit(1))->appendChild(id(new AphrontFormTokenizerControl())->setLabel('CC')->setName('cc')->setValue($cc_value)->setUser($user)->setDatasource('/typeahead/common/mailable/'))->appendChild(id(new AphrontFormSelectControl())->setLabel('Priority')->setName('priority')->setOptions($priority_map)->setValue($task->getPriority()))->appendChild(id(new AphrontFormTokenizerControl())->setLabel('Projects')->setName('projects')->setValue($projects_value)->setID($project_tokenizer_id)->setCaption(javelin_render_tag('a', array('href' => '/project/create/', 'mustcapture' => true, 'sigil' => 'project-create'), 'Create New Project'))->setDatasource('/typeahead/common/projects/'));
     if ($aux_fields) {
         if (!$request->isFormPost()) {
             $task->loadAndAttachAuxiliaryAttributes();
             foreach ($aux_fields as $aux_field) {
                 $aux_key = $aux_field->getAuxiliaryKey();
                 $value = $task->getAuxiliaryAttribute($aux_key);
                 $aux_field->setValueFromStorage($value);
             }
         }
         foreach ($aux_fields as $aux_field) {
             if ($aux_field->isRequired() && !$aux_field->getError() && !$aux_field->getValue()) {
                 $aux_field->setError(true);
             }
             $aux_control = $aux_field->renderControl();
             $form->appendChild($aux_control);
         }
     }
     require_celerity_resource('aphront-error-view-css');
     Javelin::initBehavior('maniphest-project-create', array('tokenizerID' => $project_tokenizer_id));
     if ($files) {
         $file_display = array();
         foreach ($files as $file) {
             $file_display[] = phutil_escape_html($file->getName());
         }
         $file_display = implode('<br />', $file_display);
         $form->appendChild(id(new AphrontFormMarkupControl())->setLabel('Files')->setValue($file_display));
         foreach ($files as $ii => $file) {
             $form->addHiddenInput('files[' . $ii . ']', $file->getPHID());
         }
     }
     $email_create = PhabricatorEnv::getEnvConfig('metamta.maniphest.public-create-email');
     $email_hint = null;
     if (!$task->getID() && $email_create) {
         $email_hint = 'You can also create tasks by sending an email to: ' . '<tt>' . phutil_escape_html($email_create) . '</tt>';
     }
     $panel_id = celerity_generate_unique_node_id();
     $form->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Description')->setName('description')->setID('description-textarea')->setCaption($email_hint)->setValue($task->getDescription()));
     if (!$task->getID()) {
         $form->appendChild(id(new AphrontFormDragAndDropUploadControl())->setLabel('Attached Files')->setName('files')->setDragAndDropTarget($panel_id)->setActivatedClass('aphront-panel-view-drag-and-drop'));
     }
     $form->appendChild(id(new AphrontFormSubmitControl())->addCancelButton($cancel_uri)->setValue($button_name));
     $panel = new AphrontPanelView();
     $panel->setWidth(AphrontPanelView::WIDTH_FULL);
     $panel->setHeader($header_name);
     $panel->setID($panel_id);
     $panel->appendChild($form);
     $description_preview_panel = '<div class="aphront-panel-preview aphront-panel-preview-full">
     <div class="maniphest-description-preview-header">
       Description Preview
     </div>
     <div id="description-preview">
       <div class="aphront-panel-preview-loading-text">
         Loading preview...
       </div>
     </div>
   </div>';
     Javelin::initBehavior('maniphest-description-preview', array('preview' => 'description-preview', 'textarea' => 'description-textarea', 'uri' => '/maniphest/task/descriptionpreview/'));
     return $this->buildStandardPageResponse(array($error_view, $panel, $description_preview_panel), array('title' => $header_name));
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     if (!$this->id) {
         $this->id = $request->getInt('revisionID');
     }
     if ($this->id) {
         $revision = id(new DifferentialRevision())->load($this->id);
         if (!$revision) {
             return new Aphront404Response();
         }
     } else {
         $revision = new DifferentialRevision();
     }
     $diff_id = $request->getInt('diffID');
     if ($diff_id) {
         $diff = id(new DifferentialDiff())->load($diff_id);
         if (!$diff) {
             return new Aphront404Response();
         }
         if ($diff->getRevisionID()) {
             // TODO: Redirect?
             throw new Exception("This diff is already attached to a revision!");
         }
     } else {
         $diff = null;
     }
     $e_title = true;
     $e_testplan = true;
     $e_reviewers = null;
     $errors = array();
     $revision->loadRelationships();
     if ($request->isFormPost() && !$request->getStr('viaDiffView')) {
         $revision->setTitle($request->getStr('title'));
         $revision->setSummary($request->getStr('summary'));
         $revision->setTestPlan($request->getStr('testplan'));
         $revision->setBlameRevision($request->getStr('blame'));
         $revision->setRevertPlan($request->getStr('revert'));
         if (!strlen(trim($revision->getTitle()))) {
             $errors[] = 'You must provide a title.';
             $e_title = 'Required';
         } else {
             $e_title = null;
         }
         if (!strlen(trim($revision->getTestPlan()))) {
             $errors[] = 'You must provide a test plan.';
             $e_testplan = 'Required';
         } else {
             $e_testplan = null;
         }
         $user_phid = $request->getUser()->getPHID();
         if (in_array($user_phid, $request->getArr('reviewers'))) {
             $errors[] = 'You may not review your own revision.';
             $e_reviewers = 'Invalid';
         }
         if (!$errors) {
             $editor = new DifferentialRevisionEditor($revision, $user_phid);
             if ($diff) {
                 $editor->addDiff($diff, $request->getStr('comments'));
             }
             $editor->setCCPHIDs($request->getArr('cc'));
             $editor->setReviewers($request->getArr('reviewers'));
             $editor->save();
             return id(new AphrontRedirectResponse())->setURI('/D' . $revision->getID());
         }
         $reviewer_phids = $request->getArr('reviewers');
         $cc_phids = $request->getArr('cc');
     } else {
         $reviewer_phids = $revision->getReviewers();
         $cc_phids = $revision->getCCPHIDs();
     }
     $phids = array_merge($reviewer_phids, $cc_phids);
     $phids = array_unique($phids);
     $handles = id(new PhabricatorObjectHandleData($phids))->loadHandles();
     $handles = mpull($handles, 'getFullName', 'getPHID');
     $reviewer_map = array_select_keys($handles, $reviewer_phids);
     $cc_map = array_select_keys($handles, $cc_phids);
     $form = new AphrontFormView();
     $form->setUser($request->getUser());
     if ($diff) {
         $form->addHiddenInput('diffID', $diff->getID());
     }
     if ($revision->getID()) {
         $form->setAction('/differential/revision/edit/' . $revision->getID() . '/');
     } else {
         $form->setAction('/differential/revision/edit/');
     }
     $error_view = null;
     if ($errors) {
         $error_view = id(new AphrontErrorView())->setTitle('Form Errors')->setErrors($errors);
     }
     if ($diff && $revision->getID()) {
         $form->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Comments')->setName('comments')->setCaption("Explain what's new in this diff.")->setValue($request->getStr('comments')))->appendChild(id(new AphrontFormSubmitControl())->setValue('Save'))->appendChild(id(new AphrontFormDividerControl()));
     }
     $form->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Title')->setName('title')->setHeight(AphrontFormTextAreaControl::HEIGHT_VERY_SHORT)->setValue($revision->getTitle())->setError($e_title))->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Summary')->setName('summary')->setValue($revision->getSummary()))->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Test Plan')->setName('testplan')->setValue($revision->getTestPlan())->setError($e_testplan))->appendChild(id(new AphrontFormTokenizerControl())->setLabel('Reviewers')->setName('reviewers')->setDatasource('/typeahead/common/users/')->setError($e_reviewers)->setValue($reviewer_map))->appendChild(id(new AphrontFormTokenizerControl())->setLabel('CC')->setName('cc')->setDatasource('/typeahead/common/mailable/')->setValue($cc_map))->appendChild(id(new AphrontFormTextControl())->setLabel('Blame Revision')->setName('blame')->setValue($revision->getBlameRevision())->setCaption('Revision which broke the stuff which this ' . 'change fixes.'))->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Revert Plan')->setName('revert')->setValue($revision->getRevertPlan())->setCaption('Special steps required to safely revert this change.'));
     $submit = id(new AphrontFormSubmitControl())->setValue('Save');
     if ($diff) {
         $submit->addCancelButton('/differential/diff/' . $diff->getID() . '/');
     } else {
         $submit->addCancelButton('/D' . $revision->getID());
     }
     $form->appendChild($submit);
     $panel = new AphrontPanelView();
     if ($revision->getID()) {
         if ($diff) {
             $panel->setHeader('Update Differential Revision');
         } else {
             $panel->setHeader('Edit Differential Revision');
         }
     } else {
         $panel->setHeader('Create New Differential Revision');
     }
     $panel->appendChild($form);
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     return $this->buildStandardPageResponse(array($error_view, $panel), array('title' => 'Edit Differential Revision'));
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $user = $request->getUser();
     $provider = $this->provider;
     $notice = null;
     $provider_name = $provider->getProviderName();
     $provider_key = $provider->getProviderKey();
     $oauth_info = id(new PhabricatorUserOAuthInfo())->loadOneWhere('userID = %d AND oauthProvider = %s', $user->getID(), $provider->getProviderKey());
     $form = new AphrontFormView();
     $form->setUser($user);
     $forms = array();
     $forms[] = $form;
     if (!$oauth_info) {
         $form->appendChild('<p class="aphront-form-instructions">There is currently no ' . $provider_name . ' account linked to your Phabricator account. You ' . 'can link an account, which will allow you to use it to log into ' . 'Phabricator.</p>');
         switch ($provider_key) {
             case PhabricatorOAuthProvider::PROVIDER_GITHUB:
                 $form->appendChild('<p class="aphront-form-instructions">Additionally, you must ' . 'link your Github account before Phabricator can access any ' . 'information about hosted repositories.</p>');
                 break;
         }
         $auth_uri = $provider->getAuthURI();
         $client_id = $provider->getClientID();
         $redirect_uri = $provider->getRedirectURI();
         $minimum_scope = $provider->getMinimumScope();
         $form->setAction($auth_uri)->setMethod('GET')->addHiddenInput('redirect_uri', $redirect_uri)->addHiddenInput('client_id', $client_id)->addHiddenInput('scope', $minimum_scope);
         foreach ($provider->getExtraAuthParameters() as $key => $value) {
             $form->addHiddenInput($key, $value);
         }
         $form->appendChild(id(new AphrontFormSubmitControl())->setValue('Link ' . $provider_name . " Account »"));
     } else {
         $form->appendChild('<p class="aphront-form-instructions">Your account is linked with ' . 'a ' . $provider_name . ' account. You may use your ' . $provider_name . ' ' . 'credentials to log into Phabricator.</p>')->appendChild(id(new AphrontFormStaticControl())->setLabel($provider_name . ' ID')->setValue($oauth_info->getOAuthUID()))->appendChild(id(new AphrontFormStaticControl())->setLabel($provider_name . ' Name')->setValue($oauth_info->getAccountName()))->appendChild(id(new AphrontFormStaticControl())->setLabel($provider_name . ' URI')->setValue($oauth_info->getAccountURI()));
         if (!$provider->isProviderLinkPermanent()) {
             $unlink = 'Unlink ' . $provider_name . ' Account';
             $unlink_form = new AphrontFormView();
             $unlink_form->setUser($user)->appendChild('<p class="aphront-form-instructions">You may unlink this account ' . 'from your ' . $provider_name . ' account. This will prevent you from ' . 'logging in with your ' . $provider_name . ' credentials.</p>')->appendChild(id(new AphrontFormSubmitControl())->addCancelButton('/oauth/' . $provider_key . '/unlink/', $unlink));
             $forms['Unlink Account'] = $unlink_form;
         }
         $expires = $oauth_info->getTokenExpires();
         if ($expires) {
             if ($expires <= time()) {
                 $expires = "Expired";
             } else {
                 $expires = phabricator_datetime($expires, $user);
             }
         } else {
             $expires = 'No Information Available';
         }
         $scope = $oauth_info->getTokenScope();
         if (!$scope) {
             $scope = 'No Information Available';
         }
         $status = $oauth_info->getTokenStatus();
         $status = PhabricatorUserOAuthInfo::getReadableTokenStatus($status);
         $token_form = new AphrontFormView();
         $token_form->setUser($user)->appendChild('<p class="aphront-from-instructions">insert rap about tokens</p>')->appendChild(id(new AphrontFormStaticControl())->setLabel('Token Status')->setValue($status))->appendChild(id(new AphrontFormStaticControl())->setLabel('Expires')->setValue($expires))->appendChild(id(new AphrontFormStaticControl())->setLabel('Scope')->setValue($scope));
         $forms['Account Token Information'] = $token_form;
     }
     $panel = new AphrontPanelView();
     $panel->setHeader($provider_name . ' Account Settings');
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     foreach ($forms as $name => $form) {
         if ($name) {
             $panel->appendChild('<br /><br /><h1>' . $name . '</h1>');
         }
         $panel->appendChild($form);
     }
     return id(new AphrontNullView())->appendChild(array($notice, $panel));
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     if ($request->getUser()->getPHID()) {
         // Kick the user out if they're already logged in.
         return id(new AphrontRedirectResponse())->setURI('/');
     }
     if ($request->isConduit()) {
         // A common source of errors in Conduit client configuration is getting
         // the request path wrong. The client will end up here, so make some
         // effort to give them a comprehensible error message.
         $request_path = $this->getRequest()->getPath();
         $conduit_path = '/api/<method>';
         $example_path = '/api/conduit.ping';
         $message = "ERROR: You are making a Conduit API request to '{$request_path}', " . "but the correct HTTP request path to use in order to access a " . "Conduit method is '{$conduit_path}' (for example, " . "'{$example_path}'). Check your configuration.";
         return id(new AphrontPlainTextResponse())->setContent($message);
     }
     $error_view = null;
     if ($request->getCookie('phusr') && $request->getCookie('phsid')) {
         // The session cookie is invalid, so clear it.
         $request->clearCookie('phusr');
         $request->clearCookie('phsid');
         $error_view = new AphrontErrorView();
         $error_view->setTitle('Invalid Session');
         $error_view->setErrors(array("Your login session is invalid. Try logging in again. If that " . "doesn't work, clear your browser cookies."));
     }
     $next_uri = $this->getRequest()->getPath();
     if ($next_uri == '/login/') {
         $next_uri = '/';
     }
     if (!$request->isFormPost()) {
         $request->setCookie('next_uri', $next_uri);
     }
     $password_auth = PhabricatorEnv::getEnvConfig('auth.password-auth-enabled');
     $forms = array();
     $errors = array();
     if ($password_auth) {
         $require_captcha = false;
         $e_captcha = true;
         $username_or_email = $request->getCookie('phusr');
         if ($request->isFormPost()) {
             if (AphrontFormRecaptchaControl::isRecaptchaEnabled()) {
                 $failed_attempts = PhabricatorUserLog::loadRecentEventsFromThisIP(PhabricatorUserLog::ACTION_LOGIN_FAILURE, 60 * 15);
                 if (count($failed_attempts) > 5) {
                     $require_captcha = true;
                     if (!AphrontFormRecaptchaControl::processCaptcha($request)) {
                         if (AphrontFormRecaptchaControl::hasCaptchaResponse($request)) {
                             $e_captcha = 'Invalid';
                             $errors[] = 'CAPTCHA was not entered correctly.';
                         } else {
                             $e_captcha = 'Required';
                             $errors[] = 'Too many login failures recently. You must ' . 'submit a CAPTCHA with your login request.';
                         }
                     }
                 }
             }
             $username_or_email = $request->getStr('username_or_email');
             $user = id(new PhabricatorUser())->loadOneWhere('username = %s', $username_or_email);
             if (!$user) {
                 $user = id(new PhabricatorUser())->loadOneWhere('email = %s', $username_or_email);
             }
             if (!$errors) {
                 // Perform username/password tests only if we didn't get rate limited
                 // by the CAPTCHA.
                 if (!$user || !$user->comparePassword($request->getStr('password'))) {
                     $errors[] = 'Bad username/password.';
                 }
             }
             if (!$errors) {
                 $session_key = $user->establishSession('web');
                 $request->setCookie('phusr', $user->getUsername());
                 $request->setCookie('phsid', $session_key);
                 $uri = new PhutilURI('/login/validate/');
                 $uri->setQueryParams(array('phusr' => $user->getUsername()));
                 return id(new AphrontRedirectResponse())->setURI((string) $uri);
             } else {
                 $log = PhabricatorUserLog::newLog(null, $user, PhabricatorUserLog::ACTION_LOGIN_FAILURE);
                 $log->save();
                 $request->clearCookie('phusr');
                 $request->clearCookie('phsid');
             }
         }
         if ($errors) {
             $error_view = new AphrontErrorView();
             $error_view->setTitle('Login Failed');
             $error_view->setErrors($errors);
         }
         $form = new AphrontFormView();
         $form->setUser($request->getUser())->setAction('/login/')->appendChild(id(new AphrontFormTextControl())->setLabel('Username/Email')->setName('username_or_email')->setValue($username_or_email))->appendChild(id(new AphrontFormPasswordControl())->setLabel('Password')->setName('password')->setCaption('<a href="/login/email/">' . 'Forgot your password? / Email Login</a>'));
         if ($require_captcha) {
             $form->appendChild(id(new AphrontFormRecaptchaControl())->setError($e_captcha));
         }
         $form->appendChild(id(new AphrontFormSubmitControl())->setValue('Login'));
         //    $panel->setCreateButton('Register New Account', '/login/register/');
         $forms['Phabricator Login'] = $form;
     }
     $providers = PhabricatorOAuthProvider::getAllProviders();
     foreach ($providers as $provider) {
         $enabled = $provider->isProviderEnabled();
         if (!$enabled) {
             continue;
         }
         $auth_uri = $provider->getAuthURI();
         $redirect_uri = $provider->getRedirectURI();
         $client_id = $provider->getClientID();
         $provider_name = $provider->getProviderName();
         $minimum_scope = $provider->getMinimumScope();
         $extra_auth = $provider->getExtraAuthParameters();
         // TODO: In theory we should use 'state' to prevent CSRF, but the total
         // effect of the CSRF attack is that an attacker can cause a user to login
         // to Phabricator if they're already logged into some OAuth provider. This
         // does not seem like the most severe threat in the world, and generating
         // CSRF for logged-out users is vaugely tricky.
         if ($provider->isProviderRegistrationEnabled()) {
             $title = "Login or Register with {$provider_name}";
             $body = 'Login or register for Phabricator using your ' . phutil_escape_html($provider_name) . ' account.';
             $button = "Login or Register with {$provider_name}";
         } else {
             $title = "Login with {$provider_name}";
             $body = 'Login to your existing Phabricator account using your ' . phutil_escape_html($provider_name) . ' account.<br /><br />' . '<strong>You can not use ' . phutil_escape_html($provider_name) . ' to register a new ' . 'account.</strong>';
             $button = "Login with {$provider_name}";
         }
         $auth_form = new AphrontFormView();
         $auth_form->setAction($auth_uri)->addHiddenInput('client_id', $client_id)->addHiddenInput('redirect_uri', $redirect_uri)->addHiddenInput('scope', $minimum_scope);
         foreach ($extra_auth as $key => $value) {
             $auth_form->addHiddenInput($key, $value);
         }
         $auth_form->setUser($request->getUser())->setMethod('GET')->appendChild('<p class="aphront-form-instructions">' . $body . '</p>')->appendChild(id(new AphrontFormSubmitControl())->setValue("{$button} »"));
         $forms[$title] = $auth_form;
     }
     $panel = new AphrontPanelView();
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     foreach ($forms as $name => $form) {
         $panel->appendChild('<h1>' . $name . '</h1>');
         $panel->appendChild($form);
         $panel->appendChild('<br />');
     }
     return $this->buildStandardPageResponse(array($error_view, $panel), array('title' => 'Login'));
 }
 public function processRequest()
 {
     $provider = $this->getOAuthProvider();
     $oauth_info = $this->getOAuthInfo();
     $request = $this->getRequest();
     $errors = array();
     $e_username = true;
     $e_email = true;
     $e_realname = true;
     $user = new PhabricatorUser();
     $user->setUsername($provider->retrieveUserAccountName());
     $user->setRealName($provider->retrieveUserRealName());
     $new_email = $provider->retrieveUserEmail();
     if ($new_email) {
         // If the user's OAuth provider account has an email address but the
         // email address domain is not allowed by the Phabricator configuration,
         // we just pretend the provider did not supply an address.
         //
         // For instance, if the user uses Google OAuth and their Google address
         // is "*****@*****.**" but Phabricator is configured to require users
         // use "@company.com" addresses, we show a prompt below and tell the user
         // to provide their "@company.com" address. They can still use the OAuth
         // account to login, they just need to associate their account with an
         // allowed address.
         //
         // If the OAuth address is fine, we just use it and don't prompt the user.
         if (!PhabricatorUserEmail::isAllowedAddress($new_email)) {
             $new_email = null;
         }
     }
     $show_email_input = $new_email === null;
     if ($request->isFormPost()) {
         $user->setUsername($request->getStr('username'));
         $username = $user->getUsername();
         if (!strlen($user->getUsername())) {
             $e_username = '******';
             $errors[] = 'Username is required.';
         } else {
             if (!PhabricatorUser::validateUsername($username)) {
                 $e_username = '******';
                 $errors[] = PhabricatorUser::describeValidUsername();
             } else {
                 $e_username = null;
             }
         }
         if (!$new_email) {
             $new_email = trim($request->getStr('email'));
             if (!$new_email) {
                 $e_email = 'Required';
                 $errors[] = 'Email is required.';
             } else {
                 $e_email = null;
             }
         }
         if ($new_email) {
             $email_ok = PhabricatorUserEmail::isAllowedAddress($new_email);
             if (!$email_ok) {
                 $e_email = 'Invalid';
                 $errors[] = PhabricatorUserEmail::describeAllowedAddresses();
             }
         }
         if (!strlen($user->getRealName())) {
             $user->setRealName($request->getStr('realname'));
             if (!strlen($user->getRealName())) {
                 $e_realname = 'Required';
                 $errors[] = 'Real name is required.';
             } else {
                 $e_realname = null;
             }
         }
         if (!$errors) {
             $image = $provider->retrieveUserProfileImage();
             if ($image) {
                 $file = PhabricatorFile::newFromFileData($image, array('name' => $provider->getProviderKey() . '-profile.jpg', 'authorPHID' => $user->getPHID()));
                 $xformer = new PhabricatorImageTransformer();
                 // Resize OAuth image to a reasonable size
                 $small_xformed = $xformer->executeProfileTransform($file, $width = 50, $min_height = 50, $max_height = 50);
                 $user->setProfileImagePHID($small_xformed->getPHID());
             }
             try {
                 // NOTE: We don't verify OAuth email addresses by default because
                 // OAuth providers might associate email addresses with accounts that
                 // haven't actually verified they own them. We could selectively
                 // auto-verify some providers that we trust here, but the stakes for
                 // verifying an email address are high because having a corporate
                 // address at a company is sometimes the key to the castle.
                 $email_obj = id(new PhabricatorUserEmail())->setAddress($new_email)->setIsVerified(0);
                 id(new PhabricatorUserEditor())->setActor($user)->createNewUser($user, $email_obj);
                 $oauth_info->setUserID($user->getID());
                 $oauth_info->save();
                 $session_key = $user->establishSession('web');
                 $request->setCookie('phusr', $user->getUsername());
                 $request->setCookie('phsid', $session_key);
                 $email_obj->sendVerificationEmail($user);
                 return id(new AphrontRedirectResponse())->setURI('/');
             } catch (AphrontQueryDuplicateKeyException $exception) {
                 $same_username = id(new PhabricatorUser())->loadOneWhere('userName = %s', $user->getUserName());
                 $same_email = id(new PhabricatorUserEmail())->loadOneWhere('address = %s', $new_email);
                 if ($same_username) {
                     $e_username = '******';
                     $errors[] = 'That username or email is not unique.';
                 } else {
                     if ($same_email) {
                         $e_email = 'Duplicate';
                         $errors[] = 'That email is not unique.';
                     } else {
                         throw $exception;
                     }
                 }
             }
         }
     }
     $error_view = null;
     if ($errors) {
         $error_view = new AphrontErrorView();
         $error_view->setTitle('Registration Failed');
         $error_view->setErrors($errors);
     }
     // Strip the URI down to the path, because otherwise we'll trigger
     // external CSRF protection (by having a protocol in the form "action")
     // and generate a form with no CSRF token.
     $action_uri = new PhutilURI($provider->getRedirectURI());
     $action_path = $action_uri->getPath();
     $form = new AphrontFormView();
     $form->addHiddenInput('confirm_token', $provider->getAccessToken())->addHiddenInput('expires', $oauth_info->getTokenExpires())->addHiddenInput('state', $this->getOAuthState())->setUser($request->getUser())->setAction($action_path)->appendChild(id(new AphrontFormTextControl())->setLabel('Username')->setName('username')->setValue($user->getUsername())->setError($e_username));
     if ($show_email_input) {
         $form->appendChild(id(new AphrontFormTextControl())->setLabel('Email')->setName('email')->setValue($request->getStr('email'))->setCaption(PhabricatorUserEmail::describeAllowedAddresses())->setError($e_email));
     }
     if ($provider->retrieveUserRealName() === null) {
         $form->appendChild(id(new AphrontFormTextControl())->setLabel('Real Name')->setName('realname')->setValue($request->getStr('realname'))->setError($e_realname));
     }
     $form->appendChild(id(new AphrontFormSubmitControl())->setValue('Create Account'));
     $panel = new AphrontPanelView();
     $panel->setHeader('Create New Account');
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     $panel->appendChild($form);
     return $this->buildStandardPageResponse(array($error_view, $panel), array('title' => 'Create New Account'));
 }
 public function processRequest()
 {
     $request = $this->getRequest();
     $viewer = $request->getUser();
     if (!$this->id) {
         $this->id = $request->getInt('revisionID');
     }
     if ($this->id) {
         $revision = id(new DifferentialRevisionQuery())->setViewer($viewer)->withIDs(array($this->id))->needRelationships(true)->needReviewerStatus(true)->needActiveDiffs(true)->requireCapabilities(array(PhabricatorPolicyCapability::CAN_VIEW, PhabricatorPolicyCapability::CAN_EDIT))->executeOne();
         if (!$revision) {
             return new Aphront404Response();
         }
     } else {
         $revision = DifferentialRevision::initializeNewRevision($viewer);
         $revision->attachReviewerStatus(array());
     }
     $diff_id = $request->getInt('diffID');
     if ($diff_id) {
         $diff = id(new DifferentialDiffQuery())->setViewer($viewer)->withIDs(array($diff_id))->executeOne();
         if (!$diff) {
             return new Aphront404Response();
         }
         if ($diff->getRevisionID()) {
             // TODO: Redirect?
             throw new Exception('This diff is already attached to a revision!');
         }
     } else {
         $diff = null;
     }
     if (!$diff) {
         if (!$revision->getID()) {
             throw new Exception(pht('You can not create a new revision without a diff!'));
         }
     } else {
         // TODO: It would be nice to show the diff being attached in the UI.
     }
     $field_list = PhabricatorCustomField::getObjectFields($revision, PhabricatorCustomField::ROLE_EDIT);
     $field_list->setViewer($viewer)->readFieldsFromStorage($revision);
     $validation_exception = null;
     if ($request->isFormPost() && !$request->getStr('viaDiffView')) {
         $xactions = $field_list->buildFieldTransactionsFromRequest(new DifferentialTransaction(), $request);
         if ($diff) {
             $xactions[] = id(new DifferentialTransaction())->setTransactionType(DifferentialTransaction::TYPE_UPDATE)->setNewValue($diff->getPHID());
         }
         $comments = $request->getStr('comments');
         if (strlen($comments)) {
             $xactions[] = id(new DifferentialTransaction())->setTransactionType(PhabricatorTransactions::TYPE_COMMENT)->attachComment(id(new DifferentialTransactionComment())->setContent($comments));
         }
         $editor = id(new DifferentialTransactionEditor())->setActor($viewer)->setContentSourceFromRequest($request)->setContinueOnNoEffect(true);
         try {
             $editor->applyTransactions($revision, $xactions);
             $revision_uri = '/D' . $revision->getID();
             return id(new AphrontRedirectResponse())->setURI($revision_uri);
         } catch (PhabricatorApplicationTransactionValidationException $ex) {
             $validation_exception = $ex;
         }
     }
     $form = new AphrontFormView();
     $form->setUser($request->getUser());
     if ($diff) {
         $form->addHiddenInput('diffID', $diff->getID());
     }
     if ($revision->getID()) {
         $form->setAction('/differential/revision/edit/' . $revision->getID() . '/');
     } else {
         $form->setAction('/differential/revision/edit/');
     }
     if ($diff && $revision->getID()) {
         $form->appendChild(id(new AphrontFormTextAreaControl())->setLabel(pht('Comments'))->setName('comments')->setCaption(pht("Explain what's new in this diff."))->setValue($request->getStr('comments')))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Save')))->appendChild(id(new AphrontFormDividerControl()));
     }
     $field_list->appendFieldsToForm($form);
     $submit = id(new AphrontFormSubmitControl())->setValue('Save');
     if ($diff) {
         $submit->addCancelButton('/differential/diff/' . $diff->getID() . '/');
     } else {
         $submit->addCancelButton('/D' . $revision->getID());
     }
     $form->appendChild($submit);
     $crumbs = $this->buildApplicationCrumbs();
     if ($revision->getID()) {
         if ($diff) {
             $title = pht('Update Differential Revision');
             $crumbs->addTextCrumb('D' . $revision->getID(), '/differential/diff/' . $diff->getID() . '/');
         } else {
             $title = pht('Edit Differential Revision');
             $crumbs->addTextCrumb('D' . $revision->getID(), '/D' . $revision->getID());
         }
     } else {
         $title = pht('Create New Differential Revision');
     }
     $form_box = id(new PHUIObjectBoxView())->setHeaderText($title)->setValidationException($validation_exception)->setForm($form);
     $crumbs->addTextCrumb($title);
     return $this->buildApplicationPage(array($crumbs, $form_box), array('title' => $title));
 }