Passed
Push — master ( fde2cc...f1d90a )
by Mark
17:04 queued 08:09
created

Parser::rangeToPackedRange()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 18
nc 8
nop 1
dl 0
loc 30
ccs 0
cts 19
cp 0
crap 30
rs 9.3554
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer\Xls;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
7
use PhpOffice\PhpSpreadsheet\Spreadsheet;
8
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet as PhpspreadsheetWorksheet;
9
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
10
11
// Original file header of PEAR::Spreadsheet_Excel_Writer_Parser (used as the base for this class):
12
// -----------------------------------------------------------------------------------------
13
// *  Class for parsing Excel formulas
14
// *
15
// *  License Information:
16
// *
17
// *    Spreadsheet_Excel_Writer:  A library for generating Excel Spreadsheets
18
// *    Copyright (c) 2002-2003 Xavier Noguer [email protected]
19
// *
20
// *    This library is free software; you can redistribute it and/or
21
// *    modify it under the terms of the GNU Lesser General Public
22
// *    License as published by the Free Software Foundation; either
23
// *    version 2.1 of the License, or (at your option) any later version.
24
// *
25
// *    This library is distributed in the hope that it will be useful,
26
// *    but WITHOUT ANY WARRANTY; without even the implied warranty of
27
// *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28
// *    Lesser General Public License for more details.
29
// *
30
// *    You should have received a copy of the GNU Lesser General Public
31
// *    License along with this library; if not, write to the Free Software
32
// *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
33
// */
34
class Parser
35
{
36
    /**    Constants                */
37
    // Sheet title in unquoted form
38
    // Invalid sheet title characters cannot occur in the sheet title:
39
    //         *:/\?[]
40
    // Moreover, there are valid sheet title characters that cannot occur in unquoted form (there may be more?)
41
    // +-% '^&<>=,;#()"{}
42
    const REGEX_SHEET_TITLE_UNQUOTED = '[^\*\:\/\\\\\?\[\]\+\-\% \\\'\^\&\<\>\=\,\;\#\(\)\"\{\}]+';
43
44
    // Sheet title in quoted form (without surrounding quotes)
45
    // Invalid sheet title characters cannot occur in the sheet title:
46
    // *:/\?[]                    (usual invalid sheet title characters)
47
    // Single quote is represented as a pair ''
48
    const REGEX_SHEET_TITLE_QUOTED = '(([^\*\:\/\\\\\?\[\]\\\'])+|(\\\'\\\')+)+';
49
50
    /**
51
     * The index of the character we are currently looking at.
52
     *
53
     * @var int
54
     */
55
    public $currentCharacter;
56
57
    /**
58
     * The token we are working on.
59
     *
60
     * @var string
61
     */
62
    public $currentToken;
63
64
    /**
65
     * The formula to parse.
66
     *
67
     * @var string
68
     */
69
    private $formula;
70
71
    /**
72
     * The character ahead of the current char.
73
     *
74
     * @var string
75
     */
76
    public $lookAhead;
77
78
    /**
79
     * The parse tree to be generated.
80
     *
81
     * @var array|string
82
     */
83
    public $parseTree;
84
85
    /**
86
     * Array of external sheets.
87
     *
88
     * @var array
89
     */
90
    private $externalSheets;
91
92
    /**
93
     * Array of sheet references in the form of REF structures.
94
     *
95
     * @var array
96
     */
97
    public $references;
98
99
    /**
100
     * The Excel ptg indices.
101
     *
102
     * @var array
103
     */
104
    private $ptg = [
105
        'ptgExp' => 0x01,
106
        'ptgTbl' => 0x02,
107
        'ptgAdd' => 0x03,
108
        'ptgSub' => 0x04,
109
        'ptgMul' => 0x05,
110
        'ptgDiv' => 0x06,
111
        'ptgPower' => 0x07,
112
        'ptgConcat' => 0x08,
113
        'ptgLT' => 0x09,
114
        'ptgLE' => 0x0A,
115
        'ptgEQ' => 0x0B,
116
        'ptgGE' => 0x0C,
117
        'ptgGT' => 0x0D,
118
        'ptgNE' => 0x0E,
119
        'ptgIsect' => 0x0F,
120
        'ptgUnion' => 0x10,
121
        'ptgRange' => 0x11,
122
        'ptgUplus' => 0x12,
123
        'ptgUminus' => 0x13,
124
        'ptgPercent' => 0x14,
125
        'ptgParen' => 0x15,
126
        'ptgMissArg' => 0x16,
127
        'ptgStr' => 0x17,
128
        'ptgAttr' => 0x19,
129
        'ptgSheet' => 0x1A,
130
        'ptgEndSheet' => 0x1B,
131
        'ptgErr' => 0x1C,
132
        'ptgBool' => 0x1D,
133
        'ptgInt' => 0x1E,
134
        'ptgNum' => 0x1F,
135
        'ptgArray' => 0x20,
136
        'ptgFunc' => 0x21,
137
        'ptgFuncVar' => 0x22,
138
        'ptgName' => 0x23,
139
        'ptgRef' => 0x24,
140
        'ptgArea' => 0x25,
141
        'ptgMemArea' => 0x26,
142
        'ptgMemErr' => 0x27,
143
        'ptgMemNoMem' => 0x28,
144
        'ptgMemFunc' => 0x29,
145
        'ptgRefErr' => 0x2A,
146
        'ptgAreaErr' => 0x2B,
147
        'ptgRefN' => 0x2C,
148
        'ptgAreaN' => 0x2D,
149
        'ptgMemAreaN' => 0x2E,
150
        'ptgMemNoMemN' => 0x2F,
151
        'ptgNameX' => 0x39,
152
        'ptgRef3d' => 0x3A,
153
        'ptgArea3d' => 0x3B,
154
        'ptgRefErr3d' => 0x3C,
155
        'ptgAreaErr3d' => 0x3D,
156
        'ptgArrayV' => 0x40,
157
        'ptgFuncV' => 0x41,
158
        'ptgFuncVarV' => 0x42,
159
        'ptgNameV' => 0x43,
160
        'ptgRefV' => 0x44,
161
        'ptgAreaV' => 0x45,
162
        'ptgMemAreaV' => 0x46,
163
        'ptgMemErrV' => 0x47,
164
        'ptgMemNoMemV' => 0x48,
165
        'ptgMemFuncV' => 0x49,
166
        'ptgRefErrV' => 0x4A,
167
        'ptgAreaErrV' => 0x4B,
168
        'ptgRefNV' => 0x4C,
169
        'ptgAreaNV' => 0x4D,
170
        'ptgMemAreaNV' => 0x4E,
171
        'ptgMemNoMemNV' => 0x4F,
172
        'ptgFuncCEV' => 0x58,
173
        'ptgNameXV' => 0x59,
174
        'ptgRef3dV' => 0x5A,
175
        'ptgArea3dV' => 0x5B,
176
        'ptgRefErr3dV' => 0x5C,
177
        'ptgAreaErr3dV' => 0x5D,
178
        'ptgArrayA' => 0x60,
179
        'ptgFuncA' => 0x61,
180
        'ptgFuncVarA' => 0x62,
181
        'ptgNameA' => 0x63,
182
        'ptgRefA' => 0x64,
183
        'ptgAreaA' => 0x65,
184
        'ptgMemAreaA' => 0x66,
185
        'ptgMemErrA' => 0x67,
186
        'ptgMemNoMemA' => 0x68,
187
        'ptgMemFuncA' => 0x69,
188
        'ptgRefErrA' => 0x6A,
189
        'ptgAreaErrA' => 0x6B,
190
        'ptgRefNA' => 0x6C,
191
        'ptgAreaNA' => 0x6D,
192
        'ptgMemAreaNA' => 0x6E,
193
        'ptgMemNoMemNA' => 0x6F,
194
        'ptgFuncCEA' => 0x78,
195
        'ptgNameXA' => 0x79,
196
        'ptgRef3dA' => 0x7A,
197
        'ptgArea3dA' => 0x7B,
198
        'ptgRefErr3dA' => 0x7C,
199
        'ptgAreaErr3dA' => 0x7D,
200
    ];
201
202
    /**
203
     * Thanks to Michael Meeks and Gnumeric for the initial arg values.
204
     *
205
     * The following hash was generated by "function_locale.pl" in the distro.
206
     * Refer to function_locale.pl for non-English function names.
207
     *
208
     * The array elements are as follow:
209
     * ptg:   The Excel function ptg code.
210
     * args:  The number of arguments that the function takes:
211
     *           >=0 is a fixed number of arguments.
212
     *           -1  is a variable  number of arguments.
213
     * class: The reference, value or array class of the function args.
214
     * vol:   The function is volatile.
215
     *
216
     * @var array
217
     */
218
    private $functions = [
219
        // function                  ptg  args  class  vol
220
        'COUNT' => [0, -1, 0, 0],
221
        'IF' => [1, -1, 1, 0],
222
        'ISNA' => [2, 1, 1, 0],
223
        'ISERROR' => [3, 1, 1, 0],
224
        'SUM' => [4, -1, 0, 0],
225
        'AVERAGE' => [5, -1, 0, 0],
226
        'MIN' => [6, -1, 0, 0],
227
        'MAX' => [7, -1, 0, 0],
228
        'ROW' => [8, -1, 0, 0],
229
        'COLUMN' => [9, -1, 0, 0],
230
        'NA' => [10, 0, 0, 0],
231
        'NPV' => [11, -1, 1, 0],
232
        'STDEV' => [12, -1, 0, 0],
233
        'DOLLAR' => [13, -1, 1, 0],
234
        'FIXED' => [14, -1, 1, 0],
235
        'SIN' => [15, 1, 1, 0],
236
        'COS' => [16, 1, 1, 0],
237
        'TAN' => [17, 1, 1, 0],
238
        'ATAN' => [18, 1, 1, 0],
239
        'PI' => [19, 0, 1, 0],
240
        'SQRT' => [20, 1, 1, 0],
241
        'EXP' => [21, 1, 1, 0],
242
        'LN' => [22, 1, 1, 0],
243
        'LOG10' => [23, 1, 1, 0],
244
        'ABS' => [24, 1, 1, 0],
245
        'INT' => [25, 1, 1, 0],
246
        'SIGN' => [26, 1, 1, 0],
247
        'ROUND' => [27, 2, 1, 0],
248
        'LOOKUP' => [28, -1, 0, 0],
249
        'INDEX' => [29, -1, 0, 1],
250
        'REPT' => [30, 2, 1, 0],
251
        'MID' => [31, 3, 1, 0],
252
        'LEN' => [32, 1, 1, 0],
253
        'VALUE' => [33, 1, 1, 0],
254
        'TRUE' => [34, 0, 1, 0],
255
        'FALSE' => [35, 0, 1, 0],
256
        'AND' => [36, -1, 0, 0],
257
        'OR' => [37, -1, 0, 0],
258
        'NOT' => [38, 1, 1, 0],
259
        'MOD' => [39, 2, 1, 0],
260
        'DCOUNT' => [40, 3, 0, 0],
261
        'DSUM' => [41, 3, 0, 0],
262
        'DAVERAGE' => [42, 3, 0, 0],
263
        'DMIN' => [43, 3, 0, 0],
264
        'DMAX' => [44, 3, 0, 0],
265
        'DSTDEV' => [45, 3, 0, 0],
266
        'VAR' => [46, -1, 0, 0],
267
        'DVAR' => [47, 3, 0, 0],
268
        'TEXT' => [48, 2, 1, 0],
269
        'LINEST' => [49, -1, 0, 0],
270
        'TREND' => [50, -1, 0, 0],
271
        'LOGEST' => [51, -1, 0, 0],
272
        'GROWTH' => [52, -1, 0, 0],
273
        'PV' => [56, -1, 1, 0],
274
        'FV' => [57, -1, 1, 0],
275
        'NPER' => [58, -1, 1, 0],
276
        'PMT' => [59, -1, 1, 0],
277
        'RATE' => [60, -1, 1, 0],
278
        'MIRR' => [61, 3, 0, 0],
279
        'IRR' => [62, -1, 0, 0],
280
        'RAND' => [63, 0, 1, 1],
281
        'MATCH' => [64, -1, 0, 0],
282
        'DATE' => [65, 3, 1, 0],
283
        'TIME' => [66, 3, 1, 0],
284
        'DAY' => [67, 1, 1, 0],
285
        'MONTH' => [68, 1, 1, 0],
286
        'YEAR' => [69, 1, 1, 0],
287
        'WEEKDAY' => [70, -1, 1, 0],
288
        'HOUR' => [71, 1, 1, 0],
289
        'MINUTE' => [72, 1, 1, 0],
290
        'SECOND' => [73, 1, 1, 0],
291
        'NOW' => [74, 0, 1, 1],
292
        'AREAS' => [75, 1, 0, 1],
293
        'ROWS' => [76, 1, 0, 1],
294
        'COLUMNS' => [77, 1, 0, 1],
295
        'OFFSET' => [78, -1, 0, 1],
296
        'SEARCH' => [82, -1, 1, 0],
297
        'TRANSPOSE' => [83, 1, 1, 0],
298
        'TYPE' => [86, 1, 1, 0],
299
        'ATAN2' => [97, 2, 1, 0],
300
        'ASIN' => [98, 1, 1, 0],
301
        'ACOS' => [99, 1, 1, 0],
302
        'CHOOSE' => [100, -1, 1, 0],
303
        'HLOOKUP' => [101, -1, 0, 0],
304
        'VLOOKUP' => [102, -1, 0, 0],
305
        'ISREF' => [105, 1, 0, 0],
306
        'LOG' => [109, -1, 1, 0],
307
        'CHAR' => [111, 1, 1, 0],
308
        'LOWER' => [112, 1, 1, 0],
309
        'UPPER' => [113, 1, 1, 0],
310
        'PROPER' => [114, 1, 1, 0],
311
        'LEFT' => [115, -1, 1, 0],
312
        'RIGHT' => [116, -1, 1, 0],
313
        'EXACT' => [117, 2, 1, 0],
314
        'TRIM' => [118, 1, 1, 0],
315
        'REPLACE' => [119, 4, 1, 0],
316
        'SUBSTITUTE' => [120, -1, 1, 0],
317
        'CODE' => [121, 1, 1, 0],
318
        'FIND' => [124, -1, 1, 0],
319
        'CELL' => [125, -1, 0, 1],
320
        'ISERR' => [126, 1, 1, 0],
321
        'ISTEXT' => [127, 1, 1, 0],
322
        'ISNUMBER' => [128, 1, 1, 0],
323
        'ISBLANK' => [129, 1, 1, 0],
324
        'T' => [130, 1, 0, 0],
325
        'N' => [131, 1, 0, 0],
326
        'DATEVALUE' => [140, 1, 1, 0],
327
        'TIMEVALUE' => [141, 1, 1, 0],
328
        'SLN' => [142, 3, 1, 0],
329
        'SYD' => [143, 4, 1, 0],
330
        'DDB' => [144, -1, 1, 0],
331
        'INDIRECT' => [148, -1, 1, 1],
332
        'CALL' => [150, -1, 1, 0],
333
        'CLEAN' => [162, 1, 1, 0],
334
        'MDETERM' => [163, 1, 2, 0],
335
        'MINVERSE' => [164, 1, 2, 0],
336
        'MMULT' => [165, 2, 2, 0],
337
        'IPMT' => [167, -1, 1, 0],
338
        'PPMT' => [168, -1, 1, 0],
339
        'COUNTA' => [169, -1, 0, 0],
340
        'PRODUCT' => [183, -1, 0, 0],
341
        'FACT' => [184, 1, 1, 0],
342
        'DPRODUCT' => [189, 3, 0, 0],
343
        'ISNONTEXT' => [190, 1, 1, 0],
344
        'STDEVP' => [193, -1, 0, 0],
345
        'VARP' => [194, -1, 0, 0],
346
        'DSTDEVP' => [195, 3, 0, 0],
347
        'DVARP' => [196, 3, 0, 0],
348
        'TRUNC' => [197, -1, 1, 0],
349
        'ISLOGICAL' => [198, 1, 1, 0],
350
        'DCOUNTA' => [199, 3, 0, 0],
351
        'USDOLLAR' => [204, -1, 1, 0],
352
        'FINDB' => [205, -1, 1, 0],
353
        'SEARCHB' => [206, -1, 1, 0],
354
        'REPLACEB' => [207, 4, 1, 0],
355
        'LEFTB' => [208, -1, 1, 0],
356
        'RIGHTB' => [209, -1, 1, 0],
357
        'MIDB' => [210, 3, 1, 0],
358
        'LENB' => [211, 1, 1, 0],
359
        'ROUNDUP' => [212, 2, 1, 0],
360
        'ROUNDDOWN' => [213, 2, 1, 0],
361
        'ASC' => [214, 1, 1, 0],
362
        'DBCS' => [215, 1, 1, 0],
363
        'RANK' => [216, -1, 0, 0],
364
        'ADDRESS' => [219, -1, 1, 0],
365
        'DAYS360' => [220, -1, 1, 0],
366
        'TODAY' => [221, 0, 1, 1],
367
        'VDB' => [222, -1, 1, 0],
368
        'MEDIAN' => [227, -1, 0, 0],
369
        'SUMPRODUCT' => [228, -1, 2, 0],
370
        'SINH' => [229, 1, 1, 0],
371
        'COSH' => [230, 1, 1, 0],
372
        'TANH' => [231, 1, 1, 0],
373
        'ASINH' => [232, 1, 1, 0],
374
        'ACOSH' => [233, 1, 1, 0],
375
        'ATANH' => [234, 1, 1, 0],
376
        'DGET' => [235, 3, 0, 0],
377
        'INFO' => [244, 1, 1, 1],
378
        'DB' => [247, -1, 1, 0],
379
        'FREQUENCY' => [252, 2, 0, 0],
380
        'ERROR.TYPE' => [261, 1, 1, 0],
381
        'REGISTER.ID' => [267, -1, 1, 0],
382
        'AVEDEV' => [269, -1, 0, 0],
383
        'BETADIST' => [270, -1, 1, 0],
384
        'GAMMALN' => [271, 1, 1, 0],
385
        'BETAINV' => [272, -1, 1, 0],
386
        'BINOMDIST' => [273, 4, 1, 0],
387
        'CHIDIST' => [274, 2, 1, 0],
388
        'CHIINV' => [275, 2, 1, 0],
389
        'COMBIN' => [276, 2, 1, 0],
390
        'CONFIDENCE' => [277, 3, 1, 0],
391
        'CRITBINOM' => [278, 3, 1, 0],
392
        'EVEN' => [279, 1, 1, 0],
393
        'EXPONDIST' => [280, 3, 1, 0],
394
        'FDIST' => [281, 3, 1, 0],
395
        'FINV' => [282, 3, 1, 0],
396
        'FISHER' => [283, 1, 1, 0],
397
        'FISHERINV' => [284, 1, 1, 0],
398
        'FLOOR' => [285, 2, 1, 0],
399
        'GAMMADIST' => [286, 4, 1, 0],
400
        'GAMMAINV' => [287, 3, 1, 0],
401
        'CEILING' => [288, 2, 1, 0],
402
        'HYPGEOMDIST' => [289, 4, 1, 0],
403
        'LOGNORMDIST' => [290, 3, 1, 0],
404
        'LOGINV' => [291, 3, 1, 0],
405
        'NEGBINOMDIST' => [292, 3, 1, 0],
406
        'NORMDIST' => [293, 4, 1, 0],
407
        'NORMSDIST' => [294, 1, 1, 0],
408
        'NORMINV' => [295, 3, 1, 0],
409
        'NORMSINV' => [296, 1, 1, 0],
410
        'STANDARDIZE' => [297, 3, 1, 0],
411
        'ODD' => [298, 1, 1, 0],
412
        'PERMUT' => [299, 2, 1, 0],
413
        'POISSON' => [300, 3, 1, 0],
414
        'TDIST' => [301, 3, 1, 0],
415
        'WEIBULL' => [302, 4, 1, 0],
416
        'SUMXMY2' => [303, 2, 2, 0],
417
        'SUMX2MY2' => [304, 2, 2, 0],
418
        'SUMX2PY2' => [305, 2, 2, 0],
419
        'CHITEST' => [306, 2, 2, 0],
420
        'CORREL' => [307, 2, 2, 0],
421
        'COVAR' => [308, 2, 2, 0],
422
        'FORECAST' => [309, 3, 2, 0],
423
        'FTEST' => [310, 2, 2, 0],
424
        'INTERCEPT' => [311, 2, 2, 0],
425
        'PEARSON' => [312, 2, 2, 0],
426
        'RSQ' => [313, 2, 2, 0],
427
        'STEYX' => [314, 2, 2, 0],
428
        'SLOPE' => [315, 2, 2, 0],
429
        'TTEST' => [316, 4, 2, 0],
430
        'PROB' => [317, -1, 2, 0],
431
        'DEVSQ' => [318, -1, 0, 0],
432
        'GEOMEAN' => [319, -1, 0, 0],
433
        'HARMEAN' => [320, -1, 0, 0],
434
        'SUMSQ' => [321, -1, 0, 0],
435
        'KURT' => [322, -1, 0, 0],
436
        'SKEW' => [323, -1, 0, 0],
437
        'ZTEST' => [324, -1, 0, 0],
438
        'LARGE' => [325, 2, 0, 0],
439
        'SMALL' => [326, 2, 0, 0],
440
        'QUARTILE' => [327, 2, 0, 0],
441
        'PERCENTILE' => [328, 2, 0, 0],
442
        'PERCENTRANK' => [329, -1, 0, 0],
443
        'MODE' => [330, -1, 2, 0],
444
        'TRIMMEAN' => [331, 2, 0, 0],
445
        'TINV' => [332, 2, 1, 0],
446
        'CONCATENATE' => [336, -1, 1, 0],
447
        'POWER' => [337, 2, 1, 0],
448
        'RADIANS' => [342, 1, 1, 0],
449
        'DEGREES' => [343, 1, 1, 0],
450
        'SUBTOTAL' => [344, -1, 0, 0],
451
        'SUMIF' => [345, -1, 0, 0],
452
        'COUNTIF' => [346, 2, 0, 0],
453
        'COUNTBLANK' => [347, 1, 0, 0],
454
        'ISPMT' => [350, 4, 1, 0],
455
        'DATEDIF' => [351, 3, 1, 0],
456
        'DATESTRING' => [352, 1, 1, 0],
457
        'NUMBERSTRING' => [353, 2, 1, 0],
458
        'ROMAN' => [354, -1, 1, 0],
459
        'GETPIVOTDATA' => [358, -1, 0, 0],
460
        'HYPERLINK' => [359, -1, 1, 0],
461
        'PHONETIC' => [360, 1, 0, 0],
462
        'AVERAGEA' => [361, -1, 0, 0],
463
        'MAXA' => [362, -1, 0, 0],
464
        'MINA' => [363, -1, 0, 0],
465
        'STDEVPA' => [364, -1, 0, 0],
466
        'VARPA' => [365, -1, 0, 0],
467
        'STDEVA' => [366, -1, 0, 0],
468
        'VARA' => [367, -1, 0, 0],
469
        'BAHTTEXT' => [368, 1, 0, 0],
470
    ];
471
472
    /** @var Spreadsheet */
473
    private $spreadsheet;
474
475
    /**
476
     * The class constructor.
477
     */
478 100
    public function __construct(Spreadsheet $spreadsheet)
479
    {
480 100
        $this->spreadsheet = $spreadsheet;
481
482 100
        $this->currentCharacter = 0;
483 100
        $this->currentToken = ''; // The token we are working on.
484 100
        $this->formula = ''; // The formula to parse.
485 100
        $this->lookAhead = ''; // The character ahead of the current char.
486 100
        $this->parseTree = ''; // The parse tree to be generated.
487 100
        $this->externalSheets = [];
488 100
        $this->references = [];
489
    }
490
491
    /**
492
     * Convert a token to the proper ptg value.
493
     *
494
     * @param mixed $token the token to convert
495
     *
496
     * @return mixed the converted token on success
497
     */
498 47
    private function convert($token)
499
    {
500 47
        if (preg_match('/"([^"]|""){0,255}"/', $token)) {
501 21
            return $this->convertString($token);
502
        }
503 47
        if (is_numeric($token)) {
504 42
            return $this->convertNumber($token);
505
        }
506
        // match references like A1 or $A$1
507 45
        if (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/', $token)) {
508 28
            return $this->convertRef2d($token);
509
        }
510
        // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1
511 45
        if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?(\\d+)$/u', $token)) {
512
            return $this->convertRef3d($token);
513
        }
514
        // match external references like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1
515 45
        if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?(\\d+)$/u", $token)) {
516 6
            return $this->convertRef3d($token);
517
        }
518
        // match ranges like A1:B2 or $A$1:$B$2
519 44
        if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/', $token)) {
520 25
            return $this->convertRange2d($token);
521
        }
522
        // match external ranges like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
523 43
        if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?(\\d+)\\:\$?([A-Ia-i]?[A-Za-z])?\$?(\\d+)$/u', $token)) {
524
            return $this->convertRange3d($token);
525
        }
526
        // match external ranges like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
527 43
        if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?(\\d+)\\:\\$?([A-Ia-i]?[A-Za-z])?\\$?(\\d+)$/u", $token)) {
528 4
            return $this->convertRange3d($token);
529
        }
530
        // operators (including parentheses)
531 43
        if (isset($this->ptg[$token])) {
532 27
            return pack('C', $this->ptg[$token]);
533
        }
534
        // match error codes
535 36
        if (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token == '#N/A') {
536 1
            return $this->convertError($token);
537
        }
538 36
        if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/mui', $token) && $this->spreadsheet->getDefinedName($token) !== null) {
539 5
            return $this->convertDefinedName($token);
540
        }
541
        // commented so argument number can be processed correctly. See toReversePolish().
542
        /*if (preg_match("/[A-Z0-9\xc0-\xdc\.]+/", $token))
543
        {
544
            return($this->convertFunction($token, $this->_func_args));
545
        }*/
