Feature GLP11

This commit is contained in:
Stanislas
2025-06-26 16:16:43 +02:00
parent e283c254cd
commit cfa0a09cea
32 changed files with 3916 additions and 1983 deletions

21
.php-cs-fixer.php Normal file
View File

@ -0,0 +1,21 @@
<?php
use PhpCsFixer\Config;
use PhpCsFixer\Finder;
$finder = Finder::create()
->in(__DIR__)
->name('*.php')
->ignoreVCSIgnored(true);
$config = new Config();
$rules = [
'@PER-CS2.0' => true,
'trailing_comma_in_multiline' => ['elements' => ['arguments', 'array_destructuring', 'arrays']], // For PHP 7.4 compatibility
];
return $config
->setRules($rules)
->setFinder($finder)
->setUsingCache(false);

View File

@ -1,15 +1,26 @@
{ {
"require": { "require": {
"php": ">=7.4" "php": ">=8.2"
}, },
"require-dev": { "require-dev": {
"glpi-project/tools": "^0.5" "friendsofphp/php-cs-fixer": "^3.75",
"friendsoftwig/twigcs": "^6.1",
"glpi-project/tools": "^0.7.5",
"php-parallel-lint/php-parallel-lint": "^1.4"
}, },
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,
"platform": { "platform": {
"php": "7.4.0" "php": "8.2.99"
}, },
"sort-packages": true "sort-packages": true,
"allow-plugins": {
"phpstan/extension-installer": true
}
},
"autoload-dev": {
"psr-4": {
"Glpi\\Tools\\": "../../tools/src/"
}
} }
} }

2298
composer.lock generated

File diff suppressed because it is too large Load Diff

216
hook.php
View File

