Vamos a crear un plugin básico que solo diga hola mundo, pero que dará las primeras luces en cómo crear un plugin en glpi
La estructura del directorio:
Depende de tu plugin, se pueden crear infinitas carpetas, pero el estándar es
-Miplugin(*)/
-front(*)/
-inc(*)/
-locales(**)/
-tools/
-README.md
-LICENSE
-setup.php(*)
-hook.php(*)
-miplugin.xml
-miplugin.png
(*) Obligatorio que existan.
(**) Para mi debería ser obligatorio porque hace internacional tu aplicación
- en front, están los archivos de php que se mostraran al usuario (la vista)
- el setup.php, es automáticamente cargado por el core de glpi, chequea prerequisitos, etc
- el hook.php, se usa para realizar acciones por ejemplo al instalar o desinstalar el plugin
Pasos para crear el plugin1.-la carpeta raíz se debe llamar igual que el plugin y debe estar en minúscula y sin espacios. Ejemplo:
holamundo2.-Recrear las carpetas y archivos obligatorios necesarios para el plugins, como lo son front/ inc/ locales/ setup.php y hook.php Ejemplo:
holamundo/
front/
inc/
locales/
setup.php
hook.php
3.-Editar el archivo setup.php ejemplo:
<?php
/*
*
-------------------------------------------------------------------------
Plugin GLPI hola mundo
*/
function plugin_init_
holamundo() {
global $PLUGIN_HOOKS;
$PLUGIN_HOOKS['csrf_compliant']['
holamundo'] = true;
$PLUGIN_HOOKS['change_profile']['
holamundo'] = array('Plugin
HolamundoProfile', 'changeProfile');
//aquí esta registrando la clase profile que es la que desencadena todo en este ejemplo
Plugin::registerClass('Plugin
HolamundoProfile', array('addtabon' => '
Profile'));
$plugin = new Plugin();
if (isset($_SESSION['glpiID']) && $plugin->isInstalled('
holamundo') && $plugin->isActivated('
holamundo')) {
if (Session::haveRight('plugin_
holamundo', READ)) {
//aquí se agrega al menú complementos
$PLUGIN_HOOKS['menu_toadd']['
holamundo'] = array(
'plugins' => 'Plugin
HolamundoIndex'); //en la clase form.class.php hace referencia esto
}
}
}
function plugin_version_
holamundo() {
global $LANG;
return array(
'name' =>
$LANG['plugin_holamundo']['title'],
'version' => '1.1.0',
'author' => "Alexander Chale",
'license' => "GPLv2+",
'homepage' => 'https://glpiconchale.blogspot.com',
'minGlpiVersion' => '9.2' //aqui le digo que mi plugin va a trabajar con la versión minima de glpi
);
}
function plugin_
holamundo_check_prerequisites() {
if (GLPI_VERSION >= 9.2) { //aqui le digo que el prerequisito es la versión 9.2 de glpi
return true;
} else { //aquí le mando un mensaje si no tiene instalada la versión de glpi que yo deseo, y no lo deja instalar el plugin
echo "La versión de GLPI no es compatible. Requiere GLPI 9.2";
return false;
}
}
function plugin_
holamundo_check_config() {
return true;
}
4.- Editar el archivo hook.php ejemplo:
<?php
// plugin_"nombredelpluginenminúscula"_install() Nombre de la carpeta del plugin en el directorio plugins
function plugin_
holamundo_install() {
global $DB;
//PluginHolamundoProfile el Plugin"Nombredelpluginprimeraletramayúscula"Profile
//donde Profile es un archivo ubicado en plugins/holamundo/inc/profile.class.php
Plugin
HolamundoProfile::createFirstAccess($_SESSION['glpiactiveprofile']['id']);
// aquí podrías crear tablas en la base de datos que luego tu aplicación necesite
return true;
}
function plugin_
holamundo_uninstall() {
global $DB;
Plugin
HolamundoProfile::uninstallProfile();
// aquí podrás eliminar las tablas que creaste en la base de datos
return true;
}
?>
5.- deberíamos empezar con las clases que declaramos en el archivo setup.php
las clases declaradas fueron Profile y hacemos un llamado en el menú de Index
5.1.- Creamos y editamos el archivo profile.class.php en inc/
<?php
/*
*
-------------------------------------------------------------------------
Copyright (C) 2017 by Walid H.
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
class Plugin
HolamundoProfile extends Profile {
static $rightname = 'profile';
public static function getAllRights() {
global $LANG;
return array(
array(
'itemtype' => 'Plugin
HolamundoProfile',
'label' =>
$LANG['plugin_holamundo']['manage_alerts'],
'field' => 'plugin_
holamundo'
),
);
}
public static function addDefaultProfileInfos($profiles_id, $rights) {
$profileRight = new ProfileRight();
foreach ($rights as $right => $value) {
if (!countElementsInTable('glpi_profilerights', "`profiles_id`='$profiles_id' AND `name`='$right'")) {
$myright['profiles_id'] = $profiles_id;
$myright['name'] = $right;
$myright['rights'] = $value;
$profileRight->add($myright);
//Add right to the current session
$_SESSION['glpiactiveprofile'][$right] = $value;
}
}
}
/**
* @param $ID integer
*/
public static function createFirstAccess($profiles_id) {
$profile = new self();
foreach ($profile->getAllRights() as $right) {
self::addDefaultProfileInfos($profiles_id, array($right['field'] => ALLSTANDARDRIGHT));
}
}
public static function changeProfile() {
$profile = new self();
if ($profile->getFromDBByProfile($_SESSION['glpiactiveprofile']['id'])) {
$_SESSION['glpiactiveprofile']['
holamundo_alert'] = $profile->getField('alert');
} else {
unset($_SESSION['glpiactiveprofile']['
holamundo_alert']);
}
}
public function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
global $LANG;
return
$LANG['plugin_holamundo']['title'];
}
public function getFromDBByProfile($profiles_id) {
global $DB;
$query = "SELECT *
FROM `" . $this->getTable() . "`
WHERE `profiles_id` = '" . (int) $profiles_id . "' ";
if ($result = $DB->query($query)) {
if ($DB->numrows($result)) {
$this->fields = $DB->fetch_assoc($result);
if (is_array($this->fields) && count($this->fields)) {
return true;
}
}
}
return false;
}
public static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
$profile = new self();
if (!$profile->getFromDBByProfile($item->getID())) {
self::createFirstAccess($item->getID());
$profile->getFromDBByProfile($item->getID());
}
$profile->showForm($item->getField('id'));
}
public function showForm($profiles_id, $options = array()) {
global $LANG;
$profile = new Profile();
$profile->getFromDB($profiles_id);
if ($canedit = Session::haveRightsOr(self::$rightname, array(CREATE, UPDATE, PURGE))) {
echo "<form action='" . $profile->getFormURL() . "' method='post'>";
}
$profile = new Profile();
$profile->getFromDB($profiles_id);
$rights = $this->getAllRights();
$profile->displayRightsChoiceMatrix($rights, array(
'canedit' => $canedit,
'default_class' => 'tab_bg_2',
'title' =>
$LANG['plugin_holamundo']['title'],
));
if ($canedit) {
echo "<div class='center'>";
echo Html::hidden('id', array('value' => $profiles_id));
echo Html::submit(_sx('button', 'Save'), array('name' => 'update'));
echo "</div>\n";
Html::closeForm();
}
HTML::closeForm();
}
public static function uninstallProfile() {
$pfProfile = new self();
$a_rights = $pfProfile->getAllRights();
foreach ($a_rights as $data) {
ProfileRight::deleteProfileRights(array($data['field']));
}
}
}
5.2.- Creamos y editamos el archivo index.class.php en inc/
<?php
/*
*
-------------------------------------------------------------------------
Plugin GLPI Example
Copyright (C) 2017 by Walid H.
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
class Plugin
HolamundoIndex extends CommonDBTM {
static $rightname = 'plugin_
holamundo';
/**
*
* @return type
*/
public static function getTypeName() {
return
$GLOBALS['LANG']['plugin_holamundo']['title'];
}
/**
* Show the form (menu->plugin->holamundo)
*/
public function formIndex() {
echo "<form action='' method='post'>";
echo '<div class="tab_cadre_fixe" style="box-shadow: 0 1px 8px #aaa;text-align:center;padding:1em;">';
echo "<h1>Ver holamundo</h1>";
echo "<p>...</p>";
echo "</div>";
html::closeForm();
}
/**
* @see CommonGLPI::getAdditionalMenuLinks()
**/
static function getAdditionalMenuLinks() {
global $CFG_GLPI;
$links = array();
// $links['config'] = '/plugins/holamundo/front/link_cualquiera.php';
// $links["<img src='".$CFG_GLPI["root_doc"]."/pics/menu_showall.png' title='".__s('Show all')."' alt='".__s('Show all')."'>"] = '/plugins/holamundo/front/link_cualquiera.php';
$links[__s('Ver Link', '
holamundo')] = '/plugins/
holamundo/front/link_cualquiera.php';
return $links;
}
}
6.- aqui agrego una clase que no esta declarada en ninguna lugar pero que yo denomino mis funciones, en este ejemplo solo tiene funciones de saludo, pero esto muestra la potencia de los plugins
creamos y editamos misfunciones.php en inc/
<?php
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
function printHolamundo () {//agregado
global $DB, $CFG_GLPI, $LANG;
$itemtype = 0;
$items_id = "";
$content = "";
$title = "";
$ticketcategories_id = 0;
$urgency = 3;
$type = 0;
echo "Hola mundo...de aqui puedo llamar a cualquier cosa";
}
function printHolamundo2 () {//agregado
global $DB, $CFG_GLPI, $LANG;
$itemtype = 0;
$items_id = "";
$content = "";
$title = "";
$ticketcategories_id = 0;
$urgency = 3;
$type = 0;
echo "aqui podría estar otro código que tenga relación con la creación";
}
?>
7.- en algunos de estos archivos hemos utilizado los locales por eso creamos el archivo es_VE.php que es mi idioma predeterminado
creamos y editamos el archivo es_VE.php en locales/
<?php
$LANG['plugin_holamundo']['title'] = "Titulo del plugin";
$LANG['plugin_holamundo']['manage_alerts'] = "Plugin de ejemplo para GLPI";
8.- creamos el archivo index.php en front/ que sera lo ṕrimero que veamos al invocar el plugin desde el menú
<?php
/*
*
-------------------------------------------------------------------------
Plugin GLPI Example
*/
include ("../../../inc/includes.php");
include ('../inc/misfunciones.php'); //aqui esta parte de la lógica
Session::checkLoginUser();
session_start();
$plugin = new Plugin();
if (!$plugin->isInstalled("
holamundo") || !$plugin->isActivated("
holamundo")) {
Html::displayNotFoundError();
}
Session::checkRight('plugin_
holamundo', READ);
$app = new Plugin
HolamundoIndex();
Html::header(
$LANG['plugin_holamundo']['title'],
$_SERVER["PHP_SELF"],
'plugins',
"Plugin
HolamundoIndex"
);
//podriamos llamar a las funciones desde cualquier lado con include
//printHolamundo();
ó utilizamos la herencia de la clase index
$app->formIndex();
if (Session::getCurrentInterface() == "helpdesk") {
Html::helpFooter();
} else {
Html::footer();
}
9.- con esto ya tienes un plugin en glpi que no hace nada, para que en el boton de busqueda de + haga algo (en nuestro caso mostrar otro mensaje) vamos a crear el archivo index.form.php en front/
<?php
/*
*
-------------------------------------------------------------------------
Plugin GLPI Example
Copyright (C) 2017 by Walid H.
*/
include ("../../../inc/includes.php");
include ('../inc/misfunciones.php'); //aqui esta parte de la lógica
Session::checkLoginUser();
session_start();
$plugin = new Plugin();
if (!$plugin->isInstalled("
holamundo") || !$plugin->isActivated("
holamundo")) {
Html::displayNotFoundError();
}
Session::checkRight('plugin_
holamundo', READ);
$app = new Plugin
HolamundoIndex();
Html::header(
$LANG['plugin_holamundo']['title'],
$_SERVER["PHP_SELF"],
'plugins',
"Plugin
HolamundoIndex"
);
printHolamundo2();
if (Session::getCurrentInterface() == "helpdesk") {
Html::helpFooter();
} else {
Html::footer();
}
y por último en el paso 5.2 especificamente en la función "static function getAdditionalMenuLinks()" estamos llamando a un archivo link_cualquiera.php
ese archivo hay que crearlo en front/
<?php
include ("../../../inc/includes.php");
Session::checkLoginUser();
session_start();
$plugin = new Plugin();
if (!$plugin->isInstalled("
holamundo") || !$plugin->isActivated("
holamundo")) {
Html::displayNotFoundError();
}
Session::checkRight('plugin_
holamundo', READ);
$app = new Plugin
HolamundoIndex();
Html::header(
$LANG['plugin_holamundo']['title'],
$_SERVER["PHP_SELF"],
'plugins',
"Plugin
HolamundoIndex"
);
//aqui va lo que ve el usuario
echo ("me llamaron desde otro lugar");
//$app->formIndex();
if (Session::getCurrentInterface() == "helpdesk") {
Html::helpFooter();
} else {
Html::footer();
}
Eso es todo.