This repository has been archived by the owner on Aug 9, 2021. It is now read-only.
/
agent.class.php
1837 lines (1612 loc) · 60.7 KB
/
agent.class.php
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
/**
* LICENSE
*
* Copyright © 2016-2018 Teclib'
* Copyright © 2010-2018 by the FusionInventory Development Team.
*
* This file is part of Flyve MDM Plugin for GLPI.
*
* Flyve MDM Plugin for GLPI is a subproject of Flyve MDM. Flyve MDM is a mobile
* device management software.
*
* Flyve MDM Plugin for GLPI is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* Flyve MDM Plugin for GLPI is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with Flyve MDM Plugin for GLPI. If not, see http://www.gnu.org/licenses/.
* ------------------------------------------------------------------------------
* @author Thierry Bugier
* @copyright Copyright © 2018 Teclib
* @license AGPLv3+ http://www.gnu.org/licenses/agpl.txt
* @link https://github.com/flyve-mdm/glpi-plugin
* @link https://flyve-mdm.com/
* ------------------------------------------------------------------------------
*/
if (!defined('GLPI_ROOT')) {
die("Sorry. You can't access this file directly");
}
/**
* @since 0.1.0
*/
class PluginFlyvemdmAgent extends CommonDBTM implements PluginFlyvemdmNotifiable {
const ENROLL_DENY = 0;
const ENROLL_INVITATION_TOKEN = 1;
const ENROLL_ENTITY_TOKEN = 2;
const DEFAULT_TOKEN_LIFETIME = "P7D";
/**
* @var string $rightname name of the right in DB
*/
public static $rightname = 'flyvemdm:agent';
/**
* @var bool $dohistory maintain history
*/
public $dohistory = true;
/**
* @var bool $usenotepad enable notepad for the itemtype (GLPi < 0.85)
*/
protected $usenotepad = true;
/**
* @var bool $usenotepad enable notepad for the itemtype (GLPi >=0.85)
*/
protected $usenotepadRights = true;
protected $topic = null;
/**
*
* Returns the minimum version of the agent accepted by the backend
*
* @param string $mdmType the type of the agent.
*
* @return string the minimum version of the agent depending on its type
*/
private function getMinVersioForType($mdmType) {
switch ($mdmType) {
case 'android':
return '2.0';
break;
case 'apple':
return '1.0';
break;
}
return '';
}
/**
* get mdm types availables
*/
public static function getEnumMdmType() {
return [
'android' => __("Android", 'flyvemdm'),
'apple' => __("Apple", 'flyvemdm'),
];
}
/**
* Localized name of the type
* @param integer $nb number of item in the type (default 0)
* @return string
*/
public static function getTypeName($nb = 0) {
return _n('Agent', 'Agents', $nb, 'flyvemdm');
}
/**
* Return the picture file for the menu
* @return string
*/
public static function getMenuPicture() {
return 'fa-tablet';
}
/**
* @since version 0.1.0
* @see commonDBTM::getRights()
*/
public function getRights($interface = 'central') {
$rights = parent::getRights();
/// For additional rights if needed
//$rights[self::RIGHTS] = self::getTypeName();
return $rights;
}
/**
* Define tabs available for this itemtype
*/
public function defineTabs($options = []) {
$tab = [];
$this->addDefaultFormTab($tab);
$this->addStandardTab(PluginFlyvemdmGeolocation::class, $tab, $options);
$this->addStandardTab(__CLASS__, $tab, $options);
$this->addStandardTab(Notepad::class, $tab, $options);
$this->addStandardTab(Log::class, $tab, $options);
return $tab;
}
/**
* @see CommonGLPI::getTabNameForItem()
*
* @since version 9.1
* @param CommonGLPI $item
* @param integer $withtemplate
* @return array|string
*/
function getTabNameForItem(CommonGLPI $item, $withtemplate = 0) {
if (static::canView()) {
switch ($item->getType()) {
case __CLASS__ :
$tab = [1 => __('Danger zone !', 'flyvemdm')];
return $tab;
break;
case PluginFlyvemdmFleet::class:
if (!$withtemplate) {
$nb = 0;
$fleetId = $item->getID();
$pluralNumber = Session::getPluralNumber();
if ($_SESSION['glpishow_count_on_tabs']) {
$nb = countElementsInTable(static::getTable(), ['plugin_flyvemdm_fleets_id' => $fleetId]);
}
return self::createTabEntry(self::getTypeName($pluralNumber), $nb);
}
break;
case Computer::class:
return __('Flyve MDM Agent', 'flyvemdm');
break;
}
}
}
/**
* @param CommonGLPI $item
* @param integer $tabnum (default 1)
* @param integer $withtemplate (default 0)
*
* @since version 9.1
*
* @return bool
*/
static function displayTabContentForItem(CommonGLPI $item, $tabnum = 1, $withtemplate = 0) {
switch (get_class($item)) {
case static::class:
self::showDangerZone($item);
return true;
break;
case PluginFlyvemdmFleet::class:
self::showForFleet($item);
return true;
break;
}
}
/**
* Show form for edition
* @param integer $ID
* @param array $options
*/
public function showForm($ID, array $options = []) {
$this->initForm($ID, $options);
$this->showFormHeader($options);
$canUpdate = (!$this->isNewID($ID)) && ($this->canUpdate() > 0);
$fields = $this->fields;
$objectName = autoName($this->fields["name"], "name",
(isset($options['withtemplate']) && $options['withtemplate'] == 2),
$this->getType(), -1);
$fields['name'] = Html::autocompletionTextField($this, 'name',
['value' => $objectName, 'display' => false]);
$fields['computer'] = Computer::dropdown([
'display' => false,
'name' => 'computers_id',
'value' => $this->fields['computers_id'],
'entity' => $this->fields['entities_id']
]);
$fields['fleet'] = PluginFlyvemdmFleet::dropdown([
'display' => false,
'name' => 'plugin_flyvemdm_fleets_id',
'value' => $this->fields['plugin_flyvemdm_fleets_id'],
'entity' => $this->fields['entities_id']
]);
if (empty($fields['last_contact'])) {
$fields['last_contact'] = __('Never seen online', 'flyvemdm');
}
$data = [
'withTemplate' => (isset($options['withtemplate']) && $options['withtemplate'] ? '*' : ''),
'isNewID' => $this->isNewID($ID),
'canUpdate' => $canUpdate,
'agent' => $fields,
'pingButton' => Html::submit(_x('button', 'Ping'), ['name' => 'ping']),
'geolocateButton' => Html::submit(_x('button', 'Geolocate'), ['name' => 'geolocate']),
'inventoryButton' => Html::submit(_x('button', 'Inventory'), ['name' => 'inventory']),
];
$twig = plugin_flyvemdm_getTemplateEngine();
echo $twig->render('agent.html', $data);
$this->showFormButtons($options);
}
/**
* Print the computer's operating system form
*
* @param PluginFlyvemdmAgent $item
*
* @since version 9.1
*/
public static function showDangerZone(PluginFlyvemdmAgent $item) {
$ID = $item->fields['id'];
$item->initForm($ID);
$item->showFormHeader(['formtitle' => false]);
$canedit = static::canUpdate();
$fields = $item->fields;
$fields['lock'] = Html::getCheckbox([
'title' => __('Lock the device as soon as possible', 'flyvemdm'),
'name' => 'lock',
'checked' => $item->fields['lock'],
'value' => '1',
'readonly' => ($canedit == '0' ? '1' : '0'),
]);
$fields['wipe'] = Html::getCheckbox([
'title' => __('Wipe the device as soon as possible', 'flyvemdm'),
'name' => 'wipe',
'checked' => $item->fields['wipe'],
'value' => '1',
'readonly' => ($canedit == '0' ? '1' : '0'),
]);
$data = [
'withTemplate' => '',
'isNewID' => $item->isNewID($ID),
'canUpdate' => (!$item->isNewID($ID)) && ($item->canUpdate() > 0),
'agent' => $fields,
'unenrollButton' => Html::submit(_x('button', 'Unenroll'), ['name' => 'unenroll']),
];
$twig = plugin_flyvemdm_getTemplateEngine();
echo $twig->render('agent_dangerzone.html', $data);
$item->showFormButtons(['candel' => false, 'formfooter' => false]);
}
/**
* Display the agents according the fleet
* @param PluginFlyvemdmFleet $item
* @return string an html with the agents
*/
public static function showForFleet(PluginFlyvemdmFleet $item) {
if (isset($_GET["start"])) {
$start = intval($_GET["start"]);
} else {
$start = 0;
}
$dbUtils = new DbUtils();
// Total Number of agents
$items_id = $item->getField('id');
$itemFk = $item::getForeignKeyField();
$number = $dbUtils->countElementsInTableForMyEntities(
static::getTable(),
[$itemFk => $items_id]
);
// get the pager
$pager = Html::printAjaxPager(self::getTypeName(1), $start, $number, '', false);
$pager = ''; // disabled because the results are not paged yet
// get items
$agent = new static();
$condition = "`$itemFk` = '$items_id' " . $dbUtils->getEntitiesRestrictRequest();
$rows = $agent->find($condition, '', '');
$data = [
'number' => $number,
'pager' => $pager,
'agents' => $rows,
];
$twig = plugin_flyvemdm_getTemplateEngine();
echo $twig->render('agent_fleet.html', $data);
}
/**
* @param CommonDBTM $item
*/
public static function displayTabContentForComputer(CommonDBTM $item) {
$agent = new static();
if (!$agent->getFromDBByCrit(['computers_id' => $item->getID()])) {
return;
}
$fields = $agent->fields;
$fields['fleet']=$agent->getFleet();
if (empty($fields['last_contact'])) {
$fields['last_contact'] = __('Never seen online', 'flyvemdm');
}
$twig = plugin_flyvemdm_getTemplateEngine();
echo $twig->render('agentComputerInfo.html', [
'agent' => $fields,
'agentUrl' => Toolbox::getItemTypeFormURL(self::class),
'fleetUrl' => Toolbox::getItemTypeFormURL(PluginFlyvemdmFleet::class)
]);
}
/**
* @see CommonDBTM::canViewItem()
*/
public function canViewItem() {
// Check the active profile
$config = Config::getConfigurationValues('flyvemdm', ['guest_profiles_id']);
if ($_SESSION['glpiactiveprofile']['id'] != $config['guest_profiles_id']) {
return parent::canViewItem();
}
if (!$this->checkEntity(true)) {
return false;
}
// the active profile is guest user, then check the user is
// owner of the item's computer
$computer = $this->getComputer();
if ($computer === null) {
return false;
}
return $_SESSION['glpiID'] == $computer->getField('users_id');
}
/**
* Send a wipe command to the agent
*/
protected function sendWipeQuery() {
$topic = $this->getTopic();
if ($topic !== null) {
$mqttMessage = ['wipe' => 'now'];
$this->notify("$topic/Command/Wipe", json_encode($mqttMessage, JSON_UNESCAPED_SLASHES), 0, 1);
}
}
/**
* Send a lock command to the agent
*/
protected function sendLockQuery() {
$topic = $this->getTopic();
if ($topic !== null) {
$mqttMessage = ['lock' => 'now'];
$this->notify("$topic/Command/Lock", json_encode($mqttMessage, JSON_UNESCAPED_SLASHES), 0, 1);
}
}
/**
* Send a lock command to the agent
*/
protected function sendUnlockQuery() {
$topic = $this->getTopic();
if ($topic !== null) {
$mqttMessage = ['lock' => 'unlock'];
$this->notify("$topic/Command/Lock", json_encode($mqttMessage, JSON_UNESCAPED_SLASHES), 0, 1);
}
}
/**
* Send unenrollment command to the agent
*/
protected function sendUnenrollQuery() {
$topic = $this->getTopic();
if ($topic !== null) {
$mqttMessage = ['unenroll' => 'now'];
$this->notify("$topic/Command/Unenroll", json_encode($mqttMessage, JSON_UNESCAPED_SLASHES), 0, 1);
}
}
/**
* @param array $input
* @return array|bool
*/
public function prepareInputForAdd($input) {
// Get the maximum quantity of devices allowed for the current entity
$entityConfig = new PluginFlyvemdmEntityconfig();
if (!$entityConfig->getFromDBOrCreate($_SESSION['glpiactive_entity'])) {
$this->filterMessages(Session::addMessageAfterRedirect(__('Failed to read configuration of the entity', 'flyvemdm')));
return false;
}
$maxAgents = $entityConfig->getField('device_limit');
$entityId = $_SESSION['glpiactive_entity'];
$deviceCount = countElementsInTable($this->getTable(), "`entities_id`='$entityId'");
if ($maxAgents > 0 && $deviceCount >= $maxAgents) {
// Too many devices
$this->filterMessages(Session::addMessageAfterRedirect(__('Too many devices', 'flyvemdm')));
$input = false;
}
// User already logged in : user token has been validated
switch ($this->chooseEnrollMethod($input)) {
case self::ENROLL_DENY:
$this->filterMessages(Session::addMessageAfterRedirect(__('Unable to find a enrollment method', 'flyvemdm')));
$input = false;
break;
case self::ENROLL_INVITATION_TOKEN:
$input = $this->enrollByInvitationToken($input);
break;
case self::ENROLL_ENTITY_TOKEN:
// Method disabled, waiting for implementation
$input = false;
break;
}
unset($input['is_online']);
return $input;
}
/**
* @param array $input
* @return array|bool
*/
public function prepareInputForUpdate($input) {
if (isset($input['plugin_flyvemdm_fleets_id'])) {
// Update MQTT ACL for the fleet
$oldFleet = new PluginFlyvemdmFleet();
if (!$oldFleet->getFromDB($this->fields['plugin_flyvemdm_fleets_id'])) {
// Unable to load fleet currently associated to the agent
Session::addMessageAfterRedirect(__("The fleet of the device does not longer exists", 'flyvemdm'));
return false;
}
$newFleet = new PluginFlyvemdmFleet();
if (!$newFleet->getFromDB($input['plugin_flyvemdm_fleets_id'])) {
//Unable to load the new fleet
Session::addMessageAfterRedirect(__("The target fleet does not exists", 'flyvemdm'));
return false;
}
$this->changeMqttAcl($oldFleet, $newFleet);
}
// send wipe to the agent
if (isset($input['wipe']) && $input['wipe'] != '0') {
$input['wipe'] == '1';
}
// send lock to the agent
if (isset($input['lock']) && $input['lock'] != '0') {
$input['lock'] == '1';
}
if (array_key_exists('lock', $input)
&& ($this->fields['wipe'] != '0'
|| (isset($input['wipe']) && $input['wipe'] != '0') )) {
unset($input['lock']);
}
unset($input['enroll_status']);
if (isset($input['_unenroll'])) {
$input['enroll_status'] = 'unenrolling';
}
//Send a connection status request to the device
if (isset($input['_ping'])) {
if ($this->getTopic() === null) {
Session::addMessageAfterRedirect(__("The device is not enrolled yet", 'flyvemdm'));
return false;
}
if (!$this->sendPingQuery()) {
Session::addMessageAfterRedirect(__("Timeout querying the device", 'flyvemdm'));
return false;
}
}
if (isset($input['_geolocate'])) {
if ($this->getTopic() === null) {
Session::addMessageAfterRedirect(__("The device is not enrolled yet", 'flyvemdm'));
return false;
}
$errorMessage = '';
if (!$this->sendGeolocationQuery($errorMessage)) {
Session::addMessageAfterRedirect($errorMessage);
return false;
}
}
if (isset($input['_inventory'])) {
if ($this->getTopic() === null) {
Session::addMessageAfterRedirect(__("The device is not enrolled yet", 'flyvemdm'));
return false;
}
if (!$this->sendInventoryQuery()) {
Session::addMessageAfterRedirect(__("Timeout querying the device inventory", 'flyvemdm'));
return false;
}
}
return $input;
}
/**
* @see CommonDBTM::post_addItem()
*/
public function post_addItem() {
// Notify the agent about its fleets
$this->updateSubscription();
}
/**
* @see CommonDBTM::post_getFromDB()
*/
public function post_getFromDB() {
// set Topic after getting an item
// Useful for post_purgeItem
$this->getTopic();
$this->setupMqttAccess();
$this->fields['api_token'] = User::getToken($this->fields['users_id'], 'api_token');
}
/**
* Actions done before the DELETE of the item in the database /
* Maybe used to add another check for deletion
*
* @return bool : true if item need to be deleted else false
*/
public function pre_deleteItem() {
$success = false;
// get serial of the computer
$computer = $this->getComputer();
if ($computer === null) {
// The associated computer is already deleted
return true;
}
// get the guest profile ID
$config = Config::getConfigurationValues('flyvemdm', ['guest_profiles_id']);
$guestProfileId = $config['guest_profiles_id'];
if ($guestProfileId === null) {
Session::addMessageAfterRedirect(__('Failed to find the guest user profile', 'flyvemdm'));
return false;
}
$computerId = $computer->getID();
$serial = $computer->getField('serial');
$entityId = $this->getField('entities_id');
$ownerUserId = $computer->getField('users_id');
// Find other computers belong to the user in the current entity
// TODO : maybe use getEntityRestrict for multientity support
$rows = $computer->find("`entities_id`='$entityId' AND `users_id`='$ownerUserId' AND `id` <> '$computerId'", '', '1');
if (count($rows) == 0) {
// Remove guest habilitation for the entity
$profile_User = new Profile_User();
$success = $profile_User->deleteByCriteria([
'users_id' => $ownerUserId,
'entities_id' => $entityId,
'profiles_id' => $guestProfileId,
'is_dynamic' => 0
]);
if (!$success) {
Session::addMessageAfterRedirect(__('Failed to remove guest habilitation for the user of the device', 'flyvemdm'));
return false;
}
}
// Delete the user account of the agent
$agentUser = new User();
$agentUser->delete([
'id' => $this->fields['users_id'],
], true);
// Send unrolling message to reset agent status
if ($this->fields['enroll_status'] == 'enrolled') {
$this->sendUnenrollQuery();
}
// Delete the MQTT user for the agent
if (!empty($serial)) {
$mqttUser = new PluginFlyvemdmMqttuser();
if ($mqttUser->getFromDBByQuery("WHERE `user` = '$serial'")) {
if (!$mqttUser->delete(['id' => $mqttUser->getID()], true)) {
Session::addMessageAfterRedirect(__('Failed to delete MQTT user for the device', 'flyvemdm'));
return false;
}
}
}
// Delete documents associated to the agent
$document_Item = new Document_Item();
$success = $document_Item->deleteByCriteria([
'itemtype' => PluginFlyvemdmAgent::class,
'items_id' => $this->fields['id']
]);
if (!$success) {
Session::addMessageAfterRedirect(__('Failed to delete documents attached to the device', 'flyvemdm'));
return false;
}
return true;
}
/**
* Actions done after the UPDATE of the item in the database
* @param integer $history store changes history ? (default 1)
* @return void
*/
public function post_updateItem($history = 1) {
if (in_array('plugin_flyvemdm_fleets_id', $this->updates)) {
// create tasks for the agent from already applied policies
$newFleet = new PluginFlyvemdmFleet();
if ($newFleet->getFromDB($this->fields['plugin_flyvemdm_fleets_id'])) {
$task = new PluginFlyvemdmTask();
// get groups of policies where a policy applies
$groups = $task->getGroupsOfAppliedPolicies($newFleet);
foreach ($groups as $groupName) {
// get policies per group
$policiesToApply = $task->getGroupOfPolicies($groupName, $newFleet);
// create task statuses for a single agent
$task->createTaskStatus($this, $policiesToApply);
}
}
$this->updateSubscription();
if (isset($this->oldvalues['plugin_flyvemdm_fleets_id'])) {
$oldFleet = new PluginFlyvemdmFleet();
$oldFleet->getFromDB($this->oldvalues['plugin_flyvemdm_fleets_id']);
}
}
// If both wipe and lock are enabled for the device, only send wipe command
if (in_array('wipe', $this->updates) && $this->fields['wipe'] != '0') {
$this->sendWipeQuery();
}
if (in_array('lock', $this->updates) && $this->fields['wipe'] == '0') {
if ($this->fields['lock'] != '0') {
$this->sendLockQuery();
} else {
$this->sendUnlockQuery();
}
}
if (in_array('enroll_status', $this->updates) && $this->fields['enroll_status'] == 'unenrolling') {
$this->sendUnenrollQuery();
}
}
/**
* Actions done after the restore of the item
* @return void
*/
public function post_restoreItem() {
$computer = $this->getComputer();
if ($computer !== null) {
$mqttUser = new PluginFlyvemdmMqttuser();
if ($mqttUser->getFromDB($this->fields['computers_id'])) {
$mqttUser->update([
'id' => $mqttUser->getID(),
'enabled' => '1'
], 0);
}
}
}
/**
* Actions done after the purge of an item
*/
public function post_purgeItem() {
$this->cleanupSubtopics();
}
/**
* @return array
*/
public function getSearchOptionsNew() {
$tab = parent::getSearchOptionsNew();
$tab[] = [
'id' => '3',
'table' => 'glpi_plugin_flyvemdm_fleets',
'field' => 'name',
'name' => __('Fleet', 'flyvemdm'),
'datatype' => 'dropdown'
];
$tab[] = [
'id' => '4',
'table' => 'glpi_computers',
'field' => 'id',
'name' => __('Computer'),
'datatype' => 'dropdown',
'massiveaction' => false
];
$tab[] = [
'id' => '7',
'table' => 'glpi_plugin_flyvemdm_fleets',
'field' => 'id',
'name' => __('Fleet - ID'),
'massiveaction' => false,
'datatype' => 'number'
];
$tab[] = [
'id' => '8',
'table' => $this->getTable(),
'field' => 'last_contact',
'name' => __('Last contact', 'flyvemdm'),
'datatype' => 'datetime',
'massiveaction' => false
];
$tab[] = [
'id' => '10',
'table' => $this->getTable(),
'field' => 'version',
'name' => __('Version'),
'datatype' => 'string',
'massiveaction' => false
];
$tab[] = [
'id' => '11',
'table' => $this->getTable(),
'field' => 'is_online',
'name' => __('Is online', 'flyvemdm'),
'datatype' => 'boolean',
'massiveaction' => false
];
$tab[] = [
'id' => '12',
'table' => $this->getTable(),
'field' => 'mdm_type',
'name' => __('MDM type', 'flyvemdm'),
'datatype' => 'boolean',
'massiveaction' => false
];
$tab[] = [
'id' => '13',
'table' => $this->getTable(),
'field' => 'has_system_permission',
'name' => __('Has system permission', 'flyvemdm'),
'datatype' => 'boolean',
'massiveaction' => false
];
$tab[] = [
'id' => '14',
'table' => $this->getTable(),
'field' => 'enroll_status',
'name' => __('Enroll status', 'flyvemdm'),
'datatype' => 'boolean',
'massiveaction' => false
];
$tab[] = [
'id' => '15',
'table' => $this->getTable(),
'field' => 'wipe',
'name' => __('Wipe requested', 'flyvemdm'),
'datatype' => 'boolean',
'massiveaction' => false
];
$tab[] = [
'id' => '16',
'table' => $this->getTable(),
'field' => 'lock',
'name' => __('Lock requested', 'flyvemdm'),
'datatype' => 'boolean',
'massiveaction' => false
];
return $tab;
}
/**
* Limit search for agents of guest user
*/
public static function addDefaultJoin() {
$join = '';
$config = Config::getConfigurationValues('flyvemdm', ['guest_profiles_id']);
$guestProfileId = $config['guest_profiles_id'];
if ($_SESSION['glpiactiveprofile']['id'] == $guestProfileId) {
$agentTable = self::getTable();
$computerTable = Computer::getTable();
$join = "LEFT JOIN `$computerTable` AS `c` ON `$agentTable`.`computers_id`=`c`.`id` ";
}
return $join;
}
/**
* Limit search for agents if guest user
*/
public static function addDefaultWhere() {
$where = '';
$config = Config::getConfigurationValues('flyvemdm', ['guest_profiles_id']);
$guestProfileId = $config['guest_profiles_id'];
if ($_SESSION['glpiactiveprofile']['id'] == $guestProfileId) {
$userId = $_SESSION['glpiID'];
$where = " AND `c`.`users_id`='$userId'";
}
return $where;
}
/**
* Returns the topic the agent shall listen
*
* @return string MQTT Topic
*
*/
public function getSubscribedTopic() {
$fleet = new PluginFlyvemdmFleet();
$subscribedTopic = null;
if ($fleet->getFromDB($this->fields['plugin_flyvemdm_fleets_id'])) {
if (! $fleet->fields['is_default']) {
$subscribedTopic = $fleet->getTopic();
}
}
return $subscribedTopic;
}
/**
* Send to an agent an up to date list of MQTT topics it must subscribe
*/
public function updateSubscription() {
$topicToSubscribe = $this->getSubscribedTopic();
$topicList = [
'subscribe' => [
['topic' => $topicToSubscribe]
]
];
$topic = $this->getTopic();
if ($topicToSubscribe !== null && $topic !== null) {
$this->notify("$topic/Command/Subscribe", json_encode($topicList, JSON_UNESCAPED_SLASHES), 0, 1);
}
}
/**
* get the MQTT topic of the agent
*
* @return string|null the permanent MQTT topic of the agent.
*/
public function getTopic() {
if ($this->topic === null) {
$computer = $this->getComputer();
if ($computer !== null) {
$serial = $computer->getField('serial');
if (strlen($serial)) {
$entity = $this->getField('entities_id');
$this->topic = "/$entity/agent/$serial";
}
}
}
return $this->topic;
}
/**
* get an agent from DB by topic
*
* @param string|false $topic
* @return bool
*/
public function getByTopic($topic) {
global $DB;
$mqttPath = explode('/', $topic);
if (isset($mqttPath[3])) {
if ($mqttPath[2] == 'agent') {
$entity = intval($mqttPath[1]);
$serial = $DB->escape($mqttPath[3]);
if (strlen($serial)) {
$computerTable = Computer::getTable();
$agentTable = self::getTable();
return $this->getFromDBByQuery("LEFT JOIN `$computerTable` `c` ON (
`c`.`id` = `$agentTable`.`computers_id`
)
WHERE `$agentTable`.`entities_id`='$entity' AND `c`.`serial` = '$serial'"
);
}
}
}
return false;
}
/**
* unsibscribe from a fleet
*/
public function unsubscribe() {
$this->update([
'id' => $this->getID(),
'plugin_flyvemdm_fleets_id' => null
]);
$topic = $this->getTopic();
if ($topic !== null) {
$topic = $topic . "/Subscription";
$this->notify($topic, json_encode([], JSON_UNESCAPED_SLASHES));
}
}
/**
* Checks if the data provided for enrollment satisfy our requirements
* @param array $authFactors
* @return integer enroll method
*/
protected static function checkChallengeCombinations($authFactors) {
$method = self::ENROLL_DENY;
if (array_key_exists('email', $authFactors) && array_key_exists('agentToken', $authFactors)) {
// require challenge on email and an agent token only
if (count($authFactors) == 2) {
$method = self::ENROLL_AGENT_TOKEN;
}
} else if (array_key_exists('entityToken', $authFactors)) {
// or require challenge on a entity token only
if (count($authFactors) == 1) {
$method = self::ENROLL_ENTITY_TOKEN;
}
}
return $method;
}
/**
* Attempt to enroll using an invitation token
* @param array $input Enrollment data
* @return array|bool
*/
protected function enrollByInvitationToken($input) {
$invitationToken = isset($input['_invitation_token']) ? $input['_invitation_token'] : null;
$email = isset($input['_email']) ? $input['_email'] : null;
$serial = isset($input['_serial']) ? $input['_serial'] : null;
$uuid = isset($input['_uuid']) ? $input['_uuid'] : null;