forked from opendcim/openDCIM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
install.php.bak2
1915 lines (1764 loc) · 67.6 KB
/
install.php.bak2
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
$codeversion="3.3";
// Pre-Flight check
$tests=array();
$errors=0;
if (isset($_SERVER['REMOTE_USER'])) {
$tests['Remote User']['state']="good";
$tests['Remote User']['message']='';
}else{
$tests['Remote User']['state']="fail";
$tests['Remote User']['message']='<a href="http://httpd.apache.org/docs/2.2/howto/auth.html">http://httpd.apache.org/docs/2.2/howto/auth.html</a>';
$errors++;
}
if (extension_loaded('mbstring')) {
$tests['mbstring']['state']="good";
$tests['mbstring']['message']='';
}else{
$tests['mbstring']['state']="fail";
$tests['mbstring']['message']='PHP is missing the <a href="http://php.net/mbstring">mbstring extension</a>';
$errors++;
}
if(extension_loaded('gettext')) {
$tests['gettext']['state']="good";
$tests['gettext']['message']='';
}else{
$tests['gettext']['state']="fail";
$tests['gettext']['message']='PHP is missing the <a href="http://php.net/manual/book.gettext.php">Gettext extension</a>. Please install it.';
}
if(extension_loaded('snmp')) {
$tests['snmp']['state']="good";
$tests['snmp']['message']='';
}else{
$tests['snmp']['state']="fail";
$tests['snmp']['message']='PHP is missing the <a href="http://php.net/manual/book.snmp.php">snmp extension</a>. Please install it.';
}
$tests['pdo']['message']='';
if (extension_loaded('PDO')) {
$tests['pdo']['state']="good";
if (count(PDO::getAvailableDrivers())>0) {
$tests['pdodrivers']['message']='Available drivers: '.implode(", ",PDO::getAvailableDrivers());
$tests['pdodrivers']['state']="good";
// pdo is loaded check for the db.inc
if(file_exists("db.inc.php")){
$tests['db.inc']['state']="good";
$tests['db.inc']['message']="db.inc.php has been detected and in the proper place";
require_once("db.inc.php");
// check for strict_trans_tables
if(strpos(@end($dbh->query("select @@global.sql_mode;")->fetch()),'STRICT_TRANS_TABLES') === false){
$tests['strictdb']['state']="good";
$tests['strictdb']['message']='';
}else{
$tests['strictdb']['state']="fail";
$tests['strictdb']['message']='openDCIM does not support STRICT_TRANS_TABLES. The following SQL statement might clear the error for this session. More information can be found <a href="https://github.com/samilliken/openDCIM/issues/457">here</a>.<br><br><i>SET GLOBAL sql_mode = "";</i>';
$errors++;
}
}else{
$tests['db.inc']['state']="fail";
$tests['db.inc']['message']="Please copy db.inc.php-dist to db.inc.php and edit appropriately";
$errors++;
}
}else{
$tests['pdodrivers']['message']='Available drivers: none';
$tests['pdodrivers']['state']="fail";
$errors++;
}
}else{
$tests['pdo']['state']="fail";
$tests['pdo']['message']='openDCIM requires the <a href="http://php.net/manual/pdo.installation.php">PDO extention</a> and you do not appear to have it loaded';
$tests['pdodrivers']['state']="fail";
$tests['pdodrivers']['message']='No PDO drivers have been detected';
$errors++;
}
if (function_exists('json_encode')) {
$tests['json']['state']="good";
$tests['json']['message']='PHP json module detected';
}else{
$tests['json']['state']="fail";
$tests['json']['message']='PHP is missing the <a href="http://php.net/manual/book.json.php">JavaScript Object Notation (JSON) extension</a>. Please install it.';
$errors++;
}
if ($errors > 0) {
echo '<!doctype html><html><head><title>openDCIM :: pre-flight environment sanity check</title><script type="text/javascript" src="scripts/jquery.min.js"></script><script type="text/javascript">$(document).ready(function(){$("tr").each(function(){if($(this).find("td:last-child").text()=="fail"){$(this).addClass("fail");}});});</script><style type="text/css">table{width:80%;border-collapse:collapse;border:3px solid black;}th{text-align:left;text-transform:uppercase;border-right: 1px solid black;}th,td{padding:5px;}tr:nth-child(even){background-color:#d1e1f1;}td:last-child{text-align:center;text-transform:uppercase;border:2px solid;background-color:green;}.fail td:last-child{font-weight: bold;background-color: red;}</style></head><body><h2>Pre-flight environment checks</h2><table>';
foreach($tests as $test => $text){
print "<tr><th>$test</th><td>{$text['message']}</td><td>{$text['state']}</td></tr>";
}
echo '<tr><th>javascript</th><td>Javascript is used heavily for data validation and a more polished user experience.</td><td><script>document.write("good")</script><noscript>fail</noscript></td></tr>
</table>
<p>If you are seeing this page then you must correct any issues shown above before the installer will continue.</p>
</body></html>';
exit;
}
// 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;
}
// 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;
}
// New install so create a user
require_once("customers.inc.php");
$user=new User();
$user->UserID=$_SERVER['REMOTE_USER'];
/* 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. */
$sql="SELECT COUNT(*) AS TotalUsers FROM fac_User;";
$users=$dbh->query($sql)->fetchColumn();
if($users==0){
$user->Name="Default Admin";
foreach($user as $prop => $value){
if($prop!='Name' && $prop!='UserID'){
$user->$prop=true;
}
}
$user->Disabled=false;
$user->CreateUser();
}
// This will be reloading the rights for a new install but for upgrades
// it will be the actual rights load
$user->GetUserRights();
// Re-read the config
$config->Config();
// Check to see if we have any users in the database.
$sth=$dbh->prepare("SELECT * FROM fac_User 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";
exit;
$rightserror=1;
}else{ // so we have users and at least one site admin
require_once("customers.inc.php");
$user=new User();
$user->UserID=$_SERVER['REMOTE_USER'];
$user->GetUserRights();
if(!$user->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.";
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();
}
}
if($upgrade==true){ //If we're doing an upgrade don't call the rest of the installer.
?>
<!doctype html>
<html>
<head>
<title>Upgrade</title>
<style type="text/css">
.error { color: red;}
.success { color: green;}
</style>
</head>
<body>
<?php
upgrade();
if(isset($results)){
date_default_timezone_set($config->ParameterArray['timezone']);
$fh=fopen('install.err', 'a');
fwrite($fh, date("Y-m-d g:i:s a\n"));
foreach($results as $key => $value){
foreach($value as $status => $message){
if($status==1){$class="error";}else{$class="success";}
fwrite($fh, $message);
}
}
fclose($fh);
print "<p>Anything shown here is just a notice. It is not necessarily an error. We will occasionally have to repeat database modifications that will fail and will show here. <b>This is behavior is to be expected</b>. Take note of any errors displayed in red then press F5 to reload this page until it goes to the configuration screen.</p>";
}else{
echo '<p class="success">All is well. Please remove install.php to return to normal functionality</p>';
}
?>
</body>
</html>
<?php
exit;
}
require_once( "facilities.inc.php" );
$dept=new Department();
$dc=new DataCenter();
$cab=new Cabinet();
function BuildFileList(){
$imageselect='<div id="preview"></div><div id="filelist">';
$path='./images';
$dir=scandir($path);
foreach($dir as $i => $f){
if(is_file($path.DIRECTORY_SEPARATOR.$f) && round(filesize($path.DIRECTORY_SEPARATOR.$f) / 1024, 2)>=4 && $f!="serverrack.png" && $f!="gradient.png"){
$imageinfo=getimagesize($path.DIRECTORY_SEPARATOR.$f);
if(preg_match('/^image/i', $imageinfo['mime'])){
$imageselect.="<span>$f</span>\n";
}
}
}
$imageselect.="</div>";
return $imageselect;
}
// AJAX Requests
if(isset($_GET['fl'])){
echo BuildFileList();
exit;
}
if(isset($_POST['fe'])){
echo(is_file($_POST['fe']))?1:0;
exit;
}
if(isset($_POST['cc'])){ // Cable color codes
$col=new ColorCoding();
$col->Name=trim($_POST['cc']);
$col->DefaultNote=trim($_POST['ccdn']);
if(isset($_POST['cid'])){ // If set we're updating an existing entry
$col->ColorID=$_POST['cid'];
if(isset($_POST['original'])){
$col->GetCode();
header('Content-Type: application/json');
echo json_encode($col);
exit;
}
if(isset($_POST['clear']) || isset($_POST['change'])){
$newcolorid=0;
if(isset($_POST['clear'])){
ColorCoding::ResetCode($col->ColorID);
}else{
$newcolorid=$_POST['change'];
ColorCoding::ResetCode($col->ColorID,$newcolorid);
}
$mediatypes=MediaTypes::GetMediaTypeList();
foreach($mediatypes as $mt){
if($mt->ColorID==$col->ColorID){
$mt->ColorID=$newcolorid;
$mt->UpdateType();
}
}
if($col->DeleteCode()){
echo 'u';
}else{
echo 'f';
}
exit;
}
if($col->UpdateCode()){
echo 'u';
}else{
echo 'f';
}
}else{
if($col->CreateCode()){
echo $col->ColorID;
}else{
echo 'f';
}
}
exit;
}
if(isset($_POST['ccused'])){
$count=ColorCoding::TimesUsed($_POST['ccused']);
if($count==0){
$col=new ColorCoding();
$col->ColorID=$_POST['ccused'];
$col->DeleteCode();
}
echo $count;
exit;
}
if(isset($_POST['mt'])){ // Media Types
$mt=new MediaTypes();
$mt->MediaType=trim($_POST['mt']);
$mt->ColorID=$_POST['mtcc'];
if(isset($_POST['mtid'])){ // If set we're updating an existing entry
$mt->MediaID=$_POST['mtid'];
if(isset($_POST['original'])){
$mt->GetType();
header('Content-Type: application/json');
echo json_encode($mt);
exit;
}
if(isset($_POST['clear']) || isset($_POST['change'])){
if(isset($_POST['clear'])){
MediaTypes::ResetType($mt->MediaID);
}else{
$newmediaid=$_POST['change'];
MediaTypes::ResetType($mt->MediaID,$newmediaid);
}
if($mt->DeleteType()){
echo 'u';
}else{
echo 'f';
}
exit;
}
if($mt->UpdateType()){
echo 'u';
}else{
echo 'f';
}
}else{
if($mt->CreateType()){
echo $mt->MediaID;
}else{
echo 'f';
}
}
exit;
}
if(isset($_POST['mtused'])){
$count=MediaTypes::TimesUsed($_POST['mtused']);
if($count==0){
$mt=new MediaTypes();
$mt->MediaID=$_POST['mtused'];
$mt->DeleteType();
}
echo $count;
exit;
}
if(isset($_POST['mtlist'])){
$codeList=MediaTypes::GetMediaTypeList();
$output='<option value=""></option>';
foreach($codeList as $mt){
$output.="<option value=\"$mt->MediaID\">$mt->MediaType</option>";
}
echo $output;
exit;
}
if(isset($_POST['cclist'])){
$codeList=ColorCoding::GetCodeList();
$output='<option value=""></option>';
foreach($codeList as $cc){
$output.="<option value=\"$cc->ColorID\">$cc->Name</option>";
}
echo $output;
exit;
}
// END AJAX Requests
// Configuration Form Submission
if(isset($_REQUEST["confaction"]) && $_REQUEST["confaction"]=="Update"){
foreach($config->ParameterArray as $key=>$value){
if($key=="ClassList"){
$List=explode(", ",$_REQUEST[$key]);
$config->ParameterArray[$key]=$List;
}else{
$config->ParameterArray[$key]=$_REQUEST[$key];
}
}
$config->UpdateConfig();
//Disable all tooltip items and clear the SortOrder
$dbh->query("UPDATE fac_CabinetToolTip SET SortOrder = NULL, Enabled=0;");
if(isset($_POST["tooltip"]) && !empty($_POST["tooltip"])){
foreach($_POST["tooltip"] as $order => $field){
$dbh->query("UPDATE fac_CabinetToolTip SET SortOrder=".intval($order).", Enabled=1 WHERE Field='".addslashes($field)."' LIMIT 1;");
}
}
//Disable all cdu tooltip items and clear the SortOrder
$dbh->exec("UPDATE fac_CDUToolTip SET SortOrder = NULL, Enabled=0;");
if(isset($_POST["cdutooltip"]) && !empty($_POST["cdutooltip"])){
$p=$dbh->prepare("UPDATE fac_CDUToolTip SET SortOrder=:sortorder, Enabled=1 WHERE Field=:field LIMIT 1;");
foreach($_POST["cdutooltip"] as $order => $field){
$p->bindParam(":sortorder",$order);
$p->bindParam(":field",$field);
$p->execute();
}
}
}
// Departments Form Submission
if(isset($_REQUEST['deptid'])&&($_REQUEST['deptid']>0)){
$dept->DeptID = $_REQUEST['deptid'];
$dept->GetDeptByID();
}
if(isset($_REQUEST['deptaction'])&& (($_REQUEST['deptaction']=='Create') || ($_REQUEST['deptaction']=='Update'))){
$dept->DeptID = $_REQUEST['deptid'];
$dept->Name = $_REQUEST['name'];
$dept->ExecSponsor = $_REQUEST['execsponsor'];
$dept->SDM = $_REQUEST['sdm'];
$dept->Classification = $_REQUEST['classification'];
if($_REQUEST['deptaction']=='Create'){
if($dept->Name != '' && $dept->Name != null)
$dept->CreateDepartment();
}else{
$dept->UpdateDepartment();
}
}
$result=$dbh->prepare("SELECT * FROM fac_Department LIMIT 1;");
$result->execute();
if($result->rowCount()==0){ // No departments defined
$nodept="<h3>Create a department</h3>";
$nodeptdrop="readonly";
}else{
$nodept=$nodeptdrop="";
}
// Data Centers Form Submission
if(isset($_REQUEST['dcaction']) && (($_REQUEST['dcaction']=='Create')||($_REQUEST['dcaction']=='Update'))){
$dc->DataCenterID = $_REQUEST['datacenterid'];
$dc->Name = $_REQUEST['name'];
$dc->SquareFootage = $_REQUEST['squarefootage'];
$dc->DeliveryAddress = $_REQUEST['deliveryaddress'];
$dc->Administrator = $_REQUEST['administrator'];
$dc->DrawingFileName = $_REQUEST['drawingfilename'];
if($_REQUEST['dcaction']=='Create'){
$dc->CreateDataCenter();
}else{
$dc->UpdateDataCenter();
}
}
if(isset($_REQUEST['datacenterid']) && $_REQUEST['datacenterid'] >0){
$dc->DataCenterID=$_REQUEST['datacenterid'];
$dc->GetDataCenter();
}
$dcList=$dc->GetDCList();
$result=$dbh->prepare("SELECT * FROM fac_DataCenter LIMIT 1;");
$result->execute();
if($result->rowCount()==0){ // No data centers configured disable cabinets and complete options
$nodc="<h3>Define a data center</h3>";
$nodccab="<h3>You must create a Data Center before you can create cabinets in it.</h3>";
$nodcfield="disabled";