forked from opendcim/openDCIM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
devices.php
2580 lines (2376 loc) · 95.1 KB
/
devices.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
require_once( 'db.inc.php' );
require_once( 'facilities.inc.php' );
$subheader=__("Data Center Device Detail");
$dev=new Device();
$cab=new Cabinet();
$taginsert="";
// Ajax functions
// SNMP Test
if(isset($_POST['snmptest'])){
// Parse through the post data and pull in site defaults if necessary
$community=($_POST['SNMPCommunity']=="")?$config->ParameterArray["SNMPCommunity"]:$_POST['SNMPCommunity'];
$version=($_POST['SNMPVersion']=="" || $_POST['SNMPVersion']=="default")?$config->ParameterArray["SNMPVersion"]:$_POST['SNMPVersion'];
$v3SecurityLevel=($_POST['v3SecurityLevel']=="")?$config->ParameterArray["v3SecurityLevel"]:$_POST['v3SecurityLevel'];
$v3AuthProtocol=($_POST['v3AuthProtocol']=="")?$config->ParameterArray["v3AuthProtocol"]:$_POST['v3AuthProtocol'];
$v3AuthPassphrase=($_POST['v3AuthPassphrase']=="")?$config->ParameterArray["v3AuthPassphrase"]:$_POST['v3AuthPassphrase'];
$v3PrivProtocol=($_POST['v3PrivProtocol']=="")?$config->ParameterArray["v3PrivProtocol"]:$_POST['v3PrivProtocol'];
$v3PrivPassphrase=($_POST['v3PrivPassphrase']=="")?$config->ParameterArray["v3PrivPassphrase"]:$_POST['v3PrivPassphrase'];
// Init the snmp handler
$snmpHost=new OSS_SNMP\SNMP(
$_POST['PrimaryIP'],
$community,
$version,
$v3SecurityLevel,
$v3AuthProtocol,
$v3AuthPassphrase,
$v3PrivProtocol,
$v3PrivPassphrase
);
// Try to connect to keep us from killing the system on a failure
$error=false;
try {
$snmpresults=$snmpHost->useSystem()->name();
}catch (Exception $e){
$error=true;
}
// Show the end user something to make them feel good about it being correct
if(!$error){
foreach($snmpHost->realWalk('1.3.6.1.2.1.1') as $oid => $value){
print "$oid => $value <br>\n";
}
}else{
print __("Something isn't working correctly");
}
exit;
}
// Get CDU uptime
if(isset($_POST['cduuptime'])){
$pdu=new PowerDistribution();
$pdu->PDUID=$_POST['DeviceID'];
echo $pdu->GetSmartCDUUptime();
exit;
}
// Get log entries
if(isset($_POST['logging'])){
$dev->DeviceID=$_POST['devid'];
$actions=array();
if($dev->GetDevice()){
$actions=LogActions::GetLog($dev,false);
}
header('Content-Type: application/json');
echo json_encode($actions);
exit;
}
// Get cabinet height
if(isset($_POST['cab'])){
$cab->CabinetID=$_POST['cab'];
$cab->GetCabinet();
echo $cab->CabinetHeight;
exit;
}
// Get list of media types
if(isset($_GET['mt'])){
header('Content-Type: application/json');
echo json_encode(MediaTypes::GetMediaTypeList());
exit;
}
// Get list of name patterns
if(isset($_GET['spn'])){
header('Content-Type: application/json');
$PortNamePatterns=array();
if(isset($_GET['power'])){
foreach(array('PS(1)','R(1)','Custom',__("From Template"),__("Invert Port Labels")) as $pattern){
$PortNamePatterns[]['Pattern']=$pattern;
}
}else{
foreach(array('NIC(1)','Port(1)','Fa/(1)','Gi/(1)','Ti/(1)','Custom',__("From Template"),__("Invert Port Labels")) as $pattern){
$PortNamePatterns[]['Pattern']=$pattern;
}
}
echo json_encode($PortNamePatterns);
exit;
}
// Get connection path for a patch panel connection
if(isset($_GET['path'])){
$path=DevicePorts::followPathToEndPoint($_GET['ConnectedDeviceID'], $_GET['ConnectedPort']);
foreach($path as $port){
$dev->DeviceID=$port->DeviceID;
$dev->GetDevice();
$port->DeviceName=$dev->Label;
}
header('Content-Type: application/json');
echo json_encode($path);
exit;
}
// This will allow any jackass to certify an audit but the function is hidden and
// this is the type of function that will be fixed with the API so i'm not fixing it
// as long as logging is enabled we'll know who triggered it.
if(isset($_POST['audit'])){
$dev->DeviceID=$_POST['audit'];
$dev->Audit();
$dev->AuditStamp=date('r',strtotime($dev->AuditStamp));
header('Content-Type: application/json');
echo json_encode($dev);
exit;
};
if(isset($_POST['olog'])){
$dev->DeviceID=$_POST['devid'];
$dev->GetDevice();
$dev->OMessage=sanitize($_POST['olog']);
$tmpDev=new Device();
$tmpDev->DeviceID=$dev->DeviceID;
$tmpDev->GetDevice();
$return=(class_exists('LogActions') && $tmpDev->Rights=="Write")?LogActions::LogThis($dev,$tmpDev):false;
header('Content-Type: application/json');
echo json_encode($return);
exit;
};
// Set all ports to the same Label pattern, media type or color code
if(isset($_POST['setall'])){
$portnames=array();
if(isset($_POST['spn']) && strlen($_POST['spn'])>0){
// Special Condition to load ports from the device template and use those names
if($_POST['spn']==__("From Template") || $_POST['spn']==__("Invert Port Labels")){
$dev->DeviceID=$_POST['devid'];
$dev->GetDevice();
if($_POST['spn']==__("From Template")){
$ports=(isset($_POST['power']))?new TemplatePowerPorts():new TemplatePorts();
$ports->TemplateID=$dev->TemplateID;
foreach($ports->getPorts() as $pn => $portobject){
$portnames[$pn]=$portobject->Label;
}
}else{
$dp=(isset($_POST['power']))?new PowerPorts():new DevicePorts();
$pc=(isset($_POST['power']))?$dev->PowerSupplyCount:$dev->Ports;
$dp->DeviceID=$dev->DeviceID;
$ports=$dp->getPorts();
foreach($ports as $portid => $port){
// patch panels make everything more complicated
if($portid >0){
$portnames[$portid]=$ports[($pc-(abs($portid)-1))]->Label;
if($dev->DeviceType=="PatchPanel"){
$portnames[($portid*-1)]=$ports[($pc-(abs($portid)-1))]->Label;
}
}
}
}
}else{
//using premade patterns if the input differs and causes an error then fuck em
list($result, $msg, $idx) = parseGeneratorString($_POST['spn']);
if($result){
$dev->DeviceID=$_POST['devid'];
$dev->GetDevice();
$portnames=generatePatterns($result, (isset($_POST['power']))?$dev->PowerSupplyCount:$dev->Ports);
// generatePatterns starts the index at 0, it's more useful to us starting at 1
array_unshift($portnames, null);
}
}
}
// Make a new method to set all the ports to a media type?
$blurg=(isset($_POST['power']))?PowerPorts::getPortList($_POST['devid']):DevicePorts::getPortList($_POST['devid']);
foreach($blurg as $portnum => $port){
$port->Label=(isset($_POST['spn']) && (($_POST['setall']=='true' && count($portnames)>0) || (count($portnames)>0 && strlen($port->Label)==0)))?$portnames[abs($port->PortNumber)]:$port->Label;
if(!isset($_POST['power'])){
$port->MediaID=(($_POST['setall']=='true' || $port->MediaID==0) && isset($_POST['mt']) && ($_POST['setall']=='true' || intval($_POST['mt'])>0))?$_POST['mt']:$port->MediaID;
$port->ColorID=(($_POST['setall']=='true' || $port->ColorID==0) && isset($_POST['cc']) && ($_POST['setall']=='true' || intval($_POST['cc'])>0))?$_POST['cc']:$port->ColorID;
}
$port->updatePort();
// Update the other side to keep media types in sync if it is connected same
// rule applies that it will only be set if it is currently unset
if($port->ConnectedDeviceID!='NULL'){
$port->DeviceID=$port->ConnectedDeviceID;
$port->PortNumber=$port->ConnectedPort;
$port->getPort();
if(!isset($_POST['power'])){
$port->MediaID=(($_POST['setall']=='true' || $port->MediaID==0) && isset($_POST['mt']) && ($_POST['setall']=='true' || intval($_POST['mt'])>0))?$_POST['mt']:$port->MediaID;
$port->ColorID=(($_POST['setall']=='true' || $port->ColorID==0) && isset($_POST['cc']) && ($_POST['setall']=='true' || intval($_POST['cc'])>0))?$_POST['cc']:$port->ColorID;
}
$port->updatePort();
}
}
// Return all the ports for the device then eval just the MT and CC
$dp=(isset($_POST['power']))?new PowerPorts():new DevicePorts();
$dp->DeviceID=$_POST['devid'];
header('Content-Type: application/json');
$ports=array(
'mt' => MediaTypes::GetMediaTypeList(),
'cc' => ColorCoding::GetCodeList(),
'ports' => $dp->getPorts()
);
echo json_encode($ports);
exit;
}
if(isset($_POST['fp'])){
$dev->DeviceID=$_POST['devid'];
$dev->GetDevice();
if($dev->Rights=="Write"){
if($_POST['fp']==''){ // querying possible first ports
$portCandidates=SwitchInfo::findFirstPort($dev->DeviceID);
if(count($portCandidates)>0){
foreach($portCandidates as $id => $portdesc){
$checked=($id==$dev->FirstPortNum)?' checked':'';
print '<input type="radio" name="FirstPortNum" id="fp'.$id.'" value="'.$id.'"'.$checked.'><label for="fp'.$id.'">'.$portdesc.'</label><br>';
}
}else{
print __("ERROR: No ports found");
}
}else{ // setting first port
$dev->FirstPortNum=$_POST['fp'];
if($dev->UpdateDevice()){
echo 'Updated';
}else{
echo 'Failure';
}
}
}else{
// The button to trigger this function is hidden if they don't have rights
// but users aren't to be trusted.
echo 'Failure';
}
exit;
};
if(isset($_POST['swdev'])){
$dev->DeviceID=$_POST['swdev'];
$dev->GetDevice();
if($dev->Rights=="Write"){
if(isset($_POST['saveport'])){
$dp=new DevicePorts();
$dp->DeviceID=$_POST['swdev'];
$dp->PortNumber=$_POST['pnum'];
$dp->Label=$_POST['pname'];
$dp->MediaID=$_POST['porttype'];
$dp->ColorID=$_POST['portcolor'];
$dp->Notes=$_POST['cnotes'];
$dp->ConnectedDeviceID=$_POST['cdevice'];
$dp->ConnectedPort=$_POST['cdeviceport'];
if($dp->updatePort()){
// when updating the media type on a rear port update the mediatype on the front port as well to make sure they match.
if($dp->PortNumber<0){
$dp->PortNumber=abs($dp->PortNumber);
$dp->GetPort();
$dp->MediaID=$_POST['porttype'];
$dp->ColorID=$_POST['portcolor'];
$dp->updatePort();
}
echo 1;
}else{
echo 0;
}
exit;
}
if(isset($_POST['delport'])){
$dp=new DevicePorts();
$dp->DeviceID=$_POST['swdev'];
$dp->PortNumber=$_POST['pnum'];
$ports=end($dp->getPorts());
function updatedevice($devid){
$dev=new Device();
$dev->DeviceID=$devid;
$dev->GetDevice();
$dev->Ports=$dev->Ports-1;
$dev->UpdateDevice();
}
// remove the selected port then shuffle the data to fill the hole if needed
if($ports->PortNumber!=$dp->PortNumber){
foreach($ports as $i=>$prop){
if($i!="PortNumber"){
$dp->$i=$prop;
}
}
if($dp->updatePort()){
if($ports->removePort()){
updatedevice($dp->DeviceID);
echo 1;
exit;
}
}
echo 0;
}else{ // Last available port. just delete it.
if($dp->removePort()){
updatedevice($dp->DeviceID);
echo 1;
}else{
echo 0;
}
}
exit;
}
// Attach all rear ports of patch panel to another patch panel
if(isset($_POST['rear']) && isset($_POST['cdevice'])){
$ConnectTo=new Device();
$ConnectTo->DeviceID=$_POST['cdevice'];
// error out if connecting device doesn't exist
if(!$ConnectTo->GetDevice() && $_POST['cdevice']!='clear'){
echo 'false';
exit;
}
$cp=new DevicePorts();
$cp->DeviceID=$ConnectTo->DeviceID;
$cp=$cp->getPorts();
$dp=new DevicePorts();
$dp->DeviceID=$dev->DeviceID;
foreach($dp->getPorts() as $index => $port){
if($port->PortNumber<0){
if($_POST['cdevice']=='clear' && $_POST['override']=='true'){
$port->removeConnection();
}elseif(isset($cp[$port->PortNumber]) && (is_null($port->ConnectedDeviceID) || (!is_null($port->ConnectedDeviceID) && $_POST['override']=='true'))){
$port->ConnectedDeviceID=$ConnectTo->DeviceID;
$port->ConnectedPort=$port->PortNumber;
$port->updatePort();
}
}
}
$ports=array();
$sql="SELECT p.*, d.Label as DeviceLabel, (SELECT Label FROM fac_Device
WHERE DeviceID=p.ConnectedDeviceID) AS ConnectedDeviceLabel, (SELECT Label
from fac_Ports WHERE DeviceID=p.ConnectedDeviceID AND
PortNumber=p.ConnectedPort) AS ConnectedPortLabel FROM fac_Ports p,
fac_Device d WHERE p.DeviceID=d.DeviceID AND p.DeviceID=$dev->DeviceID;";
foreach($dbh->query($sql) as $row){
$ports[$row['PortNumber']]=$row;
}
echo json_encode($ports);
exit;
}
}
if(isset($_POST['getport'])){
$dp=new DevicePorts();
$dp->DeviceID=$_POST['swdev'];
$dp->PortNumber=$_POST['pnum'];
$dp->getPort();
$cd=new DevicePorts();
$cd->DeviceID=$dp->ConnectedDeviceID;
$cd->PortNumber=$dp->ConnectedPort;
$cd->getPort();
$mt=MediaTypes::GetMediaTypeList();
$cc=ColorCoding::GetCodeList();
$dp->MediaName=(isset($mt[$dp->MediaID]))?$mt[$dp->MediaID]->MediaType:'';
$dp->ColorName=(isset($cc[$dp->ColorID]))?$cc[$dp->ColorID]->Name:'';
$dev->DeviceID=$dp->ConnectedDeviceID;
$dp->Label=($dp->Label=='')?abs($dp->PortNumber):$dp->Label;
$dp->ConnectedDeviceLabel=($dev->GetDevice())?stripslashes($dev->Label):'';
$dp->ConnectedDeviceType=$dev->DeviceType;
$dp->ConnectedPort=(!is_null($cd->DeviceID) && $dp->ConnectedPort==0)?'':$dp->ConnectedPort;
$dp->ConnectedPortLabel=(!is_null($cd->Label) && $cd->Label!='')?$cd->Label:$dp->ConnectedPort;
($dp->ConnectedPort<0)?$dp->ConnectedPortLabel.=' ('.__("Rear").')':'';
header('Content-Type: application/json');
echo json_encode($dp);
exit;
}
$list='';
if(isset($_POST['listports'])){
$dp=new DevicePorts();
$dp->DeviceID=$_POST['thisdev'];
$list=$dp->getPorts();
if($config->ParameterArray["MediaEnforce"]=='enabled'){
$dp->DeviceID=$_POST['swdev'];
$dp->PortNumber=$_POST['pn'];
$dp->getPort();
foreach($list as $key => $port){
if($port->MediaID!=$dp->MediaID){
unset($list[$key]); // remove the nonmatching ports
}
}
}
foreach($list as $key => $port){
if(!is_null($port->ConnectedDeviceID)){
if($port->ConnectedDeviceID==$_POST['swdev'] && $port->ConnectedPort==$_POST['pn']){
// This is what is currently connected so leave it in the list
}else{
// Remove any other ports that already have connections
unset($list[$key]);
}
}
}
// S.U.T. #2342 I touch myself
if($dp->DeviceID == $_POST['swdev'] && isset($list[$_POST['pn']])){
unset($list[$_POST['pn']]);
}
// Sort the ports so that all front ports will be first then the rear ports.
$front=array();
$rear=array();
foreach($list as $pn => $port){
if($pn>0){
$front[$pn]=$port;
}else{
$rear[$pn]=$port;
}
}
// Positive and negative numbers have different sorts to make sure that 1 is on top of the list
ksort($front);
krsort($rear);
$list=array_replace($front,$rear);
}else{
$patchpanels=(isset($_POST['rear']))?"true":null;
$portnumber=(isset($_POST['pn']))?$_POST['pn']:null;
$limiter=(isset($_POST['limiter']))?$_POST['limiter']:null;
$list=DevicePorts::getPatchCandidates($_POST['swdev'],$portnumber,null,$patchpanels,$limiter);
}
header('Content-Type: application/json');
echo json_encode($list);
exit;
}
if(isset($_POST['ESXrefresh'])){
$dev->DeviceID=$_POST['ESXrefresh'];
$dev->GetDevice();
if($dev->Rights=="Write"){
ESX::RefreshInventory($_POST['ESXrefresh']);
buildESXtable($_POST['ESXrefresh']);
}
exit;
}
if(isset($_POST['customattrrefresh'])){
$template=new DeviceTemplate();
$template->TemplateID=$_POST['customattrrefresh'];
$template->GetTemplateByID();
$dev->DeviceID=$_POST['DeviceID'];
$dev->GetDevice();
buildCustomAttributes($template, $dev);
exit;
}
if(isset($_POST['refreshswitch'])){
header('Content-Type: application/json');
if(isset($_POST['names'])){
$dev->DeviceID=$_POST['refreshswitch'];
$dev->GetDevice();
// This function should be hidden if they don't have rights, but just in case
if($dev->Rights=="Write"){
foreach(SwitchInfo::getPortNames($_POST['refreshswitch']) as $PortNumber => $Label){
$port=new DevicePorts();
$port->DeviceID=$_POST['refreshswitch'];
$port->PortNumber=$PortNumber;
$port->Label=$Label;
$port->updateLabel();
}
}
echo json_encode(SwitchInfo::getPortNames($_POST['refreshswitch']));
}elseif(isset($_POST['Notes'])){
$dev->DeviceID=$_POST['refreshswitch'];
$dev->GetDevice();
// This function should be hidden if they don't have rights, but just in case
if($dev->Rights=="Write"){
foreach(SwitchInfo::getPortAlias($_POST['refreshswitch']) as $PortNumber => $Notes){
$port=new DevicePorts();
$port->DeviceID=$_POST['refreshswitch'];
$port->PortNumber=$PortNumber;
$port->getPort();
$port->Notes=$Notes;
$port->updatePort();
}
}
echo json_encode(SwitchInfo::getPortAlias($_POST['refreshswitch']));
}else{
echo json_encode(SwitchInfo::getPortStatus($_POST['refreshswitch']));
}
exit;
}
if(isset($_POST["currwatts"]) && isset($_POST['pduid']) && $_POST['pduid'] >0){
$pdu=new PowerDistribution();
$pdu->PDUID=$_POST['pduid'];
$wattage->Wattage='Err';
$wattage->LastRead='Err';
if($pdu->GetPDU()){
$cab->CabinetID=$pdu->CabinetID;
$cab->GetCabinet();
if($person->canWrite($cab->AssignedTo)){
$wattage=$pdu->LogManualWattage($_POST["currwatts"]);
$wattage->LastRead=strftime("%c",strtotime($wattage->LastRead));
}
}
header('Content-Type: application/json');
echo json_encode($wattage);
exit;
}
// END AJAX
// These objects are used no matter what operation we're performing
$templ=new DeviceTemplate();
$mfg=new Manufacturer();
$esc=new Escalations();
$escTime=new EscalationTimes();
$contactList=$person->GetUserList();
$Dept=new Department();
$pwrConnection=new PowerPorts();
$pdu=new PowerDistribution();
$panel=new PowerPanel();
$pwrCords=null;
$chassis="";
$copy = false;
$copyerr=__("This device is a copy of an existing device. Remember to set the new location before saving.");
$childList=array();
// This page was called from somewhere so let's do stuff.
// If this page wasn't called then present a blank record for device creation.
if(isset($_REQUEST['action'])||isset($_REQUEST['DeviceID'])){
if(isset($_REQUEST['CabinetID'])){
$dev->Cabinet=$_REQUEST['CabinetID'];
$cab->CabinetID=$dev->Cabinet;
$cab->GetCabinet();
}
if(isset($_REQUEST['action'])&&$_REQUEST['action']=='new'){
// sets install date to today when a new device is being created
$dev->InstallDate=date("m/d/Y");
$dev->DeviceType=(isset($_REQUEST['DeviceType']))?$_REQUEST['DeviceType']:$dev->DeviceType;
// Some fields are pre-populated when you click "Add device to this cabinet"
// If you are adding a device that is assigned to a specific customer, assume that device is also owned by that customer
if($cab->AssignedTo >0){
$dev->Owner=$cab->AssignedTo;
}
}
// if no device id requested then we must be making a new device so skip all data lookups.
if(isset($_REQUEST['DeviceID'])){
$dev->DeviceID=intval($_REQUEST['DeviceID']);
// If no action is requested then we must be just querying a device info.
// Skip all modification checks
$tagarray=array();
if(isset($_POST['tags'])){
$tagarray=json_decode($_POST['tags']);
}
if(isset($_POST['action'])){
$dev->GetDevice();
// Pull all properties from a template and apply to the device before we add the values set
// on the screen. This will make sure things like slots are pulled from the template that aren't
// available to the end user initially
if($_POST['action']=='Create' && $_POST['TemplateID']>0){
$templ->TemplateID=$_POST['TemplateID'];
if($templ->GetTemplateByID()){
foreach($templ as $prop => $value){
$dev->$prop=$value;
}
}
}
// This shouldn't be needed now that we have the pdu model getting extended onto the device model. and we can just reference pdu as a variable to dev
if($dev->DeviceType=="CDU" || (isset($_POST['DeviceType']) && $_POST['DeviceType']=="CDU")){
$pdu->PDUID=$dev->DeviceID;
$pdu->GetPDU();
}
if($_POST['action']!='Child'){
// Preserve this as a special variable to keep an injection from being possible
$devrights=$dev->Rights;
foreach($dev as $prop => $val){
$dev->$prop=(isset($_POST[$prop]))?$_POST[$prop]:$val;
}
// Put the device rights back just in case we had someone try to inject them
$dev->Rights=$devrights;
// Stupid Cabinet vs CabinetID
$dev->Cabinet=$_POST['CabinetID'];
// Checkboxes don't work quite like normal inputs
$dev->ESX=(isset($_POST['ESX']))?$_POST['ESX']:0;
$dev->BackSide=(isset($_POST['BackSide']))?($_POST['BackSide']=="on")?1:0:0;
$dev->HalfDepth=(isset($_POST['HalfDepth']))?($_POST['HalfDepth']=="on")?1:0:0;
$dev->Reservation=(isset($_POST['Reservation']))?($_POST['Reservation']=="on")?1:0:0;
$dev->SNMPFailureCount=(isset($_POST['SNMPFailureCount']))?$_POST['SNMPFailureCount']:0;
// Used by CDU type devices only
if($dev->DeviceType=='CDU'){
foreach($pdu as $prop => $val){
$dev->$prop=(isset($_POST[$prop]))?$_POST[$prop]:$val;
}
(isset($_POST['failsafe']))?$dev->FailSafe=($_POST['failsafe']=="on")?1:0:'';
}
}
if(($dev->TemplateID >0)&&(intval($dev->NominalWatts==0))){$dev->UpdateWattageFromTemplate();}
$write=false;
$write=($person->canWrite($cab->AssignedTo))?true:$write;
$write=($dev->Rights=="Write")?true:$write;
if($dev->Rights=="Write" && $dev->DeviceID >0){
switch($_POST['action']){
case 'Update':
// User has changed the device type from chassis to something else and has said yes
// that they want to remove the dependant child devices
if(isset($_POST['killthechildren'])){
$childList=$dev->GetDeviceChildren();
foreach($childList as $childDev){
$childDev->DeleteDevice();
}
}
$dev->SetTags($tagarray);
if($dev->Cabinet <0){
$dev->MoveToStorage();
}else{
$dev->UpdateDevice();
updateCustomValues($dev);
}
break;
case 'Delete':
$dev->DeleteDevice();
//the $dev object should still exist even though we've deleted the db entry now
if($dev->ParentDevice >0){
header('Location: '.redirect("devices.php?DeviceID=$dev->ParentDevice"));
}else{
if($dev->Cabinet==-1){
header('Location: '.redirect("storageroom.php?dc=$dev->Position"));
}else{
header('Location: '.redirect("cabnavigator.php?cabinetid=$dev->Cabinet"));
}
}
exit;
break; // the exit should handle it
case 'Copy':
$copy=true;
$parent=($dev->ParentDevice)?$dev->ParentDevice:null;
if(!$dev->CopyDevice($parent)){
$copyerr=__("Device did not copy. Error.");
}
break;
case 'Child':
foreach($dev as $prop => $value){
$dev->$prop=null;
}
$dev->ParentDevice=$_REQUEST["ParentDevice"];
// sets install date to today when a new device is being created
$dev->InstallDate=date("m/d/Y");
break;
}
// Can't check the device for rights because it shouldn't exist yet
// but the user could have rights from the cabinet and it is checked above
// when the device object is populated.
}elseif($write && $_POST['action']=='Create'){
// Since the cabinet isn't part of the form for a child device creation
// it's possible to create a new child that doesn't follow the new cabinet designation
// we're creatig a device at this point so look up the parent just in case and match
// the cabinet designations
if($dev->ParentDevice){
$pdev=new Device();
$pdev->DeviceID=$dev->ParentDevice;
$pdev->getDevice();
$dev->Cabinet=$pdev->Cabinet;
}
if($dev->TemplateID>0 && intval($dev->NominalWatts==0)){
$dev->UpdateWattageFromTemplate();
}
$dev->CreateDevice();
$dev->SetTags($tagarray);
updateCustomValues($dev);
// We've, hopefully, successfully created a new device. Force them to the new device page.
header('Location: '.redirect("devices.php?DeviceID=$dev->DeviceID"));
exit;
}
}
/*
* Prepare data for display
*
*/
// Finished updating devices or creating them. Refresh the object with data from the DB
$dev->GetDevice();
// Get any tags associated with this device
$tags=$dev->GetTags();
if(count($tags)>0){
// We have some tags so build the javascript elements we need to create the tags themselves
$taginsert="\t\ttags: {items: ".json_encode($tags)."},\n";
}
// Since a device exists we're gonna need some additional info, but only if it's not a copy
if(!$copy){
// clearing errors for now
$LastWattage=$LastRead=$upTime=0;
$pwrConnection->DeviceID=($dev->ParentDevice>0)?$dev->GetRootDeviceID():$dev->DeviceID;
$pwrCords=$pwrConnection->getPorts();
if($dev->DeviceType=='Switch'){
$linkList=SwitchInfo::getPortStatus($dev->DeviceID);
}elseif($dev->DeviceType=='CDU'){
$pdu->PDUID=$dev->DeviceID;
$pdu->GetPDU();
$lastreading=$pdu->GetLastReading();
$LastWattage=($lastreading)?$lastreading->Wattage:0;
$LastRead=($lastreading)?strftime("%c",strtotime($lastreading->LastRead)):"Never";
}
}
if($dev->ChassisSlots>0 || $dev->RearChassisSlots>0){
$childList=$dev->GetDeviceChildren();
}
if($dev->ParentDevice >0){
$pDev=new Device();
$pDev->DeviceID=$dev->ParentDevice;
$pDev->GetDevice();
$parentList=$pDev->GetParentDevices();
//$cab->CabinetID=$pDev->Cabinet;
//JMGA: changed for multichassis
$cab->CabinetID=$pDev->GetDeviceCabinetID();
$cab->GetCabinet();
$chassis="Chassis";
// This is a child device and if the action of new is set let's assume the
// departmental Owner, primary contact, etc are the same as the parent
if(isset($_POST['action']) && $_POST['action']=='Child'){
$dev->Owner=$pDev->Owner;
$dev->EscalationTimeID=$pDev->EscalationTimeID;
$dev->EscalationID=$pDev->EscalationID;
$dev->PrimaryContact=$pDev->PrimaryContact;
}
}
}
$cab->CabinetID=$dev->Cabinet;
$cab->GetCabinet();
}else{
/*
* Everything below here will get processed when no DeviceID is present
* aka adding a new device
*/
// sets install date to today when a new device is being created
$dev->InstallDate=date("m/d/Y");
}
// We don't want someone accidentally adding a chassis device inside of a chassis slot.
if($dev->ParentDevice>0){
$devarray=array('Server' => __("Server"),
'Appliance' => __("Appliance"),
'Storage Array' => __("Storage Array"),
'Switch' => __("Switch"),
'Chassis' => __("Chassis"),
'Patch Panel' => __("Patch Panel"),
'Sensor' => __("Sensor"),
);
/* If you only have rear slots, don't make the user click Backside, which they forget to do half the time, anyway */
if ( $pDev->ChassisSlots < 1 && $pDev->RearChassisSlots > 0 ) {
$dev->BackSide = 1;
}
}else{
$devarray=array('Server' => __("Server"),
'Appliance' => __("Appliance"),
'Storage Array' => __("Storage Array"),
'Switch' => __("Switch"),
'Chassis' => __("Chassis"),
'Patch Panel' => __("Patch Panel"),
'Physical Infrastructure' => __("Physical Infrastructure"),
'CDU' => __("CDU"),
'Sensor' => __("Sensor"),
);
}
if($config->ParameterArray["mDate"]=="now"){
if($dev->MfgDate <= "1970-01-01"){
$dev->MfgDate=date("Y-m-d");
}
}
if($config->ParameterArray["wDate"]=="now"){
if($dev->WarrantyExpire <= "1970-01-01"){
$dev->WarrantyExpire=date("Y-m-d");
}
}
$portList=DevicePorts::getPortList($dev->DeviceID);
$mediaTypes=MediaTypes::GetMediaTypeList();
$colorCodes=ColorCoding::GetCodeList();
$templateList=$templ->GetTemplateList();
$escTimeList=$escTime->GetEscalationTimeList();
$escList=$esc->GetEscalationList();
$deptList=$Dept->GetDepartmentList();
$templ->TemplateID=$dev->TemplateID;
$templ->GetTemplateByID();
$title=($dev->Label!='')?"$dev->Label :: $dev->DeviceID":__("openDCIM Device Maintenance");
function buildESXtable($DeviceID){
$ESX=new ESX();
$ESX->DeviceID=$DeviceID;
$vmList=$ESX->GetDeviceInventory();
print "\n<div class=\"table border\"><div><div>".__("VM Name")."</div><div>".__("Status")."</div><div>".__("Owner")."</div><div>".__("Primary Contact")."</div><div>".__("Last Updated")."</div></div>\n";
foreach($vmList as $vmRow){
$onOff=(preg_match('/off/i',$vmRow->vmState))?'off':'on';
$Dept=new Department();
$Dept->DeptID=$vmRow->Owner;
if($Dept->DeptID >0){
$Dept->GetDeptByID();
}else{
$Dept->Name=__("Unknown");
}
if ( $vmRow->PrimaryContact > 0 ) {
$con = new People();
$con->PersonID = $vmRow->PrimaryContact;
$con->GetPerson();
$PCName = $con->LastName . ", " . $con->FirstName;
} else {
$PCName = __("Unknown");
}
print "<div><div>$vmRow->vmName</div><div class=\"$onOff\">$vmRow->vmState</div><div><a href=\"updatevmowner.php?vmindex=$vmRow->VMIndex\">$Dept->Name</a></div><div><a href=\"updatevmowner.php?vmindex=$vmRow->VMIndex\">$PCName</a></div><div>$vmRow->LastUpdated</div></div>\n";
}
echo '</div> <!-- END div.table -->';
}
function buildCustomAttributes($template, $device) {
$dcaList=DeviceCustomAttribute::GetDeviceCustomAttributeList();
$tdcaList=$template->CustomValues;
$dcvList=$device->CustomValues;
$customvalues = array();
// pull the "all devices" custom attributes
if(isset($dcaList)) {
foreach($dcaList as $dca) {
if($dca->AllDevices==1) {
$customvalues[$dca->AttributeID]["value"]=$dca->DefaultValue;
$customvalues[$dca->AttributeID]["type"]=$dca->AttributeType;
$customvalues[$dca->AttributeID]["required"]=$dca->Required;
}
}
}
if(isset($tdcaList)) {
// pull the device template level custom attributes (done second so we overwrite all devices)
foreach($tdcaList as $AttributeID=>$tdca) {
$customvalues[$AttributeID]["value"]=$tdca["value"];
$customvalues[$AttributeID]["type"]=$dcaList[$AttributeID]->AttributeType;
$customvalues[$AttributeID]["required"]=$tdca["required"];
}
}
if(isset($dcvList)) {
// pull the values set at this device level if any exist, the assumption being that one of the 2 loops above has already populated the type and required fields
foreach($dcvList as $AttributeID=>$dcv) {
if(array_key_exists($AttributeID, $customvalues)) {
$customvalues[$AttributeID]["value"]=$dcv;
} else {
// this is probably an error, what do?
}
}
}
echo '<div class="table">';
foreach($customvalues as $customkey=>$customdata) {
$inputname = "customvalue[$customkey]";
$validation="";
$cvtype = $customvalues[$customkey]["type"];
if($customvalues[$customkey]["required"]==1 || $cvtype!="string"){
$validation=' class="validate[';
$validationrules=array();
if($customvalues[$customkey]["required"]==1) {
$validationrules[]="required";
}
if($cvtype!="string" && $cvtype != "checkbox"){
$validationrules[]='custom['.$cvtype.']';
}
$validation.=implode(",",$validationrules);
$validation.=']" ';
}
echo '<div>
<div><label for="',$inputname,'">',$dcaList[$customkey]->Label,'</label></div>';
if($cvtype=="checkbox"){
$checked = "";
if($customdata["value"] == "1" || $customdata["value"]=="on"){
$checked = " checked";
}
echo '<div><input type="checkbox" name="',$inputname,'" id="',$inputname,'"',$checked,'></div>';
} else if ($cvtype=="set") {
echo '<div><select name="',$inputname,'" id="',$inputname,'">';
foreach(explode(',',$dcaList[$customkey]->DefaultValue) as $dcaValue){
$selected=($customdata["value"]==$dcaValue)?' selected':'';
print "\n\t<option value=\"$dcaValue\"$selected>$dcaValue</option>";
}
echo '</select></div>';
} else {
echo '<div><input type="text"',$validation,' name="',$inputname,'" id="',$inputname,'" value="',$customdata["value"],'"></div>';
}
echo '</div>';
}
echo '</div>';
}
function updateCustomValues($device) {
$template=new DeviceTemplate();
$template->TemplateID=$device->TemplateID;
$template->GetTemplateByID();
$dcaList=DeviceCustomAttribute::GetDeviceCustomAttributeList();
$tdcaList=$template->CustomValues;
$defaultvalues = array();
if(isset($dcaList)) {
foreach($dcaList as $dca) {
if($dca->AllDevices==1) {
$defaultvalues[$dca->AttributeID]["value"]=$dca->DefaultValue;
$defaultvalues[$dca->AttributeID]["required"]=$dca->Required;
}
}
}
if(isset($tdcaList)) {
foreach($tdcaList as $AttributeID=>$tdca) {
$defaultvalues[$AttributeID]["value"]=$tdca["value"];
$defaultvalues[$AttributeID]["required"]=$tdca["required"];
}
}
$device->DeleteCustomValues();
if(isset($_POST["customvalue"])){
foreach($_POST["customvalue"] as $AttributeID=>$value) {
if(trim($value) != trim($defaultvalues[$AttributeID]["value"])) {
$device->InsertCustomValue($AttributeID, $value);
}
}
}
}
// In the case of a child device we might define this above and in that case we
// need to preserve the flag
$write=(isset($write))?$write:false;
$write=($person->canWrite($cab->AssignedTo))?true:$write;
$write=($dev->Rights=="Write")?true:$write;
?>
<!doctype html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><?php echo $title; ?></title>
<link rel="stylesheet" href="css/inventory.php" type="text/css">
<link rel="stylesheet" href="css/print.css" type="text/css" media="print">
<link rel="stylesheet" href="css/jquery-ui.css" type="text/css">
<link rel="stylesheet" href="css/validationEngine.jquery.css" type="text/css">
<link rel="stylesheet" href="css/jHtmlArea.css" type="text/css">
<style type="text/css"></style>
<!--[if lt IE 9]>
<link rel="stylesheet" href="css/ie.css" type="text/css" />
<![endif]-->
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<script type="text/javascript" src="scripts/jquery-ui.min.js"></script>
<script type="text/javascript" src="scripts/mdetect.js"></script>
<script type="text/javascript" src="scripts/jquery.validationEngine-en.js"></script>
<script type="text/javascript" src="scripts/jquery.validationEngine.js"></script>
<script type="text/javascript" src="scripts/jHtmlArea-0.8.min.js"></script>
<script type="text/javascript" src="scripts/jquery.textext.js"></script>
<script type="text/javascript" src="scripts/common.js"></script>
<SCRIPT type="text/javascript" >
var nextField;
function getScan(fieldName){
var href=window.location.href;
var ptr=href.lastIndexOf("#");
if(ptr>0){
href=href.substr(0,ptr);
}
nextField=fieldName;
window.location.href="zxing://scan/?ret="+escape(href+"#{CODE}");
}