Unverified Commit 0f5e5079 authored by Adrien Clairembault's avatar Adrien Clairembault Committed by GitHub
Browse files

Add forcename option to API (#6858)

* Add forcename option to API

* Add deprecated in changelog

* Remove const

* Do not add add hateoas for names

* Change forcename to add_keys_names

* Update doc and changelog
parent 650d8d50
......@@ -81,6 +81,7 @@ The present file will list all changes made to the project; according to the
- `Plugin::setUnloaded()`
- `Plugin::setUnloadedByName()`
- Usage of `$LOADED_PLUGINS` global variable
- `CommonDBTM::getRawName()` replaced by `CommonDBTM::getFriendlyName()`
#### Removed
......
......@@ -508,6 +508,7 @@ $ curl -X GET \
* *with_changes*: Retrieve associated ITIL changes. Optional.
* *with_notes*: Retrieve Notes. Optional.
* *with_logs*: Retrieve historical. Optional.
* *add_keys_names*: Retrieve friendly names. Array containing fkey(s) and/or "id". Optional.
* **Returns**:
* 200 (OK) with item data (Last-Modified header should contain the date of last modification of the item).
* 401 (UNAUTHORIZED).
......@@ -598,6 +599,7 @@ Note: To download a document see [Download a document file](#download-a-document
* *order* (default ASC): ASC - Ascending sort / DESC Descending sort. Optional.
* *searchText* (default NULL): array of filters to pass on the query (with key = field and value the text to search)
* *is_deleted* (default: false): Return deleted element. Optional.
* *add_keys_names*: Retrieve friendly names. Array containing fkey(s) and/or "id". Optional.
* **Returns**:
* 200 (OK) with items data.
* 206 (PARTIAL CONTENT) with items data defined by range.
......@@ -703,6 +705,7 @@ $ curl -X GET \
* *range* (default: 0-50): a string with a couple of number for start and end of pagination separated by a '-' char. Ex: 150-200. Optional.
* *sort* (default 1): id of the "searchoption" to sort by. Optional.
* *order* (default ASC): ASC - Ascending sort / DESC Descending sort. Optional.
* *add_keys_names*: Retrieve friendly names. Array containing fkey(s) and/or "id". Optional.
* **Returns**:
* 200 (OK) with the items data.
* 401 (UNAUTHORIZED).
......@@ -781,6 +784,7 @@ $ curl -X GET \
* *with_changes*: Retrieve associated ITIL changes. Optional.
* *with_notes*: Retrieve Notes. Optional.
* *with_logs*: Retrieve historical. Optional.
* *add_keys_names*: Retrieve friendly names. Array containing fkey(s) and/or "id". Optional.
* **Returns**:
* 200 (OK) with item data (Last-Modified header should contain the date of last modification of the item).
* 401 (UNAUTHORIZED).
......
......@@ -508,6 +508,7 @@ abstract class API extends CommonGLPI {
* - 'with_changes': Retrieve associated itil changes. Optionnal.
* - 'with_notes': Retrieve Notes (if exists, not all itemtypes have notes). Optionnal.
* - 'with_logs': Retrieve historical. Optionnal.
* - 'add_keys_names': Get friendly names. Optionnal.
*
* @return array fields of found object
*/
......@@ -532,7 +533,9 @@ abstract class API extends CommonGLPI {
'with_problems' => false,
'with_changes' => false,
'with_notes' => false,
'with_logs' => false];
'with_logs' => false,
'add_keys_names' => [],
];
$params = array_merge($default, $params);
$item = new $itemtype;
......@@ -1065,6 +1068,14 @@ abstract class API extends CommonGLPI {
| JSON_NUMERIC_CHECK));
}
if (count($params['add_keys_names']) > 0) {
$fields["_names"] = $this->getFriendlyNames(
$fields,
$params,
$itemtype
);
}
return $fields;
}
......@@ -1098,6 +1109,7 @@ abstract class API extends CommonGLPI {
* - 'order' (default: ASC): ASC(ending) or DESC(ending).
* - 'searchText' (default: NULL): array of filters to pass on the query (with key = field and value the search)
* - 'is_deleted' (default: false): show trashbin. Optionnal
* - 'add_keys_names' (default: []): insert raw name(s) for given itemtype(s) and fkey(s)
* @param integer $totalcount output parameter who receive the total count of the query resulat.
* As this function paginate results (with a mysql LIMIT),
* we can have the full range. (default 0)
......@@ -1117,7 +1129,9 @@ abstract class API extends CommonGLPI {
'sort' => "id",
'order' => "ASC",
'searchText' => null,
'is_deleted' => false];
'is_deleted' => false,
'add_keys_names' => [],
];
$params = array_merge($default, $params);
if (!$itemtype::canView()) {
......@@ -1249,6 +1263,9 @@ abstract class API extends CommonGLPI {
$where.= ")";
}
// Check if we need to add raw names later on
$add_keys_names = count($params['add_keys_names']) > 0;
// build query
$query = "SELECT SQL_CALC_FOUND_ROWS DISTINCT ".$DB->quoteName("$table.id").", ".$DB->quoteName("$table.*")."
FROM ".$DB->quoteName($table)."
......@@ -1258,6 +1275,15 @@ abstract class API extends CommonGLPI {
LIMIT ".(int)$params['start'].", ".(int)$params['list_limit'];
if ($result = $DB->query($query)) {
while ($data = $DB->fetchAssoc($result)) {
if ($add_keys_names) {
// Insert raw names into the data row
$data["_keys_names"] = $this->getFriendlyNames(
$data,
$params,
$itemtype
);
}
$found[] = $data;
}
}
......@@ -1297,7 +1323,6 @@ abstract class API extends CommonGLPI {
return array_values($found);
}
/**
* Return a collection of items queried in input ($items)
*
......@@ -2347,7 +2372,7 @@ abstract class API extends CommonGLPI {
$itemtype = getItemTypeForTable($tablename);
// get hateoas
if ($params['get_hateoas']) {
if ($params['get_hateoas'] && is_integer($value)) {
$fields['links'][] = ['rel' => $itemtype,
'href' => self::$api_url."/$itemtype/".$value];
}
......@@ -2606,4 +2631,57 @@ abstract class API extends CommonGLPI {
protected function getHttpBody() {
return file_get_contents('php://input');
}
/**
* Get raw names
*
* @since 9.5
*
* @param array $data A raw from the database
* @param array $params API parameters
* @param string $self_itemtype Itemtype the API was called on
*
* @return array
*/
protected function getFriendlyNames(
array $data,
array $params,
string $self_itemtype
) {
$_names = [];
foreach ($params['add_keys_names'] as $kn_fkey) {
if ($kn_fkey == "id") {
// Get friendlyname for current item
$kn_itemtype = $self_itemtype;
$kn_id = $data[$kn_itemtype::getIndexName()];
} else {
if (!isset($data[$kn_fkey])) {
\Toolbox::logWarning(
"Invalid value: \"$kn_fkey\" doesn't exist.
");
continue;
}
// Get friendlyname for given fkey
$kn_itemtype = getItemtypeForForeignKeyField($kn_fkey);
$kn_id = $data[$kn_fkey];
}
// Check itemtype is valid
$kn_item = getItemForItemtype($kn_itemtype);
if (!$kn_item) {
\Toolbox::logWarning(
"Invalid itemtype \"$kn_itemtype\" for fkey \"$kn_fkey\""
);
continue;
}
$kn_name = $kn_item::getFriendlyNameById($kn_id);
$_names[$kn_fkey] = $kn_name;
}
return $_names;
}
}
......@@ -86,7 +86,7 @@ class Calendar extends AbstractBackend {
'uri' => self::BASE_CALENDAR_URI,
'principaluri' => $principalPath,
'name' => $principal_item->getName(),
'desc' => sprintf(__('Calendar of %s'), $principal_item->getRawName()),
'desc' => sprintf(__('Calendar of %s'), $principal_item->getFriendlyName()),
'color' => null,
]
];
......@@ -124,7 +124,7 @@ class Calendar extends AbstractBackend {
: $key,
'principaluri' => $this->getPrincipalUri($calendar_principal),
'name' => $calendar_principal->getName(),
'desc' => sprintf(__('Calendar of %s'), $calendar_principal->getRawName()),
'desc' => sprintf(__('Calendar of %s'), $calendar_principal->getFriendlyName()),
'color' => $calendar_params['color'],
];
}
......
......@@ -1312,7 +1312,7 @@ class CommonDBTM extends CommonGLPI {
* @return boolean true on success
**/
function update(array $input, $history = 1, $options = []) {
global $DB;
global $DB, $GLPI_CACHE;
if ($DB->isSlave()) {
return false;
......@@ -1451,6 +1451,13 @@ class CommonDBTM extends CommonGLPI {
QueuedNotification::forceSendFor($this->getType(), $this->fields['id']);
}
// Update raw names cache (for API)
$GLPI_CACHE->delete(self::getCacheKeyForFriendlyName(
$this->getType(),
$this->fields['id']
));
$this->getFriendlyName();
return true;
}
}
......@@ -3332,21 +3339,20 @@ class CommonDBTM extends CommonGLPI {
}
/** Get raw name of the object
/**
* Get raw name of the object
* Maybe overloaded
*
* @deprecated 9.5
* @see CommonDBTM::getNameField
*
* @since 0.85
*
* @return string
**/
function getRawName() {
\Toolbox::deprecated('Use CommonDBTM::getFriendlyName()');
if (isset($this->fields[static::getNameField()])) {
return $this->fields[static::getNameField()];
}
return '';
return $this->getFriendlyName();
}
......@@ -3379,7 +3385,7 @@ class CommonDBTM extends CommonGLPI {
* @return string name of the object in the current language
*
* @see CommonDBTM::getRawCompleteName
* @see CommonDBTM::getRawName
* @see CommonDBTM::getFriendlyName
**/
function getName($options = []) {
......@@ -3400,7 +3406,7 @@ class CommonDBTM extends CommonGLPI {
$name = $this->getRawCompleteName();
}
if (empty($name)) {
$name = $this->getRawName();
$name = $this->getFriendlyName();
}
if (strlen($name) != 0) {
......@@ -5304,4 +5310,82 @@ class CommonDBTM extends CommonGLPI {
static function getIcon() {
return "";
}
/**
* Get cache key containing raw name for a given itemtype and id
*
* @since 9.5
*
* @param string $itemtype
* @param int $id
*/
public static function getCacheKeyForFriendlyName($itemtype, $id) {
return "raw_name__{$itemtype}__{$id}";
}
/**
* Get friendly name by items id
* The purpose of this function is to try to access the friendly name
* without having to read the object from the database
*
* @since 9.5
*
* @param int $id
*
* @return string Friendly name of the object
*/
public static function getFriendlyNameById($id) {
global $GLPI_CACHE;
$cache_key = self::getCacheKeyForFriendlyName(self::getType(), $id);
if ($GLPI_CACHE->has($cache_key)) {
return $GLPI_CACHE->get($cache_key);
} else {
$item = new static();
$item->getFromDB($id);
return $item->getFriendlyName();
}
}
/**
* Return the computed friendly name and set the cache.
*
* @since 9.5
*
* @return string
*/
final public function getFriendlyName() {
global $GLPI_CACHE;
$cache_key = self::getCacheKeyForFriendlyName(
self::getType(),
$this->getID()
);
if ($GLPI_CACHE->has($cache_key)) {
// Get from cache
$name = $GLPI_CACHE->get($cache_key);
} else {
// Compute the name then set the cache
$name = $this->computeFriendlyName();
$GLPI_CACHE->set($cache_key, $name);
}
return $name;
}
/**
* Compute the friendly name of the object
*
* @since 9.5
*
* @return string
*/
protected function computeFriendlyName() {
if (isset($this->fields[static::getNameField()])) {
return $this->fields[static::getNameField()];
}
return '';
}
}
......@@ -558,13 +558,7 @@ abstract class CommonITILTask extends CommonDBTM implements CalDAVCompatibleItem
// SPECIFIC FUNCTIONS
/**
* @see CommonDBTM::getRawName()
*
* @since 0.85
**/
function getRawName() {
public function computeFriendlyName() {
if (isset($this->fields['taskcategories_id'])) {
if ($this->fields['taskcategories_id']) {
......
......@@ -260,7 +260,7 @@ class Contact extends CommonDBTM{
}
function getRawName() {
public function computeFriendlyName() {
if (isset($this->fields["id"]) && ($this->fields["id"] > 0)) {
return formatUserName('',
......
......@@ -80,7 +80,7 @@ class Item_Devices extends CommonDBRelation {
return true;
}
function getRawName() {
public function computeFriendlyName() {
$itemtype = static::$itemtype_2;
if (!empty($this->fields[static::$itemtype_1])) {
$item = new $this->fields[static::$itemtype_1];
......
......@@ -342,7 +342,7 @@ class Item_OperatingSystem extends CommonDBRelation {
$this->showFormButtons($options);
}
function getRawName() {
public function computeFriendlyName() {
$item = getItemForItemtype($this->fields['itemtype']);
$item->getFromDB($this->fields['items_id']);
$name = $item->getTypeName(1) . ' ' . $item->getName();
......
......@@ -1075,7 +1075,7 @@ JAVASCRIPT;
return $input;
}
function getRawName() {
public function computeFriendlyName() {
$rack = new Rack();
$rack->getFromDB($this->fields['racks_id']);
$name = sprintf(
......
......@@ -470,7 +470,7 @@ class ITILFollowup extends CommonDBChild {
}
function getRawName() {
public function computeFriendlyName() {
if (isset($this->fields['requesttypes_id'])) {
if ($this->fields['requesttypes_id']) {
......
......@@ -75,7 +75,7 @@ abstract class ITILTemplateField extends CommonDBChild {
}
function getRawName() {
function computeFriendlyName() {
$tt_class = static::$itemtype;
$tt = new $tt_class;
$fields = $tt->getAllowedFieldsNames(true);
......
......@@ -49,7 +49,7 @@ class ITILTemplatePredefinedField extends ITILTemplateField {
}
function getRawName() {
function computeFriendlyName() {
$tt_class = static::$itemtype;
$tt = new $tt_class;
......
......@@ -226,15 +226,7 @@ class NotificationTarget extends CommonDBChild {
return _n('Recipient', 'Recipients', $nb);
}
/**
* Get a notificationtarget class by giving the object which raises the event
*
* @see CommonDBTM::getRawName
*
* @return string
**/
function getRawName() {
public function computeFriendlyName() {
if (isset($this->notification_targets_labels[$this->getField("type")]
[$this->getField("items_id")])) {
......@@ -245,7 +237,6 @@ class NotificationTarget extends CommonDBChild {
return '';
}
/**
* Get a notificationtarget class by giving the object which raises the event
*
......
......@@ -62,10 +62,7 @@ class NotificationTemplateTranslation extends CommonDBChild {
}
/**
* @see CommonDBTM::getRawName()
**/
function getRawName() {
public function computeFriendlyName() {
global $CFG_GLPI;
if ($this->getField('language') != '') {
......
......@@ -62,16 +62,9 @@ class OperatingSystemKernelVersion extends CommonDropdown {
}
}
function getRawName() {
$kernel = new OperatingSystemKernel();
$kname = $kernel->getRawName();
$kvname = parent::getRawName();
public function computeFriendlyName() {
$kvname = parent::computeFriendlyName();
$name = str_replace(
['%kernel', '%version'],
[$kname, $kvname],
'%kernel %version'
);
return trim($name);
return trim($kvname);
}
}
......@@ -113,7 +113,7 @@ class PlanningCsv extends CommonGLPI {
//(acteur;titre item;id item;date-heure début,date-heure fin;catégorie)
$this->lines[] = [
'actor' => $user->getRawName(),
'actor' => $user->getFriendlyName(),
'title' => $val['name'],
'itemtype' => $itemtype->getTypeName(1),
'items_id' => $val[$itemtype->getForeignKeyField()],
......
......@@ -957,11 +957,7 @@ class Profile_User extends CommonDBRelation {
return _n('Profile', 'Profiles', $nb);
}
/**
* @see CommonDBTM::getRawName()
**/
function getRawName() {
public function computeFriendlyName() {
$name = sprintf(__('%1$s, %2$s'),
Dropdown::getDropdownName('glpi_profiles', $this->fields['profiles_id']),
......@@ -980,7 +976,6 @@ class Profile_User extends CommonDBRelation {
return $name;
}
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
global $DB;
......
......@@ -89,11 +89,7 @@ class RuleAction extends CommonDBChild {
return _n('Action', 'Actions', $nb);
}
/**
* @see CommonDBTM::getRawName()
**/
function getRawName() {
public function computeFriendlyName() {
if ($rule = getItemForItemtype(static::$itemtype)) {
return Html::clean($rule->getMinimalActionText($this->fields));
......@@ -101,7 +97,6 @@ class RuleAction extends CommonDBChild {
return '';
}
/**
* @since 0.84
*
......
......@@ -92,11 +92,7 @@ class RuleCriteria extends CommonDBChild {
return _n('Criterion', 'Criteria', $nb);
}
/**
* @see CommonDBTM::getRawName()
**/
function getRawName() {
public function computeFriendlyName() {
if ($rule = getItemForItemtype(static::$itemtype)) {
return Html::clean($rule->getMinimalCriteriaText($this->fields));
......@@ -104,7 +100,6 @@ class RuleCriteria extends CommonDBChild {
return '';
}
/**
* @since 0.84
*
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment