Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Excel writer abstraction layer.
19
 *
20
 * @copyright  (C) 2001-3001 Eloy Lafuente (stronk7) {@link http://contiento.com}
21
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
22
 * @package    core
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
1441 ariadna 27
use PhpOffice\PhpSpreadsheet\Cell\CellAddress;
28
use PhpOffice\PhpSpreadsheet\Cell\CellRange;
29
use PhpOffice\PhpSpreadsheet\Spreadsheet;
30
use PhpOffice\PhpSpreadsheet\IOFactory;
31
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
32
use PhpOffice\PhpSpreadsheet\Cell\DataType;
33
use PhpOffice\PhpSpreadsheet\Shared\Date;
34
use PhpOffice\PhpSpreadsheet\Style\Alignment;
35
use PhpOffice\PhpSpreadsheet\Style\Border;
36
use PhpOffice\PhpSpreadsheet\Style\Fill;
37
use PhpOffice\PhpSpreadsheet\Style\Font;
38
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
39
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
40
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
1 efrain 41
 
42
/**
43
 * Define and operate over one Moodle Workbook.
44
 *
45
 * This class acts as a wrapper around another library
46
 * maintaining Moodle functions isolated from underlying code.
47
 *
48
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
49
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50
 * @package moodlecore
51
 */
52
class MoodleExcelWorkbook {
53
    /** @var \PhpOffice\PhpSpreadsheet\Spreadsheet */
54
    protected $objspreadsheet;
55
 
56
    /** @var string */
57
    protected $filename;
58
 
59
    /** @var string format type */
60
    protected $type;
61
 
62
    /**
63
     * Constructs one Moodle Workbook.
64
     *
65
     * @param string $filename The name of the file
66
     * @param string $type file format type used to be 'Xls or Xlsx' but now only 'Xlsx'
67
     */
68
    public function __construct($filename, $type = 'Xlsx') {
69
        global $CFG;
70
 
71
        $this->objspreadsheet = new Spreadsheet();
72
        $this->objspreadsheet->removeSheetByIndex(0);
73
 
74
        $this->filename = $filename;
75
 
76
        if (strtolower($type) === 'Xls') {
77
            debugging('Xls is no longer supported, using Xlsx instead');
78
            $this->type = 'Xlsx';
79
        } else {
80
            $this->type = 'Xlsx';
81
        }
82
    }
83
 
84
    /**
85
     * Create one Moodle Worksheet
86
     *
87
     * @param string $name Name of the sheet
88
     * @return MoodleExcelWorksheet
89
     */
90
    public function add_worksheet($name = '') {
91
        return new MoodleExcelWorksheet($name, $this->objspreadsheet);
92
    }
93
 
94
    /**
95
     * Create one cell Format.
96
     *
97
     * @param array $properties array of properties [name]=value;
98
     *                          valid names are set_XXXX existing
99
     *                          functions without the set_ part
100
     *                          i.e: [bold]=1 for set_bold(1)...Optional!
101
     * @return MoodleExcelFormat
102
     */
103
    public function add_format($properties = array()) {
104
        return new MoodleExcelFormat($properties);
105
    }
106
 
107
    /**
108
     * Close the Moodle Workbook
109
     */
110
    public function close() {
111
        global $CFG;
112
 
113
        foreach ($this->objspreadsheet->getAllSheets() as $sheet) {
114
            $sheet->setSelectedCells('A1');
115
        }
116
        $this->objspreadsheet->setActiveSheetIndex(0);
117
 
118
        $filename = preg_replace('/\.xlsx?$/i', '', $this->filename);
119
 
120
        $mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
121
        $filename = $filename.'.xlsx';
122
 
123
        if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
124
            header('Cache-Control: max-age=10');
125
            header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
126
            header('Pragma: ');
127
        } else { //normal http - prevent caching at all cost
128
            header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
129
            header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
130
            header('Pragma: no-cache');
131
        }
132
 
133
        if (core_useragent::is_ie() || core_useragent::is_edge()) {
134
            $filename = rawurlencode($filename);
135
        } else {
136
            $filename = s($filename);
137
        }
138
 
139
        header('Content-Type: '.$mimetype);
140
        header('Content-Disposition: attachment;filename="'.$filename.'"');
141
 
142
        $objwriter = IOFactory::createWriter($this->objspreadsheet, $this->type);
143
        $objwriter->save('php://output');
144
    }
145
 
146
    /**
147
     * Not required to use.
148
     * @param string $filename Name of the downloaded file
149
     */
150
    public function send($filename) {
151
        $this->filename = $filename;
152
    }
153
}
154
 
