protected function buildSchemaQuery()
 {
     $conf = PhabricatorEnv::newObjectFromConfig('mysql.configuration-provider', array($dao = null, 'w'));
     $api = id(new PhabricatorStorageManagementAPI())->setUser($conf->getUser())->setHost($conf->getHost())->setPort($conf->getPort())->setNamespace(PhabricatorLiskDAO::getDefaultStorageNamespace())->setPassword($conf->getPassword());
     $query = id(new PhabricatorConfigSchemaQuery())->setAPI($api);
     return $query;
 }
 protected function processReceivedObjectMail(PhabricatorMetaMTAReceivedMail $mail, PhabricatorLiskDAO $object, PhabricatorUser $sender)
 {
     $handler = PhabricatorEnv::newObjectFromConfig('metamta.maniphest.reply-handler');
     $handler->setMailReceiver($object);
     $handler->setActor($sender);
     $handler->setExcludeMailRecipientPHIDs($mail->loadExcludeMailRecipientPHIDs());
     $handler->processEmail($mail);
 }
 public static function newEngine()
 {
     $engine = PhabricatorEnv::newObjectFromConfig('syntax-highlighter.engine');
     $config = array('pygments.enabled' => PhabricatorEnv::getEnvConfig('pygments.enabled'), 'filename.map' => PhabricatorEnv::getEnvConfig('syntax.filemap'));
     foreach ($config as $key => $value) {
         $engine->setConfig($key, $value);
     }
     return $engine;
 }
 public function getConn($fragment)
 {
     $database = $this->getDatabaseName($fragment);
     $return =& $this->conns[$this->host][$this->user][$database];
     if (!$return) {
         $return = PhabricatorEnv::newObjectFromConfig('mysql.implementation', array(array('user' => $this->user, 'pass' => $this->password, 'host' => $this->host, 'port' => $this->port, 'database' => $fragment ? $database : null)));
     }
     return $return;
 }
 protected function processReceivedMail(PhabricatorMetaMTAReceivedMail $mail, PhabricatorUser $sender)
 {
     $task = ManiphestTask::initializeNewTask($sender);
     $task->setOriginalEmailSource($mail->getHeader('From'));
     $handler = PhabricatorEnv::newObjectFromConfig('metamta.maniphest.reply-handler');
     $handler->setMailReceiver($task);
     $handler->setActor($sender);
     $handler->setExcludeMailRecipientPHIDs($mail->loadExcludeMailRecipientPHIDs());
     $handler->processEmail($mail);
     $mail->setRelatedPHID($task->getPHID());
 }
 public function processRequest(AphrontRequest $request)
 {
     $user = $request->getUser();
     $username = $user->getUsername();
     $pref_time = PhabricatorUserPreferences::PREFERENCE_TIME_FORMAT;
     $preferences = $user->loadPreferences();
     $errors = array();
     if ($request->isFormPost()) {
         $new_timezone = $request->getStr('timezone');
         if (in_array($new_timezone, DateTimeZone::listIdentifiers(), true)) {
             $user->setTimezoneIdentifier($new_timezone);
         } else {
             $errors[] = pht('The selected timezone is not a valid timezone.');
         }
         $sex = $request->getStr('sex');
         $sexes = array(PhutilPerson::SEX_MALE, PhutilPerson::SEX_FEMALE);
         if (in_array($sex, $sexes)) {
             $user->setSex($sex);
         } else {
             $user->setSex(null);
         }
         // Checked in runtime.
         $user->setTranslation($request->getStr('translation'));
         $preferences->setPreference($pref_time, $request->getStr($pref_time));
         if (!$errors) {
             $preferences->save();
             $user->save();
             return id(new AphrontRedirectResponse())->setURI($this->getPanelURI('?saved=true'));
         }
     }
     $timezone_ids = DateTimeZone::listIdentifiers();
     $timezone_id_map = array_fuse($timezone_ids);
     $label_unknown = pht('%s updated their profile', $username);
     $label_her = pht('%s updated her profile', $username);
     $label_his = pht('%s updated his profile', $username);
     $sexes = array(PhutilPerson::SEX_UNKNOWN => $label_unknown, PhutilPerson::SEX_MALE => $label_his, PhutilPerson::SEX_FEMALE => $label_her);
     $translations = array();
     $symbols = id(new PhutilSymbolLoader())->setType('class')->setAncestorClass('PhabricatorTranslation')->setConcreteOnly(true)->selectAndLoadSymbols();
     foreach ($symbols as $symbol) {
         $class = $symbol['name'];
         $translations[$class] = newv($class, array())->getName();
     }
     asort($translations);
     $default = PhabricatorEnv::newObjectFromConfig('translation.provider');
     $translations = array('' => pht('Server Default (%s)', $default->getName())) + $translations;
     $form = new AphrontFormView();
     $form->setUser($user)->appendChild(id(new AphrontFormSelectControl())->setLabel(pht('Timezone'))->setName('timezone')->setOptions($timezone_id_map)->setValue($user->getTimezoneIdentifier()))->appendRemarkupInstructions(pht('**Choose the pronoun you prefer:**'))->appendChild(id(new AphrontFormSelectControl())->setOptions($sexes)->setLabel(pht('Pronoun'))->setName('sex')->setValue($user->getSex()))->appendChild(id(new AphrontFormSelectControl())->setOptions($translations)->setLabel(pht('Translation'))->setName('translation')->setValue($user->getTranslation()))->appendRemarkupInstructions(pht("**Custom Date and Time Formats**\n\n" . "You can specify custom formats which will be used when " . "rendering dates and times of day. Examples:\n\n" . "| Format  | Example  | Notes |\n" . "| ------  | -------- | ----- |\n" . "| `g:i A` | 2:34 PM  | Default 12-hour time. |\n" . "| `G.i a` | 02.34 pm | Alternate 12-hour time. |\n" . "| `H:i`   | 14:34    | 24-hour time. |\n" . "\n\n" . "You can find a [[%s | full reference in the PHP manual]].", 'http://www.php.net/manual/en/function.date.php'))->appendChild(id(new AphrontFormTextControl())->setLabel(pht('Time-of-Day Format'))->setName($pref_time)->setCaption(pht('Format used when rendering a time of day.'))->setValue($preferences->getPreference($pref_time)))->appendChild(id(new AphrontFormSubmitControl())->setValue(pht('Save Account Settings')));
     $form_box = id(new PHUIObjectBoxView())->setHeaderText(pht('Account Settings'))->setFormSaved($request->getStr('saved'))->setFormErrors($errors)->setForm($form);
     return array($form_box);
 }
 protected function executeChecks()
 {
     $conf = PhabricatorEnv::newObjectFromConfig('mysql.configuration-provider');
     $conn_user = $conf->getUser();
     $conn_pass = $conf->getPassword();
     $conn_host = $conf->getHost();
     $conn_port = $conf->getPort();
     ini_set('mysql.connect_timeout', 2);
     $config = array('user' => $conn_user, 'pass' => $conn_pass, 'host' => $conn_host, 'port' => $conn_port, 'database' => null);
     $conn_raw = PhabricatorEnv::newObjectFromConfig('mysql.implementation', array($config));
     try {
         queryfx($conn_raw, 'SELECT 1');
     } catch (AphrontConnectionQueryException $ex) {
         $message = pht("Unable to connect to MySQL!\n\n" . "%s\n\n" . "Make sure Phabricator and MySQL are correctly configured.", $ex->getMessage());
         $this->newIssue('mysql.connect')->setName(pht('Can Not Connect to MySQL'))->setMessage($message)->setIsFatal(true)->addRelatedPhabricatorConfig('mysql.host')->addRelatedPhabricatorConfig('mysql.port')->addRelatedPhabricatorConfig('mysql.user')->addRelatedPhabricatorConfig('mysql.pass');
         return;
     }
     $engines = queryfx_all($conn_raw, 'SHOW ENGINES');
     $engines = ipull($engines, 'Support', 'Engine');
     $innodb = idx($engines, 'InnoDB');
     if ($innodb != 'YES' && $innodb != 'DEFAULT') {
         $message = pht("The 'InnoDB' engine is not available in MySQL. Enable InnoDB in " . "your MySQL configuration." . "\n\n" . "(If you aleady created tables, MySQL incorrectly used some other " . "engine to create them. You need to convert them or drop and " . "reinitialize them.)");
         $this->newIssue('mysql.innodb')->setName(pht('MySQL InnoDB Engine Not Available'))->setMessage($message)->setIsFatal(true);
         return;
     }
     $namespace = PhabricatorEnv::getEnvConfig('storage.default-namespace');
     $databases = queryfx_all($conn_raw, 'SHOW DATABASES');
     $databases = ipull($databases, 'Database', 'Database');
     if (empty($databases[$namespace . '_meta_data'])) {
         $message = pht("Run the storage upgrade script to setup Phabricator's database " . "schema.");
         $this->newIssue('storage.upgrade')->setName(pht('Setup MySQL Schema'))->setMessage($message)->setIsFatal(true)->addCommand(hsprintf('<tt>phabricator/ $</tt> ./bin/storage upgrade'));
     } else {
         $config['database'] = $namespace . '_meta_data';
         $conn_meta = PhabricatorEnv::newObjectFromConfig('mysql.implementation', array($config));
         $applied = queryfx_all($conn_meta, 'SELECT patch FROM patch_status');
         $applied = ipull($applied, 'patch', 'patch');
         $all = PhabricatorSQLPatchList::buildAllPatches();
         $diff = array_diff_key($all, $applied);
         if ($diff) {
             $this->newIssue('storage.patch')->setName(pht('Upgrade MySQL Schema'))->setMessage(pht("Run the storage upgrade script to upgrade Phabricator's " . "database schema. Missing patches:<br />%s<br />", phutil_implode_html(phutil_tag('br'), array_keys($diff))))->addCommand(hsprintf('<tt>phabricator/ $</tt> ./bin/storage upgrade'));
         }
     }
     $host = PhabricatorEnv::getEnvConfig('mysql.host');
     $matches = null;
     if (preg_match('/^([^:]+):(\\d+)$/', $host, $matches)) {
         $host = $matches[1];
         $port = $matches[2];
         $this->newIssue('storage.mysql.hostport')->setName(pht('Deprecated mysql.host Format'))->setSummary(pht('Move port information from `%s` to `%s` in your config.', 'mysql.host', 'mysql.port'))->setMessage(pht('Your `%s` configuration contains a port number, but this usage ' . 'is deprecated. Instead, put the port number in `%s`.', 'mysql.host', 'mysql.port'))->addPhabricatorConfig('mysql.host')->addPhabricatorConfig('mysql.port')->addCommand(hsprintf('<tt>phabricator/ $</tt> ./bin/config set mysql.host %s', $host))->addCommand(hsprintf('<tt>phabricator/ $</tt> ./bin/config set mysql.port %s', $port));
     }
 }
 protected function execute(ConduitAPIRequest $request)
 {
     $task_phid = $request->getValue('task_phid');
     $orig_rev_phids = $request->getValue('orig_rev_phids');
     if (empty($orig_rev_phids)) {
         $orig_rev_phids = array();
     }
     $new_rev_phids = $request->getValue('new_rev_phids');
     if (empty($new_rev_phids)) {
         $new_rev_phids = array();
     }
     try {
         $task_attacher = PhabricatorEnv::newObjectFromConfig('differential.attach-task-class');
         $task_attacher->updateTaskRevisionAssoc($task_phid, $orig_rev_phids, $new_rev_phids);
     } catch (ReflectionException $ex) {
         throw new ConduitException('ERR_NO_TASKATTACHER_DEFINED');
     }
 }
 public function processRequest()
 {
     $current_user = $this->getRequest()->getUser();
     $provider = $this->provider;
     if (!$provider->isProviderEnabled()) {
         return new Aphront400Response();
     }
     $provider_name = $provider->getProviderName();
     $provider_key = $provider->getProviderKey();
     $request = $this->getRequest();
     if ($request->getStr('error')) {
         $error_view = id(new PhabricatorOAuthFailureView())->setRequest($request);
         return $this->buildErrorResponse($error_view);
     }
     $error_response = $this->retrieveAccessToken($provider);
     if ($error_response) {
         return $error_response;
     }
     $userinfo_uri = new PhutilURI($provider->getUserInfoURI());
     $userinfo_uri->setQueryParams(array('access_token' => $this->accessToken));
     $user_data = @file_get_contents($userinfo_uri);
     $provider->setUserData($user_data);
     $provider->setAccessToken($this->accessToken);
     $user_id = $provider->retrieveUserID();
     $provider_key = $provider->getProviderKey();
     $oauth_info = $this->retrieveOAuthInfo($provider);
     if ($current_user->getPHID()) {
         if ($oauth_info->getID()) {
             if ($oauth_info->getUserID() != $current_user->getID()) {
                 $dialog = new AphrontDialogView();
                 $dialog->setUser($current_user);
                 $dialog->setTitle('Already Linked to Another Account');
                 $dialog->appendChild(hsprintf('<p>The %s account you just authorized is already linked to ' . 'another Phabricator account. Before you can associate your %s ' . 'account with this Phabriactor account, you must unlink it from ' . 'the Phabricator account it is currently linked to.</p>', $provider_name, $provider_name));
                 $dialog->addCancelButton('/settings/page/' . $provider_key . '/');
                 return id(new AphrontDialogResponse())->setDialog($dialog);
             } else {
                 return id(new AphrontRedirectResponse())->setURI('/settings/page/' . $provider_key . '/');
             }
         }
         $existing_oauth = id(new PhabricatorUserOAuthInfo())->loadOneWhere('userID = %d AND oauthProvider = %s', $current_user->getID(), $provider_key);
         if ($existing_oauth) {
             $dialog = new AphrontDialogView();
             $dialog->setUser($current_user);
             $dialog->setTitle('Already Linked to an Account From This Provider');
             $dialog->appendChild(hsprintf('<p>The account you are logged in with is already linked to a %s ' . 'account. Before you can link it to a different %s account, you ' . 'must unlink the old account.</p>', $provider_name, $provider_name));
             $dialog->addCancelButton('/settings/page/' . $provider_key . '/');
             return id(new AphrontDialogResponse())->setDialog($dialog);
         }
         if (!$request->isDialogFormPost()) {
             $dialog = new AphrontDialogView();
             $dialog->setUser($current_user);
             $dialog->setTitle('Link ' . $provider_name . ' Account');
             $dialog->appendChild(hsprintf('<p>Link your %s account to your Phabricator account?</p>', $provider_name));
             $dialog->addHiddenInput('token', $provider->getAccessToken());
             $dialog->addHiddenInput('expires', $oauth_info->getTokenExpires());
             $dialog->addHiddenInput('state', $this->oauthState);
             $dialog->addSubmitButton('Link Accounts');
             $dialog->addCancelButton('/settings/page/' . $provider_key . '/');
             return id(new AphrontDialogResponse())->setDialog($dialog);
         }
         $oauth_info->setUserID($current_user->getID());
         $this->saveOAuthInfo($oauth_info);
         return id(new AphrontRedirectResponse())->setURI('/settings/page/' . $provider_key . '/');
     }
     // Login with known auth.
     if ($oauth_info->getID()) {
         $unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
         $known_user = id(new PhabricatorUser())->load($oauth_info->getUserID());
         $request->getApplicationConfiguration()->willAuthenticateUserWithOAuth($known_user, $oauth_info, $provider);
         $session_key = $known_user->establishSession('web');
         $this->saveOAuthInfo($oauth_info);
         $request->setCookie('phusr', $known_user->getUsername());
         $request->setCookie('phsid', $session_key);
         $uri = new PhutilURI('/login/validate/');
         $uri->setQueryParams(array('phusr' => $known_user->getUsername()));
         return id(new AphrontRedirectResponse())->setURI((string) $uri);
     }
     $oauth_email = $provider->retrieveUserEmail();
     if ($oauth_email) {
         $known_email = id(new PhabricatorUser())->loadOneWhere('email = %s', $oauth_email);
         if ($known_email) {
             $dialog = new AphrontDialogView();
             $dialog->setUser($current_user);
             $dialog->setTitle('Already Linked to Another Account');
             $dialog->appendChild(hsprintf('<p>The %s account you just authorized has an email address which ' . 'is already in use by another Phabricator account. To link the ' . 'accounts, log in to your Phabricator account and then go to ' . 'Settings.</p>', $provider_name));
             $dialog->addCancelButton('/login/');
             return id(new AphrontDialogResponse())->setDialog($dialog);
         }
     }
     if (!$provider->isProviderRegistrationEnabled()) {
         $dialog = new AphrontDialogView();
         $dialog->setUser($current_user);
         $dialog->setTitle('No Account Registration With ' . $provider_name);
         $dialog->appendChild(hsprintf('<p>You can not register a new account using %s; you can only use ' . 'your %s account to log into an existing Phabricator account which ' . 'you have registered through other means.</p>', $provider_name, $provider_name));
         $dialog->addCancelButton('/login/');
         return id(new AphrontDialogResponse())->setDialog($dialog);
     }
     $controller = PhabricatorEnv::newObjectFromConfig('controller.oauth-registration', array($this->getRequest()));
     $controller->setOAuthProvider($provider);
     $controller->setOAuthInfo($oauth_info);
     $controller->setOAuthState($this->oauthState);
     return $this->delegateToController($controller);
 }
