summaryrefslogtreecommitdiffstats
path: root/library/Fileshipper/Xlsx/Workbook.php
blob: 9c20d955b3ca4b0f61948f6e6f7c1b1e8bf9308f (plain)
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
<?php

namespace Icinga\Module\Fileshipper\Xlsx;

use RuntimeException;
use ZipArchive;

/**
 * Classes in this namespace have been built roughly based on various OSS
 * XLSXReader implementations
 */
class Workbook
{
    // XML schemas
    const SCHEMA_OFFICEDOCUMENT  = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument';
    const SCHEMA_OFFICEDOCUMENT_RELATIONSHIP = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships';
    const SCHEMA_RELATIONSHIP    = 'http://schemas.openxmlformats.org/package/2006/relationships';
    const SCHEMA_SHAREDSTRINGS   = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings';
    const SCHEMA_WORKSHEETRELATION = 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet';

    protected static $zipErrors = [
        ZipArchive::ER_EXISTS => 'File already exists',
        ZipArchive::ER_INCONS => 'Zip archive inconsistent',
        ZipArchive::ER_INVAL  => 'Invalid argument',
        ZipArchive::ER_MEMORY => 'Malloc failure',
        ZipArchive::ER_NOENT  => 'No such file',
        ZipArchive::ER_NOZIP  => 'Not a zip archive',
        ZipArchive::ER_OPEN   => 'Can\'t open file',
        ZipArchive::ER_READ   => 'Read error',
        ZipArchive::ER_SEEK   => 'Seek error',
    ];

    /** @var Worksheet[] */
    protected $sheets = [];

    public $sharedStrings = [];

    protected $sheetInfo;

    protected $sheetNameIndex;

    /** @var ZipArchive */
    protected $zip;

    public $config = [
        'removeTrailingRows' => true
    ];

    protected $mainRelation;

    public function __construct($filename, $config = [])
    {
        $this->config = array_merge($this->config, $config);
        $this->initialize($filename);
    }

    protected function initialize($filename)
    {
        $this->zip = new ZipArchive();
        if (true === ($result = $this->zip->open($filename))) {
            $this->parse();
        } else {
            throw new RuntimeException(sprintf(
                'Failed to open %s : %s',
                $filename,
                $this->getZipErrorString($result)
            ));
        }
    }

    protected function getZipErrorString($errorCode)
    {
        if (array_key_exists($errorCode, self::$zipErrors)) {
            return self::$zipErrors[$errorCode];
        } else {
            return "Unknown ZIP error code $errorCode";
        }
    }

    // get a file from the zip
    protected function extractFile($name)
    {
        $data = $this->zip->getFromName($name);
        if ($data === false) {
            throw new RuntimeException(sprintf(
                "File %s does not exist in the Excel file",
                $name
            ));
        } else {
            return $data;
        }
    }

    protected function loadPackageRelationshipXml()
    {
        return simplexml_load_string($this->extractFile('_rels/.rels'));
    }

    /**
     * @return \SimpleXMLElement[]
     */
    protected function getPackageRelationships()
    {
        return $this->loadPackageRelationshipXml()->Relationship;
    }

    // workbookXML
    protected function getMainDocumentRelation()
    {
        if ($this->mainRelation === null) {
            foreach ($this->getPackageRelationships() as $relation) {
                if ($relation['Type'] == self::SCHEMA_OFFICEDOCUMENT) {
                    $this->mainRelation = $relation;
                    break;
                }
            }

            if ($this->mainRelation === null) {
                throw new RuntimeException(
                    'Got invalid Excel file, found no main document'
                );
            }
        }

        return $this->mainRelation;
    }

    protected function getWorkbookXml()
    {
        return simplexml_load_string(
            $this->extractFile(
                $this->getMainDocumentRelation()['Target']
            )
        );
    }

    protected function getWorkbookDir()
    {
        return dirname($this->getMainDocumentRelation()['Target']);
    }

    /**
     * @return \SimpleXMLElement[]
     */
    protected function getWorkbookRelationShips()
    {
        $wbDir = $this->getWorkbookDir();
        $target = basename($this->getMainDocumentRelation()['Target']);

        return simplexml_load_string(
            $this->extractFile("$wbDir/_rels/$target.rels")
        )->Relationship;
    }