155
/**
156
 * Define and operate over one Worksheet.
157
 *
158
 * This class acts as a wrapper around another library
159
 * maintaining Moodle functions isolated from underlying code.
160
 *
161
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
162
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
163
 * @package   core
164
 */
165
class MoodleExcelWorksheet {
166
    /** @var Worksheet */
167
    protected $worksheet;
168
 
169
    /**
170
     * Constructs one Moodle Worksheet.
171
     *
172
     * @param string $name The name of the file
173
     * @param Spreadsheet $workbook The internal Workbook object we are creating.
174
     */
175
    public function __construct($name, Spreadsheet $workbook) {
176
        // Replace any characters in the name that Excel cannot cope with.
177
        $name = strtr(trim($name, "'"), '[]*/\?:', '       ');
178
        // Shorten the title if necessary.
179
        $name = core_text::substr($name, 0, 31);
180
        // After the substr, we might now have a single quote on the end.
181
        $name = trim($name, "'");
182
 
183
        if ($name === '') {
184
            // Name is required!
185
            $name = 'Sheet'.($workbook->getSheetCount()+1);
186
        }
187
 
188
        $this->worksheet = new Worksheet($workbook, $name);
189
        $this->worksheet->setPrintGridlines(false);
190
 
191
        $workbook->addSheet($this->worksheet);
192
    }
193
 
194
    /**
195
     * Write one string somewhere in the worksheet.
196
     *
197
     * @param integer $row    Zero indexed row
198
     * @param integer $col    Zero indexed column
199
     * @param string  $str    The string to write
200
     * @param mixed   $format The XF format for the cell
201
     */
202
    public function write_string($row, $col, $str, $format = null) {
203
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
204
        $col += 1;
205
 
1441 ariadna 206
        $celladdress = CellAddress::fromColumnAndRow($col, $row + 1);
207
 
208
        $this->worksheet->getStyle($celladdress)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_TEXT);
209
        $this->worksheet->getCell($celladdress)->setValueExplicit($str, DataType::TYPE_STRING);
1 efrain 210
        $this->apply_format($row, $col, $format);
211
    }
212
 
213
    /**
214
     * Write one number somewhere in the worksheet.
215
     *
216
     * @param integer $row    Zero indexed row
217
     * @param integer $col    Zero indexed column
218
     * @param float   $num    The number to write
219
     * @param mixed   $format The XF format for the cell
220
     */
221
    public function write_number($row, $col, $num, $format = null) {
222
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
223
        $col += 1;
224
 
1441 ariadna 225
        $celladdress = CellAddress::fromColumnAndRow($col, $row + 1);
226
 
227
        $this->worksheet->getStyle($celladdress)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_GENERAL);
228
        $this->worksheet->getCell($celladdress)->setValueExplicit($num, DataType::TYPE_NUMERIC);
1 efrain 229
        $this->apply_format($row, $col, $format);
230
    }
231
 
232
    /**
233
     * Write one url somewhere in the worksheet.
234
     *
235
     * @param integer $row    Zero indexed row
236
     * @param integer $col    Zero indexed column
237
     * @param string  $url    The url to write
238
     * @param mixed   $format The XF format for the cell
239
     */
240
    public function write_url($row, $col, $url, $format = null) {
241
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
242
        $col += 1;
243
 
1441 ariadna 244
        $celladdress = CellAddress::fromColumnAndRow($col, $row + 1);
245
 
246
        $cell = $this->worksheet->getCell($celladdress);
247
        $cell->setValue($url);
248
        $cell->getHyperlink()->setUrl($url);
1 efrain 249
        $this->apply_format($row, $col, $format);
250
    }