예제 #10
0
 public static function newFromFileData($data, array $params = array())
 {
     $selector = PhabricatorEnv::newObjectFromConfig('storage.engine-selector');
     $engines = $selector->selectStorageEngines($data, $params);
     if (!$engines) {
         throw new Exception("No valid storage engines are available!");
     }
     $data_handle = null;
     $engine_identifier = null;
     $exceptions = array();
     foreach ($engines as $engine) {
         $engine_class = get_class($engine);
         try {
             // Perform the actual write.
             $data_handle = $engine->writeFile($data, $params);
             if (!$data_handle || strlen($data_handle) > 255) {
                 // This indicates an improperly implemented storage engine.
                 throw new PhabricatorFileStorageConfigurationException("Storage engine '{$engine_class}' executed writeFile() but did " . "not return a valid handle ('{$data_handle}') to the data: it " . "must be nonempty and no longer than 255 characters.");
             }
             $engine_identifier = $engine->getEngineIdentifier();
             if (!$engine_identifier || strlen($engine_identifier) > 32) {
                 throw new PhabricatorFileStorageConfigurationException("Storage engine '{$engine_class}' returned an improper engine " . "identifier '{$engine_identifier}': it must be nonempty " . "and no longer than 32 characters.");
             }
             // We stored the file somewhere so stop trying to write it to other
             // places.
             break;
         } catch (Exception $ex) {
             if ($ex instanceof PhabricatorFileStorageConfigurationException) {
                 // If an engine is outright misconfigured (or misimplemented), raise
                 // that immediately since it probably needs attention.
                 throw $ex;
             }
             // If an engine doesn't work, keep trying all the other valid engines
             // in case something else works.
             phlog($ex);
             $exceptions[] = $ex;
         }
     }
     if (!$data_handle) {
         throw new PhutilAggregateException("All storage engines failed to write file:", $exceptions);
     }
     $file_name = idx($params, 'name');
     $file_name = self::normalizeFileName($file_name);
     // If for whatever reason, authorPHID isn't passed as a param
     // (always the case with newFromFileDownload()), store a ''
     $authorPHID = idx($params, 'authorPHID');
     $file = new PhabricatorFile();
     $file->setName($file_name);
     $file->setByteSize(strlen($data));
     $file->setAuthorPHID($authorPHID);
     $file->setContentHash(PhabricatorHash::digest($data));
     $file->setStorageEngine($engine_identifier);
     $file->setStorageHandle($data_handle);
     // TODO: This is probably YAGNI, but allows for us to do encryption or
     // compression later if we want.
     $file->setStorageFormat(self::STORAGE_FORMAT_RAW);
     if (isset($params['mime-type'])) {
         $file->setMimeType($params['mime-type']);
     } else {
         $tmp = new TempFile();
         Filesystem::writeFile($tmp, $data);
         $file->setMimeType(Filesystem::getMimeType($tmp));
     }
     $file->save();
     return $file;
 }
 public function buildDefaultMailer()
 {
     return PhabricatorEnv::newObjectFromConfig('metamta.mail-adapter');
 }
 public function processRequest(AphrontRequest $request)
 {
     $user = $request->getUser();
     $profile = id(new PhabricatorUserProfile())->loadOneWhere('userPHID = %s', $user->getPHID());
     if (!$profile) {
         $profile = new PhabricatorUserProfile();
         $profile->setUserPHID($user->getPHID());
     }
     $supported_formats = PhabricatorFile::getTransformableImageFormats();
     $e_image = null;
     $errors = array();
     if ($request->isFormPost()) {
         $profile->setTitle($request->getStr('title'));
         $profile->setBlurb($request->getStr('blurb'));
         $sex = $request->getStr('sex');
         $sexes = array(PhutilPerson::SEX_MALE, PhutilPerson::SEX_FEMALE);
         if (in_array($sex, $sexes)) {
             $user->setSex($sex);
         } else {
             $user->setSex(null);
         }
         // Checked in runtime.
         $user->setTranslation($request->getStr('translation'));
         $default_image = $request->getExists('default_image');
         if ($default_image) {
             $profile->setProfileImagePHID(null);
             $user->setProfileImagePHID(null);
         } else {
             if (!empty($_FILES['image'])) {
                 $err = idx($_FILES['image'], 'error');
                 if ($err != UPLOAD_ERR_NO_FILE) {
                     $file = PhabricatorFile::newFromPHPUpload($_FILES['image'], array('authorPHID' => $user->getPHID()));
                     $okay = $file->isTransformableImage();
                     if ($okay) {
                         $xformer = new PhabricatorImageTransformer();
                         // Generate the large picture for the profile page.
                         $large_xformed = $xformer->executeProfileTransform($file, $width = 280, $min_height = 140, $max_height = 420);
                         $profile->setProfileImagePHID($large_xformed->getPHID());
                         // Generate the small picture for comments, etc.
                         $small_xformed = $xformer->executeProfileTransform($file, $width = 50, $min_height = 50, $max_height = 50);
                         $user->setProfileImagePHID($small_xformed->getPHID());
                     } else {
                         $e_image = 'Not Supported';
                         $errors[] = 'This server only supports these image formats: ' . implode(', ', $supported_formats) . '.';
                     }
                 }
             }
         }
         if (!$errors) {
             $user->save();
             $profile->save();
             $response = id(new AphrontRedirectResponse())->setURI($this->getPanelURI('?saved=true'));
             return $response;
         }
     }
     $error_view = null;
     if ($errors) {
         $error_view = new AphrontErrorView();
         $error_view->setTitle('Form Errors');
         $error_view->setErrors($errors);
     } else {
         if ($request->getStr('saved')) {
             $error_view = new AphrontErrorView();
             $error_view->setSeverity(AphrontErrorView::SEVERITY_NOTICE);
             $error_view->setTitle('Changes Saved');
             $error_view->appendChild('<p>Your changes have been saved.</p>');
             $error_view = $error_view->render();
         }
     }
     $img_src = $user->loadProfileImageURI();
     $profile_uri = PhabricatorEnv::getURI('/p/' . $user->getUsername() . '/');
     $sexes = array(PhutilPerson::SEX_UNKNOWN => 'Unknown', PhutilPerson::SEX_MALE => 'Male', PhutilPerson::SEX_FEMALE => 'Female');
     $translations = array();
     $symbols = id(new PhutilSymbolLoader())->setType('class')->setAncestorClass('PhabricatorTranslation')->setConcreteOnly(true)->selectAndLoadSymbols();
     foreach ($symbols as $symbol) {
         $class = $symbol['name'];
         $translations[$class] = newv($class, array())->getName();
     }
     asort($translations);
     $default = PhabricatorEnv::newObjectFromConfig('translation.provider');
     $translations = array('' => 'Server Default (' . $default->getName() . ')') + $translations;
     $form = new AphrontFormView();
     $form->setUser($request->getUser())->setEncType('multipart/form-data')->appendChild(id(new AphrontFormTextControl())->setLabel('Title')->setName('title')->setValue($profile->getTitle())->setCaption('Serious business title.'))->appendChild(id(new AphrontFormSelectControl())->setOptions($sexes)->setLabel('Sex')->setName('sex')->setValue($user->getSex()))->appendChild(id(new AphrontFormSelectControl())->setOptions($translations)->setLabel('Translation')->setName('translation')->setValue($user->getTranslation()))->appendChild(id(new AphrontFormMarkupControl())->setLabel('Profile URI')->setValue(phutil_render_tag('a', array('href' => $profile_uri), phutil_escape_html($profile_uri))))->appendChild('<p class="aphront-form-instructions">Write something about yourself! ' . 'Make sure to include <strong>important information</strong> like ' . 'your favorite Pokemon and which Starcraft race you play.</p>')->appendChild(id(new AphrontFormTextAreaControl())->setLabel('Blurb')->setName('blurb')->setValue($profile->getBlurb()))->appendChild(id(new AphrontFormMarkupControl())->setLabel('Profile Image')->setValue(phutil_render_tag('img', array('src' => $img_src))))->appendChild(id(new AphrontFormImageControl())->setLabel('Change Image')->setName('image')->setError($e_image)->setCaption('Supported formats: ' . implode(', ', $supported_formats)))->appendChild(id(new AphrontFormSubmitControl())->setValue('Save')->addCancelButton('/p/' . $user->getUsername() . '/'));
     $panel = new AphrontPanelView();
     $panel->setHeader('Edit Profile Details');
     $panel->appendChild($form);
     $panel->setWidth(AphrontPanelView::WIDTH_FORM);
     return array($error_view, $panel);
 }
