Repository navigation
Expand file tree
/
Copy pathsetup.php
More file actions
1086 lines (1010 loc) · 55.8 KB
/
Copy pathsetup.php
File metadata and controls
1086 lines (1010 loc) · 55.8 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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* -------------------------------------------------------------------------
* NexTool Solutions - Setup
* -------------------------------------------------------------------------
* Plugin principal para GLPI 11. Sistema modular: ModuleManager (auto-discovery),
* BaseModule (classe base), módulos em modules/[nome]/[nome].class.php.
* Documentação completa em: docs/
* -------------------------------------------------------------------------
* @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` (nao `require_once`) de proposito (nextool-dev#282): um script CLI que toque um arquivo
// do plugin ANTES de bootar o kernel inclui este arquivo sem GLPI_ROOT, e as constantes de caminho
// dos modulos ficam por definir; o arquivo e idempotente (guardas por defined/function_exists),
// entao reincluir aqui, com GLPI_ROOT garantido, completa o que faltou.
require __DIR__ . '/inc/modulespath.inc.php';
require_once __DIR__ . '/inc/localeresolver.class.php';
// Compat de versao: shim da interface de Search do GLPI 11 (no-op no GLPI 11,
// declara stub no GLPI 10). Carregado ANTES de qualquer classe do plugin que
// faca `implements \Glpi\Search\DefaultSearchRequestInterface` (base e modulos).
require_once __DIR__ . '/inc/compat/searchcompat.php';
// Helper das APIs que mudaram entre as majors (GLPI 10/11/12). O autoloader do core o
// resolve pelo nome; o require aqui so garante a ordem. Guardado por is_file() porque o
// self-update grava arquivo a arquivo: este setup.php pode chegar ao disco antes do helper.
if (is_file(__DIR__ . '/inc/compat.class.php')) {
require_once __DIR__ . '/inc/compat.class.php';
}
/** Versão do plugin (usada em plugin_version_nextool e migrations) */
define('PLUGIN_NEXTOOL_VERSION', '6.42.0');
/** GLPI mínimo e máximo suportados (requisitos oficiais Teclib/marketplace) */
define('PLUGIN_NEXTOOL_MIN_GLPI_VERSION', '10.0.0');
define('PLUGIN_NEXTOOL_MAX_GLPI_VERSION', '12.0.99');
/** URLs e metadados do projeto (centralizados para evitar hardcoding) */
define('NEXTOOL_AUTHOR_NAME', 'Richard Loureiro');
define('NEXTOOL_AUTHOR_URL', 'https://linkedin.com/in/richard-ti/');
define('NEXTOOL_SITE_URL', 'https://nextoolsolutions.com');
define('NEXTOOL_WHATSAPP_URL', 'https://api.whatsapp.com/send?phone=5532984692962&text=Ol%C3%A1%2C%20gostaria%20de%20falar%20sobre%20os%20produtos%20da%20Nextools.');
define('NEXTOOL_BOOKING_URL', 'https://nextoolsolutions.com/agenda');
// Solicitações do cliente no portal: o atendimento é aberto pelo popup Suporte e acompanhado aqui.
define('NEXTOOL_PORTAL_SUPPORT_URL', 'https://app.nextoolsolutions.com/painel/solicitacoes');
define('NEXTOOL_RELEASES_URL', 'https://github.com/RPGMais/nextool/releases');
define('NEXTOOL_TERMS_URL', 'https://nextoolsolutions.com/termos-de-uso');
/**
* Retorno de plugin_version_*: exibido em Configurar → Plugins e usado pelo marketplace.
* requirements: formato oficial desde GLPI 9.2 (minGlpiVersion está deprecado).
*/
function plugin_version_nextool() {
return [
'name' => 'NexTool Solutions',
'version' => PLUGIN_NEXTOOL_VERSION,
'author' => 'Richard Loureiro - <a href="https://linkedin.com/in/richard-ti/" target="_blank" rel="noopener">linkedin.com/in/richard-ti</a>',
'license' => 'GPLv3+',
'homepage' => 'https://nextoolsolutions.com',
'requirements' => [
'glpi' => [
'min' => PLUGIN_NEXTOOL_MIN_GLPI_VERSION,
'max' => PLUGIN_NEXTOOL_MAX_GLPI_VERSION,
],
],
];
}
/**
* Profiler nativo do GLPI por etapa do boot (nextool-dev#249). So coleta em modo
* DEBUG (Session::DEBUG_MODE) e quando a classe existe (GLPI 10.0.x recentes e
* 11.x); fora disso custa 1 comparacao. As secoes aninham sob "nextool:init" (o
* core abre essa secao em Plugin::load) e aparecem no debug bar e em
* ajax/debug.php?ajax_id=<X-Glpi-Ajax-ID>. Nunca lanca: qualquer falha do
* profiler nao pode derrubar o boot.
*/
function plugin_nextool_prof_enabled(): bool {
static $on = null;
if ($on === null) {
try {
$on = isset($_SESSION['glpi_use_mode'])
&& class_exists('Session')
&& (int) $_SESSION['glpi_use_mode'] === Session::DEBUG_MODE
&& class_exists('\Glpi\Debug\Profiler');
} catch (\Throwable $e) {
$on = false;
}
}
return $on;
}
function plugin_nextool_prof_start(string $name): void {
if (!plugin_nextool_prof_enabled()) {
return;
}
try {
$category = defined('\Glpi\Debug\Profiler::CATEGORY_PLUGINS') ? \Glpi\Debug\Profiler::CATEGORY_PLUGINS : 'plugins';
\Glpi\Debug\Profiler::getInstance()->start('nextool:' . $name, $category);
} catch (\Throwable $e) {
// profiler nunca derruba o boot
}
}
function plugin_nextool_prof_stop(string $name): void {
if (!plugin_nextool_prof_enabled()) {
return;
}
try {
\Glpi\Debug\Profiler::getInstance()->stop('nextool:' . $name);
} catch (\Throwable $e) {
// idem
}
}
/**
* Fast-path de assets (nextool-dev#249): requests de front/module_bundle.php,
* front/module_assets.php e dos wrappers front/*.js.php|*.css.php da base so
* precisam de sessao + classes da base + descoberta de modulos (para
* getModule()->loadModuleLang() e getConfig()). Eles NAO precisam dos 33
* onInit(), do bundler, do hook.php, dos providers, do sync de rights, do
* scan de classes nem dos menus -- que e o grosso do nextool:init. Cada pagina
* dispara 2 a 3 desses requests, e no GLPI 11 eles seguram o lock da sessao
* durante o boot inteiro. Decisao por PATH (nunca por query string): casar so
* reduz trabalho, nunca concede nada (o guard 401 dos endpoints continua).
*
* Kill switch (sem schema): define('NEXTOOL_BOOT_FAST_PATH', false) em
* config/local_define.php, ou arquivo GLPI_CACHE_DIR/nextool_boot_fast_path.off.
*/
function plugin_nextool_is_asset_request(): bool {
static $is = null;
if ($is !== null) {
return $is;
}
$is = false;
if (PHP_SAPI === 'cli') {
return false;
}
$path = (string) parse_url((string) ($_SERVER['REQUEST_URI'] ?? ''), PHP_URL_PATH);
if ($path === '' || substr($path, -10) === '/index.php') {
$path = (string) ($_SERVER['SCRIPT_NAME'] ?? '');
}
$is = (bool) preg_match('#/nextool/front/module_(?:bundle|assets)\.php(?:/|$)#', $path)
|| (bool) preg_match('#/nextool/front/[\w.-]+\.(?:js|css)\.php$#', $path);
return $is;
}
function plugin_nextool_boot_fast_path_enabled(): bool {
if (defined('NEXTOOL_BOOT_FAST_PATH')) {
return (bool) NEXTOOL_BOOT_FAST_PATH;
}
if (defined('GLPI_CACHE_DIR') && is_file(GLPI_CACHE_DIR . '/nextool_boot_fast_path.off')) {
return false;
}
return true;
}
/**
* Registra o dicionário da base no idioma da sessão (com fallback de variante:
* es_CO usa es_ES.mo sem alterar o idioma corrente do GLPI). Usado no init e
* pelo ajax/module_ajax.php quando ele restaura a sessão depois do boot.
*/
function plugin_nextool_load_base_lang(): void {
global $CFG_GLPI;
$requested = (string) ($_SESSION['glpilanguage'] ?? $CFG_GLPI['language'] ?? 'en_GB');
$resolved = PluginNextoolLocaleResolver::resolveMoFile(
NEXTOOL_PHP_DIR . '/locales',
$requested,
(string) ($CFG_GLPI['language'] ?? 'en_GB'),
(array) ($CFG_GLPI['languages'] ?? [])
);
if ($resolved !== null) {
// O 3o argumento registra o catálogo escolhido sob o locale real da sessão.
Plugin::loadLang('nextool', $resolved['locale'], $requested);
} else {
Plugin::loadLang('nextool');
}
}
/**
* Hook executado durante o boot do GLPI, antes da sessão e da inicialização dos plugins.
*
* GLPI 11 (Symfony) aplica CSRF em qualquer POST não-stateless via CheckCsrfListener.
* Para permitir webhooks (stateless) em module_ajax.php, registramos o path do
* roteador como stateless no SessionManager para que o Kernel NÃO aplique CSRF.
*
* Importante: isso faz o GLPI desabilitar cookies e NÃO iniciar sessão por padrão
* nesse path. Para não quebrar módulos autenticados (geolocation, aiassist, etc.),
* o próprio module_ajax.php reabilita cookies, inicia a sessão e faz check CSRF
* SOMENTE quando o arquivo do módulo NÃO é stateless.
*
* A decisão do que é stateless continua sendo feita internamente pelo module_ajax.php
* via plugin_nextool_stateless_files() (whitelist explícita).
*
* O Firewall recebe STRATEGY_NO_CHECK para module_ajax.php, permitindo que
* o próprio roteador faça a validação (sessão ou stateless conforme o módulo).
*/
function plugin_nextool_boot() {
// Necessário para webhooks (POST) e endpoints stateless não caírem no CheckCsrfListener do Symfony.
// Proteção defensiva: se os métodos não existirem (GLPI 11 antigo), o plugin não quebra o GLPI.
try {
if (class_exists('\Glpi\Http\SessionManager')
&& method_exists('\Glpi\Http\SessionManager', 'registerPluginStatelessPath')) {
\Glpi\Http\SessionManager::registerPluginStatelessPath(
'nextool',
'#^/ajax/module_ajax\\.php$#'
);
// Cloud link v1: push do cérebro, autenticado por HMAC (sem cookie/CSRF).
\Glpi\Http\SessionManager::registerPluginStatelessPath(
'nextool',
'#^/ajax/cloud_exec\\.php$#'
);
// Rota pública dos módulos (src/Controller/SsoController.php,
// /plugins/nextool/sso/<modulo>/<acao>): só a ação `callback` é stateless (volta do
// provedor de identidade: sem cookie, sem sessão, sem CSRF). As demais ações rodam
// com sessão anônima; o firewall vem do atributo SecurityStrategy do controller.
// O padrão casa o recurso DEPOIS de /plugins/nextool (SessionManager::isResourceStateless).
\Glpi\Http\SessionManager::registerPluginStatelessPath(
'nextool',
'#^/sso/[a-z0-9_]+/callback$#'
);
}
if (class_exists('\Glpi\Http\Firewall')
&& method_exists('\Glpi\Http\Firewall', 'addPluginStrategyForLegacyScripts')) {
\Glpi\Http\Firewall::addPluginStrategyForLegacyScripts(
'nextool',
'#^/ajax/module_ajax\\.php#',
\Glpi\Http\Firewall::STRATEGY_NO_CHECK
);
\Glpi\Http\Firewall::addPluginStrategyForLegacyScripts(
'nextool',
'#^/ajax/cloud_exec\\.php#',
\Glpi\Http\Firewall::STRATEGY_NO_CHECK
);
// Assets buscados pelo browser (script/link) NAO podem cair no fallback
// AUTHENTICATED do firewall: ele responde 302 /?redirect=<asset> ao fetch
// deslogado, e plugins de SSO (ex.: samlsso) persistem esse redirect e
// despejam o usuario no asset cru apos o login (KB glpi-dev, armadilha 89).
// - nextool-tabs.(js|css).php e os wrappers *-*.js/css.php: publicos ou
// roteados ao module_assets.php, que tem guard proprio (401 sem redirect);
// - module_assets.php / module_bundle.php: exigem sessao INTERNAMENTE e
// negam em 401 seco, sem gerar redirect.
// No GLPI 10 o Apache serve front/*.php direto (sem firewall) e o guard
// interno cumpre o mesmo papel.
\Glpi\Http\Firewall::addPluginStrategyForLegacyScripts(
'nextool',
'#^/front/[\\w.-]+\\.(js|css)\\.php$#',
\Glpi\Http\Firewall::STRATEGY_NO_CHECK
);
\Glpi\Http\Firewall::addPluginStrategyForLegacyScripts(
'nextool',
'#^/front/module_(assets|bundle)\\.php#',
\Glpi\Http\Firewall::STRATEGY_NO_CHECK
);
}
} catch (\Throwable $e) {
// NUNCA crashar o GLPI - log silencioso
error_log('[NexTool] boot error: ' . $e->getMessage());
}
}
/**
* Inicialização do plugin
*/
function plugin_init_nextool() {
global $PLUGIN_HOOKS, $CFG_GLPI;
// csrf_compliant PRIMEIRO, incondicionalmente: se qualquer coisa abaixo
// lançar (ex.: Plugin::install do pending_apply falhando), o init morre -
// e sem esta flag TODO POST do plugin vira 403 "A ação que você requisitou
// não é permitida" (module_action, Sincronizar, etc.), travando o GLPI do
// cliente em loop. Incidente do portfolio em 2026-06-10 (update 4.3.0).
$PLUGIN_HOOKS['csrf_compliant']['nextool'] = true;
// Maintenance mode: apply em andamento - skip init para evitar carregar código inconsistente
if (defined('NEXTOOL_DOC_DIR')) {
$maintenanceFlag = rtrim(NEXTOOL_DOC_DIR, '/') . '/core-update/.maintenance';
if (is_file($maintenanceFlag)) {
$ts = (int)trim((string)@file_get_contents($maintenanceFlag));
if ($ts > 0 && (time() - $ts) < 300) {
$PLUGIN_HOOKS['csrf_compliant']['nextool'] = true;
return;
}
// Flag expirado (> 5 min) - remover e continuar normalmente
@unlink($maintenanceFlag);
}
}
// Apply pendente: após copy do staging para plugins/, executar Plugin::install na nova requisição.
// Fast-path via flag-file (evita SELECT em glpi_configs a cada request).
// Flag criada por PluginNextoolCoreUpdater::applyByCopyAndReload (espelhada com Config).
$pendingApplyFlag = (defined('GLPI_CACHE_DIR') && is_dir(GLPI_CACHE_DIR))
? GLPI_CACHE_DIR . '/nextool_pending_apply'
: null;
if ($pendingApplyFlag !== null && is_file($pendingApplyFlag)) {
// Um processo por vez (nextool-dev#287): a flag só some no fim, então requisições simultâneas logo
// depois do apply viam a flag e rodavam o install ao mesmo tempo -- a segunda falhava com
// "Duplicate column (1060)" no meio da migração (JMBA, 14/10/2026). Mesma trava do
// _plugin_nextool_ensure_schema(); com ela ocupada, outra requisição está migrando: não mexe na flag
// (a próxima requisição confere). Sem conseguir abrir o arquivo da trava, segue sem ela (como antes).
$pendingLock = @fopen(GLPI_CACHE_DIR . '/nextool_schema.lock', 'c');
$pendingLocked = $pendingLock !== false && flock($pendingLock, LOCK_EX | LOCK_NB);
clearstatcache(true, $pendingApplyFlag);
if (($pendingLock === false || $pendingLocked) && is_file($pendingApplyFlag)) {
// try/catch OBRIGATÓRIO: uma exceção aqui (install de módulo antigo
// incompatível, permissão de arquivo, etc.) matava o init em TODO
// request - plugin sem hooks, POSTs 403 e flag/update_available presos
// para sempre (incidente do portfolio, 2026-06-10). Em falha: remove o
// flag (sai do loop), loga o erro e segue o init - o update pode ser
// re-tentado pela UI com o GLPI utilizável.
try {
global $DB;
$plugin = new Plugin();
if ($plugin->getFromDBbyDir('nextool')) {
$plugin->install($plugin->fields['id']);
$plugin->getFromDB($plugin->fields['id']);
if ((int)($plugin->fields['state'] ?? 0) !== Plugin::ACTIVATED) {
$plugin->activate($plugin->fields['id']);
}
// BOOT-SAFE: escrita DIRETA em glpi_configs - NUNCA Config::setConfigurationValues()
// aqui. setConfigurationValues() → CommonDBTM->update → post_updateItem →
// logConfigChange → Log::constructHistory → SearchOption::getOptionsForItemtype('Config')
// → plugin_fields_getAddSearchOptions() → "Class PluginFieldsContainer not found"
// quando o plugin Fields ainda não foi carregado NESTE boot dos plugins. Essa
// exceção matava o plugin_init e - no 4.3.0, antes do csrf_compliant - virava 403
// ("A ação que você requisitou não é permitida") em TODO POST, travando o cliente
// em loop. getConfigurationValues() lê direto do DB (sem cache), então o reset é
// visto no mesmo request. Incidente portfolio 2026-06-10 (stack real:
// setup.php → Config::setConfigurationValues → fields/hook.php:178).
foreach ([
'pending_apply_version' => '',
'update_available' => '0',
'staged_target_version' => '',
'staged_source' => '',
'staged_at' => '',
] as $cfgName => $cfgValue) {
$DB->update('glpi_configs', ['value' => $cfgValue], [
'context' => 'plugin:nextool_core_update',
'name' => $cfgName,
]);
}
}
} catch (\Throwable $e) {
error_log('[NexTool] pending_apply falhou (update pode ser re-tentado pela UI): ' . $e->getMessage());
if (class_exists('Toolbox')) {
Toolbox::logInFile('plugin_nextool', '[CORE-UPDATE] pending_apply EXCEPTION: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
}
} finally {
@unlink($pendingApplyFlag);
}
}
if ($pendingLock !== false) {
if ($pendingLocked) {
flock($pendingLock, LOCK_UN);
}
fclose($pendingLock);
}
}
// Rede de segurança do schema: a flag acima é de uso único; se ela se perde ou o install
// falha, nada tentava de novo e o banco ficava sem a migração da versão nova.
_plugin_nextool_ensure_schema();
// CSS global escopado a .nextool-tab-card: oculta os controles de "pesquisa salva"
// (SavedSearch) nas grades Search::show embarcadas em abas de modulo (bugados fora de
// pagina de busca pura) e remove a 2a barra de rolagem. Nao afeta telas puras.
$PLUGIN_HOOKS['add_css']['nextool'][] = 'front/nextool-tabs.css.php';
// JS global: window.NexToolSession, guarda de sessao compartilhada pelos modulos
// com polling. Precisa vir ANTES do JS dos modulos (que o consomem com guarda).
// SEM query string no path: o GLPI 10 valida o registro com file_exists() na string
// INTEIRA -- com "?fv=" o arquivo "nao existe", vira warning em TODO request e o
// script fica FORA da pagina (fix de sessao inerte no G10; incidente paerro
// 2026-08-10). O cache-bust ja vem do core: a URL final ganha ?v=<versao dos files
// do plugin> nos 2 majors ($options['version'] em Html::script) -- bump de release
// rebusta; edicao sem bump aguarda o max-age de 1h, aceitavel em producao.
$PLUGIN_HOOKS['add_javascript']['nextool'][] = 'front/nextool-session.js.php';
// JS global: intercepta o ENTER nas abas de modulo (grades Search::show e forms de
// config) para nao recarregar a pagina. Servido via front/*.php porque o GLPI 11
// (Symfony) NAO serve .js estatico de plugin por path direto (/plugins/X/js/*.js ->
// 404) -- mesmo padrao do add_css. Ver front/nextool-tabs.js.php.
$PLUGIN_HOOKS['add_javascript']['nextool'][] = 'front/nextool-tabs.js.php';
// Ordenacao padrao das grades Search::show em abas de modulo (#275). Precisa ser
// pre_show_tab, e nao o boot: o ajax/common.tabs.php preenche sort/order com ''
// DEPOIS do init do plugin. Ver plugin_nextool_pre_show_tab() no hook.php.
$PLUGIN_HOOKS['pre_show_tab']['nextool'] = 'plugin_nextool_pre_show_tab';
try {
// Base do scan de classes declaradas DURANTE o init (ver abaixo): so as
// classes desta fatia interessam ao mapa tabela->itemtype.
$nxDeclaredBefore = count(get_declared_classes());
// Fast-path de assets: ver plugin_nextool_is_asset_request(). Definido como
// constante para os endpoints (module_bundle/module_assets) saberem que o
// onInit dos modulos NAO rodou e chamarem loadModuleLang() por conta propria.
$nxAssetFastPath = plugin_nextool_is_asset_request() && plugin_nextool_boot_fast_path_enabled();
if ($nxAssetFastPath && !defined('NEXTOOL_BOOT_FAST_PATH_ACTIVE')) {
define('NEXTOOL_BOOT_FAST_PATH_ACTIVE', true);
}
plugin_nextool_prof_start('lang');
plugin_nextool_load_base_lang();
plugin_nextool_prof_stop('lang');
$permissionfile = NEXTOOL_PHP_DIR . '/inc/permissionmanager.class.php';
if (file_exists($permissionfile)) {
require_once $permissionfile;
}
// Define a página de configuração do plugin (engrenagem na lista Configurar → Plugins)
$PLUGIN_HOOKS['config_page']['nextool'] = 'front/nextoolconfig.form.php?id=1&forcetab=PluginNextoolMainConfig$1';
// Habilita ações em massa (MassiveActions) para que o GLPI consulte:
// - plugin_nextool_MassiveActions()
// - plugin_nextool_MassiveActionsFieldsDisplay()
// (ex.: módulos com MassiveActions na listagem Search)
if (Session::getLoginUserID()) {
$PLUGIN_HOOKS['use_massive_action']['nextool'] = 1;
}
// F1a -- a identidade (client_identifier) NÃO é mais gerada localmente: é cunhada pelo
// ContainerAPI via enroll no provisionamento ativo (front/config.save.php). Esta chamada
// apenas garante o registro base de config e carrega a configuração; getConfig() não gera
// mais identificador (installs novos ficam sem identidade até enrollar).
$configfile = NEXTOOL_PHP_DIR . '/inc/config.class.php';
if (file_exists($configfile)) {
require_once $configfile;
if (class_exists('PluginNextoolConfig')) {
try {
if (!$nxAssetFastPath) {
plugin_nextool_prof_start('getConfig');
PluginNextoolConfig::getConfig();
plugin_nextool_prof_stop('getConfig');
}
} catch (Exception $e) {
Toolbox::logInFile('plugin_nextool', "Erro ao inicializar client_identifier: " . $e->getMessage());
}
}
}
// Classe de setup mantida para uso interno; abas em Configurar → Geral foram removidas
$setupfile = NEXTOOL_PHP_DIR . '/inc/setup.class.php';
if (file_exists($setupfile)) {
require_once $setupfile;
}
// Classe de configuração standalone (página com abas verticais nativas)
$mainconfigfile = NEXTOOL_PHP_DIR . '/inc/nextoolmainconfig.class.php';
if (file_exists($mainconfigfile)) {
require_once $mainconfigfile;
// (registerClass sem atributos removido na 6.13.0: e no-op no core e custa
// um preg_grep sobre todas as chaves de $CFG_GLPI por chamada -- #249)
}
// Log unificado da base (aba Logs): pin tabela<->itemtype para o Search::show, que não deduz
// a classe de uma tabela com nome fora da convenção (`main_logs` != `eventlogs`).
$eventLogFile = NEXTOOL_PHP_DIR . '/inc/eventlog.class.php';
if (file_exists($eventLogFile)) {
require_once $eventLogFile;
$CFG_GLPI['glpiitemtypetables']['glpi_plugin_nextool_main_logs'] = 'PluginNextoolEventLog';
$CFG_GLPI['glpitablesitemtype']['PluginNextoolEventLog'] = 'glpi_plugin_nextool_main_logs';
// ensureDisplayPreferences() saiu daqui (1 SELECT em TODO request para um
// estado que so muda no install): roda junto com o sync de rights, sob o
// file-flag versionado nextool_rights_synced_v* (A5, #249).
}
$profilefile = NEXTOOL_PHP_DIR . '/inc/profile.class.php';
if (file_exists($profilefile)) {
require_once $profilefile;
// Equivalente exato de Plugin::registerClass(..., ['addtabon' => ['Profile']])
// sem o preg_grep das chaves de $CFG_GLPI (#249).
CommonGLPI::registerStandardTab('Profile', 'PluginNextoolProfile');
}
// Carrega ModuleManager e inicializa módulos ativos
// Verifica se tabela de módulos existe (plugin já instalado)
$managerfile = NEXTOOL_PHP_DIR . '/inc/modulemanager.class.php';
$basefile = NEXTOOL_PHP_DIR . '/inc/basemodule.class.php';
if (file_exists($managerfile) && file_exists($basefile)) {
global $DB;
$hookdispatcherfile = NEXTOOL_PHP_DIR . '/inc/hookdispatcher.class.php';
if (file_exists($hookdispatcherfile)) {
require_once $hookdispatcherfile;
// Fonte de notificação da PRÓPRIA BASE: os avisos da NexTool (aba Novidades)
// também são publicados no canal e entregues POR USUÁRIO no sino do módulo
// de notificações, para quem enxerga as abas admin da base. A audiência é
// 'base_admins', resolvida pelo consumidor na LEITURA (a base não é módulo
// instalável -- não existe direito plugin_nextool_module_nextool para
// required_bit; o sink trata este emissor como caso próprio).
if (class_exists('PluginNextoolHookDispatcher')
&& method_exists('PluginNextoolHookDispatcher', 'registerNotificationSource')) {
PluginNextoolHookDispatcher::registerNotificationSource('nextool.server_alert', [
// rotulos lazy: traduzidos so no consumidor, nao em todo boot (#249)
'label' => ['Avisos da NexTool', 'nextool'],
'description' => ['Comunicados oficiais recebidos do servidor NexTool (os mesmos da aba Novidades).', 'nextool'],
'icon' => 'ti ti-bell-ringing',
'color' => 'purple',
'severity' => 'info',
]);
// Vigia das rotinas: avisos obrigatórios de rotina/ação automática parada.
$watchdogFile = NEXTOOL_PHP_DIR . '/inc/jobwatchdog.class.php';
if (file_exists($watchdogFile)) {
require_once $watchdogFile;
PluginNextoolJobWatchdog::registerSources();
}
}
}
// Só carrega módulos se plugin já foi instalado
if ($DB->tableExists('glpi_plugin_nextool_main_modules')) {
try {
require_once $basefile;
require_once $managerfile;
$manager = PluginNextoolModuleManager::getInstance();
if ($nxAssetFastPath) {
// Request de asset: nada abaixo e necessario (ver
// plugin_nextool_is_asset_request). A descoberta fica lazy: os
// endpoints chamam getModule() so para o(s) modulo(s) servido(s).
plugin_nextool_prof_start('asset_fast_path');
plugin_nextool_prof_stop('asset_fast_path');
return;
}
plugin_nextool_prof_start('loadActiveModules');
$manager->loadActiveModules();
plugin_nextool_prof_stop('loadActiveModules');
// Menu da sessao vs conjunto de modulos ATIVOS. O core cacheia o menu em
// $_SESSION['glpimenu'] e so regenera em sessao nova; ao (des)ativar um
// modulo, ModuleManager::invalidateSessionMenu() cura a sessao de quem
// clicou, mas as DEMAIS sessoes ficariam com o item fantasma ate relogar.
// Assinatura do conjunto ativo por sessao: mudou -> descarta o menu (o
// core o remonta nesta mesma request, ja sem/com o modulo). Custo: um
// md5 de ~35 chaves; sem login e no-op.
if (isset($_SESSION['glpiactiveprofile']['id'])) {
$nxMenuSig = md5(implode(',', array_keys($manager->getActiveModules())));
if (($_SESSION['nextool_menu_sig'] ?? '') !== $nxMenuSig) {
PluginNextoolModuleManager::invalidateSessionMenu();
$_SESSION['nextool_menu_sig'] = $nxMenuSig;
}
}
// Bundle de assets: colapsa os N registros de module_assets.php
// feitos pelos onInit acima em 1 URL por tipo (css/js) - reduz
// ~16-27 requests com bootstrap completo por page load para 2.
// Entradas com &nobundle=1 e assets fora do module_assets ficam
// intactos. Ver inc/assetbundler.class.php.
$bundlerFile = NEXTOOL_PHP_DIR . '/inc/assetbundler.class.php';
if (file_exists($bundlerFile)) {
require_once $bundlerFile;
plugin_nextool_prof_start('bundler');
PluginNextoolAssetBundler::collapseHooks();
plugin_nextool_prof_stop('bundler');
}
// Pina o mapeamento reverso tabela->itemtype dos tipos CORE que
// classes de tab do ecossistema "emprestam" via getTable() (padrão
// KB #26: PluginNextoolProfile e ProfileTab de módulos retornam
// glpi_profiles). Se getTableForItemType() resolve a classe do
// plugin ANTES do core, DbUtils grava glpiitemtypetables
// [glpi_profiles] = PluginNextool... e o Search da lista de perfis
// monta os links das células para /plugins/nextool/front/
// profile.form.php - clicar num perfil cai no central (bug
// 2026-06-10). A pinagem garante o itemtype canônico.
$CFG_GLPI['glpiitemtypetables']['glpi_profiles'] = 'Profile';
$CFG_GLPI['glpitablesitemtype']['Profile'] = 'glpi_profiles';
$hookfile = NEXTOOL_PHP_DIR . '/hook.php';
if (file_exists($hookfile)) {
plugin_nextool_prof_start('hook_include');
require_once $hookfile;
plugin_nextool_prof_stop('hook_include');
}
// Registra classes necessárias para Search/MassiveActions via providers dos módulos ativos
$dispatcherFile = NEXTOOL_PHP_DIR . '/inc/hookprovidersdispatcher.class.php';
if (file_exists($dispatcherFile)) {
require_once $dispatcherFile;
if (class_exists('PluginNextoolHookProvidersDispatcher')) {
plugin_nextool_prof_start('providers');
PluginNextoolHookProvidersDispatcher::registerClasses();
plugin_nextool_prof_stop('providers');
}
}
// HI-07: sync de rights apenas quando a versão muda (file-flag versionada).
// Antes: 31+ queries em glpi_profilerights em todo init universal.
// Agora: zero queries quando flag da versão atual existe.
// Eventos que mudam permissões (install, upgrade, mudança de catálogo,
// criação de perfil) continuam chamando syncModuleRights diretamente.
plugin_nextool_prof_start('rights');
$rightsSyncFlag = (defined('GLPI_CACHE_DIR') && is_dir(GLPI_CACHE_DIR))
? GLPI_CACHE_DIR . '/nextool_rights_synced_v' . PLUGIN_NEXTOOL_VERSION
: null;
if ($rightsSyncFlag === null || !is_file($rightsSyncFlag)) {
// Preferencias de exibicao da grade de logs: so mudam no install;
// sincronizadas 1x por versao junto com os rights.
if (class_exists('PluginNextoolEventLog')) {
PluginNextoolEventLog::ensureDisplayPreferences();
}
PluginNextoolPermissionManager::syncModuleRights();
if ($rightsSyncFlag !== null) {
// Remove flags de versões anteriores antes de marcar a atual
foreach (glob(GLPI_CACHE_DIR . '/nextool_rights_synced_v*') ?: [] as $oldFlag) {
if ($oldFlag !== $rightsSyncFlag) {
@unlink($oldFlag);
}
}
@touch($rightsSyncFlag);
}
}
// Sessao stale: o file-flag acima ressincroniza o BANCO quando a versao muda, mas a
// sessao web carregada ANTES de um update (ex.: self-update, que nao passa por
// plugin_nextool_install na sessao ativa do usuario) nao recebe os direitos novos --
// e o gate da interface central le da SESSAO (Session::haveRight), nao do banco. Sem
// isto, o super-direito so passaria a valer apos deslogar/relogar. Recarrega os
// direitos 'nextool*'/'plugin_nextool*' do perfil ativo 1x por sessao por versao
// (1 query; no-op quando nao ha login).
if (isset($_SESSION['glpiactiveprofile']['id'])
&& (($_SESSION['nextool_session_rights_v'] ?? null) !== PLUGIN_NEXTOOL_VERSION)) {
PluginNextoolPermissionManager::reloadActiveProfileRights();
$_SESSION['nextool_session_rights_v'] = PLUGIN_NEXTOOL_VERSION;
}
plugin_nextool_prof_stop('rights');
// Pré-requisitos que exigem humano (nextool-dev#260): base desatualizada
// bloqueando módulos, extensão PHP ausente, diretório sem escrita -> alerta
// local (aba Novidades + sino). 1x/h real por file-flag em GLPI_CACHE_DIR
// (regime: 1 is_file + 1 filemtime, zero query); nunca derruba o boot.
plugin_nextool_prof_start('prereq');
$prereqFile = NEXTOOL_PHP_DIR . '/inc/prereqcheck.class.php';
if (file_exists($prereqFile)) {
require_once $prereqFile;
if (class_exists('PluginNextoolPrereqCheck')) {
try {
PluginNextoolPrereqCheck::run('boot');
} catch (Throwable $e) {
Toolbox::logInFile('plugin_nextool', 'PrereqCheck (boot): ' . $e->getMessage());
}
}
}
plugin_nextool_prof_stop('prereq');
// O loop que registrava as classes Config/PageConfig de todos os modulos
// instalados (inclusive desativados) foi removido na 6.13.0 (#249): o
// class_exists() dele AUTOCARREGAVA ~50 classes de config por request, o
// probe de PageConfig falhava 42x pela cadeia de autoloaders, e o
// Plugin::registerClass() sem atributos e no-op. common.tabs.php resolve
// PluginNextool<Mk>Config / PageConfig pelo autoloader central
// (inc/modulespath.inc.php) sob demanda.
// Mapeamento reverso tabela->itemtype para classes searchable de módulo já
// carregadas (pelos onInit via require_once, que "furam" o autoloader do NexTool).
// getItemTypeForTable() não resolve tabelas custom (ex: ..._log) -> retorna null e o
// Search estoura getItemForItemtype(null) ao renderizar a grade. O autoloader mapeia
// as classes que ELE carrega; este scan cobre as pré-carregadas pelos onInit.
plugin_nextool_prof_start('classScan');
// Cada classe isolada: um getTable() que lanca (classe abstrata/base sem
// tabela, modulo com bug) NAO pode derrubar o resto do init -- este loop
// fica DENTRO do try do boot, e a excecao pulava a instalacao de todos os
// hooks do dispatcher em silencio (2026-09-07: aprovacao do workflow parou
// no CLI/cron enquanto a web seguia normal pelo OPcache).
foreach (array_slice(get_declared_classes(), $nxDeclaredBefore) as $ntClass) {
if (strncmp($ntClass, 'PluginNextool', 13) === 0 && is_subclass_of($ntClass, 'CommonDBTM')) {
try {
if ((new ReflectionClass($ntClass))->isAbstract()) {
continue;
}
$ntTable = $ntClass::getTable();
} catch (\Throwable $ntErr) {
continue;
}
// Só tabela do NexTool: subclasse de itemtype do core (ex.: de Rule, que
// devolve glpi_rules) não pode virar a dona da tabela do core.
if (plugin_nextool_is_own_table($ntTable) && !isset($CFG_GLPI['glpiitemtypetables'][$ntTable])) {
$CFG_GLPI['glpiitemtypetables'][$ntTable] = $ntClass;
}
}
}
plugin_nextool_prof_stop('classScan');
plugin_nextool_prof_start('dispatch_menus');
// Menu "Nextools" (nativo) + menus de módulos via redefine_menus
$PLUGIN_HOOKS['redefine_menus']['nextool'] = 'plugin_nextool_redefine_menus';
// Dispatcher central: registrado DEPOIS do loadActiveModules, com ocupação
// APPEND-AWARE (installHook). Módulo NOVO registra no registry (register*)
// e é despachado pelo dispatcher; módulo ANTIGO que atribuiu callback
// direto no slot durante o onInit() é ENCADEADO (dispatcher + legado),
// nunca sobrescrito -- retrocompat na janela base-nova + módulo-velho
// (regressão real de 2026-07-23: subtaskflow E2E 8 FAIL por clobber).
if (class_exists('PluginNextoolHookDispatcher')) {
$nxInstall = ['PluginNextoolHookDispatcher', 'installHook'];
$nxInstall($PLUGIN_HOOKS, 'pre_item_add', 'Ticket', 'dispatchPreItemAddTicket');
$nxInstall($PLUGIN_HOOKS, 'item_add', 'Ticket', 'dispatchItemAddTicket');
$nxInstall($PLUGIN_HOOKS, 'item_update', 'Ticket', 'dispatchItemUpdateTicket');
// pre_item_update: módulos podem BLOQUEAR a atualização antes da gravação
// (abort via input=[] + mensagem; ver PluginNextoolValidationException).
$nxInstall($PLUGIN_HOOKS, 'pre_item_update', 'Ticket', 'dispatchPreItemUpdateTicket');
// Sub-itens de chamado (bloqueio na criação/edição): tarefa, acompanhamento,
// solução. Habilita módulos a exigir mínimos/obrigatoriedades (ex.: ticketrules).
$nxInstall($PLUGIN_HOOKS, 'pre_item_add', 'TicketTask', 'dispatchPreItemAddTicketTask');
$nxInstall($PLUGIN_HOOKS, 'pre_item_update', 'TicketTask', 'dispatchPreItemUpdateTicketTask');
$nxInstall($PLUGIN_HOOKS, 'pre_item_add', 'ITILFollowup', 'dispatchPreItemAddITILFollowup');
$nxInstall($PLUGIN_HOOKS, 'pre_item_update', 'ITILFollowup', 'dispatchPreItemUpdateITILFollowup');
$nxInstall($PLUGIN_HOOKS, 'pre_item_add', 'ITILSolution', 'dispatchPreItemAddITILSolution');
$nxInstall($PLUGIN_HOOKS, 'item_add', 'TicketValidation', 'dispatchItemAddTicketValidation');
$nxInstall($PLUGIN_HOOKS, 'item_add', 'TicketTask', 'dispatchItemAddTicketTask');
$nxInstall($PLUGIN_HOOKS, 'item_update', 'TicketValidation', 'dispatchItemUpdateTicketValidation');
$nxInstall($PLUGIN_HOOKS, 'item_update', 'TicketTask', 'dispatchItemUpdateTicketTask');
// item_purge: pós-exclusão definitiva de sub-item. Módulos que mantêm
// dados atrelados (ex.: contracthours timer<->TicketTask) limpam aqui.
$nxInstall($PLUGIN_HOOKS, 'item_purge', 'TicketTask', 'dispatchItemPurgeTicketTask');
$nxInstall($PLUGIN_HOOKS, 'item_add', 'ITILFollowup', 'dispatchItemAddITILFollowup');
$nxInstall($PLUGIN_HOOKS, 'item_add', 'ITILSolution', 'dispatchItemAddITILSolution');
// Categorias ITIL (AI Assist gerenciado, fase 4): palavras-chave gravadas junto com o formulário nativo.
$nxInstall($PLUGIN_HOOKS, 'item_add', 'ITILCategory', 'dispatchItemAddITILCategory');
$nxInstall($PLUGIN_HOOKS, 'item_update', 'ITILCategory', 'dispatchItemUpdateITILCategory');
$nxInstall($PLUGIN_HOOKS, 'item_purge', 'ITILCategory', 'dispatchItemPurgeITILCategory');
// KnowbaseItem (6.14.0): módulos com dados atrelados a artigos da KB
// (aiassist: palavras-chave) limpam no purge. Sem lixeira no itemtype,
// o core dispara só o item_purge; item_delete fica por completude.
$nxInstall($PLUGIN_HOOKS, 'item_purge', 'KnowbaseItem', 'dispatchItemPurgeKnowbaseItem');
$nxInstall($PLUGIN_HOOKS, 'item_delete', 'KnowbaseItem', 'dispatchItemDeleteKnowbaseItem');
// post_show_item: timeline separator e outros hooks visuais.
// Nota: nao pode usar HookManager para este hook (limitacao do core GLPI 11).
$nxInstall($PLUGIN_HOOKS, 'post_show_item', null, 'dispatchPostShowItemHook');
// post_item_form: modificação de formulários nativos por módulos
// (registrados via HookDispatcher::registerPostItemForm no onInit).
$nxInstall($PLUGIN_HOOKS, 'post_item_form', null, 'dispatchPostItemFormHook');
// pre_itil_info_section (GLPI 11): topo do painel lateral do chamado, antes da
// seção de campos (registrados via HookDispatcher::registerPreItilInfoSection).
$nxInstall($PLUGIN_HOOKS, 'pre_itil_info_section', null, 'dispatchPreItilInfoSectionHook');
// timeline_answer_actions: ações na barra da timeline do chamado
// (registradas via HookDispatcher::registerTimelineActions no onInit).
// Instalador PRÓPRIO, e não $nxInstall: este hook devolve a LISTA DE
// AÇÕES, então o callback de módulo antigo é MESCLADO (mesmo payload),
// nunca encadeado -- ver installTimelineActionsHook().
PluginNextoolHookDispatcher::installTimelineActionsHook($PLUGIN_HOOKS);
// timeline_items (GLPI 11) / show_in_timeline (GLPI 10): itens próprios dos
// módulos na timeline do chamado (registrados via registerTimelineItems no
// onInit). Só ocupa o slot se algum módulo registrou -- ver installTimelineItemsHook().
PluginNextoolHookDispatcher::installTimelineItemsHook($PLUGIN_HOOKS);
// display_login: vários módulos na tela de login (registrados via
// registerDisplayLogin no onInit; branding 10 = CSS/JS, botões de SSO 100).
// Só ocupa o slot se algum módulo registrou -- ver installDisplayLoginHook().
PluginNextoolHookDispatcher::installDisplayLoginHook($PLUGIN_HOOKS);
// item_get_events / item_add_targets / item_action_targets / item_get_datas:
// eventos de notificação próprios dos módulos num alvo do core (registrados via
// registerNotificationProvider no onInit). Só ocupa as classes com provider.
PluginNextoolHookDispatcher::installNotificationHooks($PLUGIN_HOOKS);
}
// Registra menus de módulos ativos via getMenuRegistration()
foreach ($manager->getActiveModules() as $moduleKey => $module) {
if (method_exists($module, 'getMenuRegistration')) {
$reg = $module->getMenuRegistration();
if (is_array($reg) && !empty($reg['key']) && !empty($reg['class'])) {
// Se o módulo declarou class_file, carrega e registra a classe
if (!empty($reg['class_file'])) {
$classFile = NEXTOOL_MODULES_BASE . '/' . $moduleKey . '/' . $reg['class_file'];
if (file_exists($classFile)) {
require_once $classFile;
// registerClass sem atributos removido (no-op, #249)
}
}
// Registra no hook menu_toadd (exceto módulos que usam redefine_menus).
// Acumula em array por seção: vários módulos podem registrar na mesma
// seção (ex.: 'management' - digitalsignature + autentique). O core
// (Html.php) aceita array de classes por seção do menu_toadd.
// A secao 'nextools' e remontada pelo redefine_menus (hook.php), que usa o
// getMenuContent() da classe direto; via menu_toadd o item seria descartado.
if (empty($reg['uses_redefine_menus']) && $reg['key'] !== 'nextools') {
if (!isset($PLUGIN_HOOKS['menu_toadd']['nextool'])) {
$PLUGIN_HOOKS['menu_toadd']['nextool'] = [];
}
$existing = $PLUGIN_HOOKS['menu_toadd']['nextool'][$reg['key']] ?? [];
if (!is_array($existing)) {
$existing = [$existing];
}
if (!in_array($reg['class'], $existing, true)) {
$existing[] = $reg['class'];
}
$PLUGIN_HOOKS['menu_toadd']['nextool'][$reg['key']] = $existing;
}
}
}
}
plugin_nextool_prof_stop('dispatch_menus');
// Vigia das rotinas pela web (cron do servidor parado não roda o vigia). Depois dos
// módulos: o sino (sink) já está registrado. Um stat por request; checagem a cada 10 min.
if (!$nxAssetFastPath && class_exists('PluginNextoolJobWatchdog')) {
PluginNextoolJobWatchdog::maybeRunFromWeb();
}
} catch (Exception $e) {
Toolbox::logInFile('plugin_nextool', "Erro ao carregar módulos: " . $e->getMessage());
}
}
}
} catch (\Throwable $e) {
error_log('[NexTool] init error: ' . $e->getMessage());
// Plugin não carrega seus recursos, mas GLPI continua operando
}
}
/**
* Verifica pré-requisitos antes da instalação (GLPI/PHP).
* Mensagens incompatíveis via Plugin::messageIncompatible quando disponível.
*/
function plugin_nextool_check_prerequisites() {
if (version_compare(GLPI_VERSION, PLUGIN_NEXTOOL_MIN_GLPI_VERSION, 'lt')) {
if (method_exists('Plugin', 'messageIncompatible')) {
Plugin::messageIncompatible('core', PLUGIN_NEXTOOL_MIN_GLPI_VERSION, PLUGIN_NEXTOOL_MAX_GLPI_VERSION);
} else {
echo "Este plugin requer GLPI >= " . PLUGIN_NEXTOOL_MIN_GLPI_VERSION;
}
return false;
}
if (version_compare(GLPI_VERSION, PLUGIN_NEXTOOL_MAX_GLPI_VERSION, 'gt')) {
if (method_exists('Plugin', 'messageIncompatible')) {
Plugin::messageIncompatible('core', PLUGIN_NEXTOOL_MIN_GLPI_VERSION, PLUGIN_NEXTOOL_MAX_GLPI_VERSION);
} else {
echo "Este plugin suporta GLPI até " . PLUGIN_NEXTOOL_MAX_GLPI_VERSION;
}
return false;
}
return true;
}
/**
* Verifica configuração
*/
function plugin_nextool_check_config() {
return true;
}
/**
* Contexto em glpi_configs do marcador de schema: `version` (versão cuja migração concluiu),
* `last_attempt` (timestamp da última tentativa da rede) e `last_error`.
*/
define('PLUGIN_NEXTOOL_SCHEMA_CONTEXT', 'plugin:nextool_schema');
/** Intervalo mínimo entre duas tentativas da rede de segurança do schema (s). */
define('PLUGIN_NEXTOOL_SCHEMA_RETRY_SECONDS', 900);
/**
* Lê o marcador de schema direto do banco.
*
* BOOT-SAFE: nada de Config::getConfigurationValues/setConfigurationValues aqui (ver o bloco
* pending_apply em plugin_init_nextool: o Config no boot já derrubou o init de cliente).
*/
function _plugin_nextool_schema_get(): array {
global $DB;
$values = [];
foreach ($DB->request([
'SELECT' => ['name', 'value'],
'FROM' => 'glpi_configs',
'WHERE' => ['context' => PLUGIN_NEXTOOL_SCHEMA_CONTEXT],
]) as $row) {
$values[(string) $row['name']] = (string) $row['value'];
}
return $values;
}
/** Grava uma chave do marcador de schema direto no banco (boot-safe, ver _plugin_nextool_schema_get). */
function _plugin_nextool_schema_set(string $name, string $value): void {
global $DB;
// GLPI 10 não escapa no insert/update: o valor fica restrito a um conjunto sem aspas nem barra.
$value = mb_substr((string) preg_replace('/[^\p{L}\p{N}\s.,:;()\/_#=<>+-]/u', ' ', $value), 0, 250);
$where = ['context' => PLUGIN_NEXTOOL_SCHEMA_CONTEXT, 'name' => $name];
$exists = count($DB->request(['SELECT' => ['id'], 'FROM' => 'glpi_configs', 'WHERE' => $where, 'LIMIT' => 1])) > 0;
if ($exists) {
$DB->update('glpi_configs', ['value' => $value], $where);
} else {
$DB->insert('glpi_configs', $where + ['value' => $value]);
}
}
/**
* Marca o schema da versão atual como migrado. Chamado por plugin_nextool_install() logo após a
* Migration, então install pela UI, pela CLI, pelo pending_apply ou pela própria rede marcam igual.
*/
function _plugin_nextool_schema_mark(): void {
_plugin_nextool_schema_set('version', PLUGIN_NEXTOOL_VERSION);
_plugin_nextool_schema_set('last_error', '');
}
/**
* Rede de segurança do schema da base (cliente IRSSL, 2026-10-05).
*
* O update pelo botão grava a versão nova e o estado ATIVO direto em glpi_plugins e deixa a
* migração para a flag de uso único `nextool_pending_apply`. Se a flag se perde (cache limpo,
* escrita falhou) ou o install lança, a flag é apagada mesmo assim e nada tentava de novo: com a
* versão do banco igual à dos arquivos, o GLPI nem oferece "atualizar". O cliente ficou com a
* 6.31.0 sem a coluna `name_i18n` e toda validação de licença morria em 1054.
*
* Aqui o boot compara o marcador gravado pelo install com a versão dos arquivos e, se divergir,
* roda o install de novo (idempotente). Caminho rápido por arquivo no cache (sem SELECT por
* request); no máximo uma tentativa a cada PLUGIN_NEXTOOL_SCHEMA_RETRY_SECONDS, com o erro gravado
* em `last_error`; flock evita dois requests migrando juntos. Nunca lança.
*/
function _plugin_nextool_ensure_schema(): void {
global $DB;
$cacheDir = (defined('GLPI_CACHE_DIR') && is_dir(GLPI_CACHE_DIR)) ? GLPI_CACHE_DIR : null;
$okFlag = $cacheDir !== null ? $cacheDir . '/nextool_schema_ok_' . PLUGIN_NEXTOOL_VERSION : null;
if ($okFlag !== null && is_file($okFlag)) {
return;
}
$lock = null;
try {
$state = _plugin_nextool_schema_get();
if (($state['version'] ?? '') === PLUGIN_NEXTOOL_VERSION) {
if ($okFlag !== null) {
@touch($okFlag);
}
return;
}
$lastAttempt = (int) ($state['last_attempt'] ?? 0);
if ($lastAttempt > 0 && (time() - $lastAttempt) < PLUGIN_NEXTOOL_SCHEMA_RETRY_SECONDS) {
return;
}
if ($cacheDir !== null) {
$lock = @fopen($cacheDir . '/nextool_schema.lock', 'c');
if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) {
$lock = $lock === false ? null : $lock;
return; // outro request já está migrando
}
}
_plugin_nextool_schema_set('last_attempt', (string) time());
$from = (string) ($state['version'] ?? '');
Toolbox::logInFile('plugin_nextool', sprintf(
"[SCHEMA] marcador=%s, arquivos=%s: rodando a migração da base\n",
$from !== '' ? $from : 'ausente',
PLUGIN_NEXTOOL_VERSION
));
// Direto no install (o que o plugin_nextool_upgrade faz), não no Plugin::install: este
// derruba o estado para NOTACTIVATED e deixa "Plugin instalado! Deseja ativá-lo?" na tela de
// quem disparou o request, que pode ser um usuário do self-service. O buffer engole o eco da
// Migration ("Tarefa concluída"), que sairia no meio do HTML ou de uma resposta JSON.
if (!function_exists('plugin_nextool_install')) {
require_once __DIR__ . '/hook.php';
}
if (method_exists($DB, 'disableTableCaching')) {
$DB->disableTableCaching(); // fieldExists em cache esconderia a coluna que falta
}
ob_start();
try {
plugin_nextool_install();
} finally {
ob_end_clean();
}
$after = _plugin_nextool_schema_get();
if (($after['version'] ?? '') === PLUGIN_NEXTOOL_VERSION) {
Toolbox::logInFile('plugin_nextool', "[SCHEMA] migração da base concluída\n");
if ($okFlag !== null) {
@touch($okFlag);
}
} else {
_plugin_nextool_schema_set('last_error', 'install terminou sem marcar o schema');
Toolbox::logInFile('plugin_nextool', "[SCHEMA] install terminou sem marcar o schema\n");
}
} catch (\Throwable $e) {
error_log('[NexTool] migração de schema falhou (nova tentativa em 15 min): ' . $e->getMessage());
try {
_plugin_nextool_schema_set('last_error', $e->getMessage());
Toolbox::logInFile('plugin_nextool', '[SCHEMA] migração falhou: ' . $e->getMessage() . "\n" . $e->getTraceAsString() . "\n");
} catch (\Throwable $ignored) {
// banco indisponível: o error_log acima já registrou
}
} finally {
if ($lock !== null) {
flock($lock, LOCK_UN);
fclose($lock);
}
}