    // extract the shared string and the list of sheets
    protected function parse()
    {
        $sheets = [];
        /** @var \SimpleXMLElement $sheet */
        $pos = 0;
        foreach ($this->getWorkbookXml()->sheets->sheet as $sheet) {
            $pos++;
            $rId = (string) $sheet->attributes('r', true)->id;
            // $sheets[$pos] = [ --> check docs
            $sheets[$rId] = [
                'rId'     => $rId,
                'sheetId' => (int)$sheet['sheetId'],
                'name'    => (string)$sheet['name'],
            ];
        }

        $workbookDir = $this->getWorkbookDir() . '/';
        foreach ($this->getWorkbookRelationShips() as $relation) {
            switch ($relation['Type']) {
                case self::SCHEMA_WORKSHEETRELATION:
                    $sheets[(string) $relation['Id']]['path'] = $workbookDir . (string)$relation['Target'];
                    break;

                case self::SCHEMA_SHAREDSTRINGS:
                    $sharedStringsXML = simplexml_load_string(
                        $this->extractFile($workbookDir . $relation['Target'])
                    );

                    foreach ($sharedStringsXML->si as $val) {
                        if (isset($val->t)) {
                            $this->sharedStrings[] = (string)$val->t;
                        } elseif (isset($val->r)) {
                            $this->sharedStrings[] = Utils::parseRichText($val);
                        }
                    }

                    break;
            }
        }

        $this->sheetInfo = [];
        foreach ($sheets as $rid => $info) {
            if (! array_key_exists('path', $info)) {
                var_dump($sheets);
                exit;
            }
            $this->sheetInfo[$info['name']] = [
                'sheetId' => $info['sheetId'],
                'rid'     => $rid,
                'path'    => $info['path']
            ];
        }
    }

    // returns an array of sheet names, indexed by sheetId
    public function getSheetNames()
    {
        $res = [];
        foreach ($this->sheetInfo as $sheetName => $info) {
            $res[$info['sheetId']] = $sheetName;
            // $res[$info['rid']] = $sheetName;
        }

        return $res;
    }

    public function getSheetCount()
    {
        return count($this->sheetInfo);
    }

    // instantiates a sheet object (if needed) and returns an array of its data
    public function getSheetData($sheetNameOrId)
    {
        $sheet = $this->getSheet($sheetNameOrId);

        return $sheet->getData();
    }

    // instantiates a sheet object (if needed) and returns the sheet object
    public function getSheet($sheet)
    {
        if (is_numeric($sheet)) {
            $sheet = $this->getSheetNameById($sheet);
        } elseif (!is_string($sheet)) {
            throw new RuntimeException("Sheet must be a string or a sheet Id");
        }
        if (!array_key_exists($sheet, $this->sheets)) {
            $this->sheets[$sheet] = new Worksheet($this->getSheetXML($sheet), $sheet, $this);
        }

        return $this->sheets[$sheet];
    }

    public function getSheetByName($name)
    {
        if (!array_key_exists($name, $this->sheets)) {
            $this->sheets[$name] = new Worksheet($this->getSheetXML($name), $name, $this);
        }

        return $this->sheets[$name];
    }

    public function enumRidNames()
    {
        $res = [];
        foreach ($this->sheetInfo as $name => $info) {
            $res[$name] = $name;
        }

        return $res;
    }

    public function getSheetNameById($sheetId)
    {
        foreach ($this->sheetInfo as $sheetName => $sheetInfo) {
            if ($sheetInfo['sheetId'] === $sheetId) {
                return $sheetName;
            }
        }

        throw new RuntimeException(sprintf(
            "Sheet ID %s does not exist in the Excel file",
            $sheetId
        ));
    }

    public function getFirstSheetName()
    {
        if (empty($this->sheetInfo)) {
            throw new RuntimeException('Workbook contains no sheets');
        }

        foreach ($this->sheetInfo as $sheetName => $sheetInfo) {
            return $sheetName;
        }
    }

    protected function getSheetXML($name)
    {
        return simplexml_load_string(
            $this->extractFile($this->sheetInfo[$name]['path'])
        );
    }
}