546
        // if it's an argument, ignore the token (the argument remains)
547 34
        if ($token == 'arg') {
548 33
            return '';
549
        }
550 2
        if (preg_match('/^true$/i', $token)) {
551 1
            return $this->convertBool(1);
552
        }
553 2
        if (preg_match('/^false$/i', $token)) {
554 1
            return $this->convertBool(0);
555
        }
556
557
        // TODO: use real error codes
558 1
        throw new WriterException("Unknown token $token");
559
    }
560
561
    /**
562
     * Convert a number token to ptgInt or ptgNum.
563
     *
564
     * @param mixed $num an integer or double for conversion to its ptg value
565
     *
566
     * @return string
567
     */
568 42
    private function convertNumber($num)
569
    {
570
        // Integer in the range 0..2**16-1
571 42
        if ((preg_match('/^\\d+$/', $num)) && ($num <= 65535)) {
572 42
            return pack('Cv', $this->ptg['ptgInt'], $num);
573
        }
574
575
        // A float
576 11
        if (BIFFwriter::getByteOrder()) { // if it's Big Endian
577
            $num = strrev($num);
578
        }
579
580 11
        return pack('Cd', $this->ptg['ptgNum'], $num);
581
    }
582
583 1
    private function convertBool(int $num): string
584
    {
585 1
        return pack('CC', $this->ptg['ptgBool'], $num);
586
    }