251
 
252
    /**
253
     * Write one date somewhere in the worksheet.
254
     * @param integer $row    Zero indexed row
255
     * @param integer $col    Zero indexed column
256
     * @param int     $date   The date to write in UNIX timestamp format
257
     * @param mixed   $format The XF format for the cell
258
     */
259
    public function write_date($row, $col, $date, $format = null) {
260
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
261
        $col += 1;
262
 
263
        $getdate = usergetdate($date);
264
        $exceldate = Date::FormattedPHPToExcel(
265
            $getdate['year'],
266
            $getdate['mon'],
267
            $getdate['mday'],
268
            $getdate['hours'],
269
            $getdate['minutes'],
270
            $getdate['seconds']
271
        );
272
 
1441 ariadna 273
        $celladdress = CellAddress::fromColumnAndRow($col, $row + 1);
274
 
275
        $this->worksheet->getCell($celladdress)->setValue($exceldate);
276
        $this->worksheet->getStyle($celladdress)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_DATE_XLSX22);
1 efrain 277
        $this->apply_format($row, $col, $format);
278
    }
279
 
280
    /**
281
     * Write one formula somewhere in the worksheet.
282
     *
283
     * @param integer $row    Zero indexed row
284
     * @param integer $col    Zero indexed column
285
     * @param string  $formula The formula to write
286
     * @param mixed   $format The XF format for the cell
287
     */
288
    public function write_formula($row, $col, $formula, $format = null) {
289
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
290
        $col += 1;
291
 
1441 ariadna 292
        $celladdress = CellAddress::fromColumnAndRow($col, $row + 1);
293
        $this->worksheet->getCell($celladdress)->setValueExplicit($formula, DataType::TYPE_FORMULA);
1 efrain 294
        $this->apply_format($row, $col, $format);
295
    }
296
 
297
    /**
298
     * Write one blank somewhere in the worksheet.
299
     *
300
     * @param integer $row    Zero indexed row
301
     * @param integer $col    Zero indexed column
302
     * @param mixed   $format The XF format for the cell
303
     */
304
    public function write_blank($row, $col, $format = null) {
305
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
306
        $col += 1;
307
 
1441 ariadna 308
        $celladdress = CellAddress::fromColumnAndRow($col, $row + 1);
309
        $this->worksheet->getCell($celladdress)->setValue('');
1 efrain 310
        $this->apply_format($row, $col, $format);
311
    }
312
 
313
    /**
314
     * Write anything somewhere in the worksheet,
315
     * type will be automatically detected.
316
     *
317
     * @param integer $row    Zero indexed row
318
     * @param integer $col    Zero indexed column
319
     * @param mixed   $token  What we are writing
320
     * @param mixed   $format The XF format for the cell
321
     */
322
    public function write($row, $col, $token, $format = null) {
323
        // Analyse what are we trying to send.
324
        if (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/", $token)) {
325
            // Match number
326
            return $this->write_number($row, $col, $token, $format);
327
        } elseif (preg_match("/^[fh]tt?p:\/\//", $token)) {
328
            // Match http or ftp URL
329
            return $this->write_url($row, $col, $token, '', $format);
330
        } elseif (preg_match("/^mailto:/", $token)) {
331
            // Match mailto:
332
            return $this->write_url($row, $col, $token, '', $format);
333
        } elseif (preg_match("/^(?:in|ex)ternal:/", $token)) {
334
            // Match internal or external sheet link
335
            return $this->write_url($row, $col, $token, '', $format);
336
        } elseif (preg_match("/^=/", $token)) {
337
            // Match formula
338
            return $this->write_formula($row, $col, $token, $format);
339
        } elseif (preg_match("/^@/", $token)) {
340
            // Match formula
341
            return $this->write_formula($row, $col, $token, $format);
342
        } elseif ($token == '') {
343
            // Match blank
344
            return $this->write_blank($row, $col, $format);
345
        } else {
346
            // Default: match string
347
            return $this->write_string($row, $col, $token, $format);
348
        }
349
    }
