forked from opendcim/openDCIM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.php
1856 lines (1647 loc) · 67.9 KB
/
install.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( "version.php" );
require_once( "preflight.php" );
// Make sure that a db.inc.php has been created
if(!file_exists("db.inc.php")){
print "Please copy db.inc.php-dist to db.inc.php.<br>\nOpen db.inc.php with a text editor and fill in the blanks for user, pass, database, and server.";
exit;
}else{
require_once("db.inc.php");
}
// Functions for upgrade / installing db objects
$successlog="";
function applyupdate ($updatefile){
global $dbh;
//Make sure the upgrade file exists.
if(file_exists($updatefile)){
$file=fopen($updatefile, 'r');
$sql=array();
while(feof($file)===false){
$sql[]=fgets($file);
}
$sqlstring="";
foreach($sql as $key => $value){
// I really need a better way to filter out comments but this works.
if(substr($value,0,1)=='-'){
}else{
$sqlstring.=trim($value);
}
}
fclose($file);
$sql=explode(";",$sqlstring);
unset($sql[count($sql)-1]);
$result=0;
$errormsg = "";
foreach($sql as $key => $value){
// uncomment to debug sql injection
// echo $value."<br>\n";
if(!$dbh->query($value)){
$info=$dbh->errorInfo();
//something broke log it
$errormsg.="$value<br>\n";
$errormsg.=$info[2];
$errormsg.="<br>\n";
$result=1;
}
}
if($result){
if(!isset($errormsg)){
$errormsg="An error has occured while applying $updatefile. Please consult the server logs for more details.<br>\n";
}
}else{
$successlog="$updatefile: Database updates applied.<br>\n";
}
}else{
$errormsg="An update has been unpacked to the openDCIM installation but the database update "$updatefile" is missing.<br><br>\nPlease unpack the archive and try again.";
}
$temp=array();
if(isset($errormsg)){
$temp[1]=$errormsg;
}else{
$temp[0]=$successlog;
}
$message=(isset($errormsg))?$errormsg:$successlog;
$class=(isset($errormsg))?'error':'success';
print "<h1 class=\"$class\">$message</h1>";
return $temp;
}
$upgrade=false;
/* Generic html sanitization routine */
function sanitize($string,$stripall=true){
// Trim any leading or trailing whitespace
$clean=trim($string);
// Convert any special characters to their normal parts
$clean=html_entity_decode($clean,ENT_COMPAT,"UTF-8");
// By default strip all html
$allowedtags=($stripall)?'':'<a><b><i><img><u><br>';
// Strip out the shit we don't allow
$clean=strip_tags($clean, $allowedtags);
// If we decide to strip double quotes instead of encoding them uncomment the
// next line
// $clean=($stripall)?str_replace('"','',$clean):$clean;
// What is this gonna do ?
$clean=filter_var($clean, FILTER_SANITIZE_SPECIAL_CHARS);
// There shoudln't be anything left to escape but wtf do it anyway
$clean=addslashes($clean);
return $clean;
}
function ArraySearchRecursive($Needle,$Haystack,$NeedleKey="",$Strict=false,$Path=array()) {
if(!is_array($Haystack))
return false;
foreach($Haystack as $Key => $Val) {
if(is_array($Val)&&$SubPath=ArraySearchRecursive($Needle,$Val,$NeedleKey,$Strict,$Path)) {
$Path=array_merge($Path,Array($Key),$SubPath);
return $Path;
}elseif((!$Strict&&$Val==$Needle&&$Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))||($Strict&&$Val===$Needle&&$Key==(strlen($NeedleKey)>0?$NeedleKey:$Key))) {
$Path[]=$Key;
return $Path;
}
}
return false;
}
// Check to see if we are doing an upgrade or an install
$result=$dbh->prepare("SHOW TABLES;");
$result->execute();
if($result->rowCount()==0){ // No tables in the DB so try to install.
$results[]=applyupdate("create.sql");
$upgrade=false;
}
/*
v4.0 migrated fac_Users to fac_People we need to adjust for older
installs that need upgrading. The logic has remained nearly the
same but this will support upgrades as well as new installs
*/
$test=$result->fetchAll();
// First test for fac_People, second test for people using non-standard installs with all lower case table names
$usePeople=($result->rowCount()>0 && !ArraySearchRecursive('fac_People',$test))?($result->rowCount()>0 && !ArraySearchRecursive('fac_people',$test))?false:true:true;
// New install so create a user
require_once("classes/People.class.php");
if($usePeople){
$person=new People();
}else{
require_once("installer.userconversion.inc.php");
$person=new User();
}
if(AUTHENTICATION=="Apache"){
$person->UserID=$_SERVER['REMOTE_USER'];
}elseif(AUTHENTICATION=="Oauth" || AUTHENTICATION=="LDAP" || AUTHENTICATION=="Saml"){
$person->UserID=$_SESSION['userid'];
}
/* Check the table to see if there are any users
defined, yet. If not, this is a new install, so
create an admin user (all rights) as the current
user. */
$table=($usePeople)?'fac_People':'fac_User';
$sql="SELECT COUNT(*) AS TotalUsers FROM $table;";
$users=$dbh->query($sql)->fetchColumn();
if($users==0){
$person->Name="Default Admin";
foreach($person as $prop => $value){
if(strstr($prop,"Admin") || strstr($prop,"Access")){
$person->$prop=true;
}
}
$person->Disabled=false;
$person->CreatePerson();
}
// This will be reloading the rights for a new install but for upgrades
// it will be the actual rights load
$person->GetUserRights();
// Re-read the config
$config->Config();
// Check to see if we have any users in the database.
$sth=$dbh->prepare("SELECT * FROM $table WHERE SiteAdmin=1;");
$sth->execute();
if($sth->rowCount()<1){
// no users in the system or no users with site admin rights, either way we're missing the class of people we need
// put stuff here like correcting for a missing site admin
print "There are no users in the database with sufficient privileges to perform this update. Current userid=" . $person->UserID;
exit;
$rightserror=1;
}else{ // so we have users and at least one site admin
require_once("classes/People.class.php");
if(!$person->SiteAdmin){
// dolemite says you aren't an admin so you can't apply the update
print "An update has been applied to the system but the system hasn't been taken out of maintenance mode. Please contact a site Administrator to correct this issue. Current userid=" . $person->UserID;
exit;
}
$rightserror=0;
}
// test for openDCIM version
$result=$dbh->prepare("SELECT Value FROM fac_Config WHERE Parameter='Version' LIMIT 1;");
$result->execute();
if($result->rowCount()==0){// Empty result set means this is either 1.0 or 1.1. Surely the check above caught all 1.0 instances.
$results[]=applyupdate("db-1.1-to-1.2.sql");
$version="1.2";
}else{
$version=$result->fetchColumn();//sets version number
}
// Check the detected version against the code version. Update the current
// code version at the top of this file each time we update.
$upgrade=($codeversion!=$version)?true:false;
function upgrade(){
global $version;
global $config;
global $results;
global $dbh;
global $errormsg;
if($version==""){ // something borked re-apply all database updates and pray for forgiveness
$version="1.2";
}
if($version=="1.2"){ // Do 1.2 to 1.3 Update
$results[]=applyupdate("db-1.2-to-1.3.sql");
$version="1.3";
}
if($version=="1.3"){ // Do 1.3 to 1.4 Update
// Clean the configuration table of any duplicate values that might have been added.
$config->rebuild();
$results[]=applyupdate("db-1.3-to-1.4.sql");
$version="1.4";
}
if($version=="1.4"){ // Do 1.4 to 1.5 Update
// A few of the database changes require some tests to ensure that they will be able to apply.
// Both of these need to return 0 results before we continue or the database schema update will not complete.
$conflicts=0;
$sql="SELECT PDUID, CONCAT(PDUID,'-',PDUPosition) AS KEY1, COUNT(PDUID) AS Count FROM fac_PowerConnection GROUP BY KEY1 HAVING (COUNT(KEY1)>1) ORDER BY PDUID ASC;";
$sth=$dbh->prepare($sql);$sth->execute();
$conflicts+=($sth->rowCount()>0)?1:0;
$sql="SELECT DeviceID, CONCAT(DeviceID,'-',DeviceConnNumber) AS KEY2, COUNT(DeviceID) AS Count FROM fac_PowerConnection GROUP BY KEY2 HAVING (COUNT(KEY2)>1) ORDER BY DeviceID ASC;";
$sth=$dbh->prepare($sql);$sth->execute();
$conflicts+=($sth->rowCount()>0)?1:0;
$sql="SELECT SwitchDeviceID, CONCAT(SwitchDeviceID,'-',SwitchPortNumber) AS KEY1, COUNT(SwitchDeviceID) AS Count FROM fac_SwitchConnection GROUP BY KEY1 HAVING (COUNT(KEY1)>1) ORDER BY SwitchDeviceID ASC;";
$sth=$dbh->prepare($sql);$sth->execute();
$conflicts+=($sth->rowCount()>0)?1:0;
$sql="SELECT SwitchDeviceID, SwitchPortNumber, EndpointDeviceID, EndpointPort, CONCAT(EndpointDeviceID,'-',EndpointPort) AS KEY2, COUNT(EndpointDeviceID) AS Count FROM fac_SwitchConnection GROUP BY KEY2 HAVING (COUNT(KEY2)>1) ORDER BY EndpointDeviceID ASC;";
$sth=$dbh->prepare($sql);$sth->execute();
$conflicts+=($sth->rowCount()>0)?1:0;
require_once("facilities.inc.php");
if($conflicts!=0){
header('Location: '.redirect("conflicts.php"));
exit;
}
$config->rebuild();
$results[]=applyupdate("db-1.4-to-1.5.sql");
$version="1.5";
}
if($version=="1.5"){ // Do the 1.5 to 2.0 Update
// Get a list of all Manufacturers that are duplicated
$sql="SELECT ManufacturerID,Name FROM fac_Manufacturer GROUP BY Name HAVING COUNT(*)>1;";
foreach($dbh->query($sql) as $row){
// Set all devices with that Manufacturer to the ID of just one
$sql="UPDATE fac_DeviceTemplate SET ManufacturerID={$row["ManufacturerID"]} WHERE ManufacturerID IN (SELECT ManufacturerID FROM fac_Manufacturer WHERE Name=\"{$row["Name"]}\");";
$dbh->query($sql);
// Delete all the duplicates other than the one you set everything to
$sql="DELETE FROM fac_Manufacturer WHERE Name=\"{$row["Name"]}\" and ManufacturerID!={$row["ManufacturerID"]};";
$dbh->query($sql);
}
// Repeat for Templates
$sql="SELECT TemplateID,ManufacturerID,Model FROM fac_DeviceTemplate GROUP BY ManufacturerID,Model HAVING COUNT(*)>1;";
foreach($dbh->query($sql) as $row){
$sql="UPDATE fac_Device SET TemplateID={$row["TemplateID"]} WHERE TemplateID IN (SELECT TemplateID FROM fac_DeviceTemplate WHERE ManufacturerID={$row["ManufacturerID"]} AND Model=\"{$row["Model"]}\");";
$dbh->query($sql);
$sql="DELETE FROM fac_DeviceTemplate WHERE ManufacturerID={$row["ManufacturerID"]} AND TemplateID!={$row["TemplateID"]};";
$dbh->query($sql);
}
// And finally, Departments
$sql="SELECT DeptID, Name FROM fac_Department GROUP BY Name HAVING COUNT(*)>1;";
foreach($dbh->query($sql) as $row){
$sql="UPDATE fac_Device SET Owner={$row["DeptID"]} WHERE Owner IN (SELECT DeptID FROM fac_Department WHERE Name=\"{$row["Name"]}\");";
$dbh->query($sql);
// Yes, I know, this may create duplicates
$sql="UPDATE fac_DeptContacts SET DeptID={$row["DeptID"]} WHERE DeptID IN (SELECT DeptID FROM fac_Department WHERE Name=\"{$row["Name"]}\");";
$dbh->query($sql);
$sql="DELETE FROM fac_Department WHERE Name=\"{$row["Name"]}\" AND DeptID!={$row["DeptID"]};";
$dbh->query($sql);
}
// So delete the potential duplicate contact links created in the last step
$sql="SELECT DeptID,ContactID FROM fac_DeptContacts GROUP BY DeptID,ContactID HAVING COUNT(*)>1;";
foreach($dbh->query($sql) as $row){
$sql="DELETE FROM fac_DeptContacts WHERE DeptID={$row["DeptID"]} AND ContactID={$row["ContactID"]};";
$dbh->query($sql);
$sql="INSERT INTO fac_DeptContacts VALUES ({$row["DeptID"]},{$row["ContactID"]});";
$dbh->query($sql);
}
/*
/ Clean up multiple key issues.
/
/ 1. Identify Multiple Keys
/ 2. Remove them
/ 3. Recreate keys based on structure in create.sql
/
*/
$array=array();
$sql="SHOW INDEXES FROM fac_PowerConnection;";
foreach($dbh->query($sql) as $row){
$array[$row["Key_name"]]=1;
}
foreach($array as $key => $garbage){
$sql="ALTER TABLE fac_PowerConnection DROP INDEX $key;";
$dbh->query($sql);
}
$sql="ALTER TABLE fac_PowerConnection ADD UNIQUE KEY PDUID (PDUID,PDUPosition);";
$dbh->query($sql);
$sql="ALTER TABLE fac_PowerConnection ADD UNIQUE KEY DeviceID (DeviceID,DeviceConnNumber);";
$dbh->query($sql);
// Just removing keys from fac_CabinetAudit
$array=array();
$sql="SHOW INDEXES FROM fac_CabinetAudit;";
foreach($dbh->query($sql) as $row){
$array[$row["Key_name"]]=1;
}
foreach($array as $key => $garbage){
$sql="ALTER TABLE fac_CabinetAudit DROP INDEX $key;";
$dbh->query($sql);
}
$array=array();
$sql="SHOW INDEXES FROM fac_Department;";
foreach($dbh->query($sql) as $row){
$array[$row["Key_name"]]=1;
}
foreach($array as $key => $garbage){
$sql="ALTER TABLE fac_Department DROP INDEX $key;";
$dbh->query($sql);
}
$sql="ALTER TABLE fac_Department ADD PRIMARY KEY (DeptID);";
$dbh->query($sql);
$sql="ALTER TABLE fac_Department ADD UNIQUE KEY Name (Name);";
$dbh->query($sql);
$config->rebuild();
$results[]=applyupdate("db-1.5-to-2.0.sql");
$version="2.0";
}
if($version=="2.0"){
$sql="select InputAmperage from fac_PowerDistribution limit 1";
// See if the field exists - some people have manually added the missing one already, so we can't add what's already there
if(!$dbh->query($sql)){
// if(mysql_errno($facDB)==1054){
$sql="ALTER TABLE fac_PowerDistribution ADD COLUMN InputAmperage INT(11) NOT NULL AFTER PanelPole";
$dbh->query($sql);
}
$sql='UPDATE fac_Config SET Value="2.0.1" WHERE Parameter="Version"';
$dbh->query($sql);
$version="2.0.1";
}
if($version=="2.0.1"){
// Get a list of all Manufacturers that are duplicated
$sql="SELECT ManufacturerID,Name FROM fac_Manufacturer GROUP BY Name HAVING COUNT(*)>1;";
foreach($dbh->query($sql) as $row){
// Set all devices with that Manufacturer to the ID of just one
$sql="UPDATE fac_DeviceTemplate SET ManufacturerID={$row["ManufacturerID"]} WHERE ManufacturerID IN (SELECT ManufacturerID FROM fac_Manufacturer WHERE Name=\"{$row["Name"]}\");";
$dbh->query($sql);
// Delete all the duplicates other than the one you set everything to
$sql="DELETE FROM fac_Manufacturer WHERE Name=\"{$row["Name"]}\" and ManufacturerID!={$row["ManufacturerID"]};";
$dbh->query($sql);
}
// Repeat for Templates
$sql="SELECT TemplateID,ManufacturerID,Model FROM fac_DeviceTemplate GROUP BY ManufacturerID,Model HAVING COUNT(*)>1;";
foreach($dbh->query($sql) as $row){
$sql="UPDATE fac_Device SET TemplateID={$row["TemplateID"]} WHERE TemplateID IN (SELECT TemplateID FROM fac_DeviceTemplate WHERE ManufacturerID={$row["ManufacturerID"]} AND Model=\"{$row["Model"]}\");";
$dbh->query($sql);
$sql="DELETE FROM fac_DeviceTemplate WHERE ManufacturerID={$row["ManufacturerID"]} AND TemplateID!={$row["TemplateID"]};";
$dbh->query($sql);
}
// Clean up multiple indexes in fac_Department
$array=array();
$sql="SHOW INDEXES FROM fac_Department;";
foreach($dbh->query($sql) as $row){
$array[$row["Key_name"]]=1;
}
foreach($array as $key => $garbage){
$sql="ALTER TABLE fac_Department DROP INDEX $key;";
$dbh->query($sql);
}
$sql="ALTER TABLE fac_Department ADD PRIMARY KEY (DeptID);";
$dbh->query($sql);
$sql="ALTER TABLE fac_Department ADD UNIQUE KEY Name (Name);";
$dbh->query($sql);
// Clean up multiple indexes in fac_DeviceTemplate
$array=array();
$sql="SHOW INDEXES FROM fac_DeviceTemplate;";
foreach($dbh->query($sql) as $row){
$array[$row["Key_name"]]=1;
}
foreach($array as $key => $garbage){
$sql="ALTER TABLE fac_Department DROP INDEX $key;";
$dbh->query($sql);
}
$sql="ALTER TABLE fac_DeviceTemplate ADD PRIMARY KEY (TemplateID);";
$dbh->query($sql);
$sql="ALTER TABLE fac_DeviceTemplate ADD UNIQUE KEY ManufacturerID (ManufacturerID,Model);";
$dbh->query($sql);
// Apply SQL Updates
$results[]=applyupdate("db-2.0-to-2.1.sql");
// Add new field for the ConnectionID
$dbh->query('ALTER TABLE fac_SwitchConnection ADD ConnectionID INT NULL DEFAULT NULL;');
$sql="SELECT * FROM fac_SwitchConnection;";
foreach($dbh->query($sql) as $row){
$insert="INSERT INTO fac_DevicePorts VALUES (NULL , '{$row['EndpointDeviceID']}', '{$row['EndpointPort']}', NULL , '{$row['Notes']}');";
$dbh->query($insert);
$update="UPDATE fac_SwitchConnection SET ConnectionID='".$dbh->lastInsertId()."' WHERE EndpointDeviceID='{$row['EndpointDeviceID']}' AND EndpointPort='{$row['EndpointPort']}';";
$dbh->query($update);
}
// Clear eany old primary key information
$dbh->query('ALTER TABLE fac_SwitchConnection DROP PRIMARY KEY;');
// Ensure new ConnectionID is unique
$dbh->query('ALTER TABLE fac_SwitchConnection ADD UNIQUE(ConnectionID);');
// Rebuild the config table just in case. I dunno gremlins.
$config->rebuild();
$version="2.1";
}
if($version=="2.1"){
// First apply the schema updates needed.
$results[]=applyupdate("db-2.1-to-3.0.sql");
print "Update blade devices for new front/rear tracking method<br>\n";
$sql="UPDATE fac_Device SET BackSide=1, ChassisSlots=0 WHERE ChassisSlots=1 AND ParentDevice>0;";
$dbh->query($sql);
// Port conversion
$numports=$dbh->query('SELECT SUM(Ports) + (SELECT SUM(Ports) FROM fac_Device WHERE DeviceType="Patch Panel") as TotalPorts, COUNT(DeviceID) as Devices FROM fac_Device')->fetch();
print "Creating {$numports['TotalPorts']} ports for {$numports['Devices']} devices. <b>THIS MAY TAKE A WHILE</b><br>\n";
// Retrieve a list of all devices and make ports for them.
$sql='SELECT DeviceID,Ports,DeviceType from fac_Device WHERE
DeviceType!="Physical Infrastructure" AND Ports>0;';
$errors=array();
$ports=array();
foreach($dbh->query($sql) as $row){
for($x=1;$x<=$row['Ports'];$x++){
// Create a port for every device
$ports[$row['DeviceID']][$x]['Label']=$x;
if($row['DeviceType']=='Patch Panel'){
// Patch panels needs rear ports as well
$ports[$row['DeviceID']][-$x]['Label']="Rear $x";
}
}
}
$findswitch=$dbh->prepare('SELECT * FROM fac_SwitchConnection WHERE EndpointDeviceID=:deviceid ORDER BY EndpointPort ASC;');
foreach($ports as $deviceid => $port){
$findswitch->execute(array(':deviceid' => $deviceid));
$defined=$findswitch->fetchAll();
foreach($defined as $row){
// Weed out any port numbers that have been defined outside the range of
// valid ports for the device
if(isset($ports[$deviceid][$row['EndpointPort']])){
// Device Ports
$ports[$deviceid][$row['EndpointPort']]['Notes']=$row['Notes'];
$ports[$deviceid][$row['EndpointPort']]['Connected Device']=$row['SwitchDeviceID'];
$ports[$deviceid][$row['EndpointPort']]['Connected Port']=$row['SwitchPortNumber'];
// Switch Ports
$ports[$row['SwitchDeviceID']][$row['SwitchPortNumber']]['Notes']=$row['Notes'];
$ports[$row['SwitchDeviceID']][$row['SwitchPortNumber']]['Connected Device']=$row['EndpointDeviceID'];
$ports[$row['SwitchDeviceID']][$row['SwitchPortNumber']]['Connected Port']=$row['EndpointPort'];
}else{
// Either display this as a log item later or possibly backfill empty
// ports with this data
$errors[$deviceid][$row['EndpointPort']]['Notes']=$row['Notes'];
$errors[$deviceid][$row['EndpointPort']]['Connected Device']=$row['SwitchDeviceID'];
$errors[$deviceid][$row['EndpointPort']]['Connected Port']=$row['SwitchPortNumber'];
}
}
}
$findpatch=$dbh->prepare('SELECT * FROM fac_PatchConnection WHERE FrontEndpointDeviceID=:deviceid ORDER BY FrontEndpointPort ASC;');
foreach($ports as $deviceid => $port){
$findpatch->execute(array(':deviceid' => $deviceid));
$defined=$findpatch->fetchAll();
foreach($defined as $row){
// Weed out any port numbers that have been defined outside the range of
// valid ports for the device
if(isset($ports[$deviceid][$row['FrontEndpointPort']])){
// Connect the device to the panel
$ports[$deviceid][$row['FrontEndpointPort']]['Notes']=$row['FrontNotes'];
$ports[$deviceid][$row['FrontEndpointPort']]['Connected Device']=$row['PanelDeviceID'];
$ports[$deviceid][$row['FrontEndpointPort']]['Connected Port']=$row['PanelPortNumber'];
// Connect the panel to the device
$ports[$row['PanelDeviceID']][$row['PanelPortNumber']]['Connected Device']=$row['FrontEndpointDeviceID'];
$ports[$row['PanelDeviceID']][$row['PanelPortNumber']]['Connected Port']=$row['FrontEndpointPort'];
$ports[$row['PanelDeviceID']][$row['PanelPortNumber']]['Notes']=$row['FrontNotes'];
}else{
// Either display this as a log item later or possibly backfill empty
// ports with this data
$errors[$deviceid][$row['FrontEndpointPort']]['Notes']=$row['FrontNotes'];
$errors[$deviceid][$row['FrontEndpointPort']]['Connected Device']=$row['PanelDeviceID'];
$errors[$deviceid][$row['FrontEndpointPort']]['Connected Port']=$row['PanelPortNumber'];
}
}
}
foreach($dbh->query('SELECT * FROM fac_PatchConnection;') as $row){
// Read all the patch connections again to get the rear connection info
$ports[$row['RearEndpointDeviceID']][-$row['RearEndpointPort']]['Connected Device']=$row['PanelDeviceID'];
$ports[$row['RearEndpointDeviceID']][-$row['RearEndpointPort']]['Connected Port']=-$row['PanelPortNumber'];
$ports[$row['RearEndpointDeviceID']][-$row['RearEndpointPort']]['Notes']=$row['RearNotes'];
$ports[$row['PanelDeviceID']][-$row['PanelPortNumber']]['Connected Device']=$row['RearEndpointDeviceID'];
$ports[$row['PanelDeviceID']][-$row['PanelPortNumber']]['Connected Port']=-$row['RearEndpointPort'];
$ports[$row['PanelDeviceID']][-$row['PanelPortNumber']]['Notes']=$row['RearNotes'];
}
// Backfill the extra data
foreach($errors as $deviceid => $row){
$numPorts=count($ports[$deviceid])+1;
foreach($row as $portnum => $port){
for($n=1;$n<$numPorts;$n++){
if(!isset($ports[$deviceid][$n]['Notes'])){
$ports[$deviceid][$n]=$port;
// connect up the other side as well
$ports[$port['Connected Device']][$port['Connected Port']]['Connected Device']=$deviceid;
$ports[$port['Connected Device']][$port['Connected Port']]['Connected Port']=$n;
$ports[$port['Connected Device']][$port['Connected Port']]['Notes']=$port['Notes'];
unset($errors[$deviceid][$portnum]); // Remove it from the backfill data
break;
}
}
}
}
$incdataports=$dbh->prepare('UPDATE fac_Device SET Ports=:n WHERE DeviceID=:deviceid;');
// Anything left in $errors now is an extra port that exists outside the number of designated deviceports.
foreach($errors as $deviceid => $row){
foreach($row as $portnum => $port){
$n=count($ports[$deviceid])+1;
$ports[$deviceid][]=$port;
// connect up the other side as well, $n will give us the new port number
// since it is outside the defined range for the device
$ports[$port['Connected Device']][$port['Connected Port']]['Connected Device']=$deviceid;
$ports[$port['Connected Device']][$port['Connected Port']]['Connected Port']=$n;
$ports[$port['Connected Device']][$port['Connected Port']]['Notes']=$port['Notes'];
// Update the number of ports on this device to match the corrected value
$incdataports->execute(array(":n"=>$n,":deviceid"=>$deviceid));
unset($errors[$deviceid][$portnum]); // Remove it from the backfill data
}
}
$n=1; $insertsql=''; $insertlimit=100;
$insertprogress=100/($numports['TotalPorts']/$insertlimit);
$insertprogress=(intval($insertprogress)>0)?intval($insertprogress):1; // if this is gonna do more than 100 inserts we might have issues
echo "<br>\nConversion process: <br>\n<table style=\"border: 1px solid black; border-collapse: collapse; width: 100%;\"><tr>";flush();
// All the ports should be in the array now, use the prepared statement to load them all
foreach($ports as $deviceid => $row){
foreach($row as $portnum => $port){
$null=null;$blank="";
$cdevice=(isset($port['Connected Device']))?$port['Connected Device']:'NULL';
$cport=(isset($port['Connected Port']))?$port['Connected Port']:'NULL';
$notes=(isset($port['Notes']))?$port['Notes']:'';
$insertsql.="($deviceid,$portnum,\"\",0,0,\"\",$cdevice,$cport,\"$notes\")";
if($n%$insertlimit!=0){
$insertsql.=" ,";
}else{
$dbh->exec('INSERT INTO fac_Ports VALUES'.$insertsql);
$insertsql='';
print "<td width=\"$insertprogress%\" style=\"background-color: green\"> </td>";
flush(); // attempt to update the progress as this goes on.
}
++$n;
}
}
//do one last insert
$insertsql=substr($insertsql, 0, -1);// shave off that last comma
$dbh->exec('INSERT INTO fac_Ports VALUES'.$insertsql);
echo "</tr></table>";
print "<br>\nPort conversion complete.<br>\n";
// Rebuild the config table just in case.
$config->rebuild();
$version="3.0";
}
if($version=="3.0"){
// First apply the schema updates needed.
$results[]=applyupdate("db-3.0-to-3.1.sql");
// Rebuild the config table just in case.
$config->rebuild();
$version="3.1";
}
if($version=="3.1"){
// First apply the schema updates needed.
$results[]=applyupdate("db-3.1-to-3.2.sql");
// Rebuild the config table just in case.
$config->rebuild();
$version="3.2";
}
if($version=="3.2"){
// First apply the schema updates needed.
$results[]=applyupdate("db-3.2-to-3.3.sql");
// Rebuild the config table just in case.
$config->rebuild();
$version="3.3";
}
if($version=="3.3"){
// First apply the schema updates needed.
$results[]=applyupdate("db-3.3-to-4.0.sql");
// Rebuild the config table just in case.
$config->rebuild();
// We added in some new config items and one of them is referenced in misc.
// Reload the config;
$config->Config();
// We have several things to convert this time around.
// Bring up the rest of the classes
require_once("facilities.inc.php");
// People conversion
$p=new People();
$c=new Contact();
$u=new User();
$plist=$p->GetUserList();
// Check if we have an empty fac_People table then merge if that's the case
if(sizeof($plist)==0){
$clist=$c->GetContactList();
foreach( $clist as $tmpc ) {
foreach($tmpc as $prop => $val){
$p->$prop=$val;
}
// we're keeping the Contact ID so assign it to the PersonID
$p->PersonID=$tmpc->ContactID;
$u->UserID=$p->UserID;
$u->GetUserRights();
foreach($u as $prop => $val){
$p->$prop=$val;
}
// This shouldn't be necessary but...
$p->MakeSafe();
$sql="INSERT INTO fac_People SET PersonID=$p->PersonID, UserID=\"$p->UserID\",
AdminOwnDevices=$p->AdminOwnDevices, ReadAccess=$p->ReadAccess,
WriteAccess=$p->WriteAccess, DeleteAccess=$p->DeleteAccess,
ContactAdmin=$p->ContactAdmin, RackRequest=$p->RackRequest,
RackAdmin=$p->RackAdmin, SiteAdmin=$p->SiteAdmin, Disabled=$p->Disabled,
LastName=\"$p->LastName\", FirstName=\"$p->FirstName\",
Phone1=\"$p->Phone1\", Phone2=\"$p->Phone2\", Phone3=\"$p->Phone3\",
Email=\"$p->Email\";";
$dbh->query($sql);
}
$ulist=$u->GetUserList();
foreach($ulist as $tmpu){
/* This time around we have to see if the User is already in the fac_People table */
$p->UserID=$tmpu->UserID;
if(!$p->GetPersonByUserID()){
foreach($tmpu as $prop => $val){
$p->$prop=$val;
}
// Names have changed formats between the user table and the people table
$p->LastName=$tmpu->Name;
$p->CreatePerson();
}
}
}
// END - People conversion
// CDU template conversion, to be done prior to device conversion
/*
I made a poor asumption on the initial build of this that we'd always have fewer
CDU templates than device templates. We're seeing an overlap conversion that is
screwing the pooch. This will find the highest template id from the two sets then
we'll jump the line on the device_template id's and get them lined up.
*/
$sql="SELECT TemplateID FROM fac_CDUTemplate UNION SELECT TemplateID FROM
fac_DeviceTemplate ORDER BY TemplateID DESC LIMIT 1;";
$baseid=$dbh->query($sql)->fetchColumn();
class PowerTemplate extends DeviceTemplate {
function CreateTemplate($templateid=null){
global $dbh;
$this->MakeSafe();
$sqlinsert=(is_null($templateid))?'':" TemplateID=$templateid,";
$sql="INSERT INTO fac_DeviceTemplate SET ManufacturerID=$this->ManufacturerID,
Model=\"$this->Model\", Height=$this->Height, Weight=$this->Weight,
Wattage=$this->Wattage, DeviceType=\"$this->DeviceType\",
SNMPVersion=\"$this->SNMPVersion\", PSCount=$this->PSCount,
NumPorts=$this->NumPorts, Notes=\"$this->Notes\",
FrontPictureFile=\"$this->FrontPictureFile\",
RearPictureFile=\"$this->RearPictureFile\",$sqlinsert
ChassisSlots=$this->ChassisSlots, RearChassisSlots=$this->RearChassisSlots;";
if(!$dbh->exec($sql)){
error_log( "SQL Error: " . $sql );
return false;
}else{
$this->TemplateID=$dbh->lastInsertId();
(class_exists('LogActions'))?LogActions::LogThis($this):'';
$this->MakeDisplay();
return true;
}
}
static function Convert($row){
$ct=new stdClass();
$ct->TemplateID=$row["TemplateID"];
$ct->ManufacturerID=$row["ManufacturerID"];
$ct->Model=$row["Model"];
$ct->PSCount=$row["NumOutlets"];
$ct->SNMPVersion=$row["SNMPVersion"];
return $ct;
}
}
$converted=array(); //index old id, value new id
$sql="SELECT * FROM fac_CDUTemplate;";
foreach($dbh->query($sql) as $cdutemplate){
$ct=PowerTemplate::Convert($cdutemplate);
$dt=new PowerTemplate();
$dt->TemplateID=++$baseid;
$dt->ManufacturerID=$ct->ManufacturerID;
$dt->Model="CDU $ct->Model";
$dt->PSCount=$ct->PSCount;
$dt->DeviceType="CDU";
$dt->SNMPVersion=$ct->SNMPVersion;
$dt->CreateTemplate($dt->TemplateID);
$converted[$ct->TemplateID]=$dt->TemplateID;
}
// Update all the records with their new templateid
foreach($converted as $oldid => $newid){
$dbh->query("UPDATE fac_CDUTemplate SET TemplateID=$newid WHERE TemplateID=$oldid;");
$dbh->query("UPDATE fac_PowerDistribution SET TemplateID=$newid WHERE TemplateID=$oldid");
}
// END - CDU template conversion
// Store a list of existing CDU ids and their converted DeviceID
$ConvertedCDUs=array();
// Store a list of the cdu template ids and the number of power connections they support
$CDUTemplates=array();
// List of ports we are going to create for every device in the system
$PowerPorts=array();
// These should only apply to me but the possibility exists
$PreNamedPorts=array();
class PowerDevice extends Device {
/*
to be efficient we don't want to create ports right now so we're extending
the class to override the create function
*/
function CreateDevice(){
global $dbh;
$this->MakeSafe();
$this->Label=transform($this->Label);
$this->SerialNo=transform($this->SerialNo);
$this->AssetTag=transform($this->AssetTag);
$sql="INSERT INTO fac_Device SET Label=\"$this->Label\", SerialNo=\"$this->SerialNo\", AssetTag=\"$this->AssetTag\",
PrimaryIP=\"$this->PrimaryIP\", SNMPCommunity=\"$this->SNMPCommunity\", Hypervisor=$this->Hypervisor, Owner=$this->Owner,
EscalationTimeID=$this->EscalationTimeID, EscalationID=$this->EscalationID, PrimaryContact=$this->PrimaryContact,
Cabinet=$this->Cabinet, Position=$this->Position, Height=$this->Height, Ports=$this->Ports,
FirstPortNum=$this->FirstPortNum, TemplateID=$this->TemplateID, NominalWatts=$this->NominalWatts,
PowerSupplyCount=$this->PowerSupplyCount, DeviceType=\"$this->DeviceType\", ChassisSlots=$this->ChassisSlots,
RearChassisSlots=$this->RearChassisSlots,ParentDevice=$this->ParentDevice,
MfgDate=\"".date("Y-m-d", strtotime($this->MfgDate))."\",
InstallDate=\"".date("Y-m-d", strtotime($this->InstallDate))."\", WarrantyCo=\"$this->WarrantyCo\",
WarrantyExpire=\"".date("Y-m-d", strtotime($this->WarrantyExpire))."\", Notes=\"$this->Notes\",
Reservation=$this->Reservation, HalfDepth=$this->HalfDepth, BackSide=$this->BackSide;";
if(!$dbh->exec($sql)){
$info=$dbh->errorInfo();
error_log( "PDO Error: {$info[2]} SQL=$sql" );
return false;
}
$this->DeviceID=$dbh->lastInsertId();
(class_exists('LogActions'))?LogActions::LogThis($this):'';
return $this->DeviceID;
}
}
// Create new devices from existing CDUs
$sql="SELECT * FROM fac_PowerDistribution;";
foreach($dbh->query($sql) as $row){
$dev=new PowerDevice();
$dev->Label=$row['Label'];
$dev->Cabinet=$row['CabinetID'];
$dev->TemplateID=$row['TemplateID'];
$dev->PrimaryIP=$row['IPAddress'];
$dev->SNMPCommunity=$row['SNMPCommunity'];
$dev->Position=0;
$dev->Height=0;
$dev->Ports=1;
if(!isset($CDUTemplates[$dev->TemplateID])){
$CDUTemplates[$dev->TemplateID]=$dbh->query("SELECT NumOutlets FROM fac_CDUTemplate WHERE TemplateID=$dev->TemplateID LIMIT 1;")->fetchColumn();
}
$dev->PowerSupplyCount=$CDUTemplates[$dev->TemplateID];
$dev->PowerSupplyCount;
$dev->DeviceType='CDU';
$ConvertedCDUs[$row['PDUID']]=$dev->CreateDevice();
}
// Create a list of all ports that we need to create, no need to look at children or any device with no defined power supplies
$sql="SELECT DeviceID, PowerSupplyCount FROM fac_Device WHERE ParentDevice=0 AND PowerSupplyCount>0;";
foreach($dbh->query($sql) as $row){
for($x=1;$x<=$row['PowerSupplyCount'];$x++){
$PowerPorts[$row['DeviceID']][$x]['label']=$x;
}
}
function workdamnit($numeric=true,&$PreNamedPorts,&$PowerPorts,&$ConvertedCDUs){
// a PDUID of 0 is considered an error, data fragment, etc. Fuck em, not dealing with em.
global $dbh;
$sql="SELECT * FROM fac_PowerConnection;";
foreach($dbh->query($sql) as $row){
// something is going stupid so assign everythign to variables
$pduid=intval($row['PDUID']);
$pdupos=$row['PDUPosition'];
$devid=intval($row['DeviceID']);
$devcon=$row['DeviceConnNumber'];
$newpduid=$ConvertedCDUs[$pduid];
$port='';
if(is_numeric($pdupos) && $numeric && $pduid>0){
$port=$pdupos;
}elseif(!is_numeric($pdupos) && !$numeric && $pduid>0){
$newPDUID=$newpduid;
if(!isset($PreNamedPorts[$newPDUID][$pdupos])){
// Move the array pointer to the end of the ports array
end($PowerPorts[$newPDUID]);
$max=key($PowerPorts[$newPDUID]);
++$max;
// Create a new port for the named port, this will likely extend past the valid amount of ports on the device.
$PowerPorts[$newPDUID][$max]['label']=$pdupos;
// Store a pointer between the name and new port index
$PreNamedPorts[$newPDUID][$pdupos]=$max;
}
$port=$PreNamedPorts[$newPDUID][$pdupos];
}
if((is_numeric($pdupos) && $numeric) || (!is_numeric($pdupos) && !$numeric) && $pduid>0){
// Create primary connections
$PowerPorts[$devid][$devcon]['ConnectedDeviceID']=$newpduid;
$PowerPorts[$devid][$devcon]['ConnectedPort']=$port;
// Create reverse of primary
$PowerPorts[$newpduid][$port]['ConnectedDeviceID']=$devid;
$PowerPorts[$newpduid][$port]['ConnectedPort']=$devcon;
}
}
}
// We need to get a list of all existing power connections
workdamnit(true,$PreNamedPorts,$PowerPorts,$ConvertedCDUs); // First time through setting up all numeric ports
workdamnit(false,$PreNamedPorts,$PowerPorts,$ConvertedCDUs); // Run through again but this time only deal with named ports and append them to the end of the numeric
/*
* Debug Info
print "Converted CDUs:\n<br>";
print_r($ConvertedCDUs);
print "Port list:\n<br>";
print_r($PowerPorts);
print "SQL entries:\n<br>";
*/
$n=1; $insertsql=''; $insertlimit=100;
foreach($PowerPorts as $DeviceID => $PowerPort){
foreach($PowerPort as $PortNum => $PortDetails){
$label=(isset($PortDetails['label']))?$PortDetails['label']:$PortNum;
$cdevice=(isset($PortDetails['ConnectedDeviceID']))?$PortDetails['ConnectedDeviceID']:'NULL';
$cport=(isset($PortDetails['ConnectedPort']))?$PortDetails['ConnectedPort']:'NULL';
$insertsql.="($DeviceID,$PortNum,\"$label\",$cdevice,$cport,\"\")";
if($n%$insertlimit!=0){
$insertsql.=" ,";
}else{
$dbh->exec('INSERT INTO fac_PowerPorts VALUES'.$insertsql);
// Debug for sql
// print "$insertsql\n\n<br><br>";
// print_r($dbh->errorInfo());
$insertsql='';
}
$n++;
}
}
//do one last insert
$insertsql=substr($insertsql, 0, -1);// shave off that last comma
$dbh->exec('INSERT INTO fac_PowerPorts VALUES'.$insertsql);
// Debug for sql
// print "$insertsql\n\n<br><br>";
// print_r($dbh->errorInfo());
// Update all the records with their new deviceid
foreach($ConvertedCDUs as $oldid => $newid){
$dbh->query("UPDATE fac_PowerDistribution SET PDUID = '$newid' WHERE PDUID=$oldid;");
}
// Since we moved SNMPVersion out of the subtemplates and into the main one, we need one last cleanup
$st = $dbh->prepare( "select * from fac_DeviceTemplate where DeviceType='CDU'" );
$st->execute();
$up = $dbh->prepare( "update fac_Device set SNMPVersion=:SNMPVersion where TemplateID=:TemplateID" );
while ( $row = $st->fetch() ) {
$up->execute( array( ":SNMPVersion"=>$row["SNMPVersion"], ":TemplateID"=>$row["TemplateID"] ) );
}
// END - CDU template conversion, to be done prior to device conversion
// Sensor template conversion
// Step one - convert individual SensorTemplates into just Templates
$s = $dbh->prepare( "select * from fac_SensorTemplate" );
$s->execute();
while ( $row = $s->fetch() ) {
// Create fresh instances
$st = new SensorTemplate();
$dt = new DeviceTemplate();
$dt->ManufacturerID = $row["ManufacturerID"];
$dt->Model = $row["Model"];
$dt->Height = 0;
$dt->Weight = 0;
$dt->Wattage = 0;
$dt->DeviceType = "Sensor";
$dt->PSCount = 0;
$dt->NumPorts = 0;
$dt->Notes = "Converted from version 3.3 format.";
$dt->FrontPictureFile = '';
$dt->RearPictureFile = '';
$dt->ChassisSlots = 0;
$dt->RearChassisSlots = 0;
$dt->CreateTemplate();
// The DeviceTemplate::CreateTemplate() method created a new SensorTemplate already
if ( $dt->TemplateID < 1 ) {
error_log( "DeviceTemplate creation failed." );
} else {
$st->TemplateID = $dt->TemplateID;
$st->GetTemplate();
$st->SNMPVersion = $row["SNMPVersion"];
$st->TemperatureOID = $row["TemperatureOID"];
$st->HumidityOID = $row["HumidityOID"];
$st->TempMultiplier = $row["TempMultiplier"];
$st->HumidityMultiplier = $row["HumidityMultiplier"];
$st->mUnits = $row["mUnits"];
$st->UpdateTemplate();