587
588
    /**
589
     * Convert a string token to ptgStr.
590
     *
591
     * @param string $string a string for conversion to its ptg value
592
     *
593
     * @return mixed the converted token on success
594
     */
595 21
    private function convertString($string)
596
    {
597
        // chop away beggining and ending quotes
598 21
        $string = substr($string, 1, -1);
599 21
        if (strlen($string) > 255) {
600
            throw new WriterException('String is too long');
601
        }
602
603 21
        return pack('C', $this->ptg['ptgStr']) . StringHelper::UTF8toBIFF8UnicodeShort($string);
604
    }
605
606
    /**
607
     * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of
608
     * args that it takes.
609
     *
610
     * @param string $token the name of the function for convertion to ptg value
611
     * @param int $num_args the number of arguments the function receives
612
     *
613
     * @return string The packed ptg for the function
614
     */
615 32
    private function convertFunction($token, $num_args)
616
    {
617 32
        $args = $this->functions[$token][1];
618
619
        // Fixed number of args eg. TIME($i, $j, $k).
620 32
        if ($args >= 0) {
621 13
            return pack('Cv', $this->ptg['ptgFuncV'], $this->functions[$token][0]);
622
        }
623
624
        // Variable number of args eg. SUM($i, $j, $k, ..).
625 29
        return pack('CCv', $this->ptg['ptgFuncVarV'], $num_args, $this->functions[$token][0]);
626
    }
627
628
    /**
629
     * Convert an Excel range such as A1:D4 to a ptgRefV.
630
     *
631
     * @param string $range An Excel range in the A1:A2
632
     * @param int $class
633
     *
634
     * @return string
635
     */
636 25
    private function convertRange2d($range, $class = 0)
637
    {
638
        // TODO: possible class value 0,1,2 check Formula.pm
639
        // Split the range into 2 cell refs
640 25
        if (preg_match('/^(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)\:(\$)?([A-Ia-i]?[A-Za-z])(\$)?(\d+)$/', $range)) {
641 25
            [$cell1, $cell2] = explode(':', $range);
642
        } else {
643
            // TODO: use real error codes
644
            throw new WriterException('Unknown range separator');
645
        }
646
        // Convert the cell references
647 25
        [$row1, $col1] = $this->cellToPackedRowcol($cell1);
648 25
        [$row2, $col2] = $this->cellToPackedRowcol($cell2);
649
650
        // The ptg value depends on the class of the ptg.
651 25
        if ($class == 0) {
652 25
            $ptgArea = pack('C', $this->ptg['ptgArea']);
653
        } elseif ($class == 1) {
654
            $ptgArea = pack('C', $this->ptg['ptgAreaV']);
655
        } elseif ($class == 2) {
656
            $ptgArea = pack('C', $this->ptg['ptgAreaA']);
657
        } else {
658
            // TODO: use real error codes
659
            throw new WriterException("Unknown class $class");
660
        }
661
662 25
        return $ptgArea . $row1 . $row2 . $col1 . $col2;
663
    }
664
665
    /**
666
     * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to
667
     * a ptgArea3d.
668
     *
669
     * @param string $token an Excel range in the Sheet1!A1:A2 format
670
     *
671
     * @return mixed the packed ptgArea3d token on success
672
     */
673 4
    private function convertRange3d($token)
674
    {
675
        // Split the ref at the ! symbol
676 4
        [$ext_ref, $range] = PhpspreadsheetWorksheet::extractSheetTitle($token, true);
677
678
        // Convert the external reference part (different for BIFF8)
679 4
        $ext_ref = $this->getRefIndex($ext_ref);
680
681
        // Split the range into 2 cell refs
682 4
        [$cell1, $cell2] = explode(':', $range);
683
684
        // Convert the cell references
685 4
        if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\\d+)$/', $cell1)) {
686 4
            [$row1, $col1] = $this->cellToPackedRowcol($cell1);
687 4
            [$row2, $col2] = $this->cellToPackedRowcol($cell2);
688
        } else { // It's a rows range (like 26:27)
689
            [$row1, $col1, $row2, $col2] = $this->rangeToPackedRange($cell1 . ':' . $cell2);
690
        }
691
692
        // The ptg value depends on the class of the ptg.
693 4
        $ptgArea = pack('C', $this->ptg['ptgArea3d']);
694
695 4
        return $ptgArea . $ext_ref . $row1 . $row2 . $col1 . $col2;
696
    }
697
698
    /**
699
     * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV.
700
     *
701
     * @param string $cell An Excel cell reference
702
     *
703
     * @return string The cell in packed() format with the corresponding ptg
704
     */
705 28
    private function convertRef2d($cell)
706
    {
707
        // Convert the cell reference
708 28
        $cell_array = $this->cellToPackedRowcol($cell);
709 28
        [$row, $col] = $cell_array;
710
711
        // The ptg value depends on the class of the ptg.
712 28
        $ptgRef = pack('C', $this->ptg['ptgRefA']);
713
714 28
        return $ptgRef . $row . $col;
715
    }