350
 
351
    /**
352
     * Sets the height (and other settings) of one row.
353
     *
354
     * @param integer $row    The row to set
355
     * @param integer $height Height we are giving to the row (null to set just format without setting the height)
356
     * @param mixed   $format The optional format we are giving to the row
357
     * @param bool    $hidden The optional hidden attribute
358
     * @param integer $level  The optional outline level (0-7)
359
     */
360
    public function set_row($row, $height, $format = null, $hidden = false, $level = 0) {
361
        if ($level < 0) {
362
            $level = 0;
363
        } else if ($level > 7) {
364
            $level = 7;
365
        }
366
        if (isset($height)) {
367
            $this->worksheet->getRowDimension($row + 1)->setRowHeight($height);
368
        }
369
        $this->worksheet->getRowDimension($row + 1)->setVisible(!$hidden);
370
        $this->worksheet->getRowDimension($row + 1)->setOutlineLevel($level);
371
        $this->apply_row_format($row, $format);
372
    }
373
 
374
    /**
375
     * Sets the width (and other settings) of one column.
376
     *
377
     * @param integer $firstcol first column on the range
378
     * @param integer $lastcol  last column on the range
379
     * @param integer $width    width to set  (null to set just format without setting the width)
380
     * @param mixed   $format   The optional format to apply to the columns
381
     * @param bool    $hidden   The optional hidden attribute
382
     * @param integer $level    The optional outline level (0-7)
383
     */
384
    public function set_column($firstcol, $lastcol, $width, $format = null, $hidden = false, $level = 0) {
385
        if ($level < 0) {
386
            $level = 0;
387
        } else if ($level > 7) {
388
            $level = 7;
389
        }
390
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
391
        $i = $firstcol + 1;
392
        while ($i <= $lastcol + 1) {
393
            if (isset($width)) {
394
                $this->worksheet->getColumnDimensionByColumn($i)->setWidth($width);
395
            }
396
            $this->worksheet->getColumnDimensionByColumn($i)->setVisible(!$hidden);
397
            $this->worksheet->getColumnDimensionByColumn($i)->setOutlineLevel($level);
398
            $this->apply_column_format($i, $format);
399
            $i++;
400
        }
401
    }
402
 
403
   /**
404
    * Set the option to hide grid lines on the printed page.
405
    */
406
    public function hide_gridlines() {
407
        // Not implemented - always off.
408
    }
409
 
410
   /**
411
    * Set the option to hide gridlines on the worksheet (as seen on the screen).
412
    */
413
    public function hide_screen_gridlines() {
414
        $this->worksheet->setShowGridlines(false);
415
    }
416
 
417
   /**
418
    * Insert an image in a worksheet.
419
    *
420
    * @param integer $row     The row we are going to insert the bitmap into
421
    * @param integer $col     The column we are going to insert the bitmap into
422
    * @param string  $bitmap  The bitmap filename
423
    * @param integer $x       The horizontal position (offset) of the image inside the cell.
424
    * @param integer $y       The vertical position (offset) of the image inside the cell.
425
    * @param integer $scalex The horizontal scale
426
    * @param integer $scaley The vertical scale
427
    */
428
    public function insert_bitmap($row, $col, $bitmap, $x = 0, $y = 0, $scalex = 1, $scaley = 1) {
429
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
430
        $col += 1;
431
 
432
        $objdrawing = new Drawing();
433
        $objdrawing->setPath($bitmap);
434
        $objdrawing->setCoordinates(Coordinate::stringFromColumnIndex($col) . ($row + 1));
435
        $objdrawing->setOffsetX($x);
436
        $objdrawing->setOffsetY($y);
437
        $objdrawing->setWorksheet($this->worksheet);
438
        if ($scalex != 1) {
439
            $objdrawing->setResizeProportional(false);
440
            $objdrawing->getWidth($objdrawing->getWidth() * $scalex);
441
        }
442
        if ($scaley != 1) {
443
            $objdrawing->setResizeProportional(false);
444
            $objdrawing->setHeight($objdrawing->getHeight() * $scaley);
445
        }
446
    }
