Fix #7647 - php8 fixes
[Pman.Core] / SimpleExcel.php
1 <?php
2
3 /**
4  * class to generate excel file from rows of data, and a configuration.
5  *
6  * usage :
7  *   $x = new Pman_Core_SimpleExcel($data_array, array())
8  *   $x->send($fn);
9  *
10  * 
11  *
12  
13 new Pman_Core_SimpleExcel($data_array, array(
14     'formats' => array(
15         'format_name' => array( 'Align' =>  'left' ), // etc...
16     ),
17     'workbook' => 'name_of_workbook'm
18     
19     'head' => array(
20         array ( 'this', 'is', 'the' , 'first', 'row'), 
21         array ( 'this', 'is', 'the' , 'seconde', 'row'),  // ... etc.
22         array (  array( 'string', 'format_name') , 'another cell') ,  // with formating..
23     ),
24    
25     'merged_ranges' => array(
26                            array($first_row, $first_col, $last_row, $last_col),
27                          array($first_row, $first_col, $last_row, $last_col),
28     ),
29     'cols' =>  array(
30             array(
31                 'header'=> "Thumbnail",
32                 'dataIndex'=> 'id',
33                 'dataFormat' => 'string' // to force a string..
34                 'width'=>  75,
35                 'renderer' => array($this, 'getThumb'),
36                 'txtrenderer' => function($value, $worksheet, $row, $col, $row_data) {
37                     return $value
38                 },   // for text content...
39                 'color' => 'yellow', // set color for the cell which is a header element
40                 'fillBlank' => 'gray', // set the color for the cell which is a blank area
41             ),
42             //..... and ther rows...
43     ),
44     
45     // if this is set then it will add a tab foreach one.
46     'workbooks' = array(
47             workbook => '....' // ???
48     ),
49     'leave_open' => false,  // if you call addrows?? later..
50     'nonspacer' => false, // should add line between head and header row.     
51 ));
52
53     callbacks: renderer
54         
55         function($value, $worksheet, $row, $col, $row_data)
56         
57         // callbacks : txtrenderer
58         function($value, $worksheet, $row, $col, $row_data)
59                         
60             
61             
62  */
63  
64  
65  
66 require_once 'Pman.php';
67
68
69 class Pman_Core_SimpleExcel extends Pman
70 {
71     
72     var $worksheet_cfg = array();
73     var $start_row = 0;
74     var $formats = array();
75     var $workbook = false;
76     var $worksheet= false;
77     var $postRender = array();
78     var $outfile2;
79      
80     function __construct($data,$cfg)
81     {
82       // print_r($cfg);exit;
83         require_once 'Spreadsheet/Excel/Writer.php';
84         // Creating a workbook
85         $outfile2 = $this->tempName('xls');
86        // var_dump($outfile2);
87         $workbook = new Spreadsheet_Excel_Writer($outfile2);
88         //$workbook = new Spreadsheet_Excel_Writer();
89         $workbook->setVersion(8);
90         // sending HTTP headers
91         $this->workbook = $workbook;
92             
93         $formats = array();
94        
95         $cfg['formats'] = isset($cfg['formats']) ? $cfg['formats'] : array();
96         
97         $this->formats['_default_date_format_'] = $workbook->addFormat();;
98         $this->formats['_default_date_format_']->setNumFormat('YYYY-MM-DD');
99         
100         foreach($cfg['formats'] as $f=>$fcfg) {
101             
102             $this->formats[$f] = & $workbook->addFormat();
103             foreach((array)$fcfg as $k=>$v) {
104                 $this->formats[$f]->{'set' . $k}($v);
105             }
106             
107         }
108          
109          
110         if (!empty($cfg['workbook'])) {
111             $this->buildPage(  array(), $data,$cfg);
112         } elseif (!empty($cfg['workbooks'])) {
113             foreach($cfg['workbooks'] as $i =>$wcfg) {
114                 $this->buildPage(   array() , $data[$i],$wcfg);
115             }
116             
117         }
118         // if workbooks == false - > the user can call buildpage..
119         
120         
121         if (!empty($cfg['leave_open'])) {
122             $this->outfile2 = $outfile2;
123             return;
124         }
125         
126         $workbook->close();
127         $this->outfile2 = $outfile2;
128          
129     }
130     
131     
132     
133     
134     static function date($str)
135     {
136         
137         return (strtotime($str . ' UTC') +  (86400 *  25569)) / 86400;
138         
139     }
140     
141     
142     function buildPage( $formats , $data, $cfg)
143     {
144         $workbook = $this->workbook;
145         //echo '<PRE>';        print_R($cfg);
146       //  print_r($cfg);exit;
147         // Creating a worksheet
148         //print_R($cfg);exit;
149         // copy the config and alias so that book can be written to..
150         $this->worksheet_cfg[$cfg['workbook']] = &$cfg;
151         
152         
153         //$this->formats = (array)$formats;
154         
155         foreach($formats as $k=>$fcfg) {
156             if (!isset($this->formats[$f])) {
157                 $this->formats[$f] = & $workbook->addFormat();
158             }
159             if (is_a($fcfg,'Spreadsheet_Excel_Writer_Format')) {
160                 continue; // skip!?!?
161             }
162             // not an object..
163             foreach((array)$fcfg as $k=>$v) {
164                 $this->formats[$f]->{'set' . $k}($v);
165             }
166         }
167         
168         if (isset($cfg['formats'])) {
169             
170             foreach($cfg['formats'] as $f=>$fcfg) {
171                 if (!isset($this->formats[$f])) {
172                     $this->formats[$f] = & $workbook->addFormat();
173                 }
174                 foreach((array)$fcfg as $k=>$v) {
175                     $this->formats[$f]->{'set' . $k}($v);
176                 }
177                  
178             }
179             
180              
181         }
182         
183         
184         
185         //var_dump($cfg['workbook']);
186
187         $worksheet =  $workbook->addWorksheet($cfg['workbook']);
188         if (is_a($worksheet, 'PEAR_Error')) {
189             die($worksheet->toString());
190         }
191         //print_R($worksheet);
192         $worksheet->setInputEncoding('UTF-8'); 
193          
194         if(!empty($cfg['merged_ranges'])){ // merge cell
195             $worksheet->_merged_ranges = $cfg['merged_ranges'];
196         }
197         
198         $this->worksheet = $worksheet;
199          
200         $start_row = 0;
201         
202         if (!empty($cfg['head'])) {
203             foreach($cfg['head'] as $row) { 
204                 foreach($row as $c => $col) {
205                     if (is_array($col)) {
206                         $format = isset($this->formats[$col[1]] ) ?$this->formats[$col[1]] : false;
207                         $worksheet->write($start_row, $c, $col[0], $format);
208                         continue;
209                     }
210                     
211                     $worksheet->write($start_row, $c, $col);
212                     
213                 }
214                 $start_row++;
215             }
216             // add a spacer..
217             if(!isset($cfg['nonspacer'])){ $start_row++; }
218         }
219             
220                
221         foreach($cfg['cols'] as $c=>$col_cfg) {
222             if (is_string($col_cfg)) {
223                 $cfg['cols'][$c] = array(
224                     'header' => $col_cfg,
225                     'dataIndex' => $col_cfg,
226                     'width' => 50,
227                 );
228             }
229         }
230          
231          
232         foreach($cfg['cols'] as $c=>$col_cfg) {
233             
234             $format = isset($col_cfg['color']) && isset($this->formats[$col_cfg['color']]) ? $this->formats[$col_cfg['color']] : false;
235             $worksheet->write($start_row, $c, @$col_cfg['header'],$format);
236             $worksheet->setColumn ( $c, $c, $col_cfg['width'] / 5);
237         }
238         $start_row++;
239         $this->start_row = &$start_row;
240         
241         
242         $hasRender  = false;
243          
244         if (empty($data)) {
245             return;
246         }
247          
248         foreach($cfg['cols']  as $c => $col_cfg) {
249             if (isset($col_cfg['renderer'])) {
250                 $hasRender = true;
251                 break;
252             }
253         }
254         
255         
256         
257         if (is_object($data)) {
258             $data_ar = array();
259             $count = $data->count();
260             $data->find();
261             
262             while($data->fetch()) {
263                 $hasRenderRow = $this->addLine($cfg['workbook'], $data);
264                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
265             }
266             $start_row += $count;
267         } else { 
268         
269             foreach($data as $r=>$clo) {
270                 $hasRenderRow = $this->addLine($cfg['workbook'], $clo);
271                 $hasRender = ($hasRender  || $hasRenderRow) ? true : false;
272                  
273             }
274         /// call user render on any that are defined..
275             if ($hasRender) {
276                 foreach($data as $r=>$cl) {
277                 
278                     foreach($cfg['cols']   as $c=>$col_cfg) {
279                         $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
280                         if (empty($cl[$col_cfg['dataIndex']])) {
281                             continue;
282                         }
283                         if (!empty($col_cfg['renderer'])) {
284                              if (is_a($col_cfg['renderer'], 'Closure')) {
285                                 $col_cfg['renderer']($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
286                             } else {
287                             // not sure if row is correct here...!!!?
288                                 call_user_func($col_cfg['renderer'], $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $cl);
289                             }
290                             
291                         }
292                       //  echo "<PRE>WRITE: ". htmlspecialchars(print_r(array($r+1, $c, $cl[$col_cfg['dataIndex']]), true));
293                  
294                     }
295                 }
296             }
297             $start_row += count($data);
298
299         }
300         
301         if (!empty($cfg['foot'])) {
302             foreach($cfg['foot'] as $row) { 
303                 foreach($row as $c => $col) {
304                     // if it's an array? - formated ???
305                     if (is_array($col)) {
306                         $format = isset($this->formats[$col[1]] ) ? $this->formats[$col[1]] : false;
307                         $worksheet->write($start_row, $c, $col[0], $format);
308                         continue;
309                     }
310                     $worksheet->write($start_row, $c, $col);
311                     
312                 }
313                 $start_row++;
314             }
315             // add a spacer..
316             $start_row++;
317         }
318          
319     }
320     
321     function addLine($worksheet_name, $clo)
322     {
323         $cfg        = $this->worksheet_cfg[$worksheet_name];
324         $start_row  = $this->start_row;
325         $formats    = (array)$this->formats;
326         $worksheet  = $this->worksheet;
327         
328         $hasRender   = false;
329         $r = 0;
330        
331         $cl = $clo;
332         if (is_object($clo)) {
333             $cl = (array)$clo; // lossless converstion..
334         }
335         
336         if (isset($cfg['row_height'])) {
337             $worksheet->setRow($start_row +$r, $cfg['row_height']);
338         }
339         
340         $line_height = (isset($cfg['line_height'])) ? $cfg['line_height'] : 12;
341         $height = 0;
342         
343         foreach($cfg['cols']  as $c => $col_cfg) {
344             
345             if(isset($col_cfg['dataIndex']) && isset($cl[$col_cfg['dataIndex']])){
346                 $v =    $cl[$col_cfg['dataIndex']]  ;
347                 
348             }else{
349                 if(isset($col_cfg['fillBlank'])){
350                     $worksheet->write($start_row+$r, $c, '', $formats[$col_cfg['fillBlank']]);
351                 }
352                 continue;
353             }
354             
355             if (!isset($cl[$col_cfg['dataIndex']])) {
356                 continue;
357             }
358             if (isset($col_cfg['txtrenderer'])) {
359                 
360                  if (is_a($col_cfg['txtrenderer'], 'Closure')) {
361                      
362                     $v =     $col_cfg['txtrenderer']($cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
363                 } else {
364                     $v = call_user_func($col_cfg['txtrenderer'], 
365                             $cl[$col_cfg['dataIndex']], $worksheet, $r+1, $c, $clo);
366                 }
367                 if ($v === false) {
368                     continue;
369                 }
370               //  var_dump($v);
371             }
372             if (isset($col_cfg['renderer'])) {
373                 $hasRender = true;
374                 
375                 $v = isset($cl[$col_cfg['dataIndex']]) ? $cl[$col_cfg['dataIndex']] : '';
376                 if (empty($cl[$col_cfg['dataIndex']])) {
377                     continue;
378                 }
379                 $this->postRender[] = array(
380                     $col_cfg['renderer'], $cl[$col_cfg['dataIndex']], $worksheet, $start_row+$r+1, $c, $cl
381                 );
382                   
383                 
384                 
385                 
386                 continue;
387             }
388             
389             $v = @iconv('UTF-8', 'UTF-8//TRANSLIT//IGNORE', $v);
390             
391             $dataFormat = empty($col_cfg['dataFormat']) ? '' : $col_cfg['dataFormat'];
392               
393             
394             $format = isset($col_cfg['format'])  && isset($formats[$col_cfg['format']] )   ? $formats[$col_cfg['format']] : false;
395           //  print_R(array($start_row+$r, $c, $v, $format));exit;
396           // handle 0 prefixes..
397           
398             if ($dataFormat == 'date' || preg_match('/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/', $v)) {
399                 $dataFormat = 'date';
400                 $format = empty($format) ? $this->formats['_default_date_format_']: $format;
401                 $ut_to_ed_diff = 86400 * 25569;
402                 $gmt = strtotime('1970-01-01');
403
404                 $v = (strtotime($v) + $ut_to_ed_diff - $gmt) / 86400;
405                 // need to +8hrs to get real time..
406                 
407                 
408             }
409           
410             if ( (is_numeric($v) &&  strlen($v) > 1 && substr($v,0,1) == '0' && substr($v,1,1) != '.' )
411                     || 
412                     $dataFormat == 'string' ) {
413                 $worksheet->writeString($start_row+$r, $c, $v, $format);
414             } else {
415           
416                 $worksheet->write($start_row+$r, $c, $v, $format);
417             }
418             
419             if(isset($col_cfg['autoHeight'])){
420                 $vv = explode("\n", $v);
421                 $height = MAX(count($vv) * $line_height, $height);;
422                 $worksheet->setRow($start_row+$r, $height);
423             }
424         }
425         $this->start_row++;
426         
427         return $hasRender;
428     }
429      
430     
431     function send($fname)
432     {
433         
434         if (!empty($this->postRender)) {
435             foreach($this->postRender as $ar) {
436                  if (is_a($ar[0], 'Closure')) {
437                     $ar[0]($ar[1], $ar[2], $ar[3], $ar[4], $ar[5]);
438                 } else {
439                 // not sure if row is correct here...!!!?
440                     call_user_func($ar[0],$ar[1], $ar[2], $ar[3], $ar[4], $ar[5]);
441                 }
442             }
443             
444         }
445         
446         
447         if (!empty($this->workbook)) {
448             $this->workbook->close();
449             $this->workbook = false;
450         }
451         
452         require_once 'File/Convert.php';
453         //var_Dump($this->outfile2);
454         $fc=  new File_Convert($this->outfile2, "application/vnd.ms-excel");
455         $fn = $fc->convert("application/vnd.ms-excel");
456         //print_r($fc);
457         $fc->serve('attachment',$fname); // can fix IE Mess
458     }
459      
460     
461 }