예제 #13
0
#!/usr/bin/env php
<?php 
$root = dirname(dirname(dirname(__FILE__)));
require_once $root . '/scripts/__init_script__.php';
if ($argc !== 2 || $argv[1] === '--help') {
    echo "Usage: aphrontpath.php <url>\n";
    echo "Purpose: Print controller which will process passed <url>.\n";
    exit(1);
}
$url = parse_url($argv[1]);
$path = '/' . (isset($url['path']) ? ltrim($url['path'], '/') : '');
$config_key = 'aphront.default-application-configuration-class';
$application = PhabricatorEnv::newObjectFromConfig($config_key);
$application->setRequest(new AphrontRequest('', $path));
list($controller) = $application->buildControllerForPath($path);
if (!$controller && substr($path, -1) !== '/') {
    list($controller) = $application->buildControllerForPath($path . '/');
}
if ($controller) {
    echo get_class($controller) . "\n";
}
 public static function newReplyHandlerForCommit($commit)
 {
     $reply_handler = PhabricatorEnv::newObjectFromConfig('metamta.diffusion.reply-handler');
     $reply_handler->setMailReceiver($commit);
     return $reply_handler;
 }
예제 #15
0
ini_set('include_path', $include_path . PATH_SEPARATOR . dirname(__FILE__) . '/../../');
@(include_once 'libphutil/scripts/__init_script__.php');
if (!@constant('__LIBPHUTIL__')) {
    echo "ERROR: Unable to load libphutil. Update your PHP 'include_path' to " . "include the parent directory of libphutil/.\n";
    exit(1);
}
phutil_load_library(dirname(__FILE__) . '/../src/');
// NOTE: This is dangerous in general, but we know we're in a script context and
// are not vulnerable to CSRF.
AphrontWriteGuard::allowDangerousUnguardedWrites(true);
require_once dirname(dirname(__FILE__)) . '/conf/__init_conf__.php';
$env = isset($_SERVER['PHABRICATOR_ENV']) ? $_SERVER['PHABRICATOR_ENV'] : getenv('PHABRICATOR_ENV');
if (!$env) {
    echo phutil_console_wrap(phutil_console_format("**ERROR**: PHABRICATOR_ENV Not Set\n\n" . "Define the __PHABRICATOR_ENV__ environment variable before running " . "this script. You can do it on the command line like this:\n\n" . "  \$ PHABRICATOR_ENV=__custom/myconfig__ %s ...\n\n" . "Replace __custom/myconfig__ with the path to your configuration file. " . "For more information, see the 'Configuration Guide' in the " . "Phabricator documentation.\n\n", $argv[0]));
    exit(1);
}
$conf = phabricator_read_config_file($env);
$conf['phabricator.env'] = $env;
PhabricatorEnv::setEnvConfig($conf);
phutil_load_library('arcanist/src');
foreach (PhabricatorEnv::getEnvConfig('load-libraries') as $library) {
    phutil_load_library($library);
}
PhutilErrorHandler::initialize();
PhabricatorEventEngine::initialize();
$tz = PhabricatorEnv::getEnvConfig('phabricator.timezone');
if ($tz) {
    date_default_timezone_set($tz);
}
$translation = PhabricatorEnv::newObjectFromConfig('translation.provider');
PhutilTranslator::getInstance()->setLanguage($translation->getLanguage())->addTranslations($translation->getTranslations());
 /**
  * @phutil-external-symbol class PhabricatorStartup
  */
 public static function runHTTPRequest(AphrontHTTPSink $sink)
 {
     $multimeter = MultimeterControl::newInstance();
     $multimeter->setEventContext('<http-init>');
     $multimeter->setEventViewer('<none>');
     // Build a no-op write guard for the setup phase. We'll replace this with a
     // real write guard later on, but we need to survive setup and build a
     // request object first.
     $write_guard = new AphrontWriteGuard('id');
     PhabricatorEnv::initializeWebEnvironment();
     $multimeter->setSampleRate(PhabricatorEnv::getEnvConfig('debug.sample-rate'));
     $debug_time_limit = PhabricatorEnv::getEnvConfig('debug.time-limit');
     if ($debug_time_limit) {
         PhabricatorStartup::setDebugTimeLimit($debug_time_limit);
     }
     // This is the earliest we can get away with this, we need env config first.
     PhabricatorAccessLog::init();
     $access_log = PhabricatorAccessLog::getLog();
     PhabricatorStartup::setAccessLog($access_log);
     $access_log->setData(array('R' => AphrontRequest::getHTTPHeader('Referer', '-'), 'r' => idx($_SERVER, 'REMOTE_ADDR', '-'), 'M' => idx($_SERVER, 'REQUEST_METHOD', '-')));
     DarkConsoleXHProfPluginAPI::hookProfiler();
     DarkConsoleErrorLogPluginAPI::registerErrorHandler();
     $response = PhabricatorSetupCheck::willProcessRequest();
     if ($response) {
         PhabricatorStartup::endOutputCapture();
         $sink->writeResponse($response);
         return;
     }
     $host = AphrontRequest::getHTTPHeader('Host');
     $path = $_REQUEST['__path__'];
     switch ($host) {
         default:
             $config_key = 'aphront.default-application-configuration-class';
             $application = PhabricatorEnv::newObjectFromConfig($config_key);
             break;
     }
     $application->setHost($host);
     $application->setPath($path);
     $application->willBuildRequest();
     $request = $application->buildRequest();
     // Now that we have a request, convert the write guard into one which
     // actually checks CSRF tokens.
     $write_guard->dispose();
     $write_guard = new AphrontWriteGuard(array($request, 'validateCSRF'));
     // Build the server URI implied by the request headers. If an administrator
     // has not configured "phabricator.base-uri" yet, we'll use this to generate
     // links.
     $request_protocol = $request->isHTTPS() ? 'https' : 'http';
     $request_base_uri = "{$request_protocol}://{$host}/";
     PhabricatorEnv::setRequestBaseURI($request_base_uri);
     $access_log->setData(array('U' => (string) $request->getRequestURI()->getPath()));
     $processing_exception = null;
     try {
         $response = $application->processRequest($request, $access_log, $sink, $multimeter);
         $response_code = $response->getHTTPResponseCode();
     } catch (Exception $ex) {
         $processing_exception = $ex;
         $response_code = 500;
     }
     $write_guard->dispose();
     $access_log->setData(array('c' => $response_code, 'T' => PhabricatorStartup::getMicrosecondsSinceStart()));
     $multimeter->newEvent(MultimeterEvent::TYPE_REQUEST_TIME, $multimeter->getEventContext(), PhabricatorStartup::getMicrosecondsSinceStart());
     $access_log->write();
     $multimeter->saveEvents();
     DarkConsoleXHProfPluginAPI::saveProfilerSample($access_log);
     // Add points to the rate limits for this request.
     if (isset($_SERVER['REMOTE_ADDR'])) {
         $user_ip = $_SERVER['REMOTE_ADDR'];
         // The base score for a request allows users to make 30 requests per
         // minute.
         $score = 1000 / 30;
         // If the user was logged in, let them make more requests.
         if ($request->getUser() && $request->getUser()->getPHID()) {
             $score = $score / 5;
         }
         PhabricatorStartup::addRateLimitScore($user_ip, $score);
     }
     if ($processing_exception) {
         throw $processing_exception;
     }
 }
