-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhook.php
More file actions
434 lines (386 loc) · 15.4 KB
/
hook.php
File metadata and controls
434 lines (386 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
<?php
declare(strict_types=1);
/**
* -------------------------------------------------------------------------
* NexTool Solutions - Hooks
* -------------------------------------------------------------------------
* Instalação: sql/install.sql (tabelas e seeds), geração do client_identifier.
* Desinstalação: sql/uninstall.sql (tabelas operacionais), remoção de
* diretórios dos módulos baixados. MassiveActions, giveItem, redefine_menus.
* -------------------------------------------------------------------------
* @author Richard Loureiro - https://linkedin.com/in/richard-ti/ - https://github.com/RPGMais/nextool
* @copyright 2025 Richard Loureiro
* @license GPLv3+ https://www.gnu.org/licenses/gpl-3.0.html
* @link https://linkedin.com/in/richard-ti
* -------------------------------------------------------------------------
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access directly to this file");
}
require_once __DIR__ . '/inc/modulespath.inc.php';
require_once __DIR__ . '/inc/modulemanager.class.php';
require_once __DIR__ . '/inc/basemodule.class.php';
require_once __DIR__ . '/inc/permissionmanager.class.php';
require_once __DIR__ . '/inc/hookprovidersdispatcher.class.php';
require_once __DIR__ . '/inc/nextoolmainconfig.class.php';
function plugin_nextool_install() {
global $DB;
if (!is_dir(NEXTOOL_DOC_DIR)) {
@mkdir(NEXTOOL_DOC_DIR, 0755, true);
}
if (!defined('NEXTOOL_MODULES_BASE')) {
require_once GLPI_ROOT . '/plugins/nextool/inc/modulespath.inc.php';
}
if (!is_dir(NEXTOOL_MODULES_BASE)) {
@mkdir(NEXTOOL_MODULES_BASE, 0755, true);
}
$sqlfile = GLPI_ROOT . '/plugins/nextool/sql/install.sql';
if (file_exists($sqlfile)) {
$DB->runFile($sqlfile);
}
$version = plugin_version_nextool()['version'] ?? '0.0.0';
$migration = new Migration($version);
$modulesTable = 'glpi_plugin_nextool_main_modules';
if ($DB->tableExists($modulesTable) && !$DB->fieldExists($modulesTable, 'description')) {
$migration->addField($modulesTable, 'description', 'text', ['after' => 'name', 'comment' => 'Descrição do módulo']);
}
$migration->executeMigration();
$configfile = GLPI_ROOT . '/plugins/nextool/inc/config.class.php';
if (file_exists($configfile)) {
require_once $configfile;
if (class_exists('PluginNextoolConfig')) {
try {
PluginNextoolConfig::getConfig();
} catch (Exception $e) {
Toolbox::logInFile('plugin_nextool', "Erro ao inicializar client_identifier durante install: " . $e->getMessage());
}
}
}
try {
$manager = PluginNextoolModuleManager::getInstance();
$manager->refreshModules();
Toolbox::logInFile(
'plugin_nextool',
sprintf('Install health-check: %d módulos detectados após reinstalação.', count($manager->getAllModules()))
);
} catch (Throwable $e) {
Toolbox::logInFile('plugin_nextool', 'Install health-check falhou: ' . $e->getMessage());
}
PluginNextoolPermissionManager::installRights();
PluginNextoolPermissionManager::syncModuleRights();
return true;
}
function plugin_nextool_upgrade($old_version) {
global $DB;
$result = plugin_nextool_install();
// Migração 3.7.0: remover coluna legada contract_active de 3 tabelas
if (version_compare($old_version, '3.7.0', '<')) {
$migFile = GLPI_ROOT . '/plugins/nextool/sql/migration_remove_contract_active.sql';
if (file_exists($migFile)) {
$DB->runFile($migFile);
Toolbox::logInFile('plugin_nextool', "Upgrade {$old_version} → 3.7.0: migração contract_active executada.");
}
}
PluginNextoolPermissionManager::syncModuleRights();
return $result;
}
/**
* Hook de desinstalação
*
* Remove estrutura de banco de dados e desinstala módulos usando o SQL dedicado.
*/
function plugin_nextool_uninstall() {
global $DB;
$manager = PluginNextoolModuleManager::getInstance();
$modulesTable = 'glpi_plugin_nextool_main_modules';
if ($DB->tableExists($modulesTable)) {
$iterator = $DB->request([
'FROM' => $modulesTable,
'WHERE' => ['is_installed' => 1]
]);
foreach ($iterator as $row) {
$moduleKey = $row['module_key'] ?? '';
if ($moduleKey !== '') {
try {
$manager->uninstallModule($moduleKey);
} catch (Throwable $e) {
Toolbox::logInFile('plugin_nextool', sprintf('Falha ao desinstalar módulo %s durante plugin_uninstall: %s', $moduleKey, $e->getMessage()));
}
}
}
}
$sqlfile = GLPI_ROOT . '/plugins/nextool/sql/uninstall.sql';
if (file_exists($sqlfile)) {
$DB->runFile($sqlfile);
}
// Remove diretório de dados do plugin em files/_plugins/nextool (módulos baixados; dados continuarão no banco)
if (is_dir(NEXTOOL_DOC_DIR)) {
nextool_delete_dir(NEXTOOL_DOC_DIR);
}
// Remove cache de descoberta de módulos e diretório temporário de downloads
$manager->clearCache();
$tmpRemoteDir = GLPI_TMP_DIR . '/nextool_remote';
if (is_dir($tmpRemoteDir)) {
nextool_delete_dir($tmpRemoteDir);
}
// Remove configurações do self-updater em glpi_configs
$DB->delete('glpi_configs', ['context' => 'plugin:nextool_core_update']);
$DB->delete('glpi_configs', ['context' => 'plugin:nextool_distribution']);
Toolbox::logInFile('plugin_nextool', 'Plugin desinstalado: módulos removidos, caches limpos e diretórios temporários apagados.');
PluginNextoolPermissionManager::removeRights();
return true;
}
/**
* Hook MassiveActions - adiciona ações em massa customizadas por itemtype.
*
* O GLPI descobre essas ações via função global do plugin. Para evitar acoplamento
* com módulos específicos, delegamos para providers registrados pelos módulos ativos.
*
* @param string $type
* @return array<string,string>
*/
function plugin_nextool_MassiveActions($type) {
return PluginNextoolHookProvidersDispatcher::getMassiveActions((string) $type);
}
/**
* Hook MassiveActionsFieldsDisplay - exibe campos específicos no formulário de ação em massa "Atualizar".
* Alguns itemtypes de plugin exigem renderização manual para evitar 500 no core.
* Delegado para providers.
*
* @param array $options ['itemtype' => string, 'options' => array (search option)]
* @return bool True se tratou o campo, false para deixar o core processar
*/
function plugin_nextool_MassiveActionsFieldsDisplay($options = []) {
try {
return PluginNextoolHookProvidersDispatcher::massiveActionsFieldsDisplay((array) $options);
} catch (\Throwable $e) {
error_log('[NexTool] MassiveActionsFieldsDisplay error: ' . $e->getMessage());
return false;
}
}
/**
* Hook giveItem para Search - trata exibição de células de itemtypes de plugin.
* Delegado para providers (evita acoplamento com módulos).
*
* @param string|null $itemtype
* @param int $ID ID da search option
* @param array $data Dados da linha
* @param int $num Índice da coluna
* @return string|false Valor formatado ou false para usar o padrão
*/
function plugin_nextool_giveItem($itemtype, $ID, $data, $num) {
try {
return PluginNextoolHookProvidersDispatcher::giveItem($itemtype, $ID, $data, $num);
} catch (\Throwable $e) {
error_log('[NexTool] giveItem error: ' . $e->getMessage());
return false;
}
}
/**
* Hook redefine_menus - Cria menus de primeiro nível na barra principal.
*
* 1. "Nextools" (nativo do plugin) - menu principal com submenu por módulo/admin.
* 2. Menus adicionais via getRedefineMenuItems() - módulos que precisam de menu
* de primeiro nível próprio declaram via método na BaseModule.
*
* @param array $menu Menu atual do GLPI
* @return array Menu modificado
*/
function plugin_nextool_redefine_menus($menu) {
if (empty($menu)) {
return $menu;
}
// Não exibir menus NexTool para perfis de interface simplificada (self-service/helpdesk)
if (Session::getCurrentInterface() === 'helpdesk') {
return $menu;
}
try {
return _plugin_nextool_build_menus($menu);
} catch (\Throwable $e) {
error_log('[NexTool] redefine_menus error: ' . $e->getMessage());
return $menu; // GLPI continua com menu padrão
}
}
/**
* Construção interna dos menus NexTool — isolada para que redefine_menus
* possa capturar qualquer exceção sem derrubar o GLPI.
*/
function _plugin_nextool_build_menus($menu) {
// Verificar permissões globais do NexTool
$canViewModulesGlobal = PluginNextoolPermissionManager::canViewModules();
$canAccessAdmin = PluginNextoolPermissionManager::canAccessAdminTabs();
$canViewAnyMod = PluginNextoolPermissionManager::canViewAnyModule();
$hasGlobalAdmin = Session::haveRight('config', UPDATE);
// Se o perfil não tem nenhuma permissão no NexTool, não exibir menu
if (!$canViewModulesGlobal && !$canAccessAdmin && !$canViewAnyMod && !$hasGlobalAdmin) {
return $menu;
}
global $CFG_GLPI;
$rootDoc = $CFG_GLPI['root_doc'] ?? '';
// ---- Menu nativo "Nextools" (independente de módulos) ----
$nextoolsItem = [
'title' => __('Nextools', 'nextool'),
'icon' => 'ti ti-tool',
'types' => [],
'content' => [],
];
$configBase = $rootDoc . '/plugins/nextool/front/nextoolconfig.form.php?id=1';
// Subitem "Módulos": requer permissão global de módulos OU acesso a algum módulo
if ($canViewModulesGlobal || $canViewAnyMod || $hasGlobalAdmin) {
$nextoolsItem['content']['modulos'] = [
'title' => __('Módulos', 'nextool'),
'page' => $configBase . '&forcetab=PluginNextoolMainConfig$1',
'icon' => 'ti ti-puzzle',
];
}
// Subitens administrativos: requer permissão de abas admin OU bypass global
if ($canAccessAdmin || $hasGlobalAdmin) {
$nextoolsItem['content']['contato'] = [
'title' => __('Contato', 'nextool'),
'page' => $configBase . '&forcetab=PluginNextoolMainConfig$2',
'icon' => 'ti ti-headset',
];
$nextoolsItem['content']['licenciamento'] = [
'title' => __('Licenciamento', 'nextool'),
'page' => $configBase . '&forcetab=PluginNextoolMainConfig$3',
'icon' => 'ti ti-key',
];
$nextoolsItem['content']['logs'] = [
'title' => __('Logs', 'nextool'),
'page' => $configBase . '&forcetab=PluginNextoolMainConfig$4',
'icon' => 'ti ti-report-analytics',
];
$nextoolsItem['content']['historico'] = [
'title' => __('Histórico', 'nextool'),
'page' => $configBase . '&forcetab=Log$1',
'icon' => 'ti ti-history',
];
}
$modManager = null;
try {
if (class_exists('PluginNextoolModuleManager')) {
$modManager = PluginNextoolModuleManager::getInstance();
}
} catch (Throwable $e) {
// Silenciar — ModuleManager pode não estar disponível durante instalação/desinstalação do plugin
}
// Abas dinâmicas: cada módulo instalado com config (exceto standalone)
// Cada aba de módulo só aparece se o perfil tem READ no módulo e o módulo está ativo
$moduleConfigTabs = PluginNextoolMainConfig::getModuleConfigTabs();
foreach ($moduleConfigTabs as $tabNum => $meta) {
$moduleKey = $meta['module_key'] ?? '';
if ($modManager !== null && $moduleKey !== '') {
$mod = $modManager->getModule($moduleKey);
if ($mod && !$mod->isEnabled()) {
continue;
}
}
if ($moduleKey !== '' && !PluginNextoolPermissionManager::canViewModule($moduleKey) && !$hasGlobalAdmin) {
continue;
}
$key = 'module_' . $moduleKey;
$nextoolsItem['content'][$key] = [
'title' => $meta['name'],
'page' => $configBase . '&forcetab=PluginNextoolMainConfig$' . $tabNum,
'icon' => $meta['icon'],
];
}
// Módulos standalone instalados: submenu aponta para getConfigPage()
// Aparece no menu quando instalado E ativo.
if ($modManager !== null) {
try {
foreach ($modManager->getAllModules() as $mk => $mod) {
if (!$mod->isInstalled() || !$mod->isEnabled()) {
continue;
}
if (method_exists($mod, 'usesStandaloneConfig') && $mod->usesStandaloneConfig() && $mod->hasConfig()) {
if (!PluginNextoolPermissionManager::canViewModule($mk)) {
continue;
}
$key = 'module_' . $mk;
$nextoolsItem['content'][$key] = [
'title' => $mod->getName(),
'page' => $mod->getConfigPage(),
'icon' => $mod->getIcon(),
];
}
}
} catch (Throwable $e) {
// Silenciar erros na construção do menu
}
}
// Ordem fixa: Módulos primeiro, depois Contato, Licenciamento, Logs, depois módulos
$order = ['modulos', 'contato', 'licenciamento', 'logs'];
$content = $nextoolsItem['content'];
$nextoolsItem['content'] = [];
foreach ($order as $k) {
if (isset($content[$k])) {
$nextoolsItem['content'][$k] = $content[$k];
}
}
foreach ($moduleConfigTabs as $tabNum => $meta) {
$key = 'module_' . $meta['module_key'];
if (isset($content[$key])) {
$nextoolsItem['content'][$key] = $content[$key];
}
}
// Módulos standalone (não presentes em $moduleConfigTabs) na ordem que restou
foreach ($content as $k => $v) {
if (!isset($nextoolsItem['content'][$k])) {
$nextoolsItem['content'][$k] = $v;
}
}
// Só inserir "Nextools" se tem conteúdo (perfil pode não ter nenhuma permissão)
if (!empty($nextoolsItem['content'])) {
$ordered = [];
$inserted = false;
foreach ($menu as $key => $value) {
if ($key === 'nextools') continue;
if (($key === 'ritecadmin' || $key === 'config') && !$inserted) {
$ordered['nextools'] = $nextoolsItem;
$inserted = true;
}
$ordered[$key] = $value;
}
if (!$inserted) {
$ordered['nextools'] = $nextoolsItem;
}
$menu = $ordered;
}
// ---- Menus adicionais via getRedefineMenuItems() (genérico) ----
try {
if ($modManager === null) {
$modManager = PluginNextoolModuleManager::getInstance();
}
foreach ($modManager->getActiveModules() as $rdKey => $rdModule) {
if (!method_exists($rdModule, 'getRedefineMenuItems')) {
continue;
}
if (!PluginNextoolPermissionManager::canViewModule($rdKey)) {
continue;
}
$menuData = $rdModule->getRedefineMenuItems();
if (is_array($menuData) && !empty($menuData['menu_key']) && !empty($menuData['menu'])) {
$mKey = $menuData['menu_key'];
if (empty($menu[$mKey])) {
$menu[$mKey] = $menuData['menu'];
} else {
// Merge conteúdo se menu já existe
if (!empty($menuData['menu']['content'])) {
$menu[$mKey]['content'] = array_merge(
$menu[$mKey]['content'] ?? [],
$menuData['menu']['content']
);
}
}
}
}
} catch (Throwable $e) {
// Silenciar erros na construção de menus de módulos
}
return $menu;
}
function nextool_delete_dir(string $dir): void {
require_once GLPI_ROOT . '/plugins/nextool/inc/filehelper.class.php';
PluginNextoolFileHelper::deleteDirectory($dir, false);
}