forked from opendcim/openDCIM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
report_asset_Excel.php
1629 lines (1532 loc) · 55.8 KB
/
report_asset_Excel.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
/**
* This is a library to create an Excel file with the information on all devices
* and cabinets in all data centers serialized.
*
* With this library an Excel file is create which contains a header worksheet,
* a worksheet with the data center statistics, a worksheet with the serialized
* device information and a worksheet with the serialized cabinet information.
*
* Be aware that the creation of an Excel file requires lots of CPU and memory
* resources, e.g. depending on the number of objects managed it and your CPU
* power available it can be likely 3 minutes or more runtime and up to 400MB
* memory.
*
*/
require_once 'db.inc.php';
require_once 'facilities.inc.php';
// TODO: Potentially sorting of rack inventory might need to be done not
// according to the data center ID but to the names
// Error reporting
error_reporting(E_ALL);
ini_set('memory_limit', '840M');
ini_set('max_execution_time', '0');
set_include_path(get_include_path().PATH_SEPARATOR.__DIR__.'/PHPExcel');
require 'PHPExcel.php';
require 'PHPExcel/Writer/Excel2007.php';
// Configuration variables.
// Properties of the document and worksheets.
$DProps = array(
'Doc' => array(
'version' => 1.0,
'Subject' => __('Asset Report'),
'Description' => __('Data Center Statistics on all data centers assets.'),
'Title' => __('Data Center Statistics'),
'Keywords' => __('datacenter report assets statistic'),
'PageSize' => $config->ParameterArray['PageSize'],
'User' => $user->Name,
'UserID' => $user->UserID
),
'Front Page' => array(
'Title' => '&L&B' . __('Notes on DC Statistics') . '&R&A',
'FillColor' => 'DCE6F1',
'HeadingFontColor' => '000000',
'HeaderRange' => 'A1:B2',
'HeaderHeight' => 60,
'Border color' => '95B3D7',
'Logo Name' => __('Logo Name'),
'Logo Description' => __('Logo Description'),
'PageSize' => $config->ParameterArray['PageSize'],
'Orientation' => PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT,
'Columns' => array(
array('', '', null, null),
array('', '', null, null)
),
'remarks' => array(
__('● This is the combined report on all data center assets. It '
. 'contains the list of all devices and a list of all cabinets.'),
__('● Using Excel\'s pivot capabilities many different anaylsis and '
. 'statistics can be performed.'),
__('● The terms \'cabinet\' and \'rack\' are used interchangeable.'),
__('● For user who have only the \'Admin Own Devices\' right the report '
. 'is limited to the cabinets which are owned by this department.'),
__('● The \'DC Statistics\' page is only generated for users who are '
. 'not limited to \'Admin Own Devices\'.'),
__('● For a child device the column \'Parent Device\' shows the parent '
. 'device otherwise it is empty. A child devices is e.g. a '
. 'blade server.'),
__('● The \'Position\' for a child device is the slot position within '
. 'in the parent device.'),
__('● \'Half Depth\' contains a value \'front\' or \'rear\' only if the '
. 'device is of half depth in which case this indicates the '
. 'location.'),
__('● Consecutive free rack space is indicated in worksheet \'DC Inventory'
. '\' with the string \'__EMPTY \' in column \'Device\'. '
. '\'Position\' gives the start of the range and \'Height\' '
. 'specifies the size of the range of free rack space.'),
__('● A range of consecutive free slots in a chassis is indicacted in '
. 'worksheet \'DC Inventory\' with the string \'__EMPTYSLOT \' in '
. 'the column \'Device\'. \'Position\' gives the start of the '
. 'range and \'Height\' specifies the number of free slots.'),
__('● All free rack units (RU) within the racks sum up to the total '
. 'amount of free rack units. It is possible that devices of '
. 'different height are mounted at the same position within a '
. 'cabinet. Only the non occupied rack units are free RUs.'),
__('● Cabinets of \'Model\' equal \'RESERVED\' are placeholders on the '
. 'floor space in the DC for racks to come. Their number is '
. 'counted in the column \'No. Reserved Racks\'. Nevertheless, '
. 'the rack units are taken into account in all other statistics.'),
'',
__('This file is confidential and shall not be used without permission of '
. 'the owner.'),
'',
__('Generate by openDCIM')
)
),
'DC Stats' => array(
'Title' => '&L&DC ' . __('Summary Statistics') . '&R&A',
'FillColor' => 'DCE6F1',
'HeadingFontColor' => '000000',
'HeaderRange' => null,
'HeaderHeight' => 51,
'Border color' => '95B3D7',
'Border Style' => array(
'borders' => array(
'bottom' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN,
'color' => array(
'rgb' => '95B3D7'
)
)
)
),
'PageSize' => $config->ParameterArray['PageSize'],
'Orientation' => PHPExcel_Worksheet_PageSetup::ORIENTATION_LANDSCAPE,
// Columns format is <header_title>, <format_spec>, <width>, <special_attr>
'Columns' => array(
array(__("DC Room"), '', 21, 'wrap'),
array(__("Floor\nSpace\n(sqm)"), '', 9, null),
array(__("No.\nRacks"), '', 10, null),
array(__("No.\nReserved\nRacks"), '', 10, null),
array(__("Sum of\nRack\nUnits (RU)"), '', 12, null),
array(__("Sum of\nUsed\nRack\nUnits (RU)"), '', 12, null),
array(__("Percentage\nUsed\nRack\nUnits"), 'P', 12, null),
array(__("Sum of\nEmpty\nRack\nUnits (RU)"), '', 12, null),
array(__("Percentage\nEmpty\nRack\nUnits"), 'P', 12, null),
array(__("Sum of\nPower\n(kW)"), 'F', 9, null),
array(__("Sum of\nDesign\nPower\n(kW)"), '', 9, null)
),
'KPIs' => array(
'Fl_Spc', // - Fl_Spc floor space
'Rk_Num', // - Rk_Num no. racks
'Rk_UtT', // - Rk_UtT rack units Total
'Rk_UtU', // - Rk_UtU rack units used
'Rk_UtE', // - Rk_UtE rack units empty
'Rk_Res', // - Rk_Res racks reserved
'Watts', // - Watts power allocated
'DesignPower' // - DesignPower design power of DC
),
'ColIdx' => array(),
'ExpStr' => array()
),
'DC Inventory' => array(
'Title' => '&L&BDC Inventory - Devices&R&A',
'FillColor' => '162A49',
'HeadingFontColor' => 'FFFFFF',
'HeaderRange' => null,
'HeaderHeight' => null,
'PageSize' => $config->ParameterArray['PageSize'],
'Orientation' => PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT,
'Columns' => array(
array('DevID', '', null, null),
array('Zone', '', null, null),
array('Row', '', null, null),
array('DC Name', 'T', null, null),
array('Cabinet', '', 10, null),
array('Position', '', null, null),
array('Half Depth', '', null, null),
array('Height', '', null, null),
array('Device', '', 19, null),
array('Parent Device', '', 19, null),
array('Manufacturer', '', null, null),
array('Model', 'T', 15, null),
array('Device Type', '', null, null),
array('Asset Number', 'T', 11, null),
array('Serial No.', 'T', 11, null),
array('Install Date', 'D', 11, null),
array('Warranty End', 'D', 11, null),
array('Owner', '', 11, null),
array('Power (W)', '', 11, null),
array('Reservation', '', null, null),
array('Contact', '', null, null),
array('Tags', '', null, null),
array('Notes', '', 40, 'wrap')),
'ColIdx' => array(),
'ExpStr' => array()
),
'Rack Inventory' => array(
'Title' => '&L&BDC Inventory - Racks&R&A',
'FillColor' => '162A49',
'HeadingFontColor' => 'FFFFFF',
'HeaderRange' => null,
'HeaderHeight' => null,
'PageSize' => $config->ParameterArray['PageSize'],
'Orientation' => PHPExcel_Worksheet_PageSetup::ORIENTATION_PORTRAIT,
'Columns' => array(
array('CabID', '', null, null),
array('Zone', '', null, null),
array('Row', '', null, null),
array('DC Name', '', null, null),
array('Cabinet', '', 10, null),
array('AssignedTo', '', 11, null),
array('Tags', '', null, null),
array('Height', '', null, null),
array('Model', '', null, null),
array('Keylock', '', null, null),
array('MaxKW', '', null, null),
array('MaxWeight', '', null, null),
array('Install Date', 'D', 10, null),
array('Auditor', '', 10, null),
array('Timestamp', 'D', 18, null),
array('Notes', '', 40, 'wrap')),
'ColIdx' => array(),
'ExpStr' => array()
)
);
/**
* Report some runtime statistics if the log file writable and reporting flag set.
*
* @author
*
*/
class ReportStats
{
/**
* @var ReportStats instance of this singleton
*/
private static $_instance = null;
/**
* @var identifier of the report string
*/
private $rid = 0;
/**
* @var boolean $report_flag if true enable report on usage of time and memory
*/
private static $report_flag = false;
/**
* @var int $start time value when started
*/
private $start = 0;
/**
* @var int $elpase time elpased since start
*/
private $elapse = 0;
/**
* string $fname filename where the reporting is written to
*/
private $fname = '/var/tmp/report_assets_Excel.stats';
/**
* @var object|null $_fp file handle to the open reporting file or null
*/
private $_fp = null;
/**
* Get the instance of the singleton or create it if not yet created
*
* @return ReportStats
*/
public static function get()
{
/**
* object|null $_fp file handle to the open reporting file or null
*/
if (self::$_instance === null) {
self::$_instance = new ReportStats();
}
return self::$_instance;
}
private function __clone() {}
private function __construct()
{
$this->start = microtime(true);
$this->rid = time();
}
/**
* Enable the statistics reporting
*/
public function useStatReporting()
{
self::$report_flag = true;
}
/**
* Write to the statistics file consumption on time and memory
*
* If $type equals 'Info' the message is written to the statistics file with the
* delta time between the previous invocation and the total time spend by the
* program. On $type equal 'Totals' the memory usage and the timings are written.
* @param string $type
* @param string $msg
*/
public function report($type, $msg = '')
{
try {
$this->_fp = fopen($this->fname, 'a');
if (self::$report_flag and $this->_fp) {
$total = microtime(true) - $this->start;
$delta = $total - $this->elapse;
$this->elapse += $delta;
$line = null;
$timestamp = date('Y-m-d H:i:s');
switch ($type) {
case 'Info':
$line = $this->rid . ' ' . $msg . ' [Delta/Total (sec): '
. sprintf("%.2f", $delta)
. '/' . sprintf("%.2f", $total) . ']' . PHP_EOL;
break;
case 'Totals':
$line = $this->rid . ' ' . 'Summary [Delta/Total (sec): '
. sprintf("%.2f", $delta) . '/'
. sprintf("%.2f", $total) . ']' . PHP_EOL;
$mem_usage = memory_get_usage(true) / 1024 / 1024;
$line .= ' Current memory usage: ' . $mem_usage . 'MB' . "\n";
$mem_peak = memory_get_peak_usage(true) / 1024 / 1024;
$line .= ' Peak memory usage: ' . $mem_peak . 'MB' . "\n";
break;
}
if ($line) fwrite($this->_fp, $timestamp . ' ' . $line);
}
fclose($this->_fp);
} catch (Exception $e) {
// ignore error if opening the file fails for any reason
}
}
}
/**
* Create an index for the column names of a worksheet
*
* The column index has two values, the numerical and the alpha value of the
* respective column, e.g. 'ColName' => array(3, 'C').
*
* @param array $colSpec an array of column specifications for a worksheet
* @return array an associated array indexed by the column names pointing to the
* pair of the numerical and the alpha index of the column
*/
function buildColumnIndex($colSpec)
{
$idx = 0;
$colIndex = array();
foreach ($colSpec as $val) {
$colIndex[$val[0]] = array($idx, PHPExcel_Cell::stringFromColumnIndex($idx));
$idx ++;
}
return $colIndex;
}
/**
* Create the list of those columns of a worksheet which needs to be written
* explicitly as string value.
*
* The returned list consists of all the column names which require explict
* writing of values with their Excel type. The list looks like e.g.
* array('ColName3', 'ColName7').
*
* @param $colSpec
* @return array a list of column names requiring explicitly being written as string
*/
function buildExStringColIdx($colSpec)
{
$colIndex = array();
foreach ($colSpec as $key => $val) {
$colIndex[] = $val[0];
}
return $colIndex;
}
/**
* Add an index of column names for each worksheet
*
* @param $DProps document properties
*/
function addColumnIndices(&$DProps)
{
$worksheetNames = array();
foreach ($DProps as $key => $val) {
if (($key != 'Doc') and (is_array($val))) {
$worksheetNames[] = $key;
}
}
$tmpC = new Container();
$maxLevels = $tmpC->computeMaxLevel();
$levelSpecs = array();
foreach (range(1, $maxLevels) as $val) {
if ($val == $maxLevels) {
$fmt = 'T';
} else {
$fmt = '';
}
$levelSpecs[] = array(('Level' . $val), $fmt, null, null);
}
foreach ($worksheetNames as $wsName) {
$colArray = &$DProps[$wsName]['Columns'];
if (($wsName == 'DC Inventory') or ($wsName == 'Rack Inventory')) {
array_splice($colArray, 1, 0, $levelSpecs);
}
// the list of pairs of numeric and alpha values for each column of a sheet
$DProps[$wsName]['ColIdx'] = buildColumnIndex($colArray);
// the list of column names which require writing with explictly type
// specification
$DProps[$wsName]['ExpStr'] = buildExStringColIdx($colArray);
}
}
/**
* Set properties of Excel document
*
* @param PHPExcel $objPHPExcel
* workbook to be generated
* @param string $thisDate
* the date on which the workbook is generated
* @param string $ownerName
* the configuration of openDCIM
* @param array $DProps
* the workbook configuration
*/
function setDocumentProperties($objPHPExcel, $thisDate, $ownerName, $DProps)
{
$creator = basename(__FILE__) . ' version ' . $DProps['Doc']['version']
. ', '. $ownerName;
$subject = $DProps['Doc']['Subject'];
$description = $DProps['Doc']['Description'];
$title = $DProps['Doc']['Title'];
$keywords = $DProps['Doc']['Keywords'];
$objPHPExcel->getProperties()
->setCreator($creator)
->setSubject("$subject, $thisDate")
->setDescription($description)
->setTitle($title)
->setKeywords($keywords)
->setLastModifiedBy($DProps['Doc']['UserID']);
$objPHPExcel->getDefaultStyle()
->getFont()
->setName('Arial')
->setSize(10);
}
/**
* Set the properties of a worksheet
*
* @param PHPExcel_Worksheet $worksheet
* @param string $WSKind kind of worksheet
* @param array $DProps array with the document properties
* @param string $thisDate timestamp of the execution of the script
*/
function setWorksheetProperties($worksheet, $wsKind, $DProps, $thisDate)
{
$worksheet->SetTitle($wsKind . ' '. $thisDate);
$worksheet->getTabColor()->setRGB($DProps[$wsKind]['FillColor']);
// Set the printout options
switch ($DProps[$wsKind]['PageSize']) {
case 'A4':
$page_size = PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4;
break;
case 'A3':
$page_size = PHPExcel_Worksheet_PageSetup::PAPERSIZE_A3;
break;
case 'Letter':
$page_size = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER;
break;
case 'Legal':
$page_size = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LEGAL;
break;
default:
$page_size = PHPExcel_Worksheet_PageSetup::PAPERSIZE_A4;
break;
}
// Set orientation, fit to page width, paper size and page number to 1
$worksheet->getPageSetup()
->setOrientation($DProps[$wsKind]['Orientation'])
->setFitToPage(true)
->setFitToWidth(1)
->setFitToHeight(0)
->setPaperSize($page_size)
->setFirstPageNumber(1);
// Set title of header and page number footer for printout
$worksheet->getHeaderFooter()
->setOddHeader($DProps[$wsKind]['Title'])
->setEvenHeader($DProps[$wsKind]['Title'])
->setOddFooter('&RPage &P of &N')
->setEvenFooter('&RPage &P of &N');
// Set repeating header for most worksheets on the printout
switch ($wsKind) {
case 'Front Page':
break;
case 'DC Stats':
case 'Rack Inventory':
case 'DC Inventory':
$worksheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
break;
}
}
/**
* Create a list of the header names from the worksheet column attributes
*
* @param array $wsCols
* @return (string)[] a list of the column names
*/
function getHeaderNames($wsCols)
{
$colNames = array();
foreach ($wsCols as $colAttrs) {
$colNames[] = $colAttrs[0];
}
return $colNames;
}
/**
* @param array $headerDef the array column headers for a worksheet
* @return string Excel alphnum range specification
*/
function computeHeaderRange($headerDef)
{
// columns start is zero based, therefore adjustment required
$headerLen = count($headerDef) - 1;
$headerRange = 'A1:' . PHPExcel_Cell::stringFromColumnIndex($headerLen) . '1';
return $headerRange;
}
/**
* Write the header of a worksheet
*
* @param PHPExcel_Worksheet $worksheet
* @param string $wsKind the kind of worksheet
* @param array $wsProps the attribues of the worksheet
*/
function writeWSHeader($worksheet, $wsKind, $wsProps)
{
$hrange = $wsProps['HeaderRange'];
if (! $hrange) {
$hrange = computeHeaderRange($wsProps['Columns']);
}
$colNames = getHeaderNames($wsProps['Columns']);
$worksheet->fromArray($colNames, null, 'A1');
if ($wsProps['HeaderHeight']) {
$worksheet->getRowDimension('1')->setRowHeight($wsProps['HeaderHeight']);
}
$freezeCell = 'A2';
$repeat_header = true;
switch ($wsKind) {
case 'Front Page':
$freezeCell = 'A3';
$repeat_header = false;
break;
case 'DC Stats':
$worksheet->getStyle($hrange)->getAlignment()->setWrapText(true);
break;
case 'DC Inventory':
case 'Rack Inventory':
break;
}
$worksheet->freezePane($freezeCell);
$worksheet->getStyle($hrange)->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
$worksheet->getStyle($hrange)->getFill()
->getStartColor()->setRGB($wsProps['FillColor']);
$worksheet->getStyle($hrange)->getFont()
->getColor()->setRGB($wsProps['HeadingFontColor']);
$worksheet->getStyle($hrange)->getFont()->setBold(true);
if ($repeat_header) {
$worksheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
}
}
/**
* Format the columns of the worksheet according to the attribute definition
*
* @param PHPExcel_Worksheet $worksheet
* @param array $columns
*/
function formatWSColumns($worksheet, $columns)
{
$fmt_code = array(
'T' => PHPExcel_Style_NumberFormat::FORMAT_TEXT,
'D' => 'yyyy-mm-dd',
'N' => PHPExcel_Style_NumberFormat::FORMAT_NUMBER,
'F' => '0.0',
'P' => '0.0%',
'' => null
);
$highestRow = $worksheet->getHighestRow();
$colFmt = $columns[0][1];
$colidx = 0;
$start = 0;
$idx = 0;
foreach ($columns as $col) {
if ($col[2]) {
// set the column width if a specific value is defined
$colLetter = PHPExcel_Cell::stringFromColumnIndex($colidx);
$worksheet->getColumnDimension($colLetter)->setWidth($col[2]);
}
if ($col[3] and ($col[3] == 'wrap')) {
// set text wrapping attribute if requested
$colLetter = PHPExcel_Cell::stringFromColumnIndex($colidx);
$range = $colLetter . '2:' . $colLetter . $highestRow;
$worksheet->getStyle($range)->getAlignment()->setWrapText(true);
}
if ($colFmt != $col[1]) {
// assign the format to the range if a format is explicitly required
$start_col = PHPExcel_Cell::stringFromColumnIndex($start);
$end_col = PHPExcel_Cell::stringFromColumnIndex($start+$idx-1);
$range = $start_col . '2:' . $end_col . $highestRow;
$colFmtSpec = $fmt_code[$colFmt];
if ($colFmtSpec) {
$worksheet->getStyle($range)
->getNumberFormat()->setFormatCode($colFmtSpec);
}
$colFmt = $col[1];
$start = $start + $idx;
$idx = 1;
} else {
// still in the same format range
$idx += 1;
}
$colidx++;
}
$start_col = PHPExcel_Cell::stringFromColumnIndex($start);
$end_col = PHPExcel_Cell::stringFromColumnIndex($start+$idx-1);
$range = $start_col . '2:' . $end_col . $highestRow;
$colFmtSpec = $fmt_code[$colFmt];
if ($colFmtSpec) {
// assign up to the end the format if explicitly required
$worksheet->getStyle($range)->getNumberFormat()->setFormatCode($colFmtSpec);
}
}
/**
* Compare two devices according to their position within a rack
*
* @param Device $a
* @param Device $b
* @return boolean
*/
function cmpDevPos($a, $b)
{
return (intval($a->Position) > intval($b->Position));
}
/**
* Compute the device class of a device
*
* @param DeviceTemplate $devTemplates
* @param Device $device
* @return (string|string)[] Manufacturer, Model
*/
function getDeviceTemplateName($devTemplates, $device)
{
// Compute the device class of a device
$retval = array('_NoDevModel', '_NoManufDefined');
$templID = $device->TemplateID;
if ($templID != 0) {
$manufacturer = new Manufacturer();
$manufacturer->ManufacturerID = $devTemplates[$templID]->ManufacturerID;
$retcode = $manufacturer->GetManufacturerByID();
if ($retcode) {
$manufName = $manufacturer->Name;
} else {
$manufName = '_NoManufDefined';
}
$retval = array($manufName, $devTemplates[$templID]->Model);
}
return $retval;
}
/**
* Get the owner name of a device
*
* @param Device $device
* @param array $deptList
* @return (string|null) the owner or null if device doesn't have an owner
*/
function getOwnerName($device, $deptList, $emptyVal = null)
{
$retval = $emptyVal;
if ($device->Owner != 0) {
$retval = $deptList[$device->Owner]->Name;
}
return $retval;
}
/**
* Return the auditor's name.
*
* @param Cabinet $cab
* @param string|null $emptyVal
* @return string|null
*/
function getAuditorName($cab, $emptyVal = null)
{
$auditorName = $emptyVal;
$cab_audit = new CabinetAudit();
$cab_audit->CabinetID = $cab->CabinetID;
$cab_audit->GetLastAudit();
if ($cab_audit->UserID) {
$tmpUser=new User();
$tmpUser->UserID = $cab_audit->UserID;
$tmpUser->GetUserRights();
$auditorName = $tmpUser->Name;
}
return $auditorName;
}
/**
* Return the timestamp of the cabinet's last audit.
*
* @param Cabinet $cab
* @param string|null $emptyVal
* @return string|null
*/
function getAuditTimestamp($cab, $emptyVal = null)
{
$auditTimestamp = $emptyVal;
$cab_audit = new CabinetAudit();
$cab_audit->CabinetID = $cab->CabinetID;
$cab_audit->GetLastAudit();
if ($cab_audit->AuditStamp) {
$auditTimestamp = $cab_audit->AuditStamp;
}
return $auditTimestamp;
}
/**
* Merge the tags of a Device or Cabinet into one string separated by ', '
*
* @param Device|Cabinet $obj
* @return string
*/
function getTagsString($obj, $emptyVal = null)
{
$tagNames = $emptyVal;
$tag_list = $obj->GetTags();
if (count($tag_list) > 0) {
$tagNames = implode(', ', $tag_list);
}
return $tagNames;
}
/**
* Return the name of the zone for a cabinet.
*
* @param Cabinet $cab
* @param string|null $emptyVal
* @return string
*/
function getZoneName($cab, $emptyVal = null)
{
$zoneName = $emptyVal;
if ($cab->ZoneID) {
$zone = new Zone();
$zone->ZoneID = $cab->ZoneID;
$zone->GetZone();
$zoneName = $zone->Description;
}
return $zoneName;
}
/**
* Return the row name of a cabinet.
* @param Cabinet $cab
* @param (string|null) $emptyVal
* @return string|null
*/
function getRowName($cab, $emptyVal = null)
{
$rowName = $emptyVal;
if ($cab->CabRowID) {
$cabrow = new CabRow();
$cabrow->CabRowID = $cab->CabRowID;
$cabrow->GetCabRow();
$rowName = $cabrow->Name;
}
return $rowName;
}
/**
* Return if the position of the device if it is half depth, either 'front' or
* 'rear' otherwise 'null'.
* @param Device $dev
* @return string|null
*/
function getDeviceDepthPos($dev)
{
$retval = null;
if ($dev) {
if ($dev->HalfDepth) {
if ($dev->BackSide) {
$retval = 'rear';
} else {
$retval = 'front';
}
}
}
return $retval;
}
/**
* Get the name of the contact
*
* @param array $contactList
* @param int $contactID
* @return string
*/
function getContactName($contactList, $contactID)
{
$contactName = null;
if ($contactID) {
$contactName = implode(', ', array($contactList[$contactID]->LastName,
$contactList[$contactID]->FirstName));
}
return $contactName;
}
/** Alternative function to array_merge_recursive, taken from the PHP manual
* page, author: andyidol at gmail dot com
*
* The original array_merge_recursive failed on a sequence of data center names
* which could be interpreted as numbers. The last entry then was converted to
* a '0' index instead of a string such as '1029'.
*
* @param array $Arr1
* @param array $Arr2
* @return array
*/
function MergeArrays($Arr1, $Arr2)
{
foreach($Arr2 as $key => $Value)
{
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else {
$Arr1[$key] = $Value;
}
}
return $Arr1;
}
/**
* Assign the statistics values of a data center to the overall statistics
* $dcStats
*
* @param array $dcStats
* @param DataCenter $dc
* @param array $Stats
*/
function assignStatsVal(&$dcStats, $dc, $Stats)
{
$arr = array();
$tmp = &$arr;
$dcContainerList = $dc->getContainerList();
$dcContainerList[] = $dc->Name;
foreach ($dcContainerList as $level) {
$tmp[$level] = array();
$tmp = &$tmp[$level];
}
$tmp = $Stats;
// $dcStats = array_merge_recursive($dcStats, $arr);
$dcStats = MergeArrays($dcStats, $arr);
}
/**
* Return empty entry specification, kind depends on $sheetColumns
*
* @param array $sheetColumns the columns of the worksheet
* @param array $dcContainerList list of containers of data center
* @return array an array which contains all the device attributes set to null
*/
function makeEmptySpec($sheetColumns, $dcContainerList)
{
$emptySpec = array();
foreach ($sheetColumns as $col) {
$emptySpec[$col[0]] = null;
}
$idx = 1;
foreach ($dcContainerList as $containerName) {
$emptySpec[('Level'.$idx)] = $containerName;
$idx++;
}
return $emptySpec;
}
/**
* Capture the device values for child devices
*
* @param array $sheetColumns
* @param array $invData
* @param Device $parentDev
* parent device of the child
* @param array $DCName
* @param Cabinet $cab
* @param array $devTemplates
* @param array $deptList a list of departments (Department) indexed by the DeptID
* @param array $contactList list of all contacts (Contact) indexed by ContactID
* @param array $dcContainerList list of containers the data center is positioned in
* @return (integer|array)[] sum of wattage of child devices, array of devices
* in the inventory
*/
function computeDeviceChildren($sheetColumns, $invData, $parentDev, $DCName,
$cab, $devTemplates, $deptList, $contactList, $dcContainerList)
{
// capture the device values for child devices
$wattageTotal = 0;
$children = $parentDev->GetDeviceChildren();
if (is_array($children)) {
usort($children, 'cmpDevPos');
$chassisNumSlots = $parentDev->ChassisSlots;
$idx = 1;
$zoneName = getZoneName($cab);
$rowName = getRowName($cab);
foreach ($children as $child) {
if ($idx < $child->Position) {
$devSpec = makeEmptySpec($sheetColumns, $dcContainerList);
$devSpec['Zone'] = $zoneName;
$devSpec['Row'] = $rowName;
$devSpec['DC Name'] = $DCName;
$devSpec['Cabinet'] = $cab->Location;
$devSpec['Position'] = $idx;
$devSpec['Height'] = $child->Position - $idx;
$devSpec['Device'] = '__EMPTYSLOT';
$devSpec['Parent Device'] = $parentDev->Label;
$invData[] = $devSpec;
$idx = $child->Position;
}
$reserved = $child->Reservation ? 'reserved' : null;
list($manufacturer, $model) = getDeviceTemplateName($devTemplates,
$child);
$devSpec = makeEmptySpec($sheetColumns, $dcContainerList);
$devSpec['DevID'] = $child->DeviceID;
$devSpec['Zone'] = $zoneName;
$devSpec['Row'] = $rowName;
$devSpec['DC Name'] = $DCName;
$devSpec['Cabinet'] = $cab->Location;
$devSpec['Position'] = $child->Position;
$devSpec['Height'] = $child->Height;
$devSpec['Device'] = $child->Label;
$devSpec['Parent Device'] = $parentDev->Label;
$devSpec['Manufacturer'] = $manufacturer;
$devSpec['Model'] = $model;
$devSpec['Device Type'] = $child->DeviceType;
$devSpec['Asset Number'] = $child->AssetTag;
$devSpec['Serial No.'] = $child->SerialNo;
$devSpec['Install Date'] = $child->InstallDate;
$devSpec['Warranty Expire'] = $child->WarrantyExpire;
$devSpec['Owner'] = getOwnerName($child, $deptList);
$devSpec['Power (W)'] = $child->NominalWatts;
$devSpec['Reservation'] = $reserved;
$devSpec['Contact'] = getContactName($contactList, $child->PrimaryContact);
$devSpec['Tags'] = getTagsString($child);
$devSpec['Notes'] = html_entity_decode(strip_tags($child->Notes),
ENT_COMPAT, 'UTF-8');
$wattageTotal += $child->NominalWatts;
$invData[] = $devSpec;
$idx += $child->Height;
}
if ($idx <= $chassisNumSlots) {
$freeSlots = $chassisNumSlots - $idx + 1;
$devSpec = makeEmptySpec($sheetColumns, $dcContainerList);
$devSpec['Zone'] = $zoneName;
$devSpec['Row'] = $rowName;
$devSpec['DC Name'] = $DCName;
$devSpec['Cabinet'] = $cab->Location;
$devSpec['Position'] = $idx;
$devSpec['Height'] = $freeSlots;
$devSpec['Device'] = '__EMPTYSLOT';
$devSpec['Parent Device'] = $parentDev->Label;
$invData[] = $devSpec;
}
}
return array($wattageTotal, $invData);
}
/**
* Collect rack information and add it to the cab_data inventory on all data
* centers
*