716
717
    /**
718
     * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a
719
     * ptgRef3d.
720
     *
721
     * @param string $cell An Excel cell reference
722
     *
723
     * @return mixed the packed ptgRef3d token on success
724
     */
725 6
    private function convertRef3d($cell)
726
    {
727
        // Split the ref at the ! symbol
728 6
        [$ext_ref, $cell] = PhpspreadsheetWorksheet::extractSheetTitle($cell, true);
729
730
        // Convert the external reference part (different for BIFF8)
731 6
        $ext_ref = $this->getRefIndex($ext_ref);
732
733
        // Convert the cell reference part
734 5
        [$row, $col] = $this->cellToPackedRowcol($cell);
735
736
        // The ptg value depends on the class of the ptg.
737 5
        $ptgRef = pack('C', $this->ptg['ptgRef3dA']);
738
739 5
        return $ptgRef . $ext_ref . $row . $col;
740
    }
741
742
    /**
743
     * Convert an error code to a ptgErr.
744
     *
745
     * @param string $errorCode The error code for conversion to its ptg value
746
     *
747
     * @return string The error code ptgErr
748
     */
749 1
    private function convertError($errorCode)
750
    {
751
        switch ($errorCode) {
752 1
            case '#NULL!':
753
                return pack('C', 0x00);
754 1
            case '#DIV/0!':
755
                return pack('C', 0x07);
756 1
            case '#VALUE!':
757
                return pack('C', 0x0F);
758 1
            case '#REF!':
759
                return pack('C', 0x17);
760 1
            case '#NAME?':
761 1
                return pack('C', 0x1D);
762
            case '#NUM!':
763
                return pack('C', 0x24);
764
            case '#N/A':
765
                return pack('C', 0x2A);
766
        }
767
768
        return pack('C', 0xFF);
769
    }
770
771
    /** @var bool */
772
    private $tryDefinedName = false;
773
774 5
    private function convertDefinedName(string $name): string
775
    {
776 5
        if (strlen($name) > 255) {
777
            throw new WriterException('Defined Name is too long');
778
        }
779
780 5
        if ($this->tryDefinedName) {
781
            // @codeCoverageIgnoreStart
782
            $nameReference = 1;
783
            foreach ($this->spreadsheet->getDefinedNames() as $definedName) {
784
                if ($name === $definedName->getName()) {
785
                    break;
786
                }
787
                ++$nameReference;
788
            }
789
790
            $ptgRef = pack('Cvxx', $this->ptg['ptgName'], $nameReference);
791
792
            return $ptgRef;
793
            // @codeCoverageIgnoreEnd
794
        }
795
796 5
        throw new WriterException('Cannot yet write formulae with defined names to Xls');
797
    }
798
799
    /**
800
     * Look up the REF index that corresponds to an external sheet name
801
     * (or range). If it doesn't exist yet add it to the workbook's references
802
     * array. It assumes all sheet names given must exist.
803
     *
804
     * @param string $ext_ref The name of the external reference
805
     *
806
     * @return mixed The reference index in packed() format on success
807
     */
808 7
    private function getRefIndex($ext_ref)
809
    {
810 7
        $ext_ref = (string) preg_replace(["/^'/", "/'$/"], ['', ''], $ext_ref); // Remove leading and trailing ' if any.
811 7
        $ext_ref = str_replace('\'\'', '\'', $ext_ref); // Replace escaped '' with '
812
813
        // Check if there is a sheet range eg., Sheet1:Sheet2.
814 7
        if (preg_match('/:/', $ext_ref)) {
815
            [$sheet_name1, $sheet_name2] = explode(':', $ext_ref);
816
817
            $sheet1 = $this->getSheetIndex($sheet_name1);
818
            if ($sheet1 == -1) {
819
                throw new WriterException("Unknown sheet name $sheet_name1 in formula");
820
            }
821
            $sheet2 = $this->getSheetIndex($sheet_name2);
822
            if ($sheet2 == -1) {
823
                throw new WriterException("Unknown sheet name $sheet_name2 in formula");
824
            }
825
826
            // Reverse max and min sheet numbers if necessary
827
            if ($sheet1 > $sheet2) {
828
                [$sheet1, $sheet2] = [$sheet2, $sheet1];
829
            }
830
        } else { // Single sheet name only.
831 7
            $sheet1 = $this->getSheetIndex($ext_ref);
832 7
            if ($sheet1 == -1) {
833 1
                throw new WriterException("Unknown sheet name $ext_ref in formula");
834
            }
835 6
            $sheet2 = $sheet1;
836
        }
837
838
        // assume all references belong to this document
839 6
        $supbook_index = 0x00;
840 6
        $ref = pack('vvv', $supbook_index, $sheet1, $sheet2);
841 6
        $totalreferences = count($this->references);
842 6
        $index = -1;
843 6
        for ($i = 0; $i < $totalreferences; ++$i) {
844 6
            if ($ref == $this->references[$i]) {
845 6
                $index = $i;
846
847 6
                break;
848
            }
849
        }
850
        // if REF was not found add it to references array
851 6
        if ($index == -1) {
852
            $this->references[$totalreferences] = $ref;
853
            $index = $totalreferences;
854
        }
855
856 6
        return pack('v', $index);
857
    }
858
859
    /**
860
     * Look up the index that corresponds to an external sheet name. The hash of
861
     * sheet names is updated by the addworksheet() method of the
862
     * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
863
     *
864
     * @param string $sheet_name Sheet name
865
     *
866
     * @return int The sheet index, -1 if the sheet was not found
867
     */
868 7
    private function getSheetIndex($sheet_name)
869
    {
870 7
        if (!isset($this->externalSheets[$sheet_name])) {
871 1
            return -1;
872
        }
873
874 6
        return $this->externalSheets[$sheet_name];
875
    }
876
877
    /**
878
     * This method is used to update the array of sheet names. It is
879
     * called by the addWorksheet() method of the
880
     * \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook class.
881
     *
882
     * @param string $name The name of the worksheet being added
883
     * @param int $index The index of the worksheet being added
884
     *
885
     * @see \PhpOffice\PhpSpreadsheet\Writer\Xls\Workbook::addWorksheet()
886
     */
887 95
    public function setExtSheet($name, $index): void
888
    {
889 95
        $this->externalSheets[$name] = $index;
890
    }
891
892
    /**
893
     * pack() row and column into the required 3 or 4 byte format.
894
     *
895
     * @param string $cell The Excel cell reference to be packed
896
     *
897
     * @return array Array containing the row and column in packed() format
898
     */
899 37
    private function cellToPackedRowcol($cell)
900
    {
901 37
        $cell = strtoupper($cell);
902 37
        [$row, $col, $row_rel, $col_rel] = $this->cellToRowcol($cell);
903 37
        if ($col >= 256) {
904
            throw new WriterException("Column in: $cell greater than 255");
905
        }
906 37
        if ($row >= 65536) {
907
            throw new WriterException("Row in: $cell greater than 65536 ");
908
        }
909
910
        // Set the high bits to indicate if row or col are relative.
911 37
        $col |= $col_rel << 14;
912 37
        $col |= $row_rel << 15;
913 37
        $col = pack('v', $col);
914
915 37
        $row = pack('v', $row);
916
917 37
        return [$row, $col];
918
    }
919
920
    /**
921
     * pack() row range into the required 3 or 4 byte format.
922
     * Just using maximum col/rows, which is probably not the correct solution.
923
     *
924
     * @param string $range The Excel range to be packed
925
     *
926
     * @return array Array containing (row1,col1,row2,col2) in packed() format
927
     */
928
    private function rangeToPackedRange($range)
929
    {
930
        preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match);
931
        // return absolute rows if there is a $ in the ref
932
        $row1_rel = empty($match[1]) ? 1 : 0;
933
        $row1 = $match[2];
934
        $row2_rel = empty($match[3]) ? 1 : 0;
935
        $row2 = $match[4];
936
        // Convert 1-index to zero-index
937
        --$row1;
938
        --$row2;
939
        // Trick poor inocent Excel
940
        $col1 = 0;
