Merge pull request #89 from Rom1-B/feat_php-cs-fixer

Feat php cs fixer
This commit is contained in:
Stanislas
2025-07-16 08:38:54 +02:00
committed by GitHub
33 changed files with 3794 additions and 1864 deletions

20
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,20 @@
version: 2
updates:
# Ensure GitHub Actions are used in their latest version
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "monthly"
# Strategy for composer dependencies
- package-ecosystem: "composer"
directory: "/"
schedule:
interval: "monthly"
allow:
- dependency-type: "direct"
open-pull-requests-limit: 100
versioning-strategy: "increase"
groups:
dev-dependencies:
dependency-type: "development"

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

@@ -3,7 +3,8 @@
"php": ">=7.4" "php": ">=7.4"
}, },
"require-dev": { "require-dev": {
"glpi-project/tools": "^0.5" "friendsofphp/php-cs-fixer": "^3.75",
"glpi-project/tools": "^0.7.5"
}, },
"config": { "config": {
"optimize-autoloader": true, "optimize-autoloader": true,

2028
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -37,13 +37,13 @@
//header("Location:../../central.php"); //header("Location:../../central.php");
// Entry menu case // Entry menu case
include ("../../../inc/includes.php"); include('../../../inc/includes.php');
Session::checkRight("config", UPDATE); Session::checkRight('config', UPDATE);
// To be available when plugin in not activated // To be available when plugin in not activated
Plugin::load('example'); Plugin::load('example');
Html::header("TITRE", $_SERVER['PHP_SELF'], "config", "plugins"); Html::header('TITRE', $_SERVER['PHP_SELF'], 'config', 'plugins');
echo __("This is the plugin config page", 'example'); echo __('This is the plugin config page', 'example');
Html::footer(); Html::footer();

View File

@@ -35,8 +35,8 @@
use GlpiPlugin\Example\DeviceCamera; use GlpiPlugin\Example\DeviceCamera;
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkLoginUser(); Session::checkLoginUser();
$dropdown = new DeviceCamera(); $dropdown = new DeviceCamera();
include (GLPI_ROOT . "/front/dropdown.common.form.php"); include(GLPI_ROOT . '/front/dropdown.common.form.php');

View File

@@ -33,8 +33,8 @@
// Purpose of file: // Purpose of file:
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkLoginUser(); Session::checkLoginUser();
$dropdown = new DeviceCamera(); $dropdown = new DeviceCamera();
include (GLPI_ROOT . "/front/dropdown.common.php"); include(GLPI_ROOT . '/front/dropdown.common.php');

View File

@@ -35,10 +35,10 @@
use GlpiPlugin\Example\Dropdown; use GlpiPlugin\Example\Dropdown;
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkLoginUser(); Session::checkLoginUser();
Plugin::load('example', true); Plugin::load('example', true);
$dropdown = new Dropdown(); $dropdown = new Dropdown();
include (GLPI_ROOT . "/front/dropdown.common.form.php"); include(GLPI_ROOT . '/front/dropdown.common.form.php');

View File

@@ -35,10 +35,10 @@
use GlpiPlugin\Example\Dropdown; use GlpiPlugin\Example\Dropdown;
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkLoginUser(); Session::checkLoginUser();
Plugin::load('example', true); Plugin::load('example', true);
$dropdown = new Dropdown(); $dropdown = new Dropdown();
include (GLPI_ROOT . "/front/dropdown.common.php"); include(GLPI_ROOT . '/front/dropdown.common.php');

View File

@@ -35,13 +35,13 @@
use GlpiPlugin\Example\Example; use GlpiPlugin\Example\Example;
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkLoginUser(); Session::checkLoginUser();
if ($_SESSION["glpiactiveprofile"]["interface"] == "central") { if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
Html::header("TITRE", $_SERVER['PHP_SELF'], "plugins", Example::class, ""); Html::header('TITRE', $_SERVER['PHP_SELF'], 'plugins', Example::class, '');
} else { } else {
Html::helpHeader("TITRE", $_SERVER['PHP_SELF']); Html::helpHeader('TITRE', $_SERVER['PHP_SELF']);
} }
$example = new Example(); $example = new Example();

View File

@@ -35,13 +35,13 @@
use GlpiPlugin\Example\Example; use GlpiPlugin\Example\Example;
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkRight(Example::$rightname, READ); Session::checkRight(Example::$rightname, READ);
if ($_SESSION["glpiactiveprofile"]["interface"] == "central") { if ($_SESSION['glpiactiveprofile']['interface'] == 'central') {
Html::header("TITRE", $_SERVER['PHP_SELF'], "plugins", Example::class, ""); Html::header('TITRE', $_SERVER['PHP_SELF'], 'plugins', Example::class, '');
} else { } else {
Html::helpHeader("TITRE", $_SERVER['PHP_SELF']); Html::helpHeader('TITRE', $_SERVER['PHP_SELF']);
} }

View File

@@ -28,32 +28,32 @@
* ------------------------------------------------------------------------- * -------------------------------------------------------------------------
*/ */
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkLoginUser(); Session::checkLoginUser();
if (isset($_GET["popup"])) { if (isset($_GET['popup'])) {
$_SESSION["glpipopup"]["name"] = $_GET["popup"]; $_SESSION['glpipopup']['name'] = $_GET['popup'];
} }
if (isset($_SESSION["glpipopup"]["name"])) { if (isset($_SESSION['glpipopup']['name'])) {
switch ($_SESSION["glpipopup"]["name"]) { switch ($_SESSION['glpipopup']['name']) {
case "test_rule" : case 'test_rule':
Html::popHeader(__('Test'), $_SERVER['PHP_SELF']); Html::popHeader(__('Test'), $_SERVER['PHP_SELF']);
include "../../../front/rule.test.php"; include '../../../front/rule.test.php';
break; break;
case "test_all_rules" : case 'test_all_rules':
Html::popHeader(__('Test rules engine'), $_SERVER['PHP_SELF']); Html::popHeader(__('Test rules engine'), $_SERVER['PHP_SELF']);
include "../../../front/rulesengine.test.php"; include '../../../front/rulesengine.test.php';
break; break;
case "show_cache" : case 'show_cache':
Html::popHeader(__('Cache information'), $_SERVER['PHP_SELF']); Html::popHeader(__('Cache information'), $_SERVER['PHP_SELF']);
include "../../../front/rule.cache.php"; include '../../../front/rule.cache.php';
break; break;
} }
echo "<div class='center'><br><a href='javascript:window.close()'>".__('Back')."</a>"; echo "<div class='center'><br><a href='javascript:window.close()'>" . __('Back') . '</a>';
echo "</div>"; echo '</div>';
Html::popFooter(); Html::popFooter();
} }

View File

@@ -35,9 +35,9 @@
use GlpiPlugin\Example\RuleTestCollection; use GlpiPlugin\Example\RuleTestCollection;
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkLoginUser(); Session::checkLoginUser();
$rulecollection = new RuleTestCollection(); $rulecollection = new RuleTestCollection();
include (GLPI_ROOT . "/front/rule.common.form.php"); include(GLPI_ROOT . '/front/rule.common.form.php');

View File

@@ -35,9 +35,9 @@
use GlpiPlugin\Example\RuleTestCollection; use GlpiPlugin\Example\RuleTestCollection;
include ('../../../inc/includes.php'); include('../../../inc/includes.php');
Session::checkLoginUser(); Session::checkLoginUser();
$rulecollection = new RuleTestCollection(); $rulecollection = new RuleTestCollection();
include (GLPI_ROOT . "/front/rule.common.php"); include(GLPI_ROOT . '/front/rule.common.php');

866
hook.php

File diff suppressed because it is too large Load Diff

View File

@@ -38,12 +38,12 @@
// Entry menu case // Entry menu case
define('GLPI_ROOT', '../..'); define('GLPI_ROOT', '../..');
include (GLPI_ROOT . "/inc/includes.php"); include(GLPI_ROOT . '/inc/includes.php');
Session::checkRight(Config::$rightname, UPDATE); Session::checkRight(Config::$rightname, UPDATE);
Html::header("TITRE", $_SERVER['PHP_SELF'], "plugins"); Html::header('TITRE', $_SERVER['PHP_SELF'], 'plugins');
echo "This is the plugin report page"; echo 'This is the plugin report page';
Html::footer(); Html::footer();

458
setup.php
View File

@@ -52,249 +52,256 @@ 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; {
global $PLUGIN_HOOKS,$CFG_GLPI;
// 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
//Plugin::registerClass(Example::getType(), //Plugin::registerClass(Example::getType(),
// array('classname' => Example::class, // array('classname' => Example::class,
// )); // ));
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
Plugin::registerClass(Dropdown::class); Plugin::registerClass(Dropdown::class);
$types = ['Central', 'Computer', 'ComputerDisk', 'Notification', 'Phone', $types = ['Central', 'Computer', 'ComputerDisk', 'Notification', 'Phone',
'Preference', 'Profile', 'Supplier']; 'Preference', 'Profile', 'Supplier'];
Plugin::registerClass(Example::class, Plugin::registerClass(
['notificationtemplates_types' => true, Example::class,
'addtabon' => $types, ['notificationtemplates_types' => true,
'link_types' => true]); 'addtabon' => $types,
'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 (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
$PLUGIN_HOOKS['menu_toadd']['example'] = ['plugins' => Example::class, $PLUGIN_HOOKS['menu_toadd']['example'] = ['plugins' => Example::class,
'tools' => Example::class]; 'tools' => Example::class];
// Old menu style // Old menu style
// $PLUGIN_HOOKS['menu_entry']['example'] = 'front/example.php'; // $PLUGIN_HOOKS['menu_entry']['example'] = 'front/example.php';
// //
// $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['title'] = "Search"; // $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['title'] = "Search";
// $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['page'] = '/plugins/example/front/example.php'; // $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['page'] = '/plugins/example/front/example.php';
// $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links']['search'] = '/plugins/example/front/example.php'; // $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links']['search'] = '/plugins/example/front/example.php';
// $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links']['add'] = '/plugins/example/front/example.form.php'; // $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links']['add'] = '/plugins/example/front/example.form.php';
// $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links']['config'] = '/plugins/example/index.php'; // $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links']['config'] = '/plugins/example/index.php';
// $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links']["<img src='".$CFG_GLPI["root_doc"]."/pics/menu_showall.png' title='".__s('Show all')."' alt='".__s('Show all')."'>"] = '/plugins/example/index.php'; // $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links']["<img src='".$CFG_GLPI["root_doc"]."/pics/menu_showall.png' title='".__s('Show all')."' alt='".__s('Show all')."'>"] = '/plugins/example/index.php';
// $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links'][__s('Test link', 'example')] = '/plugins/example/index.php'; // $PLUGIN_HOOKS['submenu_entry']['example']['options']['optionname']['links'][__s('Test link', 'example')] = '/plugins/example/index.php';
$PLUGIN_HOOKS[Hooks::HELPDESK_MENU_ENTRY]['example'] = true; $PLUGIN_HOOKS[Hooks::HELPDESK_MENU_ENTRY]['example'] = true;
$PLUGIN_HOOKS[Hooks::HELPDESK_MENU_ENTRY_ICON]['example'] = 'fas fa-puzzle-piece'; $PLUGIN_HOOKS[Hooks::HELPDESK_MENU_ENTRY_ICON]['example'] = 'fas fa-puzzle-piece';
} }
// Config page // Config page
if (Session::haveRight('config', UPDATE)) { if (Session::haveRight('config', UPDATE)) {
$PLUGIN_HOOKS['config_page']['example'] = 'front/config.php'; $PLUGIN_HOOKS['config_page']['example'] = 'front/config.php';
} }
// Init session // Init session
//$PLUGIN_HOOKS['init_session']['example'] = 'plugin_init_session_example'; //$PLUGIN_HOOKS['init_session']['example'] = 'plugin_init_session_example';
// Change profile // Change profile
$PLUGIN_HOOKS['change_profile']['example'] = 'plugin_change_profile_example'; $PLUGIN_HOOKS['change_profile']['example'] = 'plugin_change_profile_example';
// Change entity // Change entity
//$PLUGIN_HOOKS['change_entity']['example'] = 'plugin_change_entity_example'; //$PLUGIN_HOOKS['change_entity']['example'] = 'plugin_change_entity_example';
// Item action event // See define.php for defined ITEM_TYPE // Item action event // See define.php for defined ITEM_TYPE
$PLUGIN_HOOKS[Hooks::PRE_ITEM_UPDATE]['example'] = [Computer::class => 'plugin_pre_item_update_example']; $PLUGIN_HOOKS[Hooks::PRE_ITEM_UPDATE]['example'] = [Computer::class => 'plugin_pre_item_update_example'];
$PLUGIN_HOOKS[hooks::ITEM_UPDATE]['example'] = [Computer::class => 'plugin_item_update_example']; $PLUGIN_HOOKS[hooks::ITEM_UPDATE]['example'] = [Computer::class => 'plugin_item_update_example'];
$PLUGIN_HOOKS[Hooks::ITEM_EMPTY]['example'] = [Computer::class => 'plugin_item_empty_example']; $PLUGIN_HOOKS[Hooks::ITEM_EMPTY]['example'] = [Computer::class => 'plugin_item_empty_example'];
// Restrict right // Restrict right
$PLUGIN_HOOKS[Hooks::ITEM_CAN]['example'] = [Computer::class => [Example::class, 'item_can']]; $PLUGIN_HOOKS[Hooks::ITEM_CAN]['example'] = [Computer::class => [Example::class, 'item_can']];
$PLUGIN_HOOKS['add_default_where']['example'] = [Computer::class => [Example::class, 'add_default_where']]; $PLUGIN_HOOKS['add_default_where']['example'] = [Computer::class => [Example::class, 'add_default_where']];
// Example using a method in class // Example using a method in class
$PLUGIN_HOOKS[Hooks::PRE_ITEM_ADD]['example'] = [Computer::class => [Example::class, $PLUGIN_HOOKS[Hooks::PRE_ITEM_ADD]['example'] = [Computer::class => [Example::class,
'pre_item_add_computer']]; 'pre_item_add_computer']];
$PLUGIN_HOOKS[Hooks::POST_PREPAREADD]['example'] = [Computer::class => [Example::class, $PLUGIN_HOOKS[Hooks::POST_PREPAREADD]['example'] = [Computer::class => [Example::class,
'post_prepareadd_computer']]; 'post_prepareadd_computer']];
$PLUGIN_HOOKS[Hooks::ITEM_ADD]['example'] = [Computer::class => [Example::class, $PLUGIN_HOOKS[Hooks::ITEM_ADD]['example'] = [Computer::class => [Example::class,
'item_add_computer']]; 'item_add_computer']];
$PLUGIN_HOOKS[Hooks::PRE_ITEM_DELETE]['example'] = [Computer::class => 'plugin_pre_item_delete_example']; $PLUGIN_HOOKS[Hooks::PRE_ITEM_DELETE]['example'] = [Computer::class => 'plugin_pre_item_delete_example'];
$PLUGIN_HOOKS[Hooks::ITEM_DELETE]['example'] = [Computer::class => 'plugin_item_delete_example']; $PLUGIN_HOOKS[Hooks::ITEM_DELETE]['example'] = [Computer::class => 'plugin_item_delete_example'];
// Example using the same function // Example using the same function
$PLUGIN_HOOKS[Hooks::PRE_ITEM_PURGE]['example'] = [Computer::class => 'plugin_pre_item_purge_example', $PLUGIN_HOOKS[Hooks::PRE_ITEM_PURGE]['example'] = [Computer::class => 'plugin_pre_item_purge_example',
'Phone' => 'plugin_pre_item_purge_example']; 'Phone' => 'plugin_pre_item_purge_example'];
$PLUGIN_HOOKS[Hooks::ITEM_PURGE]['example'] = [Computer::class => 'plugin_item_purge_example', $PLUGIN_HOOKS[Hooks::ITEM_PURGE]['example'] = [Computer::class => 'plugin_item_purge_example',
'Phone' => 'plugin_item_purge_example']; 'Phone' => 'plugin_item_purge_example'];
// Example with 2 different functions // Example with 2 different functions
$PLUGIN_HOOKS[Hooks::PRE_ITEM_RESTORE]['example'] = [Computer::class => 'plugin_pre_item_restore_example', $PLUGIN_HOOKS[Hooks::PRE_ITEM_RESTORE]['example'] = [Computer::class => 'plugin_pre_item_restore_example',
'Phone' => 'plugin_pre_item_restore_example2']; 'Phone' => 'plugin_pre_item_restore_example2'];
$PLUGIN_HOOKS[Hooks::ITEM_RESTORE]['example'] = [Computer::class => 'plugin_item_restore_example']; $PLUGIN_HOOKS[Hooks::ITEM_RESTORE]['example'] = [Computer::class => 'plugin_item_restore_example'];
// Add event to GLPI core itemtype, event will be raised by the plugin. // Add event to GLPI core itemtype, event will be raised by the plugin.
// See plugin_example_uninstall for cleanup of notification // See plugin_example_uninstall for cleanup of notification
$PLUGIN_HOOKS[Hooks::ITEM_GET_EVENTS]['example'] $PLUGIN_HOOKS[Hooks::ITEM_GET_EVENTS]['example']
= ['NotificationTargetTicket' => 'plugin_example_get_events']; = ['NotificationTargetTicket' => 'plugin_example_get_events'];
// Add datas to GLPI core itemtype for notifications template. // Add datas to GLPI core itemtype for notifications template.
$PLUGIN_HOOKS[Hooks::ITEM_GET_DATA]['example'] $PLUGIN_HOOKS[Hooks::ITEM_GET_DATA]['example']
= ['NotificationTargetTicket' => 'plugin_example_get_datas']; = ['NotificationTargetTicket' => 'plugin_example_get_datas'];
$PLUGIN_HOOKS[Hooks::ITEM_TRANSFER]['example'] = 'plugin_item_transfer_example'; $PLUGIN_HOOKS[Hooks::ITEM_TRANSFER]['example'] = 'plugin_item_transfer_example';
// function to populate planning // function to populate planning
// No more used since GLPI 0.84 // No more used since GLPI 0.84
// $PLUGIN_HOOKS['planning_populate']['example'] = 'plugin_planning_populate_example'; // $PLUGIN_HOOKS['planning_populate']['example'] = 'plugin_planning_populate_example';
// Use instead : add class to planning types and define populatePlanning in class // Use instead : add class to planning types and define populatePlanning in class
$CFG_GLPI['planning_types'][] = Example::class; $CFG_GLPI['planning_types'][] = Example::class;
//function to display planning items //function to display planning items
// No more used sinc GLPi 0.84 // No more used sinc GLPi 0.84
// $PLUGIN_HOOKS['display_planning']['example'] = 'plugin_display_planning_example'; // $PLUGIN_HOOKS['display_planning']['example'] = 'plugin_display_planning_example';
// Use instead : displayPlanningItem of the specific itemtype // Use instead : displayPlanningItem of the specific itemtype
// Massive Action definition // Massive Action definition
$PLUGIN_HOOKS['use_massive_action']['example'] = 1; $PLUGIN_HOOKS['use_massive_action']['example'] = 1;
$PLUGIN_HOOKS['assign_to_ticket']['example'] = 1; $PLUGIN_HOOKS['assign_to_ticket']['example'] = 1;
// Add specific files to add to the header : javascript or css // Add specific files to add to the header : javascript or css
$PLUGIN_HOOKS[Hooks::ADD_JAVASCRIPT]['example'] = 'example.js'; $PLUGIN_HOOKS[Hooks::ADD_JAVASCRIPT]['example'] = 'example.js';
$PLUGIN_HOOKS[Hooks::ADD_CSS]['example'] = 'example.css'; $PLUGIN_HOOKS[Hooks::ADD_CSS]['example'] = 'example.css';
// Add specific tags to the header // Add specific tags to the header
$PLUGIN_HOOKS[Hooks::ADD_HEADER_TAG]['example'] = [ $PLUGIN_HOOKS[Hooks::ADD_HEADER_TAG]['example'] = [
[ [
'tag' => 'meta', 'tag' => 'meta',
'properties' => [ 'properties' => [
'name' => 'robots', 'name' => 'robots',
'content' => 'noindex, nofollow', 'content' => 'noindex, nofollow',
] ],
], ],
[ [
'tag' => 'link', 'tag' => 'link',
'properties' => [ 'properties' => [
'rel' => 'alternate', 'rel' => 'alternate',
'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',
] ],
], ],
]; ];
// Add specific files to add to the header into anonymous page : javascript or css // Add specific files to add to the header into anonymous page : javascript or css
$PLUGIN_HOOKS[Hooks::ADD_CSS_ANONYMOUS_PAGE]['example'] = 'example_anonymous.css'; $PLUGIN_HOOKS[Hooks::ADD_CSS_ANONYMOUS_PAGE]['example'] = 'example_anonymous.css';
$PLUGIN_HOOKS[Hooks::ADD_JAVASCRIPT_MODULE_ANONYMOUS_PAGE]['example'] = 'mymodule_anonymous.js'; $PLUGIN_HOOKS[Hooks::ADD_JAVASCRIPT_MODULE_ANONYMOUS_PAGE]['example'] = 'mymodule_anonymous.js';
$PLUGIN_HOOKS[Hooks::ADD_JAVASCRIPT_ANONYMOUS_PAGE]['example'] = 'example_anonymous.js'; $PLUGIN_HOOKS[Hooks::ADD_JAVASCRIPT_ANONYMOUS_PAGE]['example'] = 'example_anonymous.js';
// Add specific tags to the header into anonymous page // Add specific tags to the header into anonymous page
$PLUGIN_HOOKS[Hooks::ADD_HEADER_TAG_ANONYMOUS_PAGE]['example'] = [ $PLUGIN_HOOKS[Hooks::ADD_HEADER_TAG_ANONYMOUS_PAGE]['example'] = [
[ [
'tag' => 'meta', 'tag' => 'meta',
'properties' => [ 'properties' => [
'name' => 'robots', 'name' => 'robots',
'content' => 'noindex, nofollow', 'content' => 'noindex, nofollow',
] ],
], ],
[ [
'tag' => 'link', 'tag' => 'link',
'properties' => [ 'properties' => [
'rel' => 'alternate', 'rel' => 'alternate',
'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',
] ],
], ],
]; ];
// request more attributes from ldap // request more attributes from ldap
//$PLUGIN_HOOKS['retrieve_more_field_from_ldap']['example']="plugin_retrieve_more_field_from_ldap_example"; //$PLUGIN_HOOKS['retrieve_more_field_from_ldap']['example']="plugin_retrieve_more_field_from_ldap_example";
// Retrieve others datas from LDAP // Retrieve others datas from LDAP
//$PLUGIN_HOOKS['retrieve_more_data_from_ldap']['example']="plugin_retrieve_more_data_from_ldap_example"; //$PLUGIN_HOOKS['retrieve_more_data_from_ldap']['example']="plugin_retrieve_more_data_from_ldap_example";
// Reports // Reports
$PLUGIN_HOOKS['reports']['example'] = ['report.php' => 'New Report', $PLUGIN_HOOKS['reports']['example'] = ['report.php' => 'New Report',
'report.php?other' => 'New Report 2']; 'report.php?other' => 'New Report 2'];
// Stats // Stats
$PLUGIN_HOOKS['stats']['example'] = ['stat.php' => 'New stat', $PLUGIN_HOOKS['stats']['example'] = ['stat.php' => 'New stat',
'stat.php?other' => 'New stats 2',]; 'stat.php?other' => 'New stats 2', ];
$PLUGIN_HOOKS[Hooks::POST_INIT]['example'] = 'plugin_example_postinit'; $PLUGIN_HOOKS[Hooks::POST_INIT]['example'] = 'plugin_example_postinit';
$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(); // 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::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';
// pre_show and post_show for tabs and items, // pre_show and post_show for tabs and items,
// see GlpiPlugin\Example\Showtabitem class for implementation explanations // see GlpiPlugin\Example\Showtabitem class for implementation explanations
$PLUGIN_HOOKS[Hooks::PRE_SHOW_TAB]['example'] = [Showtabitem::class, 'pre_show_tab']; $PLUGIN_HOOKS[Hooks::PRE_SHOW_TAB]['example'] = [Showtabitem::class, 'pre_show_tab'];
$PLUGIN_HOOKS[Hooks::POST_SHOW_TAB]['example'] = [Showtabitem::class, 'post_show_tab']; $PLUGIN_HOOKS[Hooks::POST_SHOW_TAB]['example'] = [Showtabitem::class, 'post_show_tab'];
$PLUGIN_HOOKS[Hooks::PRE_SHOW_ITEM]['example'] = [Showtabitem::class, 'pre_show_item']; $PLUGIN_HOOKS[Hooks::PRE_SHOW_ITEM]['example'] = [Showtabitem::class, 'pre_show_item'];
$PLUGIN_HOOKS[Hooks::POST_SHOW_ITEM]['example'] = [Showtabitem::class, 'post_show_item']; $PLUGIN_HOOKS[Hooks::POST_SHOW_ITEM]['example'] = [Showtabitem::class, 'post_show_item'];
$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 //TODO: remove check when GLPI 11.0.0 is released
if (version_compare(GLPI_VERSION, '11.0.0', 'ge')) { 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
$PLUGIN_HOOKS['import_item']['example'] = [Computer::class => ['Plugin']]; $PLUGIN_HOOKS['import_item']['example'] = [Computer::class => ['Plugin']];
// 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';
// add new cards to dashboard grid // add new cards to dashboard grid
$PLUGIN_HOOKS['dashboard_types']['example'] = [Example::class, 'dashboardTypes']; $PLUGIN_HOOKS['dashboard_types']['example'] = [Example::class, 'dashboardTypes'];
$PLUGIN_HOOKS['dashboard_cards']['example'] = [Example::class, 'dashboardCards']; $PLUGIN_HOOKS['dashboard_cards']['example'] = [Example::class, 'dashboardCards'];
// 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 //TODO: remove check when GLPI 11.0.0 is released
if (version_compare(GLPI_VERSION, '11.0.0', 'ge')) { if (version_compare(GLPI_VERSION, '11.0.0', 'ge')) {
// Icon in the impact analysis // 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,20 +311,21 @@ function plugin_init_example() {
* *
* @return array * @return array
*/ */
function plugin_version_example() { function plugin_version_example()
return [ {
'name' => 'Plugin Example', return [
'version' => PLUGIN_EXAMPLE_VERSION, 'name' => 'Plugin Example',
'author' => 'Example plugin team', 'version' => PLUGIN_EXAMPLE_VERSION,
'license' => 'GPLv2+', 'author' => 'Example plugin team',
'homepage' => 'https://github.com/pluginsGLPI/example', 'license' => 'GPLv2+',
'requirements' => [ 'homepage' => 'https://github.com/pluginsGLPI/example',
'glpi' => [ 'requirements' => [
'min' => PLUGIN_EXAMPLE_MIN_GLPI, 'glpi' => [
'max' => PLUGIN_EXAMPLE_MAX_GLPI, 'min' => PLUGIN_EXAMPLE_MIN_GLPI,
] 'max' => PLUGIN_EXAMPLE_MAX_GLPI,
] ],
]; ],
];
} }
@@ -327,11 +335,13 @@ function plugin_version_example() {
* *
* @return boolean * @return boolean
*/ */
function plugin_example_check_prerequisites() { function plugin_example_check_prerequisites()
if (false) { {
return false; if (false) {
} return false;
return true; }
return true;
} }
/** /**
@@ -341,13 +351,15 @@ 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 {
return true; if (true) { // Your configuration check
} return true;
}
if ($verbose) { if ($verbose) {
echo __('Installed / not configured', 'example'); echo __('Installed / not configured', 'example');
} }
return false;
return false;
} }

View File

@@ -34,6 +34,7 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDBChild; use CommonDBChild;
use Session; use Session;
@@ -43,64 +44,58 @@ 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.
public static $itemtype = 'itemtype';
public static $items_id = 'items_id';
// A child rely on an item. If $itemtype=='itemtype', then that is a variable item. // With 0.84, you have to specify each right (create, view, update and delete), because
static public $itemtype = 'itemtype'; // CommonDBChild(s) and CommonDBRelation(s) mainly depend on the rights on the parent item
static public $items_id = 'items_id'; // All these methods rely on parent:can*. Two attributs are usefull :
// * $checkParentRights: define what to check regarding the parent :
// - CommonDBConnexity::DONT_CHECK_ITEM_RIGHTS don't eaven relly on parents rights
// - CommonDBConnexity::HAVE_VIEW_RIGHT_ON_ITEM view right on the item is enough
// - CommonDBConnexity::HAVE_SAME_RIGHT_ON_ITEM we must have at least update right
// on the item
// * $mustBeAttached: some CommonDBChild can be free, without any parent.
public static function canCreate()
{
return (Session::haveRight('internet', UPDATE)
&& parent::canCreate());
}
public static function canView()
{
return (Session::haveRight('internet', READ)
&& parent::canView());
}
// With 0.84, you have to specify each right (create, view, update and delete), because public static function canUpdate()
// CommonDBChild(s) and CommonDBRelation(s) mainly depend on the rights on the parent item {
// All these methods rely on parent:can*. Two attributs are usefull : return (Session::haveRight('internet', UPDATE)
// * $checkParentRights: define what to check regarding the parent : && parent::canUpdate());
// - CommonDBConnexity::DONT_CHECK_ITEM_RIGHTS don't eaven relly on parents rights }
// - CommonDBConnexity::HAVE_VIEW_RIGHT_ON_ITEM view right on the item is enough
// - CommonDBConnexity::HAVE_SAME_RIGHT_ON_ITEM we must have at least update right
// on the item
// * $mustBeAttached: some CommonDBChild can be free, without any parent.
static function canCreate() {
return (Session::haveRight('internet', UPDATE) public static function canDelete()
&& parent::canCreate()); {
} return (Session::haveRight('internet', DELETE)
&& parent::canDelete());
}
// By default, post_addItem, post_updateItem and post_deleteFromDB are defined.
// They define the history to add to the parents
// 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
// define the level of log (Log::HISTORY_ADD_DEVICE, Log::HISTORY_UPDATE_DEVICE ...)
public function getHistoryName_for_item($case) {}
static function canView() { // CommonDBChild also check if we can add or updatethe item regarding the new item
// ($input[static::$itemtype] and $input[static::$items_id]).
return (Session::haveRight('internet', READ) // But don't forget to call parent::prepareInputForAdd()
&& parent::canView()); public function prepareInputForAdd($input)
} {
// My preparation on $input
return parent::prepareInputForAdd($input);
static function canUpdate() { }
return (Session::haveRight('internet', UPDATE)
&& parent::canUpdate());
}
static function canDelete() {
return (Session::haveRight('internet', DELETE)
&& parent::canDelete());
}
// By default, post_addItem, post_updateItem and post_deleteFromDB are defined.
// They define the history to add to the parents
// 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
// define the level of log (Log::HISTORY_ADD_DEVICE, Log::HISTORY_UPDATE_DEVICE ...)
function getHistoryName_for_item($case) {
}
// CommonDBChild also check if we can add or updatethe item regarding the new item
// ($input[static::$itemtype] and $input[static::$items_id]).
// But don't forget to call parent::prepareInputForAdd()
function prepareInputForAdd($input) {
// My preparation on $input
return parent::prepareInputForAdd($input);
}
} }

View File

@@ -34,50 +34,49 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDBTM; use CommonDBTM;
// Class of the defined type // Class of the defined type
if (!defined('GLPI_ROOT')) { if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file"); die("Sorry. You can't access directly to this file");
} }
class Computer extends CommonDBTM { class Computer extends CommonDBTM
{
public static function showInfo()
{
echo '<table class="tab_glpi" width="100%">';
echo '<tr>';
echo '<th>' . __('More information') . '</th>';
echo '</tr>';
echo '<tr class="tab_bg_1">';
echo '<td>';
echo __('Test successful');
echo '</td>';
echo '</tr>';
echo '</table>';
}
static function showInfo() { public static function item_can($item)
{
if (($item->getType() == 'Computer')
&& ($item->right == READ)
&& ($item->fields['groups_id'] > 0)
&& !in_array($item->fields['groups_id'], $_SESSION['glpigroups'])) {
$item->right = 0; // unknown, so denied.
}
}
echo '<table class="tab_glpi" width="100%">'; public static function add_default_where($in)
echo '<tr>'; {
echo '<th>'.__('More information').'</th>'; list($itemtype, $condition) = $in;
echo '</tr>'; if ($itemtype == 'Computer') {
echo '<tr class="tab_bg_1">'; $table = getTableForItemType($itemtype);
echo '<td>'; $condition .= ' (' . $table . '.groups_id NOT IN (' . implode(',', $_SESSION['glpigroups']) . '))';
echo __('Test successful'); }
echo '</td>';
echo '</tr>';
echo '</table>';
}
static function item_can($item) {
if (($item->getType() == 'Computer')
&& ($item->right == READ)
&& ($item->fields['groups_id'] > 0)
&& !in_array($item->fields['groups_id'], $_SESSION["glpigroups"])) {
$item->right = 0; // unknown, so denied.
}
}
static function add_default_where($in) {
list($itemtype, $condition) = $in;
if ($itemtype == 'Computer') {
$table = getTableForItemType($itemtype);
$condition .= " (".$table.".groups_id NOT IN (".implode(',', $_SESSION["glpigroups"])."))";
}
return [$itemtype, $condition];
}
return [$itemtype, $condition];
}
} }

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,60 +38,63 @@ 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)
{
if (!$withtemplate) {
if ($item->getType() == 'Config') {
return __('Example plugin');
}
}
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) { return '';
}
if (!$withtemplate) { public static function configUpdate($input)
if ($item->getType() == 'Config') { {
return __('Example plugin'); $input['configuration'] = 1 - $input['configuration'];
}
}
return '';
}
static function configUpdate($input) { return $input;
$input['configuration'] = 1 - $input['configuration']; }
return $input;
}
function showFormExample() { public function showFormExample()
global $CFG_GLPI; {
global $CFG_GLPI;
if (!Session::haveRight("config", UPDATE)) { if (!Session::haveRight('config', UPDATE)) {
return false; return false;
} }
$my_config = GlpiConfig::getConfigurationValues('plugin:Example'); $my_config = GlpiConfig::getConfigurationValues('plugin:Example');
echo "<form name='form' action=\"".Toolbox::getItemTypeFormURL('Config')."\" method='post'>"; echo "<form name='form' action=\"" . Toolbox::getItemTypeFormURL('Config') . "\" method='post'>";
echo "<div class='center' id='tabsbody'>"; echo "<div class='center' id='tabsbody'>";
echo "<table class='tab_cadre_fixe'>"; echo "<table class='tab_cadre_fixe'>";
echo "<tr><th colspan='4'>" . __('Example setup') . "</th></tr>"; echo "<tr><th colspan='4'>" . __('Example setup') . '</th></tr>';
echo "<td >" . __('My boolean choice :') . "</td>"; echo '<td >' . __('My boolean choice :') . '</td>';
echo "<td colspan='3'>"; echo "<td colspan='3'>";
echo "<input type='hidden' name='config_class' value='".__CLASS__."'>"; echo "<input type='hidden' name='config_class' value='" . __CLASS__ . "'>";
echo "<input type='hidden' name='config_context' value='plugin:Example'>"; echo "<input type='hidden' name='config_context' value='plugin:Example'>";
Dropdown::showYesNo("configuration", $my_config['configuration']); Dropdown::showYesNo('configuration', $my_config['configuration']);
echo "</td></tr>"; echo '</td></tr>';
echo "<tr class='tab_bg_2'>"; echo "<tr class='tab_bg_2'>";
echo "<td colspan='4' class='center'>"; echo "<td colspan='4' class='center'>";
echo "<input type='submit' name='update' class='submit' value=\""._sx('button', 'Save')."\">"; echo "<input type='submit' name='update' class='submit' value=\"" . _sx('button', 'Save') . '">';
echo "</td></tr>"; echo '</td></tr>';
echo "</table></div>"; echo '</table></div>';
Html::closeForm(); Html::closeForm();
} }
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
if ($item->getType() == 'Config') {
$config = new self();
$config->showFormExample();
}
}
public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0)
{
if ($item->getType() == 'Config') {
$config = new self();
$config->showFormExample();
}
}
} }

View File

@@ -34,19 +34,20 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use CommonDevice; use CommonDevice;
// Class of the defined type // Class of the defined type
if (!defined('GLPI_ROOT')) { if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file"); 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

@@ -55,14 +55,15 @@ 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;
if (!defined('GLPI_ROOT')) { if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly"); die("Sorry. You can't access this file directly");
} }
class Document extends GlpiDocument { 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,155 +71,159 @@ class Document extends GlpiDocument {
* *
* @return string * @return string
**/ **/
public static function getTable($classname = null) { public static function getTable($classname = null)
if ($classname === null) { {
$classname = get_called_class(); if ($classname === null) {
} $classname = get_called_class();
if ($classname == get_called_class()) { }
return parent::getTable(Document::class); if ($classname == get_called_class()) {
} return parent::getTable(Document::class);
}
return parent::getTable($classname); return parent::getTable($classname);
} }
/** /**
* Prepare creation of an item * Prepare creation of an item
* *
* @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; {
if (!isset($_FILES['file'])) { $input['_only_if_upload_succeed'] = true;
return false; if (!isset($_FILES['file'])) {
} return false;
}
// Move the uploaded file to GLPi's tmp dir // Move the uploaded file to GLPi's tmp dir
while (count($_FILES['file']['name']) > 0) { while (count($_FILES['file']['name']) > 0) {
$source = array_pop($_FILES['file']['name']); $source = array_pop($_FILES['file']['name']);
$destination = GLPI_TMP_DIR . '/' . $source; $destination = GLPI_TMP_DIR . '/' . $source;
move_uploaded_file($source, $destination); move_uploaded_file($source, $destination);
$input['_filename'][] = $source; $input['_filename'][] = $source;
} }
return parent::prepareInputForAdd($input); return parent::prepareInputForAdd($input);
} }
/** /**
* Prepare update of an item * Prepare update of an item
* *
* @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 {
return false; // Do not allow update of document
} return false;
}
/** /**
* Process required after loading an object from DB * Process required after loading an object from DB
* In this example, a file is sent as a byte strem then stops execution. * In this example, a file is sent as a byte strem then stops execution.
* *
* @return void * @return void
*/ */
public function post_getFromDB() { public function post_getFromDB()
// Check the user can view this itemtype and can view this item {
if ($this->canView() && $this->canViewItem()) { // Check the user can view this itemtype and can view this item
if (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == 'application/octet-stream' if ($this->canView() && $this->canViewItem()) {
|| isset($_GET['alt']) && $_GET['alt'] == 'media') { if (isset($_SERVER['HTTP_ACCEPT']) && $_SERVER['HTTP_ACCEPT'] == 'application/octet-stream'
$this->sendFile(); // and terminate script || isset($_GET['alt']) && $_GET['alt'] == 'media') {
} $this->sendFile(); // and terminate script
}
}
/**
* Send a byte stream to the HTTP client and stops execution
*
* @return void
*/
protected function sendFile() {
$streamSource = GLPI_DOC_DIR . '/' . $this->fields['filepath'];
// Ensure the file exists
if (!file_exists($streamSource) || !is_file($streamSource)) {
header("HTTP/1.0 404 Not Found");
exit(0);
}
// Download range defaults to the full file
// get file metadata
$size = filesize($streamSource);
$begin = 0;
$end = $size - 1;
$mimeType = 'application/octet-stream';
$time = date('r', filemtime($streamSource));
// Open the file
$fileHandle = @fopen($streamSource, 'rb');
if (!$fileHandle) {
header ("HTTP/1.0 500 Internal Server Error");
exit(0);
}
// set range if specified by the client
if (isset($_SERVER['HTTP_RANGE'])) {
if (preg_match('/bytes=\h*(\d+)?-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
if (!empty($matches[1])) {
$begin = intval($matches[1]);
} }
if (!empty($matches[2])) { }
$end = min(intval($matches[2]), $end); }
}
}
}
// seek to the begining of the range /**
$currentPosition = $begin; * Send a byte stream to the HTTP client and stops execution
if (fseek($fileHandle, $begin, SEEK_SET) < 0) { *
header("HTTP/1.0 500 Internal Server Error"); * @return void
exit(0); */
} protected function sendFile()
{
$streamSource = GLPI_DOC_DIR . '/' . $this->fields['filepath'];
// send headers to ensure the client is able to detect a corrupted download // Ensure the file exists
// example : less bytes than the expected range if (!file_exists($streamSource) || !is_file($streamSource)) {
// send meta data header('HTTP/1.0 404 Not Found');
// setup client's cache behavior
header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
header('Pragma: private'); /// IE BUG + SSL
header('Cache-control: private, must-revalidate'); /// IE BUG + SSL
header("Content-disposition: attachment; filename=\"" . $this->fields['filename'] . "\"");
header("Content-type: $mimeType");
header("Last-Modified: $time");
header('Accept-Ranges: bytes');
header('Content-Length:' . ($end - $begin + 1));
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');
// Prepare HTTP response
if ($begin > 0 || $end < $size - 1) {
header('HTTP/1.0 206 Partial Content');
} else {
header('HTTP/1.0 200 OK');
}
// Sends bytes until the end of the range or connection closed
while (!feof($fileHandle) && $currentPosition < $end && (connection_status() == 0)) {
// allow a few seconds to send a few KB.
set_time_limit(10);
$content = fread($fileHandle, min(1024 * 16, $end - $currentPosition + 1));
if ($content === false) {
header("HTTP/1.0 500 Internal Server Error", true); // Replace previously sent headers
exit(0); exit(0);
} else { }
print $content;
}
flush();
$currentPosition += 1024 * 16;
}
// End now to prevent any unwanted bytes // Download range defaults to the full file
exit(0); // get file metadata
} $size = filesize($streamSource);
$begin = 0;
$end = $size - 1;
$mimeType = 'application/octet-stream';
$time = date('r', filemtime($streamSource));
// Open the file
$fileHandle = @fopen($streamSource, 'rb');
if (!$fileHandle) {
header('HTTP/1.0 500 Internal Server Error');
exit(0);
}
// set range if specified by the client
if (isset($_SERVER['HTTP_RANGE'])) {
if (preg_match('/bytes=\h*(\d+)?-(\d*)[\D.*]?/i', $_SERVER['HTTP_RANGE'], $matches)) {
if (!empty($matches[1])) {
$begin = intval($matches[1]);
}
if (!empty($matches[2])) {
$end = min(intval($matches[2]), $end);
}
}
}
// seek to the begining of the range
$currentPosition = $begin;
if (fseek($fileHandle, $begin, SEEK_SET) < 0) {
header('HTTP/1.0 500 Internal Server Error');
exit(0);
}
// send headers to ensure the client is able to detect a corrupted download
// example : less bytes than the expected range
// send meta data
// setup client's cache behavior
header('Expires: Mon, 26 Nov 1962 00:00:00 GMT');
header('Pragma: private'); /// IE BUG + SSL
header('Cache-control: private, must-revalidate'); /// IE BUG + SSL
header('Content-disposition: attachment; filename="' . $this->fields['filename'] . '"');
header("Content-type: $mimeType");
header("Last-Modified: $time");
header('Accept-Ranges: bytes');
header('Content-Length:' . ($end - $begin + 1));
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');
// Prepare HTTP response
if ($begin > 0 || $end < $size - 1) {
header('HTTP/1.0 206 Partial Content');
} else {
header('HTTP/1.0 200 OK');
}
// Sends bytes until the end of the range or connection closed
while (!feof($fileHandle) && $currentPosition < $end && (connection_status() == 0)) {
// allow a few seconds to send a few KB.
set_time_limit(10);
$content = fread($fileHandle, min(1024 * 16, $end - $currentPosition + 1));
if ($content === false) {
header('HTTP/1.0 500 Internal Server Error', true); // Replace previously sent headers
exit(0);
} else {
print $content;
}
flush();
$currentPosition += 1024 * 16;
}
// End now to prevent any unwanted bytes
exit(0);
}
} }

View File

@@ -32,18 +32,20 @@
// 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)
{
if ($nb > 0) {
return __('Plugin Example Dropdowns', 'example');
}
return __('Plugin Example Dropdowns', 'example');
static function getTypeName($nb = 0) { }
if ($nb > 0) {
return __('Plugin Example Dropdowns', 'example');
}
return __('Plugin Example Dropdowns', 'example');
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -38,12 +38,12 @@ class ComputerModelFilter extends AbstractFilter
{ {
public static function getName(): string public static function getName(): string
{ {
return __("Computer model"); return __('Computer model');
} }
public static function getId(): string public static function getId(): string
{ {
return "plugin_example_computer_model"; return 'plugin_example_computer_model';
} }
public static function canBeApplied(string $table): bool public static function canBeApplied(string $table): bool
@@ -57,9 +57,9 @@ class ComputerModelFilter extends AbstractFilter
{ {
return self::displayList( return self::displayList(
self::getName(), self::getName(),
is_string($value) ? $value : "", is_string($value) ? $value : '',
self::getId(), self::getId(),
ComputerModel::class ComputerModel::class,
); );
} }
@@ -67,10 +67,11 @@ class ComputerModelFilter extends AbstractFilter
{ {
if ((int) $value > 0) { if ((int) $value > 0) {
$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,21 +39,21 @@ 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).
*
* @param array $params Array with "item" and "options" keys
*
* @return void
*/
public static function preSection($params)
{
$item = $params['item'];
$options = $params['options'];
echo TemplateRenderer::getInstance()->renderFromStringTemplate(<<<TWIG
/**
* Display contents at the begining of ITILObject section (right panel).
*
* @param array $params Array with "item" and "options" keys
*
* @return void
*/
static public function preSection($params) {
$item = $params['item'];
$options = $params['options'];
echo TemplateRenderer::getInstance()->renderFromStringTemplate(<<<TWIG
<section class="accordion-item" aria-label="a label"> <section class="accordion-item" aria-label="a label">
<h2 class="accordion-header" id="example-heading" title="example-heading-id" data-bs-toggle="tooltip"> <h2 class="accordion-header" id="example-heading" title="example-heading-id" data-bs-toggle="tooltip">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#example-pre-content" aria-expanded="true" aria-controls="example-pre-content"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#example-pre-content" aria-expanded="true" aria-controls="example-pre-content">
@@ -70,21 +70,21 @@ class ItemForm {
</div> </div>
</section> </section>
TWIG, []); TWIG, []);
}
} /**
* Display contents at the end of ITILObject section (right panel).
*
* @param array $params Array with "item" and "options" keys
*
* @return void
*/
public static function postSection($params)
{
$item = $params['item'];
$options = $params['options'];
/** echo TemplateRenderer::getInstance()->renderFromStringTemplate(<<<TWIG
* Display contents at the end of ITILObject section (right panel).
*
* @param array $params Array with "item" and "options" keys
*
* @return void
*/
static public function postSection($params) {
$item = $params['item'];
$options = $params['options'];
echo TemplateRenderer::getInstance()->renderFromStringTemplate(<<<TWIG
<section class="accordion-item" aria-label="a label"> <section class="accordion-item" aria-label="a label">
<h2 class="accordion-header" id="example-heading" title="example-heading-id" data-bs-toggle="tooltip"> <h2 class="accordion-header" id="example-heading" title="example-heading-id" data-bs-toggle="tooltip">
<button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#example-post-content" aria-expanded="true" aria-controls="example-post-content"> <button class="accordion-button" type="button" data-bs-toggle="collapse" data-bs-target="#example-post-content" aria-expanded="true" aria-controls="example-post-content">
@@ -101,106 +101,105 @@ TWIG, []);
</div> </div>
</section> </section>
TWIG, []); TWIG, []);
} }
/**
* Display contents at the begining of item forms.
*
* @param array $params Array with "item" and "options" keys
*
* @return void
*/
public static function preItemForm($params)
{
$item = $params['item'];
$options = $params['options'];
$firstelt = ($item::getType() == Ticket::class ? 'th' : 'td');
$out = '<tr><th colspan="' . (isset($options['colspan']) ? $options['colspan'] * 2 : '4') . '">';
$out .= sprintf(
__('Start %1$s hook call for %2$s type'),
'pre_item_form',
$item::getType(),
);
$out .= '</th></tr>';
$out .= "<tr><$firstelt>";
$out .= '<label for="example_pre_form_hook">' . __('First pre form hook') . '</label>';
$out .= "</$firstelt><td>";
$out .= '<input type="text" name="example_pre_form_hook" id="example_pre_form_hook"/>';
$out .= "</td><$firstelt>";
$out .= '<label for="example_pre_form_hook2">' . __('Second pre form hook') . '</label>';
$out .= "</$firstelt><td>";
$out .= '<input type="text" name="example_pre_form_hook2" id="example_pre_form_hook2"/>';
$out .= '</td></tr>';
/** $out .= '<tr><th colspan="' . (isset($options['colspan']) ? $options['colspan'] * 2 : '4') . '">';
* Display contents at the begining of item forms. $out .= sprintf(
* __('End %1$s hook call for %2$s type'),
* @param array $params Array with "item" and "options" keys 'pre_item_form',
* $item::getType(),
* @return void );
*/ $out .= '</th></tr>';
static public function preItemForm($params) {
$item = $params['item'];
$options = $params['options'];
$firstelt = ($item::getType() == Ticket::class ? 'th' : 'td'); echo $out;
}
$out = '<tr><th colspan="' . (isset($options['colspan']) ? $options['colspan'] * 2 : '4') . '">'; /**
$out .= sprintf( * Display contents at the begining of item forms.
__('Start %1$s hook call for %2$s type'), *
'pre_item_form', * @param array $params Array with "item" and "options" keys
$item::getType() *
); * @return void
$out .= '</th></tr>'; */
public static function postItemForm($params)
{
$item = $params['item'];
$options = $params['options'];
$out .= "<tr><$firstelt>"; $firstelt = ($item::getType() == Ticket::class ? 'th' : 'td');
$out .= '<label for="example_pre_form_hook">' . __('First pre form hook') . '</label>';
$out .= "</$firstelt><td>";
$out .= '<input type="text" name="example_pre_form_hook" id="example_pre_form_hook"/>';
$out .= "</td><$firstelt>";
$out .= '<label for="example_pre_form_hook2">' . __('Second pre form hook') . '</label>';
$out .= "</$firstelt><td>";
$out .= '<input type="text" name="example_pre_form_hook2" id="example_pre_form_hook2"/>';
$out .= '</td></tr>';
$out .= '<tr><th colspan="' . (isset($options['colspan']) ? $options['colspan'] * 2 : '4') . '">'; $out = '<tr><th colspan="' . (isset($options['colspan']) ? $options['colspan'] * 2 : '4') . '">';
$out .= sprintf( $out .= sprintf(
__('End %1$s hook call for %2$s type'), __('Start %1$s hook call for %2$s type'),
'pre_item_form', 'post_item_form',
$item::getType() $item::getType(),
); );
$out .= '</th></tr>'; $out .= '</th></tr>';
echo $out; $out .= "<tr><$firstelt>";
} $out .= '<label for="example_post_form_hook">' . __('First post form hook') . '</label>';
$out .= "</$firstelt><td>";
$out .= '<input type="text" name="example_post_form_hook" id="example_post_form_hook"/>';
$out .= "</td><$firstelt>";
$out .= '<label for="example_post_form_hook2">' . __('Second post form hook') . '</label>';
$out .= "</$firstelt><td>";
$out .= '<input type="text" name="example_post_form_hook2" id="example_post_form_hook2"/>';
$out .= '</td></tr>';
/** $out .= '<tr><th colspan="' . (isset($options['colspan']) ? $options['colspan'] * 2 : '4') . '">';
* Display contents at the begining of item forms. $out .= sprintf(
* __('End %1$s hook call for %2$s type'),
* @param array $params Array with "item" and "options" keys 'post_item_form',
* $item::getType(),
* @return void );
*/ $out .= '</th></tr>';
static public function postItemForm($params) {
$item = $params['item'];
$options = $params['options'];
$firstelt = ($item::getType() == Ticket::class ? 'th' : 'td'); echo $out;
}
$out = '<tr><th colspan="' . (isset($options['colspan']) ? $options['colspan'] * 2 : '4') . '">'; public static function timelineActions($params = [])
$out .= sprintf( {
__('Start %1$s hook call for %2$s type'), $rand = $params['rand'];
'post_item_form', $ticket = $params['item'];
$item::getType()
);
$out .= '</th></tr>';
$out .= "<tr><$firstelt>"; if (get_class($ticket) !== 'Ticket') {
$out .= '<label for="example_post_form_hook">' . __('First post form hook') . '</label>'; return false;
$out .= "</$firstelt><td>"; }
$out .= '<input type="text" name="example_post_form_hook" id="example_post_form_hook"/>';
$out .= "</td><$firstelt>";
$out .= '<label for="example_post_form_hook2">' . __('Second post form hook') . '</label>';
$out .= "</$firstelt><td>";
$out .= '<input type="text" name="example_post_form_hook2" id="example_post_form_hook2"/>';
$out .= '</td></tr>';
$out .= '<tr><th colspan="' . (isset($options['colspan']) ? $options['colspan'] * 2 : '4') . '">'; $edit_panel = 'viewitem' . $ticket->fields['id'] . $rand;
$out .= sprintf( $JS = <<<JAVASCRIPT
__('End %1$s hook call for %2$s type'),
'post_item_form',
$item::getType()
);
$out .= '</th></tr>';
echo $out;
}
static public function timelineActions($params = []) {
$rand = $params['rand'];
$ticket = $params['item'];
if (get_class($ticket) !== "Ticket") {
return false;
}
$edit_panel = "viewitem".$ticket->fields['id'].$rand;
$JS = <<<JAVASCRIPT
$(function() { $(function() {
$(document).on('click', '#email_transfer_{$rand}', function(event) { $(document).on('click', '#email_transfer_{$rand}', function(event) {
$('#{$edit_panel}').html('email send'); $('#{$edit_panel}').html('email send');
@@ -208,10 +207,10 @@ TWIG, []);
}); });
JAVASCRIPT; JAVASCRIPT;
echo "<li class='followup' id='email_transfer_$rand'> echo "<li class='followup' id='email_transfer_$rand'>
<i class='far fa-envelope'></i>". <i class='far fa-envelope'></i>" .
__("Send a notification"). __('Send a notification') .
Html::scriptBlock($JS)." Html::scriptBlock($JS) . '
</li>"; </li>';
} }
} }

View File

@@ -36,21 +36,21 @@
// 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')) { if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file"); 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
{
static public $itemtype_2 = DeviceCamera::class; public static $itemtype_2 = DeviceCamera::class;
static public $items_id_2 = 'plugin_example_devicecameras_id'; public static $items_id_2 = 'plugin_example_devicecameras_id';
static protected $notable = false;
protected static $notable = false;
} }

View File

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

View File

@@ -66,9 +66,9 @@ final class Profile extends \Profile
$rights = [ $rights = [
[ [
'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,10 +34,11 @@
// ---------------------------------------------------------------------- // ----------------------------------------------------------------------
namespace GlpiPlugin\Example; namespace GlpiPlugin\Example;
use Rule; use Rule;
if (!defined('GLPI_ROOT')) { if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file"); die("Sorry. You can't access directly to this file");
} }
@@ -48,40 +49,39 @@ if (!defined('GLPI_ROOT')) {
* - actions * - actions
* *
**/ **/
class RuleTest extends Rule { class RuleTest extends Rule
{
// From Rule
public static $rightname = 'rule_import';
public $can_sort = true;
// From Rule public function getTitle()
public static $rightname = 'rule_import'; {
public $can_sort = true; return 'test';
}
public function maxActionsCount()
{
return 1;
}
function getTitle() { public function getCriterias()
return 'test'; {
} $criterias = [];
$criterias['name']['field'] = 'name';
$criterias['name']['name'] = __('Software');
$criterias['name']['table'] = 'glpi_softwares';
return $criterias;
}
function maxActionsCount() { public function getActions()
return 1; {
} $actions = [];
$actions['softwarecategories_id']['name'] = __('Category (class)', 'example');
$actions['softwarecategories_id']['type'] = 'dropdown';
$actions['softwarecategories_id']['table'] = 'glpi_softwarecategories';
return $actions;
function getCriterias() { }
$criterias = [];
$criterias['name']['field'] = 'name';
$criterias['name']['name'] = __('Software');
$criterias['name']['table'] = 'glpi_softwares';
return $criterias;
}
function getActions() {
$actions = [];
$actions['softwarecategories_id']['name'] = __('Category (class)', 'example');
$actions['softwarecategories_id']['type'] = 'dropdown';
$actions['softwarecategories_id']['table'] = 'glpi_softwarecategories';
return $actions;
}
} }

View File

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

View File

@@ -51,45 +51,47 @@ 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
* @param array $params is an array like following
* array( 'item', 'options')
* where 'item' is the parent object (like 'Ticket'),
* and 'options' are options like following
* array( 'tabnum', 'itemtype')
* where 'tabnum' is the internal name of the tab that will be shown
* 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)
*/
public static function pre_show_tab($params)
{
switch ($params['item']->getType()) {
case 'Ticket':
if ($params['options']['itemtype'] == 'TicketValidation' && $params['options']['tabnum'] == 2) {
// if tasks are not all done
// then prevent solution div to show
// this is an example to prevent solving of ticket
if (true) { // here you should test if some tasks are in todo status.
$params['options']['prevent_solution'] = true; // this will be passed to the post_show hook
echo "<div id='toHideSolution' style='display: none;'>"; // in order to hide the default solution div
}
}
}
}
/** /**
* Summary of pre_show_tab * Summary of post_show_tab
* @param array $params is an array like following * @param array $params is identical to pre_show_tab parameter
* array( 'item', 'options') * Note: you may get datas from pre_show_tab in $param['options'] array (see example below)
* where 'item' is the parent object (like 'Ticket'), */
* and 'options' are options like following public static function post_show_tab($params)
* array( 'tabnum', 'itemtype') {
* where 'tabnum' is the internal name of the tab that will be shown switch ($params['item']->getType()) {
* and 'itemtype' is the type of the tab (ex: 'ITILFollowup' when showing followup tab in a ticket) case 'Ticket':
* Note: you may pass datas to post_show_tab using the $param['options'] array (see example below) if (isset($params['options']['prevent_solution'])) {
*/ echo '</div>';
static function pre_show_tab($params) { echo "<div style='margin-bottom: 20px;' class='box'>
switch ($params['item']->getType()) {
case 'Ticket':
if ($params['options']['itemtype']=='TicketValidation' && $params['options']['tabnum']==2) {
// if tasks are not all done
// then prevent solution div to show
// this is an example to prevent solving of ticket
if (true) { // here you should test if some tasks are in todo status.
$params['options']['prevent_solution'] = true; // this will be passed to the post_show hook
echo "<div id='toHideSolution' style='display: none;'>"; // in order to hide the default solution div
}
}
}
}
/**
* Summary of post_show_tab
* @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)
*/
static function post_show_tab($params) {
switch ($params['item']->getType()) {
case 'Ticket':
if (isset($params['options']['prevent_solution'])) {
echo "</div>";
echo "<div style='margin-bottom: 20px;' class='box'>
<div class='box-tleft'> <div class='box-tleft'>
<div class='box-tright'> <div class='box-tright'>
<div class='box-tcenter'> <div class='box-tcenter'>
@@ -100,12 +102,12 @@ class Showtabitem {
<div class='box-mright'> <div class='box-mright'>
<div class='box-mcenter'> <div class='box-mcenter'>
<h3> <h3>
<span class='red'>"."Can't solve ticket"." <span class='red'>" . "Can't solve ticket" . '
<br> <br>
</span> </span>
</h3> </h3>
<h3> <h3>
<span >"."Tasks are waiting to be done"." <span >' . 'Tasks are waiting to be done' . "
</span> </span>
</h3> </h3>
</div> </div>
@@ -118,83 +120,84 @@ class Showtabitem {
</div> </div>
</div> </div>
</div> "; </div> ";
}
break;
case 'Computer':
break;
}
}
/**
* Summary of pre_show_item
* @param array $params is an array like following
* array( 'item', 'options')
* where 'item' is the object to show (like 'Ticket', 'TicketTask', ...),
* BEWARE that sometimes it can be an array of data and not an object (ex: for solution item)
* and 'options' are options like following
* if item is a main object like a ticket, change, problem, ... then it contains
* array( 'id' )
* where 'id' is the id of object that will be shown (same than $param['item']->fields['id'])
* or if item contains a sub-object like followup, task, ... then it contains
* array( 'parent', 'rand', 'showprivate')
* where 'parent' is the main object related to the current item (ex: if 'item' is ITILFollowup then it will be the related Ticket)
* and 'rand' contains the random number that will be used to render the item
* and 'showprivate' is the right to show private items
* Note: you may pass datas to post_show_item using the $param['options'] array
*/
public static function pre_show_item($params)
{
if (!is_array($params['item'])) {
switch ($params['item']->getType()) {
case 'Ticket':
//echo 'test' ;
break;
case 'TicketTask':
//echo 'test' ;
break;
case 'ITILFollowup':
//echo 'test' ;
break;
} }
break; } else {
// here we are going to view a Solution
case 'Computer': return;
break; }
} }
}
/**
* Summary of pre_show_item
* @param array $params is an array like following
* array( 'item', 'options')
* where 'item' is the object to show (like 'Ticket', 'TicketTask', ...),
* BEWARE that sometimes it can be an array of data and not an object (ex: for solution item)
* and 'options' are options like following
* if item is a main object like a ticket, change, problem, ... then it contains
* array( 'id' )
* where 'id' is the id of object that will be shown (same than $param['item']->fields['id'])
* or if item contains a sub-object like followup, task, ... then it contains
* array( 'parent', 'rand', 'showprivate')
* where 'parent' is the main object related to the current item (ex: if 'item' is ITILFollowup then it will be the related Ticket)
* and 'rand' contains the random number that will be used to render the item
* and 'showprivate' is the right to show private items
* Note: you may pass datas to post_show_item using the $param['options'] array
*/
static function pre_show_item($params) {
if (!is_array($params['item'])) {
switch ($params['item']->getType()) {
case 'Ticket':
//echo 'test' ;
break;
case 'TicketTask' :
//echo 'test' ;
break;
case 'ITILFollowup' :
//echo 'test' ;
break;
}
} else {
// here we are going to view a Solution
return;
}
}
/**
* Summary of post_show_item
* @param array $params is an array like following
* array( 'item', 'options')
* where 'item' is the object to show (like 'Ticket', 'TicketTask', ...),
* and 'options' are options like following
* if item is a main object like a ticket, change, problem, ... then it contains
* array( 'id' )
* where 'id' is the id of object that will be shown (same than $param['item']->fields['id'])
* or if item contains a sub-object like followup, task, ... then it contains
* array( 'parent', 'rand', 'showprivate')
* where 'parent' is the main object related to the current item (ex: if 'item' is ITILFollowup then it will be the related Ticket)
* and 'rand' contains the random number that will be used to render the item
* and 'showprivate' is the right to show private items
* Note: you may get datas from pre_show_item using the $param['options'] array
*/
static function post_show_item($params) {
if (!is_array($params['item'])) {
switch ($params['item']->getType()) {
case 'Ticket':
//echo 'test' ;
break;
case 'TicketTask' :
//echo 'test' ;
break;
case 'ITILFollowup' :
//echo 'test' ;
break;
}
} else {
// here we are going to view a Solution
return;
}
}
/**
* Summary of post_show_item
* @param array $params is an array like following
* array( 'item', 'options')
* where 'item' is the object to show (like 'Ticket', 'TicketTask', ...),
* and 'options' are options like following
* if item is a main object like a ticket, change, problem, ... then it contains
* array( 'id' )
* where 'id' is the id of object that will be shown (same than $param['item']->fields['id'])
* or if item contains a sub-object like followup, task, ... then it contains
* array( 'parent', 'rand', 'showprivate')
* where 'parent' is the main object related to the current item (ex: if 'item' is ITILFollowup then it will be the related Ticket)
* and 'rand' contains the random number that will be used to render the item
* and 'showprivate' is the right to show private items
* Note: you may get datas from pre_show_item using the $param['options'] array
*/
public static function post_show_item($params)
{
if (!is_array($params['item'])) {
switch ($params['item']->getType()) {
case 'Ticket':
//echo 'test' ;
break;
case 'TicketTask':
//echo 'test' ;
break;
case 'ITILFollowup':
//echo 'test' ;
break;
}
} else {
// here we are going to view a Solution
return;
}
}
} }

View File

@@ -38,12 +38,12 @@
// Entry menu case // Entry menu case
define('GLPI_ROOT', '../..'); define('GLPI_ROOT', '../..');
include (GLPI_ROOT . "/inc/includes.php"); include(GLPI_ROOT . '/inc/includes.php');
Session::checkRight(Config::$rightname, UPDATE); Session::checkRight(Config::$rightname, UPDATE);
Html::header("TITLE", $_SERVER['PHP_SELF'], "plugins"); Html::header('TITLE', $_SERVER['PHP_SELF'], 'plugins');
echo "This is the plugin stat page"; echo 'This is the plugin stat page';
Html::footer(); Html::footer();