Parser.php 51 KB

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