941
        $col2 = 65535; // FIXME: maximum possible value for Excel 5 (change this!!!)
942
943
        // FIXME: this changes for BIFF8
944
        if (($row1 >= 65536) || ($row2 >= 65536)) {
945
            throw new WriterException("Row in: $range greater than 65536 ");
946
        }
947
948
        // Set the high bits to indicate if rows are relative.
949
        $col1 |= $row1_rel << 15;
950
        $col2 |= $row2_rel << 15;
951
        $col1 = pack('v', $col1);
952
        $col2 = pack('v', $col2);
953
954
        $row1 = pack('v', $row1);
955
        $row2 = pack('v', $row2);
956
957
        return [$row1, $col1, $row2, $col2];
958
    }
959
960
    /**
961
     * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero
962
     * indexed row and column number. Also returns two (0,1) values to indicate
963
     * whether the row or column are relative references.
964
     *
965
     * @param string $cell the Excel cell reference in A1 format
966
     *
967
     * @return array
968
     */
969 37
    private function cellToRowcol($cell)
970
    {
971 37
        preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/', $cell, $match);
972
        // return absolute column if there is a $ in the ref
973 37
        $col_rel = empty($match[1]) ? 1 : 0;
974 37
        $col_ref = $match[2];
975 37
        $row_rel = empty($match[3]) ? 1 : 0;
976 37
        $row = $match[4];
977
978
        // Convert base26 column string to a number.
979 37
        $expn = strlen($col_ref) - 1;
980 37
        $col = 0;
981 37
        $col_ref_length = strlen($col_ref);
982 37
        for ($i = 0; $i < $col_ref_length; ++$i) {
983 37
            $col += (ord($col_ref[$i]) - 64) * 26 ** $expn;
984 37
            --$expn;
985
        }
986
987
        // Convert 1-index to zero-index
988 37
        --$row;
989 37
        --$col;
990
991 37
        return [$row, $col, $row_rel, $col_rel];
992
    }
993
994
    /**
995
     * Advance to the next valid token.
996
     */
997 45
    private function advance(): void
998
    {
999 45
        $token = '';
1000 45
        $i = $this->currentCharacter;
1001 45
        $formula_length = strlen($this->formula);
1002
        // eat up white spaces
1003 45
        if ($i < $formula_length) {
1004 45
            while ($this->formula[$i] == ' ') {
1005 4
                ++$i;
1006
            }
1007
1008 45
            if ($i < ($formula_length - 1)) {
1009 44
                $this->lookAhead = $this->formula[$i + 1];
1010
            }
1011 45
            $token = '';
1012
        }
1013
1014 45
        while ($i < $formula_length) {
1015 45
            $token .= $this->formula[$i];
1016
1017 45
            if ($i < ($formula_length - 1)) {
1018 44
                $this->lookAhead = $this->formula[$i + 1];
1019
            } else {
1020 45
                $this->lookAhead = '';
1021
            }
1022
1023 45
            if ($this->match($token) != '') {
1024 45
                $this->currentCharacter = $i + 1;
1025 45
                $this->currentToken = $token;
1026
1027 45
                return;
1028
            }
1029
1030 44
            if ($i < ($formula_length - 2)) {
1031 41
                $this->lookAhead = $this->formula[$i + 2];
1032
            } else { // if we run out of characters lookAhead becomes empty
1033 30
                $this->lookAhead = '';
1034
            }
1035 44
            ++$i;
1036
        }
1037
        //die("Lexical error ".$this->currentCharacter);
1038
    }
1039
1040
    /**
1041
     * Checks if it's a valid token.
1042
     *
1043
     * @param mixed $token the token to check
1044
     *
1045
     * @return mixed The checked token or false on failure
1046
     */
1047 45
    private function match($token)
1048
    {
1049
        switch ($token) {
1050 45
            case '+':
1051 45
            case '-':
1052 45
            case '*':
1053 45
            case '/':
1054 45
            case '(':
1055 45
            case ')':
1056 45
            case ',':
1057 45
            case ';':
1058 45
            case '>=':
1059 45
            case '<=':
1060 45
            case '=':
1061 45
            case '<>':
1062 45
            case '^':
1063 45
            case '&':
1064 45
            case '%':
1065 42
                return $token;
1066
1067 45
            case '>':
1068 2
                if ($this->lookAhead === '=') { // it's a GE token
1069 1
                    break;
1070
                }
1071
1072 2
                return $token;
1073
1074 45
            case '<':
1075
                // it's a LE or a NE token
1076 8
                if (($this->lookAhead === '=') || ($this->lookAhead === '>')) {
1077 8
                    break;
1078
                }
1079
1080 1
                return $token;
1081
        }
1082
1083
        // if it's a reference A1 or $A$1 or $A1 or A$1
1084 45
        if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.') && ($this->lookAhead !== '!')) {
1085 28
            return $token;
1086
        }
1087
        // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
1088 45
        if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')) {
1089
            return $token;
1090
        }
1091
        // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
1092 45
        if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?\\d+$/u", $token) && !preg_match('/\d/', $this->lookAhead) && ($this->lookAhead !== ':') && ($this->lookAhead !== '.')) {
1093 6
            return $token;
1094
        }
1095
        // if it's a range A1:A2 or $A$1:$A$2
1096 45
        if (preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $token) && !preg_match('/\d/', $this->lookAhead)) {
1097 25
            return $token;
1098
        }
1099
        // If it's an external range like Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2
1100 45
        if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u', $token) && !preg_match('/\d/', $this->lookAhead)) {
1101
            return $token;
1102
        }
1103
        // If it's an external range like 'Sheet1'!A1:B2 or 'Sheet1:Sheet2'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1:Sheet2'!$A$1:$B$2
1104 45
        if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+:\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+$/u", $token) && !preg_match('/\d/', $this->lookAhead)) {
1105 4
            return $token;
1106
        }
1107
        // If it's a number (check that it's not a sheet name or range)
1108 45
        if (is_numeric($token) && (!is_numeric($token . $this->lookAhead) || ($this->lookAhead == '')) && ($this->lookAhead !== '!') && ($this->lookAhead !== ':')) {
1109 27
            return $token;
1110
        }
1111 44
        if (preg_match('/"([^"]|""){0,255}"/', $token) && $this->lookAhead !== '"' && (substr_count($token, '"') % 2 == 0)) {
1112
            // If it's a string (of maximum 255 characters)
1113 21
            return $token;
1114
        }
1115
        // If it's an error code
1116 44
        if (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $token) || $token === '#N/A') {
1117 1
            return $token;
1118
        }
1119
        // if it's a function call
1120 44
        if (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $token) && ($this->lookAhead === '(')) {
1121 33
            return $token;
1122
        }
1123 44
        if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $token) && $this->spreadsheet->getDefinedName($token) !== null) {
1124 5
            return $token;
1125
        }
1126 44
        if (preg_match('/^true$/i', $token) && ($this->lookAhead === ')' || $this->lookAhead === ',')) {
1127 1
            return $token;
1128
        }
1129 44
        if (preg_match('/^false$/i', $token) && ($this->lookAhead === ')' || $this->lookAhead === ',')) {
1130 1
            return $token;
1131
        }
1132 44
        if (substr($token, -1) === ')') {
1133
            //    It's an argument of some description (e.g. a named range),
1134
            //        precise nature yet to be determined
1135 1
            return $token;
1136
        }
1137
1138 44
        return '';
1139
    }
1140
1141
    /**
1142
     * The parsing method. It parses a formula.
1143
     *
1144
     * @param string $formula the formula to parse, without the initial equal
1145
     *                        sign (=)
1146
     *
1147
     * @return mixed true on success
1148
     */
1149 45
    public function parse($formula)
1150
    {
1151 45
        $this->currentCharacter = 0;
1152 45
        $this->formula = (string) $formula;
1153 45
        $this->lookAhead = $formula[1] ?? '';
1154 45
        $this->advance();
1155 45
        $this->parseTree = $this->condition();
1156
1157 45
        return true;
1158
    }
1159
1160
    /**
1161
     * It parses a condition. It assumes the following rule:
1162
     * Cond -> Expr [(">" | "<") Expr].
1163
     *
1164
     * @return mixed The parsed ptg'd tree on success
1165
     */