@ -33,23 +33,24 @@
// Purpose of file: // Purpose of file:
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
use GlpiPlugin\Example\Dropdown;
use GlpiPlugin\Example\Example; use GlpiPlugin\Example\Example;
use Dropdown as GlpiDropdown;
function plugin_change_profile_example() { function plugin_change_profile_example()
{
// Some logic that runs when the profile is changed // Some logic that runs when the profile is changed
} }
// Define dropdown relations // Define dropdown relations
function plugin_example_getDatabaseRelations() { function plugin_example_getDatabaseRelations()
{
return ["glpi_plugin_example_dropdowns" => ["glpi_plugin_example" => "plugin_example_dropdowns_id"]]; return ["glpi_plugin_example_dropdowns" => ["glpi_plugin_example" => "plugin_example_dropdowns_id"]];
} }
// Define Dropdown tables to be manage in GLPI : // Define Dropdown tables to be manage in GLPI :
function plugin_example_getDropdown() { function plugin_example_getDropdown()
{
// Table => Name // Table => Name
return [Dropdown::class => __("Plugin Example Dropdown", 'example')]; return [Dropdown::class => __("Plugin Example Dropdown", 'example')];
} }
@ -59,7 +60,8 @@ function plugin_example_getDropdown() {
////// SEARCH FUNCTIONS ///////(){ ////// SEARCH FUNCTIONS ///////(){
// Define Additionnal search options for types (other than the plugin ones) // Define Additionnal search options for types (other than the plugin ones)
function plugin_example_getAddSearchOptions($itemtype) { function plugin_example_getAddSearchOptions($itemtype)
{
$sopt = []; $sopt = [];
if ($itemtype == 'Computer') { if ($itemtype == 'Computer') {
// Just for example, not working... // Just for example, not working...
@ -71,7 +73,8 @@ function plugin_example_getAddSearchOptions($itemtype) {
return $sopt; return $sopt;
} }
function plugin_example_getAddSearchOptionsNew($itemtype) { function plugin_example_getAddSearchOptionsNew($itemtype)
{
$options = []; $options = [];
if ($itemtype == 'Computer') { if ($itemtype == 'Computer') {
//Just for example, not working //Just for example, not working
@ -80,14 +83,15 @@ function plugin_example_getAddSearchOptionsNew($itemtype) {
'table' => 'glpi_plugin_example_dropdowns', 'table' => 'glpi_plugin_example_dropdowns',
'field' => 'name', 'field' => 'name',
'linkfield' => 'plugin_example_dropdowns_id', 'linkfield' => 'plugin_example_dropdowns_id',
'name' => __('Example plugin new', 'example') 'name' => __('Example plugin new', 'example'),
]; ];
} }
return $options; return $options;
} }
// See also GlpiPlugin\Example\Example::getSpecificValueToDisplay() // See also GlpiPlugin\Example\Example::getSpecificValueToDisplay()
function plugin_example_giveItem($type, $ID, $data, $num) { function plugin_example_giveItem($type, $ID, $data, $num)
{
$searchopt = &Search::getOptions($type); $searchopt = &Search::getOptions($type);
$table = $searchopt[$ID]["table"]; $table = $searchopt[$ID]["table"];
$field = $searchopt[$ID]["field"]; $field = $searchopt[$ID]["field"];
@ -106,7 +110,8 @@ function plugin_example_giveItem($type, $ID, $data, $num) {
} }
function plugin_example_displayConfigItem($type, $ID, $data, $num) { function plugin_example_displayConfigItem($type, $ID, $data, $num)
{
$searchopt = &Search::getOptions($type); $searchopt = &Search::getOptions($type);
$table = $searchopt[$ID]["table"]; $table = $searchopt[$ID]["table"];
$field = $searchopt[$ID]["field"]; $field = $searchopt[$ID]["field"];
@ -121,20 +126,27 @@ function plugin_example_displayConfigItem($type, $ID, $data, $num) {
} }
function plugin_example_addDefaultJoin($type, $ref_table, &$already_link_tables) { function plugin_example_addDefaultJoin($type, $ref_table, &$already_link_tables)
{
// Example of default JOIN clause // Example of default JOIN clause
// No need of the function if you do not have specific cases // No need of the function if you do not have specific cases
switch ($type) { switch ($type) {
// case Example::class : // case Example::class :
case "MyType": case "MyType":
return Search::addLeftJoin($type, $ref_table, $already_link_tables, return Search::addLeftJoin(
"newtable", "linkfield"); $type,
$ref_table,
$already_link_tables,
"newtable",
"linkfield",
);
} }
return ""; return "";
} }
function plugin_example_addDefaultSelect($type) { function plugin_example_addDefaultSelect($type)
{
// Example of default SELECT item to be added // Example of default SELECT item to be added
// No need of the function if you do not have specific cases // No need of the function if you do not have specific cases
switch ($type) { switch ($type) {
@ -146,7 +158,8 @@ function plugin_example_addDefaultSelect($type) {
} }
function plugin_example_addDefaultWhere($type) { function plugin_example_addDefaultWhere($type)
{
// Example of default WHERE item to be added // Example of default WHERE item to be added
// No need of the function if you do not have specific cases // No need of the function if you do not have specific cases
switch ($type) { switch ($type) {
@ -158,7 +171,8 @@ function plugin_example_addDefaultWhere($type) {
} }
function plugin_example_addLeftJoin($type, $ref_table, $new_table, $linkfield) { function plugin_example_addLeftJoin($type, $ref_table, $new_table, $linkfield)
{
// Example of standard LEFT JOIN clause but use it ONLY for specific LEFT JOIN // Example of standard LEFT JOIN clause but use it ONLY for specific LEFT JOIN
// No need of the function if you do not have specific cases // No need of the function if you do not have specific cases
switch ($new_table) { switch ($new_table) {
@ -169,7 +183,8 @@ function plugin_example_addLeftJoin($type, $ref_table, $new_table, $linkfield) {
} }
function plugin_example_forceGroupBy($type) { function plugin_example_forceGroupBy($type)
{
switch ($type) { switch ($type) {
case Example::class: case Example::class:
// Force add GROUP BY IN REQUEST // Force add GROUP BY IN REQUEST
@ -179,7 +194,8 @@ function plugin_example_forceGroupBy($type) {
} }
function plugin_example_addWhere($link, $nott, $type, $ID, $val, $searchtype) { function plugin_example_addWhere($link, $nott, $type, $ID, $val, $searchtype)
{
$searchopt = &Search::getOptions($type); $searchopt = &Search::getOptions($type);
$table = $searchopt[$ID]["table"]; $table = $searchopt[$ID]["table"];
$field = $searchopt[$ID]["field"]; $field = $searchopt[$ID]["field"];
@ -203,7 +219,8 @@ function plugin_example_addWhere($link, $nott, $type, $ID, $val, $searchtype) {
// This is not a real example because the use of Having condition in this case is not suitable // This is not a real example because the use of Having condition in this case is not suitable
function plugin_example_addHaving($link, $nott, $type, $ID, $val, $num) { function plugin_example_addHaving($link, $nott, $type, $ID, $val, $num)
{
$searchopt = &Search::getOptions($type); $searchopt = &Search::getOptions($type);
$table = $searchopt[$ID]["table"]; $table = $searchopt[$ID]["table"];
$field = $searchopt[$ID]["field"]; $field = $searchopt[$ID]["field"];
@ -219,13 +236,14 @@ function plugin_example_addHaving($link, $nott, $type, $ID, $val, $num) {
|| $val == '^$') { || $val == '^$') {
$ADD = " OR ITEM_$num IS NULL"; $ADD = " OR ITEM_$num IS NULL";
} }
return " $LINK ( ITEM_".$num.$SEARCH." $ADD ) "; return " $link ( ITEM_" . $num . $SEARCH . " $ADD ) ";
} }
return ""; return "";
} }
function plugin_example_addSelect($type, $ID, $num) { function plugin_example_addSelect($type, $ID, $num)
{
$searchopt = &Search::getOptions($type); $searchopt = &Search::getOptions($type);
$table = $searchopt[$ID]["table"]; $table = $searchopt[$ID]["table"];
$field = $searchopt[$ID]["field"]; $field = $searchopt[$ID]["field"];
@ -240,7 +258,8 @@ function plugin_example_addSelect($type, $ID, $num) {
} }
function plugin_example_addOrderBy($type, $ID, $order, $key = 0) { function plugin_example_addOrderBy($type, $ID, $order, $key = 0)
{
$searchopt = &Search::getOptions($type); $searchopt = &Search::getOptions($type);
$table = $searchopt[$ID]["table"]; $table = $searchopt[$ID]["table"];
$field = $searchopt[$ID]["field"]; $field = $searchopt[$ID]["field"];
@ -260,7 +279,8 @@ function plugin_example_addOrderBy($type, $ID, $order, $key = 0) {
// Define actions : // Define actions :
function plugin_example_MassiveActions($type) { function plugin_example_MassiveActions($type)
{
switch ($type) { switch ($type) {
// New action for core and other plugin types : name = plugin_PLUGINNAME_actionname // New action for core and other plugin types : name = plugin_PLUGINNAME_actionname
case 'Computer': case 'Computer':
@ -275,7 +295,8 @@ function plugin_example_MassiveActions($type) {
// How to display specific update fields ? // How to display specific update fields ?
// options must contain at least itemtype and options array // options must contain at least itemtype and options array
function plugin_example_MassiveActionsFieldsDisplay($options = []) { function plugin_example_MassiveActionsFieldsDisplay($options = [])
{
//$type,$table,$field,$linkfield //$type,$table,$field,$linkfield
$table = $options['options']['table']; $table = $options['options']['table'];
@ -309,7 +330,8 @@ function plugin_example_MassiveActionsFieldsDisplay($options = []) {
// How to display specific search fields or dropdown ? // How to display specific search fields or dropdown ?
// options must contain at least itemtype and options array // options must contain at least itemtype and options array
// MUST Use a specific AddWhere & $tab[X]['searchtype'] = 'equals'; declaration // MUST Use a specific AddWhere & $tab[X]['searchtype'] = 'equals'; declaration
function plugin_example_searchOptionsValues($options = []) { function plugin_example_searchOptionsValues($options = [])
{
$table = $options['searchoption']['table']; $table = $options['searchoption']['table'];
$field = $options['searchoption']['field']; $field = $options['searchoption']['field'];
@ -317,10 +339,12 @@ function plugin_example_searchOptionsValues($options = []) {
switch ($table . "." . $field) { switch ($table . "." . $field) {
case "glpi_plugin_example_examples.serial": case "glpi_plugin_example_examples.serial":
echo __("Not really specific - Use your own dropdown - Just for example", 'example'); echo __("Not really specific - Use your own dropdown - Just for example", 'example');
GlpiDropdown::show(getItemTypeForTable($options['searchoption']['table']), Dropdown::show(
getItemTypeForTable($options['searchoption']['table']),
['value' => $options['value'], ['value' => $options['value'],
'name' => $options['name'], 'name' => $options['name'],
'comments' => 0]); 'comments' => 0],
);
// Need to return true if specific display // Need to return true if specific display
return true; return true;
} }
@ -331,7 +355,8 @@ function plugin_example_searchOptionsValues($options = []) {
////////////////////////////// //////////////////////////////
// Hook done on before update item case // Hook done on before update item case
function plugin_pre_item_update_example($item) { function plugin_pre_item_update_example($item)
{
/* Manipulate data if needed /* Manipulate data if needed
if (!isset($item->input['comment'])) { if (!isset($item->input['comment'])) {
$item->input['comment'] = addslashes($item->fields['comment']); $item->input['comment'] = addslashes($item->fields['comment']);
@ -343,14 +368,16 @@ function plugin_pre_item_update_example($item) {
// Hook done on update item case // Hook done on update item case
function plugin_item_update_example($item) { function plugin_item_update_example($item)
{
Session::addMessageAfterRedirect(sprintf(__("Update Computer Hook (%s)", 'example'), implode(',', $item->updates)), true); Session::addMessageAfterRedirect(sprintf(__("Update Computer Hook (%s)", 'example'), implode(',', $item->updates)), true);
return true; return true;
} }
// Hook done on get empty item case // Hook done on get empty item case
function plugin_item_empty_example($item) { function plugin_item_empty_example($item)
{
if (empty($_SESSION['Already displayed "Empty Computer Hook"'])) { if (empty($_SESSION['Already displayed "Empty Computer Hook"'])) {
Session::addMessageAfterRedirect(__("Empty Computer Hook", 'example'), true); Session::addMessageAfterRedirect(__("Empty Computer Hook", 'example'), true);
$_SESSION['Already displayed "Empty Computer Hook"'] = true; $_SESSION['Already displayed "Empty Computer Hook"'] = true;
@ -360,65 +387,78 @@ function plugin_item_empty_example($item) {
// Hook done on before delete item case // Hook done on before delete item case
function plugin_pre_item_delete_example($object) { function plugin_pre_item_delete_example($object)
{
// Manipulate data if needed // Manipulate data if needed
Session::addMessageAfterRedirect(__("Pre Delete Computer Hook", 'example'), true); Session::addMessageAfterRedirect(__("Pre Delete Computer Hook", 'example'), true);
} }
// Hook done on delete item case // Hook done on delete item case
function plugin_item_delete_example($object) { function plugin_item_delete_example($object)
{
Session::addMessageAfterRedirect(__("Delete Computer Hook", 'example'), true); Session::addMessageAfterRedirect(__("Delete Computer Hook", 'example'), true);
return true; return true;
} }
// Hook done on before purge item case // Hook done on before purge item case
function plugin_pre_item_purge_example($object) { function plugin_pre_item_purge_example($object)
{
// Manipulate data if needed // Manipulate data if needed
Session::addMessageAfterRedirect(__("Pre Purge Computer Hook", 'example'), true); Session::addMessageAfterRedirect(__("Pre Purge Computer Hook", 'example'), true);
} }
// Hook done on purge item case // Hook done on purge item case
function plugin_item_purge_example($object) { function plugin_item_purge_example($object)
{
Session::addMessageAfterRedirect(__("Purge Computer Hook", 'example'), true); Session::addMessageAfterRedirect(__("Purge Computer Hook", 'example'), true);
return true; return true;
} }
// Hook done on before restore item case // Hook done on before restore item case
function plugin_pre_item_restore_example($item) { function plugin_pre_item_restore_example($item)
{
// Manipulate data if needed // Manipulate data if needed
Session::addMessageAfterRedirect(__("Pre Restore Computer Hook", 'example')); Session::addMessageAfterRedirect(__("Pre Restore Computer Hook", 'example'));
} }
// Hook done on before restore item case // Hook done on before restore item case
function plugin_pre_item_restore_example2($item) { function plugin_pre_item_restore_example2($item)
{
// Manipulate data if needed // Manipulate data if needed
Session::addMessageAfterRedirect(__("Pre Restore Phone Hook", 'example')); Session::addMessageAfterRedirect(__("Pre Restore Phone Hook", 'example'));
} }
// Hook done on restore item case // Hook done on restore item case
function plugin_item_restore_example($item) { function plugin_item_restore_example($item)
{
Session::addMessageAfterRedirect(__("Restore Computer Hook", 'example')); Session::addMessageAfterRedirect(__("Restore Computer Hook", 'example'));
return true; return true;
} }
// Hook done on restore item case // Hook done on restore item case
function plugin_item_transfer_example($parm) { function plugin_item_transfer_example($parm)
{
//TRANS: %1$s is the source type, %2$d is the source ID, %3$d is the destination ID //TRANS: %1$s is the source type, %2$d is the source ID, %3$d is the destination ID
Session::addMessageAfterRedirect(sprintf(__('Transfer Computer Hook %1$s %2$d -> %3$d', 'example'), $parm['type'], $parm['id'], Session::addMessageAfterRedirect(sprintf(
$parm['newID'])); __('Transfer Computer Hook %1$s %2$d -> %3$d', 'example'),
$parm['type'],
$parm['id'],
$parm['newID'],
));
return false; return false;
} }
// Do special actions for dynamic report // Do special actions for dynamic report
function plugin_example_dynamicReport($parm) { function plugin_example_dynamicReport($parm)
{
if ($parm["item_type"] == Example::class) { if ($parm["item_type"] == Example::class) {
// Do all what you want for export depending on $parm // Do all what you want for export depending on $parm
echo "Personalized export for type " . $parm["display_type"]; echo "Personalized export for type " . $parm["display_type"];
@ -436,7 +476,8 @@ function plugin_example_dynamicReport($parm) {
// Add parameters to Html::printPager in search system // Add parameters to Html::printPager in search system
function plugin_example_addParamFordynamicReport($itemtype) { function plugin_example_addParamFordynamicReport($itemtype)
{
if ($itemtype == Example::class) { if ($itemtype == Example::class) {
// Return array data containing all params to add : may be single data or array data // Return array data containing all params to add : may be single data or array data
// Search config are available from session variable // Search config are available from session variable
@ -454,7 +495,9 @@ function plugin_example_addParamFordynamicReport($itemtype) {
* *
* @return boolean * @return boolean
*/ */
function plugin_example_install() { function plugin_example_install()
{
/** @var DBmysql $DB */
global $DB; global $DB;
$migration = new Migration(PLUGIN_EXAMPLE_VERSION); $migration = new Migration(PLUGIN_EXAMPLE_VERSION);
@ -482,7 +525,7 @@ function plugin_example_install() {
PRIMARY KEY (`id`) PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;";
$DB->query($query) or die("error creating glpi_plugin_example_examples ". $DB->error()); $DB->doQuery($query);
$query = "INSERT INTO `glpi_plugin_example_examples` $query = "INSERT INTO `glpi_plugin_example_examples`
(`id`, `name`, `serial`, `plugin_example_dropdowns_id`, `is_deleted`, (`id`, `name`, `serial`, `plugin_example_dropdowns_id`, `is_deleted`,
@ -490,7 +533,7 @@ function plugin_example_install() {
VALUES (1, 'example 1', 'serial 1', 1, 0, 0, NULL), VALUES (1, 'example 1', 'serial 1', 1, 0, 0, NULL),
(2, 'example 2', 'serial 2', 2, 0, 0, NULL), (2, 'example 2', 'serial 2', 2, 0, 0, NULL),
(3, 'example 3', 'serial 3', 1, 0, 0, NULL)"; (3, 'example 3', 'serial 3', 1, 0, 0, NULL)";
$DB->query($query) or die("error populate glpi_plugin_example ". $DB->error()); $DB->doQuery($query);
} }
if (!$DB->tableExists("glpi_plugin_example_dropdowns")) { if (!$DB->tableExists("glpi_plugin_example_dropdowns")) {
@ -502,14 +545,14 @@ function plugin_example_install() {
KEY `name` (`name`) KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;";
$DB->query($query) or die("error creating glpi_plugin_example_dropdowns". $DB->error()); $DB->doQuery($query);
$query = "INSERT INTO `glpi_plugin_example_dropdowns` $query = "INSERT INTO `glpi_plugin_example_dropdowns`
(`id`, `name`, `comment`) (`id`, `name`, `comment`)
VALUES (1, 'dp 1', 'comment 1'), VALUES (1, 'dp 1', 'comment 1'),
(2, 'dp2', 'comment 2')"; (2, 'dp2', 'comment 2')";
$DB->query($query) or die("error populate glpi_plugin_example_dropdowns". $DB->error()); $DB->doQuery($query);
} }
@ -524,7 +567,7 @@ function plugin_example_install() {
KEY `manufacturers_id` (`manufacturers_id`) KEY `manufacturers_id` (`manufacturers_id`)
) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;";
$DB->query($query) or die("error creating glpi_plugin_example_examples ". $DB->error()); $DB->doQuery($query);
} }
if (!$DB->tableExists('glpi_plugin_example_items_devicecameras')) { if (!$DB->tableExists('glpi_plugin_example_items_devicecameras')) {
@ -542,7 +585,7 @@ function plugin_example_install() {
KEY `is_dynamic` (`is_dynamic`) KEY `is_dynamic` (`is_dynamic`)
) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;"; ) ENGINE=InnoDB DEFAULT CHARSET={$default_charset} COLLATE={$default_collation} ROW_FORMAT=DYNAMIC;";
$DB->query($query) or die("error creating glpi_plugin_example_examples ". $DB->error()); $DB->doQuery($query);
} }
// To be called for each task the plugin manage // To be called for each task the plugin manage
@ -557,7 +600,9 @@ function plugin_example_install() {
* *
* @return boolean * @return boolean
*/ */
function plugin_example_uninstall() { function plugin_example_uninstall()
{
/** @var DBmysql $DB */
global $DB; global $DB;
$config = new Config(); $config = new Config();
@ -566,61 +611,68 @@ function plugin_example_uninstall() {
ProfileRight::deleteProfileRights([Example::$rightname]); ProfileRight::deleteProfileRights([Example::$rightname]);
$notif = new Notification(); $notif = new Notification();
$options = ['itemtype' => 'Ticket', $criteria = [
'SELECT' => 'id',
'FROM' => 'glpi_notifications',
'WHERE' => [
'itemtype' => 'Ticket',
'event' => 'plugin_example', 'event' => 'plugin_example',
'FIELDS' => 'id']; ],
foreach ($DB->request('glpi_notifications', $options) as $data) { ];
foreach ($DB->request($criteria) as $data) {
$notif->delete($data); $notif->delete($data);
} }
// Old version tables // Old version tables
if ($DB->tableExists("glpi_dropdown_plugin_example")) { if ($DB->tableExists("glpi_dropdown_plugin_example")) {
$query = "DROP TABLE `glpi_dropdown_plugin_example`"; $query = "DROP TABLE `glpi_dropdown_plugin_example`";
$DB->query($query) or die("error deleting glpi_dropdown_plugin_example"); $DB->doQuery($query);
} }
if ($DB->tableExists("glpi_plugin_example")) { if ($DB->tableExists("glpi_plugin_example")) {
$query = "DROP TABLE `glpi_plugin_example`"; $query = "DROP TABLE `glpi_plugin_example`";
$DB->query($query) or die("error deleting glpi_plugin_example"); $DB->doQuery($query);
} }
// Current version tables // Current version tables
if ($DB->tableExists("glpi_plugin_example_example")) { if ($DB->tableExists("glpi_plugin_example_example")) {
$query = "DROP TABLE `glpi_plugin_example_example`"; $query = "DROP TABLE `glpi_plugin_example_example`";
$DB->query($query) or die("error deleting glpi_plugin_example_example"); $DB->doQuery($query);
} }
if ($DB->tableExists("glpi_plugin_example_dropdowns")) { if ($DB->tableExists("glpi_plugin_example_dropdowns")) {
$query = "DROP TABLE `glpi_plugin_example_dropdowns`;"; $query = "DROP TABLE `glpi_plugin_example_dropdowns`;";
$DB->query($query) or die("error deleting glpi_plugin_example_dropdowns"); $DB->doQuery($query);
} }
if ($DB->tableExists("glpi_plugin_example_devicecameras")) { if ($DB->tableExists("glpi_plugin_example_devicecameras")) {
$query = "DROP TABLE `glpi_plugin_example_devicecameras`;"; $query = "DROP TABLE `glpi_plugin_example_devicecameras`;";
$DB->query($query) or die("error deleting glpi_plugin_example_devicecameras"); $DB->doQuery($query);
} }
if ($DB->tableExists("glpi_plugin_example_items_devicecameras")) { if ($DB->tableExists("glpi_plugin_example_items_devicecameras")) {
$query = "DROP TABLE `glpi_plugin_example_items_devicecameras`;"; $query = "DROP TABLE `glpi_plugin_example_items_devicecameras`;";
$DB->query($query) or die("error deleting glpi_plugin_example_items_devicecameras"); $DB->doQuery($query);
} }
return true; return true;
} }
function plugin_example_AssignToTicket($types) { function plugin_example_AssignToTicket($types)
{
$types[Example::class] = "Example"; $types[Example::class] = "Example";
return $types; return $types;
} }
function plugin_example_get_events(NotificationTargetTicket $target) { function plugin_example_get_events(NotificationTargetTicket $target)
{
$target->events['plugin_example'] = __("Example event", 'example'); $target->events['plugin_example'] = __("Example event", 'example');
} }
function plugin_example_get_datas(NotificationTargetTicket $target) { function plugin_example_get_datas(NotificationTargetTicket $target)
{
$target->data['##ticket.example##'] = __("Example datas", 'example'); $target->data['##ticket.example##'] = __("Example datas", 'example');
} }
function plugin_example_postinit() { function plugin_example_postinit()
global $CFG_GLPI; {
// All plugins are initialized, so all types are registered // All plugins are initialized, so all types are registered
//foreach (Infocom::getItemtypesThatCanHave() as $type) { //foreach (Infocom::getItemtypesThatCanHave() as $type) {
// do something // do something
@ -634,9 +686,10 @@ function plugin_example_postinit() {
* *
* @param $datas array * @param $datas array
* *
* @return un tableau * @return array
**/ **/
function plugin_retrieve_more_data_from_ldap_example(array $datas) { function plugin_retrieve_more_data_from_ldap_example(array $datas)
{
return $datas; return $datas;
} }
@ -646,17 +699,20 @@ function plugin_retrieve_more_data_from_ldap_example(array $datas) {
* *
* @param $fields array * @param $fields array
* *
* @return un tableau * @return array
**/ **/
function plugin_retrieve_more_field_from_ldap_example($fields) { function plugin_retrieve_more_field_from_ldap_example($fields)
{
return $fields; return $fields;
} }
// Check to add to status page // Check to add to status page
function plugin_example_Status($param) { function plugin_example_Status($param)
{
// Do checks (no check for example) // Do checks (no check for example)
$ok = true; $ok = true;
echo "example plugin: example"; echo "example plugin: example";
if ($ok) { if ($ok) {
echo "_OK"; echo "_OK";
} else { } else {
@ -668,7 +724,8 @@ function plugin_example_Status($param) {
return $param; return $param;
} }
function plugin_example_display_central() { function plugin_example_display_central()
{
echo "<tr><th colspan='2'>"; echo "<tr><th colspan='2'>";
echo "<div style='text-align:center; font-size:2em'>"; echo "<div style='text-align:center; font-size:2em'>";
echo __("Plugin example displays on central page", "example"); echo __("Plugin example displays on central page", "example");
@ -676,19 +733,22 @@ function plugin_example_display_central() {
echo "</th></tr>"; echo "</th></tr>";
} }
function plugin_example_display_login() { function plugin_example_display_login()
{
echo "<div style='text-align:center; font-size:2em'>"; echo "<div style='text-align:center; font-size:2em'>";
echo __("Plugin example displays on login page", "example"); echo __("Plugin example displays on login page", "example");
echo "</div>"; echo "</div>";
} }
function plugin_example_infocom_hook($params) { function plugin_example_infocom_hook($params)
{
echo "<tr><th colspan='4'>"; echo "<tr><th colspan='4'>";
echo __("Plugin example displays on central page", "example"); echo __("Plugin example displays on central page", "example");
echo "</th></tr>"; echo "</th></tr>";
} }
function plugin_example_filter_actors(array $params = []): array { function plugin_example_filter_actors(array $params = []): array
{
$itemtype = $params['params']['itemtype']; $itemtype = $params['params']['itemtype'];
$items_id = $params['params']['items_id']; $items_id = $params['params']['items_id'];
@ -704,13 +764,17 @@ function plugin_example_filter_actors(array $params = []): array {
return $params; return $params;
} }
function plugin_example_set_impact_icon(array $params) { function plugin_example_set_impact_icon(array $params)
{
/** @var array $CFG_GLPI */
global $CFG_GLPI;
$itemtype = $params['itemtype']; $itemtype = $params['itemtype'];
$items_id = $params['items_id']; $items_id = $params['items_id'];
$item = getItemForItemtype($itemtype); $item = getItemForItemtype($itemtype);
if ($item instanceof Computer && $item->getFromDB($items_id)) { if ($item instanceof Computer && $item->getFromDB($items_id)) {
return Plugin::getWebDir('example', true, false) . '/public/computer_icon.svg'; return $CFG_GLPI['root_doc'] . '/plugins/example/public/computer_icon.svg';
} }
return null; return null;
} }

View File

@ -42,9 +42,9 @@ use GlpiPlugin\Example\Showtabitem;
define('PLUGIN_EXAMPLE_VERSION', '0.0.1'); define('PLUGIN_EXAMPLE_VERSION', '0.0.1');
// Minimal GLPI version, inclusive // Minimal GLPI version, inclusive
define('PLUGIN_EXAMPLE_MIN_GLPI', '10.0.0'); define('PLUGIN_EXAMPLE_MIN_GLPI', '11.0.0');
// Maximum GLPI version, exclusive // Maximum GLPI version, exclusive
define('PLUGIN_EXAMPLE_MAX_GLPI', '10.0.99'); define('PLUGIN_EXAMPLE_MAX_GLPI', '11.0.99');
/** /**
* Init hooks of the plugin. * Init hooks of the plugin.
@ -52,8 +52,12 @@ define('PLUGIN_EXAMPLE_MAX_GLPI', '10.0.99');
* *
* @return void * @return void
*/ */
function plugin_init_example() { function plugin_init_example()
global $PLUGIN_HOOKS,$CFG_GLPI; {
/** @var array $CFG_GLPI */
/** @var array $PLUGIN_HOOKS */
global $CFG_GLPI, $PLUGIN_HOOKS;
// Params : plugin name - string type - ID - Array of attributes // Params : plugin name - string type - ID - Array of attributes
// No specific information passed so not needed // No specific information passed so not needed
@ -61,6 +65,8 @@ function plugin_init_example() {
// array('classname' => Example::class, // array('classname' => Example::class,
// )); // ));
require_once(__DIR__ . '/vendor/autoload.php');
Plugin::registerClass(Config::class, ['addtabon' => 'Config']); Plugin::registerClass(Config::class, ['addtabon' => 'Config']);
// Params : plugin name - string type - ID - Array of attributes // Params : plugin name - string type - ID - Array of attributes
@ -68,22 +74,27 @@ function plugin_init_example() {
$types = ['Central', 'Computer', 'ComputerDisk', 'Notification', 'Phone', $types = ['Central', 'Computer', 'ComputerDisk', 'Notification', 'Phone',
'Preference', 'Profile', 'Supplier']; 'Preference', 'Profile', 'Supplier'];
Plugin::registerClass(Example::class, Plugin::registerClass(
Example::class,
['notificationtemplates_types' => true, ['notificationtemplates_types' => true,
'addtabon' => $types, 'addtabon' => $types,
'link_types' => true]); 'link_types' => true],
);
Plugin::registerClass(RuleTestCollection::class, Plugin::registerClass(
['rulecollections_types' => true]); RuleTestCollection::class,
['rulecollections_types' => true],
);
Plugin::registerClass(DeviceCamera::class, Plugin::registerClass(
['device_types' => true]); DeviceCamera::class,
['device_types' => true],
);
if (version_compare(GLPI_VERSION, '9.1', 'ge')) {
if (class_exists(Example::class)) { if (class_exists(Example::class)) {
Link::registerTag(Example::$tags); Link::registerTag(Example::$tags);
} }
}
// Display a menu entry ? // Display a menu entry ?
Plugin::registerClass(\GlpiPlugin\Example\Profile::class, ['addtabon' => ['Profile']]); Plugin::registerClass(\GlpiPlugin\Example\Profile::class, ['addtabon' => ['Profile']]);
if (Example::canView()) { // Right set in change_profile hook if (Example::canView()) { // Right set in change_profile hook
@ -187,7 +198,7 @@ function plugin_init_example() {
'properties' => [ 'properties' => [
'name' => 'robots', 'name' => 'robots',
'content' => 'noindex, nofollow', 'content' => 'noindex, nofollow',
] ],
], ],
[ [
'tag' => 'link', 'tag' => 'link',
@ -196,7 +207,7 @@ function plugin_init_example() {
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => 'The company RSS feed', 'title' => 'The company RSS feed',
'href' => 'https://example.org/feed.xml', 'href' => 'https://example.org/feed.xml',
] ],
], ],
]; ];
@ -212,7 +223,7 @@ function plugin_init_example() {
'properties' => [ 'properties' => [
'name' => 'robots', 'name' => 'robots',
'content' => 'noindex, nofollow', 'content' => 'noindex, nofollow',
] ],
], ],
[ [
'tag' => 'link', 'tag' => 'link',
@ -221,7 +232,7 @@ function plugin_init_example() {
'type' => 'application/rss+xml', 'type' => 'application/rss+xml',
'title' => 'The company RSS feed', 'title' => 'The company RSS feed',
'href' => 'https://example.org/feed.xml', 'href' => 'https://example.org/feed.xml',
] ],
], ],
]; ];
@ -243,9 +254,6 @@ function plugin_init_example() {
$PLUGIN_HOOKS['status']['example'] = 'plugin_example_Status'; $PLUGIN_HOOKS['status']['example'] = 'plugin_example_Status';
// CSRF compliance : All actions must be done via POST and forms closed by Html::closeForm();
$PLUGIN_HOOKS[Hooks::CSRF_COMPLIANT]['example'] = true;
$PLUGIN_HOOKS[Hooks::DISPLAY_CENTRAL]['example'] = "plugin_example_display_central"; $PLUGIN_HOOKS[Hooks::DISPLAY_CENTRAL]['example'] = "plugin_example_display_central";
$PLUGIN_HOOKS[Hooks::DISPLAY_LOGIN]['example'] = "plugin_example_display_login"; $PLUGIN_HOOKS[Hooks::DISPLAY_LOGIN]['example'] = "plugin_example_display_login";
$PLUGIN_HOOKS[Hooks::INFOCOM]['example'] = "plugin_example_infocom_hook"; $PLUGIN_HOOKS[Hooks::INFOCOM]['example'] = "plugin_example_infocom_hook";
@ -260,15 +268,12 @@ function plugin_init_example() {
$PLUGIN_HOOKS[Hooks::PRE_ITEM_FORM]['example'] = [ItemForm::class, 'preItemForm']; $PLUGIN_HOOKS[Hooks::PRE_ITEM_FORM]['example'] = [ItemForm::class, 'preItemForm'];
$PLUGIN_HOOKS[Hooks::POST_ITEM_FORM]['example'] = [ItemForm::class, 'postItemForm']; $PLUGIN_HOOKS[Hooks::POST_ITEM_FORM]['example'] = [ItemForm::class, 'postItemForm'];
//TODO: remove check when GLPI 11.0.0 is released
if (version_compare(GLPI_VERSION, '11.0.0', 'ge')) {
$PLUGIN_HOOKS[Hooks::PRE_ITIL_INFO_SECTION]['example'] = [ItemForm::class, 'preSection']; $PLUGIN_HOOKS[Hooks::PRE_ITIL_INFO_SECTION]['example'] = [ItemForm::class, 'preSection'];
$PLUGIN_HOOKS[Hooks::POST_ITIL_INFO_SECTION]['example'] = [ItemForm::class, 'postSection']; $PLUGIN_HOOKS[Hooks::POST_ITIL_INFO_SECTION]['example'] = [ItemForm::class, 'postSection'];
}
// Add new actions to timeline // Add new actions to timeline
$PLUGIN_HOOKS[Hooks::TIMELINE_ACTIONS]['example'] = [ $PLUGIN_HOOKS[Hooks::TIMELINE_ACTIONS]['example'] = [
ItemForm::class, 'timelineActions' ItemForm::class, 'timelineActions',
]; ];
// declare this plugin as an import plugin for Computer itemtype // declare this plugin as an import plugin for Computer itemtype
@ -276,7 +281,7 @@ function plugin_init_example() {
// add additional informations on Computer::showForm // add additional informations on Computer::showForm
$PLUGIN_HOOKS[Hooks::AUTOINVENTORY_INFORMATION]['example'] = [ $PLUGIN_HOOKS[Hooks::AUTOINVENTORY_INFORMATION]['example'] = [
Computer::class => [Computer::class, 'showInfo'] Computer::class => [Computer::class, 'showInfo'],
]; ];
$PLUGIN_HOOKS[Hooks::FILTER_ACTORS]['example'] = "plugin_example_filter_actors"; $PLUGIN_HOOKS[Hooks::FILTER_ACTORS]['example'] = "plugin_example_filter_actors";
@ -287,15 +292,11 @@ function plugin_init_example() {
// Dashboard filter // Dashboard filter
$PLUGIN_HOOKS[Hooks::DASHBOARD_FILTERS]['example'] = [ $PLUGIN_HOOKS[Hooks::DASHBOARD_FILTERS]['example'] = [
ComputerModelFilter::class ComputerModelFilter::class,
]; ];
//TODO: remove check when GLPI 11.0.0 is released
if (version_compare(GLPI_VERSION, '11.0.0', 'ge')) {
// Icon in the impact analysis
$PLUGIN_HOOKS[Hooks::SET_ITEM_IMPACT_ICON]['example'] = 'plugin_example_set_impact_icon'; $PLUGIN_HOOKS[Hooks::SET_ITEM_IMPACT_ICON]['example'] = 'plugin_example_set_impact_icon';
} }
}
/** /**
@ -304,7 +305,8 @@ function plugin_init_example() {
* *
* @return array * @return array
*/ */
function plugin_version_example() { function plugin_version_example()
{
return [ return [
'name' => 'Plugin Example', 'name' => 'Plugin Example',
'version' => PLUGIN_EXAMPLE_VERSION, 'version' => PLUGIN_EXAMPLE_VERSION,
@ -315,8 +317,8 @@ function plugin_version_example() {
'glpi' => [ 'glpi' => [
'min' => PLUGIN_EXAMPLE_MIN_GLPI, 'min' => PLUGIN_EXAMPLE_MIN_GLPI,
'max' => PLUGIN_EXAMPLE_MAX_GLPI, 'max' => PLUGIN_EXAMPLE_MAX_GLPI,
] ],
] ],
]; ];
} }
@ -327,7 +329,8 @@ function plugin_version_example() {
* *
* @return boolean * @return boolean
*/ */
function plugin_example_check_prerequisites() { function plugin_example_check_prerequisites()
{
if (false) { if (false) {
return false; return false;
} }
@ -341,7 +344,8 @@ function plugin_example_check_prerequisites() {
* *
* @return boolean * @return boolean
*/ */
function plugin_example_check_config($verbose = false) { function plugin_example_check_config($verbose = false)
{
if (true) { // Your configuration check if (true) { // Your configuration check
return true; return true;
} }

View File

@ -34,6 +34,7 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDBChild; use CommonDBChild;
use Session; use Session;
@ -43,11 +44,11 @@ use Session;
// enhancements. // enhancements.
// For CommonDBRelation, the variable are quiet equivalent, but they use _1 and _2 for each side // For CommonDBRelation, the variable are quiet equivalent, but they use _1 and _2 for each side
// parent // parent
class Child extends CommonDBChild { class Child extends CommonDBChild
{
// A child rely on an item. If $itemtype=='itemtype', then that is a variable item. // A child rely on an item. If $itemtype=='itemtype', then that is a variable item.
static public $itemtype = 'itemtype'; public static $itemtype = 'itemtype';
static public $items_id = 'items_id'; public static $items_id = 'items_id';
// With 0.84, you have to specify each right (create, view, update and delete), because // With 0.84, you have to specify each right (create, view, update and delete), because
@ -59,28 +60,32 @@ class Child extends CommonDBChild {
// - CommonDBConnexity::HAVE_SAME_RIGHT_ON_ITEM we must have at least update right // - CommonDBConnexity::HAVE_SAME_RIGHT_ON_ITEM we must have at least update right
// on the item // on the item
// * $mustBeAttached: some CommonDBChild can be free, without any parent. // * $mustBeAttached: some CommonDBChild can be free, without any parent.
static function canCreate() { public static function canCreate(): bool
{
return (Session::haveRight('internet', UPDATE) return (Session::haveRight('internet', UPDATE)
&& parent::canCreate()); && parent::canCreate());
} }
static function canView() { public static function canView(): bool
{
return (Session::haveRight('internet', READ) return (Session::haveRight('internet', READ)
&& parent::canView()); && parent::canView());
} }
static function canUpdate() { public static function canUpdate(): bool
{
return (Session::haveRight('internet', UPDATE) return (Session::haveRight('internet', UPDATE)
&& parent::canUpdate()); && parent::canUpdate());
} }
static function canDelete() { public static function canDelete(): bool
{
return (Session::haveRight('internet', DELETE) return (Session::haveRight('internet', DELETE)
&& parent::canDelete()); && parent::canDelete());
@ -92,13 +97,13 @@ class Child extends CommonDBChild {
// This method define the name to set inside the history of the parent. // This method define the name to set inside the history of the parent.
// All these methods use $log_history_add, $log_history_update and $log_history_delete to // All these methods use $log_history_add, $log_history_update and $log_history_delete to
// define the level of log (Log::HISTORY_ADD_DEVICE, Log::HISTORY_UPDATE_DEVICE ...) // define the level of log (Log::HISTORY_ADD_DEVICE, Log::HISTORY_UPDATE_DEVICE ...)
function getHistoryName_for_item($case) { public function getHistoryName_for_item($case) {}
}
// CommonDBChild also check if we can add or updatethe item regarding the new item // CommonDBChild also check if we can add or updatethe item regarding the new item
// ($input[static::$itemtype] and $input[static::$items_id]). // ($input[static::$itemtype] and $input[static::$items_id]).
// But don't forget to call parent::prepareInputForAdd() // But don't forget to call parent::prepareInputForAdd()
function prepareInputForAdd($input) { public function prepareInputForAdd($input)
{
// My preparation on $input // My preparation on $input
return parent::prepareInputForAdd($input); return parent::prepareInputForAdd($input);
} }

View File

@ -34,17 +34,13 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDBTM; use CommonDBTM;
// Class of the defined type class Computer extends CommonDBTM
{
if (!defined('GLPI_ROOT')) { public static function showInfo()
die("Sorry. You can't access directly to this file"); {
}
class Computer extends CommonDBTM {
static function showInfo() {
echo '<table class="tab_glpi" width="100%">'; echo '<table class="tab_glpi" width="100%">';
echo '<tr>'; echo '<tr>';
@ -59,7 +55,8 @@ class Computer extends CommonDBTM {
} }
static function item_can($item) { public static function item_can($item)
{
if (($item->getType() == 'Computer') if (($item->getType() == 'Computer')
&& ($item->right == READ) && ($item->right == READ)
@ -70,7 +67,8 @@ class Computer extends CommonDBTM {
} }
static function add_default_where($in) { public static function add_default_where($in)
{
list($itemtype, $condition) = $in; list($itemtype, $condition) = $in;
if ($itemtype == 'Computer') { if ($itemtype == 'Computer') {

View File

@ -29,6 +29,7 @@
*/ */
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDBTM; use CommonDBTM;
use CommonGLPI; use CommonGLPI;
use Config as GlpiConfig; use Config as GlpiConfig;
@ -37,11 +38,12 @@ use Html;
use Session; use Session;
use Toolbox; use Toolbox;
class Config extends CommonDBTM { class Config extends CommonDBTM
{
protected static $notable = true;
static protected $notable = true; public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)
{
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if (!$withtemplate) { if (!$withtemplate) {
if ($item->getType() == 'Config') { if ($item->getType() == 'Config') {
@ -51,12 +53,15 @@ class Config extends CommonDBTM {
return ''; return '';
} }
static function configUpdate($input) { public static function configUpdate($input)
{
$input['configuration'] = 1 - $input['configuration']; $input['configuration'] = 1 - $input['configuration'];
return $input; return $input;
} }
function showFormExample() { public function showFormExample()
{
/** @var array $CFG_GLPI */
global $CFG_GLPI; global $CFG_GLPI;
if (!Session::haveRight("config", UPDATE)) { if (!Session::haveRight("config", UPDATE)) {
@ -85,12 +90,13 @@ class Config extends CommonDBTM {
Html::closeForm(); Html::closeForm();
} }
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) { public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
{
if ($item->getType() == 'Config') { if ($item->getType() == Config::class) {
$config = new self(); $config = new self();
$config->showFormExample(); $config->showFormExample();
} }
return true;
} }
} }

View File

@ -34,18 +34,14 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDevice; use CommonDevice;
// Class of the defined type
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/// Class DeviceCamera /// Class DeviceCamera
class DeviceCamera extends CommonDevice { class DeviceCamera extends CommonDevice
{
static function getTypeName($nb = 0) { public static function getTypeName($nb = 0)
{
return _n('Camera', 'Cameras', $nb); return _n('Camera', 'Cameras', $nb);
} }

View File

@ -1,30 +1,31 @@
<?php <?php
/* /**
------------------------------------------------------------------------- * -------------------------------------------------------------------------
GLPI - Gestionnaire Libre de Parc Informatique * Example plugin for GLPI
Copyright (C) 2003-2011 by the INDEPNET Development Team. * -------------------------------------------------------------------------
*
http://indepnet.net/ http://glpi-project.org * LICENSE
------------------------------------------------------------------------- *
* This file is part of Example.
LICENSE *
* Example is free software; you can redistribute it and/or modify
This file is part of GLPI. * it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
GLPI is free software; you can redistribute it and/or modify * (at your option) any later version.
it under the terms of the GNU General Public License as published by *
the Free Software Foundation; either version 2 of the License, or * Example is distributed in the hope that it will be useful,
(at your option) any later version. * but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GLPI is distributed in the hope that it will be useful, * GNU General Public License for more details.
but WITHOUT ANY WARRANTY; without even the implied warranty of *
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * You should have received a copy of the GNU General Public License
GNU General Public License for more details. * along with Example. If not, see <http://www.gnu.org/licenses/>.
* -------------------------------------------------------------------------
You should have received a copy of the GNU General Public License * @copyright Copyright (C) 2006-2022 by Example plugin team.
along with GLPI. If not, see <http://www.gnu.org/licenses/>. * @license GPLv2 https://www.gnu.org/licenses/gpl-2.0.html
-------------------------------------------------------------------------- * @link https://github.com/pluginsGLPI/example
* -------------------------------------------------------------------------
*/ */
/** /**
@ -55,14 +56,14 @@ along with GLPI. If not, see <http://www.gnu.org/licenses/>.
*/ */
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use Document as GlpiDocument; use Document as GlpiDocument;
use Exception;
use Glpi\Exception\Http\NotFoundHttpException;
use Sabre\DAV\Exception\BadRequest;
if (!defined('GLPI_ROOT')) { class Document extends GlpiDocument
die("Sorry. You can't access this file directly"); {
}
class Document extends GlpiDocument {
/** /**
* Return the table used to store this object. Overloads the implementation in CommonDBTM * Return the table used to store this object. Overloads the implementation in CommonDBTM
* *
@ -70,7 +71,8 @@ class Document extends GlpiDocument {
* *
* @return string * @return string
**/ **/
public static function getTable($classname = null) { public static function getTable($classname = null)
{
if ($classname === null) { if ($classname === null) {
$classname = get_called_class(); $classname = get_called_class();
} }
@ -87,7 +89,8 @@ class Document extends GlpiDocument {
* @param array $input * @param array $input
* @return array|false * @return array|false
*/ */
public function prepareInputForAdd($input) { public function prepareInputForAdd($input)
{
$input['_only_if_upload_succeed'] = true; $input['_only_if_upload_succeed'] = true;
if (!isset($_FILES['file'])) { if (!isset($_FILES['file'])) {
return false; return false;
@ -110,7 +113,8 @@ class Document extends GlpiDocument {
* @param array $input * @param array $input
* @return array|false * @return array|false
*/ */
public function prepareInputForUpdate($input) { public function prepareInputForUpdate($input)
{
// Do not allow update of document // Do not allow update of document
return false; return false;
} }
@ -121,7 +125,8 @@ class Document extends GlpiDocument {
* *
* @return void * @return void
*/ */
public function post_getFromDB() { public function post_getFromDB()
{
// Check the user can view this itemtype and can view this item // Check the user can view this itemtype and can view this item
if ($this->canView() && $this->canViewItem()) { if ($this->canView() && $this->canViewItem()) {
if (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == 'application/octet-stream' if (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == 'application/octet-stream'
@ -136,13 +141,14 @@ class Document extends GlpiDocument {
* *
* @return void * @return void
*/ */
protected function sendFile() { protected function sendFile()
{
$streamSource = GLPI_DOC_DIR . '/' . $this->fields['filepath']; $streamSource = GLPI_DOC_DIR . '/' . $this->fields['filepath'];
// Ensure the file exists // Ensure the file exists
if (!file_exists($streamSource) || !is_file($streamSource)) { if (!file_exists($streamSource) || !is_file($streamSource)) {
header("HTTP/1.0 404 Not Found"); header("HTTP/1.0 404 Not Found");
exit(0); throw new NotFoundHttpException();
} }
// Download range defaults to the full file // Download range defaults to the full file
@ -157,7 +163,7 @@ class Document extends GlpiDocument {
$fileHandle = @fopen($streamSource, 'rb'); $fileHandle = @fopen($streamSource, 'rb');
if (!$fileHandle) { if (!$fileHandle) {
header("HTTP/1.0 500 Internal Server Error"); header("HTTP/1.0 500 Internal Server Error");
exit(0); throw new Exception();
} }
// set range if specified by the client // set range if specified by the client
@ -176,7 +182,7 @@ class Document extends GlpiDocument {
$currentPosition = $begin; $currentPosition = $begin;
if (fseek($fileHandle, $begin, SEEK_SET) < 0) { if (fseek($fileHandle, $begin, SEEK_SET) < 0) {
header("HTTP/1.0 500 Internal Server Error"); header("HTTP/1.0 500 Internal Server Error");
exit(0); throw new Exception();
} }
// send headers to ensure the client is able to detect a corrupted download // send headers to ensure the client is able to detect a corrupted download
@ -209,7 +215,7 @@ class Document extends GlpiDocument {
$content = fread($fileHandle, min(1024 * 16, $end - $currentPosition + 1)); $content = fread($fileHandle, min(1024 * 16, $end - $currentPosition + 1));
if ($content === false) { if ($content === false) {
header("HTTP/1.0 500 Internal Server Error", true); // Replace previously sent headers header("HTTP/1.0 500 Internal Server Error", true); // Replace previously sent headers
exit(0); throw new Exception();
} else { } else {
print $content; print $content;
} }
@ -218,7 +224,7 @@ class Document extends GlpiDocument {
} }
// End now to prevent any unwanted bytes // End now to prevent any unwanted bytes
exit(0); return;
} }
} }

View File

@ -32,14 +32,16 @@
// Original Author of file: // Original Author of file:
// Purpose of file: // Purpose of file:
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDropdown; use CommonDropdown;
// Class for a Dropdown // Class for a Dropdown
class Dropdown extends CommonDropdown { class Dropdown extends CommonDropdown
{
public static function getTypeName($nb = 0)
static function getTypeName($nb = 0) { {
if ($nb > 0) { if ($nb > 0) {
return __('Plugin Example Dropdowns', 'example'); return __('Plugin Example Dropdowns', 'example');

View File

@ -34,30 +34,36 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDBTM; use CommonDBTM;
use CommonGLPI; use CommonGLPI;
use Computer; use Computer;
use DBmysql;
use Html; use Html;
use Log; use Log;
use MassiveAction; use MassiveAction;
use Session; use Session;
// Class of the defined type // Class of the defined type
class Example extends CommonDBTM { class Example extends CommonDBTM
{
static $tags = '[EXAMPLE_ID]'; public static $tags = '[EXAMPLE_ID]';
public static $rightname = 'plugin_example'; public static $rightname = 'plugin_example';
// Should return the localized name of the type // Should return the localized name of the type
static function getTypeName($nb = 0) { public static function getTypeName($nb = 0)
{
return 'Example Type'; return 'Example Type';
} }
static function getMenuName() { public static function getMenuName()
{
return __('Example plugin'); return __('Example plugin');
} }
static function getAdditionalMenuLinks() { public static function getAdditionalMenuLinks()
{
/** @var array $CFG_GLPI */
global $CFG_GLPI; global $CFG_GLPI;
$links = []; $links = [];
@ -68,7 +74,8 @@ class Example extends CommonDBTM {
return $links; return $links;
} }
function defineTabs($options = []) { public function defineTabs($options = [])
{
$ong = []; $ong = [];
$this->addDefaultFormTab($ong); $this->addDefaultFormTab($ong);
@ -77,9 +84,8 @@ class Example extends CommonDBTM {
return $ong; return $ong;
} }
function showForm($ID, array $options = []) { public function showForm($ID, array $options = [])
global $CFG_GLPI; {
$this->initForm($ID, $options); $this->initForm($ID, $options);
$this->showFormHeader($options); $this->showFormHeader($options);
@ -95,13 +101,14 @@ class Example extends CommonDBTM {
return true; return true;
} }
function rawSearchOptions() { public function rawSearchOptions()
{
$tab = []; $tab = [];
$tab[] = [ $tab[] = [
'id' => 'common', 'id' => 'common',
'name' => __('Header Needed') 'name' => __('Header Needed'),
]; ];
$tab[] = [ $tab[] = [
@ -147,7 +154,8 @@ class Example extends CommonDBTM {
* *
* @return array of strings * @return array of strings
*/ */
static function cronInfo($name) { public static function cronInfo($name)
{
switch ($name) { switch ($name) {
case 'Sample': case 'Sample':
@ -163,13 +171,13 @@ class Example extends CommonDBTM {
* *
* @param $task Object of CronTask class for log / stat * @param $task Object of CronTask class for log / stat
* *
* @return interger * @return int
* >0 : done * >0 : done
* <0 : to be run again (not finished) * <0 : to be run again (not finished)
* 0 : nothing to do * 0 : nothing to do
*/ */
static function cronSample($task) { public static function cronSample($task)
{
$task->log("Example log message from class"); $task->log("Example log message from class");
$r = mt_rand(0, $task->fields['param']); $r = mt_rand(0, $task->fields['param']);
usleep(1000000 + $r * 1000); usleep(1000000 + $r * 1000);
@ -180,7 +188,8 @@ class Example extends CommonDBTM {
// Hook done on before add item case (data from form, not altered) // Hook done on before add item case (data from form, not altered)
static function pre_item_add_computer(Computer $item) { public static function pre_item_add_computer(Computer $item)
{
if (isset($item->input['name']) && empty($item->input['name'])) { if (isset($item->input['name']) && empty($item->input['name'])) {
Session::addMessageAfterRedirect("Pre Add Computer Hook KO (name empty)", true); Session::addMessageAfterRedirect("Pre Add Computer Hook KO (name empty)", true);
return $item->input = false; return $item->input = false;
@ -190,65 +199,66 @@ class Example extends CommonDBTM {
} }
// Hook done on before add item case (data altered by object prepareInputForAdd) // Hook done on before add item case (data altered by object prepareInputForAdd)
static function post_prepareadd_computer(Computer $item) { public static function post_prepareadd_computer(Computer $item)
{
Session::addMessageAfterRedirect("Post prepareAdd Computer Hook", true); Session::addMessageAfterRedirect("Post prepareAdd Computer Hook", true);
} }
// Hook done on add item case // Hook done on add item case
static function item_add_computer(Computer $item) { public static function item_add_computer(Computer $item)
{
Session::addMessageAfterRedirect("Add Computer Hook, ID=" . $item->getID(), true); Session::addMessageAfterRedirect("Add Computer Hook, ID=" . $item->getID(), true);
return true; return true;
} }
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)
{
if (!$withtemplate) { if (!$withtemplate) {
switch ($item->getType()) { if ($item instanceof \Profile) {
case 'Profile' :
if ($item->getField('central')) { if ($item->getField('central')) {
return __('Example', 'example'); return __('Example', 'example');
} }
break;
case 'Phone' : } elseif ($item instanceof \Phone) {
if ($_SESSION['glpishow_count_on_tabs']) { if ($_SESSION['glpishow_count_on_tabs']) {
return self::createTabEntry(__('Example', 'example'), return self::createTabEntry(
countElementsInTable($this->getTable())); __('Example', 'example'),
countElementsInTable($this->getTable()),
);
} }
return __('Example', 'example'); return __('Example', 'example');
case 'ComputerDisk' : } elseif ($item instanceof \Item_Disk || $item instanceof \Supplier) {
case 'Supplier' : return [
return [1 => __("Test Plugin", 'example'), 1 => __("Test Plugin", 'example'),
2 => __("Test Plugin 2", 'example')]; 2 => __("Test Plugin 2", 'example'),
];
case 'Computer' : } elseif (
case 'Central' : $item instanceof \Computer ||
case 'Preference': $item instanceof \Central ||
case 'Notification': $item instanceof \Preference ||
$item instanceof \Notification
) {
return [1 => __("Test Plugin", 'example')]; return [1 => __("Test Plugin", 'example')];
}
}
}
}
return ''; return '';
} }
public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) { {
if ($item instanceof \Phone) {
switch ($item->getType()) {
case 'Phone' :
echo __("Plugin Example on Phone", 'example'); echo __("Plugin Example on Phone", 'example');
break;
case 'Central' : } elseif ($item instanceof \Central) {
echo __("Plugin central action", 'example'); echo __("Plugin central action", 'example');
break;
case 'Preference' : } elseif ($item instanceof \Preference) {
// Complete form display // Complete form display
$data = plugin_version_example(); $data = plugin_version_example();
@ -259,36 +269,33 @@ class Example extends CommonDBTM {
echo "<tr class='tab_bg_1'><td>Name of the pref</td>"; echo "<tr class='tab_bg_1'><td>Name of the pref</td>";
echo "<td>Input to set the pref</td>"; echo "<td>Input to set the pref</td>";
echo "<td><input class='submit' type='submit' name='submit' value='submit'></td>"; echo "<td><input class='submit' type='submit' name='submit' value='submit'></td>";
echo "</tr>"; echo "</tr>";
echo "</table>"; echo "</table>";
echo "</form>"; echo "</form>";
break;
case 'Notification' : } elseif ($item instanceof \Notification) {
echo __("Plugin mailing action", 'example'); echo __("Plugin mailing action", 'example');
break;
case 'ComputerDisk' : } elseif ($item instanceof \Item_Disk || $item instanceof \Supplier) {
case 'Supplier' :
if ($tabnum == 1) { if ($tabnum == 1) {
echo __('First tab of Plugin example', 'example'); echo __('First tab of Plugin example', 'example');
} else { } else {
echo __('Second tab of Plugin example', 'example'); echo __('Second tab of Plugin example', 'example');
} }
break;
default : } else {
//TRANS: %1$s is a class name, %2$d is an item ID //TRANS: %1$s is a class name, %2$d is an item ID
printf(__('Plugin example CLASS=%1$s id=%2$d', 'example'), $item->getType(), $item->getField('id')); printf(__('Plugin example CLASS=%1$s', 'example'), get_class($item));
break;
} }
return true; return true;
} }
static function getSpecificValueToDisplay($field, $values, array $options = []) {
public static function getSpecificValueToDisplay($field, $values, array $options = [])
{
if (!is_array($values)) { if (!is_array($values)) {
$values = [$field => $values]; $values = [$field => $values];
@ -302,7 +309,8 @@ class Example extends CommonDBTM {
// Parm contains begin, end and who // Parm contains begin, end and who
// Create data to be displayed in the planning of $parm["who"] or $parm["who_group"] between $parm["begin"] and $parm["end"] // Create data to be displayed in the planning of $parm["who"] or $parm["who_group"] between $parm["begin"] and $parm["end"]
static function populatePlanning($parm) { public static function populatePlanning($parm)
{
// Add items in the output array // Add items in the output array
// Items need to have an unique index beginning by the begin date of the item to display // Items need to have an unique index beginning by the begin date of the item to display
@ -322,40 +330,47 @@ class Example extends CommonDBTM {
/** /**
* Display a Planning Item * Display a Planning Item
* *
* @param $val Array of the item to display * @param array $val array of the item to display
* @param $who ID of the user (0 if all) * @param integer $who ID of the user (0 if all)
* @param $type position of the item in the time block (in, through, begin or end) * @param string $type position of the item in the time block (in, through, begin or end)
* @param $complete complete display (more details) * @param integer|boolean $complete complete display (more details)
* *
* @return Nothing (display function) * @return string
**/ */
static function displayPlanningItem(array $val, $who, $type = "", $complete = 0) { public static function displayPlanningItem(array $val, $who, $type = "", $complete = 0)
{
// $parm["type"] say begin end in or from type // $parm["type"] say begin end in or from type
// Add items in the items fields of the parm array // Add items in the items fields of the parm array
$out = '';
switch ($type) { switch ($type) {
case "in": case "in":
//TRANS: %1$s is the start time of a planned item, %2$s is the end //TRANS: %1$s is the start time of a planned item, %2$s is the end
printf(__('From %1$s to %2$s :'), $out .= sprintf(
date("H:i", strtotime($val["begin"])), date("H:i", strtotime($val["end"]))); __('From %1$s to %2$s :'),
date("H:i", strtotime($val["begin"])),
date("H:i", strtotime($val["end"])),
);
break; break;
case "through": case "through":
echo Html::resume_text($val["name"], 80); $out .= Html::resume_text($val["name"], 80);
break; break;
case "begin": case "begin":
//TRANS: %s is the start time of a planned item //TRANS: %s is the start time of a planned item
printf(__('Start at %s:'), date("H:i", strtotime($val["begin"]))); $out .= sprintf(__('Start at %s:'), date("H:i", strtotime($val["begin"])));
break; break;
case "end": case "end":
//TRANS: %s is the end time of a planned item //TRANS: %s is the end time of a planned item
printf(__('End at %s:'), date("H:i", strtotime($val["end"]))); $out .= sprintf(__('End at %s:'), date("H:i", strtotime($val["end"])));
break; break;
} }
echo "<br>"; $out .= "<br>";
echo Html::resume_text($val["name"], 80); $out .= Html::resume_text($val["name"], 80);
return $out;
} }
/** /**
@ -367,7 +382,8 @@ class Example extends CommonDBTM {
* *
* @return string * @return string
**/ **/
static function getHistoryEntry($data) { public static function getHistoryEntry($data)
{
switch ($data['linked_action'] - Log::HISTORY_PLUGIN) { switch ($data['linked_action'] - Log::HISTORY_PLUGIN) {
case 0: case 0:
@ -380,7 +396,8 @@ class Example extends CommonDBTM {
////////////////////////////// //////////////////////////////
////// SPECIFIC MODIF MASSIVE FUNCTIONS /////// ////// SPECIFIC MODIF MASSIVE FUNCTIONS ///////
function getSpecificMassiveActions($checkitem = null) { public function getSpecificMassiveActions($checkitem = null)
{
$actions = parent::getSpecificMassiveActions($checkitem); $actions = parent::getSpecificMassiveActions($checkitem);
@ -392,7 +409,8 @@ class Example extends CommonDBTM {
return $actions; return $actions;
} }
static function showMassiveActionsSubForm(MassiveAction $ma) { public static function showMassiveActionsSubForm(MassiveAction $ma)
{
switch ($ma->getAction()) { switch ($ma->getAction()) {
case 'DoIt': case 'DoIt':
@ -414,10 +432,11 @@ class Example extends CommonDBTM {
* *
* @see CommonDBTM::processMassiveActionsForOneItemtype() * @see CommonDBTM::processMassiveActionsForOneItemtype()
**/ **/
static function processMassiveActionsForOneItemtype(MassiveAction $ma, CommonDBTM $item, public static function processMassiveActionsForOneItemtype(
array $ids) { MassiveAction $ma,
global $DB; CommonDBTM $item,
array $ids
) {
switch ($ma->getAction()) { switch ($ma->getAction()) {
case 'DoIt': case 'DoIt':
if ($item->getType() == 'Computer') { if ($item->getType() == 'Computer') {
@ -427,8 +446,13 @@ class Example extends CommonDBTM {
foreach ($ids as $id) { foreach ($ids as $id) {
if ($item->getFromDB($id)) { if ($item->getFromDB($id)) {
Session::addMessageAfterRedirect("- " . $item->getField("name")); Session::addMessageAfterRedirect("- " . $item->getField("name"));
Log::history($id, 'Computer', $changes, Example::class, Log::history(
Log::HISTORY_PLUGIN); $id,
'Computer',
$changes,
Example::class,
Log::HISTORY_PLUGIN,
);
$ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK); $ma->itemDone($item->getType(), $id, MassiveAction::ACTION_OK);
} else { } else {
// Example of ko count // Example of ko count
@ -442,10 +466,12 @@ class Example extends CommonDBTM {
return; return;
case 'do_nothing': case 'do_nothing':
If ($item->getType() == Example::class) { if ($item->getType() == Example::class) {
Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example')); Session::addMessageAfterRedirect(__("Right it is the type I want...", 'example'));
Session::addMessageAfterRedirect(__("But... I say I will do nothing for:", Session::addMessageAfterRedirect(__(
'example')); "But... I say I will do nothing for:",
'example',
));
foreach ($ids as $id) { foreach ($ids as $id) {
if ($item->getFromDB($id)) { if ($item->getFromDB($id)) {
Session::addMessageAfterRedirect("- " . $item->getField("name")); Session::addMessageAfterRedirect("- " . $item->getField("name"));
@ -458,23 +484,24 @@ class Example extends CommonDBTM {
} else { } else {
$ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO); $ma->itemDone($item->getType(), $ids, MassiveAction::ACTION_KO);
} }
Return; return;
} }
parent::processMassiveActionsForOneItemtype($ma, $item, $ids); parent::processMassiveActionsForOneItemtype($ma, $item, $ids);
} }
static function generateLinkContents($link, CommonDBTM $item) { public static function generateLinkContents($link, CommonDBTM $item, bool $safe_url = true)
{
if (strstr($link, "[EXAMPLE_ID]")) { if (strstr($link, "[EXAMPLE_ID]")) {
$link = str_replace("[EXAMPLE_ID]", $item->getID(), $link); $link = str_replace("[EXAMPLE_ID]", (string) $item->getID(), $link);
return [$link]; return [$link];
} }
return parent::generateLinkContents($link, $item); return parent::generateLinkContents($link, $item, $safe_url);
} }
static function dashboardTypes() { public static function dashboardTypes()
{
return [ return [
'example' => [ 'example' => [
'label' => __("Plugin Example", 'example'), 'label' => __("Plugin Example", 'example'),
@ -490,7 +517,8 @@ class Example extends CommonDBTM {
} }
static function dashboardCards($cards = []) { public static function dashboardCards($cards = [])
{
if (is_null($cards)) { if (is_null($cards)) {
$cards = []; $cards = [];
} }
@ -515,7 +543,8 @@ class Example extends CommonDBTM {
} }
static function cardWidget(array $params = []) { public static function cardWidget(array $params = [])
{
$default = [ $default = [
'data' => [], 'data' => [],
'title' => '', 'title' => '',
@ -539,7 +568,8 @@ class Example extends CommonDBTM {
return $html; return $html;
} }
static function cardDataProvider(array $params = []) { public static function cardDataProvider(array $params = [])
{
$default_params = [ $default_params = [
'label' => null, 'label' => null,
'icon' => "fas fa-smile-wink", 'icon' => "fas fa-smile-wink",
@ -553,11 +583,12 @@ class Example extends CommonDBTM {
'test1', 'test1',
'test2', 'test2',
'test3', 'test3',
] ],
]; ];
} }
static function cardWidgetWithoutProvider(array $params = []) { public static function cardWidgetWithoutProvider(array $params = [])
{
$default = [ $default = [
// this property is "pretty" mandatory, // this property is "pretty" mandatory,
// as it contains the colors selected when adding widget on the grid send // as it contains the colors selected when adding widget on the grid send
@ -576,7 +607,8 @@ class Example extends CommonDBTM {
return $html; return $html;
} }
static function cardBigNumberProvider(array $params = []) { public static function cardBigNumberProvider(array $params = [])
{
$default_params = [ $default_params = [
'label' => null, 'label' => null,
'icon' => null, 'icon' => null,

View File

@ -48,6 +48,7 @@ class ComputerModelFilter extends AbstractFilter
public static function canBeApplied(string $table): bool public static function canBeApplied(string $table): bool
{ {
/** @var DBmysql $DB */
global $DB; global $DB;
return $DB->fieldExists($table, ComputerModel::getForeignKeyField()); return $DB->fieldExists($table, ComputerModel::getForeignKeyField());
@ -59,7 +60,7 @@ class ComputerModelFilter extends AbstractFilter
self::getName(), self::getName(),
is_string($value) ? $value : "", is_string($value) ? $value : "",
self::getId(), self::getId(),
ComputerModel::class ComputerModel::class,
); );
} }
@ -69,8 +70,8 @@ class ComputerModelFilter extends AbstractFilter
$field = ComputerModel::getForeignKeyField(); $field = ComputerModel::getForeignKeyField();
return [ return [
"WHERE" => [ "WHERE" => [
"$table.$field" => (int) $value "$table.$field" => (int) $value,
] ],
]; ];
} }
@ -88,9 +89,9 @@ class ComputerModelFilter extends AbstractFilter
'field' => self::getSearchOptionID( 'field' => self::getSearchOptionID(
$table, $table,
ComputerModel::getForeignKeyField(), ComputerModel::getForeignKeyField(),
ComputerModel::getTable() ComputerModel::getTable(),
), ),
] ],
]; ];
} }

View File

@ -39,9 +39,8 @@ use Ticket;
* Example of *_item_form implementation * Example of *_item_form implementation
* @see http://glpi-developer-documentation.rtfd.io/en/master/plugins/hooks.html#items-display-related * @see http://glpi-developer-documentation.rtfd.io/en/master/plugins/hooks.html#items-display-related
* */ * */
class ItemForm { class ItemForm
{
/** /**
* Display contents at the begining of ITILObject section (right panel). * Display contents at the begining of ITILObject section (right panel).
* *
@ -49,7 +48,8 @@ class ItemForm {
* *
* @return void * @return void
*/ */
static public function preSection($params) { public static function preSection($params)
{
$item = $params['item']; $item = $params['item'];
$options = $params['options']; $options = $params['options'];
@ -80,7 +80,8 @@ TWIG, []);
* *
* @return void * @return void
*/ */
static public function postSection($params) { public static function postSection($params)
{
$item = $params['item']; $item = $params['item'];
$options = $params['options']; $options = $params['options'];
@ -114,7 +115,8 @@ TWIG, []);
* *
* @return void * @return void
*/ */
static public function preItemForm($params) { public static function preItemForm($params)
{
$item = $params['item']; $item = $params['item'];
$options = $params['options']; $options = $params['options'];
@ -124,7 +126,7 @@ TWIG, []);
$out .= sprintf( $out .= sprintf(
__('Start %1$s hook call for %2$s type'), __('Start %1$s hook call for %2$s type'),
'pre_item_form', 'pre_item_form',
$item::getType() $item::getType(),
); );
$out .= '</th></tr>'; $out .= '</th></tr>';
@ -142,7 +144,7 @@ TWIG, []);
$out .= sprintf( $out .= sprintf(
__('End %1$s hook call for %2$s type'), __('End %1$s hook call for %2$s type'),
'pre_item_form', 'pre_item_form',
$item::getType() $item::getType(),
); );
$out .= '</th></tr>'; $out .= '</th></tr>';
@ -156,7 +158,8 @@ TWIG, []);
* *
* @return void * @return void
*/ */
static public function postItemForm($params) { public static function postItemForm($params)
{
$item = $params['item']; $item = $params['item'];
$options = $params['options']; $options = $params['options'];
@ -166,7 +169,7 @@ TWIG, []);
$out .= sprintf( $out .= sprintf(
__('Start %1$s hook call for %2$s type'), __('Start %1$s hook call for %2$s type'),
'post_item_form', 'post_item_form',
$item::getType() $item::getType(),
); );
$out .= '</th></tr>'; $out .= '</th></tr>';
@ -184,14 +187,15 @@ TWIG, []);
$out .= sprintf( $out .= sprintf(
__('End %1$s hook call for %2$s type'), __('End %1$s hook call for %2$s type'),
'post_item_form', 'post_item_form',
$item::getType() $item::getType(),
); );
$out .= '</th></tr>'; $out .= '</th></tr>';
echo $out; echo $out;
} }
static public function timelineActions($params = []) { public static function timelineActions($params = [])
{
$rand = $params['rand']; $rand = $params['rand'];
$ticket = $params['item']; $ticket = $params['item'];

View File

@ -36,21 +36,18 @@
// Class of the defined type // Class of the defined type
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use GlpiPlugin\Example\DeviceCamera; use GlpiPlugin\Example\DeviceCamera;
use Item_Devices; use Item_Devices;
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/** /**
* Relation between item and devices * Relation between item and devices
**/ **/
class Item_DeviceCamera extends Item_Devices { class Item_DeviceCamera extends Item_Devices
{
public static $itemtype_2 = DeviceCamera::class;
public static $items_id_2 = 'plugin_example_devicecameras_id';
static public $itemtype_2 = DeviceCamera::class; protected static $notable = false;
static public $items_id_2 = 'plugin_example_devicecameras_id';
static protected $notable = false;
} }

View File

@ -29,22 +29,19 @@
*/ */
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use NotificationTarget; use NotificationTarget;
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
// Class NotificationTarget // Class NotificationTarget
class NotificationTargetExample extends NotificationTarget { class NotificationTargetExample extends NotificationTarget
{
function getEvents() { public function getEvents()
{
return ['alert' => 'alert example']; return ['alert' => 'alert example'];
} }
function addDataForTemplate($event, $options = []) { public function addDataForTemplate($event, $options = [])
global $DB, $CFG_GLPI; {
$this->data['##example.name##'] = __('Example', 'example'); $this->data['##example.name##'] = __('Example', 'example');
} }
} }

View File

@ -34,18 +34,28 @@ use CommonGLPI;
use Html; use Html;
use Session; use Session;
final class Profile extends \Profile class Profile extends \Profile
{ {
public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0)
{ {
return __('Example plugin'); if (
$item instanceof \Profile
&& $item->getField('id')
) {
return self::createTabEntry(__('Example plugin'));
}
return '';
} }
public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
{ {
if ($item instanceof self) {
$profile = new self(); $profile = new self();
$profile->showFormExample($item->getID()); $profile->showFormExample($item->getID());
} }
return true;
}
public function showFormExample(int $profiles_id): void public function showFormExample(int $profiles_id): void
{ {
@ -67,8 +77,8 @@ final class Profile extends \Profile
[ [
'itemtype' => Example::class, 'itemtype' => Example::class,
'label' => Example::getTypeName(Session::getPluralNumber()), 'label' => Example::getTypeName(Session::getPluralNumber()),
'field' => Example::$rightname 'field' => Example::$rightname,
] ],
]; ];
$matrix_options['title'] = self::getTypeName(1); $matrix_options['title'] = self::getTypeName(1);
$this->displayRightsChoiceMatrix($rights, $matrix_options); $this->displayRightsChoiceMatrix($rights, $matrix_options);

View File

@ -34,13 +34,9 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use Rule; use Rule;
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
/** /**
* Rule class store all informations about a GLPI rule : * Rule class store all informations about a GLPI rule :
* - description * - description
@ -48,24 +44,27 @@ if (!defined('GLPI_ROOT')) {
* - actions * - actions
* *
**/ **/
class RuleTest extends Rule { class RuleTest extends Rule
{
// From Rule // From Rule
public static $rightname = 'rule_import'; public static $rightname = 'rule_import';
public $can_sort = true; public $can_sort = true;
function getTitle() { public function getTitle()
{
return 'test'; return 'test';
} }
function maxActionsCount() { public function maxActionsCount()
{
return 1; return 1;
} }
function getCriterias() { public function getCriterias()
{
$criterias = []; $criterias = [];
$criterias['name']['field'] = 'name'; $criterias['name']['field'] = 'name';
@ -76,7 +75,8 @@ class RuleTest extends Rule {
} }
function getActions() { public function getActions()
{
$actions = []; $actions = [];
$actions['softwarecategories_id']['name'] = __('Category (class)', 'example'); $actions['softwarecategories_id']['name'] = __('Category (class)', 'example');

View File

@ -34,21 +34,18 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use RuleCollection; use RuleCollection;
if (!defined('GLPI_ROOT')) { class RuleTestCollection extends RuleCollection
die("Sorry. You can't access directly to this file"); {
}
class RuleTestCollection extends RuleCollection {
// From RuleCollection // From RuleCollection
public $stop_on_first_match = true; public $stop_on_first_match = true;
public static $rightname = 'rule_import'; public static $rightname = 'rule_import';
public $menu_option = 'test'; public $menu_option = 'test';
function getTitle() { public function getTitle()
{
return 'Rulesengine test'; return 'Rulesengine test';
} }
} }

View File

@ -51,8 +51,8 @@ namespace GlpiPlugin\Example;
* post_show_tab will be fired after the tab show * post_show_tab will be fired after the tab show
* *
* */ * */
class Showtabitem { class Showtabitem
{
/** /**
* Summary of pre_show_tab * Summary of pre_show_tab
* @param array $params is an array like following * @param array $params is an array like following
@ -64,7 +64,8 @@ class Showtabitem {
* and 'itemtype' is the type of the tab (ex: 'ITILFollowup' when showing followup tab in a ticket) * and 'itemtype' is the type of the tab (ex: 'ITILFollowup' when showing followup tab in a ticket)
* Note: you may pass datas to post_show_tab using the $param['options'] array (see example below) * Note: you may pass datas to post_show_tab using the $param['options'] array (see example below)
*/ */
static function pre_show_tab($params) { public static function pre_show_tab($params)
{
switch ($params['item']->getType()) { switch ($params['item']->getType()) {
case 'Ticket': case 'Ticket':
if ($params['options']['itemtype'] == 'TicketValidation' && $params['options']['tabnum'] == 2) { if ($params['options']['itemtype'] == 'TicketValidation' && $params['options']['tabnum'] == 2) {
@ -84,7 +85,8 @@ class Showtabitem {
* @param array $params is identical to pre_show_tab parameter * @param array $params is identical to pre_show_tab parameter
* Note: you may get datas from pre_show_tab in $param['options'] array (see example below) * Note: you may get datas from pre_show_tab in $param['options'] array (see example below)
*/ */
static function post_show_tab($params) { public static function post_show_tab($params)
{
switch ($params['item']->getType()) { switch ($params['item']->getType()) {
case 'Ticket': case 'Ticket':
if (isset($params['options']['prevent_solution'])) { if (isset($params['options']['prevent_solution'])) {
@ -143,7 +145,8 @@ class Showtabitem {
* and 'showprivate' is the right to show private items * and 'showprivate' is the right to show private items
* Note: you may pass datas to post_show_item using the $param['options'] array * Note: you may pass datas to post_show_item using the $param['options'] array
*/ */
static function pre_show_item($params) { public static function pre_show_item($params)
{
if (!is_array($params['item'])) { if (!is_array($params['item'])) {
switch ($params['item']->getType()) { switch ($params['item']->getType()) {
case 'Ticket': case 'Ticket':
@ -178,7 +181,8 @@ class Showtabitem {
* and 'showprivate' is the right to show private items * and 'showprivate' is the right to show private items
* Note: you may get datas from pre_show_item using the $param['options'] array * Note: you may get datas from pre_show_item using the $param['options'] array
*/ */
static function post_show_item($params) { public static function post_show_item($params)
{
if (!is_array($params['item'])) { if (!is_array($params['item'])) {
switch ($params['item']->getType()) { switch ($params['item']->getType()) {
case 'Ticket': case 'Ticket':