Parser.php 52 KB

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