1166 45
    private function condition()
1167
    {
1168 45
        $result = $this->expression();
1169 45
        if ($this->currentToken == '<') {
1170 1
            $this->advance();
1171 1
            $result2 = $this->expression();
1172 1
            $result = $this->createTree('ptgLT', $result, $result2);
1173 45
        } elseif ($this->currentToken == '>') {
1174 2
            $this->advance();
1175 2
            $result2 = $this->expression();
1176 2
            $result = $this->createTree('ptgGT', $result, $result2);
1177 45
        } elseif ($this->currentToken == '<=') {
1178 2
            $this->advance();
1179 2
            $result2 = $this->expression();
1180 2
            $result = $this->createTree('ptgLE', $result, $result2);
1181 45
        } elseif ($this->currentToken == '>=') {
1182 1
            $this->advance();
1183 1
            $result2 = $this->expression();
1184 1
            $result = $this->createTree('ptgGE', $result, $result2);
1185 45
        } elseif ($this->currentToken == '=') {
1186 4
            $this->advance();
1187 4
            $result2 = $this->expression();
1188 4
            $result = $this->createTree('ptgEQ', $result, $result2);
1189 45
        } elseif ($this->currentToken == '<>') {
1190 7
            $this->advance();
1191 7
            $result2 = $this->expression();
1192 7
            $result = $this->createTree('ptgNE', $result, $result2);
1193
        }
1194
1195 45
        return $result;
1196
    }
1197
1198
    /**
1199
     * It parses a expression. It assumes the following rule:
1200
     * Expr -> Term [("+" | "-") Term]
1201
     *      -> "string"
1202
     *      -> "-" Term : Negative value
1203
     *      -> "+" Term : Positive value
1204
     *      -> Error code.
1205
     *
1206
     * @return mixed The parsed ptg'd tree on success
1207
     */
1208 45
    private function expression()
1209
    {
1210
        // If it's a string return a string node
1211 45
        if (preg_match('/"([^"]|""){0,255}"/', $this->currentToken)) {
1212 21
            $tmp = str_replace('""', '"', $this->currentToken);
1213 21
            if (($tmp == '"') || ($tmp == '')) {
1214
                //    Trap for "" that has been used for an empty string
1215 7
                $tmp = '""';
1216
            }
1217 21
            $result = $this->createTree($tmp, '', '');
1218 21
            $this->advance();
1219
1220 21
            return $result;
1221 45
        } elseif (preg_match('/^#[A-Z0\\/]{3,5}[!?]{1}$/', $this->currentToken) || $this->currentToken == '#N/A') { // error code
1222 1
            $result = $this->createTree($this->currentToken, 'ptgErr', '');
1223 1
            $this->advance();
1224
1225 1
            return $result;
1226 45
        } elseif ($this->currentToken == '-') { // negative value
1227
            // catch "-" Term
1228 5
            $this->advance();
1229 5
            $result2 = $this->expression();
1230
1231 5
            return $this->createTree('ptgUminus', $result2, '');
1232 45
        } elseif ($this->currentToken == '+') { // positive value
1233
            // catch "+" Term
1234 1
            $this->advance();
1235 1
            $result2 = $this->expression();
1236
1237 1
            return $this->createTree('ptgUplus', $result2, '');
1238
        }
1239 45
        $result = $this->term();
1240 45
        while ($this->currentToken === '&') {
1241 8
            $this->advance();
1242 8
            $result2 = $this->expression();
1243 8
            $result = $this->createTree('ptgConcat', $result, $result2);
1244
        }
1245
        while (
1246 45
            ($this->currentToken == '+') ||
1247 45
            ($this->currentToken == '-') ||
1248 45
            ($this->currentToken == '^')
1249
        ) {
1250 20
            if ($this->currentToken == '+') {
1251 20
                $this->advance();
1252 20
                $result2 = $this->term();
1253 20
                $result = $this->createTree('ptgAdd', $result, $result2);
1254 6
            } elseif ($this->currentToken == '-') {
1255 6
                $this->advance();
1256 6
                $result2 = $this->term();
1257 6
                $result = $this->createTree('ptgSub', $result, $result2);
1258
            } else {
1259 1
                $this->advance();
1260 1
                $result2 = $this->term();
1261 1
                $result = $this->createTree('ptgPower', $result, $result2);
1262
            }
1263
        }
1264
1265 45
        return $result;
1266
    }
1267
1268
    /**
1269
     * This function just introduces a ptgParen element in the tree, so that Excel
1270
     * doesn't get confused when working with a parenthesized formula afterwards.
1271
     *
1272
     * @return array The parsed ptg'd tree
1273
     *
1274
     * @see fact()
1275
     */
1276 3
    private function parenthesizedExpression()
1277
    {
1278 3
        return $this->createTree('ptgParen', $this->expression(), '');
1279
    }
1280
1281
    /**
1282
     * It parses a term. It assumes the following rule:
1283
     * Term -> Fact [("*" | "/") Fact].
1284
     *
1285
     * @return mixed The parsed ptg'd tree on success
1286
     */
1287 45
    private function term()
1288
    {
1289 45
        $result = $this->fact();
1290
        while (
1291 45
            ($this->currentToken == '*') ||
1292 45
            ($this->currentToken == '/')
1293
        ) {
1294 17
            if ($this->currentToken == '*') {
1295 16
                $this->advance();
1296 16
                $result2 = $this->fact();
1297 16
                $result = $this->createTree('ptgMul', $result, $result2);
1298
            } else {
1299 4
                $this->advance();
1300 4
                $result2 = $this->fact();
1301 4
                $result = $this->createTree('ptgDiv', $result, $result2);
1302
            }
1303
        }
1304
1305 45
        return $result;
1306
    }
1307
1308
    /**
1309
     * It parses a factor. It assumes the following rule:
1310
     * Fact -> ( Expr )
1311
     *       | CellRef
1312
     *       | CellRange
1313
     *       | Number
1314
     *       | Function.
1315
     *
1316
     * @return mixed The parsed ptg'd tree on success
1317
     */
1318 45
    private function fact()
1319
    {
1320 45
        $currentToken = $this->currentToken;
1321 45
        if ($currentToken === '(') {
1322 3
            $this->advance(); // eat the "("
1323 3
            $result = $this->parenthesizedExpression();
1324 3
            if ($this->currentToken !== ')') {
1325
                throw new WriterException("')' token expected.");
1326
            }
1327 3
            $this->advance(); // eat the ")"
1328
1329 3
            return $result;
1330
        }
1331
        // if it's a reference
1332 45
        if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?\d+$/', $this->currentToken)) {
1333 28
            $result = $this->createTree($this->currentToken, '', '');
1334 28
            $this->advance();
1335
1336 28
            return $result;
1337
        }
1338 42
        if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?[A-Ia-i]?[A-Za-z]\$?\\d+$/u', $this->currentToken)) {
1339
            // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1 or Sheet1!$A$1 or Sheet1:Sheet2!$A$1)
1340
            $result = $this->createTree($this->currentToken, '', '');
1341
            $this->advance();
1342
1343
            return $result;
1344
        }
1345 42
        if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?[A-Ia-i]?[A-Za-z]\\$?\\d+$/u", $this->currentToken)) {
1346
            // If it's an external reference ('Sheet1'!A1 or 'Sheet1:Sheet2'!A1 or 'Sheet1'!$A$1 or 'Sheet1:Sheet2'!$A$1)
1347 6
            $result = $this->createTree($this->currentToken, '', '');
1348 6
            $this->advance();
1349
1350 6
            return $result;
1351
        }
1352
        if (
1353 41
            preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+:(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken) ||
1354 41
            preg_match('/^(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?\d+$/', $this->currentToken)
1355
        ) {
1356
            // if it's a range A1:B2 or $A$1:$B$2
1357
            // must be an error?
1358 25
            $result = $this->createTree($this->currentToken, '', '');
1359 25
            $this->advance();
1360
1361 25
            return $result;
1362
        }
