Page MenuHomestyx hydra

No OneTemporary

diff --git a/src/applications/people/query/PhabricatorPeopleSearchEngine.php b/src/applications/people/query/PhabricatorPeopleSearchEngine.php
index c1ec65cb76..f141b256c6 100644
--- a/src/applications/people/query/PhabricatorPeopleSearchEngine.php
+++ b/src/applications/people/query/PhabricatorPeopleSearchEngine.php
@@ -1,330 +1,253 @@
<?php
final class PhabricatorPeopleSearchEngine
extends PhabricatorApplicationSearchEngine {
public function getResultTypeDescription() {
return pht('Users');
}
public function getApplicationClassName() {
return 'PhabricatorPeopleApplication';
}
- public function getCustomFieldObject() {
+ public function newResultObject() {
return new PhabricatorUser();
}
- public function buildSavedQueryFromRequest(AphrontRequest $request) {
- $saved = new PhabricatorSavedQuery();
-
- $saved->setParameter('usernames', $request->getStrList('usernames'));
- $saved->setParameter('nameLike', $request->getStr('nameLike'));
-
- $saved->setParameter(
- 'isAdmin',
- $this->readBoolFromRequest($request, 'isAdmin'));
-
- $saved->setParameter(
- 'isDisabled',
- $this->readBoolFromRequest($request, 'isDisabled'));
-
- $saved->setParameter(
- 'isSystemAgent',
- $this->readBoolFromRequest($request, 'isSystemAgent'));
-
- $saved->setParameter(
- 'isMailingList',
- $this->readBoolFromRequest($request, 'isMailingList'));
-
- $saved->setParameter(
- 'needsApproval',
- $this->readBoolFromRequest($request, 'needsApproval'));
-
- $saved->setParameter('createdStart', $request->getStr('createdStart'));
- $saved->setParameter('createdEnd', $request->getStr('createdEnd'));
-
- $this->readCustomFieldsFromRequest($request, $saved);
+ protected function buildCustomSearchFields() {
+ return array(
+ id(new PhabricatorSearchStringListField())
+ ->setLabel(pht('Usernames'))
+ ->setKey('usernames')
+ ->setAliases(array('username')),
+ id(new PhabricatorSearchTextField())
+ ->setLabel(pht('Name Contains'))
+ ->setKey('nameLike'),
+ id(new PhabricatorSearchThreeStateField())
+ ->setLabel(pht('Administrators'))
+ ->setKey('isAdmin')
+ ->setOptions(
+ pht('(Show All)'),
+ pht('Show Only Administrators'),
+ pht('Hide Administrators')),
+ id(new PhabricatorSearchThreeStateField())
+ ->setLabel(pht('Disabled'))
+ ->setKey('isDisabled')
+ ->setOptions(
+ pht('(Show All)'),
+ pht('Show Only Disabled Users'),
+ pht('Hide Disabled Users')),
+ id(new PhabricatorSearchThreeStateField())
+ ->setLabel(pht('Bots'))
+ ->setKey('isSystemAgent')
+ ->setOptions(
+ pht('(Show All)'),
+ pht('Show Only Bots'),
+ pht('Hide Bots')),
+ id(new PhabricatorSearchThreeStateField())
+ ->setLabel(pht('Mailing Lists'))
+ ->setKey('isMailingList')
+ ->setOptions(
+ pht('(Show All)'),
+ pht('Show Only Mailing Lists'),
+ pht('Hide Mailing Lists')),
+ id(new PhabricatorSearchThreeStateField())
+ ->setLabel(pht('Needs Approval'))
+ ->setKey('needsApproval')
+ ->setOptions(
+ pht('(Show All)'),
+ pht('Show Only Unapproved Users'),
+ pht('Hide Unappproved Users')),
+ id(new PhabricatorSearchDateField())
+ ->setKey('createdStart')
+ ->setLabel(pht('Joined After')),
+ id(new PhabricatorSearchDateField())
+ ->setKey('createdEnd')
+ ->setLabel(pht('Joined Before')),
+ );
+ }
- return $saved;
+ protected function getDefaultFieldOrder() {
+ return array(
+ '...',
+ 'createdStart',
+ 'createdEnd',
+ );
}
- public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) {
+ public function buildQueryFromParameters(array $map) {
$query = id(new PhabricatorPeopleQuery())
->needPrimaryEmail(true)
->needProfileImage(true);
$viewer = $this->requireViewer();
// If the viewer can't browse the user directory, restrict the query to
// just the user's own profile. This is a little bit silly, but serves to
// restrict users from creating a dashboard panel which essentially just
// contains a user directory anyway.
$can_browse = PhabricatorPolicyFilter::hasCapability(
$viewer,
$this->getApplication(),
PeopleBrowseUserDirectoryCapability::CAPABILITY);
if (!$can_browse) {
$query->withPHIDs(array($viewer->getPHID()));
}
- $usernames = $saved->getParameter('usernames', array());
- if ($usernames) {
- $query->withUsernames($usernames);
+ if ($map['usernames']) {
+ $query->withUsernames($map['usernames']);
}
- $like = $saved->getParameter('nameLike');
- if ($like) {
- $query->withNameLike($like);
+ if ($map['nameLike']) {
+ $query->withNameLike($map['nameLike']);
}
- $is_admin = $saved->getParameter('isAdmin');
- $is_disabled = $saved->getParameter('isDisabled');
- $is_system_agent = $saved->getParameter('isSystemAgent');
- $is_mailing_list = $saved->getParameter('isMailingList');
- $needs_approval = $saved->getParameter('needsApproval');
-
- if ($is_admin !== null) {
- $query->withIsAdmin($is_admin);
+ if ($map['isAdmin'] !== null) {
+ $query->withIsAdmin($map['isAdmin']);
}
- if ($is_disabled !== null) {
- $query->withIsDisabled($is_disabled);
+ if ($map['isDisabled'] !== null) {
+ $query->withIsDisabled($map['isDisabled']);
}
- if ($is_system_agent !== null) {
- $query->withIsSystemAgent($is_system_agent);
+ if ($map['isMailingList'] !== null) {
+ $query->withIsMailingList($map['isMailingList']);
}
- if ($is_mailing_list !== null) {
- $query->withIsMailingList($is_mailing_list);
+ if ($map['isSystemAgent'] !== null) {
+ $query->withIsSystemAgent($map['isSystemAgent']);
}
- if ($needs_approval !== null) {
- $query->withIsApproved(!$needs_approval);
+ if ($map['needsApproval'] !== null) {
+ $query->withIsApproved(!$map['needsApproval']);
}
- $start = $this->parseDateTime($saved->getParameter('createdStart'));
- $end = $this->parseDateTime($saved->getParameter('createdEnd'));
-
- if ($start) {
- $query->withDateCreatedAfter($start);
+ if ($map['createdStart']) {
+ $query->withDateCreatedAfter($map['createdStart']);
}
- if ($end) {
- $query->withDateCreatedBefore($end);
+ if ($map['createdEnd']) {
+ $query->withDateCreatedBefore($map['createdEnd']);
}
- $this->applyCustomFieldsToQuery($query, $saved);
-
return $query;
}
- public function buildSearchForm(
- AphrontFormView $form,
- PhabricatorSavedQuery $saved) {
-
- $usernames = $saved->getParameter('usernames', array());
- $like = $saved->getParameter('nameLike');
-
- $is_admin = $this->getBoolFromQuery($saved, 'isAdmin');
- $is_disabled = $this->getBoolFromQuery($saved, 'isDisabled');
- $is_system_agent = $this->getBoolFromQuery($saved, 'isSystemAgent');
- $is_mailing_list = $this->getBoolFromQuery($saved, 'isMailingList');
- $needs_approval = $this->getBoolFromQuery($saved, 'needsApproval');
-
- $form
- ->appendChild(
- id(new AphrontFormTextControl())
- ->setName('usernames')
- ->setLabel(pht('Usernames'))
- ->setValue(implode(', ', $usernames)))
- ->appendChild(
- id(new AphrontFormTextControl())
- ->setName('nameLike')
- ->setLabel(pht('Name Contains'))
- ->setValue($like))
- ->appendChild(
- id(new AphrontFormSelectControl())
- ->setName('isAdmin')
- ->setLabel(pht('Administrators'))
- ->setValue($is_admin)
- ->setOptions(
- array(
- '' => pht('(Show All)'),
- 'true' => pht('Show Only Administrators'),
- 'false' => pht('Hide Administrators'),
- )))
- ->appendChild(
- id(new AphrontFormSelectControl())
- ->setName('isDisabled')
- ->setLabel(pht('Disabled'))
- ->setValue($is_disabled)
- ->setOptions(
- array(
- '' => pht('(Show All)'),
- 'true' => pht('Show Only Disabled Users'),
- 'false' => pht('Hide Disabled Users'),
- )))
- ->appendChild(
- id(new AphrontFormSelectControl())
- ->setName('isSystemAgent')
- ->setLabel(pht('Bots'))
- ->setValue($is_system_agent)
- ->setOptions(
- array(
- '' => pht('(Show All)'),
- 'true' => pht('Show Only Bots'),
- 'false' => pht('Hide Bots'),
- )))
- ->appendChild(
- id(new AphrontFormSelectControl())
- ->setName('isMailingList')
- ->setLabel(pht('Mailing Lists'))
- ->setValue($is_mailing_list)
- ->setOptions(
- array(
- '' => pht('(Show All)'),
- 'true' => pht('Show Only Mailing Lists'),
- 'false' => pht('Hide Mailing Lists'),
- )))
- ->appendChild(
- id(new AphrontFormSelectControl())
- ->setName('needsApproval')
- ->setLabel(pht('Needs Approval'))
- ->setValue($needs_approval)
- ->setOptions(
- array(
- '' => pht('(Show All)'),
- 'true' => pht('Show Only Unapproved Users'),
- 'false' => pht('Hide Unapproved Users'),
- )));
-
- $this->appendCustomFieldsToForm($form, $saved);
-
- $this->buildDateRange(
- $form,
- $saved,
- 'createdStart',
- pht('Joined After'),
- 'createdEnd',
- pht('Joined Before'));
- }
-
protected function getURI($path) {
return '/people/'.$path;
}
protected function getBuiltinQueryNames() {
$names = array(
'active' => pht('Active'),
'all' => pht('All'),
);
$viewer = $this->requireViewer();
if ($viewer->getIsAdmin()) {
$names['approval'] = pht('Approval Queue');
}
return $names;
}
public function buildSavedQueryFromBuiltin($query_key) {
$query = $this->newSavedQuery();
$query->setQueryKey($query_key);
switch ($query_key) {
case 'all':
return $query;
case 'active':
return $query
->setParameter('isDisabled', false);
case 'approval':
return $query
->setParameter('needsApproval', true)
->setParameter('isDisabled', false);
}
return parent::buildSavedQueryFromBuiltin($query_key);
}
protected function renderResultList(
array $users,
PhabricatorSavedQuery $query,
array $handles) {
assert_instances_of($users, 'PhabricatorUser');
$request = $this->getRequest();
$viewer = $this->requireViewer();
$list = new PHUIObjectItemListView();
$is_approval = ($query->getQueryKey() == 'approval');
foreach ($users as $user) {
$primary_email = $user->loadPrimaryEmail();
if ($primary_email && $primary_email->getIsVerified()) {
$email = pht('Verified');
} else {
$email = pht('Unverified');
}
$item = new PHUIObjectItemView();
$item->setHeader($user->getFullName())
->setHref('/p/'.$user->getUsername().'/')
->addAttribute(phabricator_datetime($user->getDateCreated(), $viewer))
->addAttribute($email)
->setImageURI($user->getProfileImageURI());
if ($is_approval && $primary_email) {
$item->addAttribute($primary_email->getAddress());
}
if ($user->getIsDisabled()) {
$item->addIcon('fa-ban', pht('Disabled'));
}
if (!$is_approval) {
if (!$user->getIsApproved()) {
$item->addIcon('fa-clock-o', pht('Needs Approval'));
}
}
if ($user->getIsAdmin()) {
$item->addIcon('fa-star', pht('Admin'));
}
if ($user->getIsSystemAgent()) {
$item->addIcon('fa-desktop', pht('Bot'));
}
if ($user->getIsMailingList()) {
$item->addIcon('fa-envelope-o', pht('Mailing List'));
}
if ($viewer->getIsAdmin()) {
$user_id = $user->getID();
if ($is_approval) {
$item->addAction(
id(new PHUIListItemView())
->setIcon('fa-ban')
->setName(pht('Disable'))
->setWorkflow(true)
->setHref($this->getApplicationURI('disapprove/'.$user_id.'/')));
$item->addAction(
id(new PHUIListItemView())
->setIcon('fa-thumbs-o-up')
->setName(pht('Approve'))
->setWorkflow(true)
->setHref($this->getApplicationURI('approve/'.$user_id.'/')));
}
}
$list->addItem($item);
}
return $list;
}
}
diff --git a/src/applications/search/engine/PhabricatorApplicationSearchEngine.php b/src/applications/search/engine/PhabricatorApplicationSearchEngine.php
index 569b1ba234..84c7743d1f 100644
--- a/src/applications/search/engine/PhabricatorApplicationSearchEngine.php
+++ b/src/applications/search/engine/PhabricatorApplicationSearchEngine.php
@@ -1,1137 +1,1204 @@
<?php
/**
* Represents an abstract search engine for an application. It supports
* creating and storing saved queries.
*
* @task construct Constructing Engines
* @task app Applications
* @task builtin Builtin Queries
* @task uri Query URIs
* @task dates Date Filters
* @task order Result Ordering
* @task read Reading Utilities
* @task exec Paging and Executing Queries
* @task render Rendering Results
*/
abstract class PhabricatorApplicationSearchEngine extends Phobject {
private $application;
private $viewer;
private $errors = array();
private $customFields = false;
private $request;
private $context;
const CONTEXT_LIST = 'list';
const CONTEXT_PANEL = 'panel';
public function newResultObject() {
return null;
}
public function setViewer(PhabricatorUser $viewer) {
$this->viewer = $viewer;
return $this;
}
protected function requireViewer() {
if (!$this->viewer) {
throw new PhutilInvalidStateException('setViewer');
}
return $this->viewer;
}
public function setContext($context) {
$this->context = $context;
return $this;
}
public function isPanelContext() {
return ($this->context == self::CONTEXT_PANEL);
}
public function canUseInPanelContext() {
return true;
}
public function saveQuery(PhabricatorSavedQuery $query) {
$query->setEngineClassName(get_class($this));
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
try {
$query->save();
} catch (AphrontDuplicateKeyQueryException $ex) {
// Ignore, this is just a repeated search.
}
unset($unguarded);
}
/**
* Create a saved query object from the request.
*
* @param AphrontRequest The search request.
* @return PhabricatorSavedQuery
*/
public function buildSavedQueryFromRequest(AphrontRequest $request) {
$fields = $this->buildSearchFields();
$viewer = $this->requireViewer();
$saved = new PhabricatorSavedQuery();
foreach ($fields as $field) {
$field->setViewer($viewer);
$value = $field->readValueFromRequest($request);
$saved->setParameter($field->getKey(), $value);
}
return $saved;
}
/**
* Executes the saved query.
*
* @param PhabricatorSavedQuery The saved query to operate on.
* @return The result of the query.
*/
public function buildQueryFromSavedQuery(PhabricatorSavedQuery $saved) {
$fields = $this->buildSearchFields();
$viewer = $this->requireViewer();
$parameters = array();
foreach ($fields as $field) {
$field->setViewer($viewer);
$field->readValueFromSavedQuery($saved);
$value = $field->getValueForQuery($field->getValue());
$parameters[$field->getKey()] = $value;
}
$query = $this->buildQueryFromParameters($parameters);
$object = $this->newResultObject();
if (!$object) {
return $query;
}
if ($object instanceof PhabricatorProjectInterface) {
if (!empty($parameters['projectPHIDs'])) {
$query->withEdgeLogicConstraints(
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
$parameters['projectPHIDs']);
}
}
if ($object instanceof PhabricatorSpacesInterface) {
if (!empty($parameters['spacePHIDs'])) {
$query->withSpacePHIDs($parameters['spacePHIDs']);
}
}
if ($object instanceof PhabricatorCustomFieldInterface) {
$this->applyCustomFieldsToQuery($query, $saved);
}
return $query;
}
protected function buildQueryFromParameters(array $parameters) {
throw new PhutilMethodNotImplementedException();
}
/**
* Builds the search form using the request.
*
* @param AphrontFormView Form to populate.
* @param PhabricatorSavedQuery The query from which to build the form.
* @return void
*/
public function buildSearchForm(
AphrontFormView $form,
PhabricatorSavedQuery $saved) {
$fields = $this->buildSearchFields();
$viewer = $this->requireViewer();
foreach ($fields as $field) {
$field->setViewer($viewer);
$field->readValueFromSavedQuery($saved);
}
foreach ($fields as $field) {
foreach ($field->getErrors() as $error) {
$this->addError(last($error));
}
}
foreach ($fields as $field) {
$field->appendToForm($form);
}
}
protected function buildSearchFields() {
$fields = array();
foreach ($this->buildCustomSearchFields() as $field) {
$fields[] = $field;
}
$object = $this->newResultObject();
if (!$object) {
return $fields;
}
if ($object instanceof PhabricatorProjectInterface) {
$fields[] = id(new PhabricatorSearchProjectsField())
->setKey('projectPHIDs')
->setAliases(array('project', 'projects'))
->setLabel(pht('Projects'));
}
if ($object instanceof PhabricatorSpacesInterface) {
if (PhabricatorSpacesNamespaceQuery::getSpacesExist()) {
$fields[] = id(new PhabricatorSearchSpacesField())
->setKey('spacePHIDs')
->setAliases(array('space', 'spaces'))
->setLabel(pht('Spaces'));
}
}
foreach ($this->buildCustomFieldSearchFields() as $custom_field) {
$fields[] = $custom_field;
}
- return $fields;
+ $field_map = array();
+ foreach ($fields as $field) {
+ $key = $field->getKey();
+ if (isset($field_map[$key])) {
+ throw new Exception(
+ pht(
+ 'Two fields in this SearchEngine use the same key ("%s"), but '.
+ 'each field must use a unique key.',
+ $key));
+ }
+ $field_map[$key] = $field;
+ }
+
+ return $this->adjustFieldsForDisplay($field_map);
+ }
+
+ private function adjustFieldsForDisplay(array $field_map) {
+ $order = $this->getDefaultFieldOrder();
+
+ $head_keys = array();
+ $tail_keys = array();
+ $seen_tail = false;
+ foreach ($order as $order_key) {
+ if ($order_key === '...') {
+ $seen_tail = true;
+ continue;
+ }
+
+ if (!$seen_tail) {
+ $head_keys[] = $order_key;
+ } else {
+ $tail_keys[] = $order_key;
+ }
+ }
+
+ $head = array_select_keys($field_map, $head_keys);
+ $body = array_diff_key($field_map, array_fuse($tail_keys));
+ $tail = array_select_keys($field_map, $tail_keys);
+
+ return $head + $body + $tail;
}
protected function buildCustomSearchFields() {
throw new PhutilMethodNotImplementedException();
}
+
+ /**
+ * Define the default display order for fields by returning a list of
+ * field keys.
+ *
+ * You can use the special key `...` to mean "all unspecified fields go
+ * here". This lets you easily put important fields at the top of the form,
+ * standard fields in the middle of the form, and less important fields at
+ * the bottom.
+ *
+ * For example, you might return a list like this:
+ *
+ * return array(
+ * 'authorPHIDs',
+ * 'reviewerPHIDs',
+ * '...',
+ * 'createdAfter',
+ * 'createdBefore',
+ * );
+ *
+ * Any unspecified fields (including custom fields and fields added
+ * automatically by infrastruture) will be put in the middle.
+ *
+ * @return list<string> Default ordering for field keys.
+ */
+ protected function getDefaultFieldOrder() {
+ return array();
+ }
+
public function getErrors() {
return $this->errors;
}
public function addError($error) {
$this->errors[] = $error;
return $this;
}
/**
* Return an application URI corresponding to the results page of a query.
* Normally, this is something like `/application/query/QUERYKEY/`.
*
* @param string The query key to build a URI for.
* @return string URI where the query can be executed.
* @task uri
*/
public function getQueryResultsPageURI($query_key) {
return $this->getURI('query/'.$query_key.'/');
}
/**
* Return an application URI for query management. This is used when, e.g.,
* a query deletion operation is cancelled.
*
* @return string URI where queries can be managed.
* @task uri
*/
public function getQueryManagementURI() {
return $this->getURI('query/edit/');
}
/**
* Return the URI to a path within the application. Used to construct default
* URIs for management and results.
*
* @return string URI to path.
* @task uri
*/
abstract protected function getURI($path);
/**
* Return a human readable description of the type of objects this query
* searches for.
*
* For example, "Tasks" or "Commits".
*
* @return string Human-readable description of what this engine is used to
* find.
*/
abstract public function getResultTypeDescription();
public function newSavedQuery() {
return id(new PhabricatorSavedQuery())
->setEngineClassName(get_class($this));
}
public function addNavigationItems(PHUIListView $menu) {
$viewer = $this->requireViewer();
$menu->newLabel(pht('Queries'));
$named_queries = $this->loadEnabledNamedQueries();
foreach ($named_queries as $query) {
$key = $query->getQueryKey();
$uri = $this->getQueryResultsPageURI($key);
$menu->newLink($query->getQueryName(), $uri, 'query/'.$key);
}
if ($viewer->isLoggedIn()) {
$manage_uri = $this->getQueryManagementURI();
$menu->newLink(pht('Edit Queries...'), $manage_uri, 'query/edit');
}
$menu->newLabel(pht('Search'));
$advanced_uri = $this->getQueryResultsPageURI('advanced');
$menu->newLink(pht('Advanced Search'), $advanced_uri, 'query/advanced');
return $this;
}
public function loadAllNamedQueries() {
$viewer = $this->requireViewer();
$named_queries = id(new PhabricatorNamedQueryQuery())
->setViewer($viewer)
->withUserPHIDs(array($viewer->getPHID()))
->withEngineClassNames(array(get_class($this)))
->execute();
$named_queries = mpull($named_queries, null, 'getQueryKey');
$builtin = $this->getBuiltinQueries($viewer);
$builtin = mpull($builtin, null, 'getQueryKey');
foreach ($named_queries as $key => $named_query) {
if ($named_query->getIsBuiltin()) {
if (isset($builtin[$key])) {
$named_queries[$key]->setQueryName($builtin[$key]->getQueryName());
unset($builtin[$key]);
} else {
unset($named_queries[$key]);
}
}
unset($builtin[$key]);
}
$named_queries = msort($named_queries, 'getSortKey');
return $named_queries + $builtin;
}
public function loadEnabledNamedQueries() {
$named_queries = $this->loadAllNamedQueries();
foreach ($named_queries as $key => $named_query) {
if ($named_query->getIsBuiltin() && $named_query->getIsDisabled()) {
unset($named_queries[$key]);
}
}
return $named_queries;
}
protected function setQueryProjects(
PhabricatorCursorPagedPolicyAwareQuery $query,
PhabricatorSavedQuery $saved) {
$datasource = id(new PhabricatorProjectLogicalDatasource())
->setViewer($this->requireViewer());
$projects = $saved->getParameter('projects', array());
$constraints = $datasource->evaluateTokens($projects);
if ($constraints) {
$query->withEdgeLogicConstraints(
PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
$constraints);
}
}
/* -( Applications )------------------------------------------------------- */
protected function getApplicationURI($path = '') {
return $this->getApplication()->getApplicationURI($path);
}
protected function getApplication() {
if (!$this->application) {
$class = $this->getApplicationClassName();
$this->application = id(new PhabricatorApplicationQuery())
->setViewer($this->requireViewer())
->withClasses(array($class))
->withInstalled(true)
->executeOne();
if (!$this->application) {
throw new Exception(
pht(
'Application "%s" is not installed!',
$class));
}
}
return $this->application;
}
abstract public function getApplicationClassName();
/* -( Constructing Engines )----------------------------------------------- */
/**
* Load all available application search engines.
*
* @return list<PhabricatorApplicationSearchEngine> All available engines.
* @task construct
*/
public static function getAllEngines() {
$engines = id(new PhutilSymbolLoader())
->setAncestorClass(__CLASS__)
->loadObjects();
return $engines;
}
/**
* Get an engine by class name, if it exists.
*
* @return PhabricatorApplicationSearchEngine|null Engine, or null if it does
* not exist.
* @task construct
*/
public static function getEngineByClassName($class_name) {
return idx(self::getAllEngines(), $class_name);
}
/* -( Builtin Queries )---------------------------------------------------- */
/**
* @task builtin
*/
public function getBuiltinQueries() {
$names = $this->getBuiltinQueryNames();
$queries = array();
$sequence = 0;
foreach ($names as $key => $name) {
$queries[$key] = id(new PhabricatorNamedQuery())
->setUserPHID($this->requireViewer()->getPHID())
->setEngineClassName(get_class($this))
->setQueryName($name)
->setQueryKey($key)
->setSequence((1 << 24) + $sequence++)
->setIsBuiltin(true);
}
return $queries;
}
/**
* @task builtin
*/
public function getBuiltinQuery($query_key) {
if (!$this->isBuiltinQuery($query_key)) {
throw new Exception(pht("'%s' is not a builtin!", $query_key));
}
return idx($this->getBuiltinQueries(), $query_key);
}
/**
* @task builtin
*/
protected function getBuiltinQueryNames() {
return array();
}
/**
* @task builtin
*/
public function isBuiltinQuery($query_key) {
$builtins = $this->getBuiltinQueries();
return isset($builtins[$query_key]);
}
/**
* @task builtin
*/
public function buildSavedQueryFromBuiltin($query_key) {
throw new Exception(pht("Builtin '%s' is not supported!", $query_key));
}
/* -( Reading Utilities )--------------------------------------------------- */
/**
* Read a list of user PHIDs from a request in a flexible way. This method
* supports either of these forms:
*
* users[]=alincoln&users[]=htaft
* users=alincoln,htaft
*
* Additionally, users can be specified either by PHID or by name.
*
* The main goal of this flexibility is to allow external programs to generate
* links to pages (like "alincoln's open revisions") without needing to make
* API calls.
*
* @param AphrontRequest Request to read user PHIDs from.
* @param string Key to read in the request.
* @param list<const> Other permitted PHID types.
* @return list<phid> List of user PHIDs and selector functions.
* @task read
*/
protected function readUsersFromRequest(
AphrontRequest $request,
$key,
array $allow_types = array()) {
$list = $this->readListFromRequest($request, $key);
$phids = array();
$names = array();
$allow_types = array_fuse($allow_types);
$user_type = PhabricatorPeopleUserPHIDType::TYPECONST;
foreach ($list as $item) {
$type = phid_get_type($item);
if ($type == $user_type) {
$phids[] = $item;
} else if (isset($allow_types[$type])) {
$phids[] = $item;
} else {
if (PhabricatorTypeaheadDatasource::isFunctionToken($item)) {
// If this is a function, pass it through unchanged; we'll evaluate
// it later.
$phids[] = $item;
} else {
$names[] = $item;
}
}
}
if ($names) {
$users = id(new PhabricatorPeopleQuery())
->setViewer($this->requireViewer())
->withUsernames($names)
->execute();
foreach ($users as $user) {
$phids[] = $user->getPHID();
}
$phids = array_unique($phids);
}
return $phids;
}
/**
* Read a list of project PHIDs from a request in a flexible way.
*
* @param AphrontRequest Request to read user PHIDs from.
* @param string Key to read in the request.
* @return list<phid> List of projet PHIDs and selector functions.
* @task read
*/
protected function readProjectsFromRequest(AphrontRequest $request, $key) {
$list = $this->readListFromRequest($request, $key);
$phids = array();
$slugs = array();
$project_type = PhabricatorProjectProjectPHIDType::TYPECONST;
foreach ($list as $item) {
$type = phid_get_type($item);
if ($type == $project_type) {
$phids[] = $item;
} else {
if (PhabricatorTypeaheadDatasource::isFunctionToken($item)) {
// If this is a function, pass it through unchanged; we'll evaluate
// it later.
$phids[] = $item;
} else {
$slugs[] = $item;
}
}
}
if ($slugs) {
$projects = id(new PhabricatorProjectQuery())
->setViewer($this->requireViewer())
->withSlugs($slugs)
->execute();
foreach ($projects as $project) {
$phids[] = $project->getPHID();
}
$phids = array_unique($phids);
}
return $phids;
}
/**
* Read a list of subscribers from a request in a flexible way.
*
* @param AphrontRequest Request to read PHIDs from.
* @param string Key to read in the request.
* @return list<phid> List of object PHIDs.
* @task read
*/
protected function readSubscribersFromRequest(
AphrontRequest $request,
$key) {
return $this->readUsersFromRequest(
$request,
$key,
array(
PhabricatorProjectProjectPHIDType::TYPECONST,
));
}
/**
* Read a list of generic PHIDs from a request in a flexible way. Like
* @{method:readUsersFromRequest}, this method supports either array or
* comma-delimited forms. Objects can be specified either by PHID or by
* object name.
*
* @param AphrontRequest Request to read PHIDs from.
* @param string Key to read in the request.
* @param list<const> Optional, list of permitted PHID types.
* @return list<phid> List of object PHIDs.
*
* @task read
*/
protected function readPHIDsFromRequest(
AphrontRequest $request,
$key,
array $allow_types = array()) {
$list = $this->readListFromRequest($request, $key);
$objects = id(new PhabricatorObjectQuery())
->setViewer($this->requireViewer())
->withNames($list)
->execute();
$list = mpull($objects, 'getPHID');
if (!$list) {
return array();
}
// If only certain PHID types are allowed, filter out all the others.
if ($allow_types) {
$allow_types = array_fuse($allow_types);
foreach ($list as $key => $phid) {
if (empty($allow_types[phid_get_type($phid)])) {
unset($list[$key]);
}
}
}
return $list;
}
/**
* Read a list of items from the request, in either array format or string
* format:
*
* list[]=item1&list[]=item2
* list=item1,item2
*
* This provides flexibility when constructing URIs, especially from external
* sources.
*
* @param AphrontRequest Request to read strings from.
* @param string Key to read in the request.
* @return list<string> List of values.
*/
protected function readListFromRequest(
AphrontRequest $request,
$key) {
$list = $request->getArr($key, null);
if ($list === null) {
$list = $request->getStrList($key);
}
if (!$list) {
return array();
}
return $list;
}
protected function readDateFromRequest(
AphrontRequest $request,
$key) {
$value = AphrontFormDateControlValue::newFromRequest($request, $key);
if ($value->isEmpty()) {
return null;
}
return $value->getDictionary();
}
protected function readBoolFromRequest(
AphrontRequest $request,
$key) {
if (!strlen($request->getStr($key))) {
return null;
}
return $request->getBool($key);
}
protected function getBoolFromQuery(PhabricatorSavedQuery $query, $key) {
$value = $query->getParameter($key);
if ($value === null) {
return $value;
}
return $value ? 'true' : 'false';
}
/* -( Dates )-------------------------------------------------------------- */
/**
* @task dates
*/
protected function parseDateTime($date_time) {
if (!strlen($date_time)) {
return null;
}
return PhabricatorTime::parseLocalTime($date_time, $this->requireViewer());
}
/**
* @task dates
*/
protected function buildDateRange(
AphrontFormView $form,
PhabricatorSavedQuery $saved_query,
$start_key,
$start_name,
$end_key,
$end_name) {
$start_str = $saved_query->getParameter($start_key);
$start = null;
if (strlen($start_str)) {
$start = $this->parseDateTime($start_str);
if (!$start) {
$this->addError(
pht(
'"%s" date can not be parsed.',
$start_name));
}
}
$end_str = $saved_query->getParameter($end_key);
$end = null;
if (strlen($end_str)) {
$end = $this->parseDateTime($end_str);
if (!$end) {
$this->addError(
pht(
'"%s" date can not be parsed.',
$end_name));
}
}
if ($start && $end && ($start >= $end)) {
$this->addError(
pht(
'"%s" must be a date before "%s".',
$start_name,
$end_name));
}
$form
->appendChild(
id(new PHUIFormFreeformDateControl())
->setName($start_key)
->setLabel($start_name)
->setValue($start_str))
->appendChild(
id(new AphrontFormTextControl())
->setName($end_key)
->setLabel($end_name)
->setValue($end_str));
}
/* -( Result Ordering )---------------------------------------------------- */
/**
* Save order selection to a @{class:PhabricatorSavedQuery}.
*/
protected function saveQueryOrder(
PhabricatorSavedQuery $saved,
AphrontRequest $request) {
$saved->setParameter('order', $request->getStr('order'));
return $this;
}
/**
* Set query ordering from a saved value.
*/
protected function setQueryOrder(
PhabricatorCursorPagedPolicyAwareQuery $query,
PhabricatorSavedQuery $saved) {
$order = $saved->getParameter('order');
$builtin = $query->getBuiltinOrders();
if (strlen($order) && isset($builtin[$order])) {
$query->setOrder($order);
} else {
// If the order is invalid or not available, we choose the first
// builtin order. This isn't always the default order for the query,
// but is the first value in the "Order" dropdown, and makes the query
// behavior more consistent with the UI. In queries where the two
// orders differ, this order is the preferred order for humans.
$query->setOrder(head_key($builtin));
}
return $this;
}
protected function appendOrderFieldsToForm(
AphrontFormView $form,
PhabricatorSavedQuery $saved,
PhabricatorCursorPagedPolicyAwareQuery $query) {
$orders = $query->getBuiltinOrders();
$orders = ipull($orders, 'name');
$form->appendControl(
id(new AphrontFormSelectControl())
->setLabel(pht('Order'))
->setName('order')
->setOptions($orders)
->setValue($saved->getParameter('order')));
}
/* -( Paging and Executing Queries )--------------------------------------- */
public function getPageSize(PhabricatorSavedQuery $saved) {
return $saved->getParameter('limit', 100);
}
public function shouldUseOffsetPaging() {
return false;
}
public function newPagerForSavedQuery(PhabricatorSavedQuery $saved) {
if ($this->shouldUseOffsetPaging()) {
$pager = new AphrontPagerView();
} else {
$pager = new AphrontCursorPagerView();
}
$page_size = $this->getPageSize($saved);
if (is_finite($page_size)) {
$pager->setPageSize($page_size);
} else {
// Consider an INF pagesize to mean a large finite pagesize.
// TODO: It would be nice to handle this more gracefully, but math
// with INF seems to vary across PHP versions, systems, and runtimes.
$pager->setPageSize(0xFFFF);
}
return $pager;
}
public function executeQuery(
PhabricatorPolicyAwareQuery $query,
AphrontView $pager) {
$query->setViewer($this->requireViewer());
if ($this->shouldUseOffsetPaging()) {
$objects = $query->executeWithOffsetPager($pager);
} else {
$objects = $query->executeWithCursorPager($pager);
}
return $objects;
}
/* -( Rendering )---------------------------------------------------------- */
public function setRequest(AphrontRequest $request) {
$this->request = $request;
return $this;
}
public function getRequest() {
return $this->request;
}
public function renderResults(
array $objects,
PhabricatorSavedQuery $query) {
$phids = $this->getRequiredHandlePHIDsForResultList($objects, $query);
if ($phids) {
$handles = id(new PhabricatorHandleQuery())
->setViewer($this->requireViewer())
->witHPHIDs($phids)
->execute();
} else {
$handles = array();
}
return $this->renderResultList($objects, $query, $handles);
}
protected function getRequiredHandlePHIDsForResultList(
array $objects,
PhabricatorSavedQuery $query) {
return array();
}
protected function renderResultList(
array $objects,
PhabricatorSavedQuery $query,
array $handles) {
throw new Exception(pht('Not supported here yet!'));
}
/* -( Application Search )------------------------------------------------- */
/**
* Retrieve an object to use to define custom fields for this search.
*
* To integrate with custom fields, subclasses should override this method
* and return an instance of the application object which implements
* @{interface:PhabricatorCustomFieldInterface}.
*
* @return PhabricatorCustomFieldInterface|null Object with custom fields.
* @task appsearch
*/
public function getCustomFieldObject() {
$object = $this->newResultObject();
if ($object instanceof PhabricatorCustomFieldInterface) {
return $object;
}
return null;
}
/**
* Get the custom fields for this search.
*
* @return PhabricatorCustomFieldList|null Custom fields, if this search
* supports custom fields.
* @task appsearch
*/
public function getCustomFieldList() {
if ($this->customFields === false) {
$object = $this->getCustomFieldObject();
if ($object) {
$fields = PhabricatorCustomField::getObjectFields(
$object,
PhabricatorCustomField::ROLE_APPLICATIONSEARCH);
$fields->setViewer($this->requireViewer());
} else {
$fields = null;
}
$this->customFields = $fields;
}
return $this->customFields;
}
/**
* Moves data from the request into a saved query.
*
* @param AphrontRequest Request to read.
* @param PhabricatorSavedQuery Query to write to.
* @return void
* @task appsearch
*/
protected function readCustomFieldsFromRequest(
AphrontRequest $request,
PhabricatorSavedQuery $saved) {
$list = $this->getCustomFieldList();
if (!$list) {
return;
}
foreach ($list->getFields() as $field) {
$key = $this->getKeyForCustomField($field);
$value = $field->readApplicationSearchValueFromRequest(
$this,
$request);
$saved->setParameter($key, $value);
}
}
/**
* Applies data from a saved query to an executable query.
*
* @param PhabricatorCursorPagedPolicyAwareQuery Query to constrain.
* @param PhabricatorSavedQuery Saved query to read.
* @return void
*/
protected function applyCustomFieldsToQuery(
PhabricatorCursorPagedPolicyAwareQuery $query,
PhabricatorSavedQuery $saved) {
$list = $this->getCustomFieldList();
if (!$list) {
return;
}
foreach ($list->getFields() as $field) {
$key = $this->getKeyForCustomField($field);
$value = $field->applyApplicationSearchConstraintToQuery(
$this,
$query,
$saved->getParameter($key));
}
}
protected function applyOrderByToQuery(
PhabricatorCursorPagedPolicyAwareQuery $query,
array $standard_values,
$order) {
if (substr($order, 0, 7) === 'custom:') {
$list = $this->getCustomFieldList();
if (!$list) {
$query->setOrderBy(head($standard_values));
return;
}
foreach ($list->getFields() as $field) {
$key = $this->getKeyForCustomField($field);
if ($key === $order) {
$index = $field->buildOrderIndex();
if ($index === null) {
$query->setOrderBy(head($standard_values));
return;
}
$query->withApplicationSearchOrder(
$field,
$index,
false);
break;
}
}
} else {
$order = idx($standard_values, $order);
if ($order) {
$query->setOrderBy($order);
} else {
$query->setOrderBy(head($standard_values));
}
}
}
protected function getCustomFieldOrderOptions() {
$list = $this->getCustomFieldList();
if (!$list) {
return;
}
$custom_order = array();
foreach ($list->getFields() as $field) {
if ($field->shouldAppearInApplicationSearch()) {
if ($field->buildOrderIndex() !== null) {
$key = $this->getKeyForCustomField($field);
$custom_order[$key] = $field->getFieldName();
}
}
}
return $custom_order;
}
/**
* Get a unique key identifying a field.
*
* @param PhabricatorCustomField Field to identify.
* @return string Unique identifier, suitable for use as an input name.
*/
public function getKeyForCustomField(PhabricatorCustomField $field) {
return 'custom:'.$field->getFieldIndex();
}
-
- protected function buildCustomFieldSearchFields() {
+ private function buildCustomFieldSearchFields() {
$list = $this->getCustomFieldList();
if (!$list) {
return array();
}
$fields = array();
foreach ($list->getFields() as $field) {
$fields[] = id(new PhabricatorSearchCustomFieldProxyField())
->setSearchEngine($this)
->setCustomField($field);
}
return $fields;
}
// TODO: Remove.
protected function appendCustomFieldsToForm(
AphrontFormView $form,
PhabricatorSavedQuery $saved) {
$list = $this->getCustomFieldList();
if (!$list) {
return;
}
foreach ($list->getFields() as $field) {
$key = $this->getKeyForCustomField($field);
$value = $saved->getParameter($key);
$field->appendToApplicationSearchForm($this, $form, $value);
}
}
}

File Metadata

Mime Type
text/x-diff
Expires
Mon, Dec 1, 12:20 AM (20 h, 16 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
430050
Default Alt Text
(44 KB)

Event Timeline