447
 
448
   /**
449
    * Merges the area given by its arguments.
450
    *
451
    * @param integer $firstrow First row of the area to merge
452
    * @param integer $firstcol First column of the area to merge
453
    * @param integer $lastrow  Last row of the area to merge
454
    * @param integer $lastcol  Last column of the area to merge
455
    */
456
    public function merge_cells($firstrow, $firstcol, $lastrow, $lastcol) {
457
        // For PhpSpreadsheet library, the column indexes start on 1 (instead of 0 as before).
1441 ariadna 458
        $this->worksheet->mergeCells(
459
            new CellRange(
460
                CellAddress::fromColumnAndRow($firstcol + 1, $firstrow + 1),
461
                CellAddress::fromColumnAndRow($lastcol + 1, $lastrow + 1),
462
            )
463
        );
1 efrain 464
    }
465
 
466
    protected function apply_format($row, $col, $format = null) {
467
        if (!$format) {
468
            $format = new MoodleExcelFormat();
469
        } else if (is_array($format)) {
470
            $format = new MoodleExcelFormat($format);
471
        }
1441 ariadna 472
        $this->worksheet->getStyle(CellAddress::fromColumnAndRow($col, $row + 1))->applyFromArray($format->get_format_array());
1 efrain 473
    }
474
 
475
    protected function apply_column_format($col, $format = null) {
476
        if (!$format) {
477
            $format = new MoodleExcelFormat();
478
        } else if (is_array($format)) {
479
            $format = new MoodleExcelFormat($format);
480
        }
481
        $this->worksheet->getStyle(Coordinate::stringFromColumnIndex($col))->applyFromArray($format->get_format_array());
482
    }
483
 
484
    protected function apply_row_format($row, $format = null) {
485
        if (!$format) {
486
            $format = new MoodleExcelFormat();
487
        } else if (is_array($format)) {
488
            $format = new MoodleExcelFormat($format);
489
        }
490
        $this->worksheet->getStyle($row + 1)->applyFromArray($format->get_format_array());
491
    }
492
}
493
 
494
 
495
/**
496
 * Define and operate over one Format.
497
 *
498
 * A big part of this class acts as a wrapper over other libraries
499
 * maintaining Moodle functions isolated from underlying code.
500
 *
501
 * @copyright 1999 onwards Martin Dougiamas  {@link http://moodle.com}
502
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
503
 * @package moodlecore
504
 */