1363 41
        if (preg_match('/^' . self::REGEX_SHEET_TITLE_UNQUOTED . '(\\:' . self::REGEX_SHEET_TITLE_UNQUOTED . ')?\\!\$?([A-Ia-i]?[A-Za-z])?\$?\\d+:\$?([A-Ia-i]?[A-Za-z])?\$?\\d+$/u', $this->currentToken)) {
1364
            // If it's an external range (Sheet1!A1:B2 or Sheet1:Sheet2!A1:B2 or Sheet1!$A$1:$B$2 or Sheet1:Sheet2!$A$1:$B$2)
1365
            // must be an error?
1366
            $result = $this->createTree($this->currentToken, '', '');
1367
            $this->advance();
1368
1369
            return $result;
1370
        }
1371 41
        if (preg_match("/^'" . self::REGEX_SHEET_TITLE_QUOTED . '(\\:' . self::REGEX_SHEET_TITLE_QUOTED . ")?'\\!\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+:\\$?([A-Ia-i]?[A-Za-z])?\\$?\\d+$/u", $this->currentToken)) {
1372
            // If it's an external range ('Sheet1'!A1:B2 or 'Sheet1'!A1:B2 or 'Sheet1'!$A$1:$B$2 or 'Sheet1'!$A$1:$B$2)
1373
            // must be an error?
1374 4
            $result = $this->createTree($this->currentToken, '', '');
1375 4
            $this->advance();
1376
1377 4
            return $result;
1378
        }
1379 41
        if (is_numeric($this->currentToken)) {
1380
            // If it's a number or a percent
1381 27
            if ($this->lookAhead === '%') {
1382 1
                $result = $this->createTree('ptgPercent', $this->currentToken, '');
1383 1
                $this->advance(); // Skip the percentage operator once we've pre-built that tree
1384
            } else {
1385 27
                $result = $this->createTree($this->currentToken, '', '');
1386
            }
1387 27
            $this->advance();
1388
1389 27
            return $result;
1390
        }
1391 35
        if (preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/i", $this->currentToken) && ($this->lookAhead === '(')) {
1392
            // if it's a function call
1393 33
            return $this->func();
1394
        }
1395 7
        if (preg_match('/^' . Calculation::CALCULATION_REGEXP_DEFINEDNAME . '$/miu', $this->currentToken) && $this->spreadsheet->getDefinedName($this->currentToken) !== null) {
1396 5
            $result = $this->createTree('ptgName', $this->currentToken, '');
1397 5
            $this->advance();
1398
1399 5
            return $result;
1400
        }
1401 2
        if (preg_match('/^true|false$/i', $this->currentToken)) {
1402 1
            $result = $this->createTree($this->currentToken, '', '');
1403 1
            $this->advance();
1404
1405 1
            return $result;
1406
        }
1407
1408 1
        throw new WriterException('Syntax error: ' . $this->currentToken . ', lookahead: ' . $this->lookAhead . ', current char: ' . $this->currentCharacter);
1409
    }
1410
1411
    /**
1412
     * It parses a function call. It assumes the following rule:
1413
     * Func -> ( Expr [,Expr]* ).
1414
     *
1415
     * @return mixed The parsed ptg'd tree on success
1416
     */
1417 33
    private function func()
1418
    {
1419 33
        $num_args = 0; // number of arguments received
1420 33
        $function = strtoupper($this->currentToken);
1421 33
        $result = ''; // initialize result
1422 33
        $this->advance();
1423 33
        $this->advance(); // eat the "("
1424 33
        while ($this->currentToken !== ')') {
1425 33
            if ($num_args > 0) {
1426 19
                if ($this->currentToken === ',' || $this->currentToken === ';') {
1427 19
                    $this->advance(); // eat the "," or ";"
1428
                } else {
1429
                    throw new WriterException("Syntax error: comma expected in function $function, arg #{$num_args}");
1430
                }
1431 19
                $result2 = $this->condition();
1432 19
                $result = $this->createTree('arg', $result, $result2);
1433
            } else { // first argument
1434 33
                $result2 = $this->condition();
1435 33
                $result = $this->createTree('arg', '', $result2);
1436
            }
1437 33
            ++$num_args;
1438
        }
1439 33
        if (!isset($this->functions[$function])) {
1440 3
            throw new WriterException("Function $function() doesn't exist");
1441
        }
1442 33
        $args = $this->functions[$function][1];
1443
        // If fixed number of args eg. TIME($i, $j, $k). Check that the number of args is valid.
1444 33
        if (($args >= 0) && ($args != $num_args)) {
1445
            throw new WriterException("Incorrect number of arguments in function $function() ");
1446
        }
1447
1448 33
        $result = $this->createTree($function, $result, $num_args);
1449 33
        $this->advance(); // eat the ")"
1450
1451 33
        return $result;
1452
    }
1453
1454
    /**
1455
     * Creates a tree. In fact an array which may have one or two arrays (sub-trees)
1456
     * as elements.
1457
     *
1458
     * @param mixed $value the value of this node
1459
     * @param mixed $left the left array (sub-tree) or a final node
1460
     * @param mixed $right the right array (sub-tree) or a final node
1461
     *
1462
     * @return array A tree
1463
     */
1464 45
    private function createTree($value, $left, $right)
1465
    {
1466 45
        return ['value' => $value, 'left' => $left, 'right' => $right];
1467
    }
1468
1469
    /**
1470
     * Builds a string containing the tree in reverse polish notation (What you
1471
     * would use in a HP calculator stack).
1472
     * The following tree:.
1473
     *
1474
     *    +
1475
     *   / \
1476
     *  2   3
1477
     *
1478
     * produces: "23+"
1479
     *
1480
     * The following tree:
1481
     *
1482
     *    +
1483
     *   / \
1484
     *  3   *
1485
     *     / \
1486
     *    6   A1
1487
     *
1488
     * produces: "36A1*+"
1489
     *
1490
     * In fact all operands, functions, references, etc... are written as ptg's
1491
     *
1492
     * @param array $tree the optional tree to convert
1493
     *
1494
     * @return string The tree in reverse polish notation
1495
     */
1496 49
    public function toReversePolish($tree = [])
1497
    {
1498 49
        $polish = ''; // the string we are going to return
1499 49
        if (empty($tree)) { // If it's the first call use parseTree
1500 46
            $tree = $this->parseTree;
1501
        }
1502 49
        if (!is_array($tree) || !isset($tree['left'], $tree['right'], $tree['value'])) {
1503 2
            throw new WriterException('Unexpected non-array');
1504
        }
1505
1506 47
        if (is_array($tree['left'])) {
1507 42
            $converted_tree = $this->toReversePolish($tree['left']);
1508 42
            $polish .= $converted_tree;
1509 47
        } elseif ($tree['left'] != '') { // It's a final node
1510 8
            $converted_tree = $this->convert($tree['left']);
1511 3
            $polish .= $converted_tree;
1512
        }
1513 47
        if (is_array($tree['right'])) {
1514 42
            $converted_tree = $this->toReversePolish($tree['right']);
1515 41
            $polish .= $converted_tree;
1516 47
        } elseif ($tree['right'] != '') { // It's a final node
1517 34
            $converted_tree = $this->convert($tree['right']);
1518 34
            $polish .= $converted_tree;
1519
        }
1520
        // if it's a function convert it here (so we can set it's arguments)
1521
        if (
1522 47
            preg_match("/^[A-Z0-9\xc0-\xdc\\.]+$/", $tree['value']) &&
1523 47
            !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/', $tree['value']) &&
1524 47
            !preg_match('/^[A-Ia-i]?[A-Za-z](\\d+)\\.\\.[A-Ia-i]?[A-Za-z](\\d+)$/', $tree['value']) &&
1525 47
            !is_numeric($tree['value']) &&
1526 47
            !isset($this->ptg[$tree['value']])
1527
        ) {
1528
            // left subtree for a function is always an array.
1529 32
            if ($tree['left'] != '') {
1530 32
                $left_tree = $this->toReversePolish($tree['left']);
1531
            } else {
1532 8
                $left_tree = '';
1533
            }
1534
1535
            // add its left subtree and return.
1536 32
            return $left_tree . $this->convertFunction($tree['value'], $tree['right']);
1537
        }
1538 47
        $converted_tree = $this->convert($tree['value']);
1539
1540 45
        return $polish . $converted_tree;
1541
    }
1542
}
1543