예제 #17
0
 private function newConnection(array $options)
 {
     // If we believe the database is unhealthy, don't spend as much time
     // trying to connect to it, since it's likely to continue to fail and
     // hammering it can only make the problem worse.
     $record = $this->getHealthRecord();
     if ($record->getIsHealthy()) {
         $default_retries = 3;
         $default_timeout = 10;
     } else {
         $default_retries = 0;
         $default_timeout = 2;
     }
     $spec = $options + array('user' => $this->getUser(), 'pass' => $this->getPass(), 'host' => $this->getHost(), 'port' => $this->getPort(), 'database' => null, 'retries' => $default_retries, 'timeout' => $default_timeout);
     return PhabricatorEnv::newObjectFromConfig('mysql.implementation', array($spec));
 }
예제 #18
0
} else {
    $conn_user = $conf->getUser();
    $conn_pass = $conf->getPassword();
}
$conn_host = $conf->getHost();
// Split out port information, since the command-line client requires a
// separate flag for the port.
$uri = new PhutilURI('mysql://' . $conn_host);
if ($uri->getPort()) {
    $conn_port = $uri->getPort();
    $conn_bare_hostname = $uri->getDomain();
} else {
    $conn_port = null;
    $conn_bare_hostname = $conn_host;
}
$conn = PhabricatorEnv::newObjectFromConfig('mysql.implementation', array(array('user' => $conn_user, 'pass' => $conn_pass, 'host' => $conn_host, 'database' => null)));
try {
    $create_sql = <<<END
  CREATE DATABASE IF NOT EXISTS `phabricator_meta_data`;
END;
    queryfx($conn, $create_sql);
    $create_sql = <<<END
  CREATE TABLE IF NOT EXISTS phabricator_meta_data.`schema_version` (
    `version` INTEGER not null
  );
END;
    queryfx($conn, $create_sql);
    // Get the version only if commandline argument wasn't given
    if ($next_version === null) {
        $version = queryfx_one($conn, 'SELECT * FROM phabricator_meta_data.%T', SCHEMA_VERSION_TABLE_NAME);
        if (!$version) {
 public function generateData()
 {
     $log = PhutilServiceProfiler::getInstance()->getServiceCallLog();
     foreach ($log as $key => $entry) {
         $config = idx($entry, 'config', array());
         unset($log[$key]['config']);
         if (empty($_REQUEST['__analyze__'])) {
             $log[$key]['explain'] = array('sev' => 7, 'size' => null, 'reason' => 'Disabled');
             // Query analysis is disabled for this request, so don't do any of it.
             continue;
         }
         if ($entry['type'] != 'query') {
             continue;
         }
         // For each SELECT query, go issue an EXPLAIN on it so we can flag stuff
         // causing table scans, etc.
         if (preg_match('/^\\s*SELECT\\b/i', $entry['query'])) {
             $conn = PhabricatorEnv::newObjectFromConfig('mysql.implementation', array($entry['config']));
             try {
                 $explain = queryfx_all($conn, 'EXPLAIN %Q', $entry['query']);
                 $badness = 0;
                 $size = 1;
                 $reason = null;
                 foreach ($explain as $table) {
                     $size *= (int) $table['rows'];
                     switch ($table['type']) {
                         case 'index':
                             $cur_badness = 1;
                             $cur_reason = 'Index';
                             break;
                         case 'const':
                             $cur_badness = 1;
                             $cur_reason = 'Const';
                             break;
                         case 'eq_ref':
                             $cur_badness = 2;
                             $cur_reason = 'EqRef';
                             break;
                         case 'range':
                             $cur_badness = 3;
                             $cur_reason = 'Range';
                             break;
                         case 'ref':
                             $cur_badness = 3;
                             $cur_reason = 'Ref';
                             break;
                         case 'ALL':
                             if (preg_match('/Using where/', $table['Extra'])) {
                                 if ($table['rows'] < 256 && !empty($table['possible_keys'])) {
                                     $cur_badness = 2;
                                     $cur_reason = 'Small Table Scan';
                                 } else {
                                     $cur_badness = 6;
                                     $cur_reason = 'TABLE SCAN!';
                                 }
                             } else {
                                 $cur_badness = 3;
                                 $cur_reason = 'Whole Table';
                             }
                             break;
                         default:
                             if (preg_match('/No tables used/i', $table['Extra'])) {
                                 $cur_badness = 1;
                                 $cur_reason = 'No Tables';
                             } else {
                                 if (preg_match('/Impossible/i', $table['Extra'])) {
                                     $cur_badness = 1;
                                     $cur_reason = 'Empty';
                                 } else {
                                     $cur_badness = 4;
                                     $cur_reason = "Can't Analyze";
                                 }
                             }
                             break;
                     }
                     if ($cur_badness > $badness) {
                         $badness = $cur_badness;
                         $reason = $cur_reason;
                     }
                 }
                 $log[$key]['explain'] = array('sev' => $badness, 'size' => $size, 'reason' => $reason);
             } catch (Exception $ex) {
                 $log[$key]['explain'] = array('sev' => 5, 'size' => null, 'reason' => $ex->getMessage());
             }
         }
     }
     return array('start' => $GLOBALS['__start__'], 'end' => microtime(true), 'log' => $log);
 }
예제 #20
0
 private function newBasicConnection($database, $mode, $namespace)
 {
     $conf = PhabricatorEnv::newObjectFromConfig('mysql.configuration-provider', array($this, $mode, $namespace));
     return PhabricatorEnv::newObjectFromConfig('mysql.implementation', array(array('user' => $conf->getUser(), 'pass' => $conf->getPassword(), 'host' => $conf->getHost(), 'port' => $conf->getPort(), 'database' => $database, 'retries' => 3)));
 }
예제 #21
0
 public static final function newExtensions()
 {
     $key = 'maniphest.custom-task-extensions-class';
     return PhabricatorEnv::newObjectFromConfig($key);
 }
예제 #22
0
 protected function buildReplyHandler(PhabricatorLiskDAO $object)
 {
     $reply_handler = PhabricatorEnv::newObjectFromConfig('metamta.diffusion.reply-handler');
     $reply_handler->setMailReceiver($object);
     return $reply_handler;
 }
 public static final function newSelector()
 {
     return PhabricatorEnv::newObjectFromConfig('differential.field-selector');
 }
 public function buildReplyHandler(ManiphestTask $task)
 {
     $handler_object = PhabricatorEnv::newObjectFromConfig('metamta.maniphest.reply-handler');
     $handler_object->setMailReceiver($task);
     return $handler_object;
 }
예제 #25
0
require_once $root . '/scripts/__init_script__.php';
$args = new PhutilArgumentParser($argv);
$args->setTagline(pht('manage Phabricator storage and schemata'));
$args->setSynopsis(<<<EOHELP
**storage** __workflow__ [__options__]
Manage Phabricator database storage and schema versioning.

**storage** upgrade
Initialize or upgrade Phabricator storage.

**storage** upgrade --user __root__ --password __hunter2__
Use administrative credentials for schema changes.
EOHELP
);
$args->parseStandardArguments();
$conf = PhabricatorEnv::newObjectFromConfig('mysql.configuration-provider', array($dao = null, 'w'));
$default_user = $conf->getUser();
$default_host = $conf->getHost();
$default_port = $conf->getPort();
$default_namespace = PhabricatorLiskDAO::getDefaultStorageNamespace();
try {
    $args->parsePartial(array(array('name' => 'force', 'short' => 'f', 'help' => pht('Do not prompt before performing dangerous operations.')), array('name' => 'user', 'short' => 'u', 'param' => 'username', 'default' => $default_user, 'help' => pht("Connect with __username__ instead of the configured default ('%s').", $default_user)), array('name' => 'password', 'short' => 'p', 'param' => 'password', 'help' => pht('Use __password__ instead of the configured default.')), array('name' => 'namespace', 'param' => 'name', 'default' => $default_namespace, 'help' => pht("Use namespace __namespace__ instead of the configured " . "default ('%s'). This is an advanced feature used by unit tests; " . "you should not normally use this flag.", $default_namespace)), array('name' => 'dryrun', 'help' => pht('Do not actually change anything, just show what would be changed.')), array('name' => 'disable-utf8mb4', 'help' => pht('Disable utf8mb4, even if the database supports it. This is an ' . 'advanced feature used for testing changes to Phabricator; you ' . 'should not normally use this flag.'))));
} catch (PhutilArgumentUsageException $ex) {
    $args->printUsageException($ex);
    exit(77);
}
// First, test that the Phabricator configuration is set up correctly. After
// we know this works we'll test any administrative credentials specifically.
$test_api = new PhabricatorStorageManagementAPI();
$test_api->setUser($default_user);
$test_api->setHost($default_host);
예제 #26
0
 /**
  * @task config
  */
 public function establishLiveConnection($mode)
 {
     $namespace = self::getStorageNamespace();
     $conf = PhabricatorEnv::newObjectFromConfig('mysql.configuration-provider', array($this, $mode, $namespace));
     $retries = PhabricatorEnv::getEnvConfig('mysql.connection-retries');
     return PhabricatorEnv::newObjectFromConfig('mysql.implementation', array(array('user' => $conf->getUser(), 'pass' => $conf->getPassword(), 'host' => $conf->getHost(), 'database' => $conf->getDatabase(), 'retries' => $retries)));
 }
 public function getConn($fragment, $select_database = true)
 {
     return PhabricatorEnv::newObjectFromConfig('mysql.implementation', array(array('user' => $this->user, 'pass' => $this->password, 'host' => $this->host, 'database' => $select_database ? $this->getDatabaseName($fragment) : null)));
 }
 public static final function newSelector()
 {
     return PhabricatorEnv::newObjectFromConfig('search.engine-selector');
 }
예제 #29
0
 public static function newReplyHandlerForRevision(DifferentialRevision $revision)
 {
     $reply_handler = PhabricatorEnv::newObjectFromConfig('metamta.differential.reply-handler');
     $reply_handler->setMailReceiver($revision);
     return $reply_handler;
 }
예제 #30
0
 private function newReplyHandler()
 {
     $reply_handler = PhabricatorEnv::newObjectFromConfig('metamta.package.reply-handler');
     $reply_handler->setMailReceiver($this->getPackage());
     return $reply_handler;
 }