505
class MoodleExcelFormat {
506
    /** @var array */
507
    protected $format = array();
508
 
509
    /**
510
     * Constructs one Moodle Format.
511
     *
512
     * @param array $properties
513
     */
514
    public function __construct($properties = array()) {
515
        // If we have something in the array of properties, compute them
516
        foreach($properties as $property => $value) {
517
            if(method_exists($this,"set_$property")) {
518
                $aux = 'set_'.$property;
519
                $this->$aux($value);
520
            }
521
        }
522
    }
523
 
524
    /**
525
     * Returns standardised Excel format array.
526
     * @private
527
     *
528
     * @return array
529
     */
530
    public function get_format_array() {
531
        return $this->format;
532
    }
533
    /**
534
     * Set the size of the text in the format (in pixels).
535
     * By default all texts in generated sheets are 10pt.
536
     *
537
     * @param integer $size Size of the text (in points)
538
     */
539
    public function set_size($size) {
540
        $this->format['font']['size'] = $size;
541
    }
542
 
543
    /**
544
     * Set weight of the format.
545
     *
546
     * @param integer $weight Weight for the text, 0 maps to 400 (normal text),
547
     *                        1 maps to 700 (bold text). Valid range is: 100-1000.
548
     *                        It's Optional, default is 1 (bold).
549
     */
550
    public function set_bold($weight = 1) {
551
        if ($weight == 1) {
552
            $weight = 700;
553
        }
554
        $this->format['font']['bold'] = ($weight > 400);
555
    }
556
 
557
    /**
558
     * Set underline of the format.
559
     *
560
     * @param integer $underline The value for underline. Possible values are:
561
     *                           1 => underline, 2 => double underline
562
     */
563
    public function set_underline($underline) {
564
        if ($underline == 1) {
565
            $this->format['font']['underline'] = Font::UNDERLINE_SINGLE;
566
        } else if ($underline == 2) {
567
            $this->format['font']['underline'] = Font::UNDERLINE_DOUBLE;
568
        } else {
569
            $this->format['font']['underline'] = Font::UNDERLINE_NONE;
570
        }
571
    }
572
 
573
    /**
574
     * Set italic of the format.
575
     */
576
    public function set_italic() {
577
        $this->format['font']['italic'] = true;
578
    }
579
 
580
    /**
581
     * Set strikeout of the format.
582
     */
583
    public function set_strikeout() {
584
        $this->format['font']['strikethrough'] = true;
585
    }
586
 
587
    /**
588
     * Set outlining of the format.
589
     */
590
    public function set_outline() {
591
        // Not implemented.
592
    }
593
 
594
    /**
595
     * Set shadow of the format.
596
     */
597
    public function set_shadow() {
598
        // Not implemented.
599
    }
600
 
601
    /**
602
     * Set the script of the text.
603
     *
604
     * @param integer $script The value for script type. Possible values are:
605
     *                        1 => superscript, 2 => subscript
606
     */
607
    public function set_script($script) {
608
        if ($script == 1) {
609
            $this->format['font']['superscript'] = true;
610
        } else if ($script == 2) {
611
            $this->format['font']['subscript'] = true;
612
        } else {
613
            $this->format['font']['superscript'] = false;
614
            $this->format['font']['subscript'] = false;
615
        }
616
    }
617
 
618
    /**
619
     * Set color of the format. Used to specify the color of the text to be formatted.
620
     *
621
     * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63])
622
     */
623
    public function set_color($color) {
624
        $this->format['font']['color']['rgb'] = $this->parse_color($color);
625
    }
626
 
627
    /**
628
     * Standardise colour name.
629
     *
630
     * @param mixed $color name of the color (i.e.: 'blue', 'red', etc..), or an integer (range is [8...63]).
631
     * @return string the RGB color value
632
     */
633
    protected function parse_color($color) {
634
        if (strpos($color, '#') === 0) {
635
            // No conversion should be needed.
636
            return substr($color, 1);
637
        }
638
 
639
        if ($color > 7 and $color < 53) {
640
            $numbers = array(
641
                8  => 'black',
642
                12 => 'blue',
643
                16 => 'brown',
644
                15 => 'cyan',
645
                23 => 'gray',
646
                17 => 'green',
647
                11 => 'lime',
648
                14 => 'magenta',
649
                18 => 'navy',
650
                53 => 'orange',
651
                33 => 'pink',
652
                20 => 'purple',
653
                10 => 'red',
654
                22 => 'silver',
655
                9  => 'white',
656
                13 => 'yellow',
657
            );
658
            if (isset($numbers[$color])) {
659
                $color = $numbers[$color];
660
            } else {
661
                $color = 'black';
662
            }
663
        }
664
 
665
        $colors = array(
666
            'aqua'    => '00FFFF',
667
            'black'   => '000000',
668
            'blue'    => '0000FF',
669
            'brown'   => 'A52A2A',
670
            'cyan'    => '00FFFF',
671
            'fuchsia' => 'FF00FF',
672
            'gray'    => '808080',
673
            'grey'    => '808080',
674
            'green'   => '00FF00',
675
            'lime'    => '00FF00',
676
            'magenta' => 'FF00FF',
677
            'maroon'  => '800000',
678
            'navy'    => '000080',
679
            'orange'  => 'FFA500',
680
            'olive'   => '808000',
681
            'pink'    => 'FAAFBE',
682
            'purple'  => '800080',
683
            'red'     => 'FF0000',
684
            'silver'  => 'C0C0C0',
685
            'teal'    => '008080',
686
            'white'   => 'FFFFFF',
687
            'yellow'  => 'FFFF00',
688
        );
689
 
690
        if (isset($colors[$color])) {
691
            return($colors[$color]);
692
        }
693
 
694
        return($colors['black']);
695
    }
696
 
697
    /**
698
     * Not used.
699
     *
700
     * @param mixed $color
701
     */
702
    public function set_fg_color($color) {
703
        // Not implemented.
704
    }
705
 
706
    /**
707
     * Set background color of the cell.
708
     *
709
     * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63])
710
     */
711
    public function set_bg_color($color) {
712
        if (!isset($this->format['fill']['fillType'])) {
713
            $this->format['fill']['fillType'] = Fill::FILL_SOLID;
714
        }
715
        $this->format['fill']['color']['rgb'] = $this->parse_color($color);
716
    }
717
 
718
    /**
719
     * Set the cell fill pattern.
720
     *
721
     * @deprecated use set_bg_color() instead.
722
     * @param integer
723
     */
724
    public function set_pattern($pattern=1) {
725
        if ($pattern > 0) {
726
            if (!isset($this->format['fill']['color']['rgb'])) {
727
                $this->set_bg_color('black');
728
            }
729
        } else {
730
            unset($this->format['fill']['color']['rgb']);
731
            unset($this->format['fill']['fillType']);
732
        }
733
    }
734
 
735
    /**
736
     * Set text wrap of the format.
737
     */
738
    public function set_text_wrap() {
739
        $this->format['alignment']['wrapText'] = true;
740
    }
741
 
742
    /**
743
     * Set the cell alignment of the format.
744
     *
745
     * @param string $location alignment for the cell ('left', 'right', 'justify', etc...)
746
     */
747
    public function set_align($location) {
748
        if (in_array($location, array('left', 'centre', 'center', 'right', 'fill', 'merge', 'justify', 'equal_space'))) {
749
            $this->set_h_align($location);
750
 
751
        } else if (in_array($location, array('top', 'vcentre', 'vcenter', 'bottom', 'vjustify', 'vequal_space'))) {
752
            $this->set_v_align($location);
753
        }
754
    }
755
 
756
    /**
757
     * Set the cell horizontal alignment of the format.
758
     *
759
     * @param string $location alignment for the cell ('left', 'right', 'justify', etc...)
760
     */
761
    public function set_h_align($location) {
762
        switch ($location) {
763
            case 'left':
764
                $this->format['alignment']['horizontal'] = Alignment::HORIZONTAL_LEFT;
765
                break;
766
            case 'center':
767
            case 'centre':
768
                $this->format['alignment']['horizontal'] = Alignment::HORIZONTAL_CENTER;
769
                break;
770
            case 'right':
771
                $this->format['alignment']['horizontal'] = Alignment::HORIZONTAL_RIGHT;
772
                break;
773
            case 'justify':
774
                $this->format['alignment']['horizontal'] = Alignment::HORIZONTAL_JUSTIFY;
775
                break;
776
            default:
777
                $this->format['alignment']['horizontal'] = Alignment::HORIZONTAL_GENERAL;
778
        }
779
    }
780
 
781
    /**
782
     * Set the cell vertical alignment of the format.
783
     *
784
     * @param string $location alignment for the cell ('top', 'bottom', 'center', 'justify')
785
     */
786
    public function set_v_align($location) {
787
        switch ($location) {
788
            case 'top':
789
                $this->format['alignment']['vertical'] = Alignment::VERTICAL_TOP;
790
                break;
791
            case 'vcentre':
792
            case 'vcenter':
793
            case 'centre':
794
            case 'center':
795
                $this->format['alignment']['vertical'] = Alignment::VERTICAL_CENTER;
796
                break;
797
            case 'vjustify':
798
            case 'justify':
799
                $this->format['alignment']['vertical'] = Alignment::VERTICAL_JUSTIFY;
800
                break;
801
            default:
802
                $this->format['alignment']['vertical'] = Alignment::VERTICAL_BOTTOM;
803
        }
804
    }
805
 
806
    /**
807
     * Set the top border of the format.
808
     *
809
     * @param integer $style style for the cell. 1 => thin, 2 => thick
810
     */
811
    public function set_top($style) {
812
        if ($style == 1) {
813
            $this->format['borders']['top']['borderStyle'] = Border::BORDER_THIN;
814
        } else if ($style == 2) {
815
            $this->format['borders']['top']['borderStyle'] = Border::BORDER_THICK;
816
        } else {
817
            $this->format['borders']['top']['borderStyle'] = Border::BORDER_NONE;
818
        }
819
    }
820
 
821
    /**
822
     * Set the bottom border of the format.
823
     *
824
     * @param integer $style style for the cell. 1 => thin, 2 => thick
825
     */
826
    public function set_bottom($style) {
827
        if ($style == 1) {
828
            $this->format['borders']['bottom']['borderStyle'] = Border::BORDER_THIN;
829
        } else if ($style == 2) {
830
            $this->format['borders']['bottom']['borderStyle'] = Border::BORDER_THICK;
831
        } else {
832
            $this->format['borders']['bottom']['borderStyle'] = Border::BORDER_NONE;
833
        }
834
    }
835
 
836
    /**
837
     * Set the left border of the format.
838
     *
839
     * @param integer $style style for the cell. 1 => thin, 2 => thick
840
     */
841
    public function set_left($style) {
842
        if ($style == 1) {
843
            $this->format['borders']['left']['borderStyle'] = Border::BORDER_THIN;
844
        } else if ($style == 2) {
845
            $this->format['borders']['left']['borderStyle'] = Border::BORDER_THICK;
846
        } else {
847
            $this->format['borders']['left']['borderStyle'] = Border::BORDER_NONE;
848
        }
849
    }
850
 
851
    /**
852
     * Set the right border of the format.
853
     *
854
     * @param integer $style style for the cell. 1 => thin, 2 => thick
855
     */
856
    public function set_right($style) {
857
        if ($style == 1) {
858
            $this->format['borders']['right']['borderStyle'] = Border::BORDER_THIN;
859
        } else if ($style == 2) {
860
            $this->format['borders']['right']['borderStyle'] = Border::BORDER_THICK;
861
        } else {
862
            $this->format['borders']['right']['borderStyle'] = Border::BORDER_NONE;
863
        }
864
    }
865
 
866
    /**
867
     * Set cells borders to the same style.
868
     *
869
     * @param integer $style style to apply for all cell borders. 1 => thin, 2 => thick.
870
     */
871
    public function set_border($style) {
872
        $this->set_top($style);
873
        $this->set_bottom($style);
874
        $this->set_left($style);
875
        $this->set_right($style);
876
    }
877
 
878
    /**
879
     * Set the numerical format of the format.
880
     * It can be date, time, currency, etc...
881
     *
882
     * @param mixed $numformat The numeric format
883
     */
884
    public function set_num_format($numformat) {
885
        $numbers = array();
886
 
887
        $numbers[1] = '0';
888
        $numbers[2] = '0.00';
889
        $numbers[3] = '#,##0';
890
        $numbers[4] = '#,##0.00';
891
        $numbers[11] = '0.00E+00';
892
        $numbers[12] = '# ?/?';
893
        $numbers[13] = '# ??/??';
894
        $numbers[14] = 'mm-dd-yy';
895
        $numbers[15] = 'd-mmm-yy';
896
        $numbers[16] = 'd-mmm';
897
        $numbers[17] = 'mmm-yy';
898
        $numbers[22] = 'm/d/yy h:mm';
899
        $numbers[49] = '@';
900
 
901
        if ($numformat !== 0 and in_array($numformat, $numbers)) {
902
            $this->format['numberFormat']['formatCode'] = $numformat;
903
        }
904
 
905
        if (!isset($numbers[$numformat])) {
906
            return;
907
        }
908
 
909
        $this->format['numberFormat']['formatCode'] = $numbers[$numformat];
910
    }
911
}