Advanced Order Export For WooCommerce - Version 1.5.3

Version Description

  • 2018-02-12 =
  • The plugin is compatible with WooCommerce 3.3.1
  • Supports complex structures (arrays,objects) in the fields, export it as JSON string
  • Shows "download link" for iPad/iPhone
  • Added product field "Product URL"
  • Fixed bug for Excel dates
Download this release

Release Info

Developer algol.plus
Plugin Icon 128x128 Advanced Order Export For WooCommerce
Version 1.5.3
Comparing to
See all releases

Version 1.5.3

Files changed (36) hide show
  1. assets/css/export.css +610 -0
  2. assets/img/1 +0 -0
  3. assets/js/export.js +1015 -0
  4. assets/js/jquery.serializejson.js +346 -0
  5. classes/PHPExcel.php +1153 -0
  6. classes/PHPExcel/Autoloader.php +81 -0
  7. classes/PHPExcel/CachedObjectStorage/APC.php +290 -0
  8. classes/PHPExcel/CachedObjectStorage/CacheBase.php +368 -0
  9. classes/PHPExcel/CachedObjectStorage/DiscISAM.php +208 -0
  10. classes/PHPExcel/CachedObjectStorage/ICache.php +103 -0
  11. classes/PHPExcel/CachedObjectStorage/Igbinary.php +149 -0
  12. classes/PHPExcel/CachedObjectStorage/Memcache.php +308 -0
  13. classes/PHPExcel/CachedObjectStorage/Memory.php +118 -0
  14. classes/PHPExcel/CachedObjectStorage/MemoryGZip.php +133 -0
  15. classes/PHPExcel/CachedObjectStorage/MemorySerialized.php +129 -0
  16. classes/PHPExcel/CachedObjectStorage/PHPTemp.php +200 -0
  17. classes/PHPExcel/CachedObjectStorage/SQLite3.php +346 -0
  18. classes/PHPExcel/CachedObjectStorage/Wincache.php +289 -0
  19. classes/PHPExcel/CachedObjectStorageFactory.php +231 -0
  20. classes/PHPExcel/CalcEngine/CyclicReferenceStack.php +94 -0
  21. classes/PHPExcel/CalcEngine/Logger.php +151 -0
  22. classes/PHPExcel/Calculation.php +4391 -0
  23. classes/PHPExcel/Calculation/Database.php +676 -0
  24. classes/PHPExcel/Calculation/DateTime.php +1553 -0
  25. classes/PHPExcel/Calculation/Engineering.php +2650 -0
  26. classes/PHPExcel/Calculation/Exception.php +46 -0
  27. classes/PHPExcel/Calculation/ExceptionHandler.php +45 -0
  28. classes/PHPExcel/Calculation/Financial.php +2359 -0
  29. classes/PHPExcel/Calculation/FormulaParser.php +622 -0
  30. classes/PHPExcel/Calculation/FormulaToken.php +176 -0
  31. classes/PHPExcel/Calculation/Function.php +148 -0
  32. classes/PHPExcel/Calculation/Functions.php +760 -0
  33. classes/PHPExcel/Calculation/Logical.php +285 -0
  34. classes/PHPExcel/Calculation/LookupRef.php +879 -0
  35. classes/PHPExcel/Calculation/MathTrig.php +1459 -0
  36. classes/PHPExcel/Calculation/Statistical.php +3522 -0
assets/css/export.css ADDED
@@ -0,0 +1,610 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #fields {
2
+
3
+
4
+ height: 800px;
5
+ overflow: scroll;
6
+ width: 530px;
7
+ padding: 20px;
8
+ border-color: rgb(187, 180, 180);
9
+ border-style: solid;
10
+ border-width: 1px;
11
+ padding-top: 0px;
12
+
13
+ }
14
+ .fields_control_style input,select{
15
+ margin: 3px;
16
+ width: 80%;
17
+ }
18
+
19
+
20
+ .fields_control_style {
21
+ padding: 10px;
22
+ // width: 530px;
23
+ border-color: rgb(187, 180, 180);
24
+ border-style: solid;
25
+ border-width: 1px;
26
+ display: inline-block;
27
+ }
28
+ .fields_control_style .div_meta{
29
+ float: left;
30
+ width: 50%;
31
+ padding: 2px;
32
+ }
33
+ .fields_control_style .div_custom{
34
+ padding: 2px;
35
+ float: left;
36
+ width: 45%;
37
+ border-left: dotted 1px;
38
+ }
39
+ .fields_control_style label {
40
+ display: inline-block;
41
+ padding: 5px;
42
+ min-width: 100px;
43
+
44
+ }
45
+ .fields_control_style span {
46
+ display:block;
47
+ width:100px;
48
+ height: 100%;
49
+ margin: 0 auto;
50
+ padding: 5px;
51
+ }
52
+
53
+ #fields_control {
54
+ padding: 10px;
55
+ width: 530px;
56
+ border-color: rgb(187, 180, 180);
57
+ border-style: solid;
58
+ border-width: 1px;
59
+ display: inline-block;
60
+ }
61
+ #fields_control label {
62
+ display: inline-block;
63
+ padding: 5px;
64
+ min-width: 100px;
65
+
66
+ }
67
+ #fields_control span {
68
+ display:block;
69
+ width:100px;
70
+ height: 100%;
71
+ margin: 0 auto;
72
+ padding: 5px;
73
+ }
74
+ #fields_control .div1 {
75
+ width: 60%;
76
+ float:left;
77
+ }
78
+ #fields_control .div2 {
79
+ width: 40%;
80
+ float:left;
81
+ }
82
+ #fields_control .div_meta label {
83
+ display: inline-block;
84
+ padding: 0px;
85
+ min-width: 100px;
86
+ }
87
+ #order_fields { list-style-type: none; margin: 0; padding: 0; width: 490px; }
88
+ #output_preview {border-color:green; border-style: dashed; border-width: 1px; display:none; width:90% }
89
+ .spit-settings-cols {width:20px}
90
+
91
+ /*.mapping_row{
92
+ display:table-row;
93
+ border-spacing: 5px 20px;
94
+ border-top:thin solid black;
95
+ -moz-border-radius:5px 5px 5px 5px;
96
+ -webkit-border-radius:5px 5px 5px 5px;
97
+ -khtml-border-radius:5px;
98
+ }*/
99
+ .mapping_header{
100
+ display:table-row;
101
+ font-weight:bold;
102
+ }
103
+ .mapping_col_1{
104
+ display:table-cell;
105
+ width:50px;
106
+ padding: 3px;
107
+ }
108
+ .mapping_col_2{
109
+ display:table-cell;
110
+ width:150px;
111
+ }
112
+ .mapping_col_3{
113
+ display:table-cell;
114
+ padding: 3px;
115
+ }
116
+ .mapping_fieldname {
117
+ width:100%;
118
+ font-weight: normal;
119
+ }
120
+
121
+ .select2-search__field:focus
122
+ {
123
+ border-color: rgba(30,140,190,0) !important;
124
+ border:none;
125
+ -webkit-box-shadow: 0 0 2px rgba(30,140,190,0) !important;
126
+ box-shadow: 0 0 2px rgba(30,140,190,0) !important;
127
+ }
128
+
129
+ .select2-search__field{
130
+ border-color: rgba(30,140,190,0) !important;
131
+ border:none;
132
+ -webkit-box-shadow: 0 0 2px rgba(30,140,190,0) !important;
133
+ box-shadow: 0 0 2px rgba(30,140,190,0) !important;
134
+ }
135
+
136
+ input.date{
137
+ width: 25%;
138
+ }
139
+
140
+ .mapping_row {
141
+ background-color: #E0E0E0;
142
+ /*padding: 7px;*/
143
+ border: 1px #969696 solid;
144
+ }
145
+
146
+ #sort_products,#sort_coupons{
147
+ list-style-type: none;
148
+ }
149
+
150
+ .btn-edit{
151
+ padding: 2px 3px!important;
152
+ }
153
+ .btn-trash{
154
+ padding: 2px 3px !important;
155
+ }
156
+
157
+
158
+ .padding-10{
159
+ padding: 10px;
160
+ }
161
+
162
+ .run-at{
163
+ width: 180px;
164
+ float: left;
165
+ }
166
+ .weekday label {
167
+ width: 10px;
168
+ float: left;
169
+ margin: 0px 15px;
170
+ font-weight: bold;
171
+ }
172
+ .weekday {
173
+ float: left;
174
+ }
175
+
176
+ .wc-oe-header{
177
+ font-size: 15px;
178
+ font-weight: bold;
179
+ padding-bottom: 5px;
180
+ }
181
+ .wc_oe-select-interval{
182
+ width: 150px;
183
+ }
184
+ .wc_oe-select-weekday {
185
+ width: 80px;
186
+ }
187
+ #d-shedule-3 input[type="submit"] {
188
+ margin: 3px;
189
+ }
190
+
191
+
192
+ .clearfix:before,
193
+ .clearfix:after,
194
+ .wc_oe-row:after{
195
+ content:"";
196
+ display:table;
197
+ }
198
+ .clearfix:after,
199
+ .wc_oe-row:after{
200
+ clear:both;
201
+ }
202
+ .clearfix,
203
+ .wc_oe-row:after{
204
+ zoom:1; /* For IE 6/7 (trigger hasLayout) */
205
+ }
206
+
207
+ .wc-oe-schedule-type{
208
+ float: left;
209
+ }
210
+ #custom_interval{
211
+ display: none;
212
+ }
213
+
214
+ #schedule-1{
215
+ margin-top: 8px;
216
+ }
217
+ #schedule-2, #schedule-3{
218
+ margin-top: 8px;
219
+ }
220
+ .ftp-settings label{
221
+ display: block;
222
+ }
223
+ .ftp-settings .wc_oe-inline{
224
+ width:80px;
225
+ display: inline;
226
+ }
227
+ .tr-pad{
228
+ vertical-align: top;
229
+ }
230
+ #d-schedule-2{
231
+ padding-bottom: 10px;
232
+ }
233
+ .padding-bottom-10 {
234
+ padding-bottom: 10px;
235
+ }
236
+ .width-100{
237
+ width: 100%;
238
+ }
239
+ .width-5{
240
+ width: 5%;
241
+ }
242
+ .width-15{
243
+ width: 15%;
244
+ }
245
+ .set-estination{
246
+ display: none;
247
+ }
248
+
249
+ .wc_oe-row {
250
+ margin: 7px;
251
+ }
252
+ .col-50pr{
253
+ float: left;
254
+ width: 50%;
255
+ }
256
+ .col-100pr{
257
+ float: left;
258
+ width: 100%;
259
+ }
260
+
261
+ .all-input-100pr input[type="text"]{
262
+ width: 100%;
263
+ }
264
+ .hide-destination{
265
+ text-align: center;
266
+ width: 100%;
267
+ }
268
+
269
+ .xml-title{
270
+ display: inline-block;
271
+ width: 125px;
272
+ }
273
+
274
+ .my-block{
275
+ border-width: 1px;
276
+ border-style: solid;
277
+ border-radius: 3px;
278
+ border-color: #ccc;
279
+ padding: 10px 5px 10px 10px;
280
+ }
281
+
282
+ .my-test-button{
283
+ border-width: 1px !important;
284
+ border-style: solid !important;
285
+ border-radius: 3px !important;
286
+ border-color: #ccc !important;
287
+ margin-left: 0px !important;
288
+ }
289
+
290
+ .my-icon-triangle{
291
+ vertical-align: middle;
292
+ display: inline-block;
293
+ }
294
+ .my-hide-next{
295
+ cursor: pointer;
296
+ font-size: 13px;
297
+ font-weight: bold;
298
+ text-decoration: underline;
299
+ }
300
+
301
+ .my-manage-li{
302
+ display: inline-block;
303
+ width: 47%;
304
+ }
305
+
306
+ .my-manage-li:nth-child(2n){
307
+ margin-left: 10px;
308
+ float: right;
309
+ }
310
+ #my-quick-export-btn{
311
+ display: inline-block !important;
312
+ margin-left: 10px !important;
313
+ }
314
+
315
+ #add_attributes,#add_taxonomies,#add_shipping_locations,#add_billing_locations,#add_custom_fields,#add_product_custom_fields{
316
+ font-size: large;
317
+ }
318
+
319
+ .select2-selection-single{
320
+ margin-bottom: 5px;
321
+ }
322
+
323
+ #select_attributes,#select_taxonomies,#text_shipping_locations,#text_billing_locations,#select_custom_fields,#select_product_custom_fields, #select_itemmeta{
324
+ width: 120px;
325
+ }
326
+ .dashicons{
327
+ margin-top: 3px;
328
+ }
329
+
330
+ #progress_div{
331
+ z-index: 10001;
332
+ position: absolute;
333
+ top: 50%;
334
+ left: 35%;
335
+ text-align: center;
336
+ }
337
+
338
+ #progress_div .title-download {
339
+ display: none;
340
+ background-color: white;
341
+ padding: 28px;
342
+ font-weight: 400;
343
+ font-size: 16px;
344
+ width: 300px;
345
+ border: 1px solid lightgrey;
346
+ }
347
+
348
+ #progressBar {
349
+
350
+ width: 400px;
351
+ background: #292929;
352
+ border: 1px solid #111;
353
+ border-radius: 5px;
354
+ overflow: hidden;
355
+ box-shadow: 0 0 5px #333;
356
+
357
+ }
358
+
359
+ #progressBar div {
360
+ height: 100%;
361
+ color: #fff;
362
+ text-align: right;
363
+ font-size: 12px;
364
+ line-height: 22px;
365
+ text-align: right;
366
+ background-color: #1a82f7;
367
+ background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#0099FF), to(#1a82f7));
368
+ background: -webkit-linear-gradient(top, #0099FF, #1a82f7);
369
+ background: -moz-linear-gradient(top, #0099FF, #1a82f7);
370
+ background: -ms-linear-gradient(top, #0099FF, #1a82f7);
371
+ background: -o-linear-gradient(top, #0099FF, #1a82f7);
372
+ }
373
+
374
+ #background.loading{
375
+ position: fixed;
376
+ z-index: 10000;
377
+ top: 0;
378
+ left: 0;
379
+ height: 100%;
380
+ width: 100%;
381
+ background-color: #F1F1F1;
382
+ filter: progid:DXImageTransform.Microsoft.Alpha(opacity=55);
383
+ -moz-opacity: 0.55;
384
+ -khtml-opacity: 0.55;
385
+ opacity: 0.55;
386
+ }
387
+
388
+ .email_body_textarea
389
+ {
390
+ height: 451px;
391
+ width: 736px;
392
+ }
393
+ #modal-email-body
394
+ {
395
+ display: none;
396
+ }
397
+ .select_compare
398
+ {
399
+ width: 60px;
400
+ margin-top: 0px;
401
+ margin-right: 6px;
402
+ }
403
+
404
+ #custom_meta_products_mode input, #custom_meta_coupons_mode input {
405
+ width: auto;
406
+ }
407
+
408
+ #date_format_block, #time_format_block {
409
+ display: inline-block;
410
+ width: 48%;
411
+ vertical-align: top;
412
+ }
413
+
414
+ #custom_date_format_block input, #custom_time_format_block input {
415
+ width: 70%;
416
+ margin-left: 41px;
417
+ }
418
+
419
+ #date_format_block select, #time_format_block select {
420
+ width: 70%;
421
+ }
422
+
423
+ .woe-tab {
424
+ border: 1px solid #ccc;
425
+ border-top-width: 0;
426
+ background: #f1f1f1;
427
+ padding: 30px;
428
+ }
429
+ .woe-tab .form-group label input {
430
+ display: inline-block;
431
+ margin-top: -3px;
432
+ }
433
+ .woe-separator {
434
+ height: 1px;
435
+ border-top: 1px solid #ddd;
436
+ margin: 2em auto;
437
+ width: 100%;
438
+ clear: both;
439
+ }
440
+
441
+ #woe-admin .woe-tab {
442
+ margin-right: 14.16667rem;
443
+ border: none;
444
+ border-top-width: 0;
445
+ background: transparent;
446
+ padding: 0 0 3.33333rem 0;
447
+ }
448
+
449
+ #woe-admin .woe-box-main {
450
+ background-color: #fff;
451
+ padding: 1.66667rem 1.66667rem 0 1.66667rem;
452
+ }
453
+
454
+ #woe-admin .woe-input-simple textarea {
455
+ width: 100%;
456
+ border-radius: 0;
457
+ -webkit-box-shadow: none;
458
+ box-shadow: none;
459
+ border-color: #c7dff3;
460
+ background-color: #c7dff3;
461
+ padding: 0.41667rem 0.66667rem;
462
+ transition: border-color 100ms, background-color 250ms;
463
+ }
464
+ #woe-admin .woe-input-simple textarea:focus {
465
+ background-color: #003553;
466
+ color: #fff;
467
+ }
468
+ #woe-admin .tools-textarea {
469
+ width: 66.66667%;
470
+ }
471
+ #woe-admin .woe-input-simple input, #woe-admin .woe-select input, #woe-admin .woe-input-simple textarea, #woe-admin .woe-select textarea, .woe-calendar-wrapper .woe-input-simple input, .woe-calendar-wrapper .woe-select input, .woe-calendar-wrapper .woe-input-simple textarea, .woe-calendar-wrapper .woe-select textarea, #woe-admin .woe-checkbox label, #woe-admin .woe-radiobox label, #woe-admin .woe-switch label, #woe-admin .woe-select.woe-select-info-label .woe-label-big label, .woe-calendar-wrapper .woe-select.woe-select-info-label #woe-admin .woe-label-big label, .woe-calendar-wrapper .woe-checkbox label, .woe-calendar-wrapper .woe-radiobox label, .woe-calendar-wrapper .woe-switch label, .woe-calendar-wrapper .woe-select.woe-select-info-label .woe-label-big label, #woe-admin .woe-checkbutton input + label, .woe-calendar-wrapper .woe-checkbutton input + label, #woe-admin .col-time, .woe-calendar-wrapper .col-time, #woe-admin .woe-box-title, .woe-calendar-wrapper .woe-box-title, .select2-container.select2-container-woe .select2-selection-single, .select2-container.select2-container-woe .select2-selection-multiple {
472
+ font-family: "Open sans", serif;
473
+ font-size: 0.83333rem;
474
+ line-height: 1.41667rem;
475
+ line-height: 1.41667rem; }
476
+ @media only screen and (min-width: 768px) {
477
+ #woe-admin .woe-input-simple input, #woe-admin .woe-select input, #woe-admin .woe-input-simple textarea, #woe-admin .woe-select textarea, .woe-calendar-wrapper .woe-input-simple input, .woe-calendar-wrapper .woe-select input, .woe-calendar-wrapper .woe-input-simple textarea, .woe-calendar-wrapper .woe-select textarea, #woe-admin .woe-checkbox label, #woe-admin .woe-radiobox label, #woe-admin .woe-switch label, #woe-admin .woe-select.woe-select-info-label .woe-label-big label, .woe-calendar-wrapper .woe-select.woe-select-info-label #woe-admin .woe-label-big label, .woe-calendar-wrapper .woe-checkbox label, .woe-calendar-wrapper .woe-radiobox label, .woe-calendar-wrapper .woe-switch label, .woe-calendar-wrapper .woe-select.woe-select-info-label .woe-label-big label, #woe-admin .woe-checkbutton input + label, .woe-calendar-wrapper .woe-checkbutton input + label, #woe-admin .col-time, .woe-calendar-wrapper .col-time, #woe-admin .woe-box-title, .woe-calendar-wrapper .woe-box-title, .select2-container.select2-container-woe .select2-selection-single, .select2-container.select2-container-woe .select2-selection-multiple {
478
+ font-size: 1rem; } }
479
+
480
+ #woe-admin .woe-input-simple label, #woe-admin .woe-select label, .woe-calendar-wrapper .woe-input-simple label, .woe-calendar-wrapper .woe-select label, #woe-admin .woe-fake-label, .woe-calendar-wrapper .woe-fake-label, #woe-admin .woe-btn-big, #woe-admin p.submit, #woe-admin .woe-btn-big input, #woe-admin p.submit input, #woe-admin .woe-btn-big button, #woe-admin p.submit button, .woe-calendar-wrapper .woe-btn-big, .woe-calendar-wrapper p.submit, .woe-calendar-wrapper .woe-btn-big input, .woe-calendar-wrapper p.submit input, .woe-calendar-wrapper .woe-btn-big button, .woe-calendar-wrapper p.submit button, #woe-admin .woe-box-maininfo p, .woe-calendar-wrapper .woe-box-maininfo p, #woe-admin .woe-box-title span, .woe-calendar-wrapper .woe-box-title span, #woe-admin .woe-box-info .woe-box-info-content, .woe-calendar-wrapper .woe-box-info .woe-box-info-content, #woe-admin .woe-box-info .woe-box-info-content h5, .woe-calendar-wrapper .woe-box-info .woe-box-info-content h5, #woe-admin .woe-message, .woe-calendar-wrapper .woe-message, .select2-container.select2-container-woe .select2-dropdown, .select2-container.select2-container-woe .select2-search-dropdown .select2-search__field {
481
+ font-family: "Open sans", serif;
482
+ font-size: 0.75rem;
483
+ font-weight: normal;
484
+ line-height: 1.16667rem; }
485
+
486
+ #woe-admin .woe-input-simple p, #woe-admin .woe-checkbox p, #woe-admin .woe-radiobox p, #woe-admin .woe-switch p, #woe-admin .woe-select p, .woe-calendar-wrapper .woe-input-simple p, .woe-calendar-wrapper .woe-checkbox p, .woe-calendar-wrapper .woe-radiobox p, .woe-calendar-wrapper .woe-switch p, .woe-calendar-wrapper .woe-select p, #woe-admin .woe-btn-medium, #woe-admin .nav-tab-wrapper .nav-tab,
487
+ #woe-admin h2.nav-tab-wrapper .nav-tab, .woe-calendar-wrapper .nav-tab-wrapper #woe-admin .nav-tab, #woe-admin .woe-admin-nav a, .woe-calendar-wrapper .woe-admin-nav #woe-admin a, #woe-admin .woe-btn-medium input, #woe-admin .nav-tab-wrapper .nav-tab input, .woe-calendar-wrapper .nav-tab-wrapper #woe-admin .nav-tab input, #woe-admin .woe-admin-nav a input, .woe-calendar-wrapper .woe-admin-nav #woe-admin a input, #woe-admin .woe-btn-medium button, #woe-admin .nav-tab-wrapper .nav-tab button, .woe-calendar-wrapper .nav-tab-wrapper #woe-admin .nav-tab button, #woe-admin .woe-admin-nav a button, .woe-calendar-wrapper .woe-admin-nav #woe-admin a button, .woe-calendar-wrapper .woe-btn-medium, .woe-calendar-wrapper .nav-tab-wrapper .nav-tab,
488
+ .woe-calendar-wrapper h2.nav-tab-wrapper .nav-tab, .woe-calendar-wrapper .woe-admin-nav a, .woe-calendar-wrapper .woe-btn-medium input, .woe-calendar-wrapper .nav-tab-wrapper .nav-tab input, .woe-calendar-wrapper .woe-admin-nav a input, .woe-calendar-wrapper .woe-btn-medium button, .woe-calendar-wrapper .nav-tab-wrapper .nav-tab button, .woe-calendar-wrapper .woe-admin-nav a button, #woe-admin .woe-btn-small, .woe-calendar-wrapper .woe-btn-small, #woe-admin .woe-btn-small-round, .woe-calendar-wrapper .woe-btn-small-round, #woe-admin .woe-box-maininfo, .woe-calendar-wrapper .woe-box-maininfo {
489
+ font-family: "Open sans", serif;
490
+ font-size: 0.66667rem;
491
+ line-height: 0.91667rem; }
492
+
493
+ #woe-admin .woe-box-maininfo p, #woe-admin .woe-box-title span, #woe-admin .woe-box-info .woe-box-info-content, .woe-calendar-wrapper .woe-box-info .woe-box-info-content, #woe-admin .woe-box-info .woe-box-info-content h5, .woe-calendar-wrapper .woe-box-info .woe-box-info-content h5 {
494
+ color: #444; }
495
+
496
+ #woe-admin .woe-input-simple p {
497
+ color: #888;
498
+ font-weight: 400;
499
+ padding: 0.41667rem 0.66667rem;
500
+ margin: 0;
501
+ }
502
+
503
+ #woe-admin .woe-input-simple {
504
+ padding-bottom: 15px;
505
+ }
506
+ #woe-admin .woe-input-simple input, #woe-admin .woe-select input, #woe-admin .woe-input-simple textarea, #woe-admin .woe-select textarea {
507
+ color: #003553; }
508
+
509
+ #woe-admin .woe-input-simple input:focus, #woe-admin .woe-select input:focus, #woe-admin .woe-input-simple textarea:focus, #woe-admin .woe-select textarea:focus {
510
+ color: #0C6EB6; }
511
+
512
+ .woe-btn-tools {
513
+ display: inline-block;
514
+ margin-bottom: 0;
515
+ font-weight: normal;
516
+ text-align: center;
517
+ vertical-align: middle;
518
+ touch-action: manipulation;
519
+ cursor: pointer;
520
+ background-image: none;
521
+ border: 1px solid transparent;
522
+ white-space: nowrap;
523
+ padding: 6px 12px;
524
+ font-size: 14px;
525
+ line-height: 1.42857;
526
+ border-radius: 4px;
527
+ -webkit-user-select: none;
528
+ -moz-user-select: none;
529
+ -ms-user-select: none;
530
+ user-select: none;
531
+ cursor: not-allowed;
532
+ opacity: 0.65;
533
+ background-color: #fff;
534
+ border-color: #ccc;
535
+ margin-bottom: 10px;
536
+ }
537
+
538
+ #my-sort select {
539
+ width: 30%;
540
+ font-weight: normal;
541
+ }
542
+ #my-sort {
543
+ font-weight: bold;
544
+ }
545
+
546
+ #output_preview_total {
547
+ margin-left: 40px;
548
+ margin-right: 30px;
549
+ }
550
+
551
+ .hide {
552
+ display: none !important;
553
+ }
554
+
555
+
556
+ .without-dropdown.select2-dropdown,
557
+ .without-dropdown .select2-search--inline {
558
+ display: none;
559
+ }
560
+
561
+ .profiles #bulk_action{
562
+ width: 70px;
563
+ }
564
+
565
+ .like-input {
566
+ width: 120px;
567
+ }
568
+
569
+ #d-schedule-3 .block {
570
+ margin-left: 20px;
571
+ margin-right: 5px;
572
+ }
573
+
574
+ #d-schedule-3 .block.disabled {
575
+ pointer-events: none;
576
+ opacity: 0.7;
577
+ }
578
+
579
+ #d-schedule-3 .input-times {
580
+ width: 100%;
581
+ min-height: 30px;
582
+ background-color: white;
583
+ border: 1px solid #aaa;
584
+ border-radius: 4px;
585
+ cursor: text;
586
+ margin: 3px;
587
+ display: inline-block;
588
+ }
589
+
590
+ #d-schedule-3 .time {
591
+ background-color: #e4e4e4;
592
+ border: 1px solid #aaa;
593
+ border-radius: 4px;
594
+ cursor: default;
595
+ float: left;
596
+ margin: 5px;
597
+ padding: 0 5px;
598
+ }
599
+
600
+ #d-schedule-3 .btn-delete {
601
+ color: #999;
602
+ cursor: pointer;
603
+ display: inline-block;
604
+ font-weight: bold;
605
+ margin-right: 2px;
606
+ }
607
+
608
+ #d-schedule-3 .btn-delete:hover {
609
+ color: #333;
610
+ }
assets/img/1 ADDED
File without changes
assets/js/export.js ADDED
@@ -0,0 +1,1015 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ var select2WODropdownOpts = {
2
+ containerCssClass : 'without-dropdown',
3
+ dropdownCssClass: 'without-dropdown',
4
+ }
5
+
6
+
7
+ function bind_events() {
8
+
9
+ // for filter by ORDER custom fields
10
+ jQuery( '#custom_fields' ).change( function() {
11
+
12
+ jQuery( '#select_custom_fields' ).attr( 'disabled', 'disabled' );
13
+ var data = {
14
+ 'cf_name': jQuery( this ).val(),
15
+ method: "get_order_custom_fields_values",
16
+ action: "order_exporter"
17
+ };
18
+ var val_op = jQuery( '#custom_fields_compare' ).val();
19
+ jQuery( '#text_custom_fields' ).val( '' );
20
+ jQuery.post( ajaxurl, data, function( response ) {
21
+ jQuery( '#select_custom_fields' ).remove();
22
+ jQuery( '#select_custom_fields--select2 select' ).select2('destroy');
23
+ jQuery( '#select_custom_fields, #select_custom_fields--select2' ).remove();
24
+ if ( response ) {
25
+ var options = '';
26
+ jQuery.each( response, function( index, value ) {
27
+ options += '<option>' + value + '</option>';
28
+ } );
29
+ var $select = jQuery( '<div id="select_custom_fields--select2" style="margin-top: 0px;margin-right: 6px; vertical-align: top;'
30
+ + 'display: ' + (('LIKE' === val_op) ? 'none' : 'inline-block') + ';">'
31
+ + '<select id="select_custom_fields">' + options + '</select></div>' );
32
+ $select.insertBefore( jQuery( '#add_custom_fields' ) )
33
+ $select.find('select').select2({ tags: true });
34
+ }
35
+ else {
36
+ jQuery( '<input type="text" id="select_custom_fields" style="margin-right: 8px;">' ).insertBefore( jQuery( '#add_custom_fields' ) );
37
+ }
38
+ }, 'json' );
39
+ } );
40
+ jQuery( '#add_custom_fields' ).click( function() {
41
+
42
+ var val = !jQuery( "#select_custom_fields" ).is(':disabled') ? jQuery( "#select_custom_fields" ).val() : jQuery( "#text_custom_fields" ).val();
43
+ var val2 = jQuery( '#custom_fields' ).val();
44
+ var val_op = jQuery( '#custom_fields_compare' ).val();
45
+ if ( val != null && val2 != null && val.length && val2.length ) {
46
+ val = val2 + ' ' + val_op + ' ' + val;
47
+
48
+ var f = true;
49
+ jQuery( '#custom_fields_check' ).next().find( 'ul li' ).each( function() {
50
+ if ( jQuery( this ).attr( 'title' ) == val ) {
51
+ f = false;
52
+ }
53
+ } );
54
+
55
+ if ( f ) {
56
+
57
+ jQuery( '#custom_fields_check' ).append( '<option selected="selected" value="' + val + '">' + val + '</option>' );
58
+ jQuery( '#custom_fields_check' ).select2();
59
+
60
+ jQuery( '#custom_fields_check option' ).each( function() {
61
+ jQuery( '#custom_fields_check option[value=\"' + jQuery( this ).val() + '\"]:not(:last)' ).remove();
62
+ } );
63
+
64
+ jQuery( "input#select_custom_fields" ).val( '' );
65
+ }
66
+ }
67
+
68
+ return false;
69
+ } );
70
+
71
+ jQuery( '#custom_fields_compare').change(function() {
72
+ var val_op = jQuery( '#custom_fields_compare' ).val();
73
+ if ( 'LIKE' === val_op ) {
74
+ jQuery( "#select_custom_fields" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
75
+ jQuery( "#select_custom_fields--select2" ).hide();
76
+ jQuery( "#text_custom_fields" ).css('display', 'inline' ).attr( 'disabled', false );
77
+ }
78
+ else {
79
+ jQuery( "#select_custom_fields" ).css( 'display', 'inline-block' ).attr( 'disabled', false );
80
+ jQuery( '#select_custom_fields--select2' ).css('display', 'inline' );
81
+ jQuery( "#text_custom_fields" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
82
+ }
83
+ });
84
+ //end of change
85
+
86
+ //PRODUCT ATTRIBUTES BEGIN
87
+ jQuery( '#attributes' ).change( function() {
88
+
89
+ jQuery( '#select_attributes' ).attr( 'disabled', 'disabled' );
90
+ var data = {
91
+ 'attr': jQuery( this ).val(),
92
+ method: "get_products_attributes_values",
93
+ action: "order_exporter"
94
+ };
95
+
96
+ var val_op = jQuery( '#attributes_compare' ).val();
97
+ jQuery( '#text_attributes' ).val( '' );
98
+
99
+ jQuery.post( ajaxurl, data, function( response ) {
100
+ jQuery( '#select_attributes--select2 select' ).select2('destroy');
101
+ jQuery( '#select_attributes, #select_attributes--select2' ).remove();
102
+
103
+ if ( response ) {
104
+ var options = '';
105
+ jQuery.each( response, function( index, value ) {
106
+ options += '<option>' + value + '</option>';
107
+ } );
108
+ var $select = jQuery( '<div id="select_attributes--select2" style="margin-top: 0px;margin-right: 6px; vertical-align: top;'
109
+ + 'display: ' + (('LIKE' === val_op) ? 'none' : 'inline-block') + ';">'
110
+ + '<select id="select_attributes">' + options + '</select></div>' );
111
+ $select.insertBefore( jQuery( '#add_attributes' ) )
112
+ $select.find('select').select2({ tags: true });
113
+ }
114
+ else {
115
+ jQuery( '<input type="text" id="select_attributes" style="margin-right: 8px;">' ).insertBefore( jQuery( '#add_attributes' ) );
116
+ }
117
+ }, 'json' );
118
+ } );
119
+
120
+ jQuery( '#add_attributes' ).click( function() {
121
+
122
+ var val = !jQuery( "#select_attributes" ).is(':disabled') ? jQuery( "#select_attributes" ).val() : jQuery( "#text_attributes" ).val();
123
+ var val2 = jQuery( '#attributes' ).val();
124
+ var val_op = jQuery( '#attributes_compare' ).val();
125
+ if ( val != null && val2 != null && val.length && val2.length ) {
126
+ val = val2 + ' ' + val_op + ' ' + val;
127
+
128
+ var f = true;
129
+ jQuery( '#attributes_check' ).next().find( 'ul li' ).each( function() {
130
+ if ( jQuery( this ).attr( 'title' ) == val ) {
131
+ f = false;
132
+ }
133
+ } );
134
+
135
+ if ( f ) {
136
+
137
+ jQuery( '#attributes_check' ).append( '<option selected="selected" value="' + val + '">' + val + '</option>' );
138
+ jQuery( '#attributes_check' ).select2(select2WODropdownOpts);
139
+
140
+ jQuery( '#attributes_check option' ).each( function() {
141
+ jQuery( '#attributes_check option[value=\"' + jQuery( this ).val() + '\"]:not(:last)' ).remove();
142
+ } );
143
+
144
+ jQuery( "input#select_attributes" ).val( '' );
145
+ }
146
+ }
147
+
148
+ return false;
149
+ } );
150
+
151
+ jQuery( '#attributes_compare').change(function() {
152
+ var val_op = jQuery( '#attributes_compare' ).val();
153
+ if ( 'LIKE' === val_op ) {
154
+ jQuery( "#select_attributes" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
155
+ jQuery( "#select_attributes--select2" ).hide();
156
+ jQuery( "#text_attributes" ).css('display', 'inline' ).attr( 'disabled', false );
157
+ }
158
+ else {
159
+ jQuery( "#select_attributes" ).css( 'display', 'inline-block' ).attr( 'disabled', false );
160
+ jQuery( "#select_attributes--select2" ).css('display', 'inline' );
161
+ jQuery( "#text_attributes" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
162
+ }
163
+ });
164
+ //PRODUCT ATTRIBUTES END
165
+
166
+ jQuery( '#itemmeta' ).change( function() {
167
+ var selected64 = jQuery( this ).find(":selected").data("base64");
168
+
169
+ jQuery( '#select_itemmeta' ).attr( 'disabled', 'disabled' );
170
+ var data = {
171
+ 'item': window.atob(selected64),
172
+ method: "get_products_itemmeta_values",
173
+ action: "order_exporter"
174
+ };
175
+
176
+ var val_op = jQuery( '#itemmeta_compare' ).val();
177
+ jQuery( '#text_itemmeta' ).val( '' );
178
+
179
+ jQuery.post( ajaxurl, data, function( response ) {
180
+ jQuery( '#select_itemmeta--select2 select' ).select2('destroy');
181
+ jQuery( '#select_itemmeta, #select_itemmeta--select2' ).remove();
182
+ if ( response ) {
183
+ var options = '';
184
+ jQuery.each( response, function( index, value ) {
185
+ options += '<option>' + value + '</option>';
186
+ } );
187
+ var $select = jQuery( '<div id="select_itemmeta--select2" style="margin-top: 0px;margin-right: 6px; vertical-align: top;'
188
+ + 'display: ' + (('LIKE' === val_op) ? 'none' : 'inline-block') + ';">'
189
+ + '<select id="select_itemmeta">' + options + '</select></div>' );
190
+ $select.insertBefore( jQuery( '#add_itemmeta' ) )
191
+ $select.find('select').select2({ tags: true });
192
+ }
193
+ else {
194
+ jQuery( '<input type="text" id="select_itemmeta" style="margin-right: 8px;">' ).insertBefore( jQuery( '#add_itemmeta' ) );
195
+ }
196
+ }, 'json' );
197
+ } );
198
+
199
+ jQuery( '#add_itemmeta' ).click( function() {
200
+
201
+ var val = !jQuery( "#select_itemmeta" ).is(':disabled') ? jQuery( "#select_itemmeta" ).val() : jQuery( "#text_itemmeta" ).val();
202
+ var selected64 = jQuery( '#itemmeta' ).find(":selected").data("base64");
203
+ var val2 = window.atob(selected64).replace(/&/g,'&amp;');
204
+ var val_op = jQuery( '#itemmeta_compare' ).val();
205
+ if ( val != null && val2 != null && val.length && val2.length ) {
206
+ val = val2 + ' ' + val_op + ' ' + val;
207
+
208
+ var f = true;
209
+ jQuery( '#itemmeta_check' ).next().find( 'ul li' ).each( function() {
210
+ if ( jQuery( this ).attr( 'title' ) == val ) {
211
+ f = false;
212
+ }
213
+ } );
214
+
215
+ if ( f ) {
216
+
217
+ jQuery( '#itemmeta_check' ).append( '<option selected="selected" value="' + val + '">' + val + '</option>' );
218
+ jQuery( '#itemmeta_check' ).select2(select2WODropdownOpts);
219
+
220
+ jQuery( '#itemmeta_check option' ).each( function() {
221
+ jQuery( '#itemmeta_check option[value=\"' + jQuery( this ).val() + '\"]:not(:last)' ).remove(); // jQuerySelectorEscape ?
222
+ } );
223
+
224
+ jQuery( "input#select_itemmeta" ).val( '' );
225
+ }
226
+ }
227
+
228
+ return false;
229
+ } );
230
+
231
+ jQuery( '#itemmeta_compare').change(function() {
232
+ var val_op = jQuery( '#itemmeta_compare' ).val();
233
+ if ( 'LIKE' === val_op ) {
234
+ jQuery( "#select_itemmeta" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
235
+ jQuery( "#select_itemmeta--select2" ).hide();
236
+ jQuery( "#text_itemmeta" ).css('display', 'inline' ).attr( 'disabled', false );
237
+ }
238
+ else {
239
+ jQuery( "#select_itemmeta" ).css( 'display', 'inline-block' ).attr( 'disabled', false );
240
+ jQuery( "#select_itemmeta--select2" ).css('display', 'inline' );
241
+ jQuery( "#text_itemmeta" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
242
+ }
243
+ });
244
+
245
+ //PRODUCT TAXONOMIES BEGIN
246
+ jQuery( '#taxonomies' ).change( function() {
247
+
248
+ jQuery( '#select_taxonomies' ).attr( 'disabled', 'disabled' );
249
+ var data = {
250
+ 'tax': jQuery( this ).val(),
251
+ method: "get_products_taxonomies_values",
252
+ action: "order_exporter"
253
+ };
254
+
255
+ jQuery.post( ajaxurl, data, function( response ) {
256
+ jQuery( '#select_taxonomies--select2 select' ).select2('destroy');
257
+ jQuery( '#select_taxonomies, #select_taxonomies--select2' ).remove();
258
+ if ( response ) {
259
+ var options = '';
260
+ jQuery.each( response, function( index, value ) {
261
+ options += '<option>' + value + '</option>';
262
+ } );
263
+ var $select = jQuery( '<div id="select_taxonomies--select2" style="margin-top: 0px;margin-right: 6px; vertical-align: top; display: inline-block;">'
264
+ + '<select id="select_taxonomies">' + options + '</select></div>' );
265
+ $select.insertBefore( jQuery( '#add_taxonomies' ) )
266
+ $select.find('select').select2({ tags: true });
267
+ }
268
+ else {
269
+ jQuery( '<input type="text" id="select_taxonomies" style="margin-right: 8px;">' ).insertBefore( jQuery( '#add_taxonomies' ) );
270
+ }
271
+ }, 'json' );
272
+ } );
273
+
274
+ jQuery( '#add_taxonomies' ).click( function() {
275
+
276
+ var val = !jQuery( "#select_taxonomies" ).is(':disabled') ? jQuery( "#select_taxonomies" ).val() : jQuery( "#text_taxonomies" ).val();
277
+ var val2 = jQuery( '#taxonomies' ).val();
278
+ var val_op = jQuery( '#taxonomies_compare' ).val();
279
+ if ( val != null && val2 != null && val.length && val2.length ) {
280
+ val = val2 + ' ' + val_op + ' ' + val;
281
+
282
+ var f = true;
283
+ jQuery( '#taxonomies_check' ).next().find( 'ul li' ).each( function() {
284
+ if ( jQuery( this ).attr( 'title' ) == val ) {
285
+ f = false;
286
+ }
287
+ } );
288
+
289
+ if ( f ) {
290
+
291
+ jQuery( '#taxonomies_check' ).append( '<option selected="selected" value="' + val + '">' + val + '</option>' );
292
+ jQuery( '#taxonomies_check' ).select2(select2WODropdownOpts);
293
+
294
+ jQuery( '#taxonomies_check option' ).each( function() {
295
+ jQuery( '#taxonomies_check option[value=\"' + jQuery( this ).val() + '\"]:not(:last)' ).remove();
296
+ } );
297
+
298
+ jQuery( "input#select_taxonomies" ).val( '' );
299
+ }
300
+ }
301
+
302
+ return false;
303
+ } );
304
+
305
+ jQuery( '#taxonomies_compare').change(function() {
306
+ var val_op = jQuery( '#taxonomies_compare' ).val();
307
+ if ( 'LIKE' === val_op ) {
308
+ jQuery( "#select_taxonomies" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
309
+ jQuery( "#text_taxonomies" ).css('display', 'inline' ).attr( 'disabled', false );
310
+ }
311
+ else {
312
+ jQuery( "#select_taxonomies" ).css( 'display', 'inline-block' ).attr( 'disabled', false );
313
+ jQuery( "#text_taxonomies" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
314
+ }
315
+ });
316
+ //PRODUCT TAXONOMIES END
317
+
318
+ // for filter by PRODUCT custom fields
319
+ jQuery( '#product_custom_fields' ).change( function() {
320
+
321
+ jQuery( '#select_product_custom_fields' ).attr( 'disabled', 'disabled' );
322
+ var data = {
323
+ 'cf_name': jQuery( this ).val(),
324
+ method: "get_product_custom_fields_values",
325
+ action: "order_exporter"
326
+ };
327
+
328
+ var val_op = jQuery( '#product_custom_fields_compare' ).val();
329
+ jQuery( '#text_product_custom_fields' ).val( '' );
330
+
331
+ jQuery.post( ajaxurl, data, function( response ) {
332
+ jQuery( '#select_product_custom_fields--select2 select' ).select2('destroy');
333
+ jQuery( '#select_product_custom_fields, #select_product_custom_fields--select2' ).remove();
334
+ if ( response ) {
335
+ var options = '';
336
+ jQuery.each( response, function( index, value ) {
337
+ options += '<option>' + value + '</option>';
338
+ } );
339
+ var $select = jQuery( '<div id="select_product_custom_fields--select2" style="margin-top: 0px;margin-right: 6px; vertical-align: top;'
340
+ + 'display: ' + (('LIKE' === val_op) ? 'none' : 'inline-block') + ';">'
341
+ + '<select id="select_product_custom_fields">' + options + '</select></div>' );
342
+ $select.insertBefore( jQuery( '#add_product_custom_fields' ) )
343
+ $select.find('select').select2({ tags: true });
344
+ }
345
+ else {
346
+ jQuery( '<input type="text" id="select_product_custom_fields" style="margin-right: 8px;">' ).insertBefore( jQuery( '#add_product_custom_fields' ) );
347
+ }
348
+ }, 'json' );
349
+ } );
350
+ jQuery( '#add_product_custom_fields' ).click( function() {
351
+
352
+ var val = !jQuery( "#select_product_custom_fields" ).is(':disabled') ? jQuery( "#select_product_custom_fields" ).val() : jQuery( "#text_product_custom_fields" ).val();
353
+ var val2 = jQuery( '#product_custom_fields' ).val();
354
+ var val_op = jQuery( '#product_custom_fields_compare' ).val();
355
+ if ( val != null && val2 != null && val.length && val2.length ) {
356
+ val = val2 + ' ' + val_op + ' ' + val;
357
+
358
+ var f = true;
359
+ jQuery( '#product_custom_fields_check' ).next().find( 'ul li' ).each( function() {
360
+ if ( jQuery( this ).attr( 'title' ) == val ) {
361
+ f = false;
362
+ }
363
+ } );
364
+
365
+ if ( f ) {
366
+
367
+ jQuery( '#product_custom_fields_check' ).append( '<option selected="selected" value="' + val + '">' + val + '</option>' );
368
+ jQuery( '#product_custom_fields_check' ).select2(select2WODropdownOpts);
369
+
370
+ jQuery( '#product_custom_fields_check option' ).each( function() {
371
+ jQuery( '#product_custom_fields_check option[value=\"' + jQuery( this ).val() + '\"]:not(:last)' ).remove();
372
+ } );
373
+
374
+ jQuery( "input#select_product_custom_fields" ).val( '' );
375
+ }
376
+ }
377
+
378
+ return false;
379
+ } );
380
+
381
+ jQuery( '#product_custom_fields_compare').change(function() {
382
+ var val_op = jQuery( '#product_custom_fields_compare' ).val();
383
+ if ( 'LIKE' === val_op ) {
384
+ jQuery( "#select_product_custom_fields" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
385
+ jQuery( "#select_product_custom_fields--select2" ).hide();
386
+ jQuery( "#text_product_custom_fields" ).css('display', 'inline' ).attr( 'disabled', false );
387
+ }
388
+ else {
389
+ jQuery( "#select_product_custom_fields" ).css( 'display', 'inline-block' ).attr( 'disabled', false );
390
+ jQuery( "#select_product_custom_fields--select2" ).css('display', 'inline' );
391
+ jQuery( "#text_product_custom_fields" ).css( 'display', 'none' ).attr( 'disabled', 'disabled' );
392
+ }
393
+ });
394
+ //end of change
395
+
396
+
397
+ jQuery( '#orders_add_custom_field' ).click( function() {
398
+ jQuery( "#fields_control > div" ).hide();
399
+ jQuery( "#fields_control .div_custom" ).show();
400
+
401
+ //add_custom_field(jQuery("#order_fields"),'products','CSV');
402
+ return false;
403
+ } );
404
+ jQuery( '#orders_add_custom_meta' ).click( function() {
405
+ jQuery('#custom_meta_order_mode_used').attr('checked', false);
406
+ jQuery('#custom_meta_order_mode_used').change();
407
+ jQuery( "#fields_control > div" ).hide();
408
+ jQuery( "#fields_control .div_meta" ).show();
409
+
410
+ //add_custom_field(jQuery("#order_fields"),'products','CSV');
411
+ return false;
412
+ } );
413
+
414
+ jQuery( '.button_cancel' ).click( function() {
415
+ reset_field_contorls();
416
+ return false;
417
+ } );
418
+
419
+ ///*CUSTOM FIELDS BINDS
420
+ jQuery( '#button_custom_field' ).click( function() {
421
+ var colname = jQuery( '#colname_custom_field' ).val();
422
+ var value = jQuery( '#value_custom_field' ).val();
423
+ if ( !colname )
424
+ {
425
+ alert( export_messages.empty_column_name );
426
+ jQuery( '#colname_custom_field' ).focus();
427
+ return false
428
+ }
429
+ /*if ( !value )
430
+ {
431
+ alert( 'empty Value' );
432
+ jQuery( '#value_custom_field' ).focus();
433
+ return false
434
+ }*/
435
+ add_custom_field( jQuery( "#order_fields" ), 'orders', output_format, colname, value );
436
+ reset_field_contorls();
437
+ return false;
438
+ } );
439
+
440
+ jQuery('input[name=custom_meta_order_mode]').change(function() {
441
+ if ( !jQuery(this).prop('checked') ) {
442
+ var options = '<option></option>';
443
+ jQuery.each( window.order_custom_meta_fields, function( index, value ) {
444
+ options += '<option value="' + escapeStr(value) + '">' + value + '</option>';
445
+ } );
446
+ jQuery( '#select_custom_meta_order' ).html( options );
447
+ }
448
+ else {
449
+ var data = jQuery( '#export_job_settings' ).serialize()
450
+ data = data + "&action=order_exporter&method=get_used_custom_order_meta";
451
+
452
+ jQuery.post( ajaxurl, data, function( response ) {
453
+ if ( response ) {
454
+ var options = '<option></option>';
455
+ jQuery.each( response, function( index, value ) {
456
+ options += '<option value="' + escapeStr(value) + '">' + value + '</option>';
457
+ } );
458
+ jQuery( '#select_custom_meta_order' ).html( options );
459
+ }
460
+ }, 'json' );
461
+ }
462
+ });
463
+
464
+ jQuery('input[name=custom_meta_products_mode]').change(function() {
465
+ if ( !jQuery( this ).is( ':checked' ) ) {
466
+ var options = '<option></option>';
467
+ jQuery.each( window.order_products_custom_meta_fields, function( index, value ) {
468
+ options += '<option value="' + escapeStr(value) + '">' + value + '</option>';
469
+ } );
470
+ jQuery( '#select_custom_meta_products' ).html( options );
471
+ }
472
+ else {
473
+ jQuery('#modal-manage-products').html(jQuery('#TB_ajaxContent').html());
474
+ var data = jQuery( '#export_job_settings' ).serialize();
475
+ data = data + "&action=order_exporter&method=get_used_custom_products_meta&mode=" + mode + "&id=" + job_id;
476
+
477
+ jQuery.post( ajaxurl, data, function( response ) {
478
+ if ( response ) {
479
+ var options = '<option></option>';
480
+ jQuery.each( response, function( index, value ) {
481
+ options += '<option value="' + escapeStr(value) + '">' + value + '</option>';
482
+ } );
483
+ jQuery( '#select_custom_meta_products' ).html( options );
484
+ }
485
+ }, 'json' );
486
+ jQuery('#modal-manage-products').html('');
487
+ }
488
+ });
489
+
490
+ jQuery('input[name=custom_meta_coupons_mode]').change(function() {
491
+ if (jQuery(this).val() == 'all') {
492
+ var options = '<option></option>';
493
+ jQuery.each( window.order_coupons_custom_meta_fields, function( index, value ) {
494
+ options += '<option value="' + escapeStr(value) + '">' + value + '</option>';
495
+ } );
496
+ jQuery( '#select_custom_meta_coupons' ).html( options );
497
+ }
498
+ else {
499
+ var data = jQuery( '#export_job_settings' ).serialize()
500
+ data = data + "&action=order_exporter&method=get_used_custom_coupons_meta";
501
+
502
+ jQuery.post( ajaxurl, data, function( response ) {
503
+ if ( response ) {
504
+ var options = '<option></option>';
505
+ jQuery.each( response, function( index, value ) {
506
+ options += '<option value="' + escapeStr(value) + '">' + value + '</option>';
507
+ } );
508
+ jQuery( '#select_custom_meta_coupons' ).html( options );
509
+ }
510
+ }, 'json' );
511
+ }
512
+ });
513
+
514
+ jQuery( '#button_custom_meta' ).click( function() {
515
+ var label = jQuery( '#select_custom_meta_order' ).val();
516
+ var colname = jQuery( '#colname_custom_meta' ).val();
517
+ if (! label) //try custom text
518
+ label = jQuery( '#text_custom_meta_order' ).val();;
519
+ if ( !label )
520
+ {
521
+ alert( export_messages.empty_meta_key );
522
+ jQuery( '#select_custom_meta_order' ).focus();
523
+ return false
524
+ }
525
+ if ( !colname )
526
+ {
527
+ alert( export_messages.empty_column_name );
528
+ jQuery( '#colname_custom_meta' ).focus();
529
+ return false
530
+ }
531
+ add_custom_meta( jQuery( "#order_fields" ), 'orders', output_format, label, colname );
532
+ reset_field_contorls();
533
+ return false;
534
+ } );
535
+
536
+ /////////////END CUSTOM FIELDS BINDS
537
+
538
+ // SHIPPING LOCATIONS
539
+ jQuery( '#shipping_locations' ).change( function() {
540
+
541
+ jQuery( '#text_shipping_locations' ).attr( 'disabled', 'disabled' );
542
+ var data = {
543
+ 'item': jQuery( this ).val(),
544
+ method: "get_order_shipping_values",
545
+ action: "order_exporter"
546
+ };
547
+
548
+ jQuery.post( ajaxurl, data, function( response ) {
549
+ jQuery( '#text_shipping_locations--select2 select' ).select2('destroy');
550
+ jQuery( '#text_shipping_locations, #text_shipping_locations--select2' ).remove();
551
+ if ( response ) {
552
+ var options = '';
553
+ jQuery.each( response, function( index, value ) {
554
+ options += '<option>' + value + '</option>';
555
+ } );
556
+
557
+ var $select = jQuery( '<div id="text_shipping_locations--select2" style="margin-top: 0px;margin-right: 6px; vertical-align: top; display: inline-block;"><select id="text_shipping_locations">' + options + '</select></div>' );
558
+ $select.insertBefore( jQuery( '#add_shipping_locations' ) )
559
+ $select.find('select').select2({ tags: true });
560
+ }
561
+ else {
562
+ jQuery( '<input type="text" id="text_shipping_locations" style="margin-right: 8px;">' ).insertBefore( jQuery( '#add_shipping_locations' ) );
563
+ }
564
+ }, 'json' );
565
+ } );
566
+
567
+ jQuery( '#add_shipping_locations' ).click( function() {
568
+
569
+ var val = jQuery( "#text_shipping_locations" ).val();
570
+ var val2 = jQuery( '#shipping_locations' ).val();
571
+ var val_op = jQuery( '#shipping_compare' ).val();
572
+ if ( val != null && val2 != null && val.length && val2.length ) {
573
+ val = val2 + val_op + val;
574
+
575
+ var f = true;
576
+ jQuery( '#shipping_locations_check' ).next().find( 'ul li' ).each( function() {
577
+ if ( jQuery( this ).attr( 'title' ) == val ) {
578
+ f = false;
579
+ }
580
+ } );
581
+
582
+ if ( f ) {
583
+
584
+ jQuery( '#shipping_locations_check' ).append( '<option selected="selected" value="' + val + '">' + val + '</option>' );
585
+ jQuery( '#shipping_locations_check' ).select2(select2WODropdownOpts);
586
+
587
+ jQuery( '#shipping_locations_check option' ).each( function() {
588
+ jQuery( '#shipping_locations_check option[value=\"' + jQuery( this ).val() + '\"]:not(:last)' ).remove();
589
+ } );
590
+
591
+ jQuery( "input#text_shipping_locations" ).val( '' );
592
+ }
593
+ }
594
+ return false;
595
+ } );
596
+
597
+ // BILLING LOCATIONS
598
+ jQuery( '#billing_locations' ).change( function() {
599
+
600
+ jQuery( '#text_billing_locations' ).attr( 'disabled', 'disabled' );
601
+ var data = {
602
+ 'item': jQuery( this ).val(),
603
+ method: "get_order_billing_values",
604
+ action: "order_exporter"
605
+ };
606
+
607
+ jQuery.post( ajaxurl, data, function( response ) {
608
+ jQuery( '#text_billing_locations--select2 select' ).select2('destroy');
609
+ jQuery( '#text_billing_locations, #text_billing_locations--select2' ).remove();
610
+ if ( response ) {
611
+ var options = '';
612
+ jQuery.each( response, function( index, value ) {
613
+ options += '<option>' + value + '</option>';
614
+ } );
615
+ var $select = jQuery( '<div id="text_billing_locations--select2" style="margin-top: 0px;margin-right: 6px; vertical-align: top; display: inline-block;">'
616
+ + '<select id="text_billing_locations">' + options + '</select></div>' );
617
+ $select.insertBefore( jQuery( '#add_billing_locations' ) )
618
+ $select.find('select').select2({ tags: true });
619
+ }
620
+ else {
621
+ jQuery( '<input type="text" id="text_billing_locations" style="margin-right: 8px;">' ).insertBefore( jQuery( '#add_billing_locations' ) );
622
+ }
623
+ }, 'json' );
624
+ } );
625
+
626
+ jQuery( '#add_billing_locations' ).click( function() {
627
+
628
+ var val = jQuery( "#text_billing_locations" ).val();
629
+ var val2 = jQuery( '#billing_locations' ).val();
630
+ var val_op = jQuery( '#billing_compare' ).val();
631
+ if ( val != null && val2 != null && val.length && val2.length ) {
632
+ val = val2 + val_op + val;
633
+
634
+ var f = true;
635
+ jQuery( '#billing_locations_check' ).next().find( 'ul li' ).each( function() {
636
+ if ( jQuery( this ).attr( 'title' ) == val ) {
637
+ f = false;
638
+ }
639
+ } );
640
+
641
+ if ( f ) {
642
+
643
+ jQuery( '#billing_locations_check' ).append( '<option selected="selected" value="' + val + '">' + val + '</option>' );
644
+ jQuery( '#billing_locations_check' ).select2(select2WODropdownOpts);
645
+
646
+ jQuery( '#billing_locations_check option' ).each( function() {
647
+ jQuery( '#billing_locations_check option[value=\"' + jQuery( this ).val() + '\"]:not(:last)' ).remove();
648
+ } );
649
+
650
+ jQuery( "input#text_billing_locations" ).val( '' );
651
+ }
652
+ }
653
+ return false;
654
+ } )
655
+ }
656
+
657
+ function add_bind_for_custom_fields( prefix, output_format, $to ) {
658
+ jQuery( '#button_custom_meta_' + prefix + '' ).off();
659
+ jQuery( '#button_custom_field_' + prefix + '' ).off();
660
+ jQuery( '#button_custom_field_' + prefix + '' ).click( function() {
661
+ var colname = jQuery( '#colname_custom_field_' + prefix + '' ).val();
662
+ var value = jQuery( '#value_custom_field_' + prefix + '' ).val();
663
+ if ( !colname )
664
+ {
665
+ alert( export_messages.empty_column_name );
666
+ jQuery( '#colname_custom_field_' + prefix + '' ).focus();
667
+ return false
668
+ }
669
+ if ( !value )
670
+ {
671
+ alert( export_messages.empty_value );
672
+ jQuery( '#value_custom_field_' + prefix + '' ).focus();
673
+ return false
674
+ }
675
+ jQuery( '#colname_custom_field_' + prefix + '' ).val( "" );
676
+ jQuery( '#value_custom_field_' + prefix + '' ).val( "" );
677
+ add_custom_field( $to, prefix, output_format, colname, value );
678
+ return false;
679
+ } );
680
+
681
+ jQuery( '#button_custom_meta_' + prefix + '' ).click( function() {
682
+ var type = jQuery( '#select_custom_meta_' + prefix + '' ).val() != '' ? 'meta' : 'taxonomies';
683
+ type = type + '_' + prefix;
684
+ var label = jQuery( '#select_custom_' + type + '' ).val();
685
+ var colname = jQuery( '#colname_custom_meta_' + prefix + '' ).val();
686
+ if ( colname == undefined || colname == '' ) {
687
+ colname = label;
688
+ }
689
+ if ( !colname )
690
+ {
691
+ alert( export_messages.empty_column_name );
692
+ return false
693
+ }
694
+ add_custom_meta( $to, prefix, output_format, label, colname );
695
+ jQuery( '#select_custom_' + type + '' ).val( "" );
696
+ jQuery( '#colname_custom_meta_' + prefix + '' ).val( "" );
697
+ return false;
698
+ } );
699
+ }
700
+
701
+ function reset_field_contorls() {
702
+ jQuery( '#fields_control' ).find( 'input' ).val( '' );
703
+ jQuery( "#fields_control > div" ).hide();
704
+ jQuery( "#fields_control .div1" ).show();
705
+ jQuery( "#fields_control .div2" ).show();
706
+ }
707
+
708
+ function formatItem( item ) {
709
+ var markup = '<div class="clearfix">' +
710
+ '<div>';
711
+ if ( typeof item.photo_url !== "undefined" )
712
+ markup += '<img src="' + item.photo_url + '" style="width: 20%;float:left;" />';
713
+ markup += '<div style="width:75%;float:left; padding: 5px;">' + item.text + '</div>' +
714
+ '</div>' +
715
+ '</div><div style="clear:both"></div>';
716
+
717
+ return markup;
718
+ }
719
+
720
+ function add_custom_field( to, index_p, format, colname, value ) {
721
+
722
+ value = escapeStr(value);
723
+ colname = escapeStr(colname);
724
+ var arr = jQuery( 'input[name*=' + index_p + '\\[label\\]\\[custom_field]' );
725
+ var count = arr.length;
726
+
727
+ var max = 0;
728
+ for(var i=0; i<count; i++) {
729
+ var n = parseInt(arr[i].name.replace(index_p+'[label][custom_field_', '').replace(']','')); // fixed for popups
730
+ if(n > max) {
731
+ max = n;
732
+ }
733
+ }
734
+ count = max+1;
735
+
736
+ // console.log( to, index_p, format, colname, value );
737
+ var row = '<li class="mapping_row segment_modal_' + index_p + '">\
738
+ <div class="mapping_col_1">\
739
+ <input type=hidden name="' + index_p + '[exported][custom_field_' + count + ']" value="0">\
740
+ <input type=checkbox name="' + index_p + '[exported][custom_field_' + count + ']" value="1" checked>\
741
+ <input class="mapping_fieldname" type=hidden name="' + index_p + '[segment][custom_field_' + count + ']" value="misc">\
742
+ <input class="mapping_fieldname" type=hidden name="' + index_p + '[label][custom_field_' + count + ']" value="' + colname + '">\
743
+ </div>\
744
+ <div class="mapping_col_2">' + colname + '<a href="#" onclick="return remove_custom_field(this);" style="float: right;"><span class="ui-icon ui-icon-trash"></span></a></div>\
745
+ <div class="mapping_col_3"><input class="mapping_fieldname" type=input name="' + index_p + '[colname][custom_field_' + count + ']" value="' + colname + '"></div>\
746
+ <div class="mapping_col_3"><input class="mapping_fieldname" type=input name="' + index_p + '[value][custom_field_' + count + ']" value="' + value + '"></div>\
747
+ </li>\
748
+ ';
749
+ to.append( row );
750
+ }
751
+
752
+ function add_custom_meta( to, index_p, format, label, colname ) {
753
+
754
+ label = escapeStr(label);
755
+ colname = escapeStr(colname);
756
+
757
+ // console.log();
758
+ var row = '<li class="mapping_row segment_modal_' + index_p + '">\
759
+ <div class="mapping_col_1">\
760
+ <input type=hidden name="' + index_p + '[exported][' + label + ']" value="0">\
761
+ <input type=checkbox name="' + index_p + '[exported][' + label + ']" value="1" checked>\
762
+ <input class="mapping_fieldname" type=hidden name="' + index_p + '[label][' + label + ']" value="' + label + '">\
763
+ </div>\
764
+ <div class="mapping_col_2">' + label + '<a href="#" onclick="return remove_custom_field(this);" style="float: right;"><span class="ui-icon ui-icon-trash"></span></a></div>\
765
+ <div class="mapping_col_3"><input class="mapping_fieldname" type=input name="' + index_p + '[colname][' + label + ']" value="' + colname + '"></div>\
766
+ </li>\
767
+ ';
768
+ to.append( row );
769
+ }
770
+
771
+ function formatItemSelection( item ) {
772
+ return item.text;
773
+ }
774
+
775
+ function select2_inits()
776
+ {
777
+ jQuery( "#from_status, #to_status" ).select2({
778
+ multiple: true
779
+ });
780
+ jQuery( "#statuses" ).select2();
781
+ jQuery( "#shipping_methods" ).select2();
782
+ jQuery( "#user_roles" ).select2();
783
+ jQuery( "#payment_methods" ).select2();
784
+ jQuery( "#attributes" ).select2( {
785
+ width: 150
786
+ } );
787
+ jQuery( "#attributes_check" ).select2(select2WODropdownOpts);
788
+ jQuery( "#itemmeta" ).select2( {
789
+ width: 220
790
+ } );
791
+ jQuery( "#itemmeta_check" ).select2(select2WODropdownOpts);
792
+
793
+ jQuery( "#custom_fields" ).select2( {
794
+ width: 150
795
+ } );
796
+ jQuery( "#custom_fields_check" ).select2();
797
+
798
+ jQuery( "#product_custom_fields" ).select2( {
799
+ width: 150
800
+ } );
801
+ jQuery( "#product_custom_fields_check" ).select2(select2WODropdownOpts);
802
+
803
+
804
+
805
+ jQuery( "#taxonomies" ).select2( {
806
+ width: 150
807
+ } );
808
+ jQuery( "#taxonomies_check" ).select2(select2WODropdownOpts);
809
+
810
+ jQuery( "#shipping_locations" ).select2( {
811
+ width: 150
812
+ } );
813
+ jQuery( "#shipping_locations_check" ).select2(select2WODropdownOpts);
814
+
815
+ jQuery( "#billing_locations" ).select2( {
816
+ width: 150
817
+ } );
818
+ jQuery( "#billing_locations_check" ).select2(select2WODropdownOpts);
819
+
820
+
821
+
822
+ jQuery( "#product_categories" ).select2( {
823
+ ajax: {
824
+ url: ajaxurl,
825
+ dataType: 'json',
826
+ delay: 250,
827
+ data: function( params ) {
828
+ return {
829
+ q: params.term, // search term
830
+ page: params.page,
831
+ method: "get_categories",
832
+ action: "order_exporter"
833
+ };
834
+ },
835
+ processResults: function( data, page ) {
836
+ // parse the results into the format expected by Select2.
837
+ // since we are using custom formatting functions we do not need to
838
+ // alter the remote JSON data
839
+ return {
840
+ results: data
841
+ };
842
+ },
843
+ cache: true
844
+ },
845
+ escapeMarkup: function( markup ) {
846
+ return markup;
847
+ }, // let our custom formatter work
848
+ minimumInputLength: 3,
849
+ templateResult: formatItem, // omitted for brevity, see the source of this page
850
+ templateSelection: formatItemSelection // omitted for brevity, see the source of this page
851
+ } );
852
+
853
+ jQuery( "#product_vendors" ).select2( {
854
+ ajax: {
855
+ url: ajaxurl,
856
+ dataType: 'json',
857
+ delay: 250,
858
+ data: function( params ) {
859
+ return {
860
+ q: params.term, // search term
861
+ page: params.page,
862
+ method: "get_vendors",
863
+ action: "order_exporter"
864
+ };
865
+ },
866
+ processResults: function( data, page ) {
867
+ // parse the results into the format expected by Select2.
868
+ // since we are using custom formatting functions we do not need to
869
+ // alter the remote JSON data
870
+ return {
871
+ results: data
872
+ };
873
+ },
874
+ cache: true
875
+ },
876
+ escapeMarkup: function( markup ) {
877
+ return markup;
878
+ }, // let our custom formatter work
879
+ minimumInputLength: 3,
880
+ templateResult: formatItem, // omitted for brevity, see the source of this page
881
+ templateSelection: formatItemSelection // omitted for brevity, see the source of this page
882
+ } );
883
+
884
+ jQuery( "#products" ).select2( {
885
+ ajax: {
886
+ url: ajaxurl,
887
+ dataType: 'json',
888
+ delay: 250,
889
+ data: function( params ) {
890
+ return {
891
+ q: params.term, // search term
892
+ page: params.page,
893
+ method: "get_products",
894
+ action: "order_exporter"
895
+ };
896
+ },
897
+ processResults: function( data, page ) {
898
+ // parse the results into the format expected by Select2.
899
+ // since we are using custom formatting functions we do not need to
900
+ // alter the remote JSON data
901
+ return {
902
+ results: data
903
+ };
904
+ },
905
+ cache: true
906
+ },
907
+ escapeMarkup: function( markup ) {
908
+ return markup;
909
+ }, // let our custom formatter work
910
+ minimumInputLength: 3,
911
+ templateResult: formatItem, // omitted for brevity, see the source of this page
912
+ templateSelection: formatItemSelection // omitted for brevity, see the source of this page
913
+ } );
914
+
915
+ jQuery( "#user_names" ).select2( {
916
+ ajax: {
917
+ url: ajaxurl,
918
+ dataType: 'json',
919
+ delay: 250,
920
+ data: function( params ) {
921
+ return {
922
+ q: params.term, // search term
923
+ page: params.page,
924
+ method: "get_users",
925
+ action: "order_exporter"
926
+ };
927
+ },
928
+ processResults: function( data, page ) {
929
+ // parse the results into the format expected by Select2.
930
+ // since we are using custom formatting functions we do not need to
931
+ // alter the remote JSON data
932
+ return {
933
+ results: data
934
+ };
935
+ },
936
+ cache: true
937
+ },
938
+ escapeMarkup: function( markup ) {
939
+ return markup;
940
+ }, // let our custom formatter work
941
+ minimumInputLength: 3,
942
+ templateResult: formatItem, // omitted for brevity, see the source of this page
943
+ templateSelection: formatItemSelection // omitted for brevity, see the source of this page
944
+ } );
945
+
946
+ jQuery( "#coupons" ).select2( {
947
+ ajax: {
948
+ url: ajaxurl,
949
+ dataType: 'json',
950
+ delay: 250,
951
+ data: function( params ) {
952
+ return {
953
+ q: params.term, // search term
954
+ page: params.page,
955
+ method: "get_coupons",
956
+ action: "order_exporter"
957
+ };
958
+ },
959
+ processResults: function( data, page ) {
960
+ // parse the results into the format expected by Select2.
961
+ // since we are using custom formatting functions we do not need to
962
+ // alter the remote JSON data
963
+ return {
964
+ results: data
965
+ };
966
+ },
967
+ cache: true
968
+ },
969
+ escapeMarkup: function( markup ) {
970
+ return markup;
971
+ }, // let our custom formatter work
972
+ minimumInputLength: 3,
973
+ templateResult: formatItem, // omitted for brevity, see the source of this page
974
+ templateSelection: formatItemSelection // omitted for brevity, see the source of this page
975
+ } );
976
+ }
977
+
978
+ function escapeStr(str)
979
+ {
980
+ var entityMap = {
981
+ "&": "&amp;",
982
+ "<": "&lt;",
983
+ ">": "&gt;",
984
+ '"': '&quot;',
985
+ "'": '&#39;',
986
+ "/": '&#x2F;'
987
+ };
988
+
989
+ jQuery.each( entityMap, function( key, value ) {
990
+ str = String(str).replace( value, key );
991
+ });
992
+
993
+ return String(str).replace(/[&<>"'\/]/g, function (s) {
994
+ return entityMap[s];
995
+ });
996
+
997
+ }
998
+
999
+ function jQuerySelectorEscape(expression) {
1000
+ return expression.replace(/[!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~]/g, '\\$&');
1001
+ }
1002
+
1003
+ //for warning
1004
+ function setup_alert_date_filter() {
1005
+ default_date_filter_color = jQuery( "#my-date-filter" ).css('color');
1006
+ try_color_date_filter();
1007
+ jQuery( '#from_date' ).change( function() { try_color_date_filter(); });
1008
+ jQuery( '#to_date' ).change( function() { try_color_date_filter(); });
1009
+ }
1010
+ function try_color_date_filter() {
1011
+ var color = default_date_filter_color;
1012
+ if( jQuery( "#from_date" ).val() || jQuery( "#to_date" ).val() )
1013
+ color = 'red';
1014
+ jQuery( "#my-date-filter" ).css('color', color);
1015
+ }
assets/js/jquery.serializejson.js ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*!
2
+ SerializeJSON jQuery plugin.
3
+ https://github.com/marioizquierdo/jquery.serializeJSON
4
+ version 2.9.0 (Jan, 2018)
5
+
6
+ Copyright (c) 2012-2018 Mario Izquierdo
7
+ Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
8
+ and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
9
+ */
10
+ (function (factory) {
11
+ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module.
12
+ define(['jquery'], factory);
13
+ } else if (typeof exports === 'object') { // Node/CommonJS
14
+ var jQuery = require('jquery');
15
+ module.exports = factory(jQuery);
16
+ } else { // Browser globals (zepto supported)
17
+ factory(window.jQuery || window.Zepto || window.$); // Zepto supported on browsers as well
18
+ }
19
+
20
+ }(function ($) {
21
+ "use strict";
22
+
23
+ // jQuery('form').serializeJSON()
24
+ $.fn.serializeJSON = function (options) {
25
+ var f, $form, opts, formAsArray, serializedObject, name, value, parsedValue, _obj, nameWithNoType, type, keys, skipFalsy;
26
+ f = $.serializeJSON;
27
+ $form = this; // NOTE: the set of matched elements is most likely a form, but it could also be a group of inputs
28
+ opts = f.setupOpts(options); // calculate values for options {parseNumbers, parseBoolens, parseNulls, ...} with defaults
29
+
30
+ // Use native `serializeArray` function to get an array of {name, value} objects.
31
+ formAsArray = $form.serializeArray();
32
+ f.readCheckboxUncheckedValues(formAsArray, opts, $form); // add objects to the array from unchecked checkboxes if needed
33
+
34
+ // Convert the formAsArray into a serializedObject with nested keys
35
+ serializedObject = {};
36
+ $.each(formAsArray, function (i, obj) {
37
+ name = obj.name; // original input name
38
+ value = obj.value; // input value
39
+ _obj = f.extractTypeAndNameWithNoType(name);
40
+ nameWithNoType = _obj.nameWithNoType; // input name with no type (i.e. "foo:string" => "foo")
41
+ type = _obj.type; // type defined from the input name in :type colon notation
42
+ if (!type) type = f.attrFromInputWithName($form, name, 'data-value-type');
43
+ f.validateType(name, type, opts); // make sure that the type is one of the valid types if defined
44
+
45
+ if (type !== 'skip') { // ignore inputs with type 'skip'
46
+ keys = f.splitInputNameIntoKeysArray(nameWithNoType);
47
+ parsedValue = f.parseValue(value, name, type, opts); // convert to string, number, boolean, null or customType
48
+
49
+ skipFalsy = !parsedValue && f.shouldSkipFalsy($form, name, nameWithNoType, type, opts); // ignore falsy inputs if specified
50
+ if (!skipFalsy) {
51
+ f.deepSet(serializedObject, keys, parsedValue, opts);
52
+ }
53
+ }
54
+ });
55
+ return serializedObject;
56
+ };
57
+
58
+ // Use $.serializeJSON as namespace for the auxiliar functions
59
+ // and to define defaults
60
+ $.serializeJSON = {
61
+
62
+ defaultOptions: {
63
+ checkboxUncheckedValue: undefined, // to include that value for unchecked checkboxes (instead of ignoring them)
64
+
65
+ parseNumbers: false, // convert values like "1", "-2.33" to 1, -2.33
66
+ parseBooleans: false, // convert "true", "false" to true, false
67
+ parseNulls: false, // convert "null" to null
68
+ parseAll: false, // all of the above
69
+ parseWithFunction: null, // to use custom parser, a function like: function(val){ return parsed_val; }
70
+
71
+ skipFalsyValuesForTypes: [], // skip serialization of falsy values for listed value types
72
+ skipFalsyValuesForFields: [], // skip serialization of falsy values for listed field names
73
+
74
+ customTypes: {}, // override defaultTypes
75
+ defaultTypes: {
76
+ "string": function(str) { return String(str); },
77
+ "number": function(str) { return Number(str); },
78
+ "boolean": function(str) { var falses = ["false", "null", "undefined", "", "0"]; return falses.indexOf(str) === -1; },
79
+ "null": function(str) { var falses = ["false", "null", "undefined", "", "0"]; return falses.indexOf(str) === -1 ? str : null; },
80
+ "array": function(str) { return JSON.parse(str); },
81
+ "object": function(str) { return JSON.parse(str); },
82
+ "auto": function(str) { return $.serializeJSON.parseValue(str, null, null, {parseNumbers: true, parseBooleans: true, parseNulls: true}); }, // try again with something like "parseAll"
83
+ "skip": null // skip is a special type that makes it easy to ignore elements
84
+ },
85
+
86
+ useIntKeysAsArrayIndex: false // name="foo[2]" value="v" => {foo: [null, null, "v"]}, instead of {foo: ["2": "v"]}
87
+ },
88
+
89
+ // Merge option defaults into the options
90
+ setupOpts: function(options) {
91
+ var opt, validOpts, defaultOptions, optWithDefault, parseAll, f;
92
+ f = $.serializeJSON;
93
+
94
+ if (options == null) { options = {}; } // options ||= {}
95
+ defaultOptions = f.defaultOptions || {}; // defaultOptions
96
+
97
+ // Make sure that the user didn't misspell an option
98
+ validOpts = ['checkboxUncheckedValue', 'parseNumbers', 'parseBooleans', 'parseNulls', 'parseAll', 'parseWithFunction', 'skipFalsyValuesForTypes', 'skipFalsyValuesForFields', 'customTypes', 'defaultTypes', 'useIntKeysAsArrayIndex']; // re-define because the user may override the defaultOptions
99
+ for (opt in options) {
100
+ if (validOpts.indexOf(opt) === -1) {
101
+ throw new Error("serializeJSON ERROR: invalid option '" + opt + "'. Please use one of " + validOpts.join(', '));
102
+ }
103
+ }
104
+
105
+ // Helper to get the default value for this option if none is specified by the user
106
+ optWithDefault = function(key) { return (options[key] !== false) && (options[key] !== '') && (options[key] || defaultOptions[key]); };
107
+
108
+ // Return computed options (opts to be used in the rest of the script)
109
+ parseAll = optWithDefault('parseAll');
110
+ return {
111
+ checkboxUncheckedValue: optWithDefault('checkboxUncheckedValue'),
112
+
113
+ parseNumbers: parseAll || optWithDefault('parseNumbers'),
114
+ parseBooleans: parseAll || optWithDefault('parseBooleans'),
115
+ parseNulls: parseAll || optWithDefault('parseNulls'),
116
+ parseWithFunction: optWithDefault('parseWithFunction'),
117
+
118
+ skipFalsyValuesForTypes: optWithDefault('skipFalsyValuesForTypes'),
119
+ skipFalsyValuesForFields: optWithDefault('skipFalsyValuesForFields'),
120
+ typeFunctions: $.extend({}, optWithDefault('defaultTypes'), optWithDefault('customTypes')),
121
+
122
+ useIntKeysAsArrayIndex: optWithDefault('useIntKeysAsArrayIndex')
123
+ };
124
+ },
125
+
126
+ // Given a string, apply the type or the relevant "parse" options, to return the parsed value
127
+ parseValue: function(valStr, inputName, type, opts) {
128
+ var f, parsedVal;
129
+ f = $.serializeJSON;
130
+ parsedVal = valStr; // if no parsing is needed, the returned value will be the same
131
+
132
+ if (opts.typeFunctions && type && opts.typeFunctions[type]) { // use a type if available
133
+ parsedVal = opts.typeFunctions[type](valStr);
134
+ } else if (opts.parseNumbers && f.isNumeric(valStr)) { // auto: number
135
+ parsedVal = Number(valStr);
136
+ } else if (opts.parseBooleans && (valStr === "true" || valStr === "false")) { // auto: boolean
137
+ parsedVal = (valStr === "true");
138
+ } else if (opts.parseNulls && valStr == "null") { // auto: null
139
+ parsedVal = null;
140
+ } else if (opts.typeFunctions && opts.typeFunctions["string"]) { // make sure to apply :string type if it was re-defined
141
+ parsedVal = opts.typeFunctions["string"](valStr);
142
+ }
143
+
144
+ // Custom parse function: apply after parsing options, unless there's an explicit type.
145
+ if (opts.parseWithFunction && !type) {
146
+ parsedVal = opts.parseWithFunction(parsedVal, inputName);
147
+ }
148
+
149
+ return parsedVal;
150
+ },
151
+
152
+ isObject: function(obj) { return obj === Object(obj); }, // is it an Object?
153
+ isUndefined: function(obj) { return obj === void 0; }, // safe check for undefined values
154
+ isValidArrayIndex: function(val) { return /^[0-9]+$/.test(String(val)); }, // 1,2,3,4 ... are valid array indexes
155
+ isNumeric: function(obj) { return obj - parseFloat(obj) >= 0; }, // taken from jQuery.isNumeric implementation. Not using jQuery.isNumeric to support old jQuery and Zepto versions
156
+
157
+ optionKeys: function(obj) { if (Object.keys) { return Object.keys(obj); } else { var key, keys = []; for(key in obj){ keys.push(key); } return keys;} }, // polyfill Object.keys to get option keys in IE<9
158
+
159
+
160
+ // Fill the formAsArray object with values for the unchecked checkbox inputs,
161
+ // using the same format as the jquery.serializeArray function.
162
+ // The value of the unchecked values is determined from the opts.checkboxUncheckedValue
163
+ // and/or the data-unchecked-value attribute of the inputs.
164
+ readCheckboxUncheckedValues: function (formAsArray, opts, $form) {
165
+ var selector, $uncheckedCheckboxes, $el, uncheckedValue, f, name;
166
+ if (opts == null) { opts = {}; }
167
+ f = $.serializeJSON;
168
+
169
+ selector = 'input[type=checkbox][name]:not(:checked):not([disabled])';
170
+ $uncheckedCheckboxes = $form.find(selector).add($form.filter(selector));
171
+ $uncheckedCheckboxes.each(function (i, el) {
172
+ // Check data attr first, then the option
173
+ $el = $(el);
174
+ uncheckedValue = $el.attr('data-unchecked-value');
175
+ if (uncheckedValue == null) {
176
+ uncheckedValue = opts.checkboxUncheckedValue;
177
+ }
178
+
179
+ // If there's an uncheckedValue, push it into the serialized formAsArray
180
+ if (uncheckedValue != null) {
181
+ if (el.name && el.name.indexOf("[][") !== -1) { // identify a non-supported
182
+ throw new Error("serializeJSON ERROR: checkbox unchecked values are not supported on nested arrays of objects like '"+el.name+"'. See https://github.com/marioizquierdo/jquery.serializeJSON/issues/67");
183
+ }
184
+ formAsArray.push({name: el.name, value: uncheckedValue});
185
+ }
186
+ });
187
+ },
188
+
189
+ // Returns and object with properties {name_without_type, type} from a given name.
190
+ // The type is null if none specified. Example:
191
+ // "foo" => {nameWithNoType: "foo", type: null}
192
+ // "foo:boolean" => {nameWithNoType: "foo", type: "boolean"}
193
+ // "foo[bar]:null" => {nameWithNoType: "foo[bar]", type: "null"}
194
+ extractTypeAndNameWithNoType: function(name) {
195
+ return {nameWithNoType: name, type: null}; // Woocommerce Order Export :don't use types!
196
+ var match;
197
+ if (match = name.match(/(.*):([^:]+)$/)) {
198
+ return {nameWithNoType: match[1], type: match[2]};
199
+ } else {
200
+ return {nameWithNoType: name, type: null};
201
+ }
202
+ },
203
+
204
+
205
+ // Check if this input should be skipped when it has a falsy value,
206
+ // depending on the options to skip values by name or type, and the data-skip-falsy attribute.
207
+ shouldSkipFalsy: function($form, name, nameWithNoType, type, opts) {
208
+ var f = $.serializeJSON;
209
+
210
+ var skipFromDataAttr = f.attrFromInputWithName($form, name, 'data-skip-falsy');
211
+ if (skipFromDataAttr != null) {
212
+ return skipFromDataAttr !== 'false'; // any value is true, except if explicitly using 'false'
213
+ }
214
+
215
+ var optForFields = opts.skipFalsyValuesForFields;
216
+ if (optForFields && (optForFields.indexOf(nameWithNoType) !== -1 || optForFields.indexOf(name) !== -1)) {
217
+ return true;
218
+ }
219
+
220
+ var optForTypes = opts.skipFalsyValuesForTypes;
221
+ if (type == null) type = 'string'; // assume fields with no type are targeted as string
222
+ if (optForTypes && optForTypes.indexOf(type) !== -1) {
223
+ return true
224
+ }
225
+
226
+ return false;
227
+ },
228
+
229
+ // Finds the first input in $form with this name, and get the given attr from it.
230
+ // Returns undefined if no input or no attribute was found.
231
+ attrFromInputWithName: function($form, name, attrName) {
232
+ var escapedName, selector, $input, attrValue;
233
+ escapedName = name.replace(/(:|\.|\[|\]|\s)/g,'\\$1'); // every non-standard character need to be escaped by \\
234
+ escapedName = escapedName.replace(/(['"])/g, "\\$1") // alexvp escape double quotes
235
+ selector = '[name="' + escapedName + '"]';
236
+ $input = $form.find(selector).add($form.filter(selector)); // NOTE: this returns only the first $input element if multiple are matched with the same name (i.e. an "array[]"). So, arrays with different element types specified through the data-value-type attr is not supported.
237
+ return $input.attr(attrName);
238
+ },
239
+
240
+ // Raise an error if the type is not recognized.
241
+ validateType: function(name, type, opts) {
242
+ var validTypes, f;
243
+ f = $.serializeJSON;
244
+ validTypes = f.optionKeys(opts ? opts.typeFunctions : f.defaultOptions.defaultTypes);
245
+ if (!type || validTypes.indexOf(type) !== -1) {
246
+ return true;
247
+ } else {
248
+ throw new Error("serializeJSON ERROR: Invalid type " + type + " found in input name '" + name + "', please use one of " + validTypes.join(', '));
249
+ }
250
+ },
251
+
252
+
253
+ // Split the input name in programatically readable keys.
254
+ // Examples:
255
+ // "foo" => ['foo']
256
+ // "[foo]" => ['foo']
257
+ // "foo[inn][bar]" => ['foo', 'inn', 'bar']
258
+ // "foo[inn[bar]]" => ['foo', 'inn', 'bar']
259
+ // "foo[inn][arr][0]" => ['foo', 'inn', 'arr', '0']
260
+ // "arr[][val]" => ['arr', '', 'val']
261
+ splitInputNameIntoKeysArray: function(nameWithNoType) {
262
+ var keys, f;
263
+ f = $.serializeJSON;
264
+ keys = nameWithNoType.split('['); // split string into array
265
+ keys = $.map(keys, function (key) { return key.replace(/\]/g, ''); }); // remove closing brackets
266
+ if (keys[0] === '') { keys.shift(); } // ensure no opening bracket ("[foo][inn]" should be same as "foo[inn]")
267
+ return keys;
268
+ },
269
+
270
+ // Set a value in an object or array, using multiple keys to set in a nested object or array:
271
+ //
272
+ // deepSet(obj, ['foo'], v) // obj['foo'] = v
273
+ // deepSet(obj, ['foo', 'inn'], v) // obj['foo']['inn'] = v // Create the inner obj['foo'] object, if needed
274
+ // deepSet(obj, ['foo', 'inn', '123'], v) // obj['foo']['arr']['123'] = v //
275
+ //
276
+ // deepSet(obj, ['0'], v) // obj['0'] = v
277
+ // deepSet(arr, ['0'], v, {useIntKeysAsArrayIndex: true}) // arr[0] = v
278
+ // deepSet(arr, [''], v) // arr.push(v)
279
+ // deepSet(obj, ['arr', ''], v) // obj['arr'].push(v)
280
+ //
281
+ // arr = [];
282
+ // deepSet(arr, ['', v] // arr => [v]
283
+ // deepSet(arr, ['', 'foo'], v) // arr => [v, {foo: v}]
284
+ // deepSet(arr, ['', 'bar'], v) // arr => [v, {foo: v, bar: v}]
285
+ // deepSet(arr, ['', 'bar'], v) // arr => [v, {foo: v, bar: v}, {bar: v}]
286
+ //
287
+ deepSet: function (o, keys, value, opts) {
288
+ var key, nextKey, tail, lastIdx, lastVal, f;
289
+ if (opts == null) { opts = {}; }
290
+ f = $.serializeJSON;
291
+ if (f.isUndefined(o)) { throw new Error("ArgumentError: param 'o' expected to be an object or array, found undefined"); }
292
+ if (!keys || keys.length === 0) { throw new Error("ArgumentError: param 'keys' expected to be an array with least one element"); }
293
+
294
+ key = keys[0];
295
+
296
+ // Only one key, then it's not a deepSet, just assign the value.
297
+ if (keys.length === 1) {
298
+ if (key === '') {
299
+ o.push(value); // '' is used to push values into the array (assume o is an array)
300
+ } else {
301
+ o[key] = value; // other keys can be used as object keys or array indexes
302
+ }
303
+
304
+ // With more keys is a deepSet. Apply recursively.
305
+ } else {
306
+ nextKey = keys[1];
307
+
308
+ // '' is used to push values into the array,
309
+ // with nextKey, set the value into the same object, in object[nextKey].
310
+ // Covers the case of ['', 'foo'] and ['', 'var'] to push the object {foo, var}, and the case of nested arrays.
311
+ if (key === '') {
312
+ lastIdx = o.length - 1; // asume o is array
313
+ lastVal = o[lastIdx];
314
+ if (f.isObject(lastVal) && (f.isUndefined(lastVal[nextKey]) || keys.length > 2)) { // if nextKey is not present in the last object element, or there are more keys to deep set
315
+ key = lastIdx; // then set the new value in the same object element
316
+ } else {
317
+ key = lastIdx + 1; // otherwise, point to set the next index in the array
318
+ }
319
+ }
320
+
321
+ // '' is used to push values into the array "array[]"
322
+ if (nextKey === '') {
323
+ if (f.isUndefined(o[key]) || !$.isArray(o[key])) {
324
+ o[key] = []; // define (or override) as array to push values
325
+ }
326
+ } else {
327
+ if (opts.useIntKeysAsArrayIndex && f.isValidArrayIndex(nextKey)) { // if 1, 2, 3 ... then use an array, where nextKey is the index
328
+ if (f.isUndefined(o[key]) || !$.isArray(o[key])) {
329
+ o[key] = []; // define (or override) as array, to insert values using int keys as array indexes
330
+ }
331
+ } else { // for anything else, use an object, where nextKey is going to be the attribute name
332
+ if (f.isUndefined(o[key]) || !f.isObject(o[key])) {
333
+ o[key] = {}; // define (or override) as object, to set nested properties
334
+ }
335
+ }
336
+ }
337
+
338
+ // Recursively set the inner object
339
+ tail = keys.slice(1);
340
+ f.deepSet(o[key], tail, value, opts);
341
+ }
342
+ }
343
+
344
+ };
345
+
346
+ }));
classes/PHPExcel.php ADDED
@@ -0,0 +1,1153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/');
6
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
7
+ }
8
+
9
+ /**
10
+ * PHPExcel
11
+ *
12
+ * Copyright (c) 2006 - 2015 PHPExcel
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27
+ *
28
+ * @category PHPExcel
29
+ * @package PHPExcel
30
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
31
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
32
+ * @version ##VERSION##, ##DATE##
33
+ */
34
+ class PHPExcel
35
+ {
36
+ /**
37
+ * Unique ID
38
+ *
39
+ * @var string
40
+ */
41
+ private $uniqueID;
42
+
43
+ /**
44
+ * Document properties
45
+ *
46
+ * @var PHPExcel_DocumentProperties
47
+ */
48
+ private $properties;
49
+
50
+ /**
51
+ * Document security
52
+ *
53
+ * @var PHPExcel_DocumentSecurity
54
+ */
55
+ private $security;
56
+
57
+ /**
58
+ * Collection of Worksheet objects
59
+ *
60
+ * @var PHPExcel_Worksheet[]
61
+ */
62
+ private $workSheetCollection = array();
63
+
64
+ /**
65
+ * Calculation Engine
66
+ *
67
+ * @var PHPExcel_Calculation
68
+ */
69
+ private $calculationEngine;
70
+
71
+ /**
72
+ * Active sheet index
73
+ *
74
+ * @var integer
75
+ */
76
+ private $activeSheetIndex = 0;
77
+
78
+ /**
79
+ * Named ranges
80
+ *
81
+ * @var PHPExcel_NamedRange[]
82
+ */
83
+ private $namedRanges = array();
84
+
85
+ /**
86
+ * CellXf supervisor
87
+ *
88
+ * @var PHPExcel_Style
89
+ */
90
+ private $cellXfSupervisor;
91
+
92
+ /**
93
+ * CellXf collection
94
+ *
95
+ * @var PHPExcel_Style[]
96
+ */
97
+ private $cellXfCollection = array();
98
+
99
+ /**
100
+ * CellStyleXf collection
101
+ *
102
+ * @var PHPExcel_Style[]
103
+ */
104
+ private $cellStyleXfCollection = array();
105
+
106
+ /**
107
+ * hasMacros : this workbook have macros ?
108
+ *
109
+ * @var bool
110
+ */
111
+ private $hasMacros = false;
112
+
113
+ /**
114
+ * macrosCode : all macros code (the vbaProject.bin file, this include form, code, etc.), null if no macro
115
+ *
116
+ * @var binary
117
+ */
118
+ private $macrosCode;
119
+ /**
120
+ * macrosCertificate : if macros are signed, contains vbaProjectSignature.bin file, null if not signed
121
+ *
122
+ * @var binary
123
+ */
124
+ private $macrosCertificate;
125
+
126
+ /**
127
+ * ribbonXMLData : null if workbook is'nt Excel 2007 or not contain a customized UI
128
+ *
129
+ * @var null|string
130
+ */
131
+ private $ribbonXMLData;
132
+
133
+ /**
134
+ * ribbonBinObjects : null if workbook is'nt Excel 2007 or not contain embedded objects (picture(s)) for Ribbon Elements
135
+ * ignored if $ribbonXMLData is null
136
+ *
137
+ * @var null|array
138
+ */
139
+ private $ribbonBinObjects;
140
+
141
+ /**
142
+ * The workbook has macros ?
143
+ *
144
+ * @return boolean true if workbook has macros, false if not
145
+ */
146
+ public function hasMacros()
147
+ {
148
+ return $this->hasMacros;
149
+ }
150
+
151
+ /**
152
+ * Define if a workbook has macros
153
+ *
154
+ * @param boolean $hasMacros true|false
155
+ */
156
+ public function setHasMacros($hasMacros = false)
157
+ {
158
+ $this->hasMacros = (bool) $hasMacros;
159
+ }
160
+
161
+ /**
162
+ * Set the macros code
163
+ *
164
+ * @param string $MacrosCode string|null
165
+ */
166
+ public function setMacrosCode($MacrosCode = null)
167
+ {
168
+ $this->macrosCode=$MacrosCode;
169
+ $this->setHasMacros(!is_null($MacrosCode));
170
+ }
171
+
172
+ /**
173
+ * Return the macros code
174
+ *
175
+ * @return string|null
176
+ */
177
+ public function getMacrosCode()
178
+ {
179
+ return $this->macrosCode;
180
+ }
181
+
182
+ /**
183
+ * Set the macros certificate
184
+ *
185
+ * @param string|null $Certificate
186
+ */
187
+ public function setMacrosCertificate($Certificate = null)
188
+ {
189
+ $this->macrosCertificate=$Certificate;
190
+ }
191
+
192
+ /**
193
+ * Is the project signed ?
194
+ *
195
+ * @return boolean true|false
196
+ */
197
+ public function hasMacrosCertificate()
198
+ {
199
+ return !is_null($this->macrosCertificate);
200
+ }
201
+
202
+ /**
203
+ * Return the macros certificate
204
+ *
205
+ * @return string|null
206
+ */
207
+ public function getMacrosCertificate()
208
+ {
209
+ return $this->macrosCertificate;
210
+ }
211
+
212
+ /**
213
+ * Remove all macros, certificate from spreadsheet
214
+ *
215
+ */
216
+ public function discardMacros()
217
+ {
218
+ $this->hasMacros=false;
219
+ $this->macrosCode=null;
220
+ $this->macrosCertificate=null;
221
+ }
222
+
223
+ /**
224
+ * set ribbon XML data
225
+ *
226
+ */
227
+ public function setRibbonXMLData($Target = null, $XMLData = null)
228
+ {
229
+ if (!is_null($Target) && !is_null($XMLData)) {
230
+ $this->ribbonXMLData = array('target' => $Target, 'data' => $XMLData);
231
+ } else {
232
+ $this->ribbonXMLData = null;
233
+ }
234
+ }
235
+
236
+ /**
237
+ * retrieve ribbon XML Data
238
+ *
239
+ * return string|null|array
240
+ */
241
+ public function getRibbonXMLData($What = 'all') //we need some constants here...
242
+ {
243
+ $ReturnData = null;
244
+ $What = strtolower($What);
245
+ switch ($What){
246
+ case 'all':
247
+ $ReturnData = $this->ribbonXMLData;
248
+ break;
249
+ case 'target':
250
+ case 'data':
251
+ if (is_array($this->ribbonXMLData) && array_key_exists($What, $this->ribbonXMLData)) {
252
+ $ReturnData = $this->ribbonXMLData[$What];
253
+ }
254
+ break;
255
+ }
256
+
257
+ return $ReturnData;
258
+ }
259
+
260
+ /**
261
+ * store binaries ribbon objects (pictures)
262
+ *
263
+ */
264
+ public function setRibbonBinObjects($BinObjectsNames = null, $BinObjectsData = null)
265
+ {
266
+ if (!is_null($BinObjectsNames) && !is_null($BinObjectsData)) {
267
+ $this->ribbonBinObjects = array('names' => $BinObjectsNames, 'data' => $BinObjectsData);
268
+ } else {
269
+ $this->ribbonBinObjects = null;
270
+ }
271
+ }
272
+ /**
273
+ * return the extension of a filename. Internal use for a array_map callback (php<5.3 don't like lambda function)
274
+ *
275
+ */
276
+ private function getExtensionOnly($ThePath)
277
+ {
278
+ return pathinfo($ThePath, PATHINFO_EXTENSION);
279
+ }
280
+
281
+ /**
282
+ * retrieve Binaries Ribbon Objects
283
+ *
284
+ */
285
+ public function getRibbonBinObjects($What = 'all')
286
+ {
287
+ $ReturnData = null;
288
+ $What = strtolower($What);
289
+ switch($What) {
290
+ case 'all':
291
+ return $this->ribbonBinObjects;
292
+ break;
293
+ case 'names':
294
+ case 'data':
295
+ if (is_array($this->ribbonBinObjects) && array_key_exists($What, $this->ribbonBinObjects)) {
296
+ $ReturnData=$this->ribbonBinObjects[$What];
297
+ }
298
+ break;
299
+ case 'types':
300
+ if (is_array($this->ribbonBinObjects) &&
301
+ array_key_exists('data', $this->ribbonBinObjects) && is_array($this->ribbonBinObjects['data'])) {
302
+ $tmpTypes=array_keys($this->ribbonBinObjects['data']);
303
+ $ReturnData = array_unique(array_map(array($this, 'getExtensionOnly'), $tmpTypes));
304
+ } else {
305
+ $ReturnData=array(); // the caller want an array... not null if empty
306
+ }
307
+ break;
308
+ }
309
+ return $ReturnData;
310
+ }
311
+
312
+ /**
313
+ * This workbook have a custom UI ?
314
+ *
315
+ * @return boolean true|false
316
+ */
317
+ public function hasRibbon()
318
+ {
319
+ return !is_null($this->ribbonXMLData);
320
+ }
321
+
322
+ /**
323
+ * This workbook have additionnal object for the ribbon ?
324
+ *
325
+ * @return boolean true|false
326
+ */
327
+ public function hasRibbonBinObjects()
328
+ {
329
+ return !is_null($this->ribbonBinObjects);
330
+ }
331
+
332
+ /**
333
+ * Check if a sheet with a specified code name already exists
334
+ *
335
+ * @param string $pSheetCodeName Name of the worksheet to check
336
+ * @return boolean
337
+ */
338
+ public function sheetCodeNameExists($pSheetCodeName)
339
+ {
340
+ return ($this->getSheetByCodeName($pSheetCodeName) !== null);
341
+ }
342
+
343
+ /**
344
+ * Get sheet by code name. Warning : sheet don't have always a code name !
345
+ *
346
+ * @param string $pName Sheet name
347
+ * @return PHPExcel_Worksheet
348
+ */
349
+ public function getSheetByCodeName($pName = '')
350
+ {
351
+ $worksheetCount = count($this->workSheetCollection);
352
+ for ($i = 0; $i < $worksheetCount; ++$i) {
353
+ if ($this->workSheetCollection[$i]->getCodeName() == $pName) {
354
+ return $this->workSheetCollection[$i];
355
+ }
356
+ }
357
+
358
+ return null;
359
+ }
360
+
361
+ /**
362
+ * Create a new PHPExcel with one Worksheet
363
+ */
364
+ public function __construct()
365
+ {
366
+ $this->uniqueID = uniqid();
367
+ $this->calculationEngine = new PHPExcel_Calculation($this);
368
+
369
+ // Initialise worksheet collection and add one worksheet
370
+ $this->workSheetCollection = array();
371
+ $this->workSheetCollection[] = new PHPExcel_Worksheet($this);
372
+ $this->activeSheetIndex = 0;
373
+
374
+ // Create document properties
375
+ $this->properties = new PHPExcel_DocumentProperties();
376
+
377
+ // Create document security
378
+ $this->security = new PHPExcel_DocumentSecurity();
379
+
380
+ // Set named ranges
381
+ $this->namedRanges = array();
382
+
383
+ // Create the cellXf supervisor
384
+ $this->cellXfSupervisor = new PHPExcel_Style(true);
385
+ $this->cellXfSupervisor->bindParent($this);
386
+
387
+ // Create the default style
388
+ $this->addCellXf(new PHPExcel_Style);
389
+ $this->addCellStyleXf(new PHPExcel_Style);
390
+ }
391
+
392
+ /**
393
+ * Code to execute when this worksheet is unset()
394
+ *
395
+ */
396
+ public function __destruct()
397
+ {
398
+ $this->calculationEngine = null;
399
+ $this->disconnectWorksheets();
400
+ }
401
+
402
+ /**
403
+ * Disconnect all worksheets from this PHPExcel workbook object,
404
+ * typically so that the PHPExcel object can be unset
405
+ *
406
+ */
407
+ public function disconnectWorksheets()
408
+ {
409
+ $worksheet = null;
410
+ foreach ($this->workSheetCollection as $k => &$worksheet) {
411
+ $worksheet->disconnectCells();
412
+ $this->workSheetCollection[$k] = null;
413
+ }
414
+ unset($worksheet);
415
+ $this->workSheetCollection = array();
416
+ }
417
+
418
+ /**
419
+ * Return the calculation engine for this worksheet
420
+ *
421
+ * @return PHPExcel_Calculation
422
+ */
423
+ public function getCalculationEngine()
424
+ {
425
+ return $this->calculationEngine;
426
+ } // function getCellCacheController()
427
+
428
+ /**
429
+ * Get properties
430
+ *
431
+ * @return PHPExcel_DocumentProperties
432
+ */
433
+ public function getProperties()
434
+ {
435
+ return $this->properties;
436
+ }
437
+
438
+ /**
439
+ * Set properties
440
+ *
441
+ * @param PHPExcel_DocumentProperties $pValue
442
+ */
443
+ public function setProperties(PHPExcel_DocumentProperties $pValue)
444
+ {
445
+ $this->properties = $pValue;
446
+ }
447
+
448
+ /**
449
+ * Get security
450
+ *
451
+ * @return PHPExcel_DocumentSecurity
452
+ */
453
+ public function getSecurity()
454
+ {
455
+ return $this->security;
456
+ }
457
+
458
+ /**
459
+ * Set security
460
+ *
461
+ * @param PHPExcel_DocumentSecurity $pValue
462
+ */
463
+ public function setSecurity(PHPExcel_DocumentSecurity $pValue)
464
+ {
465
+ $this->security = $pValue;
466
+ }
467
+
468
+ /**
469
+ * Get active sheet
470
+ *
471
+ * @return PHPExcel_Worksheet
472
+ *
473
+ * @throws PHPExcel_Exception
474
+ */
475
+ public function getActiveSheet()
476
+ {
477
+ return $this->getSheet($this->activeSheetIndex);
478
+ }
479
+
480
+ /**
481
+ * Create sheet and add it to this workbook
482
+ *
483
+ * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
484
+ * @return PHPExcel_Worksheet
485
+ * @throws PHPExcel_Exception
486
+ */
487
+ public function createSheet($iSheetIndex = null)
488
+ {
489
+ $newSheet = new PHPExcel_Worksheet($this);
490
+ $this->addSheet($newSheet, $iSheetIndex);
491
+ return $newSheet;
492
+ }
493
+
494
+ /**
495
+ * Check if a sheet with a specified name already exists
496
+ *
497
+ * @param string $pSheetName Name of the worksheet to check
498
+ * @return boolean
499
+ */
500
+ public function sheetNameExists($pSheetName)
501
+ {
502
+ return ($this->getSheetByName($pSheetName) !== null);
503
+ }
504
+
505
+ /**
506
+ * Add sheet
507
+ *
508
+ * @param PHPExcel_Worksheet $pSheet
509
+ * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
510
+ * @return PHPExcel_Worksheet
511
+ * @throws PHPExcel_Exception
512
+ */
513
+ public function addSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null)
514
+ {
515
+ if ($this->sheetNameExists($pSheet->getTitle())) {
516
+ throw new PHPExcel_Exception(
517
+ "Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename this worksheet first."
518
+ );
519
+ }
520
+
521
+ if ($iSheetIndex === null) {
522
+ if ($this->activeSheetIndex < 0) {
523
+ $this->activeSheetIndex = 0;
524
+ }
525
+ $this->workSheetCollection[] = $pSheet;
526
+ } else {
527
+ // Insert the sheet at the requested index
528
+ array_splice(
529
+ $this->workSheetCollection,
530
+ $iSheetIndex,
531
+ 0,
532
+ array($pSheet)
533
+ );
534
+
535
+ // Adjust active sheet index if necessary
536
+ if ($this->activeSheetIndex >= $iSheetIndex) {
537
+ ++$this->activeSheetIndex;
538
+ }
539
+ }
540
+
541
+ if ($pSheet->getParent() === null) {
542
+ $pSheet->rebindParent($this);
543
+ }
544
+
545
+ return $pSheet;
546
+ }
547
+
548
+ /**
549
+ * Remove sheet by index
550
+ *
551
+ * @param int $pIndex Active sheet index
552
+ * @throws PHPExcel_Exception
553
+ */
554
+ public function removeSheetByIndex($pIndex = 0)
555
+ {
556
+
557
+ $numSheets = count($this->workSheetCollection);
558
+ if ($pIndex > $numSheets - 1) {
559
+ throw new PHPExcel_Exception(
560
+ "You tried to remove a sheet by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
561
+ );
562
+ } else {
563
+ array_splice($this->workSheetCollection, $pIndex, 1);
564
+ }
565
+ // Adjust active sheet index if necessary
566
+ if (($this->activeSheetIndex >= $pIndex) &&
567
+ ($pIndex > count($this->workSheetCollection) - 1)) {
568
+ --$this->activeSheetIndex;
569
+ }
570
+
571
+ }
572
+
573
+ /**
574
+ * Get sheet by index
575
+ *
576
+ * @param int $pIndex Sheet index
577
+ * @return PHPExcel_Worksheet
578
+ * @throws PHPExcel_Exception
579
+ */
580
+ public function getSheet($pIndex = 0)
581
+ {
582
+ if (!isset($this->workSheetCollection[$pIndex])) {
583
+ $numSheets = $this->getSheetCount();
584
+ throw new PHPExcel_Exception(
585
+ "Your requested sheet index: {$pIndex} is out of bounds. The actual number of sheets is {$numSheets}."
586
+ );
587
+ }
588
+
589
+ return $this->workSheetCollection[$pIndex];
590
+ }
591
+
592
+ /**
593
+ * Get all sheets
594
+ *
595
+ * @return PHPExcel_Worksheet[]
596
+ */
597
+ public function getAllSheets()
598
+ {
599
+ return $this->workSheetCollection;
600
+ }
601
+
602
+ /**
603
+ * Get sheet by name
604
+ *
605
+ * @param string $pName Sheet name
606
+ * @return PHPExcel_Worksheet
607
+ */
608
+ public function getSheetByName($pName = '')
609
+ {
610
+ $worksheetCount = count($this->workSheetCollection);
611
+ for ($i = 0; $i < $worksheetCount; ++$i) {
612
+ if ($this->workSheetCollection[$i]->getTitle() === $pName) {
613
+ return $this->workSheetCollection[$i];
614
+ }
615
+ }
616
+
617
+ return null;
618
+ }
619
+
620
+ /**
621
+ * Get index for sheet
622
+ *
623
+ * @param PHPExcel_Worksheet $pSheet
624
+ * @return int Sheet index
625
+ * @throws PHPExcel_Exception
626
+ */
627
+ public function getIndex(PHPExcel_Worksheet $pSheet)
628
+ {
629
+ foreach ($this->workSheetCollection as $key => $value) {
630
+ if ($value->getHashCode() == $pSheet->getHashCode()) {
631
+ return $key;
632
+ }
633
+ }
634
+
635
+ throw new PHPExcel_Exception("Sheet does not exist.");
636
+ }
637
+
638
+ /**
639
+ * Set index for sheet by sheet name.
640
+ *
641
+ * @param string $sheetName Sheet name to modify index for
642
+ * @param int $newIndex New index for the sheet
643
+ * @return int New sheet index
644
+ * @throws PHPExcel_Exception
645
+ */
646
+ public function setIndexByName($sheetName, $newIndex)
647
+ {
648
+ $oldIndex = $this->getIndex($this->getSheetByName($sheetName));
649
+ $pSheet = array_splice(
650
+ $this->workSheetCollection,
651
+ $oldIndex,
652
+ 1
653
+ );
654
+ array_splice(
655
+ $this->workSheetCollection,
656
+ $newIndex,
657
+ 0,
658
+ $pSheet
659
+ );
660
+ return $newIndex;
661
+ }
662
+
663
+ /**
664
+ * Get sheet count
665
+ *
666
+ * @return int
667
+ */
668
+ public function getSheetCount()
669
+ {
670
+ return count($this->workSheetCollection);
671
+ }
672
+
673
+ /**
674
+ * Get active sheet index
675
+ *
676
+ * @return int Active sheet index
677
+ */
678
+ public function getActiveSheetIndex()
679
+ {
680
+ return $this->activeSheetIndex;
681
+ }
682
+
683
+ /**
684
+ * Set active sheet index
685
+ *
686
+ * @param int $pIndex Active sheet index
687
+ * @throws PHPExcel_Exception
688
+ * @return PHPExcel_Worksheet
689
+ */
690
+ public function setActiveSheetIndex($pIndex = 0)
691
+ {
692
+ $numSheets = count($this->workSheetCollection);
693
+
694
+ if ($pIndex > $numSheets - 1) {
695
+ throw new PHPExcel_Exception(
696
+ "You tried to set a sheet active by the out of bounds index: {$pIndex}. The actual number of sheets is {$numSheets}."
697
+ );
698
+ } else {
699
+ $this->activeSheetIndex = $pIndex;
700
+ }
701
+ return $this->getActiveSheet();
702
+ }
703
+
704
+ /**
705
+ * Set active sheet index by name
706
+ *
707
+ * @param string $pValue Sheet title
708
+ * @return PHPExcel_Worksheet
709
+ * @throws PHPExcel_Exception
710
+ */
711
+ public function setActiveSheetIndexByName($pValue = '')
712
+ {
713
+ if (($worksheet = $this->getSheetByName($pValue)) instanceof PHPExcel_Worksheet) {
714
+ $this->setActiveSheetIndex($this->getIndex($worksheet));
715
+ return $worksheet;
716
+ }
717
+
718
+ throw new PHPExcel_Exception('Workbook does not contain sheet:' . $pValue);
719
+ }
720
+
721
+ /**
722
+ * Get sheet names
723
+ *
724
+ * @return string[]
725
+ */
726
+ public function getSheetNames()
727
+ {
728
+ $returnValue = array();
729
+ $worksheetCount = $this->getSheetCount();
730
+ for ($i = 0; $i < $worksheetCount; ++$i) {
731
+ $returnValue[] = $this->getSheet($i)->getTitle();
732
+ }
733
+
734
+ return $returnValue;
735
+ }
736
+
737
+ /**
738
+ * Add external sheet
739
+ *
740
+ * @param PHPExcel_Worksheet $pSheet External sheet to add
741
+ * @param int|null $iSheetIndex Index where sheet should go (0,1,..., or null for last)
742
+ * @throws PHPExcel_Exception
743
+ * @return PHPExcel_Worksheet
744
+ */
745
+ public function addExternalSheet(PHPExcel_Worksheet $pSheet, $iSheetIndex = null)
746
+ {
747
+ if ($this->sheetNameExists($pSheet->getTitle())) {
748
+ throw new PHPExcel_Exception("Workbook already contains a worksheet named '{$pSheet->getTitle()}'. Rename the external sheet first.");
749
+ }
750
+
751
+ // count how many cellXfs there are in this workbook currently, we will need this below
752
+ $countCellXfs = count($this->cellXfCollection);
753
+
754
+ // copy all the shared cellXfs from the external workbook and append them to the current
755
+ foreach ($pSheet->getParent()->getCellXfCollection() as $cellXf) {
756
+ $this->addCellXf(clone $cellXf);
757
+ }
758
+
759
+ // move sheet to this workbook
760
+ $pSheet->rebindParent($this);
761
+
762
+ // update the cellXfs
763
+ foreach ($pSheet->getCellCollection(false) as $cellID) {
764
+ $cell = $pSheet->getCell($cellID);
765
+ $cell->setXfIndex($cell->getXfIndex() + $countCellXfs);
766
+ }
767
+
768
+ return $this->addSheet($pSheet, $iSheetIndex);
769
+ }
770
+
771
+ /**
772
+ * Get named ranges
773
+ *
774
+ * @return PHPExcel_NamedRange[]
775
+ */
776
+ public function getNamedRanges()
777
+ {
778
+ return $this->namedRanges;
779
+ }
780
+
781
+ /**
782
+ * Add named range
783
+ *
784
+ * @param PHPExcel_NamedRange $namedRange
785
+ * @return boolean
786
+ */
787
+ public function addNamedRange(PHPExcel_NamedRange $namedRange)
788
+ {
789
+ if ($namedRange->getScope() == null) {
790
+ // global scope
791
+ $this->namedRanges[$namedRange->getName()] = $namedRange;
792
+ } else {
793
+ // local scope
794
+ $this->namedRanges[$namedRange->getScope()->getTitle().'!'.$namedRange->getName()] = $namedRange;
795
+ }
796
+ return true;
797
+ }
798
+
799
+ /**
800
+ * Get named range
801
+ *
802
+ * @param string $namedRange
803
+ * @param PHPExcel_Worksheet|null $pSheet Scope. Use null for global scope
804
+ * @return PHPExcel_NamedRange|null
805
+ */
806
+ public function getNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null)
807
+ {
808
+ $returnValue = null;
809
+
810
+ if ($namedRange != '' && ($namedRange !== null)) {
811
+ // first look for global defined name
812
+ if (isset($this->namedRanges[$namedRange])) {
813
+ $returnValue = $this->namedRanges[$namedRange];
814
+ }
815
+
816
+ // then look for local defined name (has priority over global defined name if both names exist)
817
+ if (($pSheet !== null) && isset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
818
+ $returnValue = $this->namedRanges[$pSheet->getTitle() . '!' . $namedRange];
819
+ }
820
+ }
821
+
822
+ return $returnValue;
823
+ }
824
+
825
+ /**
826
+ * Remove named range
827
+ *
828
+ * @param string $namedRange
829
+ * @param PHPExcel_Worksheet|null $pSheet Scope: use null for global scope.
830
+ * @return PHPExcel
831
+ */
832
+ public function removeNamedRange($namedRange, PHPExcel_Worksheet $pSheet = null)
833
+ {
834
+ if ($pSheet === null) {
835
+ if (isset($this->namedRanges[$namedRange])) {
836
+ unset($this->namedRanges[$namedRange]);
837
+ }
838
+ } else {
839
+ if (isset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange])) {
840
+ unset($this->namedRanges[$pSheet->getTitle() . '!' . $namedRange]);
841
+ }
842
+ }
843
+ return $this;
844
+ }
845
+
846
+ /**
847
+ * Get worksheet iterator
848
+ *
849
+ * @return PHPExcel_WorksheetIterator
850
+ */
851
+ public function getWorksheetIterator()
852
+ {
853
+ return new PHPExcel_WorksheetIterator($this);
854
+ }
855
+
856
+ /**
857
+ * Copy workbook (!= clone!)
858
+ *
859
+ * @return PHPExcel
860
+ */
861
+ public function copy()
862
+ {
863
+ $copied = clone $this;
864
+
865
+ $worksheetCount = count($this->workSheetCollection);
866
+ for ($i = 0; $i < $worksheetCount; ++$i) {
867
+ $this->workSheetCollection[$i] = $this->workSheetCollection[$i]->copy();
868
+ $this->workSheetCollection[$i]->rebindParent($this);
869
+ }
870
+
871
+ return $copied;
872
+ }
873
+
874
+ /**
875
+ * Implement PHP __clone to create a deep clone, not just a shallow copy.
876
+ */
877
+ public function __clone()
878
+ {
879
+ foreach ($this as $key => $val) {
880
+ if (is_object($val) || (is_array($val))) {
881
+ $this->{$key} = unserialize(serialize($val));
882
+ }
883
+ }
884
+ }
885
+
886
+ /**
887
+ * Get the workbook collection of cellXfs
888
+ *
889
+ * @return PHPExcel_Style[]
890
+ */
891
+ public function getCellXfCollection()
892
+ {
893
+ return $this->cellXfCollection;
894
+ }
895
+
896
+ /**
897
+ * Get cellXf by index
898
+ *
899
+ * @param int $pIndex
900
+ * @return PHPExcel_Style
901
+ */
902
+ public function getCellXfByIndex($pIndex = 0)
903
+ {
904
+ return $this->cellXfCollection[$pIndex];
905
+ }
906
+
907
+ /**
908
+ * Get cellXf by hash code
909
+ *
910
+ * @param string $pValue
911
+ * @return PHPExcel_Style|boolean False if no match found
912
+ */
913
+ public function getCellXfByHashCode($pValue = '')
914
+ {
915
+ foreach ($this->cellXfCollection as $cellXf) {
916
+ if ($cellXf->getHashCode() == $pValue) {
917
+ return $cellXf;
918
+ }
919
+ }
920
+ return false;
921
+ }
922
+
923
+ /**
924
+ * Check if style exists in style collection
925
+ *
926
+ * @param PHPExcel_Style $pCellStyle
927
+ * @return boolean
928
+ */
929
+ public function cellXfExists($pCellStyle = null)
930
+ {
931
+ return in_array($pCellStyle, $this->cellXfCollection, true);
932
+ }
933
+
934
+ /**
935
+ * Get default style
936
+ *
937
+ * @return PHPExcel_Style
938
+ * @throws PHPExcel_Exception
939
+ */
940
+ public function getDefaultStyle()
941
+ {
942
+ if (isset($this->cellXfCollection[0])) {
943
+ return $this->cellXfCollection[0];
944
+ }
945
+ throw new PHPExcel_Exception('No default style found for this workbook');
946
+ }
947
+
948
+ /**
949
+ * Add a cellXf to the workbook
950
+ *
951
+ * @param PHPExcel_Style $style
952
+ */
953
+ public function addCellXf(PHPExcel_Style $style)
954
+ {
955
+ $this->cellXfCollection[] = $style;
956
+ $style->setIndex(count($this->cellXfCollection) - 1);
957
+ }
958
+
959
+ /**
960
+ * Remove cellXf by index. It is ensured that all cells get their xf index updated.
961
+ *
962
+ * @param integer $pIndex Index to cellXf
963
+ * @throws PHPExcel_Exception
964
+ */
965
+ public function removeCellXfByIndex($pIndex = 0)
966
+ {
967
+ if ($pIndex > count($this->cellXfCollection) - 1) {
968
+ throw new PHPExcel_Exception("CellXf index is out of bounds.");
969
+ } else {
970
+ // first remove the cellXf
971
+ array_splice($this->cellXfCollection, $pIndex, 1);
972
+
973
+ // then update cellXf indexes for cells
974
+ foreach ($this->workSheetCollection as $worksheet) {
975
+ foreach ($worksheet->getCellCollection(false) as $cellID) {
976
+ $cell = $worksheet->getCell($cellID);
977
+ $xfIndex = $cell->getXfIndex();
978
+ if ($xfIndex > $pIndex) {
979
+ // decrease xf index by 1
980
+ $cell->setXfIndex($xfIndex - 1);
981
+ } elseif ($xfIndex == $pIndex) {
982
+ // set to default xf index 0
983
+ $cell->setXfIndex(0);
984
+ }
985
+ }
986
+ }
987
+ }
988
+ }
989
+
990
+ /**
991
+ * Get the cellXf supervisor
992
+ *
993
+ * @return PHPExcel_Style
994
+ */
995
+ public function getCellXfSupervisor()
996
+ {
997
+ return $this->cellXfSupervisor;
998
+ }
999
+
1000
+ /**
1001
+ * Get the workbook collection of cellStyleXfs
1002
+ *
1003
+ * @return PHPExcel_Style[]
1004
+ */
1005
+ public function getCellStyleXfCollection()
1006
+ {
1007
+ return $this->cellStyleXfCollection;
1008
+ }
1009
+
1010
+ /**
1011
+ * Get cellStyleXf by index
1012
+ *
1013
+ * @param integer $pIndex Index to cellXf
1014
+ * @return PHPExcel_Style
1015
+ */
1016
+ public function getCellStyleXfByIndex($pIndex = 0)
1017
+ {
1018
+ return $this->cellStyleXfCollection[$pIndex];
1019
+ }
1020
+
1021
+ /**
1022
+ * Get cellStyleXf by hash code
1023
+ *
1024
+ * @param string $pValue
1025
+ * @return PHPExcel_Style|boolean False if no match found
1026
+ */
1027
+ public function getCellStyleXfByHashCode($pValue = '')
1028
+ {
1029
+ foreach ($this->cellStyleXfCollection as $cellStyleXf) {
1030
+ if ($cellStyleXf->getHashCode() == $pValue) {
1031
+ return $cellStyleXf;
1032
+ }
1033
+ }
1034
+ return false;
1035
+ }
1036
+
1037
+ /**
1038
+ * Add a cellStyleXf to the workbook
1039
+ *
1040
+ * @param PHPExcel_Style $pStyle
1041
+ */
1042
+ public function addCellStyleXf(PHPExcel_Style $pStyle)
1043
+ {
1044
+ $this->cellStyleXfCollection[] = $pStyle;
1045
+ $pStyle->setIndex(count($this->cellStyleXfCollection) - 1);
1046
+ }
1047
+
1048
+ /**
1049
+ * Remove cellStyleXf by index
1050
+ *
1051
+ * @param integer $pIndex Index to cellXf
1052
+ * @throws PHPExcel_Exception
1053
+ */
1054
+ public function removeCellStyleXfByIndex($pIndex = 0)
1055
+ {
1056
+ if ($pIndex > count($this->cellStyleXfCollection) - 1) {
1057
+ throw new PHPExcel_Exception("CellStyleXf index is out of bounds.");
1058
+ } else {
1059
+ array_splice($this->cellStyleXfCollection, $pIndex, 1);
1060
+ }
1061
+ }
1062
+
1063
+ /**
1064
+ * Eliminate all unneeded cellXf and afterwards update the xfIndex for all cells
1065
+ * and columns in the workbook
1066
+ */
1067
+ public function garbageCollect()
1068
+ {
1069
+ // how many references are there to each cellXf ?
1070
+ $countReferencesCellXf = array();
1071
+ foreach ($this->cellXfCollection as $index => $cellXf) {
1072
+ $countReferencesCellXf[$index] = 0;
1073
+ }
1074
+
1075
+ foreach ($this->getWorksheetIterator() as $sheet) {
1076
+ // from cells
1077
+ foreach ($sheet->getCellCollection(false) as $cellID) {
1078
+ $cell = $sheet->getCell($cellID);
1079
+ ++$countReferencesCellXf[$cell->getXfIndex()];
1080
+ }
1081
+
1082
+ // from row dimensions
1083
+ foreach ($sheet->getRowDimensions() as $rowDimension) {
1084
+ if ($rowDimension->getXfIndex() !== null) {
1085
+ ++$countReferencesCellXf[$rowDimension->getXfIndex()];
1086
+ }
1087
+ }
1088
+
1089
+ // from column dimensions
1090
+ foreach ($sheet->getColumnDimensions() as $columnDimension) {
1091
+ ++$countReferencesCellXf[$columnDimension->getXfIndex()];
1092
+ }
1093
+ }
1094
+
1095
+ // remove cellXfs without references and create mapping so we can update xfIndex
1096
+ // for all cells and columns
1097
+ $countNeededCellXfs = 0;
1098
+ $map = array();
1099
+ foreach ($this->cellXfCollection as $index => $cellXf) {
1100
+ if ($countReferencesCellXf[$index] > 0 || $index == 0) { // we must never remove the first cellXf
1101
+ ++$countNeededCellXfs;
1102
+ } else {
1103
+ unset($this->cellXfCollection[$index]);
1104
+ }
1105
+ $map[$index] = $countNeededCellXfs - 1;
1106
+ }
1107
+ $this->cellXfCollection = array_values($this->cellXfCollection);
1108
+
1109
+ // update the index for all cellXfs
1110
+ foreach ($this->cellXfCollection as $i => $cellXf) {
1111
+ $cellXf->setIndex($i);
1112
+ }
1113
+
1114
+ // make sure there is always at least one cellXf (there should be)
1115
+ if (empty($this->cellXfCollection)) {
1116
+ $this->cellXfCollection[] = new PHPExcel_Style();
1117
+ }
1118
+
1119
+ // update the xfIndex for all cells, row dimensions, column dimensions
1120
+ foreach ($this->getWorksheetIterator() as $sheet) {
1121
+ // for all cells
1122
+ foreach ($sheet->getCellCollection(false) as $cellID) {
1123
+ $cell = $sheet->getCell($cellID);
1124
+ $cell->setXfIndex($map[$cell->getXfIndex()]);
1125
+ }
1126
+
1127
+ // for all row dimensions
1128
+ foreach ($sheet->getRowDimensions() as $rowDimension) {
1129
+ if ($rowDimension->getXfIndex() !== null) {
1130
+ $rowDimension->setXfIndex($map[$rowDimension->getXfIndex()]);
1131
+ }
1132
+ }
1133
+
1134
+ // for all column dimensions
1135
+ foreach ($sheet->getColumnDimensions() as $columnDimension) {
1136
+ $columnDimension->setXfIndex($map[$columnDimension->getXfIndex()]);
1137
+ }
1138
+
1139
+ // also do garbage collection for all the sheets
1140
+ $sheet->garbageCollect();
1141
+ }
1142
+ }
1143
+
1144
+ /**
1145
+ * Return the unique ID value assigned to this spreadsheet workbook
1146
+ *
1147
+ * @return string
1148
+ */
1149
+ public function getID()
1150
+ {
1151
+ return $this->uniqueID;
1152
+ }
1153
+ }
classes/PHPExcel/Autoloader.php ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ PHPExcel_Autoloader::register();
4
+ // As we always try to run the autoloader before anything else, we can use it to do a few
5
+ // simple checks and initialisations
6
+ //PHPExcel_Shared_ZipStreamWrapper::register();
7
+ // check mbstring.func_overload
8
+ if (ini_get('mbstring.func_overload') & 2) {
9
+ throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).');
10
+ }
11
+ PHPExcel_Shared_String::buildCharacterSets();
12
+
13
+ /**
14
+ * PHPExcel
15
+ *
16
+ * Copyright (c) 2006 - 2015 PHPExcel
17
+ *
18
+ * This library is free software; you can redistribute it and/or
19
+ * modify it under the terms of the GNU Lesser General Public
20
+ * License as published by the Free Software Foundation; either
21
+ * version 2.1 of the License, or (at your option) any later version.
22
+ *
23
+ * This library is distributed in the hope that it will be useful,
24
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
25
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
26
+ * Lesser General Public License for more details.
27
+ *
28
+ * You should have received a copy of the GNU Lesser General Public
29
+ * License along with this library; if not, write to the Free Software
30
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
31
+ *
32
+ * @category PHPExcel
33
+ * @package PHPExcel
34
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
35
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
36
+ * @version ##VERSION##, ##DATE##
37
+ */
38
+ class PHPExcel_Autoloader
39
+ {
40
+ /**
41
+ * Register the Autoloader with SPL
42
+ *
43
+ */
44
+ public static function register()
45
+ {
46
+ if (function_exists('__autoload')) {
47
+ // Register any existing autoloader function with SPL, so we don't get any clashes
48
+ spl_autoload_register('__autoload');
49
+ }
50
+ // Register ourselves with SPL
51
+ if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
52
+ return spl_autoload_register(array('PHPExcel_Autoloader', 'load'), true, true);
53
+ } else {
54
+ return spl_autoload_register(array('PHPExcel_Autoloader', 'load'));
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Autoload a class identified by name
60
+ *
61
+ * @param string $pClassName Name of the object to load
62
+ */
63
+ public static function load($pClassName)
64
+ {
65
+ if ((class_exists($pClassName, false)) || (strpos($pClassName, 'PHPExcel') !== 0)) {
66
+ // Either already loaded, or not a PHPExcel class request
67
+ return false;
68
+ }
69
+
70
+ $pClassFilePath = PHPEXCEL_ROOT .
71
+ str_replace('_', DIRECTORY_SEPARATOR, $pClassName) .
72
+ '.php';
73
+
74
+ if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
75
+ // Can't load
76
+ return false;
77
+ }
78
+
79
+ require($pClassFilePath);
80
+ }
81
+ }
classes/PHPExcel/CachedObjectStorage/APC.php ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_APC
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_APC extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Prefix used to uniquely identify cache data for this worksheet
32
+ *
33
+ * @access private
34
+ * @var string
35
+ */
36
+ private $cachePrefix = null;
37
+
38
+ /**
39
+ * Cache timeout
40
+ *
41
+ * @access private
42
+ * @var integer
43
+ */
44
+ private $cacheTime = 600;
45
+
46
+ /**
47
+ * Store cell data in cache for the current cell object if it's "dirty",
48
+ * and the 'nullify' the current cell object
49
+ *
50
+ * @access private
51
+ * @return void
52
+ * @throws PHPExcel_Exception
53
+ */
54
+ protected function storeData()
55
+ {
56
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
57
+ $this->currentObject->detach();
58
+
59
+ if (!apc_store(
60
+ $this->cachePrefix . $this->currentObjectID . '.cache',
61
+ serialize($this->currentObject),
62
+ $this->cacheTime
63
+ )) {
64
+ $this->__destruct();
65
+ throw new PHPExcel_Exception('Failed to store cell ' . $this->currentObjectID . ' in APC');
66
+ }
67
+ $this->currentCellIsDirty = false;
68
+ }
69
+ $this->currentObjectID = $this->currentObject = null;
70
+ }
71
+
72
+ /**
73
+ * Add or Update a cell in cache identified by coordinate address
74
+ *
75
+ * @access public
76
+ * @param string $pCoord Coordinate address of the cell to update
77
+ * @param PHPExcel_Cell $cell Cell to update
78
+ * @return PHPExcel_Cell
79
+ * @throws PHPExcel_Exception
80
+ */
81
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
82
+ {
83
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
84
+ $this->storeData();
85
+ }
86
+ $this->cellCache[$pCoord] = true;
87
+
88
+ $this->currentObjectID = $pCoord;
89
+ $this->currentObject = $cell;
90
+ $this->currentCellIsDirty = true;
91
+
92
+ return $cell;
93
+ }
94
+
95
+ /**
96
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
97
+ *
98
+ * @access public
99
+ * @param string $pCoord Coordinate address of the cell to check
100
+ * @throws PHPExcel_Exception
101
+ * @return boolean
102
+ */
103
+ public function isDataSet($pCoord)
104
+ {
105
+ // Check if the requested entry is the current object, or exists in the cache
106
+ if (parent::isDataSet($pCoord)) {
107
+ if ($this->currentObjectID == $pCoord) {
108
+ return true;
109
+ }
110
+ // Check if the requested entry still exists in apc
111
+ $success = apc_fetch($this->cachePrefix.$pCoord.'.cache');
112
+ if ($success === false) {
113
+ // Entry no longer exists in APC, so clear it from the cache array
114
+ parent::deleteCacheData($pCoord);
115
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache');
116
+ }
117
+ return true;
118
+ }
119
+ return false;
120
+ }
121
+
122
+ /**
123
+ * Get cell at a specific coordinate
124
+ *
125
+ * @access public
126
+ * @param string $pCoord Coordinate of the cell
127
+ * @throws PHPExcel_Exception
128
+ * @return PHPExcel_Cell Cell that was found, or null if not found
129
+ */
130
+ public function getCacheData($pCoord)
131
+ {
132
+ if ($pCoord === $this->currentObjectID) {
133
+ return $this->currentObject;
134
+ }
135
+ $this->storeData();
136
+
137
+ // Check if the entry that has been requested actually exists
138
+ if (parent::isDataSet($pCoord)) {
139
+ $obj = apc_fetch($this->cachePrefix . $pCoord . '.cache');
140
+ if ($obj === false) {
141
+ // Entry no longer exists in APC, so clear it from the cache array
142
+ parent::deleteCacheData($pCoord);
143
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in APC cache');
144
+ }
145
+ } else {
146
+ // Return null if requested entry doesn't exist in cache
147
+ return null;
148
+ }
149
+
150
+ // Set current entry to the requested entry
151
+ $this->currentObjectID = $pCoord;
152
+ $this->currentObject = unserialize($obj);
153
+ // Re-attach this as the cell's parent
154
+ $this->currentObject->attach($this);
155
+
156
+ // Return requested entry
157
+ return $this->currentObject;
158
+ }
159
+
160
+ /**
161
+ * Get a list of all cell addresses currently held in cache
162
+ *
163
+ * @return string[]
164
+ */
165
+ public function getCellList()
166
+ {
167
+ if ($this->currentObjectID !== null) {
168
+ $this->storeData();
169
+ }
170
+
171
+ return parent::getCellList();
172
+ }
173
+
174
+ /**
175
+ * Delete a cell in cache identified by coordinate address
176
+ *
177
+ * @access public
178
+ * @param string $pCoord Coordinate address of the cell to delete
179
+ * @throws PHPExcel_Exception
180
+ */
181
+ public function deleteCacheData($pCoord)
182
+ {
183
+ // Delete the entry from APC
184
+ apc_delete($this->cachePrefix.$pCoord.'.cache');
185
+
186
+ // Delete the entry from our cell address array
187
+ parent::deleteCacheData($pCoord);
188
+ }
189
+
190
+ /**
191
+ * Clone the cell collection
192
+ *
193
+ * @access public
194
+ * @param PHPExcel_Worksheet $parent The new worksheet
195
+ * @throws PHPExcel_Exception
196
+ * @return void
197
+ */
198
+ public function copyCellCollection(PHPExcel_Worksheet $parent)
199
+ {
200
+ parent::copyCellCollection($parent);
201
+ // Get a new id for the new file name
202
+ $baseUnique = $this->getUniqueID();
203
+ $newCachePrefix = substr(md5($baseUnique), 0, 8) . '.';
204
+ $cacheList = $this->getCellList();
205
+ foreach ($cacheList as $cellID) {
206
+ if ($cellID != $this->currentObjectID) {
207
+ $obj = apc_fetch($this->cachePrefix . $cellID . '.cache');
208
+ if ($obj === false) {
209
+ // Entry no longer exists in APC, so clear it from the cache array
210
+ parent::deleteCacheData($cellID);
211
+ throw new PHPExcel_Exception('Cell entry ' . $cellID . ' no longer exists in APC');
212
+ }
213
+ if (!apc_store($newCachePrefix . $cellID . '.cache', $obj, $this->cacheTime)) {
214
+ $this->__destruct();
215
+ throw new PHPExcel_Exception('Failed to store cell ' . $cellID . ' in APC');
216
+ }
217
+ }
218
+ }
219
+ $this->cachePrefix = $newCachePrefix;
220
+ }
221
+
222
+ /**
223
+ * Clear the cell collection and disconnect from our parent
224
+ *
225
+ * @return void
226
+ */
227
+ public function unsetWorksheetCells()
228
+ {
229
+ if ($this->currentObject !== null) {
230
+ $this->currentObject->detach();
231
+ $this->currentObject = $this->currentObjectID = null;
232
+ }
233
+
234
+ // Flush the APC cache
235
+ $this->__destruct();
236
+
237
+ $this->cellCache = array();
238
+
239
+ // detach ourself from the worksheet, so that it can then delete this object successfully
240
+ $this->parent = null;
241
+ }
242
+
243
+ /**
244
+ * Initialise this new cell collection
245
+ *
246
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
247
+ * @param array of mixed $arguments Additional initialisation arguments
248
+ */
249
+ public function __construct(PHPExcel_Worksheet $parent, $arguments)
250
+ {
251
+ $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
252
+
253
+ if ($this->cachePrefix === null) {
254
+ $baseUnique = $this->getUniqueID();
255
+ $this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.';
256
+ $this->cacheTime = $cacheTime;
257
+
258
+ parent::__construct($parent);
259
+ }
260
+ }
261
+
262
+ /**
263
+ * Destroy this cell collection
264
+ */
265
+ public function __destruct()
266
+ {
267
+ $cacheList = $this->getCellList();
268
+ foreach ($cacheList as $cellID) {
269
+ apc_delete($this->cachePrefix . $cellID . '.cache');
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Identify whether the caching method is currently available
275
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
276
+ *
277
+ * @return boolean
278
+ */
279
+ public static function cacheMethodIsAvailable()
280
+ {
281
+ if (!function_exists('apc_store')) {
282
+ return false;
283
+ }
284
+ if (apc_sma_info() === false) {
285
+ return false;
286
+ }
287
+
288
+ return true;
289
+ }
290
+ }
classes/PHPExcel/CachedObjectStorage/CacheBase.php ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_CacheBase
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ abstract class PHPExcel_CachedObjectStorage_CacheBase
29
+ {
30
+ /**
31
+ * Parent worksheet
32
+ *
33
+ * @var PHPExcel_Worksheet
34
+ */
35
+ protected $parent;
36
+
37
+ /**
38
+ * The currently active Cell
39
+ *
40
+ * @var PHPExcel_Cell
41
+ */
42
+ protected $currentObject = null;
43
+
44
+ /**
45
+ * Coordinate address of the currently active Cell
46
+ *
47
+ * @var string
48
+ */
49
+ protected $currentObjectID = null;
50
+
51
+ /**
52
+ * Flag indicating whether the currently active Cell requires saving
53
+ *
54
+ * @var boolean
55
+ */
56
+ protected $currentCellIsDirty = true;
57
+
58
+ /**
59
+ * An array of cells or cell pointers for the worksheet cells held in this cache,
60
+ * and indexed by their coordinate address within the worksheet
61
+ *
62
+ * @var array of mixed
63
+ */
64
+ protected $cellCache = array();
65
+
66
+ /**
67
+ * Initialise this new cell collection
68
+ *
69
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
70
+ */
71
+ public function __construct(PHPExcel_Worksheet $parent)
72
+ {
73
+ // Set our parent worksheet.
74
+ // This is maintained within the cache controller to facilitate re-attaching it to PHPExcel_Cell objects when
75
+ // they are woken from a serialized state
76
+ $this->parent = $parent;
77
+ }
78
+
79
+ /**
80
+ * Return the parent worksheet for this cell collection
81
+ *
82
+ * @return PHPExcel_Worksheet
83
+ */
84
+ public function getParent()
85
+ {
86
+ return $this->parent;
87
+ }
88
+
89
+ /**
90
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
91
+ *
92
+ * @param string $pCoord Coordinate address of the cell to check
93
+ * @return boolean
94
+ */
95
+ public function isDataSet($pCoord)
96
+ {
97
+ if ($pCoord === $this->currentObjectID) {
98
+ return true;
99
+ }
100
+ // Check if the requested entry exists in the cache
101
+ return isset($this->cellCache[$pCoord]);
102
+ }
103
+
104
+ /**
105
+ * Move a cell object from one address to another
106
+ *
107
+ * @param string $fromAddress Current address of the cell to move
108
+ * @param string $toAddress Destination address of the cell to move
109
+ * @return boolean
110
+ */
111
+ public function moveCell($fromAddress, $toAddress)
112
+ {
113
+ if ($fromAddress === $this->currentObjectID) {
114
+ $this->currentObjectID = $toAddress;
115
+ }
116
+ $this->currentCellIsDirty = true;
117
+ if (isset($this->cellCache[$fromAddress])) {
118
+ $this->cellCache[$toAddress] = &$this->cellCache[$fromAddress];
119
+ unset($this->cellCache[$fromAddress]);
120
+ }
121
+
122
+ return true;
123
+ }
124
+
125
+ /**
126
+ * Add or Update a cell in cache
127
+ *
128
+ * @param PHPExcel_Cell $cell Cell to update
129
+ * @return PHPExcel_Cell
130
+ * @throws PHPExcel_Exception
131
+ */
132
+ public function updateCacheData(PHPExcel_Cell $cell)
133
+ {
134
+ return $this->addCacheData($cell->getCoordinate(), $cell);
135
+ }
136
+
137
+ /**
138
+ * Delete a cell in cache identified by coordinate address
139
+ *
140
+ * @param string $pCoord Coordinate address of the cell to delete
141
+ * @throws PHPExcel_Exception
142
+ */
143
+ public function deleteCacheData($pCoord)
144
+ {
145
+ if ($pCoord === $this->currentObjectID && !is_null($this->currentObject)) {
146
+ $this->currentObject->detach();
147
+ $this->currentObjectID = $this->currentObject = null;
148
+ }
149
+
150
+ if (is_object($this->cellCache[$pCoord])) {
151
+ $this->cellCache[$pCoord]->detach();
152
+ unset($this->cellCache[$pCoord]);
153
+ }
154
+ $this->currentCellIsDirty = false;
155
+ }
156
+
157
+ /**
158
+ * Get a list of all cell addresses currently held in cache
159
+ *
160
+ * @return string[]
161
+ */
162
+ public function getCellList()
163
+ {
164
+ return array_keys($this->cellCache);
165
+ }
166
+
167
+ /**
168
+ * Sort the list of all cell addresses currently held in cache by row and column
169
+ *
170
+ * @return string[]
171
+ */
172
+ public function getSortedCellList()
173
+ {
174
+ $sortKeys = array();
175
+ foreach ($this->getCellList() as $coord) {
176
+ sscanf($coord, '%[A-Z]%d', $column, $row);
177
+ $sortKeys[sprintf('%09d%3s', $row, $column)] = $coord;
178
+ }
179
+ ksort($sortKeys);
180
+
181
+ return array_values($sortKeys);
182
+ }
183
+
184
+ /**
185
+ * Get highest worksheet column and highest row that have cell records
186
+ *
187
+ * @return array Highest column name and highest row number
188
+ */
189
+ public function getHighestRowAndColumn()
190
+ {
191
+ // Lookup highest column and highest row
192
+ $col = array('A' => '1A');
193
+ $row = array(1);
194
+ foreach ($this->getCellList() as $coord) {
195
+ sscanf($coord, '%[A-Z]%d', $c, $r);
196
+ $row[$r] = $r;
197
+ $col[$c] = strlen($c).$c;
198
+ }
199
+ if (!empty($row)) {
200
+ // Determine highest column and row
201
+ $highestRow = max($row);
202
+ $highestColumn = substr(max($col), 1);
203
+ }
204
+
205
+ return array(
206
+ 'row' => $highestRow,
207
+ 'column' => $highestColumn
208
+ );
209
+ }
210
+
211
+ /**
212
+ * Return the cell address of the currently active cell object
213
+ *
214
+ * @return string
215
+ */
216
+ public function getCurrentAddress()
217
+ {
218
+ return $this->currentObjectID;
219
+ }
220
+
221
+ /**
222
+ * Return the column address of the currently active cell object
223
+ *
224
+ * @return string
225
+ */
226
+ public function getCurrentColumn()
227
+ {
228
+ sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row);
229
+ return $column;
230
+ }
231
+
232
+ /**
233
+ * Return the row address of the currently active cell object
234
+ *
235
+ * @return integer
236
+ */
237
+ public function getCurrentRow()
238
+ {
239
+ sscanf($this->currentObjectID, '%[A-Z]%d', $column, $row);
240
+ return (integer) $row;
241
+ }
242
+
243
+ /**
244
+ * Get highest worksheet column
245
+ *
246
+ * @param string $row Return the highest column for the specified row,
247
+ * or the highest column of any row if no row number is passed
248
+ * @return string Highest column name
249
+ */
250
+ public function getHighestColumn($row = null)
251
+ {
252
+ if ($row == null) {
253
+ $colRow = $this->getHighestRowAndColumn();
254
+ return $colRow['column'];
255
+ }
256
+
257
+ $columnList = array(1);
258
+ foreach ($this->getCellList() as $coord) {
259
+ sscanf($coord, '%[A-Z]%d', $c, $r);
260
+ if ($r != $row) {
261
+ continue;
262
+ }
263
+ $columnList[] = PHPExcel_Cell::columnIndexFromString($c);
264
+ }
265
+ return PHPExcel_Cell::stringFromColumnIndex(max($columnList) - 1);
266
+ }
267
+
268
+ /**
269
+ * Get highest worksheet row
270
+ *
271
+ * @param string $column Return the highest row for the specified column,
272
+ * or the highest row of any column if no column letter is passed
273
+ * @return int Highest row number
274
+ */
275
+ public function getHighestRow($column = null)
276
+ {
277
+ if ($column == null) {
278
+ $colRow = $this->getHighestRowAndColumn();
279
+ return $colRow['row'];
280
+ }
281
+
282
+ $rowList = array(0);
283
+ foreach ($this->getCellList() as $coord) {
284
+ sscanf($coord, '%[A-Z]%d', $c, $r);
285
+ if ($c != $column) {
286
+ continue;
287
+ }
288
+ $rowList[] = $r;
289
+ }
290
+
291
+ return max($rowList);
292
+ }
293
+
294
+ /**
295
+ * Generate a unique ID for cache referencing
296
+ *
297
+ * @return string Unique Reference
298
+ */
299
+ protected function getUniqueID()
300
+ {
301
+ if (function_exists('posix_getpid')) {
302
+ $baseUnique = posix_getpid();
303
+ } else {
304
+ $baseUnique = mt_rand();
305
+ }
306
+ return uniqid($baseUnique, true);
307
+ }
308
+
309
+ /**
310
+ * Clone the cell collection
311
+ *
312
+ * @param PHPExcel_Worksheet $parent The new worksheet
313
+ * @return void
314
+ */
315
+ public function copyCellCollection(PHPExcel_Worksheet $parent)
316
+ {
317
+ $this->currentCellIsDirty;
318
+ $this->storeData();
319
+
320
+ $this->parent = $parent;
321
+ if (($this->currentObject !== null) && (is_object($this->currentObject))) {
322
+ $this->currentObject->attach($this);
323
+ }
324
+ } // function copyCellCollection()
325
+
326
+ /**
327
+ * Remove a row, deleting all cells in that row
328
+ *
329
+ * @param string $row Row number to remove
330
+ * @return void
331
+ */
332
+ public function removeRow($row)
333
+ {
334
+ foreach ($this->getCellList() as $coord) {
335
+ sscanf($coord, '%[A-Z]%d', $c, $r);
336
+ if ($r == $row) {
337
+ $this->deleteCacheData($coord);
338
+ }
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Remove a column, deleting all cells in that column
344
+ *
345
+ * @param string $column Column ID to remove
346
+ * @return void
347
+ */
348
+ public function removeColumn($column)
349
+ {
350
+ foreach ($this->getCellList() as $coord) {
351
+ sscanf($coord, '%[A-Z]%d', $c, $r);
352
+ if ($c == $column) {
353
+ $this->deleteCacheData($coord);
354
+ }
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Identify whether the caching method is currently available
360
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
361
+ *
362
+ * @return boolean
363
+ */
364
+ public static function cacheMethodIsAvailable()
365
+ {
366
+ return true;
367
+ }
368
+ }
classes/PHPExcel/CachedObjectStorage/DiscISAM.php ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_DiscISAM
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_DiscISAM extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Name of the file for this cache
32
+ *
33
+ * @var string
34
+ */
35
+ private $fileName = null;
36
+
37
+ /**
38
+ * File handle for this cache file
39
+ *
40
+ * @var resource
41
+ */
42
+ private $fileHandle = null;
43
+
44
+ /**
45
+ * Directory/Folder where the cache file is located
46
+ *
47
+ * @var string
48
+ */
49
+ private $cacheDirectory = null;
50
+
51
+ /**
52
+ * Store cell data in cache for the current cell object if it's "dirty",
53
+ * and the 'nullify' the current cell object
54
+ *
55
+ * @return void
56
+ * @throws PHPExcel_Exception
57
+ */
58
+ protected function storeData()
59
+ {
60
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
61
+ $this->currentObject->detach();
62
+
63
+ fseek($this->fileHandle, 0, SEEK_END);
64
+
65
+ $this->cellCache[$this->currentObjectID] = array(
66
+ 'ptr' => ftell($this->fileHandle),
67
+ 'sz' => fwrite($this->fileHandle, serialize($this->currentObject))
68
+ );
69
+ $this->currentCellIsDirty = false;
70
+ }
71
+ $this->currentObjectID = $this->currentObject = null;
72
+ }
73
+
74
+ /**
75
+ * Add or Update a cell in cache identified by coordinate address
76
+ *
77
+ * @param string $pCoord Coordinate address of the cell to update
78
+ * @param PHPExcel_Cell $cell Cell to update
79
+ * @return PHPExcel_Cell
80
+ * @throws PHPExcel_Exception
81
+ */
82
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
83
+ {
84
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
85
+ $this->storeData();
86
+ }
87
+
88
+ $this->currentObjectID = $pCoord;
89
+ $this->currentObject = $cell;
90
+ $this->currentCellIsDirty = true;
91
+
92
+ return $cell;
93
+ }
94
+
95
+ /**
96
+ * Get cell at a specific coordinate
97
+ *
98
+ * @param string $pCoord Coordinate of the cell
99
+ * @throws PHPExcel_Exception
100
+ * @return PHPExcel_Cell Cell that was found, or null if not found
101
+ */
102
+ public function getCacheData($pCoord)
103
+ {
104
+ if ($pCoord === $this->currentObjectID) {
105
+ return $this->currentObject;
106
+ }
107
+ $this->storeData();
108
+
109
+ // Check if the entry that has been requested actually exists
110
+ if (!isset($this->cellCache[$pCoord])) {
111
+ // Return null if requested entry doesn't exist in cache
112
+ return null;
113
+ }
114
+
115
+ // Set current entry to the requested entry
116
+ $this->currentObjectID = $pCoord;
117
+ fseek($this->fileHandle, $this->cellCache[$pCoord]['ptr']);
118
+ $this->currentObject = unserialize(fread($this->fileHandle, $this->cellCache[$pCoord]['sz']));
119
+ // Re-attach this as the cell's parent
120
+ $this->currentObject->attach($this);
121
+
122
+ // Return requested entry
123
+ return $this->currentObject;
124
+ }
125
+
126
+ /**
127
+ * Get a list of all cell addresses currently held in cache
128
+ *
129
+ * @return string[]
130
+ */
131
+ public function getCellList()
132
+ {
133
+ if ($this->currentObjectID !== null) {
134
+ $this->storeData();
135
+ }
136
+
137
+ return parent::getCellList();
138
+ }
139
+
140
+ /**
141
+ * Clone the cell collection
142
+ *
143
+ * @param PHPExcel_Worksheet $parent The new worksheet
144
+ */
145
+ public function copyCellCollection(PHPExcel_Worksheet $parent)
146
+ {
147
+ parent::copyCellCollection($parent);
148
+ // Get a new id for the new file name
149
+ $baseUnique = $this->getUniqueID();
150
+ $newFileName = $this->cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
151
+ // Copy the existing cell cache file
152
+ copy($this->fileName, $newFileName);
153
+ $this->fileName = $newFileName;
154
+ // Open the copied cell cache file
155
+ $this->fileHandle = fopen($this->fileName, 'a+');
156
+ }
157
+
158
+ /**
159
+ * Clear the cell collection and disconnect from our parent
160
+ *
161
+ */
162
+ public function unsetWorksheetCells()
163
+ {
164
+ if (!is_null($this->currentObject)) {
165
+ $this->currentObject->detach();
166
+ $this->currentObject = $this->currentObjectID = null;
167
+ }
168
+ $this->cellCache = array();
169
+
170
+ // detach ourself from the worksheet, so that it can then delete this object successfully
171
+ $this->parent = null;
172
+
173
+ // Close down the temporary cache file
174
+ $this->__destruct();
175
+ }
176
+
177
+ /**
178
+ * Initialise this new cell collection
179
+ *
180
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
181
+ * @param array of mixed $arguments Additional initialisation arguments
182
+ */
183
+ public function __construct(PHPExcel_Worksheet $parent, $arguments)
184
+ {
185
+ $this->cacheDirectory = ((isset($arguments['dir'])) && ($arguments['dir'] !== null))
186
+ ? $arguments['dir']
187
+ : PHPExcel_Shared_File::sys_get_temp_dir();
188
+
189
+ parent::__construct($parent);
190
+ if (is_null($this->fileHandle)) {
191
+ $baseUnique = $this->getUniqueID();
192
+ $this->fileName = $this->cacheDirectory.'/PHPExcel.'.$baseUnique.'.cache';
193
+ $this->fileHandle = fopen($this->fileName, 'a+');
194
+ }
195
+ }
196
+
197
+ /**
198
+ * Destroy this cell collection
199
+ */
200
+ public function __destruct()
201
+ {
202
+ if (!is_null($this->fileHandle)) {
203
+ fclose($this->fileHandle);
204
+ unlink($this->fileName);
205
+ }
206
+ $this->fileHandle = null;
207
+ }
208
+ }
classes/PHPExcel/CachedObjectStorage/ICache.php ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_ICache
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ interface PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Add or Update a cell in cache identified by coordinate address
32
+ *
33
+ * @param string $pCoord Coordinate address of the cell to update
34
+ * @param PHPExcel_Cell $cell Cell to update
35
+ * @return PHPExcel_Cell
36
+ * @throws PHPExcel_Exception
37
+ */
38
+ public function addCacheData($pCoord, PHPExcel_Cell $cell);
39
+
40
+ /**
41
+ * Add or Update a cell in cache
42
+ *
43
+ * @param PHPExcel_Cell $cell Cell to update
44
+ * @return PHPExcel_Cell
45
+ * @throws PHPExcel_Exception
46
+ */
47
+ public function updateCacheData(PHPExcel_Cell $cell);
48
+
49
+ /**
50
+ * Fetch a cell from cache identified by coordinate address
51
+ *
52
+ * @param string $pCoord Coordinate address of the cell to retrieve
53
+ * @return PHPExcel_Cell Cell that was found, or null if not found
54
+ * @throws PHPExcel_Exception
55
+ */
56
+ public function getCacheData($pCoord);
57
+
58
+ /**
59
+ * Delete a cell in cache identified by coordinate address
60
+ *
61
+ * @param string $pCoord Coordinate address of the cell to delete
62
+ * @throws PHPExcel_Exception
63
+ */
64
+ public function deleteCacheData($pCoord);
65
+
66
+ /**
67
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
68
+ *
69
+ * @param string $pCoord Coordinate address of the cell to check
70
+ * @return boolean
71
+ */
72
+ public function isDataSet($pCoord);
73
+
74
+ /**
75
+ * Get a list of all cell addresses currently held in cache
76
+ *
77
+ * @return string[]
78
+ */
79
+ public function getCellList();
80
+
81
+ /**
82
+ * Get the list of all cell addresses currently held in cache sorted by column and row
83
+ *
84
+ * @return string[]
85
+ */
86
+ public function getSortedCellList();
87
+
88
+ /**
89
+ * Clone the cell collection
90
+ *
91
+ * @param PHPExcel_Worksheet $parent The new worksheet
92
+ * @return void
93
+ */
94
+ public function copyCellCollection(PHPExcel_Worksheet $parent);
95
+
96
+ /**
97
+ * Identify whether the caching method is currently available
98
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
99
+ *
100
+ * @return boolean
101
+ */
102
+ public static function cacheMethodIsAvailable();
103
+ }
classes/PHPExcel/CachedObjectStorage/Igbinary.php ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_Igbinary
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_Igbinary extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Store cell data in cache for the current cell object if it's "dirty",
32
+ * and the 'nullify' the current cell object
33
+ *
34
+ * @return void
35
+ * @throws PHPExcel_Exception
36
+ */
37
+ protected function storeData()
38
+ {
39
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
40
+ $this->currentObject->detach();
41
+
42
+ $this->cellCache[$this->currentObjectID] = igbinary_serialize($this->currentObject);
43
+ $this->currentCellIsDirty = false;
44
+ }
45
+ $this->currentObjectID = $this->currentObject = null;
46
+ } // function _storeData()
47
+
48
+
49
+ /**
50
+ * Add or Update a cell in cache identified by coordinate address
51
+ *
52
+ * @param string $pCoord Coordinate address of the cell to update
53
+ * @param PHPExcel_Cell $cell Cell to update
54
+ * @return PHPExcel_Cell
55
+ * @throws PHPExcel_Exception
56
+ */
57
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
58
+ {
59
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
60
+ $this->storeData();
61
+ }
62
+
63
+ $this->currentObjectID = $pCoord;
64
+ $this->currentObject = $cell;
65
+ $this->currentCellIsDirty = true;
66
+
67
+ return $cell;
68
+ } // function addCacheData()
69
+
70
+
71
+ /**
72
+ * Get cell at a specific coordinate
73
+ *
74
+ * @param string $pCoord Coordinate of the cell
75
+ * @throws PHPExcel_Exception
76
+ * @return PHPExcel_Cell Cell that was found, or null if not found
77
+ */
78
+ public function getCacheData($pCoord)
79
+ {
80
+ if ($pCoord === $this->currentObjectID) {
81
+ return $this->currentObject;
82
+ }
83
+ $this->storeData();
84
+
85
+ // Check if the entry that has been requested actually exists
86
+ if (!isset($this->cellCache[$pCoord])) {
87
+ // Return null if requested entry doesn't exist in cache
88
+ return null;
89
+ }
90
+
91
+ // Set current entry to the requested entry
92
+ $this->currentObjectID = $pCoord;
93
+ $this->currentObject = igbinary_unserialize($this->cellCache[$pCoord]);
94
+ // Re-attach this as the cell's parent
95
+ $this->currentObject->attach($this);
96
+
97
+ // Return requested entry
98
+ return $this->currentObject;
99
+ } // function getCacheData()
100
+
101
+
102
+ /**
103
+ * Get a list of all cell addresses currently held in cache
104
+ *
105
+ * @return string[]
106
+ */
107
+ public function getCellList()
108
+ {
109
+ if ($this->currentObjectID !== null) {
110
+ $this->storeData();
111
+ }
112
+
113
+ return parent::getCellList();
114
+ }
115
+
116
+
117
+ /**
118
+ * Clear the cell collection and disconnect from our parent
119
+ *
120
+ * @return void
121
+ */
122
+ public function unsetWorksheetCells()
123
+ {
124
+ if (!is_null($this->currentObject)) {
125
+ $this->currentObject->detach();
126
+ $this->currentObject = $this->currentObjectID = null;
127
+ }
128
+ $this->cellCache = array();
129
+
130
+ // detach ourself from the worksheet, so that it can then delete this object successfully
131
+ $this->parent = null;
132
+ } // function unsetWorksheetCells()
133
+
134
+
135
+ /**
136
+ * Identify whether the caching method is currently available
137
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
138
+ *
139
+ * @return boolean
140
+ */
141
+ public static function cacheMethodIsAvailable()
142
+ {
143
+ if (!function_exists('igbinary_serialize')) {
144
+ return false;
145
+ }
146
+
147
+ return true;
148
+ }
149
+ }
classes/PHPExcel/CachedObjectStorage/Memcache.php ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_Memcache
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_Memcache extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Prefix used to uniquely identify cache data for this worksheet
32
+ *
33
+ * @var string
34
+ */
35
+ private $cachePrefix = null;
36
+
37
+ /**
38
+ * Cache timeout
39
+ *
40
+ * @var integer
41
+ */
42
+ private $cacheTime = 600;
43
+
44
+ /**
45
+ * Memcache interface
46
+ *
47
+ * @var resource
48
+ */
49
+ private $memcache = null;
50
+
51
+
52
+ /**
53
+ * Store cell data in cache for the current cell object if it's "dirty",
54
+ * and the 'nullify' the current cell object
55
+ *
56
+ * @return void
57
+ * @throws PHPExcel_Exception
58
+ */
59
+ protected function storeData()
60
+ {
61
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
62
+ $this->currentObject->detach();
63
+
64
+ $obj = serialize($this->currentObject);
65
+ if (!$this->memcache->replace($this->cachePrefix . $this->currentObjectID . '.cache', $obj, null, $this->cacheTime)) {
66
+ if (!$this->memcache->add($this->cachePrefix . $this->currentObjectID . '.cache', $obj, null, $this->cacheTime)) {
67
+ $this->__destruct();
68
+ throw new PHPExcel_Exception("Failed to store cell {$this->currentObjectID} in MemCache");
69
+ }
70
+ }
71
+ $this->currentCellIsDirty = false;
72
+ }
73
+ $this->currentObjectID = $this->currentObject = null;
74
+ } // function _storeData()
75
+
76
+
77
+ /**
78
+ * Add or Update a cell in cache identified by coordinate address
79
+ *
80
+ * @param string $pCoord Coordinate address of the cell to update
81
+ * @param PHPExcel_Cell $cell Cell to update
82
+ * @return PHPExcel_Cell
83
+ * @throws PHPExcel_Exception
84
+ */
85
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
86
+ {
87
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
88
+ $this->storeData();
89
+ }
90
+ $this->cellCache[$pCoord] = true;
91
+
92
+ $this->currentObjectID = $pCoord;
93
+ $this->currentObject = $cell;
94
+ $this->currentCellIsDirty = true;
95
+
96
+ return $cell;
97
+ } // function addCacheData()
98
+
99
+
100
+ /**
101
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
102
+ *
103
+ * @param string $pCoord Coordinate address of the cell to check
104
+ * @return boolean
105
+ * @return boolean
106
+ */
107
+ public function isDataSet($pCoord)
108
+ {
109
+ // Check if the requested entry is the current object, or exists in the cache
110
+ if (parent::isDataSet($pCoord)) {
111
+ if ($this->currentObjectID == $pCoord) {
112
+ return true;
113
+ }
114
+ // Check if the requested entry still exists in Memcache
115
+ $success = $this->memcache->get($this->cachePrefix.$pCoord.'.cache');
116
+ if ($success === false) {
117
+ // Entry no longer exists in Memcache, so clear it from the cache array
118
+ parent::deleteCacheData($pCoord);
119
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in MemCache');
120
+ }
121
+ return true;
122
+ }
123
+ return false;
124
+ }
125
+
126
+
127
+ /**
128
+ * Get cell at a specific coordinate
129
+ *
130
+ * @param string $pCoord Coordinate of the cell
131
+ * @throws PHPExcel_Exception
132
+ * @return PHPExcel_Cell Cell that was found, or null if not found
133
+ */
134
+ public function getCacheData($pCoord)
135
+ {
136
+ if ($pCoord === $this->currentObjectID) {
137
+ return $this->currentObject;
138
+ }
139
+ $this->storeData();
140
+
141
+ // Check if the entry that has been requested actually exists
142
+ if (parent::isDataSet($pCoord)) {
143
+ $obj = $this->memcache->get($this->cachePrefix . $pCoord . '.cache');
144
+ if ($obj === false) {
145
+ // Entry no longer exists in Memcache, so clear it from the cache array
146
+ parent::deleteCacheData($pCoord);
147
+ throw new PHPExcel_Exception("Cell entry {$pCoord} no longer exists in MemCache");
148
+ }
149
+ } else {
150
+ // Return null if requested entry doesn't exist in cache
151
+ return null;
152
+ }
153
+
154
+ // Set current entry to the requested entry
155
+ $this->currentObjectID = $pCoord;
156
+ $this->currentObject = unserialize($obj);
157
+ // Re-attach this as the cell's parent
158
+ $this->currentObject->attach($this);
159
+
160
+ // Return requested entry
161
+ return $this->currentObject;
162
+ }
163
+
164
+ /**
165
+ * Get a list of all cell addresses currently held in cache
166
+ *
167
+ * @return string[]
168
+ */
169
+ public function getCellList()
170
+ {
171
+ if ($this->currentObjectID !== null) {
172
+ $this->storeData();
173
+ }
174
+
175
+ return parent::getCellList();
176
+ }
177
+
178
+ /**
179
+ * Delete a cell in cache identified by coordinate address
180
+ *
181
+ * @param string $pCoord Coordinate address of the cell to delete
182
+ * @throws PHPExcel_Exception
183
+ */
184
+ public function deleteCacheData($pCoord)
185
+ {
186
+ // Delete the entry from Memcache
187
+ $this->memcache->delete($this->cachePrefix . $pCoord . '.cache');
188
+
189
+ // Delete the entry from our cell address array
190
+ parent::deleteCacheData($pCoord);
191
+ }
192
+
193
+ /**
194
+ * Clone the cell collection
195
+ *
196
+ * @param PHPExcel_Worksheet $parent The new worksheet
197
+ * @return void
198
+ */
199
+ public function copyCellCollection(PHPExcel_Worksheet $parent)
200
+ {
201
+ parent::copyCellCollection($parent);
202
+ // Get a new id for the new file name
203
+ $baseUnique = $this->getUniqueID();
204
+ $newCachePrefix = substr(md5($baseUnique), 0, 8) . '.';
205
+ $cacheList = $this->getCellList();
206
+ foreach ($cacheList as $cellID) {
207
+ if ($cellID != $this->currentObjectID) {
208
+ $obj = $this->memcache->get($this->cachePrefix.$cellID.'.cache');
209
+ if ($obj === false) {
210
+ // Entry no longer exists in Memcache, so clear it from the cache array
211
+ parent::deleteCacheData($cellID);
212
+ throw new PHPExcel_Exception("Cell entry {$cellID} no longer exists in MemCache");
213
+ }
214
+ if (!$this->memcache->add($newCachePrefix . $cellID . '.cache', $obj, null, $this->cacheTime)) {
215
+ $this->__destruct();
216
+ throw new PHPExcel_Exception("Failed to store cell {$cellID} in MemCache");
217
+ }
218
+ }
219
+ }
220
+ $this->cachePrefix = $newCachePrefix;
221
+ }
222
+
223
+ /**
224
+ * Clear the cell collection and disconnect from our parent
225
+ *
226
+ * @return void
227
+ */
228
+ public function unsetWorksheetCells()
229
+ {
230
+ if (!is_null($this->currentObject)) {
231
+ $this->currentObject->detach();
232
+ $this->currentObject = $this->currentObjectID = null;
233
+ }
234
+
235
+ // Flush the Memcache cache
236
+ $this->__destruct();
237
+
238
+ $this->cellCache = array();
239
+
240
+ // detach ourself from the worksheet, so that it can then delete this object successfully
241
+ $this->parent = null;
242
+ }
243
+
244
+ /**
245
+ * Initialise this new cell collection
246
+ *
247
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
248
+ * @param array of mixed $arguments Additional initialisation arguments
249
+ */
250
+ public function __construct(PHPExcel_Worksheet $parent, $arguments)
251
+ {
252
+ $memcacheServer = (isset($arguments['memcacheServer'])) ? $arguments['memcacheServer'] : 'localhost';
253
+ $memcachePort = (isset($arguments['memcachePort'])) ? $arguments['memcachePort'] : 11211;
254
+ $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
255
+
256
+ if (is_null($this->cachePrefix)) {
257
+ $baseUnique = $this->getUniqueID();
258
+ $this->cachePrefix = substr(md5($baseUnique), 0, 8) . '.';
259
+
260
+ // Set a new Memcache object and connect to the Memcache server
261
+ $this->memcache = new Memcache();
262
+ if (!$this->memcache->addServer($memcacheServer, $memcachePort, false, 50, 5, 5, true, array($this, 'failureCallback'))) {
263
+ throw new PHPExcel_Exception("Could not connect to MemCache server at {$memcacheServer}:{$memcachePort}");
264
+ }
265
+ $this->cacheTime = $cacheTime;
266
+
267
+ parent::__construct($parent);
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Memcache error handler
273
+ *
274
+ * @param string $host Memcache server
275
+ * @param integer $port Memcache port
276
+ * @throws PHPExcel_Exception
277
+ */
278
+ public function failureCallback($host, $port)
279
+ {
280
+ throw new PHPExcel_Exception("memcache {$host}:{$port} failed");
281
+ }
282
+
283
+ /**
284
+ * Destroy this cell collection
285
+ */
286
+ public function __destruct()
287
+ {
288
+ $cacheList = $this->getCellList();
289
+ foreach ($cacheList as $cellID) {
290
+ $this->memcache->delete($this->cachePrefix.$cellID . '.cache');
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Identify whether the caching method is currently available
296
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
297
+ *
298
+ * @return boolean
299
+ */
300
+ public static function cacheMethodIsAvailable()
301
+ {
302
+ if (!function_exists('memcache_add')) {
303
+ return false;
304
+ }
305
+
306
+ return true;
307
+ }
308
+ }
classes/PHPExcel/CachedObjectStorage/Memory.php ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_Memory
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_Memory extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Dummy method callable from CacheBase, but unused by Memory cache
32
+ *
33
+ * @return void
34
+ */
35
+ protected function storeData()
36
+ {
37
+ }
38
+
39
+ /**
40
+ * Add or Update a cell in cache identified by coordinate address
41
+ *
42
+ * @param string $pCoord Coordinate address of the cell to update
43
+ * @param PHPExcel_Cell $cell Cell to update
44
+ * @return PHPExcel_Cell
45
+ * @throws PHPExcel_Exception
46
+ */
47
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
48
+ {
49
+ $this->cellCache[$pCoord] = $cell;
50
+
51
+ // Set current entry to the new/updated entry
52
+ $this->currentObjectID = $pCoord;
53
+
54
+ return $cell;
55
+ }
56
+
57
+
58
+ /**
59
+ * Get cell at a specific coordinate
60
+ *
61
+ * @param string $pCoord Coordinate of the cell
62
+ * @throws PHPExcel_Exception
63
+ * @return PHPExcel_Cell Cell that was found, or null if not found
64
+ */
65
+ public function getCacheData($pCoord)
66
+ {
67
+ // Check if the entry that has been requested actually exists
68
+ if (!isset($this->cellCache[$pCoord])) {
69
+ $this->currentObjectID = null;
70
+ // Return null if requested entry doesn't exist in cache
71
+ return null;
72
+ }
73
+
74
+ // Set current entry to the requested entry
75
+ $this->currentObjectID = $pCoord;
76
+
77
+ // Return requested entry
78
+ return $this->cellCache[$pCoord];
79
+ }
80
+
81
+
82
+ /**
83
+ * Clone the cell collection
84
+ *
85
+ * @param PHPExcel_Worksheet $parent The new worksheet
86
+ */
87
+ public function copyCellCollection(PHPExcel_Worksheet $parent)
88
+ {
89
+ parent::copyCellCollection($parent);
90
+
91
+ $newCollection = array();
92
+ foreach ($this->cellCache as $k => &$cell) {
93
+ $newCollection[$k] = clone $cell;
94
+ $newCollection[$k]->attach($this);
95
+ }
96
+
97
+ $this->cellCache = $newCollection;
98
+ }
99
+
100
+ /**
101
+ * Clear the cell collection and disconnect from our parent
102
+ *
103
+ */
104
+ public function unsetWorksheetCells()
105
+ {
106
+ // Because cells are all stored as intact objects in memory, we need to detach each one from the parent
107
+ foreach ($this->cellCache as $k => &$cell) {
108
+ $cell->detach();
109
+ $this->cellCache[$k] = null;
110
+ }
111
+ unset($cell);
112
+
113
+ $this->cellCache = array();
114
+
115
+ // detach ourself from the worksheet, so that it can then delete this object successfully
116
+ $this->parent = null;
117
+ }
118
+ }
classes/PHPExcel/CachedObjectStorage/MemoryGZip.php ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_MemoryGZip
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_MemoryGZip extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Store cell data in cache for the current cell object if it's "dirty",
32
+ * and the 'nullify' the current cell object
33
+ *
34
+ * @return void
35
+ * @throws PHPExcel_Exception
36
+ */
37
+ protected function storeData()
38
+ {
39
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
40
+ $this->currentObject->detach();
41
+
42
+ $this->cellCache[$this->currentObjectID] = gzdeflate(serialize($this->currentObject));
43
+ $this->currentCellIsDirty = false;
44
+ }
45
+ $this->currentObjectID = $this->currentObject = null;
46
+ }
47
+
48
+
49
+ /**
50
+ * Add or Update a cell in cache identified by coordinate address
51
+ *
52
+ * @param string $pCoord Coordinate address of the cell to update
53
+ * @param PHPExcel_Cell $cell Cell to update
54
+ * @return PHPExcel_Cell
55
+ * @throws PHPExcel_Exception
56
+ */
57
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
58
+ {
59
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
60
+ $this->storeData();
61
+ }
62
+
63
+ $this->currentObjectID = $pCoord;
64
+ $this->currentObject = $cell;
65
+ $this->currentCellIsDirty = true;
66
+
67
+ return $cell;
68
+ }
69
+
70
+
71
+ /**
72
+ * Get cell at a specific coordinate
73
+ *
74
+ * @param string $pCoord Coordinate of the cell
75
+ * @throws PHPExcel_Exception
76
+ * @return PHPExcel_Cell Cell that was found, or null if not found
77
+ */
78
+ public function getCacheData($pCoord)
79
+ {
80
+ if ($pCoord === $this->currentObjectID) {
81
+ return $this->currentObject;
82
+ }
83
+ $this->storeData();
84
+
85
+ // Check if the entry that has been requested actually exists
86
+ if (!isset($this->cellCache[$pCoord])) {
87
+ // Return null if requested entry doesn't exist in cache
88
+ return null;
89
+ }
90
+
91
+ // Set current entry to the requested entry
92
+ $this->currentObjectID = $pCoord;
93
+ $this->currentObject = unserialize(gzinflate($this->cellCache[$pCoord]));
94
+ // Re-attach this as the cell's parent
95
+ $this->currentObject->attach($this);
96
+
97
+ // Return requested entry
98
+ return $this->currentObject;
99
+ }
100
+
101
+
102
+ /**
103
+ * Get a list of all cell addresses currently held in cache
104
+ *
105
+ * @return string[]
106
+ */
107
+ public function getCellList()
108
+ {
109
+ if ($this->currentObjectID !== null) {
110
+ $this->storeData();
111
+ }
112
+
113
+ return parent::getCellList();
114
+ }
115
+
116
+
117
+ /**
118
+ * Clear the cell collection and disconnect from our parent
119
+ *
120
+ * @return void
121
+ */
122
+ public function unsetWorksheetCells()
123
+ {
124
+ if (!is_null($this->currentObject)) {
125
+ $this->currentObject->detach();
126
+ $this->currentObject = $this->currentObjectID = null;
127
+ }
128
+ $this->cellCache = array();
129
+
130
+ // detach ourself from the worksheet, so that it can then delete this object successfully
131
+ $this->parent = null;
132
+ }
133
+ }
classes/PHPExcel/CachedObjectStorage/MemorySerialized.php ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_MemorySerialized
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_MemorySerialized extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Store cell data in cache for the current cell object if it's "dirty",
32
+ * and the 'nullify' the current cell object
33
+ *
34
+ * @return void
35
+ * @throws PHPExcel_Exception
36
+ */
37
+ protected function storeData()
38
+ {
39
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
40
+ $this->currentObject->detach();
41
+
42
+ $this->cellCache[$this->currentObjectID] = serialize($this->currentObject);
43
+ $this->currentCellIsDirty = false;
44
+ }
45
+ $this->currentObjectID = $this->currentObject = null;
46
+ }
47
+
48
+ /**
49
+ * Add or Update a cell in cache identified by coordinate address
50
+ *
51
+ * @param string $pCoord Coordinate address of the cell to update
52
+ * @param PHPExcel_Cell $cell Cell to update
53
+ * @return PHPExcel_Cell
54
+ * @throws PHPExcel_Exception
55
+ */
56
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
57
+ {
58
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
59
+ $this->storeData();
60
+ }
61
+
62
+ $this->currentObjectID = $pCoord;
63
+ $this->currentObject = $cell;
64
+ $this->currentCellIsDirty = true;
65
+
66
+ return $cell;
67
+ }
68
+
69
+ /**
70
+ * Get cell at a specific coordinate
71
+ *
72
+ * @param string $pCoord Coordinate of the cell
73
+ * @throws PHPExcel_Exception
74
+ * @return PHPExcel_Cell Cell that was found, or null if not found
75
+ */
76
+ public function getCacheData($pCoord)
77
+ {
78
+ if ($pCoord === $this->currentObjectID) {
79
+ return $this->currentObject;
80
+ }
81
+ $this->storeData();
82
+
83
+ // Check if the entry that has been requested actually exists
84
+ if (!isset($this->cellCache[$pCoord])) {
85
+ // Return null if requested entry doesn't exist in cache
86
+ return null;
87
+ }
88
+
89
+ // Set current entry to the requested entry
90
+ $this->currentObjectID = $pCoord;
91
+ $this->currentObject = unserialize($this->cellCache[$pCoord]);
92
+ // Re-attach this as the cell's parent
93
+ $this->currentObject->attach($this);
94
+
95
+ // Return requested entry
96
+ return $this->currentObject;
97
+ }
98
+
99
+ /**
100
+ * Get a list of all cell addresses currently held in cache
101
+ *
102
+ * @return string[]
103
+ */
104
+ public function getCellList()
105
+ {
106
+ if ($this->currentObjectID !== null) {
107
+ $this->storeData();
108
+ }
109
+
110
+ return parent::getCellList();
111
+ }
112
+
113
+ /**
114
+ * Clear the cell collection and disconnect from our parent
115
+ *
116
+ * @return void
117
+ */
118
+ public function unsetWorksheetCells()
119
+ {
120
+ if (!is_null($this->currentObject)) {
121
+ $this->currentObject->detach();
122
+ $this->currentObject = $this->currentObjectID = null;
123
+ }
124
+ $this->cellCache = array();
125
+
126
+ // detach ourself from the worksheet, so that it can then delete this object successfully
127
+ $this->parent = null;
128
+ }
129
+ }
classes/PHPExcel/CachedObjectStorage/PHPTemp.php ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_PHPTemp
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_PHPTemp extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Name of the file for this cache
32
+ *
33
+ * @var string
34
+ */
35
+ private $fileHandle = null;
36
+
37
+ /**
38
+ * Memory limit to use before reverting to file cache
39
+ *
40
+ * @var integer
41
+ */
42
+ private $memoryCacheSize = null;
43
+
44
+ /**
45
+ * Store cell data in cache for the current cell object if it's "dirty",
46
+ * and the 'nullify' the current cell object
47
+ *
48
+ * @return void
49
+ * @throws PHPExcel_Exception
50
+ */
51
+ protected function storeData()
52
+ {
53
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
54
+ $this->currentObject->detach();
55
+
56
+ fseek($this->fileHandle, 0, SEEK_END);
57
+
58
+ $this->cellCache[$this->currentObjectID] = array(
59
+ 'ptr' => ftell($this->fileHandle),
60
+ 'sz' => fwrite($this->fileHandle, serialize($this->currentObject))
61
+ );
62
+ $this->currentCellIsDirty = false;
63
+ }
64
+ $this->currentObjectID = $this->currentObject = null;
65
+ }
66
+
67
+
68
+ /**
69
+ * Add or Update a cell in cache identified by coordinate address
70
+ *
71
+ * @param string $pCoord Coordinate address of the cell to update
72
+ * @param PHPExcel_Cell $cell Cell to update
73
+ * @return PHPExcel_Cell
74
+ * @throws PHPExcel_Exception
75
+ */
76
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
77
+ {
78
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
79
+ $this->storeData();
80
+ }
81
+
82
+ $this->currentObjectID = $pCoord;
83
+ $this->currentObject = $cell;
84
+ $this->currentCellIsDirty = true;
85
+
86
+ return $cell;
87
+ }
88
+
89
+
90
+ /**
91
+ * Get cell at a specific coordinate
92
+ *
93
+ * @param string $pCoord Coordinate of the cell
94
+ * @throws PHPExcel_Exception
95
+ * @return PHPExcel_Cell Cell that was found, or null if not found
96
+ */
97
+ public function getCacheData($pCoord)
98
+ {
99
+ if ($pCoord === $this->currentObjectID) {
100
+ return $this->currentObject;
101
+ }
102
+ $this->storeData();
103
+
104
+ // Check if the entry that has been requested actually exists
105
+ if (!isset($this->cellCache[$pCoord])) {
106
+ // Return null if requested entry doesn't exist in cache
107
+ return null;
108
+ }
109
+
110
+ // Set current entry to the requested entry
111
+ $this->currentObjectID = $pCoord;
112
+ fseek($this->fileHandle, $this->cellCache[$pCoord]['ptr']);
113
+ $this->currentObject = unserialize(fread($this->fileHandle, $this->cellCache[$pCoord]['sz']));
114
+ // Re-attach this as the cell's parent
115
+ $this->currentObject->attach($this);
116
+
117
+ // Return requested entry
118
+ return $this->currentObject;
119
+ }
120
+
121
+ /**
122
+ * Get a list of all cell addresses currently held in cache
123
+ *
124
+ * @return string[]
125
+ */
126
+ public function getCellList()
127
+ {
128
+ if ($this->currentObjectID !== null) {
129
+ $this->storeData();
130
+ }
131
+
132
+ return parent::getCellList();
133
+ }
134
+
135
+ /**
136
+ * Clone the cell collection
137
+ *
138
+ * @param PHPExcel_Worksheet $parent The new worksheet
139
+ * @return void
140
+ */
141
+ public function copyCellCollection(PHPExcel_Worksheet $parent)
142
+ {
143
+ parent::copyCellCollection($parent);
144
+ // Open a new stream for the cell cache data
145
+ $newFileHandle = fopen('php://temp/maxmemory:' . $this->memoryCacheSize, 'a+');
146
+ // Copy the existing cell cache data to the new stream
147
+ fseek($this->fileHandle, 0);
148
+ while (!feof($this->fileHandle)) {
149
+ fwrite($newFileHandle, fread($this->fileHandle, 1024));
150
+ }
151
+ $this->fileHandle = $newFileHandle;
152
+ }
153
+
154
+ /**
155
+ * Clear the cell collection and disconnect from our parent
156
+ *
157
+ * @return void
158
+ */
159
+ public function unsetWorksheetCells()
160
+ {
161
+ if (!is_null($this->currentObject)) {
162
+ $this->currentObject->detach();
163
+ $this->currentObject = $this->currentObjectID = null;
164
+ }
165
+ $this->cellCache = array();
166
+
167
+ // detach ourself from the worksheet, so that it can then delete this object successfully
168
+ $this->parent = null;
169
+
170
+ // Close down the php://temp file
171
+ $this->__destruct();
172
+ }
173
+
174
+ /**
175
+ * Initialise this new cell collection
176
+ *
177
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
178
+ * @param array of mixed $arguments Additional initialisation arguments
179
+ */
180
+ public function __construct(PHPExcel_Worksheet $parent, $arguments)
181
+ {
182
+ $this->memoryCacheSize = (isset($arguments['memoryCacheSize'])) ? $arguments['memoryCacheSize'] : '1MB';
183
+
184
+ parent::__construct($parent);
185
+ if (is_null($this->fileHandle)) {
186
+ $this->fileHandle = fopen('php://temp/maxmemory:' . $this->memoryCacheSize, 'a+');
187
+ }
188
+ }
189
+
190
+ /**
191
+ * Destroy this cell collection
192
+ */
193
+ public function __destruct()
194
+ {
195
+ if (!is_null($this->fileHandle)) {
196
+ fclose($this->fileHandle);
197
+ }
198
+ $this->fileHandle = null;
199
+ }
200
+ }
classes/PHPExcel/CachedObjectStorage/SQLite3.php ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_SQLite3
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_SQLite3 extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Database table name
32
+ *
33
+ * @var string
34
+ */
35
+ private $TableName = null;
36
+
37
+ /**
38
+ * Database handle
39
+ *
40
+ * @var resource
41
+ */
42
+ private $DBHandle = null;
43
+
44
+ /**
45
+ * Prepared statement for a SQLite3 select query
46
+ *
47
+ * @var SQLite3Stmt
48
+ */
49
+ private $selectQuery;
50
+
51
+ /**
52
+ * Prepared statement for a SQLite3 insert query
53
+ *
54
+ * @var SQLite3Stmt
55
+ */
56
+ private $insertQuery;
57
+
58
+ /**
59
+ * Prepared statement for a SQLite3 update query
60
+ *
61
+ * @var SQLite3Stmt
62
+ */
63
+ private $updateQuery;
64
+
65
+ /**
66
+ * Prepared statement for a SQLite3 delete query
67
+ *
68
+ * @var SQLite3Stmt
69
+ */
70
+ private $deleteQuery;
71
+
72
+ /**
73
+ * Store cell data in cache for the current cell object if it's "dirty",
74
+ * and the 'nullify' the current cell object
75
+ *
76
+ * @return void
77
+ * @throws PHPExcel_Exception
78
+ */
79
+ protected function storeData()
80
+ {
81
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
82
+ $this->currentObject->detach();
83
+
84
+ $this->insertQuery->bindValue('id', $this->currentObjectID, SQLITE3_TEXT);
85
+ $this->insertQuery->bindValue('data', serialize($this->currentObject), SQLITE3_BLOB);
86
+ $result = $this->insertQuery->execute();
87
+ if ($result === false) {
88
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
89
+ }
90
+ $this->currentCellIsDirty = false;
91
+ }
92
+ $this->currentObjectID = $this->currentObject = null;
93
+ }
94
+
95
+ /**
96
+ * Add or Update a cell in cache identified by coordinate address
97
+ *
98
+ * @param string $pCoord Coordinate address of the cell to update
99
+ * @param PHPExcel_Cell $cell Cell to update
100
+ * @return PHPExcel_Cell
101
+ * @throws PHPExcel_Exception
102
+ */
103
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
104
+ {
105
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
106
+ $this->storeData();
107
+ }
108
+
109
+ $this->currentObjectID = $pCoord;
110
+ $this->currentObject = $cell;
111
+ $this->currentCellIsDirty = true;
112
+
113
+ return $cell;
114
+ }
115
+
116
+ /**
117
+ * Get cell at a specific coordinate
118
+ *
119
+ * @param string $pCoord Coordinate of the cell
120
+ * @throws PHPExcel_Exception
121
+ * @return PHPExcel_Cell Cell that was found, or null if not found
122
+ */
123
+ public function getCacheData($pCoord)
124
+ {
125
+ if ($pCoord === $this->currentObjectID) {
126
+ return $this->currentObject;
127
+ }
128
+ $this->storeData();
129
+
130
+ $this->selectQuery->bindValue('id', $pCoord, SQLITE3_TEXT);
131
+ $cellResult = $this->selectQuery->execute();
132
+ if ($cellResult === false) {
133
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
134
+ }
135
+ $cellData = $cellResult->fetchArray(SQLITE3_ASSOC);
136
+ if ($cellData === false) {
137
+ // Return null if requested entry doesn't exist in cache
138
+ return null;
139
+ }
140
+
141
+ // Set current entry to the requested entry
142
+ $this->currentObjectID = $pCoord;
143
+
144
+ $this->currentObject = unserialize($cellData['value']);
145
+ // Re-attach this as the cell's parent
146
+ $this->currentObject->attach($this);
147
+
148
+ // Return requested entry
149
+ return $this->currentObject;
150
+ }
151
+
152
+ /**
153
+ * Is a value set for an indexed cell?
154
+ *
155
+ * @param string $pCoord Coordinate address of the cell to check
156
+ * @return boolean
157
+ */
158
+ public function isDataSet($pCoord)
159
+ {
160
+ if ($pCoord === $this->currentObjectID) {
161
+ return true;
162
+ }
163
+
164
+ // Check if the requested entry exists in the cache
165
+ $this->selectQuery->bindValue('id', $pCoord, SQLITE3_TEXT);
166
+ $cellResult = $this->selectQuery->execute();
167
+ if ($cellResult === false) {
168
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
169
+ }
170
+ $cellData = $cellResult->fetchArray(SQLITE3_ASSOC);
171
+
172
+ return ($cellData === false) ? false : true;
173
+ }
174
+
175
+ /**
176
+ * Delete a cell in cache identified by coordinate address
177
+ *
178
+ * @param string $pCoord Coordinate address of the cell to delete
179
+ * @throws PHPExcel_Exception
180
+ */
181
+ public function deleteCacheData($pCoord)
182
+ {
183
+ if ($pCoord === $this->currentObjectID) {
184
+ $this->currentObject->detach();
185
+ $this->currentObjectID = $this->currentObject = null;
186
+ }
187
+
188
+ // Check if the requested entry exists in the cache
189
+ $this->deleteQuery->bindValue('id', $pCoord, SQLITE3_TEXT);
190
+ $result = $this->deleteQuery->execute();
191
+ if ($result === false) {
192
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
193
+ }
194
+
195
+ $this->currentCellIsDirty = false;
196
+ }
197
+
198
+ /**
199
+ * Move a cell object from one address to another
200
+ *
201
+ * @param string $fromAddress Current address of the cell to move
202
+ * @param string $toAddress Destination address of the cell to move
203
+ * @return boolean
204
+ */
205
+ public function moveCell($fromAddress, $toAddress)
206
+ {
207
+ if ($fromAddress === $this->currentObjectID) {
208
+ $this->currentObjectID = $toAddress;
209
+ }
210
+
211
+ $this->deleteQuery->bindValue('id', $toAddress, SQLITE3_TEXT);
212
+ $result = $this->deleteQuery->execute();
213
+ if ($result === false) {
214
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
215
+ }
216
+
217
+ $this->updateQuery->bindValue('toid', $toAddress, SQLITE3_TEXT);
218
+ $this->updateQuery->bindValue('fromid', $fromAddress, SQLITE3_TEXT);
219
+ $result = $this->updateQuery->execute();
220
+ if ($result === false) {
221
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
222
+ }
223
+
224
+ return true;
225
+ }
226
+
227
+ /**
228
+ * Get a list of all cell addresses currently held in cache
229
+ *
230
+ * @return string[]
231
+ */
232
+ public function getCellList()
233
+ {
234
+ if ($this->currentObjectID !== null) {
235
+ $this->storeData();
236
+ }
237
+
238
+ $query = "SELECT id FROM kvp_".$this->TableName;
239
+ $cellIdsResult = $this->DBHandle->query($query);
240
+ if ($cellIdsResult === false) {
241
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
242
+ }
243
+
244
+ $cellKeys = array();
245
+ while ($row = $cellIdsResult->fetchArray(SQLITE3_ASSOC)) {
246
+ $cellKeys[] = $row['id'];
247
+ }
248
+
249
+ return $cellKeys;
250
+ }
251
+
252
+ /**
253
+ * Clone the cell collection
254
+ *
255
+ * @param PHPExcel_Worksheet $parent The new worksheet
256
+ * @return void
257
+ */
258
+ public function copyCellCollection(PHPExcel_Worksheet $parent)
259
+ {
260
+ $this->currentCellIsDirty;
261
+ $this->storeData();
262
+
263
+ // Get a new id for the new table name
264
+ $tableName = str_replace('.', '_', $this->getUniqueID());
265
+ if (!$this->DBHandle->exec('CREATE TABLE kvp_'.$tableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)
266
+ AS SELECT * FROM kvp_'.$this->TableName)
267
+ ) {
268
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
269
+ }
270
+
271
+ // Copy the existing cell cache file
272
+ $this->TableName = $tableName;
273
+ }
274
+
275
+ /**
276
+ * Clear the cell collection and disconnect from our parent
277
+ *
278
+ * @return void
279
+ */
280
+ public function unsetWorksheetCells()
281
+ {
282
+ if (!is_null($this->currentObject)) {
283
+ $this->currentObject->detach();
284
+ $this->currentObject = $this->currentObjectID = null;
285
+ }
286
+ // detach ourself from the worksheet, so that it can then delete this object successfully
287
+ $this->parent = null;
288
+
289
+ // Close down the temporary cache file
290
+ $this->__destruct();
291
+ }
292
+
293
+ /**
294
+ * Initialise this new cell collection
295
+ *
296
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
297
+ */
298
+ public function __construct(PHPExcel_Worksheet $parent)
299
+ {
300
+ parent::__construct($parent);
301
+ if (is_null($this->DBHandle)) {
302
+ $this->TableName = str_replace('.', '_', $this->getUniqueID());
303
+ $_DBName = ':memory:';
304
+
305
+ $this->DBHandle = new SQLite3($_DBName);
306
+ if ($this->DBHandle === false) {
307
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
308
+ }
309
+ if (!$this->DBHandle->exec('CREATE TABLE kvp_'.$this->TableName.' (id VARCHAR(12) PRIMARY KEY, value BLOB)')) {
310
+ throw new PHPExcel_Exception($this->DBHandle->lastErrorMsg());
311
+ }
312
+ }
313
+
314
+ $this->selectQuery = $this->DBHandle->prepare("SELECT value FROM kvp_".$this->TableName." WHERE id = :id");
315
+ $this->insertQuery = $this->DBHandle->prepare("INSERT OR REPLACE INTO kvp_".$this->TableName." VALUES(:id,:data)");
316
+ $this->updateQuery = $this->DBHandle->prepare("UPDATE kvp_".$this->TableName." SET id=:toId WHERE id=:fromId");
317
+ $this->deleteQuery = $this->DBHandle->prepare("DELETE FROM kvp_".$this->TableName." WHERE id = :id");
318
+ }
319
+
320
+ /**
321
+ * Destroy this cell collection
322
+ */
323
+ public function __destruct()
324
+ {
325
+ if (!is_null($this->DBHandle)) {
326
+ $this->DBHandle->exec('DROP TABLE kvp_'.$this->TableName);
327
+ $this->DBHandle->close();
328
+ }
329
+ $this->DBHandle = null;
330
+ }
331
+
332
+ /**
333
+ * Identify whether the caching method is currently available
334
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
335
+ *
336
+ * @return boolean
337
+ */
338
+ public static function cacheMethodIsAvailable()
339
+ {
340
+ if (!class_exists('SQLite3', false)) {
341
+ return false;
342
+ }
343
+
344
+ return true;
345
+ }
346
+ }
classes/PHPExcel/CachedObjectStorage/Wincache.php ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorage_Wincache
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorage_Wincache extends PHPExcel_CachedObjectStorage_CacheBase implements PHPExcel_CachedObjectStorage_ICache
29
+ {
30
+ /**
31
+ * Prefix used to uniquely identify cache data for this worksheet
32
+ *
33
+ * @var string
34
+ */
35
+ private $cachePrefix = null;
36
+
37
+ /**
38
+ * Cache timeout
39
+ *
40
+ * @var integer
41
+ */
42
+ private $cacheTime = 600;
43
+
44
+
45
+ /**
46
+ * Store cell data in cache for the current cell object if it's "dirty",
47
+ * and the 'nullify' the current cell object
48
+ *
49
+ * @return void
50
+ * @throws PHPExcel_Exception
51
+ */
52
+ protected function storeData()
53
+ {
54
+ if ($this->currentCellIsDirty && !empty($this->currentObjectID)) {
55
+ $this->currentObject->detach();
56
+
57
+ $obj = serialize($this->currentObject);
58
+ if (wincache_ucache_exists($this->cachePrefix.$this->currentObjectID.'.cache')) {
59
+ if (!wincache_ucache_set($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) {
60
+ $this->__destruct();
61
+ throw new PHPExcel_Exception('Failed to store cell '.$this->currentObjectID.' in WinCache');
62
+ }
63
+ } else {
64
+ if (!wincache_ucache_add($this->cachePrefix.$this->currentObjectID.'.cache', $obj, $this->cacheTime)) {
65
+ $this->__destruct();
66
+ throw new PHPExcel_Exception('Failed to store cell '.$this->currentObjectID.' in WinCache');
67
+ }
68
+ }
69
+ $this->currentCellIsDirty = false;
70
+ }
71
+
72
+ $this->currentObjectID = $this->currentObject = null;
73
+ }
74
+
75
+ /**
76
+ * Add or Update a cell in cache identified by coordinate address
77
+ *
78
+ * @param string $pCoord Coordinate address of the cell to update
79
+ * @param PHPExcel_Cell $cell Cell to update
80
+ * @return PHPExcel_Cell
81
+ * @throws PHPExcel_Exception
82
+ */
83
+ public function addCacheData($pCoord, PHPExcel_Cell $cell)
84
+ {
85
+ if (($pCoord !== $this->currentObjectID) && ($this->currentObjectID !== null)) {
86
+ $this->storeData();
87
+ }
88
+ $this->cellCache[$pCoord] = true;
89
+
90
+ $this->currentObjectID = $pCoord;
91
+ $this->currentObject = $cell;
92
+ $this->currentCellIsDirty = true;
93
+
94
+ return $cell;
95
+ }
96
+
97
+ /**
98
+ * Is a value set in the current PHPExcel_CachedObjectStorage_ICache for an indexed cell?
99
+ *
100
+ * @param string $pCoord Coordinate address of the cell to check
101
+ * @return boolean
102
+ */
103
+ public function isDataSet($pCoord)
104
+ {
105
+ // Check if the requested entry is the current object, or exists in the cache
106
+ if (parent::isDataSet($pCoord)) {
107
+ if ($this->currentObjectID == $pCoord) {
108
+ return true;
109
+ }
110
+ // Check if the requested entry still exists in cache
111
+ $success = wincache_ucache_exists($this->cachePrefix.$pCoord.'.cache');
112
+ if ($success === false) {
113
+ // Entry no longer exists in Wincache, so clear it from the cache array
114
+ parent::deleteCacheData($pCoord);
115
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
116
+ }
117
+ return true;
118
+ }
119
+ return false;
120
+ }
121
+
122
+
123
+ /**
124
+ * Get cell at a specific coordinate
125
+ *
126
+ * @param string $pCoord Coordinate of the cell
127
+ * @throws PHPExcel_Exception
128
+ * @return PHPExcel_Cell Cell that was found, or null if not found
129
+ */
130
+ public function getCacheData($pCoord)
131
+ {
132
+ if ($pCoord === $this->currentObjectID) {
133
+ return $this->currentObject;
134
+ }
135
+ $this->storeData();
136
+
137
+ // Check if the entry that has been requested actually exists
138
+ $obj = null;
139
+ if (parent::isDataSet($pCoord)) {
140
+ $success = false;
141
+ $obj = wincache_ucache_get($this->cachePrefix.$pCoord.'.cache', $success);
142
+ if ($success === false) {
143
+ // Entry no longer exists in WinCache, so clear it from the cache array
144
+ parent::deleteCacheData($pCoord);
145
+ throw new PHPExcel_Exception('Cell entry '.$pCoord.' no longer exists in WinCache');
146
+ }
147
+ } else {
148
+ // Return null if requested entry doesn't exist in cache
149
+ return null;
150
+ }
151
+
152
+ // Set current entry to the requested entry
153
+ $this->currentObjectID = $pCoord;
154
+ $this->currentObject = unserialize($obj);
155
+ // Re-attach this as the cell's parent
156
+ $this->currentObject->attach($this);
157
+
158
+ // Return requested entry
159
+ return $this->currentObject;
160
+ }
161
+
162
+
163
+ /**
164
+ * Get a list of all cell addresses currently held in cache
165
+ *
166
+ * @return string[]
167
+ */
168
+ public function getCellList()
169
+ {
170
+ if ($this->currentObjectID !== null) {
171
+ $this->storeData();
172
+ }
173
+
174
+ return parent::getCellList();
175
+ }
176
+
177
+ /**
178
+ * Delete a cell in cache identified by coordinate address
179
+ *
180
+ * @param string $pCoord Coordinate address of the cell to delete
181
+ * @throws PHPExcel_Exception
182
+ */
183
+ public function deleteCacheData($pCoord)
184
+ {
185
+ // Delete the entry from Wincache
186
+ wincache_ucache_delete($this->cachePrefix.$pCoord.'.cache');
187
+
188
+ // Delete the entry from our cell address array
189
+ parent::deleteCacheData($pCoord);
190
+ }
191
+
192
+ /**
193
+ * Clone the cell collection
194
+ *
195
+ * @param PHPExcel_Worksheet $parent The new worksheet
196
+ * @return void
197
+ */
198
+ public function copyCellCollection(PHPExcel_Worksheet $parent)
199
+ {
200
+ parent::copyCellCollection($parent);
201
+ // Get a new id for the new file name
202
+ $baseUnique = $this->getUniqueID();
203
+ $newCachePrefix = substr(md5($baseUnique), 0, 8) . '.';
204
+ $cacheList = $this->getCellList();
205
+ foreach ($cacheList as $cellID) {
206
+ if ($cellID != $this->currentObjectID) {
207
+ $success = false;
208
+ $obj = wincache_ucache_get($this->cachePrefix.$cellID.'.cache', $success);
209
+ if ($success === false) {
210
+ // Entry no longer exists in WinCache, so clear it from the cache array
211
+ parent::deleteCacheData($cellID);
212
+ throw new PHPExcel_Exception('Cell entry '.$cellID.' no longer exists in Wincache');
213
+ }
214
+ if (!wincache_ucache_add($newCachePrefix.$cellID.'.cache', $obj, $this->cacheTime)) {
215
+ $this->__destruct();
216
+ throw new PHPExcel_Exception('Failed to store cell '.$cellID.' in Wincache');
217
+ }
218
+ }
219
+ }
220
+ $this->cachePrefix = $newCachePrefix;
221
+ }
222
+
223
+
224
+ /**
225
+ * Clear the cell collection and disconnect from our parent
226
+ *
227
+ * @return void
228
+ */
229
+ public function unsetWorksheetCells()
230
+ {
231
+ if (!is_null($this->currentObject)) {
232
+ $this->currentObject->detach();
233
+ $this->currentObject = $this->currentObjectID = null;
234
+ }
235
+
236
+ // Flush the WinCache cache
237
+ $this->__destruct();
238
+
239
+ $this->cellCache = array();
240
+
241
+ // detach ourself from the worksheet, so that it can then delete this object successfully
242
+ $this->parent = null;
243
+ }
244
+
245
+ /**
246
+ * Initialise this new cell collection
247
+ *
248
+ * @param PHPExcel_Worksheet $parent The worksheet for this cell collection
249
+ * @param array of mixed $arguments Additional initialisation arguments
250
+ */
251
+ public function __construct(PHPExcel_Worksheet $parent, $arguments)
252
+ {
253
+ $cacheTime = (isset($arguments['cacheTime'])) ? $arguments['cacheTime'] : 600;
254
+
255
+ if (is_null($this->cachePrefix)) {
256
+ $baseUnique = $this->getUniqueID();
257
+ $this->cachePrefix = substr(md5($baseUnique), 0, 8).'.';
258
+ $this->cacheTime = $cacheTime;
259
+
260
+ parent::__construct($parent);
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Destroy this cell collection
266
+ */
267
+ public function __destruct()
268
+ {
269
+ $cacheList = $this->getCellList();
270
+ foreach ($cacheList as $cellID) {
271
+ wincache_ucache_delete($this->cachePrefix.$cellID.'.cache');
272
+ }
273
+ }
274
+
275
+ /**
276
+ * Identify whether the caching method is currently available
277
+ * Some methods are dependent on the availability of certain extensions being enabled in the PHP build
278
+ *
279
+ * @return boolean
280
+ */
281
+ public static function cacheMethodIsAvailable()
282
+ {
283
+ if (!function_exists('wincache_ucache_add')) {
284
+ return false;
285
+ }
286
+
287
+ return true;
288
+ }
289
+ }
classes/PHPExcel/CachedObjectStorageFactory.php ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CachedObjectStorageFactory
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_CachedObjectStorage
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CachedObjectStorageFactory
29
+ {
30
+ const cache_in_memory = 'Memory';
31
+ const cache_in_memory_gzip = 'MemoryGZip';
32
+ const cache_in_memory_serialized = 'MemorySerialized';
33
+ const cache_igbinary = 'Igbinary';
34
+ const cache_to_discISAM = 'DiscISAM';
35
+ const cache_to_apc = 'APC';
36
+ const cache_to_memcache = 'Memcache';
37
+ const cache_to_phpTemp = 'PHPTemp';
38
+ const cache_to_wincache = 'Wincache';
39
+ const cache_to_sqlite = 'SQLite';
40
+ const cache_to_sqlite3 = 'SQLite3';
41
+
42
+ /**
43
+ * Name of the method used for cell cacheing
44
+ *
45
+ * @var string
46
+ */
47
+ private static $cacheStorageMethod = null;
48
+
49
+ /**
50
+ * Name of the class used for cell cacheing
51
+ *
52
+ * @var string
53
+ */
54
+ private static $cacheStorageClass = null;
55
+
56
+ /**
57
+ * List of all possible cache storage methods
58
+ *
59
+ * @var string[]
60
+ */
61
+ private static $storageMethods = array(
62
+ self::cache_in_memory,
63
+ self::cache_in_memory_gzip,
64
+ self::cache_in_memory_serialized,
65
+ self::cache_igbinary,
66
+ self::cache_to_phpTemp,
67
+ self::cache_to_discISAM,
68
+ self::cache_to_apc,
69
+ self::cache_to_memcache,
70
+ self::cache_to_wincache,
71
+ self::cache_to_sqlite,
72
+ self::cache_to_sqlite3,
73
+ );
74
+
75
+ /**
76
+ * Default arguments for each cache storage method
77
+ *
78
+ * @var array of mixed array
79
+ */
80
+ private static $storageMethodDefaultParameters = array(
81
+ self::cache_in_memory => array(
82
+ ),
83
+ self::cache_in_memory_gzip => array(
84
+ ),
85
+ self::cache_in_memory_serialized => array(
86
+ ),
87
+ self::cache_igbinary => array(
88
+ ),
89
+ self::cache_to_phpTemp => array( 'memoryCacheSize' => '1MB'
90
+ ),
91
+ self::cache_to_discISAM => array( 'dir' => null
92
+ ),
93
+ self::cache_to_apc => array( 'cacheTime' => 600
94
+ ),
95
+ self::cache_to_memcache => array( 'memcacheServer' => 'localhost',
96
+ 'memcachePort' => 11211,
97
+ 'cacheTime' => 600
98
+ ),
99
+ self::cache_to_wincache => array( 'cacheTime' => 600
100
+ ),
101
+ self::cache_to_sqlite => array(
102
+ ),
103
+ self::cache_to_sqlite3 => array(
104
+ ),
105
+ );
106
+
107
+ /**
108
+ * Arguments for the active cache storage method
109
+ *
110
+ * @var array of mixed array
111
+ */
112
+ private static $storageMethodParameters = array();
113
+
114
+ /**
115
+ * Return the current cache storage method
116
+ *
117
+ * @return string|null
118
+ **/
119
+ public static function getCacheStorageMethod()
120
+ {
121
+ return self::$cacheStorageMethod;
122
+ }
123
+
124
+ /**
125
+ * Return the current cache storage class
126
+ *
127
+ * @return PHPExcel_CachedObjectStorage_ICache|null
128
+ **/
129
+ public static function getCacheStorageClass()
130
+ {
131
+ return self::$cacheStorageClass;
132
+ }
133
+
134
+ /**
135
+ * Return the list of all possible cache storage methods
136
+ *
137
+ * @return string[]
138
+ **/
139
+ public static function getAllCacheStorageMethods()
140
+ {
141
+ return self::$storageMethods;
142
+ }
143
+
144
+ /**
145
+ * Return the list of all available cache storage methods
146
+ *
147
+ * @return string[]
148
+ **/
149
+ public static function getCacheStorageMethods()
150
+ {
151
+ $activeMethods = array();
152
+ foreach (self::$storageMethods as $storageMethod) {
153
+ $cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $storageMethod;
154
+ if (call_user_func(array($cacheStorageClass, 'cacheMethodIsAvailable'))) {
155
+ $activeMethods[] = $storageMethod;
156
+ }
157
+ }
158
+ return $activeMethods;
159
+ }
160
+
161
+ /**
162
+ * Identify the cache storage method to use
163
+ *
164
+ * @param string $method Name of the method to use for cell cacheing
165
+ * @param array of mixed $arguments Additional arguments to pass to the cell caching class
166
+ * when instantiating
167
+ * @return boolean
168
+ **/
169
+ public static function initialize($method = self::cache_in_memory, $arguments = array())
170
+ {
171
+ if (!in_array($method, self::$storageMethods)) {
172
+ return false;
173
+ }
174
+
175
+ $cacheStorageClass = 'PHPExcel_CachedObjectStorage_'.$method;
176
+ if (!call_user_func(array( $cacheStorageClass,
177
+ 'cacheMethodIsAvailable'))) {
178
+ return false;
179
+ }
180
+
181
+ self::$storageMethodParameters[$method] = self::$storageMethodDefaultParameters[$method];
182
+ foreach ($arguments as $k => $v) {
183
+ if (array_key_exists($k, self::$storageMethodParameters[$method])) {
184
+ self::$storageMethodParameters[$method][$k] = $v;
185
+ }
186
+ }
187
+
188
+ if (self::$cacheStorageMethod === null) {
189
+ self::$cacheStorageClass = 'PHPExcel_CachedObjectStorage_' . $method;
190
+ self::$cacheStorageMethod = $method;
191
+ }
192
+ return true;
193
+ }
194
+
195
+ /**
196
+ * Initialise the cache storage
197
+ *
198
+ * @param PHPExcel_Worksheet $parent Enable cell caching for this worksheet
199
+ * @return PHPExcel_CachedObjectStorage_ICache
200
+ **/
201
+ public static function getInstance(PHPExcel_Worksheet $parent)
202
+ {
203
+ $cacheMethodIsAvailable = true;
204
+ if (self::$cacheStorageMethod === null) {
205
+ $cacheMethodIsAvailable = self::initialize();
206
+ }
207
+
208
+ if ($cacheMethodIsAvailable) {
209
+ $instance = new self::$cacheStorageClass(
210
+ $parent,
211
+ self::$storageMethodParameters[self::$cacheStorageMethod]
212
+ );
213
+ if ($instance !== null) {
214
+ return $instance;
215
+ }
216
+ }
217
+
218
+ return false;
219
+ }
220
+
221
+ /**
222
+ * Clear the cache storage
223
+ *
224
+ **/
225
+ public static function finalize()
226
+ {
227
+ self::$cacheStorageMethod = null;
228
+ self::$cacheStorageClass = null;
229
+ self::$storageMethodParameters = array();
230
+ }
231
+ }
classes/PHPExcel/CalcEngine/CyclicReferenceStack.php ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CalcEngine_CyclicReferenceStack
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_Calculation
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CalcEngine_CyclicReferenceStack
29
+ {
30
+ /**
31
+ * The call stack for calculated cells
32
+ *
33
+ * @var mixed[]
34
+ */
35
+ private $stack = array();
36
+
37
+ /**
38
+ * Return the number of entries on the stack
39
+ *
40
+ * @return integer
41
+ */
42
+ public function count()
43
+ {
44
+ return count($this->stack);
45
+ }
46
+
47
+ /**
48
+ * Push a new entry onto the stack
49
+ *
50
+ * @param mixed $value
51
+ */
52
+ public function push($value)
53
+ {
54
+ $this->stack[$value] = $value;
55
+ }
56
+
57
+ /**
58
+ * Pop the last entry from the stack
59
+ *
60
+ * @return mixed
61
+ */
62
+ public function pop()
63
+ {
64
+ return array_pop($this->stack);
65
+ }
66
+
67
+ /**
68
+ * Test to see if a specified entry exists on the stack
69
+ *
70
+ * @param mixed $value The value to test
71
+ */
72
+ public function onStack($value)
73
+ {
74
+ return isset($this->stack[$value]);
75
+ }
76
+
77
+ /**
78
+ * Clear the stack
79
+ */
80
+ public function clear()
81
+ {
82
+ $this->stack = array();
83
+ }
84
+
85
+ /**
86
+ * Return an array of all entries on the stack
87
+ *
88
+ * @return mixed[]
89
+ */
90
+ public function showStack()
91
+ {
92
+ return $this->stack;
93
+ }
94
+ }
classes/PHPExcel/CalcEngine/Logger.php ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_CalcEngine_Logger
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_Calculation
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_CalcEngine_Logger
29
+ {
30
+ /**
31
+ * Flag to determine whether a debug log should be generated by the calculation engine
32
+ * If true, then a debug log will be generated
33
+ * If false, then a debug log will not be generated
34
+ *
35
+ * @var boolean
36
+ */
37
+ private $writeDebugLog = false;
38
+
39
+ /**
40
+ * Flag to determine whether a debug log should be echoed by the calculation engine
41
+ * If true, then a debug log will be echoed
42
+ * If false, then a debug log will not be echoed
43
+ * A debug log can only be echoed if it is generated
44
+ *
45
+ * @var boolean
46
+ */
47
+ private $echoDebugLog = false;
48
+
49
+ /**
50
+ * The debug log generated by the calculation engine
51
+ *
52
+ * @var string[]
53
+ */
54
+ private $debugLog = array();
55
+
56
+ /**
57
+ * The calculation engine cell reference stack
58
+ *
59
+ * @var PHPExcel_CalcEngine_CyclicReferenceStack
60
+ */
61
+ private $cellStack;
62
+
63
+ /**
64
+ * Instantiate a Calculation engine logger
65
+ *
66
+ * @param PHPExcel_CalcEngine_CyclicReferenceStack $stack
67
+ */
68
+ public function __construct(PHPExcel_CalcEngine_CyclicReferenceStack $stack)
69
+ {
70
+ $this->cellStack = $stack;
71
+ }
72
+
73
+ /**
74
+ * Enable/Disable Calculation engine logging
75
+ *
76
+ * @param boolean $pValue
77
+ */
78
+ public function setWriteDebugLog($pValue = false)
79
+ {
80
+ $this->writeDebugLog = $pValue;
81
+ }
82
+
83
+ /**
84
+ * Return whether calculation engine logging is enabled or disabled
85
+ *
86
+ * @return boolean
87
+ */
88
+ public function getWriteDebugLog()
89
+ {
90
+ return $this->writeDebugLog;
91
+ }
92
+
93
+ /**
94
+ * Enable/Disable echoing of debug log information
95
+ *
96
+ * @param boolean $pValue
97
+ */
98
+ public function setEchoDebugLog($pValue = false)
99
+ {
100
+ $this->echoDebugLog = $pValue;
101
+ }
102
+
103
+ /**
104
+ * Return whether echoing of debug log information is enabled or disabled
105
+ *
106
+ * @return boolean
107
+ */
108
+ public function getEchoDebugLog()
109
+ {
110
+ return $this->echoDebugLog;
111
+ }
112
+
113
+ /**
114
+ * Write an entry to the calculation engine debug log
115
+ */
116
+ public function writeDebugLog()
117
+ {
118
+ // Only write the debug log if logging is enabled
119
+ if ($this->writeDebugLog) {
120
+ $message = implode(func_get_args());
121
+ $cellReference = implode(' -> ', $this->cellStack->showStack());
122
+ if ($this->echoDebugLog) {
123
+ echo $cellReference,
124
+ ($this->cellStack->count() > 0 ? ' => ' : ''),
125
+ $message,
126
+ PHP_EOL;
127
+ }
128
+ $this->debugLog[] = $cellReference .
129
+ ($this->cellStack->count() > 0 ? ' => ' : '') .
130
+ $message;
131
+ }
132
+ }
133
+
134
+ /**
135
+ * Clear the calculation engine debug log
136
+ */
137
+ public function clearLog()
138
+ {
139
+ $this->debugLog = array();
140
+ }
141
+
142
+ /**
143
+ * Return the calculation engine debug log
144
+ *
145
+ * @return string[]
146
+ */
147
+ public function getLog()
148
+ {
149
+ return $this->debugLog;
150
+ }
151
+ }
classes/PHPExcel/Calculation.php ADDED
@@ -0,0 +1,4391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+ if (!defined('CALCULATION_REGEXP_CELLREF')) {
13
+ // Test for support of \P (multibyte options) in PCRE
14
+ if (defined('PREG_BAD_UTF8_ERROR')) {
15
+ // Cell reference (cell or range of cells, with or without a sheet reference)
16
+ define('CALCULATION_REGEXP_CELLREF', '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d{1,7})');
17
+ // Named Range of cells
18
+ define('CALCULATION_REGEXP_NAMEDRANGE', '((([^\s,!&%^\/\*\+<>=-]*)|(\'[^\']*\')|(\"[^\"]*\"))!)?([_A-Z][_A-Z0-9\.]*)');
19
+ } else {
20
+ // Cell reference (cell or range of cells, with or without a sheet reference)
21
+ define('CALCULATION_REGEXP_CELLREF', '(((\w*)|(\'[^\']*\')|(\"[^\"]*\"))!)?\$?([a-z]{1,3})\$?(\d+)');
22
+ // Named Range of cells
23
+ define('CALCULATION_REGEXP_NAMEDRANGE', '(((\w*)|(\'.*\')|(\".*\"))!)?([_A-Z][_A-Z0-9\.]*)');
24
+ }
25
+ }
26
+
27
+ /**
28
+ * PHPExcel_Calculation (Multiton)
29
+ *
30
+ * Copyright (c) 2006 - 2015 PHPExcel
31
+ *
32
+ * This library is free software; you can redistribute it and/or
33
+ * modify it under the terms of the GNU Lesser General Public
34
+ * License as published by the Free Software Foundation; either
35
+ * version 2.1 of the License, or (at your option) any later version.
36
+ *
37
+ * This library is distributed in the hope that it will be useful,
38
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
39
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
40
+ * Lesser General Public License for more details.
41
+ *
42
+ * You should have received a copy of the GNU Lesser General Public
43
+ * License along with this library; if not, write to the Free Software
44
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
45
+ *
46
+ * @category PHPExcel
47
+ * @package PHPExcel_Calculation
48
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
49
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
50
+ * @version ##VERSION##, ##DATE##
51
+ */
52
+ class PHPExcel_Calculation
53
+ {
54
+ /** Constants */
55
+ /** Regular Expressions */
56
+ // Numeric operand
57
+ const CALCULATION_REGEXP_NUMBER = '[-+]?\d*\.?\d+(e[-+]?\d+)?';
58
+ // String operand
59
+ const CALCULATION_REGEXP_STRING = '"(?:[^"]|"")*"';
60
+ // Opening bracket
61
+ const CALCULATION_REGEXP_OPENBRACE = '\(';
62
+ // Function (allow for the old @ symbol that could be used to prefix a function, but we'll ignore it)
63
+ const CALCULATION_REGEXP_FUNCTION = '@?([A-Z][A-Z0-9\.]*)[\s]*\(';
64
+ // Cell reference (cell or range of cells, with or without a sheet reference)
65
+ const CALCULATION_REGEXP_CELLREF = CALCULATION_REGEXP_CELLREF;
66
+ // Named Range of cells
67
+ const CALCULATION_REGEXP_NAMEDRANGE = CALCULATION_REGEXP_NAMEDRANGE;
68
+ // Error
69
+ const CALCULATION_REGEXP_ERROR = '\#[A-Z][A-Z0_\/]*[!\?]?';
70
+
71
+
72
+ /** constants */
73
+ const RETURN_ARRAY_AS_ERROR = 'error';
74
+ const RETURN_ARRAY_AS_VALUE = 'value';
75
+ const RETURN_ARRAY_AS_ARRAY = 'array';
76
+
77
+ private static $returnArrayAsType = self::RETURN_ARRAY_AS_VALUE;
78
+
79
+
80
+ /**
81
+ * Instance of this class
82
+ *
83
+ * @access private
84
+ * @var PHPExcel_Calculation
85
+ */
86
+ private static $instance;
87
+
88
+
89
+ /**
90
+ * Instance of the workbook this Calculation Engine is using
91
+ *
92
+ * @access private
93
+ * @var PHPExcel
94
+ */
95
+ private $workbook;
96
+
97
+ /**
98
+ * List of instances of the calculation engine that we've instantiated for individual workbooks
99
+ *
100
+ * @access private
101
+ * @var PHPExcel_Calculation[]
102
+ */
103
+ private static $workbookSets;
104
+
105
+ /**
106
+ * Calculation cache
107
+ *
108
+ * @access private
109
+ * @var array
110
+ */
111
+ private $calculationCache = array ();
112
+
113
+
114
+ /**
115
+ * Calculation cache enabled
116
+ *
117
+ * @access private
118
+ * @var boolean
119
+ */
120
+ private $calculationCacheEnabled = true;
121
+
122
+
123
+ /**
124
+ * List of operators that can be used within formulae
125
+ * The true/false value indicates whether it is a binary operator or a unary operator
126
+ *
127
+ * @access private
128
+ * @var array
129
+ */
130
+ private static $operators = array(
131
+ '+' => true, '-' => true, '*' => true, '/' => true,
132
+ '^' => true, '&' => true, '%' => false, '~' => false,
133
+ '>' => true, '<' => true, '=' => true, '>=' => true,
134
+ '<=' => true, '<>' => true, '|' => true, ':' => true
135
+ );
136
+
137
+ /**
138
+ * List of binary operators (those that expect two operands)
139
+ *
140
+ * @access private
141
+ * @var array
142
+ */
143
+ private static $binaryOperators = array(
144
+ '+' => true, '-' => true, '*' => true, '/' => true,
145
+ '^' => true, '&' => true, '>' => true, '<' => true,
146
+ '=' => true, '>=' => true, '<=' => true, '<>' => true,
147
+ '|' => true, ':' => true
148
+ );
149
+
150
+ /**
151
+ * The debug log generated by the calculation engine
152
+ *
153
+ * @access private
154
+ * @var PHPExcel_CalcEngine_Logger
155
+ *
156
+ */
157
+ private $debugLog;
158
+
159
+ /**
160
+ * Flag to determine how formula errors should be handled
161
+ * If true, then a user error will be triggered
162
+ * If false, then an exception will be thrown
163
+ *
164
+ * @access public
165
+ * @var boolean
166
+ *
167
+ */
168
+ public $suppressFormulaErrors = false;
169
+
170
+ /**
171
+ * Error message for any error that was raised/thrown by the calculation engine
172
+ *
173
+ * @access public
174
+ * @var string
175
+ *
176
+ */
177
+ public $formulaError = null;
178
+
179
+ /**
180
+ * An array of the nested cell references accessed by the calculation engine, used for the debug log
181
+ *
182
+ * @access private
183
+ * @var array of string
184
+ *
185
+ */
186
+ private $cyclicReferenceStack;
187
+
188
+ private $cellStack = array();
189
+
190
+ /**
191
+ * Current iteration counter for cyclic formulae
192
+ * If the value is 0 (or less) then cyclic formulae will throw an exception,
193
+ * otherwise they will iterate to the limit defined here before returning a result
194
+ *
195
+ * @var integer
196
+ *
197
+ */
198
+ private $cyclicFormulaCounter = 1;
199
+
200
+ private $cyclicFormulaCell = '';
201
+
202
+ /**
203
+ * Number of iterations for cyclic formulae
204
+ *
205
+ * @var integer
206
+ *
207
+ */
208
+ public $cyclicFormulaCount = 1;
209
+
210
+ /**
211
+ * Epsilon Precision used for comparisons in calculations
212
+ *
213
+ * @var float
214
+ *
215
+ */
216
+ private $delta = 0.1e-12;
217
+
218
+
219
+ /**
220
+ * The current locale setting
221
+ *
222
+ * @var string
223
+ *
224
+ */
225
+ private static $localeLanguage = 'en_us'; // US English (default locale)
226
+
227
+ /**
228
+ * List of available locale settings
229
+ * Note that this is read for the locale subdirectory only when requested
230
+ *
231
+ * @var string[]
232
+ *
233
+ */
234
+ private static $validLocaleLanguages = array(
235
+ 'en' // English (default language)
236
+ );
237
+
238
+ /**
239
+ * Locale-specific argument separator for function arguments
240
+ *
241
+ * @var string
242
+ *
243
+ */
244
+ private static $localeArgumentSeparator = ',';
245
+ private static $localeFunctions = array();
246
+
247
+ /**
248
+ * Locale-specific translations for Excel constants (True, False and Null)
249
+ *
250
+ * @var string[]
251
+ *
252
+ */
253
+ public static $localeBoolean = array(
254
+ 'TRUE' => 'TRUE',
255
+ 'FALSE' => 'FALSE',
256
+ 'NULL' => 'NULL'
257
+ );
258
+
259
+ /**
260
+ * Excel constant string translations to their PHP equivalents
261
+ * Constant conversion from text name/value to actual (datatyped) value
262
+ *
263
+ * @var string[]
264
+ *
265
+ */
266
+ private static $excelConstants = array(
267
+ 'TRUE' => true,
268
+ 'FALSE' => false,
269
+ 'NULL' => null
270
+ );
271
+
272
+ // PHPExcel functions
273
+ private static $PHPExcelFunctions = array(
274
+ 'ABS' => array(
275
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
276
+ 'functionCall' => 'abs',
277
+ 'argumentCount' => '1'
278
+ ),
279
+ 'ACCRINT' => array(
280
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
281
+ 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINT',
282
+ 'argumentCount' => '4-7'
283
+ ),
284
+ 'ACCRINTM' => array(
285
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
286
+ 'functionCall' => 'PHPExcel_Calculation_Financial::ACCRINTM',
287
+ 'argumentCount' => '3-5'
288
+ ),
289
+ 'ACOS' => array(
290
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
291
+ 'functionCall' => 'acos',
292
+ 'argumentCount' => '1'
293
+ ),
294
+ 'ACOSH' => array(
295
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
296
+ 'functionCall' => 'acosh',
297
+ 'argumentCount' => '1'
298
+ ),
299
+ 'ADDRESS' => array(
300
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
301
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::CELL_ADDRESS',
302
+ 'argumentCount' => '2-5'
303
+ ),
304
+ 'AMORDEGRC' => array(
305
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
306
+ 'functionCall' => 'PHPExcel_Calculation_Financial::AMORDEGRC',
307
+ 'argumentCount' => '6,7'
308
+ ),
309
+ 'AMORLINC' => array(
310
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
311
+ 'functionCall' => 'PHPExcel_Calculation_Financial::AMORLINC',
312
+ 'argumentCount' => '6,7'
313
+ ),
314
+ 'AND' => array(
315
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
316
+ 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_AND',
317
+ 'argumentCount' => '1+'
318
+ ),
319
+ 'AREAS' => array(
320
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
321
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
322
+ 'argumentCount' => '1'
323
+ ),
324
+ 'ASC' => array(
325
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
326
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
327
+ 'argumentCount' => '1'
328
+ ),
329
+ 'ASIN' => array(
330
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
331
+ 'functionCall' => 'asin',
332
+ 'argumentCount' => '1'
333
+ ),
334
+ 'ASINH' => array(
335
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
336
+ 'functionCall' => 'asinh',
337
+ 'argumentCount' => '1'
338
+ ),
339
+ 'ATAN' => array(
340
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
341
+ 'functionCall' => 'atan',
342
+ 'argumentCount' => '1'
343
+ ),
344
+ 'ATAN2' => array(
345
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
346
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ATAN2',
347
+ 'argumentCount' => '2'
348
+ ),
349
+ 'ATANH' => array(
350
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
351
+ 'functionCall' => 'atanh',
352
+ 'argumentCount' => '1'
353
+ ),
354
+ 'AVEDEV' => array(
355
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
356
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::AVEDEV',
357
+ 'argumentCount' => '1+'
358
+ ),
359
+ 'AVERAGE' => array(
360
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
361
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGE',
362
+ 'argumentCount' => '1+'
363
+ ),
364
+ 'AVERAGEA' => array(
365
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
366
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEA',
367
+ 'argumentCount' => '1+'
368
+ ),
369
+ 'AVERAGEIF' => array(
370
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
371
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::AVERAGEIF',
372
+ 'argumentCount' => '2,3'
373
+ ),
374
+ 'AVERAGEIFS' => array(
375
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
376
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
377
+ 'argumentCount' => '3+'
378
+ ),
379
+ 'BAHTTEXT' => array(
380
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
381
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
382
+ 'argumentCount' => '1'
383
+ ),
384
+ 'BESSELI' => array(
385
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
386
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELI',
387
+ 'argumentCount' => '2'
388
+ ),
389
+ 'BESSELJ' => array(
390
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
391
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELJ',
392
+ 'argumentCount' => '2'
393
+ ),
394
+ 'BESSELK' => array(
395
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
396
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELK',
397
+ 'argumentCount' => '2'
398
+ ),
399
+ 'BESSELY' => array(
400
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
401
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BESSELY',
402
+ 'argumentCount' => '2'
403
+ ),
404
+ 'BETADIST' => array(
405
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
406
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::BETADIST',
407
+ 'argumentCount' => '3-5'
408
+ ),
409
+ 'BETAINV' => array(
410
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
411
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::BETAINV',
412
+ 'argumentCount' => '3-5'
413
+ ),
414
+ 'BIN2DEC' => array(
415
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
416
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTODEC',
417
+ 'argumentCount' => '1'
418
+ ),
419
+ 'BIN2HEX' => array(
420
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
421
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOHEX',
422
+ 'argumentCount' => '1,2'
423
+ ),
424
+ 'BIN2OCT' => array(
425
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
426
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::BINTOOCT',
427
+ 'argumentCount' => '1,2'
428
+ ),
429
+ 'BINOMDIST' => array(
430
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
431
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::BINOMDIST',
432
+ 'argumentCount' => '4'
433
+ ),
434
+ 'CEILING' => array(
435
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
436
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::CEILING',
437
+ 'argumentCount' => '2'
438
+ ),
439
+ 'CELL' => array(
440
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
441
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
442
+ 'argumentCount' => '1,2'
443
+ ),
444
+ 'CHAR' => array(
445
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
446
+ 'functionCall' => 'PHPExcel_Calculation_TextData::CHARACTER',
447
+ 'argumentCount' => '1'
448
+ ),
449
+ 'CHIDIST' => array(
450
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
451
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIDIST',
452
+ 'argumentCount' => '2'
453
+ ),
454
+ 'CHIINV' => array(
455
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
456
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CHIINV',
457
+ 'argumentCount' => '2'
458
+ ),
459
+ 'CHITEST' => array(
460
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
461
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
462
+ 'argumentCount' => '2'
463
+ ),
464
+ 'CHOOSE' => array(
465
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
466
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::CHOOSE',
467
+ 'argumentCount' => '2+'
468
+ ),
469
+ 'CLEAN' => array(
470
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
471
+ 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMNONPRINTABLE',
472
+ 'argumentCount' => '1'
473
+ ),
474
+ 'CODE' => array(
475
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
476
+ 'functionCall' => 'PHPExcel_Calculation_TextData::ASCIICODE',
477
+ 'argumentCount' => '1'
478
+ ),
479
+ 'COLUMN' => array(
480
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
481
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMN',
482
+ 'argumentCount' => '-1',
483
+ 'passByReference' => array(true)
484
+ ),
485
+ 'COLUMNS' => array(
486
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
487
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::COLUMNS',
488
+ 'argumentCount' => '1'
489
+ ),
490
+ 'COMBIN' => array(
491
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
492
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::COMBIN',
493
+ 'argumentCount' => '2'
494
+ ),
495
+ 'COMPLEX' => array(
496
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
497
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::COMPLEX',
498
+ 'argumentCount' => '2,3'
499
+ ),
500
+ 'CONCATENATE' => array(
501
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
502
+ 'functionCall' => 'PHPExcel_Calculation_TextData::CONCATENATE',
503
+ 'argumentCount' => '1+'
504
+ ),
505
+ 'CONFIDENCE' => array(
506
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
507
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CONFIDENCE',
508
+ 'argumentCount' => '3'
509
+ ),
510
+ 'CONVERT' => array(
511
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
512
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::CONVERTUOM',
513
+ 'argumentCount' => '3'
514
+ ),
515
+ 'CORREL' => array(
516
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
517
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL',
518
+ 'argumentCount' => '2'
519
+ ),
520
+ 'COS' => array(
521
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
522
+ 'functionCall' => 'cos',
523
+ 'argumentCount' => '1'
524
+ ),
525
+ 'COSH' => array(
526
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
527
+ 'functionCall' => 'cosh',
528
+ 'argumentCount' => '1'
529
+ ),
530
+ 'COUNT' => array(
531
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
532
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNT',
533
+ 'argumentCount' => '1+'
534
+ ),
535
+ 'COUNTA' => array(
536
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
537
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTA',
538
+ 'argumentCount' => '1+'
539
+ ),
540
+ 'COUNTBLANK' => array(
541
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
542
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTBLANK',
543
+ 'argumentCount' => '1'
544
+ ),
545
+ 'COUNTIF' => array(
546
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
547
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COUNTIF',
548
+ 'argumentCount' => '2'
549
+ ),
550
+ 'COUNTIFS' => array(
551
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
552
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
553
+ 'argumentCount' => '2'
554
+ ),
555
+ 'COUPDAYBS' => array(
556
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
557
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYBS',
558
+ 'argumentCount' => '3,4'
559
+ ),
560
+ 'COUPDAYS' => array(
561
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
562
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYS',
563
+ 'argumentCount' => '3,4'
564
+ ),
565
+ 'COUPDAYSNC' => array(
566
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
567
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPDAYSNC',
568
+ 'argumentCount' => '3,4'
569
+ ),
570
+ 'COUPNCD' => array(
571
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
572
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNCD',
573
+ 'argumentCount' => '3,4'
574
+ ),
575
+ 'COUPNUM' => array(
576
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
577
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPNUM',
578
+ 'argumentCount' => '3,4'
579
+ ),
580
+ 'COUPPCD' => array(
581
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
582
+ 'functionCall' => 'PHPExcel_Calculation_Financial::COUPPCD',
583
+ 'argumentCount' => '3,4'
584
+ ),
585
+ 'COVAR' => array(
586
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
587
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::COVAR',
588
+ 'argumentCount' => '2'
589
+ ),
590
+ 'CRITBINOM' => array(
591
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
592
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CRITBINOM',
593
+ 'argumentCount' => '3'
594
+ ),
595
+ 'CUBEKPIMEMBER' => array(
596
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
597
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
598
+ 'argumentCount' => '?'
599
+ ),
600
+ 'CUBEMEMBER' => array(
601
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
602
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
603
+ 'argumentCount' => '?'
604
+ ),
605
+ 'CUBEMEMBERPROPERTY' => array(
606
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
607
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
608
+ 'argumentCount' => '?'
609
+ ),
610
+ 'CUBERANKEDMEMBER' => array(
611
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
612
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
613
+ 'argumentCount' => '?'
614
+ ),
615
+ 'CUBESET' => array(
616
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
617
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
618
+ 'argumentCount' => '?'
619
+ ),
620
+ 'CUBESETCOUNT' => array(
621
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
622
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
623
+ 'argumentCount' => '?'
624
+ ),
625
+ 'CUBEVALUE' => array(
626
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_CUBE,
627
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
628
+ 'argumentCount' => '?'
629
+ ),
630
+ 'CUMIPMT' => array(
631
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
632
+ 'functionCall' => 'PHPExcel_Calculation_Financial::CUMIPMT',
633
+ 'argumentCount' => '6'
634
+ ),
635
+ 'CUMPRINC' => array(
636
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
637
+ 'functionCall' => 'PHPExcel_Calculation_Financial::CUMPRINC',
638
+ 'argumentCount' => '6'
639
+ ),
640
+ 'DATE' => array(
641
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
642
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATE',
643
+ 'argumentCount' => '3'
644
+ ),
645
+ 'DATEDIF' => array(
646
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
647
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEDIF',
648
+ 'argumentCount' => '2,3'
649
+ ),
650
+ 'DATEVALUE' => array(
651
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
652
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATEVALUE',
653
+ 'argumentCount' => '1'
654
+ ),
655
+ 'DAVERAGE' => array(
656
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
657
+ 'functionCall' => 'PHPExcel_Calculation_Database::DAVERAGE',
658
+ 'argumentCount' => '3'
659
+ ),
660
+ 'DAY' => array(
661
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
662
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFMONTH',
663
+ 'argumentCount' => '1'
664
+ ),
665
+ 'DAYS360' => array(
666
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
667
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYS360',
668
+ 'argumentCount' => '2,3'
669
+ ),
670
+ 'DB' => array(
671
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
672
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DB',
673
+ 'argumentCount' => '4,5'
674
+ ),
675
+ 'DCOUNT' => array(
676
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
677
+ 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNT',
678
+ 'argumentCount' => '3'
679
+ ),
680
+ 'DCOUNTA' => array(
681
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
682
+ 'functionCall' => 'PHPExcel_Calculation_Database::DCOUNTA',
683
+ 'argumentCount' => '3'
684
+ ),
685
+ 'DDB' => array(
686
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
687
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DDB',
688
+ 'argumentCount' => '4,5'
689
+ ),
690
+ 'DEC2BIN' => array(
691
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
692
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOBIN',
693
+ 'argumentCount' => '1,2'
694
+ ),
695
+ 'DEC2HEX' => array(
696
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
697
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOHEX',
698
+ 'argumentCount' => '1,2'
699
+ ),
700
+ 'DEC2OCT' => array(
701
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
702
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::DECTOOCT',
703
+ 'argumentCount' => '1,2'
704
+ ),
705
+ 'DEGREES' => array(
706
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
707
+ 'functionCall' => 'rad2deg',
708
+ 'argumentCount' => '1'
709
+ ),
710
+ 'DELTA' => array(
711
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
712
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::DELTA',
713
+ 'argumentCount' => '1,2'
714
+ ),
715
+ 'DEVSQ' => array(
716
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
717
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::DEVSQ',
718
+ 'argumentCount' => '1+'
719
+ ),
720
+ 'DGET' => array(
721
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
722
+ 'functionCall' => 'PHPExcel_Calculation_Database::DGET',
723
+ 'argumentCount' => '3'
724
+ ),
725
+ 'DISC' => array(
726
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
727
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DISC',
728
+ 'argumentCount' => '4,5'
729
+ ),
730
+ 'DMAX' => array(
731
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
732
+ 'functionCall' => 'PHPExcel_Calculation_Database::DMAX',
733
+ 'argumentCount' => '3'
734
+ ),
735
+ 'DMIN' => array(
736
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
737
+ 'functionCall' => 'PHPExcel_Calculation_Database::DMIN',
738
+ 'argumentCount' => '3'
739
+ ),
740
+ 'DOLLAR' => array(
741
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
742
+ 'functionCall' => 'PHPExcel_Calculation_TextData::DOLLAR',
743
+ 'argumentCount' => '1,2'
744
+ ),
745
+ 'DOLLARDE' => array(
746
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
747
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARDE',
748
+ 'argumentCount' => '2'
749
+ ),
750
+ 'DOLLARFR' => array(
751
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
752
+ 'functionCall' => 'PHPExcel_Calculation_Financial::DOLLARFR',
753
+ 'argumentCount' => '2'
754
+ ),
755
+ 'DPRODUCT' => array(
756
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
757
+ 'functionCall' => 'PHPExcel_Calculation_Database::DPRODUCT',
758
+ 'argumentCount' => '3'
759
+ ),
760
+ 'DSTDEV' => array(
761
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
762
+ 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEV',
763
+ 'argumentCount' => '3'
764
+ ),
765
+ 'DSTDEVP' => array(
766
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
767
+ 'functionCall' => 'PHPExcel_Calculation_Database::DSTDEVP',
768
+ 'argumentCount' => '3'
769
+ ),
770
+ 'DSUM' => array(
771
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
772
+ 'functionCall' => 'PHPExcel_Calculation_Database::DSUM',
773
+ 'argumentCount' => '3'
774
+ ),
775
+ 'DURATION' => array(
776
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
777
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
778
+ 'argumentCount' => '5,6'
779
+ ),
780
+ 'DVAR' => array(
781
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
782
+ 'functionCall' => 'PHPExcel_Calculation_Database::DVAR',
783
+ 'argumentCount' => '3'
784
+ ),
785
+ 'DVARP' => array(
786
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATABASE,
787
+ 'functionCall' => 'PHPExcel_Calculation_Database::DVARP',
788
+ 'argumentCount' => '3'
789
+ ),
790
+ 'EDATE' => array(
791
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
792
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::EDATE',
793
+ 'argumentCount' => '2'
794
+ ),
795
+ 'EFFECT' => array(
796
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
797
+ 'functionCall' => 'PHPExcel_Calculation_Financial::EFFECT',
798
+ 'argumentCount' => '2'
799
+ ),
800
+ 'EOMONTH' => array(
801
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
802
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::EOMONTH',
803
+ 'argumentCount' => '2'
804
+ ),
805
+ 'ERF' => array(
806
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
807
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::ERF',
808
+ 'argumentCount' => '1,2'
809
+ ),
810
+ 'ERFC' => array(
811
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
812
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::ERFC',
813
+ 'argumentCount' => '1'
814
+ ),
815
+ 'ERROR.TYPE' => array(
816
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
817
+ 'functionCall' => 'PHPExcel_Calculation_Functions::ERROR_TYPE',
818
+ 'argumentCount' => '1'
819
+ ),
820
+ 'EVEN' => array(
821
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
822
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::EVEN',
823
+ 'argumentCount' => '1'
824
+ ),
825
+ 'EXACT' => array(
826
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
827
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
828
+ 'argumentCount' => '2'
829
+ ),
830
+ 'EXP' => array(
831
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
832
+ 'functionCall' => 'exp',
833
+ 'argumentCount' => '1'
834
+ ),
835
+ 'EXPONDIST' => array(
836
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
837
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::EXPONDIST',
838
+ 'argumentCount' => '3'
839
+ ),
840
+ 'FACT' => array(
841
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
842
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACT',
843
+ 'argumentCount' => '1'
844
+ ),
845
+ 'FACTDOUBLE' => array(
846
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
847
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::FACTDOUBLE',
848
+ 'argumentCount' => '1'
849
+ ),
850
+ 'FALSE' => array(
851
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
852
+ 'functionCall' => 'PHPExcel_Calculation_Logical::FALSE',
853
+ 'argumentCount' => '0'
854
+ ),
855
+ 'FDIST' => array(
856
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
857
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
858
+ 'argumentCount' => '3'
859
+ ),
860
+ 'FIND' => array(
861
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
862
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE',
863
+ 'argumentCount' => '2,3'
864
+ ),
865
+ 'FINDB' => array(
866
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
867
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHSENSITIVE',
868
+ 'argumentCount' => '2,3'
869
+ ),
870
+ 'FINV' => array(
871
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
872
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
873
+ 'argumentCount' => '3'
874
+ ),
875
+ 'FISHER' => array(
876
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
877
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHER',
878
+ 'argumentCount' => '1'
879
+ ),
880
+ 'FISHERINV' => array(
881
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
882
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::FISHERINV',
883
+ 'argumentCount' => '1'
884
+ ),
885
+ 'FIXED' => array(
886
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
887
+ 'functionCall' => 'PHPExcel_Calculation_TextData::FIXEDFORMAT',
888
+ 'argumentCount' => '1-3'
889
+ ),
890
+ 'FLOOR' => array(
891
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
892
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::FLOOR',
893
+ 'argumentCount' => '2'
894
+ ),
895
+ 'FORECAST' => array(
896
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
897
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::FORECAST',
898
+ 'argumentCount' => '3'
899
+ ),
900
+ 'FREQUENCY' => array(
901
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
902
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
903
+ 'argumentCount' => '2'
904
+ ),
905
+ 'FTEST' => array(
906
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
907
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
908
+ 'argumentCount' => '2'
909
+ ),
910
+ 'FV' => array(
911
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
912
+ 'functionCall' => 'PHPExcel_Calculation_Financial::FV',
913
+ 'argumentCount' => '3-5'
914
+ ),
915
+ 'FVSCHEDULE' => array(
916
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
917
+ 'functionCall' => 'PHPExcel_Calculation_Financial::FVSCHEDULE',
918
+ 'argumentCount' => '2'
919
+ ),
920
+ 'GAMMADIST' => array(
921
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
922
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMADIST',
923
+ 'argumentCount' => '4'
924
+ ),
925
+ 'GAMMAINV' => array(
926
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
927
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMAINV',
928
+ 'argumentCount' => '3'
929
+ ),
930
+ 'GAMMALN' => array(
931
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
932
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GAMMALN',
933
+ 'argumentCount' => '1'
934
+ ),
935
+ 'GCD' => array(
936
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
937
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::GCD',
938
+ 'argumentCount' => '1+'
939
+ ),
940
+ 'GEOMEAN' => array(
941
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
942
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GEOMEAN',
943
+ 'argumentCount' => '1+'
944
+ ),
945
+ 'GESTEP' => array(
946
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
947
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::GESTEP',
948
+ 'argumentCount' => '1,2'
949
+ ),
950
+ 'GETPIVOTDATA' => array(
951
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
952
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
953
+ 'argumentCount' => '2+'
954
+ ),
955
+ 'GROWTH' => array(
956
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
957
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::GROWTH',
958
+ 'argumentCount' => '1-4'
959
+ ),
960
+ 'HARMEAN' => array(
961
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
962
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::HARMEAN',
963
+ 'argumentCount' => '1+'
964
+ ),
965
+ 'HEX2BIN' => array(
966
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
967
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOBIN',
968
+ 'argumentCount' => '1,2'
969
+ ),
970
+ 'HEX2DEC' => array(
971
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
972
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTODEC',
973
+ 'argumentCount' => '1'
974
+ ),
975
+ 'HEX2OCT' => array(
976
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
977
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::HEXTOOCT',
978
+ 'argumentCount' => '1,2'
979
+ ),
980
+ 'HLOOKUP' => array(
981
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
982
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::HLOOKUP',
983
+ 'argumentCount' => '3,4'
984
+ ),
985
+ 'HOUR' => array(
986
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
987
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::HOUROFDAY',
988
+ 'argumentCount' => '1'
989
+ ),
990
+ 'HYPERLINK' => array(
991
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
992
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::HYPERLINK',
993
+ 'argumentCount' => '1,2',
994
+ 'passCellReference' => true
995
+ ),
996
+ 'HYPGEOMDIST' => array(
997
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
998
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::HYPGEOMDIST',
999
+ 'argumentCount' => '4'
1000
+ ),
1001
+ 'IF' => array(
1002
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
1003
+ 'functionCall' => 'PHPExcel_Calculation_Logical::STATEMENT_IF',
1004
+ 'argumentCount' => '1-3'
1005
+ ),
1006
+ 'IFERROR' => array(
1007
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
1008
+ 'functionCall' => 'PHPExcel_Calculation_Logical::IFERROR',
1009
+ 'argumentCount' => '2'
1010
+ ),
1011
+ 'IMABS' => array(
1012
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1013
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMABS',
1014
+ 'argumentCount' => '1'
1015
+ ),
1016
+ 'IMAGINARY' => array(
1017
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1018
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMAGINARY',
1019
+ 'argumentCount' => '1'
1020
+ ),
1021
+ 'IMARGUMENT' => array(
1022
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1023
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMARGUMENT',
1024
+ 'argumentCount' => '1'
1025
+ ),
1026
+ 'IMCONJUGATE' => array(
1027
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1028
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCONJUGATE',
1029
+ 'argumentCount' => '1'
1030
+ ),
1031
+ 'IMCOS' => array(
1032
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1033
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMCOS',
1034
+ 'argumentCount' => '1'
1035
+ ),
1036
+ 'IMDIV' => array(
1037
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1038
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMDIV',
1039
+ 'argumentCount' => '2'
1040
+ ),
1041
+ 'IMEXP' => array(
1042
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1043
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMEXP',
1044
+ 'argumentCount' => '1'
1045
+ ),
1046
+ 'IMLN' => array(
1047
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1048
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLN',
1049
+ 'argumentCount' => '1'
1050
+ ),
1051
+ 'IMLOG10' => array(
1052
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1053
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG10',
1054
+ 'argumentCount' => '1'
1055
+ ),
1056
+ 'IMLOG2' => array(
1057
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1058
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMLOG2',
1059
+ 'argumentCount' => '1'
1060
+ ),
1061
+ 'IMPOWER' => array(
1062
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1063
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPOWER',
1064
+ 'argumentCount' => '2'
1065
+ ),
1066
+ 'IMPRODUCT' => array(
1067
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1068
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMPRODUCT',
1069
+ 'argumentCount' => '1+'
1070
+ ),
1071
+ 'IMREAL' => array(
1072
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1073
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMREAL',
1074
+ 'argumentCount' => '1'
1075
+ ),
1076
+ 'IMSIN' => array(
1077
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1078
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSIN',
1079
+ 'argumentCount' => '1'
1080
+ ),
1081
+ 'IMSQRT' => array(
1082
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1083
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSQRT',
1084
+ 'argumentCount' => '1'
1085
+ ),
1086
+ 'IMSUB' => array(
1087
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1088
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUB',
1089
+ 'argumentCount' => '2'
1090
+ ),
1091
+ 'IMSUM' => array(
1092
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1093
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::IMSUM',
1094
+ 'argumentCount' => '1+'
1095
+ ),
1096
+ 'INDEX' => array(
1097
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1098
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDEX',
1099
+ 'argumentCount' => '1-4'
1100
+ ),
1101
+ 'INDIRECT' => array(
1102
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1103
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::INDIRECT',
1104
+ 'argumentCount' => '1,2',
1105
+ 'passCellReference' => true
1106
+ ),
1107
+ 'INFO' => array(
1108
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1109
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1110
+ 'argumentCount' => '1'
1111
+ ),
1112
+ 'INT' => array(
1113
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1114
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::INT',
1115
+ 'argumentCount' => '1'
1116
+ ),
1117
+ 'INTERCEPT' => array(
1118
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1119
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::INTERCEPT',
1120
+ 'argumentCount' => '2'
1121
+ ),
1122
+ 'INTRATE' => array(
1123
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1124
+ 'functionCall' => 'PHPExcel_Calculation_Financial::INTRATE',
1125
+ 'argumentCount' => '4,5'
1126
+ ),
1127
+ 'IPMT' => array(
1128
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1129
+ 'functionCall' => 'PHPExcel_Calculation_Financial::IPMT',
1130
+ 'argumentCount' => '4-6'
1131
+ ),
1132
+ 'IRR' => array(
1133
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1134
+ 'functionCall' => 'PHPExcel_Calculation_Financial::IRR',
1135
+ 'argumentCount' => '1,2'
1136
+ ),
1137
+ 'ISBLANK' => array(
1138
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1139
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_BLANK',
1140
+ 'argumentCount' => '1'
1141
+ ),
1142
+ 'ISERR' => array(
1143
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1144
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERR',
1145
+ 'argumentCount' => '1'
1146
+ ),
1147
+ 'ISERROR' => array(
1148
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1149
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ERROR',
1150
+ 'argumentCount' => '1'
1151
+ ),
1152
+ 'ISEVEN' => array(
1153
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1154
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_EVEN',
1155
+ 'argumentCount' => '1'
1156
+ ),
1157
+ 'ISLOGICAL' => array(
1158
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1159
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_LOGICAL',
1160
+ 'argumentCount' => '1'
1161
+ ),
1162
+ 'ISNA' => array(
1163
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1164
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NA',
1165
+ 'argumentCount' => '1'
1166
+ ),
1167
+ 'ISNONTEXT' => array(
1168
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1169
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NONTEXT',
1170
+ 'argumentCount' => '1'
1171
+ ),
1172
+ 'ISNUMBER' => array(
1173
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1174
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_NUMBER',
1175
+ 'argumentCount' => '1'
1176
+ ),
1177
+ 'ISODD' => array(
1178
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1179
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_ODD',
1180
+ 'argumentCount' => '1'
1181
+ ),
1182
+ 'ISPMT' => array(
1183
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1184
+ 'functionCall' => 'PHPExcel_Calculation_Financial::ISPMT',
1185
+ 'argumentCount' => '4'
1186
+ ),
1187
+ 'ISREF' => array(
1188
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1189
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1190
+ 'argumentCount' => '1'
1191
+ ),
1192
+ 'ISTEXT' => array(
1193
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1194
+ 'functionCall' => 'PHPExcel_Calculation_Functions::IS_TEXT',
1195
+ 'argumentCount' => '1'
1196
+ ),
1197
+ 'JIS' => array(
1198
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1199
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1200
+ 'argumentCount' => '1'
1201
+ ),
1202
+ 'KURT' => array(
1203
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1204
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::KURT',
1205
+ 'argumentCount' => '1+'
1206
+ ),
1207
+ 'LARGE' => array(
1208
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1209
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LARGE',
1210
+ 'argumentCount' => '2'
1211
+ ),
1212
+ 'LCM' => array(
1213
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1214
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::LCM',
1215
+ 'argumentCount' => '1+'
1216
+ ),
1217
+ 'LEFT' => array(
1218
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1219
+ 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT',
1220
+ 'argumentCount' => '1,2'
1221
+ ),
1222
+ 'LEFTB' => array(
1223
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1224
+ 'functionCall' => 'PHPExcel_Calculation_TextData::LEFT',
1225
+ 'argumentCount' => '1,2'
1226
+ ),
1227
+ 'LEN' => array(
1228
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1229
+ 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH',
1230
+ 'argumentCount' => '1'
1231
+ ),
1232
+ 'LENB' => array(
1233
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1234
+ 'functionCall' => 'PHPExcel_Calculation_TextData::STRINGLENGTH',
1235
+ 'argumentCount' => '1'
1236
+ ),
1237
+ 'LINEST' => array(
1238
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1239
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LINEST',
1240
+ 'argumentCount' => '1-4'
1241
+ ),
1242
+ 'LN' => array(
1243
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1244
+ 'functionCall' => 'log',
1245
+ 'argumentCount' => '1'
1246
+ ),
1247
+ 'LOG' => array(
1248
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1249
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::LOG_BASE',
1250
+ 'argumentCount' => '1,2'
1251
+ ),
1252
+ 'LOG10' => array(
1253
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1254
+ 'functionCall' => 'log10',
1255
+ 'argumentCount' => '1'
1256
+ ),
1257
+ 'LOGEST' => array(
1258
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1259
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGEST',
1260
+ 'argumentCount' => '1-4'
1261
+ ),
1262
+ 'LOGINV' => array(
1263
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1264
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGINV',
1265
+ 'argumentCount' => '3'
1266
+ ),
1267
+ 'LOGNORMDIST' => array(
1268
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1269
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::LOGNORMDIST',
1270
+ 'argumentCount' => '3'
1271
+ ),
1272
+ 'LOOKUP' => array(
1273
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1274
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::LOOKUP',
1275
+ 'argumentCount' => '2,3'
1276
+ ),
1277
+ 'LOWER' => array(
1278
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1279
+ 'functionCall' => 'PHPExcel_Calculation_TextData::LOWERCASE',
1280
+ 'argumentCount' => '1'
1281
+ ),
1282
+ 'MATCH' => array(
1283
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1284
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::MATCH',
1285
+ 'argumentCount' => '2,3'
1286
+ ),
1287
+ 'MAX' => array(
1288
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1289
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MAX',
1290
+ 'argumentCount' => '1+'
1291
+ ),
1292
+ 'MAXA' => array(
1293
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1294
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXA',
1295
+ 'argumentCount' => '1+'
1296
+ ),
1297
+ 'MAXIF' => array(
1298
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1299
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MAXIF',
1300
+ 'argumentCount' => '2+'
1301
+ ),
1302
+ 'MDETERM' => array(
1303
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1304
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MDETERM',
1305
+ 'argumentCount' => '1'
1306
+ ),
1307
+ 'MDURATION' => array(
1308
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1309
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1310
+ 'argumentCount' => '5,6'
1311
+ ),
1312
+ 'MEDIAN' => array(
1313
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1314
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MEDIAN',
1315
+ 'argumentCount' => '1+'
1316
+ ),
1317
+ 'MEDIANIF' => array(
1318
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1319
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1320
+ 'argumentCount' => '2+'
1321
+ ),
1322
+ 'MID' => array(
1323
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1324
+ 'functionCall' => 'PHPExcel_Calculation_TextData::MID',
1325
+ 'argumentCount' => '3'
1326
+ ),
1327
+ 'MIDB' => array(
1328
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1329
+ 'functionCall' => 'PHPExcel_Calculation_TextData::MID',
1330
+ 'argumentCount' => '3'
1331
+ ),
1332
+ 'MIN' => array(
1333
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1334
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MIN',
1335
+ 'argumentCount' => '1+'
1336
+ ),
1337
+ 'MINA' => array(
1338
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1339
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MINA',
1340
+ 'argumentCount' => '1+'
1341
+ ),
1342
+ 'MINIF' => array(
1343
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1344
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MINIF',
1345
+ 'argumentCount' => '2+'
1346
+ ),
1347
+ 'MINUTE' => array(
1348
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1349
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::MINUTEOFHOUR',
1350
+ 'argumentCount' => '1'
1351
+ ),
1352
+ 'MINVERSE' => array(
1353
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1354
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MINVERSE',
1355
+ 'argumentCount' => '1'
1356
+ ),
1357
+ 'MIRR' => array(
1358
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1359
+ 'functionCall' => 'PHPExcel_Calculation_Financial::MIRR',
1360
+ 'argumentCount' => '3'
1361
+ ),
1362
+ 'MMULT' => array(
1363
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1364
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MMULT',
1365
+ 'argumentCount' => '2'
1366
+ ),
1367
+ 'MOD' => array(
1368
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1369
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MOD',
1370
+ 'argumentCount' => '2'
1371
+ ),
1372
+ 'MODE' => array(
1373
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1374
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::MODE',
1375
+ 'argumentCount' => '1+'
1376
+ ),
1377
+ 'MONTH' => array(
1378
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1379
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::MONTHOFYEAR',
1380
+ 'argumentCount' => '1'
1381
+ ),
1382
+ 'MROUND' => array(
1383
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1384
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MROUND',
1385
+ 'argumentCount' => '2'
1386
+ ),
1387
+ 'MULTINOMIAL' => array(
1388
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1389
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::MULTINOMIAL',
1390
+ 'argumentCount' => '1+'
1391
+ ),
1392
+ 'N' => array(
1393
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1394
+ 'functionCall' => 'PHPExcel_Calculation_Functions::N',
1395
+ 'argumentCount' => '1'
1396
+ ),
1397
+ 'NA' => array(
1398
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1399
+ 'functionCall' => 'PHPExcel_Calculation_Functions::NA',
1400
+ 'argumentCount' => '0'
1401
+ ),
1402
+ 'NEGBINOMDIST' => array(
1403
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1404
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NEGBINOMDIST',
1405
+ 'argumentCount' => '3'
1406
+ ),
1407
+ 'NETWORKDAYS' => array(
1408
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1409
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::NETWORKDAYS',
1410
+ 'argumentCount' => '2+'
1411
+ ),
1412
+ 'NOMINAL' => array(
1413
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1414
+ 'functionCall' => 'PHPExcel_Calculation_Financial::NOMINAL',
1415
+ 'argumentCount' => '2'
1416
+ ),
1417
+ 'NORMDIST' => array(
1418
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1419
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMDIST',
1420
+ 'argumentCount' => '4'
1421
+ ),
1422
+ 'NORMINV' => array(
1423
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1424
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMINV',
1425
+ 'argumentCount' => '3'
1426
+ ),
1427
+ 'NORMSDIST' => array(
1428
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1429
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSDIST',
1430
+ 'argumentCount' => '1'
1431
+ ),
1432
+ 'NORMSINV' => array(
1433
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1434
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::NORMSINV',
1435
+ 'argumentCount' => '1'
1436
+ ),
1437
+ 'NOT' => array(
1438
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
1439
+ 'functionCall' => 'PHPExcel_Calculation_Logical::NOT',
1440
+ 'argumentCount' => '1'
1441
+ ),
1442
+ 'NOW' => array(
1443
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1444
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATETIMENOW',
1445
+ 'argumentCount' => '0'
1446
+ ),
1447
+ 'NPER' => array(
1448
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1449
+ 'functionCall' => 'PHPExcel_Calculation_Financial::NPER',
1450
+ 'argumentCount' => '3-5'
1451
+ ),
1452
+ 'NPV' => array(
1453
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1454
+ 'functionCall' => 'PHPExcel_Calculation_Financial::NPV',
1455
+ 'argumentCount' => '2+'
1456
+ ),
1457
+ 'OCT2BIN' => array(
1458
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1459
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOBIN',
1460
+ 'argumentCount' => '1,2'
1461
+ ),
1462
+ 'OCT2DEC' => array(
1463
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1464
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTODEC',
1465
+ 'argumentCount' => '1'
1466
+ ),
1467
+ 'OCT2HEX' => array(
1468
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_ENGINEERING,
1469
+ 'functionCall' => 'PHPExcel_Calculation_Engineering::OCTTOHEX',
1470
+ 'argumentCount' => '1,2'
1471
+ ),
1472
+ 'ODD' => array(
1473
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1474
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ODD',
1475
+ 'argumentCount' => '1'
1476
+ ),
1477
+ 'ODDFPRICE' => array(
1478
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1479
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1480
+ 'argumentCount' => '8,9'
1481
+ ),
1482
+ 'ODDFYIELD' => array(
1483
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1484
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1485
+ 'argumentCount' => '8,9'
1486
+ ),
1487
+ 'ODDLPRICE' => array(
1488
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1489
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1490
+ 'argumentCount' => '7,8'
1491
+ ),
1492
+ 'ODDLYIELD' => array(
1493
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1494
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1495
+ 'argumentCount' => '7,8'
1496
+ ),
1497
+ 'OFFSET' => array(
1498
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1499
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::OFFSET',
1500
+ 'argumentCount' => '3-5',
1501
+ 'passCellReference' => true,
1502
+ 'passByReference' => array(true)
1503
+ ),
1504
+ 'OR' => array(
1505
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
1506
+ 'functionCall' => 'PHPExcel_Calculation_Logical::LOGICAL_OR',
1507
+ 'argumentCount' => '1+'
1508
+ ),
1509
+ 'PEARSON' => array(
1510
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1511
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::CORREL',
1512
+ 'argumentCount' => '2'
1513
+ ),
1514
+ 'PERCENTILE' => array(
1515
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1516
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTILE',
1517
+ 'argumentCount' => '2'
1518
+ ),
1519
+ 'PERCENTRANK' => array(
1520
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1521
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::PERCENTRANK',
1522
+ 'argumentCount' => '2,3'
1523
+ ),
1524
+ 'PERMUT' => array(
1525
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1526
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::PERMUT',
1527
+ 'argumentCount' => '2'
1528
+ ),
1529
+ 'PHONETIC' => array(
1530
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1531
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1532
+ 'argumentCount' => '1'
1533
+ ),
1534
+ 'PI' => array(
1535
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1536
+ 'functionCall' => 'pi',
1537
+ 'argumentCount' => '0'
1538
+ ),
1539
+ 'PMT' => array(
1540
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1541
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PMT',
1542
+ 'argumentCount' => '3-5'
1543
+ ),
1544
+ 'POISSON' => array(
1545
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1546
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::POISSON',
1547
+ 'argumentCount' => '3'
1548
+ ),
1549
+ 'POWER' => array(
1550
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1551
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::POWER',
1552
+ 'argumentCount' => '2'
1553
+ ),
1554
+ 'PPMT' => array(
1555
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1556
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PPMT',
1557
+ 'argumentCount' => '4-6'
1558
+ ),
1559
+ 'PRICE' => array(
1560
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1561
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PRICE',
1562
+ 'argumentCount' => '6,7'
1563
+ ),
1564
+ 'PRICEDISC' => array(
1565
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1566
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEDISC',
1567
+ 'argumentCount' => '4,5'
1568
+ ),
1569
+ 'PRICEMAT' => array(
1570
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1571
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PRICEMAT',
1572
+ 'argumentCount' => '5,6'
1573
+ ),
1574
+ 'PROB' => array(
1575
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1576
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1577
+ 'argumentCount' => '3,4'
1578
+ ),
1579
+ 'PRODUCT' => array(
1580
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1581
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::PRODUCT',
1582
+ 'argumentCount' => '1+'
1583
+ ),
1584
+ 'PROPER' => array(
1585
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1586
+ 'functionCall' => 'PHPExcel_Calculation_TextData::PROPERCASE',
1587
+ 'argumentCount' => '1'
1588
+ ),
1589
+ 'PV' => array(
1590
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1591
+ 'functionCall' => 'PHPExcel_Calculation_Financial::PV',
1592
+ 'argumentCount' => '3-5'
1593
+ ),
1594
+ 'QUARTILE' => array(
1595
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1596
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::QUARTILE',
1597
+ 'argumentCount' => '2'
1598
+ ),
1599
+ 'QUOTIENT' => array(
1600
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1601
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::QUOTIENT',
1602
+ 'argumentCount' => '2'
1603
+ ),
1604
+ 'RADIANS' => array(
1605
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1606
+ 'functionCall' => 'deg2rad',
1607
+ 'argumentCount' => '1'
1608
+ ),
1609
+ 'RAND' => array(
1610
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1611
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND',
1612
+ 'argumentCount' => '0'
1613
+ ),
1614
+ 'RANDBETWEEN' => array(
1615
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1616
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::RAND',
1617
+ 'argumentCount' => '2'
1618
+ ),
1619
+ 'RANK' => array(
1620
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1621
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::RANK',
1622
+ 'argumentCount' => '2,3'
1623
+ ),
1624
+ 'RATE' => array(
1625
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1626
+ 'functionCall' => 'PHPExcel_Calculation_Financial::RATE',
1627
+ 'argumentCount' => '3-6'
1628
+ ),
1629
+ 'RECEIVED' => array(
1630
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1631
+ 'functionCall' => 'PHPExcel_Calculation_Financial::RECEIVED',
1632
+ 'argumentCount' => '4-5'
1633
+ ),
1634
+ 'REPLACE' => array(
1635
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1636
+ 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE',
1637
+ 'argumentCount' => '4'
1638
+ ),
1639
+ 'REPLACEB' => array(
1640
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1641
+ 'functionCall' => 'PHPExcel_Calculation_TextData::REPLACE',
1642
+ 'argumentCount' => '4'
1643
+ ),
1644
+ 'REPT' => array(
1645
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1646
+ 'functionCall' => 'str_repeat',
1647
+ 'argumentCount' => '2'
1648
+ ),
1649
+ 'RIGHT' => array(
1650
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1651
+ 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT',
1652
+ 'argumentCount' => '1,2'
1653
+ ),
1654
+ 'RIGHTB' => array(
1655
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1656
+ 'functionCall' => 'PHPExcel_Calculation_TextData::RIGHT',
1657
+ 'argumentCount' => '1,2'
1658
+ ),
1659
+ 'ROMAN' => array(
1660
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1661
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROMAN',
1662
+ 'argumentCount' => '1,2'
1663
+ ),
1664
+ 'ROUND' => array(
1665
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1666
+ 'functionCall' => 'round',
1667
+ 'argumentCount' => '2'
1668
+ ),
1669
+ 'ROUNDDOWN' => array(
1670
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1671
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDDOWN',
1672
+ 'argumentCount' => '2'
1673
+ ),
1674
+ 'ROUNDUP' => array(
1675
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1676
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::ROUNDUP',
1677
+ 'argumentCount' => '2'
1678
+ ),
1679
+ 'ROW' => array(
1680
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1681
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROW',
1682
+ 'argumentCount' => '-1',
1683
+ 'passByReference' => array(true)
1684
+ ),
1685
+ 'ROWS' => array(
1686
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1687
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::ROWS',
1688
+ 'argumentCount' => '1'
1689
+ ),
1690
+ 'RSQ' => array(
1691
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1692
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::RSQ',
1693
+ 'argumentCount' => '2'
1694
+ ),
1695
+ 'RTD' => array(
1696
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1697
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1698
+ 'argumentCount' => '1+'
1699
+ ),
1700
+ 'SEARCH' => array(
1701
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1702
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE',
1703
+ 'argumentCount' => '2,3'
1704
+ ),
1705
+ 'SEARCHB' => array(
1706
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1707
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SEARCHINSENSITIVE',
1708
+ 'argumentCount' => '2,3'
1709
+ ),
1710
+ 'SECOND' => array(
1711
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1712
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::SECONDOFMINUTE',
1713
+ 'argumentCount' => '1'
1714
+ ),
1715
+ 'SERIESSUM' => array(
1716
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1717
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SERIESSUM',
1718
+ 'argumentCount' => '4'
1719
+ ),
1720
+ 'SIGN' => array(
1721
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1722
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SIGN',
1723
+ 'argumentCount' => '1'
1724
+ ),
1725
+ 'SIN' => array(
1726
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1727
+ 'functionCall' => 'sin',
1728
+ 'argumentCount' => '1'
1729
+ ),
1730
+ 'SINH' => array(
1731
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1732
+ 'functionCall' => 'sinh',
1733
+ 'argumentCount' => '1'
1734
+ ),
1735
+ 'SKEW' => array(
1736
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1737
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::SKEW',
1738
+ 'argumentCount' => '1+'
1739
+ ),
1740
+ 'SLN' => array(
1741
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1742
+ 'functionCall' => 'PHPExcel_Calculation_Financial::SLN',
1743
+ 'argumentCount' => '3'
1744
+ ),
1745
+ 'SLOPE' => array(
1746
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1747
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::SLOPE',
1748
+ 'argumentCount' => '2'
1749
+ ),
1750
+ 'SMALL' => array(
1751
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1752
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::SMALL',
1753
+ 'argumentCount' => '2'
1754
+ ),
1755
+ 'SQRT' => array(
1756
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1757
+ 'functionCall' => 'sqrt',
1758
+ 'argumentCount' => '1'
1759
+ ),
1760
+ 'SQRTPI' => array(
1761
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1762
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SQRTPI',
1763
+ 'argumentCount' => '1'
1764
+ ),
1765
+ 'STANDARDIZE' => array(
1766
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1767
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STANDARDIZE',
1768
+ 'argumentCount' => '3'
1769
+ ),
1770
+ 'STDEV' => array(
1771
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1772
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEV',
1773
+ 'argumentCount' => '1+'
1774
+ ),
1775
+ 'STDEVA' => array(
1776
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1777
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVA',
1778
+ 'argumentCount' => '1+'
1779
+ ),
1780
+ 'STDEVP' => array(
1781
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1782
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVP',
1783
+ 'argumentCount' => '1+'
1784
+ ),
1785
+ 'STDEVPA' => array(
1786
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1787
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STDEVPA',
1788
+ 'argumentCount' => '1+'
1789
+ ),
1790
+ 'STEYX' => array(
1791
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1792
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::STEYX',
1793
+ 'argumentCount' => '2'
1794
+ ),
1795
+ 'SUBSTITUTE' => array(
1796
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1797
+ 'functionCall' => 'PHPExcel_Calculation_TextData::SUBSTITUTE',
1798
+ 'argumentCount' => '3,4'
1799
+ ),
1800
+ 'SUBTOTAL' => array(
1801
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1802
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUBTOTAL',
1803
+ 'argumentCount' => '2+'
1804
+ ),
1805
+ 'SUM' => array(
1806
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1807
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUM',
1808
+ 'argumentCount' => '1+'
1809
+ ),
1810
+ 'SUMIF' => array(
1811
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1812
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMIF',
1813
+ 'argumentCount' => '2,3'
1814
+ ),
1815
+ 'SUMIFS' => array(
1816
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1817
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMIFS',
1818
+ 'argumentCount' => '3+'
1819
+ ),
1820
+ 'SUMPRODUCT' => array(
1821
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1822
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMPRODUCT',
1823
+ 'argumentCount' => '1+'
1824
+ ),
1825
+ 'SUMSQ' => array(
1826
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1827
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMSQ',
1828
+ 'argumentCount' => '1+'
1829
+ ),
1830
+ 'SUMX2MY2' => array(
1831
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1832
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2MY2',
1833
+ 'argumentCount' => '2'
1834
+ ),
1835
+ 'SUMX2PY2' => array(
1836
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1837
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMX2PY2',
1838
+ 'argumentCount' => '2'
1839
+ ),
1840
+ 'SUMXMY2' => array(
1841
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1842
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::SUMXMY2',
1843
+ 'argumentCount' => '2'
1844
+ ),
1845
+ 'SYD' => array(
1846
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1847
+ 'functionCall' => 'PHPExcel_Calculation_Financial::SYD',
1848
+ 'argumentCount' => '4'
1849
+ ),
1850
+ 'T' => array(
1851
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1852
+ 'functionCall' => 'PHPExcel_Calculation_TextData::RETURNSTRING',
1853
+ 'argumentCount' => '1'
1854
+ ),
1855
+ 'TAN' => array(
1856
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1857
+ 'functionCall' => 'tan',
1858
+ 'argumentCount' => '1'
1859
+ ),
1860
+ 'TANH' => array(
1861
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1862
+ 'functionCall' => 'tanh',
1863
+ 'argumentCount' => '1'
1864
+ ),
1865
+ 'TBILLEQ' => array(
1866
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1867
+ 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLEQ',
1868
+ 'argumentCount' => '3'
1869
+ ),
1870
+ 'TBILLPRICE' => array(
1871
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1872
+ 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLPRICE',
1873
+ 'argumentCount' => '3'
1874
+ ),
1875
+ 'TBILLYIELD' => array(
1876
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1877
+ 'functionCall' => 'PHPExcel_Calculation_Financial::TBILLYIELD',
1878
+ 'argumentCount' => '3'
1879
+ ),
1880
+ 'TDIST' => array(
1881
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1882
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::TDIST',
1883
+ 'argumentCount' => '3'
1884
+ ),
1885
+ 'TEXT' => array(
1886
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1887
+ 'functionCall' => 'PHPExcel_Calculation_TextData::TEXTFORMAT',
1888
+ 'argumentCount' => '2'
1889
+ ),
1890
+ 'TIME' => array(
1891
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1892
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::TIME',
1893
+ 'argumentCount' => '3'
1894
+ ),
1895
+ 'TIMEVALUE' => array(
1896
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1897
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::TIMEVALUE',
1898
+ 'argumentCount' => '1'
1899
+ ),
1900
+ 'TINV' => array(
1901
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1902
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::TINV',
1903
+ 'argumentCount' => '2'
1904
+ ),
1905
+ 'TODAY' => array(
1906
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
1907
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DATENOW',
1908
+ 'argumentCount' => '0'
1909
+ ),
1910
+ 'TRANSPOSE' => array(
1911
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1912
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::TRANSPOSE',
1913
+ 'argumentCount' => '1'
1914
+ ),
1915
+ 'TREND' => array(
1916
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1917
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::TREND',
1918
+ 'argumentCount' => '1-4'
1919
+ ),
1920
+ 'TRIM' => array(
1921
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1922
+ 'functionCall' => 'PHPExcel_Calculation_TextData::TRIMSPACES',
1923
+ 'argumentCount' => '1'
1924
+ ),
1925
+ 'TRIMMEAN' => array(
1926
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1927
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::TRIMMEAN',
1928
+ 'argumentCount' => '2'
1929
+ ),
1930
+ 'TRUE' => array(
1931
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOGICAL,
1932
+ 'functionCall' => 'PHPExcel_Calculation_Logical::TRUE',
1933
+ 'argumentCount' => '0'
1934
+ ),
1935
+ 'TRUNC' => array(
1936
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_MATH_AND_TRIG,
1937
+ 'functionCall' => 'PHPExcel_Calculation_MathTrig::TRUNC',
1938
+ 'argumentCount' => '1,2'
1939
+ ),
1940
+ 'TTEST' => array(
1941
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1942
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1943
+ 'argumentCount' => '4'
1944
+ ),
1945
+ 'TYPE' => array(
1946
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1947
+ 'functionCall' => 'PHPExcel_Calculation_Functions::TYPE',
1948
+ 'argumentCount' => '1'
1949
+ ),
1950
+ 'UPPER' => array(
1951
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1952
+ 'functionCall' => 'PHPExcel_Calculation_TextData::UPPERCASE',
1953
+ 'argumentCount' => '1'
1954
+ ),
1955
+ 'USDOLLAR' => array(
1956
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1957
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1958
+ 'argumentCount' => '2'
1959
+ ),
1960
+ 'VALUE' => array(
1961
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_TEXT_AND_DATA,
1962
+ 'functionCall' => 'PHPExcel_Calculation_TextData::VALUE',
1963
+ 'argumentCount' => '1'
1964
+ ),
1965
+ 'VAR' => array(
1966
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1967
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::VARFunc',
1968
+ 'argumentCount' => '1+'
1969
+ ),
1970
+ 'VARA' => array(
1971
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1972
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::VARA',
1973
+ 'argumentCount' => '1+'
1974
+ ),
1975
+ 'VARP' => array(
1976
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1977
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::VARP',
1978
+ 'argumentCount' => '1+'
1979
+ ),
1980
+ 'VARPA' => array(
1981
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
1982
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::VARPA',
1983
+ 'argumentCount' => '1+'
1984
+ ),
1985
+ 'VDB' => array(
1986
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
1987
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
1988
+ 'argumentCount' => '5-7'
1989
+ ),
1990
+ 'VERSION' => array(
1991
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_INFORMATION,
1992
+ 'functionCall' => 'PHPExcel_Calculation_Functions::VERSION',
1993
+ 'argumentCount' => '0'
1994
+ ),
1995
+ 'VLOOKUP' => array(
1996
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_LOOKUP_AND_REFERENCE,
1997
+ 'functionCall' => 'PHPExcel_Calculation_LookupRef::VLOOKUP',
1998
+ 'argumentCount' => '3,4'
1999
+ ),
2000
+ 'WEEKDAY' => array(
2001
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
2002
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::DAYOFWEEK',
2003
+ 'argumentCount' => '1,2'
2004
+ ),
2005
+ 'WEEKNUM' => array(
2006
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
2007
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::WEEKOFYEAR',
2008
+ 'argumentCount' => '1,2'
2009
+ ),
2010
+ 'WEIBULL' => array(
2011
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
2012
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::WEIBULL',
2013
+ 'argumentCount' => '4'
2014
+ ),
2015
+ 'WORKDAY' => array(
2016
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
2017
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::WORKDAY',
2018
+ 'argumentCount' => '2+'
2019
+ ),
2020
+ 'XIRR' => array(
2021
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
2022
+ 'functionCall' => 'PHPExcel_Calculation_Financial::XIRR',
2023
+ 'argumentCount' => '2,3'
2024
+ ),
2025
+ 'XNPV' => array(
2026
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
2027
+ 'functionCall' => 'PHPExcel_Calculation_Financial::XNPV',
2028
+ 'argumentCount' => '3'
2029
+ ),
2030
+ 'YEAR' => array(
2031
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
2032
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::YEAR',
2033
+ 'argumentCount' => '1'
2034
+ ),
2035
+ 'YEARFRAC' => array(
2036
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_DATE_AND_TIME,
2037
+ 'functionCall' => 'PHPExcel_Calculation_DateTime::YEARFRAC',
2038
+ 'argumentCount' => '2,3'
2039
+ ),
2040
+ 'YIELD' => array(
2041
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
2042
+ 'functionCall' => 'PHPExcel_Calculation_Functions::DUMMY',
2043
+ 'argumentCount' => '6,7'
2044
+ ),
2045
+ 'YIELDDISC' => array(
2046
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
2047
+ 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDDISC',
2048
+ 'argumentCount' => '4,5'
2049
+ ),
2050
+ 'YIELDMAT' => array(
2051
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_FINANCIAL,
2052
+ 'functionCall' => 'PHPExcel_Calculation_Financial::YIELDMAT',
2053
+ 'argumentCount' => '5,6'
2054
+ ),
2055
+ 'ZTEST' => array(
2056
+ 'category' => PHPExcel_Calculation_Function::CATEGORY_STATISTICAL,
2057
+ 'functionCall' => 'PHPExcel_Calculation_Statistical::ZTEST',
2058
+ 'argumentCount' => '2-3'
2059
+ )
2060
+ );
2061
+
2062
+ // Internal functions used for special control purposes
2063
+ private static $controlFunctions = array(
2064
+ 'MKMATRIX' => array(
2065
+ 'argumentCount' => '*',
2066
+ 'functionCall' => 'self::mkMatrix'
2067
+ )
2068
+ );
2069
+
2070
+
2071
+ public function __construct(PHPExcel $workbook = null)
2072
+ {
2073
+ $this->delta = 1 * pow(10, 0 - ini_get('precision'));
2074
+
2075
+ $this->workbook = $workbook;
2076
+ $this->cyclicReferenceStack = new PHPExcel_CalcEngine_CyclicReferenceStack();
2077
+ $this->_debugLog = new PHPExcel_CalcEngine_Logger($this->cyclicReferenceStack);
2078
+ }
2079
+
2080
+
2081
+ private static function loadLocales()
2082
+ {
2083
+ $localeFileDirectory = PHPEXCEL_ROOT.'PHPExcel/locale/';
2084
+ foreach (glob($localeFileDirectory.'/*', GLOB_ONLYDIR) as $filename) {
2085
+ $filename = substr($filename, strlen($localeFileDirectory)+1);
2086
+ if ($filename != 'en') {
2087
+ self::$validLocaleLanguages[] = $filename;
2088
+ }
2089
+ }
2090
+ }
2091
+
2092
+ /**
2093
+ * Get an instance of this class
2094
+ *
2095
+ * @access public
2096
+ * @param PHPExcel $workbook Injected workbook for working with a PHPExcel object,
2097
+ * or NULL to create a standalone claculation engine
2098
+ * @return PHPExcel_Calculation
2099
+ */
2100
+ public static function getInstance(PHPExcel $workbook = null)
2101
+ {
2102
+ if ($workbook !== null) {
2103
+ $instance = $workbook->getCalculationEngine();
2104
+ if (isset($instance)) {
2105
+ return $instance;
2106
+ }
2107
+ }
2108
+
2109
+ if (!isset(self::$instance) || (self::$instance === null)) {
2110
+ self::$instance = new PHPExcel_Calculation();
2111
+ }
2112
+ return self::$instance;
2113
+ }
2114
+
2115
+ /**
2116
+ * Unset an instance of this class
2117
+ *
2118
+ * @access public
2119
+ */
2120
+ public function __destruct()
2121
+ {
2122
+ $this->workbook = null;
2123
+ }
2124
+
2125
+ /**
2126
+ * Flush the calculation cache for any existing instance of this class
2127
+ * but only if a PHPExcel_Calculation instance exists
2128
+ *
2129
+ * @access public
2130
+ * @return null
2131
+ */
2132
+ public function flushInstance()
2133
+ {
2134
+ $this->clearCalculationCache();
2135
+ }
2136
+
2137
+
2138
+ /**
2139
+ * Get the debuglog for this claculation engine instance
2140
+ *
2141
+ * @access public
2142
+ * @return PHPExcel_CalcEngine_Logger
2143
+ */
2144
+ public function getDebugLog()
2145
+ {
2146
+ return $this->_debugLog;
2147
+ }
2148
+
2149
+ /**
2150
+ * __clone implementation. Cloning should not be allowed in a Singleton!
2151
+ *
2152
+ * @access public
2153
+ * @throws PHPExcel_Calculation_Exception
2154
+ */
2155
+ final public function __clone()
2156
+ {
2157
+ throw new PHPExcel_Calculation_Exception('Cloning the calculation engine is not allowed!');
2158
+ }
2159
+
2160
+
2161
+ /**
2162
+ * Return the locale-specific translation of TRUE
2163
+ *
2164
+ * @access public
2165
+ * @return string locale-specific translation of TRUE
2166
+ */
2167
+ public static function getTRUE()
2168
+ {
2169
+ return self::$localeBoolean['TRUE'];
2170
+ }
2171
+
2172
+ /**
2173
+ * Return the locale-specific translation of FALSE
2174
+ *
2175
+ * @access public
2176
+ * @return string locale-specific translation of FALSE
2177
+ */
2178
+ public static function getFALSE()
2179
+ {
2180
+ return self::$localeBoolean['FALSE'];
2181
+ }
2182
+
2183
+ /**
2184
+ * Set the Array Return Type (Array or Value of first element in the array)
2185
+ *
2186
+ * @access public
2187
+ * @param string $returnType Array return type
2188
+ * @return boolean Success or failure
2189
+ */
2190
+ public static function setArrayReturnType($returnType)
2191
+ {
2192
+ if (($returnType == self::RETURN_ARRAY_AS_VALUE) ||
2193
+ ($returnType == self::RETURN_ARRAY_AS_ERROR) ||
2194
+ ($returnType == self::RETURN_ARRAY_AS_ARRAY)) {
2195
+ self::$returnArrayAsType = $returnType;
2196
+ return true;
2197
+ }
2198
+ return false;
2199
+ }
2200
+
2201
+
2202
+ /**
2203
+ * Return the Array Return Type (Array or Value of first element in the array)
2204
+ *
2205
+ * @access public
2206
+ * @return string $returnType Array return type
2207
+ */
2208
+ public static function getArrayReturnType()
2209
+ {
2210
+ return self::$returnArrayAsType;
2211
+ }
2212
+
2213
+
2214
+ /**
2215
+ * Is calculation caching enabled?
2216
+ *
2217
+ * @access public
2218
+ * @return boolean
2219
+ */
2220
+ public function getCalculationCacheEnabled()
2221
+ {
2222
+ return $this->calculationCacheEnabled;
2223
+ }
2224
+
2225
+ /**
2226
+ * Enable/disable calculation cache
2227
+ *
2228
+ * @access public
2229
+ * @param boolean $pValue
2230
+ */
2231
+ public function setCalculationCacheEnabled($pValue = true)
2232
+ {
2233
+ $this->calculationCacheEnabled = $pValue;
2234
+ $this->clearCalculationCache();
2235
+ }
2236
+
2237
+
2238
+ /**
2239
+ * Enable calculation cache
2240
+ */
2241
+ public function enableCalculationCache()
2242
+ {
2243
+ $this->setCalculationCacheEnabled(true);
2244
+ }
2245
+
2246
+
2247
+ /**
2248
+ * Disable calculation cache
2249
+ */
2250
+ public function disableCalculationCache()
2251
+ {
2252
+ $this->setCalculationCacheEnabled(false);
2253
+ }
2254
+
2255
+
2256
+ /**
2257
+ * Clear calculation cache
2258
+ */
2259
+ public function clearCalculationCache()
2260
+ {
2261
+ $this->calculationCache = array();
2262
+ }
2263
+
2264
+ /**
2265
+ * Clear calculation cache for a specified worksheet
2266
+ *
2267
+ * @param string $worksheetName
2268
+ */
2269
+ public function clearCalculationCacheForWorksheet($worksheetName)
2270
+ {
2271
+ if (isset($this->calculationCache[$worksheetName])) {
2272
+ unset($this->calculationCache[$worksheetName]);
2273
+ }
2274
+ }
2275
+
2276
+ /**
2277
+ * Rename calculation cache for a specified worksheet
2278
+ *
2279
+ * @param string $fromWorksheetName
2280
+ * @param string $toWorksheetName
2281
+ */
2282
+ public function renameCalculationCacheForWorksheet($fromWorksheetName, $toWorksheetName)
2283
+ {
2284
+ if (isset($this->calculationCache[$fromWorksheetName])) {
2285
+ $this->calculationCache[$toWorksheetName] = &$this->calculationCache[$fromWorksheetName];
2286
+ unset($this->calculationCache[$fromWorksheetName]);
2287
+ }
2288
+ }
2289
+
2290
+
2291
+ /**
2292
+ * Get the currently defined locale code
2293
+ *
2294
+ * @return string
2295
+ */
2296
+ public function getLocale()
2297
+ {
2298
+ return self::$localeLanguage;
2299
+ }
2300
+
2301
+
2302
+ /**
2303
+ * Set the locale code
2304
+ *
2305
+ * @param string $locale The locale to use for formula translation
2306
+ * @return boolean
2307
+ */
2308
+ public function setLocale($locale = 'en_us')
2309
+ {
2310
+ // Identify our locale and language
2311
+ $language = $locale = strtolower($locale);
2312
+ if (strpos($locale, '_') !== false) {
2313
+ list($language) = explode('_', $locale);
2314
+ }
2315
+
2316
+ if (count(self::$validLocaleLanguages) == 1) {
2317
+ self::loadLocales();
2318
+ }
2319
+ // Test whether we have any language data for this language (any locale)
2320
+ if (in_array($language, self::$validLocaleLanguages)) {
2321
+ // initialise language/locale settings
2322
+ self::$localeFunctions = array();
2323
+ self::$localeArgumentSeparator = ',';
2324
+ self::$localeBoolean = array('TRUE' => 'TRUE', 'FALSE' => 'FALSE', 'NULL' => 'NULL');
2325
+ // Default is English, if user isn't requesting english, then read the necessary data from the locale files
2326
+ if ($locale != 'en_us') {
2327
+ // Search for a file with a list of function names for locale
2328
+ $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $locale).DIRECTORY_SEPARATOR.'functions';
2329
+ if (!file_exists($functionNamesFile)) {
2330
+ // If there isn't a locale specific function file, look for a language specific function file
2331
+ $functionNamesFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'functions';
2332
+ if (!file_exists($functionNamesFile)) {
2333
+ return false;
2334
+ }
2335
+ }
2336
+ // Retrieve the list of locale or language specific function names
2337
+ $localeFunctions = file($functionNamesFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2338
+ foreach ($localeFunctions as $localeFunction) {
2339
+ list($localeFunction) = explode('##', $localeFunction); // Strip out comments
2340
+ if (strpos($localeFunction, '=') !== false) {
2341
+ list($fName, $lfName) = explode('=', $localeFunction);
2342
+ $fName = trim($fName);
2343
+ $lfName = trim($lfName);
2344
+ if ((isset(self::$PHPExcelFunctions[$fName])) && ($lfName != '') && ($fName != $lfName)) {
2345
+ self::$localeFunctions[$fName] = $lfName;
2346
+ }
2347
+ }
2348
+ }
2349
+ // Default the TRUE and FALSE constants to the locale names of the TRUE() and FALSE() functions
2350
+ if (isset(self::$localeFunctions['TRUE'])) {
2351
+ self::$localeBoolean['TRUE'] = self::$localeFunctions['TRUE'];
2352
+ }
2353
+ if (isset(self::$localeFunctions['FALSE'])) {
2354
+ self::$localeBoolean['FALSE'] = self::$localeFunctions['FALSE'];
2355
+ }
2356
+
2357
+ $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.str_replace('_', DIRECTORY_SEPARATOR, $locale).DIRECTORY_SEPARATOR.'config';
2358
+ if (!file_exists($configFile)) {
2359
+ $configFile = PHPEXCEL_ROOT . 'PHPExcel'.DIRECTORY_SEPARATOR.'locale'.DIRECTORY_SEPARATOR.$language.DIRECTORY_SEPARATOR.'config';
2360
+ }
2361
+ if (file_exists($configFile)) {
2362
+ $localeSettings = file($configFile, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
2363
+ foreach ($localeSettings as $localeSetting) {
2364
+ list($localeSetting) = explode('##', $localeSetting); // Strip out comments
2365
+ if (strpos($localeSetting, '=') !== false) {
2366
+ list($settingName, $settingValue) = explode('=', $localeSetting);
2367
+ $settingName = strtoupper(trim($settingName));
2368
+ switch ($settingName) {
2369
+ case 'ARGUMENTSEPARATOR':
2370
+ self::$localeArgumentSeparator = trim($settingValue);
2371
+ break;
2372
+ }
2373
+ }
2374
+ }
2375
+ }
2376
+ }
2377
+
2378
+ self::$functionReplaceFromExcel = self::$functionReplaceToExcel =
2379
+ self::$functionReplaceFromLocale = self::$functionReplaceToLocale = null;
2380
+ self::$localeLanguage = $locale;
2381
+ return true;
2382
+ }
2383
+ return false;
2384
+ }
2385
+
2386
+
2387
+
2388
+ public static function translateSeparator($fromSeparator, $toSeparator, $formula, &$inBraces)
2389
+ {
2390
+ $strlen = mb_strlen($formula);
2391
+ for ($i = 0; $i < $strlen; ++$i) {
2392
+ $chr = mb_substr($formula, $i, 1);
2393
+ switch ($chr) {
2394
+ case '{':
2395
+ $inBraces = true;
2396
+ break;
2397
+ case '}':
2398
+ $inBraces = false;
2399
+ break;
2400
+ case $fromSeparator:
2401
+ if (!$inBraces) {
2402
+ $formula = mb_substr($formula, 0, $i).$toSeparator.mb_substr($formula, $i+1);
2403
+ }
2404
+ }
2405
+ }
2406
+ return $formula;
2407
+ }
2408
+
2409
+ private static function translateFormula($from, $to, $formula, $fromSeparator, $toSeparator)
2410
+ {
2411
+ // Convert any Excel function names to the required language
2412
+ if (self::$localeLanguage !== 'en_us') {
2413
+ $inBraces = false;
2414
+ // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
2415
+ if (strpos($formula, '"') !== false) {
2416
+ // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
2417
+ // the formula
2418
+ $temp = explode('"', $formula);
2419
+ $i = false;
2420
+ foreach ($temp as &$value) {
2421
+ // Only count/replace in alternating array entries
2422
+ if ($i = !$i) {
2423
+ $value = preg_replace($from, $to, $value);
2424
+ $value = self::translateSeparator($fromSeparator, $toSeparator, $value, $inBraces);
2425
+ }
2426
+ }
2427
+ unset($value);
2428
+ // Then rebuild the formula string
2429
+ $formula = implode('"', $temp);
2430
+ } else {
2431
+ // If there's no quoted strings, then we do a simple count/replace
2432
+ $formula = preg_replace($from, $to, $formula);
2433
+ $formula = self::translateSeparator($fromSeparator, $toSeparator, $formula, $inBraces);
2434
+ }
2435
+ }
2436
+
2437
+ return $formula;
2438
+ }
2439
+
2440
+ private static $functionReplaceFromExcel = null;
2441
+ private static $functionReplaceToLocale = null;
2442
+
2443
+ public function _translateFormulaToLocale($formula)
2444
+ {
2445
+ if (self::$functionReplaceFromExcel === null) {
2446
+ self::$functionReplaceFromExcel = array();
2447
+ foreach (array_keys(self::$localeFunctions) as $excelFunctionName) {
2448
+ self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelFunctionName).'([\s]*\()/Ui';
2449
+ }
2450
+ foreach (array_keys(self::$localeBoolean) as $excelBoolean) {
2451
+ self::$functionReplaceFromExcel[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
2452
+ }
2453
+
2454
+ }
2455
+
2456
+ if (self::$functionReplaceToLocale === null) {
2457
+ self::$functionReplaceToLocale = array();
2458
+ foreach (array_values(self::$localeFunctions) as $localeFunctionName) {
2459
+ self::$functionReplaceToLocale[] = '$1'.trim($localeFunctionName).'$2';
2460
+ }
2461
+ foreach (array_values(self::$localeBoolean) as $localeBoolean) {
2462
+ self::$functionReplaceToLocale[] = '$1'.trim($localeBoolean).'$2';
2463
+ }
2464
+ }
2465
+
2466
+ return self::translateFormula(self::$functionReplaceFromExcel, self::$functionReplaceToLocale, $formula, ',', self::$localeArgumentSeparator);
2467
+ }
2468
+
2469
+
2470
+ private static $functionReplaceFromLocale = null;
2471
+ private static $functionReplaceToExcel = null;
2472
+
2473
+ public function _translateFormulaToEnglish($formula)
2474
+ {
2475
+ if (self::$functionReplaceFromLocale === null) {
2476
+ self::$functionReplaceFromLocale = array();
2477
+ foreach (array_values(self::$localeFunctions) as $localeFunctionName) {
2478
+ self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($localeFunctionName).'([\s]*\()/Ui';
2479
+ }
2480
+ foreach (array_values(self::$localeBoolean) as $excelBoolean) {
2481
+ self::$functionReplaceFromLocale[] = '/(@?[^\w\.])'.preg_quote($excelBoolean).'([^\w\.])/Ui';
2482
+ }
2483
+ }
2484
+
2485
+ if (self::$functionReplaceToExcel === null) {
2486
+ self::$functionReplaceToExcel = array();
2487
+ foreach (array_keys(self::$localeFunctions) as $excelFunctionName) {
2488
+ self::$functionReplaceToExcel[] = '$1'.trim($excelFunctionName).'$2';
2489
+ }
2490
+ foreach (array_keys(self::$localeBoolean) as $excelBoolean) {
2491
+ self::$functionReplaceToExcel[] = '$1'.trim($excelBoolean).'$2';
2492
+ }
2493
+ }
2494
+
2495
+ return self::translateFormula(self::$functionReplaceFromLocale, self::$functionReplaceToExcel, $formula, self::$localeArgumentSeparator, ',');
2496
+ }
2497
+
2498
+
2499
+ public static function localeFunc($function)
2500
+ {
2501
+ if (self::$localeLanguage !== 'en_us') {
2502
+ $functionName = trim($function, '(');
2503
+ if (isset(self::$localeFunctions[$functionName])) {
2504
+ $brace = ($functionName != $function);
2505
+ $function = self::$localeFunctions[$functionName];
2506
+ if ($brace) {
2507
+ $function .= '(';
2508
+ }
2509
+ }
2510
+ }
2511
+ return $function;
2512
+ }
2513
+
2514
+
2515
+
2516
+
2517
+ /**
2518
+ * Wrap string values in quotes
2519
+ *
2520
+ * @param mixed $value
2521
+ * @return mixed
2522
+ */
2523
+ public static function wrapResult($value)
2524
+ {
2525
+ if (is_string($value)) {
2526
+ // Error values cannot be "wrapped"
2527
+ if (preg_match('/^'.self::CALCULATION_REGEXP_ERROR.'$/i', $value, $match)) {
2528
+ // Return Excel errors "as is"
2529
+ return $value;
2530
+ }
2531
+ // Return strings wrapped in quotes
2532
+ return '"'.$value.'"';
2533
+ // Convert numeric errors to NaN error
2534
+ } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
2535
+ return PHPExcel_Calculation_Functions::NaN();
2536
+ }
2537
+
2538
+ return $value;
2539
+ }
2540
+
2541
+
2542
+ /**
2543
+ * Remove quotes used as a wrapper to identify string values
2544
+ *
2545
+ * @param mixed $value
2546
+ * @return mixed
2547
+ */
2548
+ public static function unwrapResult($value)
2549
+ {
2550
+ if (is_string($value)) {
2551
+ if ((isset($value{0})) && ($value{0} == '"') && (substr($value, -1) == '"')) {
2552
+ return substr($value, 1, -1);
2553
+ }
2554
+ // Convert numeric errors to NaN error
2555
+ } elseif ((is_float($value)) && ((is_nan($value)) || (is_infinite($value)))) {
2556
+ return PHPExcel_Calculation_Functions::NaN();
2557
+ }
2558
+ return $value;
2559
+ }
2560
+
2561
+
2562
+
2563
+
2564
+ /**
2565
+ * Calculate cell value (using formula from a cell ID)
2566
+ * Retained for backward compatibility
2567
+ *
2568
+ * @access public
2569
+ * @param PHPExcel_Cell $pCell Cell to calculate
2570
+ * @return mixed
2571
+ * @throws PHPExcel_Calculation_Exception
2572
+ */
2573
+ public function calculate(PHPExcel_Cell $pCell = null)
2574
+ {
2575
+ try {
2576
+ return $this->calculateCellValue($pCell);
2577
+ } catch (PHPExcel_Exception $e) {
2578
+ throw new PHPExcel_Calculation_Exception($e->getMessage());
2579
+ }
2580
+ }
2581
+
2582
+
2583
+ /**
2584
+ * Calculate the value of a cell formula
2585
+ *
2586
+ * @access public
2587
+ * @param PHPExcel_Cell $pCell Cell to calculate
2588
+ * @param Boolean $resetLog Flag indicating whether the debug log should be reset or not
2589
+ * @return mixed
2590
+ * @throws PHPExcel_Calculation_Exception
2591
+ */
2592
+ public function calculateCellValue(PHPExcel_Cell $pCell = null, $resetLog = true)
2593
+ {
2594
+ if ($pCell === null) {
2595
+ return null;
2596
+ }
2597
+
2598
+ $returnArrayAsType = self::$returnArrayAsType;
2599
+ if ($resetLog) {
2600
+ // Initialise the logging settings if requested
2601
+ $this->formulaError = null;
2602
+ $this->_debugLog->clearLog();
2603
+ $this->cyclicReferenceStack->clear();
2604
+ $this->cyclicFormulaCounter = 1;
2605
+
2606
+ self::$returnArrayAsType = self::RETURN_ARRAY_AS_ARRAY;
2607
+ }
2608
+
2609
+ // Execute the calculation for the cell formula
2610
+ $this->cellStack[] = array(
2611
+ 'sheet' => $pCell->getWorksheet()->getTitle(),
2612
+ 'cell' => $pCell->getCoordinate(),
2613
+ );
2614
+ try {
2615
+ $result = self::unwrapResult($this->_calculateFormulaValue($pCell->getValue(), $pCell->getCoordinate(), $pCell));
2616
+ $cellAddress = array_pop($this->cellStack);
2617
+ $this->workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']);
2618
+ } catch (PHPExcel_Exception $e) {
2619
+ $cellAddress = array_pop($this->cellStack);
2620
+ $this->workbook->getSheetByName($cellAddress['sheet'])->getCell($cellAddress['cell']);
2621
+ throw new PHPExcel_Calculation_Exception($e->getMessage());
2622
+ }
2623
+
2624
+ if ((is_array($result)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
2625
+ self::$returnArrayAsType = $returnArrayAsType;
2626
+ $testResult = PHPExcel_Calculation_Functions::flattenArray($result);
2627
+ if (self::$returnArrayAsType == self::RETURN_ARRAY_AS_ERROR) {
2628
+ return PHPExcel_Calculation_Functions::VALUE();
2629
+ }
2630
+ // If there's only a single cell in the array, then we allow it
2631
+ if (count($testResult) != 1) {
2632
+ // If keys are numeric, then it's a matrix result rather than a cell range result, so we permit it
2633
+ $r = array_keys($result);
2634
+ $r = array_shift($r);
2635
+ if (!is_numeric($r)) {
2636
+ return PHPExcel_Calculation_Functions::VALUE();
2637
+ }
2638
+ if (is_array($result[$r])) {
2639
+ $c = array_keys($result[$r]);
2640
+ $c = array_shift($c);
2641
+ if (!is_numeric($c)) {
2642
+ return PHPExcel_Calculation_Functions::VALUE();
2643
+ }
2644
+ }
2645
+ }
2646
+ $result = array_shift($testResult);
2647
+ }
2648
+ self::$returnArrayAsType = $returnArrayAsType;
2649
+
2650
+
2651
+ if ($result === null) {
2652
+ return 0;
2653
+ } elseif ((is_float($result)) && ((is_nan($result)) || (is_infinite($result)))) {
2654
+ return PHPExcel_Calculation_Functions::NaN();
2655
+ }
2656
+ return $result;
2657
+ }
2658
+
2659
+
2660
+ /**
2661
+ * Validate and parse a formula string
2662
+ *
2663
+ * @param string $formula Formula to parse
2664
+ * @return array
2665
+ * @throws PHPExcel_Calculation_Exception
2666
+ */
2667
+ public function parseFormula($formula)
2668
+ {
2669
+ // Basic validation that this is indeed a formula
2670
+ // We return an empty array if not
2671
+ $formula = trim($formula);
2672
+ if ((!isset($formula{0})) || ($formula{0} != '=')) {
2673
+ return array();
2674
+ }
2675
+ $formula = ltrim(substr($formula, 1));
2676
+ if (!isset($formula{0})) {
2677
+ return array();
2678
+ }
2679
+
2680
+ // Parse the formula and return the token stack
2681
+ return $this->_parseFormula($formula);
2682
+ }
2683
+
2684
+
2685
+ /**
2686
+ * Calculate the value of a formula
2687
+ *
2688
+ * @param string $formula Formula to parse
2689
+ * @param string $cellID Address of the cell to calculate
2690
+ * @param PHPExcel_Cell $pCell Cell to calculate
2691
+ * @return mixed
2692
+ * @throws PHPExcel_Calculation_Exception
2693
+ */
2694
+ public function calculateFormula($formula, $cellID = null, PHPExcel_Cell $pCell = null)
2695
+ {
2696
+ // Initialise the logging settings
2697
+ $this->formulaError = null;
2698
+ $this->_debugLog->clearLog();
2699
+ $this->cyclicReferenceStack->clear();
2700
+
2701
+ if ($this->workbook !== null && $cellID === null && $pCell === null) {
2702
+ $cellID = 'A1';
2703
+ $pCell = $this->workbook->getActiveSheet()->getCell($cellID);
2704
+ } else {
2705
+ // Disable calculation cacheing because it only applies to cell calculations, not straight formulae
2706
+ // But don't actually flush any cache
2707
+ $resetCache = $this->getCalculationCacheEnabled();
2708
+ $this->calculationCacheEnabled = false;
2709
+ }
2710
+
2711
+ // Execute the calculation
2712
+ try {
2713
+ $result = self::unwrapResult($this->_calculateFormulaValue($formula, $cellID, $pCell));
2714
+ } catch (PHPExcel_Exception $e) {
2715
+ throw new PHPExcel_Calculation_Exception($e->getMessage());
2716
+ }
2717
+
2718
+ if ($this->workbook === null) {
2719
+ // Reset calculation cacheing to its previous state
2720
+ $this->calculationCacheEnabled = $resetCache;
2721
+ }
2722
+
2723
+ return $result;
2724
+ }
2725
+
2726
+
2727
+ public function getValueFromCache($cellReference, &$cellValue)
2728
+ {
2729
+ // Is calculation cacheing enabled?
2730
+ // Is the value present in calculation cache?
2731
+ $this->_debugLog->writeDebugLog('Testing cache value for cell ', $cellReference);
2732
+ if (($this->calculationCacheEnabled) && (isset($this->calculationCache[$cellReference]))) {
2733
+ $this->_debugLog->writeDebugLog('Retrieving value for cell ', $cellReference, ' from cache');
2734
+ // Return the cached result
2735
+ $cellValue = $this->calculationCache[$cellReference];
2736
+ return true;
2737
+ }
2738
+ return false;
2739
+ }
2740
+
2741
+ public function saveValueToCache($cellReference, $cellValue)
2742
+ {
2743
+ if ($this->calculationCacheEnabled) {
2744
+ $this->calculationCache[$cellReference] = $cellValue;
2745
+ }
2746
+ }
2747
+
2748
+ /**
2749
+ * Parse a cell formula and calculate its value
2750
+ *
2751
+ * @param string $formula The formula to parse and calculate
2752
+ * @param string $cellID The ID (e.g. A3) of the cell that we are calculating
2753
+ * @param PHPExcel_Cell $pCell Cell to calculate
2754
+ * @return mixed
2755
+ * @throws PHPExcel_Calculation_Exception
2756
+ */
2757
+ public function _calculateFormulaValue($formula, $cellID = null, PHPExcel_Cell $pCell = null)
2758
+ {
2759
+ $cellValue = null;
2760
+
2761
+ // Basic validation that this is indeed a formula
2762
+ // We simply return the cell value if not
2763
+ $formula = trim($formula);
2764
+ if ($formula{0} != '=') {
2765
+ return self::wrapResult($formula);
2766
+ }
2767
+ $formula = ltrim(substr($formula, 1));
2768
+ if (!isset($formula{0})) {
2769
+ return self::wrapResult($formula);
2770
+ }
2771
+
2772
+ $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null;
2773
+ $wsTitle = ($pCellParent !== null) ? $pCellParent->getTitle() : "\x00Wrk";
2774
+ $wsCellReference = $wsTitle . '!' . $cellID;
2775
+
2776
+ if (($cellID !== null) && ($this->getValueFromCache($wsCellReference, $cellValue))) {
2777
+ return $cellValue;
2778
+ }
2779
+
2780
+ if (($wsTitle{0} !== "\x00") && ($this->cyclicReferenceStack->onStack($wsCellReference))) {
2781
+ if ($this->cyclicFormulaCount <= 0) {
2782
+ $this->cyclicFormulaCell = '';
2783
+ return $this->raiseFormulaError('Cyclic Reference in Formula');
2784
+ } elseif ($this->cyclicFormulaCell === $wsCellReference) {
2785
+ ++$this->cyclicFormulaCounter;
2786
+ if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
2787
+ $this->cyclicFormulaCell = '';
2788
+ return $cellValue;
2789
+ }
2790
+ } elseif ($this->cyclicFormulaCell == '') {
2791
+ if ($this->cyclicFormulaCounter >= $this->cyclicFormulaCount) {
2792
+ return $cellValue;
2793
+ }
2794
+ $this->cyclicFormulaCell = $wsCellReference;
2795
+ }
2796
+ }
2797
+
2798
+ // Parse the formula onto the token stack and calculate the value
2799
+ $this->cyclicReferenceStack->push($wsCellReference);
2800
+ $cellValue = $this->processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
2801
+ $this->cyclicReferenceStack->pop();
2802
+
2803
+ // Save to calculation cache
2804
+ if ($cellID !== null) {
2805
+ $this->saveValueToCache($wsCellReference, $cellValue);
2806
+ }
2807
+
2808
+ // Return the calculated value
2809
+ return $cellValue;
2810
+ }
2811
+
2812
+
2813
+ /**
2814
+ * Ensure that paired matrix operands are both matrices and of the same size
2815
+ *
2816
+ * @param mixed &$operand1 First matrix operand
2817
+ * @param mixed &$operand2 Second matrix operand
2818
+ * @param integer $resize Flag indicating whether the matrices should be resized to match
2819
+ * and (if so), whether the smaller dimension should grow or the
2820
+ * larger should shrink.
2821
+ * 0 = no resize
2822
+ * 1 = shrink to fit
2823
+ * 2 = extend to fit
2824
+ */
2825
+ private static function checkMatrixOperands(&$operand1, &$operand2, $resize = 1)
2826
+ {
2827
+ // Examine each of the two operands, and turn them into an array if they aren't one already
2828
+ // Note that this function should only be called if one or both of the operand is already an array
2829
+ if (!is_array($operand1)) {
2830
+ list($matrixRows, $matrixColumns) = self::getMatrixDimensions($operand2);
2831
+ $operand1 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand1));
2832
+ $resize = 0;
2833
+ } elseif (!is_array($operand2)) {
2834
+ list($matrixRows, $matrixColumns) = self::getMatrixDimensions($operand1);
2835
+ $operand2 = array_fill(0, $matrixRows, array_fill(0, $matrixColumns, $operand2));
2836
+ $resize = 0;
2837
+ }
2838
+
2839
+ list($matrix1Rows, $matrix1Columns) = self::getMatrixDimensions($operand1);
2840
+ list($matrix2Rows, $matrix2Columns) = self::getMatrixDimensions($operand2);
2841
+ if (($matrix1Rows == $matrix2Columns) && ($matrix2Rows == $matrix1Columns)) {
2842
+ $resize = 1;
2843
+ }
2844
+
2845
+ if ($resize == 2) {
2846
+ // Given two matrices of (potentially) unequal size, convert the smaller in each dimension to match the larger
2847
+ self::resizeMatricesExtend($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
2848
+ } elseif ($resize == 1) {
2849
+ // Given two matrices of (potentially) unequal size, convert the larger in each dimension to match the smaller
2850
+ self::resizeMatricesShrink($operand1, $operand2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
2851
+ }
2852
+ return array( $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns);
2853
+ }
2854
+
2855
+
2856
+ /**
2857
+ * Read the dimensions of a matrix, and re-index it with straight numeric keys starting from row 0, column 0
2858
+ *
2859
+ * @param mixed &$matrix matrix operand
2860
+ * @return array An array comprising the number of rows, and number of columns
2861
+ */
2862
+ private static function getMatrixDimensions(&$matrix)
2863
+ {
2864
+ $matrixRows = count($matrix);
2865
+ $matrixColumns = 0;
2866
+ foreach ($matrix as $rowKey => $rowValue) {
2867
+ $matrixColumns = max(count($rowValue), $matrixColumns);
2868
+ if (!is_array($rowValue)) {
2869
+ $matrix[$rowKey] = array($rowValue);
2870
+ } else {
2871
+ $matrix[$rowKey] = array_values($rowValue);
2872
+ }
2873
+ }
2874
+ $matrix = array_values($matrix);
2875
+ return array($matrixRows, $matrixColumns);
2876
+ }
2877
+
2878
+
2879
+ /**
2880
+ * Ensure that paired matrix operands are both matrices of the same size
2881
+ *
2882
+ * @param mixed &$matrix1 First matrix operand
2883
+ * @param mixed &$matrix2 Second matrix operand
2884
+ * @param integer $matrix1Rows Row size of first matrix operand
2885
+ * @param integer $matrix1Columns Column size of first matrix operand
2886
+ * @param integer $matrix2Rows Row size of second matrix operand
2887
+ * @param integer $matrix2Columns Column size of second matrix operand
2888
+ */
2889
+ private static function resizeMatricesShrink(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns)
2890
+ {
2891
+ if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
2892
+ if ($matrix2Rows < $matrix1Rows) {
2893
+ for ($i = $matrix2Rows; $i < $matrix1Rows; ++$i) {
2894
+ unset($matrix1[$i]);
2895
+ }
2896
+ }
2897
+ if ($matrix2Columns < $matrix1Columns) {
2898
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
2899
+ for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
2900
+ unset($matrix1[$i][$j]);
2901
+ }
2902
+ }
2903
+ }
2904
+ }
2905
+
2906
+ if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
2907
+ if ($matrix1Rows < $matrix2Rows) {
2908
+ for ($i = $matrix1Rows; $i < $matrix2Rows; ++$i) {
2909
+ unset($matrix2[$i]);
2910
+ }
2911
+ }
2912
+ if ($matrix1Columns < $matrix2Columns) {
2913
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
2914
+ for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
2915
+ unset($matrix2[$i][$j]);
2916
+ }
2917
+ }
2918
+ }
2919
+ }
2920
+ }
2921
+
2922
+
2923
+ /**
2924
+ * Ensure that paired matrix operands are both matrices of the same size
2925
+ *
2926
+ * @param mixed &$matrix1 First matrix operand
2927
+ * @param mixed &$matrix2 Second matrix operand
2928
+ * @param integer $matrix1Rows Row size of first matrix operand
2929
+ * @param integer $matrix1Columns Column size of first matrix operand
2930
+ * @param integer $matrix2Rows Row size of second matrix operand
2931
+ * @param integer $matrix2Columns Column size of second matrix operand
2932
+ */
2933
+ private static function resizeMatricesExtend(&$matrix1, &$matrix2, $matrix1Rows, $matrix1Columns, $matrix2Rows, $matrix2Columns)
2934
+ {
2935
+ if (($matrix2Columns < $matrix1Columns) || ($matrix2Rows < $matrix1Rows)) {
2936
+ if ($matrix2Columns < $matrix1Columns) {
2937
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
2938
+ $x = $matrix2[$i][$matrix2Columns-1];
2939
+ for ($j = $matrix2Columns; $j < $matrix1Columns; ++$j) {
2940
+ $matrix2[$i][$j] = $x;
2941
+ }
2942
+ }
2943
+ }
2944
+ if ($matrix2Rows < $matrix1Rows) {
2945
+ $x = $matrix2[$matrix2Rows-1];
2946
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
2947
+ $matrix2[$i] = $x;
2948
+ }
2949
+ }
2950
+ }
2951
+
2952
+ if (($matrix1Columns < $matrix2Columns) || ($matrix1Rows < $matrix2Rows)) {
2953
+ if ($matrix1Columns < $matrix2Columns) {
2954
+ for ($i = 0; $i < $matrix1Rows; ++$i) {
2955
+ $x = $matrix1[$i][$matrix1Columns-1];
2956
+ for ($j = $matrix1Columns; $j < $matrix2Columns; ++$j) {
2957
+ $matrix1[$i][$j] = $x;
2958
+ }
2959
+ }
2960
+ }
2961
+ if ($matrix1Rows < $matrix2Rows) {
2962
+ $x = $matrix1[$matrix1Rows-1];
2963
+ for ($i = 0; $i < $matrix2Rows; ++$i) {
2964
+ $matrix1[$i] = $x;
2965
+ }
2966
+ }
2967
+ }
2968
+ }
2969
+
2970
+
2971
+ /**
2972
+ * Format details of an operand for display in the log (based on operand type)
2973
+ *
2974
+ * @param mixed $value First matrix operand
2975
+ * @return mixed
2976
+ */
2977
+ private function showValue($value)
2978
+ {
2979
+ if ($this->_debugLog->getWriteDebugLog()) {
2980
+ $testArray = PHPExcel_Calculation_Functions::flattenArray($value);
2981
+ if (count($testArray) == 1) {
2982
+ $value = array_pop($testArray);
2983
+ }
2984
+
2985
+ if (is_array($value)) {
2986
+ $returnMatrix = array();
2987
+ $pad = $rpad = ', ';
2988
+ foreach ($value as $row) {
2989
+ if (is_array($row)) {
2990
+ $returnMatrix[] = implode($pad, array_map(array($this, 'showValue'), $row));
2991
+ $rpad = '; ';
2992
+ } else {
2993
+ $returnMatrix[] = $this->showValue($row);
2994
+ }
2995
+ }
2996
+ return '{ '.implode($rpad, $returnMatrix).' }';
2997
+ } elseif (is_string($value) && (trim($value, '"') == $value)) {
2998
+ return '"'.$value.'"';
2999
+ } elseif (is_bool($value)) {
3000
+ return ($value) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
3001
+ }
3002
+ }
3003
+ return PHPExcel_Calculation_Functions::flattenSingleValue($value);
3004
+ }
3005
+
3006
+
3007
+ /**
3008
+ * Format type and details of an operand for display in the log (based on operand type)
3009
+ *
3010
+ * @param mixed $value First matrix operand
3011
+ * @return mixed
3012
+ */
3013
+ private function showTypeDetails($value)
3014
+ {
3015
+ if ($this->_debugLog->getWriteDebugLog()) {
3016
+ $testArray = PHPExcel_Calculation_Functions::flattenArray($value);
3017
+ if (count($testArray) == 1) {
3018
+ $value = array_pop($testArray);
3019
+ }
3020
+
3021
+ if ($value === null) {
3022
+ return 'a NULL value';
3023
+ } elseif (is_float($value)) {
3024
+ $typeString = 'a floating point number';
3025
+ } elseif (is_int($value)) {
3026
+ $typeString = 'an integer number';
3027
+ } elseif (is_bool($value)) {
3028
+ $typeString = 'a boolean';
3029
+ } elseif (is_array($value)) {
3030
+ $typeString = 'a matrix';
3031
+ } else {
3032
+ if ($value == '') {
3033
+ return 'an empty string';
3034
+ } elseif ($value{0} == '#') {
3035
+ return 'a '.$value.' error';
3036
+ } else {
3037
+ $typeString = 'a string';
3038
+ }
3039
+ }
3040
+ return $typeString.' with a value of '.$this->showValue($value);
3041
+ }
3042
+ }
3043
+
3044
+
3045
+ private function convertMatrixReferences($formula)
3046
+ {
3047
+ static $matrixReplaceFrom = array('{', ';', '}');
3048
+ static $matrixReplaceTo = array('MKMATRIX(MKMATRIX(', '),MKMATRIX(', '))');
3049
+
3050
+ // Convert any Excel matrix references to the MKMATRIX() function
3051
+ if (strpos($formula, '{') !== false) {
3052
+ // If there is the possibility of braces within a quoted string, then we don't treat those as matrix indicators
3053
+ if (strpos($formula, '"') !== false) {
3054
+ // So instead we skip replacing in any quoted strings by only replacing in every other array element after we've exploded
3055
+ // the formula
3056
+ $temp = explode('"', $formula);
3057
+ // Open and Closed counts used for trapping mismatched braces in the formula
3058
+ $openCount = $closeCount = 0;
3059
+ $i = false;
3060
+ foreach ($temp as &$value) {
3061
+ // Only count/replace in alternating array entries
3062
+ if ($i = !$i) {
3063
+ $openCount += substr_count($value, '{');
3064
+ $closeCount += substr_count($value, '}');
3065
+ $value = str_replace($matrixReplaceFrom, $matrixReplaceTo, $value);
3066
+ }
3067
+ }
3068
+ unset($value);
3069
+ // Then rebuild the formula string
3070
+ $formula = implode('"', $temp);
3071
+ } else {
3072
+ // If there's no quoted strings, then we do a simple count/replace
3073
+ $openCount = substr_count($formula, '{');
3074
+ $closeCount = substr_count($formula, '}');
3075
+ $formula = str_replace($matrixReplaceFrom, $matrixReplaceTo, $formula);
3076
+ }
3077
+ // Trap for mismatched braces and trigger an appropriate error
3078
+ if ($openCount < $closeCount) {
3079
+ if ($openCount > 0) {
3080
+ return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '}'");
3081
+ } else {
3082
+ return $this->raiseFormulaError("Formula Error: Unexpected '}' encountered");
3083
+ }
3084
+ } elseif ($openCount > $closeCount) {
3085
+ if ($closeCount > 0) {
3086
+ return $this->raiseFormulaError("Formula Error: Mismatched matrix braces '{'");
3087
+ } else {
3088
+ return $this->raiseFormulaError("Formula Error: Unexpected '{' encountered");
3089
+ }
3090
+ }
3091
+ }
3092
+
3093
+ return $formula;
3094
+ }
3095
+
3096
+
3097
+ private static function mkMatrix()
3098
+ {
3099
+ return func_get_args();
3100
+ }
3101
+
3102
+
3103
+ // Binary Operators
3104
+ // These operators always work on two values
3105
+ // Array key is the operator, the value indicates whether this is a left or right associative operator
3106
+ private static $operatorAssociativity = array(
3107
+ '^' => 0, // Exponentiation
3108
+ '*' => 0, '/' => 0, // Multiplication and Division
3109
+ '+' => 0, '-' => 0, // Addition and Subtraction
3110
+ '&' => 0, // Concatenation
3111
+ '|' => 0, ':' => 0, // Intersect and Range
3112
+ '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
3113
+ );
3114
+
3115
+ // Comparison (Boolean) Operators
3116
+ // These operators work on two values, but always return a boolean result
3117
+ private static $comparisonOperators = array('>' => true, '<' => true, '=' => true, '>=' => true, '<=' => true, '<>' => true);
3118
+
3119
+ // Operator Precedence
3120
+ // This list includes all valid operators, whether binary (including boolean) or unary (such as %)
3121
+ // Array key is the operator, the value is its precedence
3122
+ private static $operatorPrecedence = array(
3123
+ ':' => 8, // Range
3124
+ '|' => 7, // Intersect
3125
+ '~' => 6, // Negation
3126
+ '%' => 5, // Percentage
3127
+ '^' => 4, // Exponentiation
3128
+ '*' => 3, '/' => 3, // Multiplication and Division
3129
+ '+' => 2, '-' => 2, // Addition and Subtraction
3130
+ '&' => 1, // Concatenation
3131
+ '>' => 0, '<' => 0, '=' => 0, '>=' => 0, '<=' => 0, '<>' => 0 // Comparison
3132
+ );
3133
+
3134
+ // Convert infix to postfix notation
3135
+ private function _parseFormula($formula, PHPExcel_Cell $pCell = null)
3136
+ {
3137
+ if (($formula = $this->convertMatrixReferences(trim($formula))) === false) {
3138
+ return false;
3139
+ }
3140
+
3141
+ // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent worksheet),
3142
+ // so we store the parent worksheet so that we can re-attach it when necessary
3143
+ $pCellParent = ($pCell !== null) ? $pCell->getWorksheet() : null;
3144
+
3145
+ $regexpMatchString = '/^('.self::CALCULATION_REGEXP_FUNCTION.
3146
+ '|'.self::CALCULATION_REGEXP_CELLREF.
3147
+ '|'.self::CALCULATION_REGEXP_NUMBER.
3148
+ '|'.self::CALCULATION_REGEXP_STRING.
3149
+ '|'.self::CALCULATION_REGEXP_OPENBRACE.
3150
+ '|'.self::CALCULATION_REGEXP_NAMEDRANGE.
3151
+ '|'.self::CALCULATION_REGEXP_ERROR.
3152
+ ')/si';
3153
+
3154
+ // Start with initialisation
3155
+ $index = 0;
3156
+ $stack = new PHPExcel_Calculation_Token_Stack;
3157
+ $output = array();
3158
+ $expectingOperator = false; // We use this test in syntax-checking the expression to determine when a
3159
+ // - is a negation or + is a positive operator rather than an operation
3160
+ $expectingOperand = false; // We use this test in syntax-checking the expression to determine whether an operand
3161
+ // should be null in a function call
3162
+ // The guts of the lexical parser
3163
+ // Loop through the formula extracting each operator and operand in turn
3164
+ while (true) {
3165
+ //echo 'Assessing Expression '.substr($formula, $index), PHP_EOL;
3166
+ $opCharacter = $formula{$index}; // Get the first character of the value at the current index position
3167
+ //echo 'Initial character of expression block is '.$opCharacter, PHP_EOL;
3168
+ if ((isset(self::$comparisonOperators[$opCharacter])) && (strlen($formula) > $index) && (isset(self::$comparisonOperators[$formula{$index+1}]))) {
3169
+ $opCharacter .= $formula{++$index};
3170
+ //echo 'Initial character of expression block is comparison operator '.$opCharacter.PHP_EOL;
3171
+ }
3172
+
3173
+ // Find out if we're currently at the beginning of a number, variable, cell reference, function, parenthesis or operand
3174
+ $isOperandOrFunction = preg_match($regexpMatchString, substr($formula, $index), $match);
3175
+ //echo '$isOperandOrFunction is '.(($isOperandOrFunction) ? 'True' : 'False').PHP_EOL;
3176
+ //var_dump($match);
3177
+
3178
+ if ($opCharacter == '-' && !$expectingOperator) { // Is it a negation instead of a minus?
3179
+ //echo 'Element is a Negation operator', PHP_EOL;
3180
+ $stack->push('Unary Operator', '~'); // Put a negation on the stack
3181
+ ++$index; // and drop the negation symbol
3182
+ } elseif ($opCharacter == '%' && $expectingOperator) {
3183
+ //echo 'Element is a Percentage operator', PHP_EOL;
3184
+ $stack->push('Unary Operator', '%'); // Put a percentage on the stack
3185
+ ++$index;
3186
+ } elseif ($opCharacter == '+' && !$expectingOperator) { // Positive (unary plus rather than binary operator plus) can be discarded?
3187
+ //echo 'Element is a Positive number, not Plus operator', PHP_EOL;
3188
+ ++$index; // Drop the redundant plus symbol
3189
+ } elseif ((($opCharacter == '~') || ($opCharacter == '|')) && (!$isOperandOrFunction)) { // We have to explicitly deny a tilde or pipe, because they are legal
3190
+ return $this->raiseFormulaError("Formula Error: Illegal character '~'"); // on the stack but not in the input expression
3191
+
3192
+ } elseif ((isset(self::$operators[$opCharacter]) or $isOperandOrFunction) && $expectingOperator) { // Are we putting an operator on the stack?
3193
+ //echo 'Element with value '.$opCharacter.' is an Operator', PHP_EOL;
3194
+ while ($stack->count() > 0 &&
3195
+ ($o2 = $stack->last()) &&
3196
+ isset(self::$operators[$o2['value']]) &&
3197
+ @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])) {
3198
+ $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
3199
+ }
3200
+ $stack->push('Binary Operator', $opCharacter); // Finally put our current operator onto the stack
3201
+ ++$index;
3202
+ $expectingOperator = false;
3203
+
3204
+ } elseif ($opCharacter == ')' && $expectingOperator) { // Are we expecting to close a parenthesis?
3205
+ //echo 'Element is a Closing bracket', PHP_EOL;
3206
+ $expectingOperand = false;
3207
+ while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
3208
+ if ($o2 === null) {
3209
+ return $this->raiseFormulaError('Formula Error: Unexpected closing brace ")"');
3210
+ } else {
3211
+ $output[] = $o2;
3212
+ }
3213
+ }
3214
+ $d = $stack->last(2);
3215
+ if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) { // Did this parenthesis just close a function?
3216
+ $functionName = $matches[1]; // Get the function name
3217
+ //echo 'Closed Function is '.$functionName, PHP_EOL;
3218
+ $d = $stack->pop();
3219
+ $argumentCount = $d['value']; // See how many arguments there were (argument count is the next value stored on the stack)
3220
+ //if ($argumentCount == 0) {
3221
+ // echo 'With no arguments', PHP_EOL;
3222
+ //} elseif ($argumentCount == 1) {
3223
+ // echo 'With 1 argument', PHP_EOL;
3224
+ //} else {
3225
+ // echo 'With '.$argumentCount.' arguments', PHP_EOL;
3226
+ //}
3227
+ $output[] = $d; // Dump the argument count on the output
3228
+ $output[] = $stack->pop(); // Pop the function and push onto the output
3229
+ if (isset(self::$controlFunctions[$functionName])) {
3230
+ //echo 'Built-in function '.$functionName, PHP_EOL;
3231
+ $expectedArgumentCount = self::$controlFunctions[$functionName]['argumentCount'];
3232
+ $functionCall = self::$controlFunctions[$functionName]['functionCall'];
3233
+ } elseif (isset(self::$PHPExcelFunctions[$functionName])) {
3234
+ //echo 'PHPExcel function '.$functionName, PHP_EOL;
3235
+ $expectedArgumentCount = self::$PHPExcelFunctions[$functionName]['argumentCount'];
3236
+ $functionCall = self::$PHPExcelFunctions[$functionName]['functionCall'];
3237
+ } else { // did we somehow push a non-function on the stack? this should never happen
3238
+ return $this->raiseFormulaError("Formula Error: Internal error, non-function on stack");
3239
+ }
3240
+ // Check the argument count
3241
+ $argumentCountError = false;
3242
+ if (is_numeric($expectedArgumentCount)) {
3243
+ if ($expectedArgumentCount < 0) {
3244
+ //echo '$expectedArgumentCount is between 0 and '.abs($expectedArgumentCount), PHP_EOL;
3245
+ if ($argumentCount > abs($expectedArgumentCount)) {
3246
+ $argumentCountError = true;
3247
+ $expectedArgumentCountString = 'no more than '.abs($expectedArgumentCount);
3248
+ }
3249
+ } else {
3250
+ //echo '$expectedArgumentCount is numeric '.$expectedArgumentCount, PHP_EOL;
3251
+ if ($argumentCount != $expectedArgumentCount) {
3252
+ $argumentCountError = true;
3253
+ $expectedArgumentCountString = $expectedArgumentCount;
3254
+ }
3255
+ }
3256
+ } elseif ($expectedArgumentCount != '*') {
3257
+ $isOperandOrFunction = preg_match('/(\d*)([-+,])(\d*)/', $expectedArgumentCount, $argMatch);
3258
+ //print_r($argMatch);
3259
+ //echo PHP_EOL;
3260
+ switch ($argMatch[2]) {
3261
+ case '+':
3262
+ if ($argumentCount < $argMatch[1]) {
3263
+ $argumentCountError = true;
3264
+ $expectedArgumentCountString = $argMatch[1].' or more ';
3265
+ }
3266
+ break;
3267
+ case '-':
3268
+ if (($argumentCount < $argMatch[1]) || ($argumentCount > $argMatch[3])) {
3269
+ $argumentCountError = true;
3270
+ $expectedArgumentCountString = 'between '.$argMatch[1].' and '.$argMatch[3];
3271
+ }
3272
+ break;
3273
+ case ',':
3274
+ if (($argumentCount != $argMatch[1]) && ($argumentCount != $argMatch[3])) {
3275
+ $argumentCountError = true;
3276
+ $expectedArgumentCountString = 'either '.$argMatch[1].' or '.$argMatch[3];
3277
+ }
3278
+ break;
3279
+ }
3280
+ }
3281
+ if ($argumentCountError) {
3282
+ return $this->raiseFormulaError("Formula Error: Wrong number of arguments for $functionName() function: $argumentCount given, ".$expectedArgumentCountString." expected");
3283
+ }
3284
+ }
3285
+ ++$index;
3286
+
3287
+ } elseif ($opCharacter == ',') { // Is this the separator for function arguments?
3288
+ //echo 'Element is a Function argument separator', PHP_EOL;
3289
+ while (($o2 = $stack->pop()) && $o2['value'] != '(') { // Pop off the stack back to the last (
3290
+ if ($o2 === null) {
3291
+ return $this->raiseFormulaError("Formula Error: Unexpected ,");
3292
+ } else {
3293
+ $output[] = $o2; // pop the argument expression stuff and push onto the output
3294
+ }
3295
+ }
3296
+ // If we've a comma when we're expecting an operand, then what we actually have is a null operand;
3297
+ // so push a null onto the stack
3298
+ if (($expectingOperand) || (!$expectingOperator)) {
3299
+ $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null);
3300
+ }
3301
+ // make sure there was a function
3302
+ $d = $stack->last(2);
3303
+ if (!preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $d['value'], $matches)) {
3304
+ return $this->raiseFormulaError("Formula Error: Unexpected ,");
3305
+ }
3306
+ $d = $stack->pop();
3307
+ $stack->push($d['type'], ++$d['value'], $d['reference']); // increment the argument count
3308
+ $stack->push('Brace', '('); // put the ( back on, we'll need to pop back to it again
3309
+ $expectingOperator = false;
3310
+ $expectingOperand = true;
3311
+ ++$index;
3312
+
3313
+ } elseif ($opCharacter == '(' && !$expectingOperator) {
3314
+ // echo 'Element is an Opening Bracket<br />';
3315
+ $stack->push('Brace', '(');
3316
+ ++$index;
3317
+
3318
+ } elseif ($isOperandOrFunction && !$expectingOperator) { // do we now have a function/variable/number?
3319
+ $expectingOperator = true;
3320
+ $expectingOperand = false;
3321
+ $val = $match[1];
3322
+ $length = strlen($val);
3323
+ // echo 'Element with value '.$val.' is an Operand, Variable, Constant, String, Number, Cell Reference or Function<br />';
3324
+
3325
+ if (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $val, $matches)) {
3326
+ $val = preg_replace('/\s/u', '', $val);
3327
+ // echo 'Element '.$val.' is a Function<br />';
3328
+ if (isset(self::$PHPExcelFunctions[strtoupper($matches[1])]) || isset(self::$controlFunctions[strtoupper($matches[1])])) { // it's a function
3329
+ $stack->push('Function', strtoupper($val));
3330
+ $ax = preg_match('/^\s*(\s*\))/ui', substr($formula, $index+$length), $amatch);
3331
+ if ($ax) {
3332
+ $stack->push('Operand Count for Function '.strtoupper($val).')', 0);
3333
+ $expectingOperator = true;
3334
+ } else {
3335
+ $stack->push('Operand Count for Function '.strtoupper($val).')', 1);
3336
+ $expectingOperator = false;
3337
+ }
3338
+ $stack->push('Brace', '(');
3339
+ } else { // it's a var w/ implicit multiplication
3340
+ $output[] = array('type' => 'Value', 'value' => $matches[1], 'reference' => null);
3341
+ }
3342
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $val, $matches)) {
3343
+ // echo 'Element '.$val.' is a Cell reference<br />';
3344
+ // Watch for this case-change when modifying to allow cell references in different worksheets...
3345
+ // Should only be applied to the actual cell column, not the worksheet name
3346
+
3347
+ // If the last entry on the stack was a : operator, then we have a cell range reference
3348
+ $testPrevOp = $stack->last(1);
3349
+ if ($testPrevOp['value'] == ':') {
3350
+ // If we have a worksheet reference, then we're playing with a 3D reference
3351
+ if ($matches[2] == '') {
3352
+ // Otherwise, we 'inherit' the worksheet reference from the start cell reference
3353
+ // The start of the cell range reference should be the last entry in $output
3354
+ $startCellRef = $output[count($output)-1]['value'];
3355
+ preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $startCellRef, $startMatches);
3356
+ if ($startMatches[2] > '') {
3357
+ $val = $startMatches[2].'!'.$val;
3358
+ }
3359
+ } else {
3360
+ return $this->raiseFormulaError("3D Range references are not yet supported");
3361
+ }
3362
+ }
3363
+
3364
+ $output[] = array('type' => 'Cell Reference', 'value' => $val, 'reference' => $val);
3365
+ // $expectingOperator = FALSE;
3366
+ } else { // it's a variable, constant, string, number or boolean
3367
+ // echo 'Element is a Variable, Constant, String, Number or Boolean<br />';
3368
+ // If the last entry on the stack was a : operator, then we may have a row or column range reference
3369
+ $testPrevOp = $stack->last(1);
3370
+ if ($testPrevOp['value'] == ':') {
3371
+ $startRowColRef = $output[count($output)-1]['value'];
3372
+ $rangeWS1 = '';
3373
+ if (strpos('!', $startRowColRef) !== false) {
3374
+ list($rangeWS1, $startRowColRef) = explode('!', $startRowColRef);
3375
+ }
3376
+ if ($rangeWS1 != '') {
3377
+ $rangeWS1 .= '!';
3378
+ }
3379
+ $rangeWS2 = $rangeWS1;
3380
+ if (strpos('!', $val) !== false) {
3381
+ list($rangeWS2, $val) = explode('!', $val);
3382
+ }
3383
+ if ($rangeWS2 != '') {
3384
+ $rangeWS2 .= '!';
3385
+ }
3386
+ if ((is_integer($startRowColRef)) && (ctype_digit($val)) &&
3387
+ ($startRowColRef <= 1048576) && ($val <= 1048576)) {
3388
+ // Row range
3389
+ $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestColumn() : 'XFD'; // Max 16,384 columns for Excel2007
3390
+ $output[count($output)-1]['value'] = $rangeWS1.'A'.$startRowColRef;
3391
+ $val = $rangeWS2.$endRowColRef.$val;
3392
+ } elseif ((ctype_alpha($startRowColRef)) && (ctype_alpha($val)) &&
3393
+ (strlen($startRowColRef) <= 3) && (strlen($val) <= 3)) {
3394
+ // Column range
3395
+ $endRowColRef = ($pCellParent !== null) ? $pCellParent->getHighestRow() : 1048576; // Max 1,048,576 rows for Excel2007
3396
+ $output[count($output)-1]['value'] = $rangeWS1.strtoupper($startRowColRef).'1';
3397
+ $val = $rangeWS2.$val.$endRowColRef;
3398
+ }
3399
+ }
3400
+
3401
+ $localeConstant = false;
3402
+ if ($opCharacter == '"') {
3403
+ // echo 'Element is a String<br />';
3404
+ // UnEscape any quotes within the string
3405
+ $val = self::wrapResult(str_replace('""', '"', self::unwrapResult($val)));
3406
+ } elseif (is_numeric($val)) {
3407
+ // echo 'Element is a Number<br />';
3408
+ if ((strpos($val, '.') !== false) || (stripos($val, 'e') !== false) || ($val > PHP_INT_MAX) || ($val < -PHP_INT_MAX)) {
3409
+ // echo 'Casting '.$val.' to float<br />';
3410
+ $val = (float) $val;
3411
+ } else {
3412
+ // echo 'Casting '.$val.' to integer<br />';
3413
+ $val = (integer) $val;
3414
+ }
3415
+ } elseif (isset(self::$excelConstants[trim(strtoupper($val))])) {
3416
+ $excelConstant = trim(strtoupper($val));
3417
+ // echo 'Element '.$excelConstant.' is an Excel Constant<br />';
3418
+ $val = self::$excelConstants[$excelConstant];
3419
+ } elseif (($localeConstant = array_search(trim(strtoupper($val)), self::$localeBoolean)) !== false) {
3420
+ // echo 'Element '.$localeConstant.' is an Excel Constant<br />';
3421
+ $val = self::$excelConstants[$localeConstant];
3422
+ }
3423
+ $details = array('type' => 'Value', 'value' => $val, 'reference' => null);
3424
+ if ($localeConstant) {
3425
+ $details['localeValue'] = $localeConstant;
3426
+ }
3427
+ $output[] = $details;
3428
+ }
3429
+ $index += $length;
3430
+
3431
+ } elseif ($opCharacter == '$') { // absolute row or column range
3432
+ ++$index;
3433
+ } elseif ($opCharacter == ')') { // miscellaneous error checking
3434
+ if ($expectingOperand) {
3435
+ $output[] = array('type' => 'NULL Value', 'value' => self::$excelConstants['NULL'], 'reference' => null);
3436
+ $expectingOperand = false;
3437
+ $expectingOperator = true;
3438
+ } else {
3439
+ return $this->raiseFormulaError("Formula Error: Unexpected ')'");
3440
+ }
3441
+ } elseif (isset(self::$operators[$opCharacter]) && !$expectingOperator) {
3442
+ return $this->raiseFormulaError("Formula Error: Unexpected operator '$opCharacter'");
3443
+ } else { // I don't even want to know what you did to get here
3444
+ return $this->raiseFormulaError("Formula Error: An unexpected error occured");
3445
+ }
3446
+ // Test for end of formula string
3447
+ if ($index == strlen($formula)) {
3448
+ // Did we end with an operator?.
3449
+ // Only valid for the % unary operator
3450
+ if ((isset(self::$operators[$opCharacter])) && ($opCharacter != '%')) {
3451
+ return $this->raiseFormulaError("Formula Error: Operator '$opCharacter' has no operands");
3452
+ } else {
3453
+ break;
3454
+ }
3455
+ }
3456
+ // Ignore white space
3457
+ while (($formula{$index} == "\n") || ($formula{$index} == "\r")) {
3458
+ ++$index;
3459
+ }
3460
+ if ($formula{$index} == ' ') {
3461
+ while ($formula{$index} == ' ') {
3462
+ ++$index;
3463
+ }
3464
+ // If we're expecting an operator, but only have a space between the previous and next operands (and both are
3465
+ // Cell References) then we have an INTERSECTION operator
3466
+ // echo 'Possible Intersect Operator<br />';
3467
+ if (($expectingOperator) && (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'.*/Ui', substr($formula, $index), $match)) &&
3468
+ ($output[count($output)-1]['type'] == 'Cell Reference')) {
3469
+ // echo 'Element is an Intersect Operator<br />';
3470
+ while ($stack->count() > 0 &&
3471
+ ($o2 = $stack->last()) &&
3472
+ isset(self::$operators[$o2['value']]) &&
3473
+ @(self::$operatorAssociativity[$opCharacter] ? self::$operatorPrecedence[$opCharacter] < self::$operatorPrecedence[$o2['value']] : self::$operatorPrecedence[$opCharacter] <= self::$operatorPrecedence[$o2['value']])) {
3474
+ $output[] = $stack->pop(); // Swap operands and higher precedence operators from the stack to the output
3475
+ }
3476
+ $stack->push('Binary Operator', '|'); // Put an Intersect Operator on the stack
3477
+ $expectingOperator = false;
3478
+ }
3479
+ }
3480
+ }
3481
+
3482
+ while (($op = $stack->pop()) !== null) { // pop everything off the stack and push onto output
3483
+ if ((is_array($op) && $op['value'] == '(') || ($op === '(')) {
3484
+ return $this->raiseFormulaError("Formula Error: Expecting ')'"); // if there are any opening braces on the stack, then braces were unbalanced
3485
+ }
3486
+ $output[] = $op;
3487
+ }
3488
+ return $output;
3489
+ }
3490
+
3491
+
3492
+ private static function dataTestReference(&$operandData)
3493
+ {
3494
+ $operand = $operandData['value'];
3495
+ if (($operandData['reference'] === null) && (is_array($operand))) {
3496
+ $rKeys = array_keys($operand);
3497
+ $rowKey = array_shift($rKeys);
3498
+ $cKeys = array_keys(array_keys($operand[$rowKey]));
3499
+ $colKey = array_shift($cKeys);
3500
+ if (ctype_upper($colKey)) {
3501
+ $operandData['reference'] = $colKey.$rowKey;
3502
+ }
3503
+ }
3504
+ return $operand;
3505
+ }
3506
+
3507
+ // evaluate postfix notation
3508
+ private function processTokenStack($tokens, $cellID = null, PHPExcel_Cell $pCell = null)
3509
+ {
3510
+ if ($tokens == false) {
3511
+ return false;
3512
+ }
3513
+
3514
+ // If we're using cell caching, then $pCell may well be flushed back to the cache (which detaches the parent cell collection),
3515
+ // so we store the parent cell collection so that we can re-attach it when necessary
3516
+ $pCellWorksheet = ($pCell !== null) ? $pCell->getWorksheet() : null;
3517
+ $pCellParent = ($pCell !== null) ? $pCell->getParent() : null;
3518
+ $stack = new PHPExcel_Calculation_Token_Stack;
3519
+
3520
+ // Loop through each token in turn
3521
+ foreach ($tokens as $tokenData) {
3522
+ // print_r($tokenData);
3523
+ // echo '<br />';
3524
+ $token = $tokenData['value'];
3525
+ // echo '<b>Token is '.$token.'</b><br />';
3526
+ // if the token is a binary operator, pop the top two values off the stack, do the operation, and push the result back on the stack
3527
+ if (isset(self::$binaryOperators[$token])) {
3528
+ // echo 'Token is a binary operator<br />';
3529
+ // We must have two operands, error if we don't
3530
+ if (($operand2Data = $stack->pop()) === null) {
3531
+ return $this->raiseFormulaError('Internal error - Operand value missing from stack');
3532
+ }
3533
+ if (($operand1Data = $stack->pop()) === null) {
3534
+ return $this->raiseFormulaError('Internal error - Operand value missing from stack');
3535
+ }
3536
+
3537
+ $operand1 = self::dataTestReference($operand1Data);
3538
+ $operand2 = self::dataTestReference($operand2Data);
3539
+
3540
+ // Log what we're doing
3541
+ if ($token == ':') {
3542
+ $this->_debugLog->writeDebugLog('Evaluating Range ', $this->showValue($operand1Data['reference']), ' ', $token, ' ', $this->showValue($operand2Data['reference']));
3543
+ } else {
3544
+ $this->_debugLog->writeDebugLog('Evaluating ', $this->showValue($operand1), ' ', $token, ' ', $this->showValue($operand2));
3545
+ }
3546
+
3547
+ // Process the operation in the appropriate manner
3548
+ switch ($token) {
3549
+ // Comparison (Boolean) Operators
3550
+ case '>': // Greater than
3551
+ case '<': // Less than
3552
+ case '>=': // Greater than or Equal to
3553
+ case '<=': // Less than or Equal to
3554
+ case '=': // Equality
3555
+ case '<>': // Inequality
3556
+ $this->executeBinaryComparisonOperation($cellID, $operand1, $operand2, $token, $stack);
3557
+ break;
3558
+ // Binary Operators
3559
+ case ':': // Range
3560
+ $sheet1 = $sheet2 = '';
3561
+ if (strpos($operand1Data['reference'], '!') !== false) {
3562
+ list($sheet1, $operand1Data['reference']) = explode('!', $operand1Data['reference']);
3563
+ } else {
3564
+ $sheet1 = ($pCellParent !== null) ? $pCellWorksheet->getTitle() : '';
3565
+ }
3566
+ if (strpos($operand2Data['reference'], '!') !== false) {
3567
+ list($sheet2, $operand2Data['reference']) = explode('!', $operand2Data['reference']);
3568
+ } else {
3569
+ $sheet2 = $sheet1;
3570
+ }
3571
+ if ($sheet1 == $sheet2) {
3572
+ if ($operand1Data['reference'] === null) {
3573
+ if ((trim($operand1Data['value']) != '') && (is_numeric($operand1Data['value']))) {
3574
+ $operand1Data['reference'] = $pCell->getColumn().$operand1Data['value'];
3575
+ } elseif (trim($operand1Data['reference']) == '') {
3576
+ $operand1Data['reference'] = $pCell->getCoordinate();
3577
+ } else {
3578
+ $operand1Data['reference'] = $operand1Data['value'].$pCell->getRow();
3579
+ }
3580
+ }
3581
+ if ($operand2Data['reference'] === null) {
3582
+ if ((trim($operand2Data['value']) != '') && (is_numeric($operand2Data['value']))) {
3583
+ $operand2Data['reference'] = $pCell->getColumn().$operand2Data['value'];
3584
+ } elseif (trim($operand2Data['reference']) == '') {
3585
+ $operand2Data['reference'] = $pCell->getCoordinate();
3586
+ } else {
3587
+ $operand2Data['reference'] = $operand2Data['value'].$pCell->getRow();
3588
+ }
3589
+ }
3590
+
3591
+ $oData = array_merge(explode(':', $operand1Data['reference']), explode(':', $operand2Data['reference']));
3592
+ $oCol = $oRow = array();
3593
+ foreach ($oData as $oDatum) {
3594
+ $oCR = PHPExcel_Cell::coordinateFromString($oDatum);
3595
+ $oCol[] = PHPExcel_Cell::columnIndexFromString($oCR[0]) - 1;
3596
+ $oRow[] = $oCR[1];
3597
+ }
3598
+ $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow);
3599
+ if ($pCellParent !== null) {
3600
+ $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($sheet1), false);
3601
+ } else {
3602
+ return $this->raiseFormulaError('Unable to access Cell Reference');
3603
+ }
3604
+ $stack->push('Cell Reference', $cellValue, $cellRef);
3605
+ } else {
3606
+ $stack->push('Error', PHPExcel_Calculation_Functions::REF(), null);
3607
+ }
3608
+ break;
3609
+ case '+': // Addition
3610
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'plusEquals', $stack);
3611
+ break;
3612
+ case '-': // Subtraction
3613
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'minusEquals', $stack);
3614
+ break;
3615
+ case '*': // Multiplication
3616
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'arrayTimesEquals', $stack);
3617
+ break;
3618
+ case '/': // Division
3619
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'arrayRightDivide', $stack);
3620
+ break;
3621
+ case '^': // Exponential
3622
+ $this->executeNumericBinaryOperation($cellID, $operand1, $operand2, $token, 'power', $stack);
3623
+ break;
3624
+ case '&': // Concatenation
3625
+ // If either of the operands is a matrix, we need to treat them both as matrices
3626
+ // (converting the other operand to a matrix if need be); then perform the required
3627
+ // matrix operation
3628
+ if (is_bool($operand1)) {
3629
+ $operand1 = ($operand1) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
3630
+ }
3631
+ if (is_bool($operand2)) {
3632
+ $operand2 = ($operand2) ? self::$localeBoolean['TRUE'] : self::$localeBoolean['FALSE'];
3633
+ }
3634
+ if ((is_array($operand1)) || (is_array($operand2))) {
3635
+ // Ensure that both operands are arrays/matrices
3636
+ self::checkMatrixOperands($operand1, $operand2, 2);
3637
+ try {
3638
+ // Convert operand 1 from a PHP array to a matrix
3639
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1);
3640
+ // Perform the required operation against the operand 1 matrix, passing in operand 2
3641
+ $matrixResult = $matrix->concat($operand2);
3642
+ $result = $matrixResult->getArray();
3643
+ } catch (PHPExcel_Exception $ex) {
3644
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
3645
+ $result = '#VALUE!';
3646
+ }
3647
+ } else {
3648
+ $result = '"'.str_replace('""', '"', self::unwrapResult($operand1, '"').self::unwrapResult($operand2, '"')).'"';
3649
+ }
3650
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result));
3651
+ $stack->push('Value', $result);
3652
+ break;
3653
+ case '|': // Intersect
3654
+ $rowIntersect = array_intersect_key($operand1, $operand2);
3655
+ $cellIntersect = $oCol = $oRow = array();
3656
+ foreach (array_keys($rowIntersect) as $row) {
3657
+ $oRow[] = $row;
3658
+ foreach ($rowIntersect[$row] as $col => $data) {
3659
+ $oCol[] = PHPExcel_Cell::columnIndexFromString($col) - 1;
3660
+ $cellIntersect[$row] = array_intersect_key($operand1[$row], $operand2[$row]);
3661
+ }
3662
+ }
3663
+ $cellRef = PHPExcel_Cell::stringFromColumnIndex(min($oCol)).min($oRow).':'.PHPExcel_Cell::stringFromColumnIndex(max($oCol)).max($oRow);
3664
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($cellIntersect));
3665
+ $stack->push('Value', $cellIntersect, $cellRef);
3666
+ break;
3667
+ }
3668
+
3669
+ // if the token is a unary operator, pop one value off the stack, do the operation, and push it back on
3670
+ } elseif (($token === '~') || ($token === '%')) {
3671
+ // echo 'Token is a unary operator<br />';
3672
+ if (($arg = $stack->pop()) === null) {
3673
+ return $this->raiseFormulaError('Internal error - Operand value missing from stack');
3674
+ }
3675
+ $arg = $arg['value'];
3676
+ if ($token === '~') {
3677
+ // echo 'Token is a negation operator<br />';
3678
+ $this->_debugLog->writeDebugLog('Evaluating Negation of ', $this->showValue($arg));
3679
+ $multiplier = -1;
3680
+ } else {
3681
+ // echo 'Token is a percentile operator<br />';
3682
+ $this->_debugLog->writeDebugLog('Evaluating Percentile of ', $this->showValue($arg));
3683
+ $multiplier = 0.01;
3684
+ }
3685
+ if (is_array($arg)) {
3686
+ self::checkMatrixOperands($arg, $multiplier, 2);
3687
+ try {
3688
+ $matrix1 = new PHPExcel_Shared_JAMA_Matrix($arg);
3689
+ $matrixResult = $matrix1->arrayTimesEquals($multiplier);
3690
+ $result = $matrixResult->getArray();
3691
+ } catch (PHPExcel_Exception $ex) {
3692
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
3693
+ $result = '#VALUE!';
3694
+ }
3695
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result));
3696
+ $stack->push('Value', $result);
3697
+ } else {
3698
+ $this->executeNumericBinaryOperation($cellID, $multiplier, $arg, '*', 'arrayTimesEquals', $stack);
3699
+ }
3700
+
3701
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_CELLREF.'$/i', $token, $matches)) {
3702
+ $cellRef = null;
3703
+ // echo 'Element '.$token.' is a Cell reference<br />';
3704
+ if (isset($matches[8])) {
3705
+ // echo 'Reference is a Range of cells<br />';
3706
+ if ($pCell === null) {
3707
+ // We can't access the range, so return a REF error
3708
+ $cellValue = PHPExcel_Calculation_Functions::REF();
3709
+ } else {
3710
+ $cellRef = $matches[6].$matches[7].':'.$matches[9].$matches[10];
3711
+ if ($matches[2] > '') {
3712
+ $matches[2] = trim($matches[2], "\"'");
3713
+ if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) {
3714
+ // It's a Reference to an external workbook (not currently supported)
3715
+ return $this->raiseFormulaError('Unable to access External Workbook');
3716
+ }
3717
+ $matches[2] = trim($matches[2], "\"'");
3718
+ // echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'<br />';
3719
+ $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in worksheet ', $matches[2]);
3720
+ if ($pCellParent !== null) {
3721
+ $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($matches[2]), false);
3722
+ } else {
3723
+ return $this->raiseFormulaError('Unable to access Cell Reference');
3724
+ }
3725
+ $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue));
3726
+ // $cellRef = $matches[2].'!'.$cellRef;
3727
+ } else {
3728
+ // echo '$cellRef='.$cellRef.' in current worksheet<br />';
3729
+ $this->_debugLog->writeDebugLog('Evaluating Cell Range ', $cellRef, ' in current worksheet');
3730
+ if ($pCellParent !== null) {
3731
+ $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
3732
+ } else {
3733
+ return $this->raiseFormulaError('Unable to access Cell Reference');
3734
+ }
3735
+ $this->_debugLog->writeDebugLog('Evaluation Result for cells ', $cellRef, ' is ', $this->showTypeDetails($cellValue));
3736
+ }
3737
+ }
3738
+ } else {
3739
+ // echo 'Reference is a single Cell<br />';
3740
+ if ($pCell === null) {
3741
+ // We can't access the cell, so return a REF error
3742
+ $cellValue = PHPExcel_Calculation_Functions::REF();
3743
+ } else {
3744
+ $cellRef = $matches[6].$matches[7];
3745
+ if ($matches[2] > '') {
3746
+ $matches[2] = trim($matches[2], "\"'");
3747
+ if ((strpos($matches[2], '[') !== false) || (strpos($matches[2], ']') !== false)) {
3748
+ // It's a Reference to an external workbook (not currently supported)
3749
+ return $this->raiseFormulaError('Unable to access External Workbook');
3750
+ }
3751
+ // echo '$cellRef='.$cellRef.' in worksheet '.$matches[2].'<br />';
3752
+ $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in worksheet ', $matches[2]);
3753
+ if ($pCellParent !== null) {
3754
+ $cellSheet = $this->workbook->getSheetByName($matches[2]);
3755
+ if ($cellSheet && $cellSheet->cellExists($cellRef)) {
3756
+ $cellValue = $this->extractCellRange($cellRef, $this->workbook->getSheetByName($matches[2]), false);
3757
+ $pCell->attach($pCellParent);
3758
+ } else {
3759
+ $cellValue = null;
3760
+ }
3761
+ } else {
3762
+ return $this->raiseFormulaError('Unable to access Cell Reference');
3763
+ }
3764
+ $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' in worksheet ', $matches[2], ' is ', $this->showTypeDetails($cellValue));
3765
+ // $cellRef = $matches[2].'!'.$cellRef;
3766
+ } else {
3767
+ // echo '$cellRef='.$cellRef.' in current worksheet<br />';
3768
+ $this->_debugLog->writeDebugLog('Evaluating Cell ', $cellRef, ' in current worksheet');
3769
+ if ($pCellParent->isDataSet($cellRef)) {
3770
+ $cellValue = $this->extractCellRange($cellRef, $pCellWorksheet, false);
3771
+ $pCell->attach($pCellParent);
3772
+ } else {
3773
+ $cellValue = null;
3774
+ }
3775
+ $this->_debugLog->writeDebugLog('Evaluation Result for cell ', $cellRef, ' is ', $this->showTypeDetails($cellValue));
3776
+ }
3777
+ }
3778
+ }
3779
+ $stack->push('Value', $cellValue, $cellRef);
3780
+
3781
+ // if the token is a function, pop arguments off the stack, hand them to the function, and push the result back on
3782
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_FUNCTION.'$/i', $token, $matches)) {
3783
+ // echo 'Token is a function<br />';
3784
+ $functionName = $matches[1];
3785
+ $argCount = $stack->pop();
3786
+ $argCount = $argCount['value'];
3787
+ if ($functionName != 'MKMATRIX') {
3788
+ $this->_debugLog->writeDebugLog('Evaluating Function ', self::localeFunc($functionName), '() with ', (($argCount == 0) ? 'no' : $argCount), ' argument', (($argCount == 1) ? '' : 's'));
3789
+ }
3790
+ if ((isset(self::$PHPExcelFunctions[$functionName])) || (isset(self::$controlFunctions[$functionName]))) { // function
3791
+ if (isset(self::$PHPExcelFunctions[$functionName])) {
3792
+ $functionCall = self::$PHPExcelFunctions[$functionName]['functionCall'];
3793
+ $passByReference = isset(self::$PHPExcelFunctions[$functionName]['passByReference']);
3794
+ $passCellReference = isset(self::$PHPExcelFunctions[$functionName]['passCellReference']);
3795
+ } elseif (isset(self::$controlFunctions[$functionName])) {
3796
+ $functionCall = self::$controlFunctions[$functionName]['functionCall'];
3797
+ $passByReference = isset(self::$controlFunctions[$functionName]['passByReference']);
3798
+ $passCellReference = isset(self::$controlFunctions[$functionName]['passCellReference']);
3799
+ }
3800
+ // get the arguments for this function
3801
+ // echo 'Function '.$functionName.' expects '.$argCount.' arguments<br />';
3802
+ $args = $argArrayVals = array();
3803
+ for ($i = 0; $i < $argCount; ++$i) {
3804
+ $arg = $stack->pop();
3805
+ $a = $argCount - $i - 1;
3806
+ if (($passByReference) &&
3807
+ (isset(self::$PHPExcelFunctions[$functionName]['passByReference'][$a])) &&
3808
+ (self::$PHPExcelFunctions[$functionName]['passByReference'][$a])) {
3809
+ if ($arg['reference'] === null) {
3810
+ $args[] = $cellID;
3811
+ if ($functionName != 'MKMATRIX') {
3812
+ $argArrayVals[] = $this->showValue($cellID);
3813
+ }
3814
+ } else {
3815
+ $args[] = $arg['reference'];
3816
+ if ($functionName != 'MKMATRIX') {
3817
+ $argArrayVals[] = $this->showValue($arg['reference']);
3818
+ }
3819
+ }
3820
+ } else {
3821
+ $args[] = self::unwrapResult($arg['value']);
3822
+ if ($functionName != 'MKMATRIX') {
3823
+ $argArrayVals[] = $this->showValue($arg['value']);
3824
+ }
3825
+ }
3826
+ }
3827
+ // Reverse the order of the arguments
3828
+ krsort($args);
3829
+ if (($passByReference) && ($argCount == 0)) {
3830
+ $args[] = $cellID;
3831
+ $argArrayVals[] = $this->showValue($cellID);
3832
+ }
3833
+ // echo 'Arguments are: ';
3834
+ // print_r($args);
3835
+ // echo '<br />';
3836
+ if ($functionName != 'MKMATRIX') {
3837
+ if ($this->_debugLog->getWriteDebugLog()) {
3838
+ krsort($argArrayVals);
3839
+ $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', implode(self::$localeArgumentSeparator.' ', PHPExcel_Calculation_Functions::flattenArray($argArrayVals)), ' )');
3840
+ }
3841
+ }
3842
+ // Process each argument in turn, building the return value as an array
3843
+ // if (($argCount == 1) && (is_array($args[1])) && ($functionName != 'MKMATRIX')) {
3844
+ // $operand1 = $args[1];
3845
+ // $this->_debugLog->writeDebugLog('Argument is a matrix: ', $this->showValue($operand1));
3846
+ // $result = array();
3847
+ // $row = 0;
3848
+ // foreach($operand1 as $args) {
3849
+ // if (is_array($args)) {
3850
+ // foreach($args as $arg) {
3851
+ // $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', $this->showValue($arg), ' )');
3852
+ // $r = call_user_func_array($functionCall, $arg);
3853
+ // $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($r));
3854
+ // $result[$row][] = $r;
3855
+ // }
3856
+ // ++$row;
3857
+ // } else {
3858
+ // $this->_debugLog->writeDebugLog('Evaluating ', self::localeFunc($functionName), '( ', $this->showValue($args), ' )');
3859
+ // $r = call_user_func_array($functionCall, $args);
3860
+ // $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($r));
3861
+ // $result[] = $r;
3862
+ // }
3863
+ // }
3864
+ // } else {
3865
+ // Process the argument with the appropriate function call
3866
+ if ($passCellReference) {
3867
+ $args[] = $pCell;
3868
+ }
3869
+ if (strpos($functionCall, '::') !== false) {
3870
+ $result = call_user_func_array(explode('::', $functionCall), $args);
3871
+ } else {
3872
+ foreach ($args as &$arg) {
3873
+ $arg = PHPExcel_Calculation_Functions::flattenSingleValue($arg);
3874
+ }
3875
+ unset($arg);
3876
+ $result = call_user_func_array($functionCall, $args);
3877
+ }
3878
+ if ($functionName != 'MKMATRIX') {
3879
+ $this->_debugLog->writeDebugLog('Evaluation Result for ', self::localeFunc($functionName), '() function call is ', $this->showTypeDetails($result));
3880
+ }
3881
+ $stack->push('Value', self::wrapResult($result));
3882
+ }
3883
+
3884
+ } else {
3885
+ // if the token is a number, boolean, string or an Excel error, push it onto the stack
3886
+ if (isset(self::$excelConstants[strtoupper($token)])) {
3887
+ $excelConstant = strtoupper($token);
3888
+ // echo 'Token is a PHPExcel constant: '.$excelConstant.'<br />';
3889
+ $stack->push('Constant Value', self::$excelConstants[$excelConstant]);
3890
+ $this->_debugLog->writeDebugLog('Evaluating Constant ', $excelConstant, ' as ', $this->showTypeDetails(self::$excelConstants[$excelConstant]));
3891
+ } elseif ((is_numeric($token)) || ($token === null) || (is_bool($token)) || ($token == '') || ($token{0} == '"') || ($token{0} == '#')) {
3892
+ // echo 'Token is a number, boolean, string, null or an Excel error<br />';
3893
+ $stack->push('Value', $token);
3894
+ // if the token is a named range, push the named range name onto the stack
3895
+ } elseif (preg_match('/^'.self::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $token, $matches)) {
3896
+ // echo 'Token is a named range<br />';
3897
+ $namedRange = $matches[6];
3898
+ // echo 'Named Range is '.$namedRange.'<br />';
3899
+ $this->_debugLog->writeDebugLog('Evaluating Named Range ', $namedRange);
3900
+ $cellValue = $this->extractNamedRange($namedRange, ((null !== $pCell) ? $pCellWorksheet : null), false);
3901
+ $pCell->attach($pCellParent);
3902
+ $this->_debugLog->writeDebugLog('Evaluation Result for named range ', $namedRange, ' is ', $this->showTypeDetails($cellValue));
3903
+ $stack->push('Named Range', $cellValue, $namedRange);
3904
+ } else {
3905
+ return $this->raiseFormulaError("undefined variable '$token'");
3906
+ }
3907
+ }
3908
+ }
3909
+ // when we're out of tokens, the stack should have a single element, the final result
3910
+ if ($stack->count() != 1) {
3911
+ return $this->raiseFormulaError("internal error");
3912
+ }
3913
+ $output = $stack->pop();
3914
+ $output = $output['value'];
3915
+
3916
+ // if ((is_array($output)) && (self::$returnArrayAsType != self::RETURN_ARRAY_AS_ARRAY)) {
3917
+ // return array_shift(PHPExcel_Calculation_Functions::flattenArray($output));
3918
+ // }
3919
+ return $output;
3920
+ }
3921
+
3922
+
3923
+ private function validateBinaryOperand($cellID, &$operand, &$stack)
3924
+ {
3925
+ if (is_array($operand)) {
3926
+ if ((count($operand, COUNT_RECURSIVE) - count($operand)) == 1) {
3927
+ do {
3928
+ $operand = array_pop($operand);
3929
+ } while (is_array($operand));
3930
+ }
3931
+ }
3932
+ // Numbers, matrices and booleans can pass straight through, as they're already valid
3933
+ if (is_string($operand)) {
3934
+ // We only need special validations for the operand if it is a string
3935
+ // Start by stripping off the quotation marks we use to identify true excel string values internally
3936
+ if ($operand > '' && $operand{0} == '"') {
3937
+ $operand = self::unwrapResult($operand);
3938
+ }
3939
+ // If the string is a numeric value, we treat it as a numeric, so no further testing
3940
+ if (!is_numeric($operand)) {
3941
+ // If not a numeric, test to see if the value is an Excel error, and so can't be used in normal binary operations
3942
+ if ($operand > '' && $operand{0} == '#') {
3943
+ $stack->push('Value', $operand);
3944
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($operand));
3945
+ return false;
3946
+ } elseif (!PHPExcel_Shared_String::convertToNumberIfFraction($operand)) {
3947
+ // If not a numeric or a fraction, then it's a text string, and so can't be used in mathematical binary operations
3948
+ $stack->push('Value', '#VALUE!');
3949
+ $this->_debugLog->writeDebugLog('Evaluation Result is a ', $this->showTypeDetails('#VALUE!'));
3950
+ return false;
3951
+ }
3952
+ }
3953
+ }
3954
+
3955
+ // return a true if the value of the operand is one that we can use in normal binary operations
3956
+ return true;
3957
+ }
3958
+
3959
+
3960
+ private function executeBinaryComparisonOperation($cellID, $operand1, $operand2, $operation, &$stack, $recursingArrays = false)
3961
+ {
3962
+ // If we're dealing with matrix operations, we want a matrix result
3963
+ if ((is_array($operand1)) || (is_array($operand2))) {
3964
+ $result = array();
3965
+ if ((is_array($operand1)) && (!is_array($operand2))) {
3966
+ foreach ($operand1 as $x => $operandData) {
3967
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2));
3968
+ $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2, $operation, $stack);
3969
+ $r = $stack->pop();
3970
+ $result[$x] = $r['value'];
3971
+ }
3972
+ } elseif ((!is_array($operand1)) && (is_array($operand2))) {
3973
+ foreach ($operand2 as $x => $operandData) {
3974
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operand1), ' ', $operation, ' ', $this->showValue($operandData));
3975
+ $this->executeBinaryComparisonOperation($cellID, $operand1, $operandData, $operation, $stack);
3976
+ $r = $stack->pop();
3977
+ $result[$x] = $r['value'];
3978
+ }
3979
+ } else {
3980
+ if (!$recursingArrays) {
3981
+ self::checkMatrixOperands($operand1, $operand2, 2);
3982
+ }
3983
+ foreach ($operand1 as $x => $operandData) {
3984
+ $this->_debugLog->writeDebugLog('Evaluating Comparison ', $this->showValue($operandData), ' ', $operation, ' ', $this->showValue($operand2[$x]));
3985
+ $this->executeBinaryComparisonOperation($cellID, $operandData, $operand2[$x], $operation, $stack, true);
3986
+ $r = $stack->pop();
3987
+ $result[$x] = $r['value'];
3988
+ }
3989
+ }
3990
+ // Log the result details
3991
+ $this->_debugLog->writeDebugLog('Comparison Evaluation Result is ', $this->showTypeDetails($result));
3992
+ // And push the result onto the stack
3993
+ $stack->push('Array', $result);
3994
+ return true;
3995
+ }
3996
+
3997
+ // Simple validate the two operands if they are string values
3998
+ if (is_string($operand1) && $operand1 > '' && $operand1{0} == '"') {
3999
+ $operand1 = self::unwrapResult($operand1);
4000
+ }
4001
+ if (is_string($operand2) && $operand2 > '' && $operand2{0} == '"') {
4002
+ $operand2 = self::unwrapResult($operand2);
4003
+ }
4004
+
4005
+ // Use case insensitive comparaison if not OpenOffice mode
4006
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
4007
+ if (is_string($operand1)) {
4008
+ $operand1 = strtoupper($operand1);
4009
+ }
4010
+ if (is_string($operand2)) {
4011
+ $operand2 = strtoupper($operand2);
4012
+ }
4013
+ }
4014
+
4015
+ $useLowercaseFirstComparison = is_string($operand1) && is_string($operand2) && PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE;
4016
+
4017
+ // execute the necessary operation
4018
+ switch ($operation) {
4019
+ // Greater than
4020
+ case '>':
4021
+ if ($useLowercaseFirstComparison) {
4022
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) > 0;
4023
+ } else {
4024
+ $result = ($operand1 > $operand2);
4025
+ }
4026
+ break;
4027
+ // Less than
4028
+ case '<':
4029
+ if ($useLowercaseFirstComparison) {
4030
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) < 0;
4031
+ } else {
4032
+ $result = ($operand1 < $operand2);
4033
+ }
4034
+ break;
4035
+ // Equality
4036
+ case '=':
4037
+ if (is_numeric($operand1) && is_numeric($operand2)) {
4038
+ $result = (abs($operand1 - $operand2) < $this->delta);
4039
+ } else {
4040
+ $result = strcmp($operand1, $operand2) == 0;
4041
+ }
4042
+ break;
4043
+ // Greater than or equal
4044
+ case '>=':
4045
+ if (is_numeric($operand1) && is_numeric($operand2)) {
4046
+ $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 > $operand2));
4047
+ } elseif ($useLowercaseFirstComparison) {
4048
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) >= 0;
4049
+ } else {
4050
+ $result = strcmp($operand1, $operand2) >= 0;
4051
+ }
4052
+ break;
4053
+ // Less than or equal
4054
+ case '<=':
4055
+ if (is_numeric($operand1) && is_numeric($operand2)) {
4056
+ $result = ((abs($operand1 - $operand2) < $this->delta) || ($operand1 < $operand2));
4057
+ } elseif ($useLowercaseFirstComparison) {
4058
+ $result = $this->strcmpLowercaseFirst($operand1, $operand2) <= 0;
4059
+ } else {
4060
+ $result = strcmp($operand1, $operand2) <= 0;
4061
+ }
4062
+ break;
4063
+ // Inequality
4064
+ case '<>':
4065
+ if (is_numeric($operand1) && is_numeric($operand2)) {
4066
+ $result = (abs($operand1 - $operand2) > 1E-14);
4067
+ } else {
4068
+ $result = strcmp($operand1, $operand2) != 0;
4069
+ }
4070
+ break;
4071
+ }
4072
+
4073
+ // Log the result details
4074
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result));
4075
+ // And push the result onto the stack
4076
+ $stack->push('Value', $result);
4077
+ return true;
4078
+ }
4079
+
4080
+ /**
4081
+ * Compare two strings in the same way as strcmp() except that lowercase come before uppercase letters
4082
+ * @param string $str1 First string value for the comparison
4083
+ * @param string $str2 Second string value for the comparison
4084
+ * @return integer
4085
+ */
4086
+ private function strcmpLowercaseFirst($str1, $str2)
4087
+ {
4088
+ $inversedStr1 = PHPExcel_Shared_String::StrCaseReverse($str1);
4089
+ $inversedStr2 = PHPExcel_Shared_String::StrCaseReverse($str2);
4090
+
4091
+ return strcmp($inversedStr1, $inversedStr2);
4092
+ }
4093
+
4094
+ private function executeNumericBinaryOperation($cellID, $operand1, $operand2, $operation, $matrixFunction, &$stack)
4095
+ {
4096
+ // Validate the two operands
4097
+ if (!$this->validateBinaryOperand($cellID, $operand1, $stack)) {
4098
+ return false;
4099
+ }
4100
+ if (!$this->validateBinaryOperand($cellID, $operand2, $stack)) {
4101
+ return false;
4102
+ }
4103
+
4104
+ // If either of the operands is a matrix, we need to treat them both as matrices
4105
+ // (converting the other operand to a matrix if need be); then perform the required
4106
+ // matrix operation
4107
+ if ((is_array($operand1)) || (is_array($operand2))) {
4108
+ // Ensure that both operands are arrays/matrices of the same size
4109
+ self::checkMatrixOperands($operand1, $operand2, 2);
4110
+
4111
+ try {
4112
+ // Convert operand 1 from a PHP array to a matrix
4113
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($operand1);
4114
+ // Perform the required operation against the operand 1 matrix, passing in operand 2
4115
+ $matrixResult = $matrix->$matrixFunction($operand2);
4116
+ $result = $matrixResult->getArray();
4117
+ } catch (PHPExcel_Exception $ex) {
4118
+ $this->_debugLog->writeDebugLog('JAMA Matrix Exception: ', $ex->getMessage());
4119
+ $result = '#VALUE!';
4120
+ }
4121
+ } else {
4122
+ if ((PHPExcel_Calculation_Functions::getCompatibilityMode() != PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) &&
4123
+ ((is_string($operand1) && !is_numeric($operand1) && strlen($operand1)>0) ||
4124
+ (is_string($operand2) && !is_numeric($operand2) && strlen($operand2)>0))) {
4125
+ $result = PHPExcel_Calculation_Functions::VALUE();
4126
+ } else {
4127
+ // If we're dealing with non-matrix operations, execute the necessary operation
4128
+ switch ($operation) {
4129
+ // Addition
4130
+ case '+':
4131
+ $result = $operand1 + $operand2;
4132
+ break;
4133
+ // Subtraction
4134
+ case '-':
4135
+ $result = $operand1 - $operand2;
4136
+ break;
4137
+ // Multiplication
4138
+ case '*':
4139
+ $result = $operand1 * $operand2;
4140
+ break;
4141
+ // Division
4142
+ case '/':
4143
+ if ($operand2 == 0) {
4144
+ // Trap for Divide by Zero error
4145
+ $stack->push('Value', '#DIV/0!');
4146
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails('#DIV/0!'));
4147
+ return false;
4148
+ } else {
4149
+ $result = $operand1 / $operand2;
4150
+ }
4151
+ break;
4152
+ // Power
4153
+ case '^':
4154
+ $result = pow($operand1, $operand2);
4155
+ break;
4156
+ }
4157
+ }
4158
+ }
4159
+
4160
+ // Log the result details
4161
+ $this->_debugLog->writeDebugLog('Evaluation Result is ', $this->showTypeDetails($result));
4162
+ // And push the result onto the stack
4163
+ $stack->push('Value', $result);
4164
+ return true;
4165
+ }
4166
+
4167
+
4168
+ // trigger an error, but nicely, if need be
4169
+ protected function raiseFormulaError($errorMessage)
4170
+ {
4171
+ $this->formulaError = $errorMessage;
4172
+ $this->cyclicReferenceStack->clear();
4173
+ if (!$this->suppressFormulaErrors) {
4174
+ throw new PHPExcel_Calculation_Exception($errorMessage);
4175
+ }
4176
+ trigger_error($errorMessage, E_USER_ERROR);
4177
+ }
4178
+
4179
+
4180
+ /**
4181
+ * Extract range values
4182
+ *
4183
+ * @param string &$pRange String based range representation
4184
+ * @param PHPExcel_Worksheet $pSheet Worksheet
4185
+ * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
4186
+ * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
4187
+ * @throws PHPExcel_Calculation_Exception
4188
+ */
4189
+ public function extractCellRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = null, $resetLog = true)
4190
+ {
4191
+ // Return value
4192
+ $returnValue = array ();
4193
+
4194
+ // echo 'extractCellRange('.$pRange.')', PHP_EOL;
4195
+ if ($pSheet !== null) {
4196
+ $pSheetName = $pSheet->getTitle();
4197
+ // echo 'Passed sheet name is '.$pSheetName.PHP_EOL;
4198
+ // echo 'Range reference is '.$pRange.PHP_EOL;
4199
+ if (strpos($pRange, '!') !== false) {
4200
+ // echo '$pRange reference includes sheet reference', PHP_EOL;
4201
+ list($pSheetName, $pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true);
4202
+ // echo 'New sheet name is '.$pSheetName, PHP_EOL;
4203
+ // echo 'Adjusted Range reference is '.$pRange, PHP_EOL;
4204
+ $pSheet = $this->workbook->getSheetByName($pSheetName);
4205
+ }
4206
+
4207
+ // Extract range
4208
+ $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
4209
+ $pRange = $pSheetName.'!'.$pRange;
4210
+ if (!isset($aReferences[1])) {
4211
+ // Single cell in range
4212
+ sscanf($aReferences[0], '%[A-Z]%d', $currentCol, $currentRow);
4213
+ $cellValue = null;
4214
+ if ($pSheet->cellExists($aReferences[0])) {
4215
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
4216
+ } else {
4217
+ $returnValue[$currentRow][$currentCol] = null;
4218
+ }
4219
+ } else {
4220
+ // Extract cell data for all cells in the range
4221
+ foreach ($aReferences as $reference) {
4222
+ // Extract range
4223
+ sscanf($reference, '%[A-Z]%d', $currentCol, $currentRow);
4224
+ $cellValue = null;
4225
+ if ($pSheet->cellExists($reference)) {
4226
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
4227
+ } else {
4228
+ $returnValue[$currentRow][$currentCol] = null;
4229
+ }
4230
+ }
4231
+ }
4232
+ }
4233
+
4234
+ return $returnValue;
4235
+ }
4236
+
4237
+
4238
+ /**
4239
+ * Extract range values
4240
+ *
4241
+ * @param string &$pRange String based range representation
4242
+ * @param PHPExcel_Worksheet $pSheet Worksheet
4243
+ * @return mixed Array of values in range if range contains more than one element. Otherwise, a single value is returned.
4244
+ * @param boolean $resetLog Flag indicating whether calculation log should be reset or not
4245
+ * @throws PHPExcel_Calculation_Exception
4246
+ */
4247
+ public function extractNamedRange(&$pRange = 'A1', PHPExcel_Worksheet $pSheet = null, $resetLog = true)
4248
+ {
4249
+ // Return value
4250
+ $returnValue = array ();
4251
+
4252
+ // echo 'extractNamedRange('.$pRange.')<br />';
4253
+ if ($pSheet !== null) {
4254
+ $pSheetName = $pSheet->getTitle();
4255
+ // echo 'Current sheet name is '.$pSheetName.'<br />';
4256
+ // echo 'Range reference is '.$pRange.'<br />';
4257
+ if (strpos($pRange, '!') !== false) {
4258
+ // echo '$pRange reference includes sheet reference', PHP_EOL;
4259
+ list($pSheetName, $pRange) = PHPExcel_Worksheet::extractSheetTitle($pRange, true);
4260
+ // echo 'New sheet name is '.$pSheetName, PHP_EOL;
4261
+ // echo 'Adjusted Range reference is '.$pRange, PHP_EOL;
4262
+ $pSheet = $this->workbook->getSheetByName($pSheetName);
4263
+ }
4264
+
4265
+ // Named range?
4266
+ $namedRange = PHPExcel_NamedRange::resolveRange($pRange, $pSheet);
4267
+ if ($namedRange !== null) {
4268
+ $pSheet = $namedRange->getWorksheet();
4269
+ // echo 'Named Range '.$pRange.' (';
4270
+ $pRange = $namedRange->getRange();
4271
+ $splitRange = PHPExcel_Cell::splitRange($pRange);
4272
+ // Convert row and column references
4273
+ if (ctype_alpha($splitRange[0][0])) {
4274
+ $pRange = $splitRange[0][0] . '1:' . $splitRange[0][1] . $namedRange->getWorksheet()->getHighestRow();
4275
+ } elseif (ctype_digit($splitRange[0][0])) {
4276
+ $pRange = 'A' . $splitRange[0][0] . ':' . $namedRange->getWorksheet()->getHighestColumn() . $splitRange[0][1];
4277
+ }
4278
+ // echo $pRange.') is in sheet '.$namedRange->getWorksheet()->getTitle().'<br />';
4279
+
4280
+ // if ($pSheet->getTitle() != $namedRange->getWorksheet()->getTitle()) {
4281
+ // if (!$namedRange->getLocalOnly()) {
4282
+ // $pSheet = $namedRange->getWorksheet();
4283
+ // } else {
4284
+ // return $returnValue;
4285
+ // }
4286
+ // }
4287
+ } else {
4288
+ return PHPExcel_Calculation_Functions::REF();
4289
+ }
4290
+
4291
+ // Extract range
4292
+ $aReferences = PHPExcel_Cell::extractAllCellReferencesInRange($pRange);
4293
+ // var_dump($aReferences);
4294
+ if (!isset($aReferences[1])) {
4295
+ // Single cell (or single column or row) in range
4296
+ list($currentCol, $currentRow) = PHPExcel_Cell::coordinateFromString($aReferences[0]);
4297
+ $cellValue = null;
4298
+ if ($pSheet->cellExists($aReferences[0])) {
4299
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($aReferences[0])->getCalculatedValue($resetLog);
4300
+ } else {
4301
+ $returnValue[$currentRow][$currentCol] = null;
4302
+ }
4303
+ } else {
4304
+ // Extract cell data for all cells in the range
4305
+ foreach ($aReferences as $reference) {
4306
+ // Extract range
4307
+ list($currentCol, $currentRow) = PHPExcel_Cell::coordinateFromString($reference);
4308
+ // echo 'NAMED RANGE: $currentCol='.$currentCol.' $currentRow='.$currentRow.'<br />';
4309
+ $cellValue = null;
4310
+ if ($pSheet->cellExists($reference)) {
4311
+ $returnValue[$currentRow][$currentCol] = $pSheet->getCell($reference)->getCalculatedValue($resetLog);
4312
+ } else {
4313
+ $returnValue[$currentRow][$currentCol] = null;
4314
+ }
4315
+ }
4316
+ }
4317
+ // print_r($returnValue);
4318
+ // echo '<br />';
4319
+ }
4320
+
4321
+ return $returnValue;
4322
+ }
4323
+
4324
+
4325
+ /**
4326
+ * Is a specific function implemented?
4327
+ *
4328
+ * @param string $pFunction Function Name
4329
+ * @return boolean
4330
+ */
4331
+ public function isImplemented($pFunction = '')
4332
+ {
4333
+ $pFunction = strtoupper($pFunction);
4334
+ if (isset(self::$PHPExcelFunctions[$pFunction])) {
4335
+ return (self::$PHPExcelFunctions[$pFunction]['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY');
4336
+ } else {
4337
+ return false;
4338
+ }
4339
+ }
4340
+
4341
+
4342
+ /**
4343
+ * Get a list of all implemented functions as an array of function objects
4344
+ *
4345
+ * @return array of PHPExcel_Calculation_Function
4346
+ */
4347
+ public function listFunctions()
4348
+ {
4349
+ $returnValue = array();
4350
+
4351
+ foreach (self::$PHPExcelFunctions as $functionName => $function) {
4352
+ if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') {
4353
+ $returnValue[$functionName] = new PHPExcel_Calculation_Function(
4354
+ $function['category'],
4355
+ $functionName,
4356
+ $function['functionCall']
4357
+ );
4358
+ }
4359
+ }
4360
+
4361
+ return $returnValue;
4362
+ }
4363
+
4364
+
4365
+ /**
4366
+ * Get a list of all Excel function names
4367
+ *
4368
+ * @return array
4369
+ */
4370
+ public function listAllFunctionNames()
4371
+ {
4372
+ return array_keys(self::$PHPExcelFunctions);
4373
+ }
4374
+
4375
+ /**
4376
+ * Get a list of implemented Excel function names
4377
+ *
4378
+ * @return array
4379
+ */
4380
+ public function listFunctionNames()
4381
+ {
4382
+ $returnValue = array();
4383
+ foreach (self::$PHPExcelFunctions as $functionName => $function) {
4384
+ if ($function['functionCall'] != 'PHPExcel_Calculation_Functions::DUMMY') {
4385
+ $returnValue[] = $functionName;
4386
+ }
4387
+ }
4388
+
4389
+ return $returnValue;
4390
+ }
4391
+ }
classes/PHPExcel/Calculation/Database.php ADDED
@@ -0,0 +1,676 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+ /**
13
+ * PHPExcel_Calculation_Database
14
+ *
15
+ * Copyright (c) 2006 - 2015 PHPExcel
16
+ *
17
+ * This library is free software; you can redistribute it and/or
18
+ * modify it under the terms of the GNU Lesser General Public
19
+ * License as published by the Free Software Foundation; either
20
+ * version 2.1 of the License, or (at your option) any later version.
21
+ *
22
+ * This library is distributed in the hope that it will be useful,
23
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25
+ * Lesser General Public License for more details.
26
+ *
27
+ * You should have received a copy of the GNU Lesser General Public
28
+ * License along with this library; if not, write to the Free Software
29
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30
+ *
31
+ * @category PHPExcel
32
+ * @package PHPExcel_Calculation
33
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
34
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
35
+ * @version ##VERSION##, ##DATE##
36
+ */
37
+ class PHPExcel_Calculation_Database
38
+ {
39
+ /**
40
+ * fieldExtract
41
+ *
42
+ * Extracts the column ID to use for the data field.
43
+ *
44
+ * @access private
45
+ * @param mixed[] $database The range of cells that makes up the list or database.
46
+ * A database is a list of related data in which rows of related
47
+ * information are records, and columns of data are fields. The
48
+ * first row of the list contains labels for each column.
49
+ * @param mixed $field Indicates which column is used in the function. Enter the
50
+ * column label enclosed between double quotation marks, such as
51
+ * "Age" or "Yield," or a number (without quotation marks) that
52
+ * represents the position of the column within the list: 1 for
53
+ * the first column, 2 for the second column, and so on.
54
+ * @return string|NULL
55
+ *
56
+ */
57
+ private static function fieldExtract($database, $field)
58
+ {
59
+ $field = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($field));
60
+ $fieldNames = array_map('strtoupper', array_shift($database));
61
+
62
+ if (is_numeric($field)) {
63
+ $keys = array_keys($fieldNames);
64
+ return $keys[$field-1];
65
+ }
66
+ $key = array_search($field, $fieldNames);
67
+ return ($key) ? $key : null;
68
+ }
69
+
70
+ /**
71
+ * filter
72
+ *
73
+ * Parses the selection criteria, extracts the database rows that match those criteria, and
74
+ * returns that subset of rows.
75
+ *
76
+ * @access private
77
+ * @param mixed[] $database The range of cells that makes up the list or database.
78
+ * A database is a list of related data in which rows of related
79
+ * information are records, and columns of data are fields. The
80
+ * first row of the list contains labels for each column.
81
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
82
+ * You can use any range for the criteria argument, as long as it
83
+ * includes at least one column label and at least one cell below
84
+ * the column label in which you specify a condition for the
85
+ * column.
86
+ * @return array of mixed
87
+ *
88
+ */
89
+ private static function filter($database, $criteria)
90
+ {
91
+ $fieldNames = array_shift($database);
92
+ $criteriaNames = array_shift($criteria);
93
+
94
+ // Convert the criteria into a set of AND/OR conditions with [:placeholders]
95
+ $testConditions = $testValues = array();
96
+ $testConditionsCount = 0;
97
+ foreach ($criteriaNames as $key => $criteriaName) {
98
+ $testCondition = array();
99
+ $testConditionCount = 0;
100
+ foreach ($criteria as $row => $criterion) {
101
+ if ($criterion[$key] > '') {
102
+ $testCondition[] = '[:'.$criteriaName.']'.PHPExcel_Calculation_Functions::ifCondition($criterion[$key]);
103
+ $testConditionCount++;
104
+ }
105
+ }
106
+ if ($testConditionCount > 1) {
107
+ $testConditions[] = 'OR(' . implode(',', $testCondition) . ')';
108
+ $testConditionsCount++;
109
+ } elseif ($testConditionCount == 1) {
110
+ $testConditions[] = $testCondition[0];
111
+ $testConditionsCount++;
112
+ }
113
+ }
114
+
115
+ if ($testConditionsCount > 1) {
116
+ $testConditionSet = 'AND(' . implode(',', $testConditions) . ')';
117
+ } elseif ($testConditionsCount == 1) {
118
+ $testConditionSet = $testConditions[0];
119
+ }
120
+
121
+ // Loop through each row of the database
122
+ foreach ($database as $dataRow => $dataValues) {
123
+ // Substitute actual values from the database row for our [:placeholders]
124
+ $testConditionList = $testConditionSet;
125
+ foreach ($criteriaNames as $key => $criteriaName) {
126
+ $k = array_search($criteriaName, $fieldNames);
127
+ if (isset($dataValues[$k])) {
128
+ $dataValue = $dataValues[$k];
129
+ $dataValue = (is_string($dataValue)) ? PHPExcel_Calculation::wrapResult(strtoupper($dataValue)) : $dataValue;
130
+ $testConditionList = str_replace('[:' . $criteriaName . ']', $dataValue, $testConditionList);
131
+ }
132
+ }
133
+ // evaluate the criteria against the row data
134
+ $result = PHPExcel_Calculation::getInstance()->_calculateFormulaValue('='.$testConditionList);
135
+ // If the row failed to meet the criteria, remove it from the database
136
+ if (!$result) {
137
+ unset($database[$dataRow]);
138
+ }
139
+ }
140
+
141
+ return $database;
142
+ }
143
+
144
+
145
+ private static function getFilteredColumn($database, $field, $criteria)
146
+ {
147
+ // reduce the database to a set of rows that match all the criteria
148
+ $database = self::filter($database, $criteria);
149
+ // extract an array of values for the requested column
150
+ $colData = array();
151
+ foreach ($database as $row) {
152
+ $colData[] = $row[$field];
153
+ }
154
+
155
+ return $colData;
156
+ }
157
+
158
+ /**
159
+ * DAVERAGE
160
+ *
161
+ * Averages the values in a column of a list or database that match conditions you specify.
162
+ *
163
+ * Excel Function:
164
+ * DAVERAGE(database,field,criteria)
165
+ *
166
+ * @access public
167
+ * @category Database Functions
168
+ * @param mixed[] $database The range of cells that makes up the list or database.
169
+ * A database is a list of related data in which rows of related
170
+ * information are records, and columns of data are fields. The
171
+ * first row of the list contains labels for each column.
172
+ * @param string|integer $field Indicates which column is used in the function. Enter the
173
+ * column label enclosed between double quotation marks, such as
174
+ * "Age" or "Yield," or a number (without quotation marks) that
175
+ * represents the position of the column within the list: 1 for
176
+ * the first column, 2 for the second column, and so on.
177
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
178
+ * You can use any range for the criteria argument, as long as it
179
+ * includes at least one column label and at least one cell below
180
+ * the column label in which you specify a condition for the
181
+ * column.
182
+ * @return float
183
+ *
184
+ */
185
+ public static function DAVERAGE($database, $field, $criteria)
186
+ {
187
+ $field = self::fieldExtract($database, $field);
188
+ if (is_null($field)) {
189
+ return null;
190
+ }
191
+
192
+ // Return
193
+ return PHPExcel_Calculation_Statistical::AVERAGE(
194
+ self::getFilteredColumn($database, $field, $criteria)
195
+ );
196
+ }
197
+
198
+
199
+ /**
200
+ * DCOUNT
201
+ *
202
+ * Counts the cells that contain numbers in a column of a list or database that match conditions
203
+ * that you specify.
204
+ *
205
+ * Excel Function:
206
+ * DCOUNT(database,[field],criteria)
207
+ *
208
+ * Excel Function:
209
+ * DAVERAGE(database,field,criteria)
210
+ *
211
+ * @access public
212
+ * @category Database Functions
213
+ * @param mixed[] $database The range of cells that makes up the list or database.
214
+ * A database is a list of related data in which rows of related
215
+ * information are records, and columns of data are fields. The
216
+ * first row of the list contains labels for each column.
217
+ * @param string|integer $field Indicates which column is used in the function. Enter the
218
+ * column label enclosed between double quotation marks, such as
219
+ * "Age" or "Yield," or a number (without quotation marks) that
220
+ * represents the position of the column within the list: 1 for
221
+ * the first column, 2 for the second column, and so on.
222
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
223
+ * You can use any range for the criteria argument, as long as it
224
+ * includes at least one column label and at least one cell below
225
+ * the column label in which you specify a condition for the
226
+ * column.
227
+ * @return integer
228
+ *
229
+ * @TODO The field argument is optional. If field is omitted, DCOUNT counts all records in the
230
+ * database that match the criteria.
231
+ *
232
+ */
233
+ public static function DCOUNT($database, $field, $criteria)
234
+ {
235
+ $field = self::fieldExtract($database, $field);
236
+ if (is_null($field)) {
237
+ return null;
238
+ }
239
+
240
+ // Return
241
+ return PHPExcel_Calculation_Statistical::COUNT(
242
+ self::getFilteredColumn($database, $field, $criteria)
243
+ );
244
+ }
245
+
246
+
247
+ /**
248
+ * DCOUNTA
249
+ *
250
+ * Counts the nonblank cells in a column of a list or database that match conditions that you specify.
251
+ *
252
+ * Excel Function:
253
+ * DCOUNTA(database,[field],criteria)
254
+ *
255
+ * @access public
256
+ * @category Database Functions
257
+ * @param mixed[] $database The range of cells that makes up the list or database.
258
+ * A database is a list of related data in which rows of related
259
+ * information are records, and columns of data are fields. The
260
+ * first row of the list contains labels for each column.
261
+ * @param string|integer $field Indicates which column is used in the function. Enter the
262
+ * column label enclosed between double quotation marks, such as
263
+ * "Age" or "Yield," or a number (without quotation marks) that
264
+ * represents the position of the column within the list: 1 for
265
+ * the first column, 2 for the second column, and so on.
266
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
267
+ * You can use any range for the criteria argument, as long as it
268
+ * includes at least one column label and at least one cell below
269
+ * the column label in which you specify a condition for the
270
+ * column.
271
+ * @return integer
272
+ *
273
+ * @TODO The field argument is optional. If field is omitted, DCOUNTA counts all records in the
274
+ * database that match the criteria.
275
+ *
276
+ */
277
+ public static function DCOUNTA($database, $field, $criteria)
278
+ {
279
+ $field = self::fieldExtract($database, $field);
280
+ if (is_null($field)) {
281
+ return null;
282
+ }
283
+
284
+ // reduce the database to a set of rows that match all the criteria
285
+ $database = self::filter($database, $criteria);
286
+ // extract an array of values for the requested column
287
+ $colData = array();
288
+ foreach ($database as $row) {
289
+ $colData[] = $row[$field];
290
+ }
291
+
292
+ // Return
293
+ return PHPExcel_Calculation_Statistical::COUNTA(
294
+ self::getFilteredColumn($database, $field, $criteria)
295
+ );
296
+ }
297
+
298
+
299
+ /**
300
+ * DGET
301
+ *
302
+ * Extracts a single value from a column of a list or database that matches conditions that you
303
+ * specify.
304
+ *
305
+ * Excel Function:
306
+ * DGET(database,field,criteria)
307
+ *
308
+ * @access public
309
+ * @category Database Functions
310
+ * @param mixed[] $database The range of cells that makes up the list or database.
311
+ * A database is a list of related data in which rows of related
312
+ * information are records, and columns of data are fields. The
313
+ * first row of the list contains labels for each column.
314
+ * @param string|integer $field Indicates which column is used in the function. Enter the
315
+ * column label enclosed between double quotation marks, such as
316
+ * "Age" or "Yield," or a number (without quotation marks) that
317
+ * represents the position of the column within the list: 1 for
318
+ * the first column, 2 for the second column, and so on.
319
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
320
+ * You can use any range for the criteria argument, as long as it
321
+ * includes at least one column label and at least one cell below
322
+ * the column label in which you specify a condition for the
323
+ * column.
324
+ * @return mixed
325
+ *
326
+ */
327
+ public static function DGET($database, $field, $criteria)
328
+ {
329
+ $field = self::fieldExtract($database, $field);
330
+ if (is_null($field)) {
331
+ return null;
332
+ }
333
+
334
+ // Return
335
+ $colData = self::getFilteredColumn($database, $field, $criteria);
336
+ if (count($colData) > 1) {
337
+ return PHPExcel_Calculation_Functions::NaN();
338
+ }
339
+
340
+ return $colData[0];
341
+ }
342
+
343
+
344
+ /**
345
+ * DMAX
346
+ *
347
+ * Returns the largest number in a column of a list or database that matches conditions you that
348
+ * specify.
349
+ *
350
+ * Excel Function:
351
+ * DMAX(database,field,criteria)
352
+ *
353
+ * @access public
354
+ * @category Database Functions
355
+ * @param mixed[] $database The range of cells that makes up the list or database.
356
+ * A database is a list of related data in which rows of related
357
+ * information are records, and columns of data are fields. The
358
+ * first row of the list contains labels for each column.
359
+ * @param string|integer $field Indicates which column is used in the function. Enter the
360
+ * column label enclosed between double quotation marks, such as
361
+ * "Age" or "Yield," or a number (without quotation marks) that
362
+ * represents the position of the column within the list: 1 for
363
+ * the first column, 2 for the second column, and so on.
364
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
365
+ * You can use any range for the criteria argument, as long as it
366
+ * includes at least one column label and at least one cell below
367
+ * the column label in which you specify a condition for the
368
+ * column.
369
+ * @return float
370
+ *
371
+ */
372
+ public static function DMAX($database, $field, $criteria)
373
+ {
374
+ $field = self::fieldExtract($database, $field);
375
+ if (is_null($field)) {
376
+ return null;
377
+ }
378
+
379
+ // Return
380
+ return PHPExcel_Calculation_Statistical::MAX(
381
+ self::getFilteredColumn($database, $field, $criteria)
382
+ );
383
+ }
384
+
385
+
386
+ /**
387
+ * DMIN
388
+ *
389
+ * Returns the smallest number in a column of a list or database that matches conditions you that
390
+ * specify.
391
+ *
392
+ * Excel Function:
393
+ * DMIN(database,field,criteria)
394
+ *
395
+ * @access public
396
+ * @category Database Functions
397
+ * @param mixed[] $database The range of cells that makes up the list or database.
398
+ * A database is a list of related data in which rows of related
399
+ * information are records, and columns of data are fields. The
400
+ * first row of the list contains labels for each column.
401
+ * @param string|integer $field Indicates which column is used in the function. Enter the
402
+ * column label enclosed between double quotation marks, such as
403
+ * "Age" or "Yield," or a number (without quotation marks) that
404
+ * represents the position of the column within the list: 1 for
405
+ * the first column, 2 for the second column, and so on.
406
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
407
+ * You can use any range for the criteria argument, as long as it
408
+ * includes at least one column label and at least one cell below
409
+ * the column label in which you specify a condition for the
410
+ * column.
411
+ * @return float
412
+ *
413
+ */
414
+ public static function DMIN($database, $field, $criteria)
415
+ {
416
+ $field = self::fieldExtract($database, $field);
417
+ if (is_null($field)) {
418
+ return null;
419
+ }
420
+
421
+ // Return
422
+ return PHPExcel_Calculation_Statistical::MIN(
423
+ self::getFilteredColumn($database, $field, $criteria)
424
+ );
425
+ }
426
+
427
+
428
+ /**
429
+ * DPRODUCT
430
+ *
431
+ * Multiplies the values in a column of a list or database that match conditions that you specify.
432
+ *
433
+ * Excel Function:
434
+ * DPRODUCT(database,field,criteria)
435
+ *
436
+ * @access public
437
+ * @category Database Functions
438
+ * @param mixed[] $database The range of cells that makes up the list or database.
439
+ * A database is a list of related data in which rows of related
440
+ * information are records, and columns of data are fields. The
441
+ * first row of the list contains labels for each column.
442
+ * @param string|integer $field Indicates which column is used in the function. Enter the
443
+ * column label enclosed between double quotation marks, such as
444
+ * "Age" or "Yield," or a number (without quotation marks) that
445
+ * represents the position of the column within the list: 1 for
446
+ * the first column, 2 for the second column, and so on.
447
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
448
+ * You can use any range for the criteria argument, as long as it
449
+ * includes at least one column label and at least one cell below
450
+ * the column label in which you specify a condition for the
451
+ * column.
452
+ * @return float
453
+ *
454
+ */
455
+ public static function DPRODUCT($database, $field, $criteria)
456
+ {
457
+ $field = self::fieldExtract($database, $field);
458
+ if (is_null($field)) {
459
+ return null;
460
+ }
461
+
462
+ // Return
463
+ return PHPExcel_Calculation_MathTrig::PRODUCT(
464
+ self::getFilteredColumn($database, $field, $criteria)
465
+ );
466
+ }
467
+
468
+
469
+ /**
470
+ * DSTDEV
471
+ *
472
+ * Estimates the standard deviation of a population based on a sample by using the numbers in a
473
+ * column of a list or database that match conditions that you specify.
474
+ *
475
+ * Excel Function:
476
+ * DSTDEV(database,field,criteria)
477
+ *
478
+ * @access public
479
+ * @category Database Functions
480
+ * @param mixed[] $database The range of cells that makes up the list or database.
481
+ * A database is a list of related data in which rows of related
482
+ * information are records, and columns of data are fields. The
483
+ * first row of the list contains labels for each column.
484
+ * @param string|integer $field Indicates which column is used in the function. Enter the
485
+ * column label enclosed between double quotation marks, such as
486
+ * "Age" or "Yield," or a number (without quotation marks) that
487
+ * represents the position of the column within the list: 1 for
488
+ * the first column, 2 for the second column, and so on.
489
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
490
+ * You can use any range for the criteria argument, as long as it
491
+ * includes at least one column label and at least one cell below
492
+ * the column label in which you specify a condition for the
493
+ * column.
494
+ * @return float
495
+ *
496
+ */
497
+ public static function DSTDEV($database, $field, $criteria)
498
+ {
499
+ $field = self::fieldExtract($database, $field);
500
+ if (is_null($field)) {
501
+ return null;
502
+ }
503
+
504
+ // Return
505
+ return PHPExcel_Calculation_Statistical::STDEV(
506
+ self::getFilteredColumn($database, $field, $criteria)
507
+ );
508
+ }
509
+
510
+
511
+ /**
512
+ * DSTDEVP
513
+ *
514
+ * Calculates the standard deviation of a population based on the entire population by using the
515
+ * numbers in a column of a list or database that match conditions that you specify.
516
+ *
517
+ * Excel Function:
518
+ * DSTDEVP(database,field,criteria)
519
+ *
520
+ * @access public
521
+ * @category Database Functions
522
+ * @param mixed[] $database The range of cells that makes up the list or database.
523
+ * A database is a list of related data in which rows of related
524
+ * information are records, and columns of data are fields. The
525
+ * first row of the list contains labels for each column.
526
+ * @param string|integer $field Indicates which column is used in the function. Enter the
527
+ * column label enclosed between double quotation marks, such as
528
+ * "Age" or "Yield," or a number (without quotation marks) that
529
+ * represents the position of the column within the list: 1 for
530
+ * the first column, 2 for the second column, and so on.
531
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
532
+ * You can use any range for the criteria argument, as long as it
533
+ * includes at least one column label and at least one cell below
534
+ * the column label in which you specify a condition for the
535
+ * column.
536
+ * @return float
537
+ *
538
+ */
539
+ public static function DSTDEVP($database, $field, $criteria)
540
+ {
541
+ $field = self::fieldExtract($database, $field);
542
+ if (is_null($field)) {
543
+ return null;
544
+ }
545
+
546
+ // Return
547
+ return PHPExcel_Calculation_Statistical::STDEVP(
548
+ self::getFilteredColumn($database, $field, $criteria)
549
+ );
550
+ }
551
+
552
+
553
+ /**
554
+ * DSUM
555
+ *
556
+ * Adds the numbers in a column of a list or database that match conditions that you specify.
557
+ *
558
+ * Excel Function:
559
+ * DSUM(database,field,criteria)
560
+ *
561
+ * @access public
562
+ * @category Database Functions
563
+ * @param mixed[] $database The range of cells that makes up the list or database.
564
+ * A database is a list of related data in which rows of related
565
+ * information are records, and columns of data are fields. The
566
+ * first row of the list contains labels for each column.
567
+ * @param string|integer $field Indicates which column is used in the function. Enter the
568
+ * column label enclosed between double quotation marks, such as
569
+ * "Age" or "Yield," or a number (without quotation marks) that
570
+ * represents the position of the column within the list: 1 for
571
+ * the first column, 2 for the second column, and so on.
572
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
573
+ * You can use any range for the criteria argument, as long as it
574
+ * includes at least one column label and at least one cell below
575
+ * the column label in which you specify a condition for the
576
+ * column.
577
+ * @return float
578
+ *
579
+ */
580
+ public static function DSUM($database, $field, $criteria)
581
+ {
582
+ $field = self::fieldExtract($database, $field);
583
+ if (is_null($field)) {
584
+ return null;
585
+ }
586
+
587
+ // Return
588
+ return PHPExcel_Calculation_MathTrig::SUM(
589
+ self::getFilteredColumn($database, $field, $criteria)
590
+ );
591
+ }
592
+
593
+
594
+ /**
595
+ * DVAR
596
+ *
597
+ * Estimates the variance of a population based on a sample by using the numbers in a column
598
+ * of a list or database that match conditions that you specify.
599
+ *
600
+ * Excel Function:
601
+ * DVAR(database,field,criteria)
602
+ *
603
+ * @access public
604
+ * @category Database Functions
605
+ * @param mixed[] $database The range of cells that makes up the list or database.
606
+ * A database is a list of related data in which rows of related
607
+ * information are records, and columns of data are fields. The
608
+ * first row of the list contains labels for each column.
609
+ * @param string|integer $field Indicates which column is used in the function. Enter the
610
+ * column label enclosed between double quotation marks, such as
611
+ * "Age" or "Yield," or a number (without quotation marks) that
612
+ * represents the position of the column within the list: 1 for
613
+ * the first column, 2 for the second column, and so on.
614
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
615
+ * You can use any range for the criteria argument, as long as it
616
+ * includes at least one column label and at least one cell below
617
+ * the column label in which you specify a condition for the
618
+ * column.
619
+ * @return float
620
+ *
621
+ */
622
+ public static function DVAR($database, $field, $criteria)
623
+ {
624
+ $field = self::fieldExtract($database, $field);
625
+ if (is_null($field)) {
626
+ return null;
627
+ }
628
+
629
+ // Return
630
+ return PHPExcel_Calculation_Statistical::VARFunc(
631
+ self::getFilteredColumn($database, $field, $criteria)
632
+ );
633
+ }
634
+
635
+
636
+ /**
637
+ * DVARP
638
+ *
639
+ * Calculates the variance of a population based on the entire population by using the numbers
640
+ * in a column of a list or database that match conditions that you specify.
641
+ *
642
+ * Excel Function:
643
+ * DVARP(database,field,criteria)
644
+ *
645
+ * @access public
646
+ * @category Database Functions
647
+ * @param mixed[] $database The range of cells that makes up the list or database.
648
+ * A database is a list of related data in which rows of related
649
+ * information are records, and columns of data are fields. The
650
+ * first row of the list contains labels for each column.
651
+ * @param string|integer $field Indicates which column is used in the function. Enter the
652
+ * column label enclosed between double quotation marks, such as
653
+ * "Age" or "Yield," or a number (without quotation marks) that
654
+ * represents the position of the column within the list: 1 for
655
+ * the first column, 2 for the second column, and so on.
656
+ * @param mixed[] $criteria The range of cells that contains the conditions you specify.
657
+ * You can use any range for the criteria argument, as long as it
658
+ * includes at least one column label and at least one cell below
659
+ * the column label in which you specify a condition for the
660
+ * column.
661
+ * @return float
662
+ *
663
+ */
664
+ public static function DVARP($database, $field, $criteria)
665
+ {
666
+ $field = self::fieldExtract($database, $field);
667
+ if (is_null($field)) {
668
+ return null;
669
+ }
670
+
671
+ // Return
672
+ return PHPExcel_Calculation_Statistical::VARP(
673
+ self::getFilteredColumn($database, $field, $criteria)
674
+ );
675
+ }
676
+ }
classes/PHPExcel/Calculation/DateTime.php ADDED
@@ -0,0 +1,1553 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+ /**
13
+ * PHPExcel_Calculation_DateTime
14
+ *
15
+ * Copyright (c) 2006 - 2015 PHPExcel
16
+ *
17
+ * This library is free software; you can redistribute it and/or
18
+ * modify it under the terms of the GNU Lesser General Public
19
+ * License as published by the Free Software Foundation; either
20
+ * version 2.1 of the License, or (at your option) any later version.
21
+ *
22
+ * This library is distributed in the hope that it will be useful,
23
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25
+ * Lesser General Public License for more details.
26
+ *
27
+ * You should have received a copy of the GNU Lesser General Public
28
+ * License along with this library; if not, write to the Free Software
29
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30
+ *
31
+ * @category PHPExcel
32
+ * @package PHPExcel_Calculation
33
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
34
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
35
+ * @version ##VERSION##, ##DATE##
36
+ */
37
+ class PHPExcel_Calculation_DateTime
38
+ {
39
+ /**
40
+ * Identify if a year is a leap year or not
41
+ *
42
+ * @param integer $year The year to test
43
+ * @return boolean TRUE if the year is a leap year, otherwise FALSE
44
+ */
45
+ public static function isLeapYear($year)
46
+ {
47
+ return ((($year % 4) == 0) && (($year % 100) != 0) || (($year % 400) == 0));
48
+ }
49
+
50
+
51
+ /**
52
+ * Return the number of days between two dates based on a 360 day calendar
53
+ *
54
+ * @param integer $startDay Day of month of the start date
55
+ * @param integer $startMonth Month of the start date
56
+ * @param integer $startYear Year of the start date
57
+ * @param integer $endDay Day of month of the start date
58
+ * @param integer $endMonth Month of the start date
59
+ * @param integer $endYear Year of the start date
60
+ * @param boolean $methodUS Whether to use the US method or the European method of calculation
61
+ * @return integer Number of days between the start date and the end date
62
+ */
63
+ private static function dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, $methodUS)
64
+ {
65
+ if ($startDay == 31) {
66
+ --$startDay;
67
+ } elseif ($methodUS && ($startMonth == 2 && ($startDay == 29 || ($startDay == 28 && !self::isLeapYear($startYear))))) {
68
+ $startDay = 30;
69
+ }
70
+ if ($endDay == 31) {
71
+ if ($methodUS && $startDay != 30) {
72
+ $endDay = 1;
73
+ if ($endMonth == 12) {
74
+ ++$endYear;
75
+ $endMonth = 1;
76
+ } else {
77
+ ++$endMonth;
78
+ }
79
+ } else {
80
+ $endDay = 30;
81
+ }
82
+ }
83
+
84
+ return $endDay + $endMonth * 30 + $endYear * 360 - $startDay - $startMonth * 30 - $startYear * 360;
85
+ }
86
+
87
+
88
+ /**
89
+ * getDateValue
90
+ *
91
+ * @param string $dateValue
92
+ * @return mixed Excel date/time serial value, or string if error
93
+ */
94
+ public static function getDateValue($dateValue)
95
+ {
96
+ if (!is_numeric($dateValue)) {
97
+ if ((is_string($dateValue)) &&
98
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
99
+ return PHPExcel_Calculation_Functions::VALUE();
100
+ }
101
+ if ((is_object($dateValue)) && ($dateValue instanceof DateTime)) {
102
+ $dateValue = PHPExcel_Shared_Date::PHPToExcel($dateValue);
103
+ } else {
104
+ $saveReturnDateType = PHPExcel_Calculation_Functions::getReturnDateType();
105
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
106
+ $dateValue = self::DATEVALUE($dateValue);
107
+ PHPExcel_Calculation_Functions::setReturnDateType($saveReturnDateType);
108
+ }
109
+ }
110
+ return $dateValue;
111
+ }
112
+
113
+
114
+ /**
115
+ * getTimeValue
116
+ *
117
+ * @param string $timeValue
118
+ * @return mixed Excel date/time serial value, or string if error
119
+ */
120
+ private static function getTimeValue($timeValue)
121
+ {
122
+ $saveReturnDateType = PHPExcel_Calculation_Functions::getReturnDateType();
123
+ PHPExcel_Calculation_Functions::setReturnDateType(PHPExcel_Calculation_Functions::RETURNDATE_EXCEL);
124
+ $timeValue = self::TIMEVALUE($timeValue);
125
+ PHPExcel_Calculation_Functions::setReturnDateType($saveReturnDateType);
126
+ return $timeValue;
127
+ }
128
+
129
+
130
+ private static function adjustDateByMonths($dateValue = 0, $adjustmentMonths = 0)
131
+ {
132
+ // Execute function
133
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
134
+ $oMonth = (int) $PHPDateObject->format('m');
135
+ $oYear = (int) $PHPDateObject->format('Y');
136
+
137
+ $adjustmentMonthsString = (string) $adjustmentMonths;
138
+ if ($adjustmentMonths > 0) {
139
+ $adjustmentMonthsString = '+'.$adjustmentMonths;
140
+ }
141
+ if ($adjustmentMonths != 0) {
142
+ $PHPDateObject->modify($adjustmentMonthsString.' months');
143
+ }
144
+ $nMonth = (int) $PHPDateObject->format('m');
145
+ $nYear = (int) $PHPDateObject->format('Y');
146
+
147
+ $monthDiff = ($nMonth - $oMonth) + (($nYear - $oYear) * 12);
148
+ if ($monthDiff != $adjustmentMonths) {
149
+ $adjustDays = (int) $PHPDateObject->format('d');
150
+ $adjustDaysString = '-'.$adjustDays.' days';
151
+ $PHPDateObject->modify($adjustDaysString);
152
+ }
153
+ return $PHPDateObject;
154
+ }
155
+
156
+
157
+ /**
158
+ * DATETIMENOW
159
+ *
160
+ * Returns the current date and time.
161
+ * The NOW function is useful when you need to display the current date and time on a worksheet or
162
+ * calculate a value based on the current date and time, and have that value updated each time you
163
+ * open the worksheet.
164
+ *
165
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
166
+ * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
167
+ *
168
+ * Excel Function:
169
+ * NOW()
170
+ *
171
+ * @access public
172
+ * @category Date/Time Functions
173
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
174
+ * depending on the value of the ReturnDateType flag
175
+ */
176
+ public static function DATETIMENOW()
177
+ {
178
+ $saveTimeZone = date_default_timezone_get();
179
+ date_default_timezone_set('UTC');
180
+ $retValue = false;
181
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
182
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
183
+ $retValue = (float) PHPExcel_Shared_Date::PHPToExcel(time());
184
+ break;
185
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
186
+ $retValue = (integer) time();
187
+ break;
188
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
189
+ $retValue = new DateTime();
190
+ break;
191
+ }
192
+ date_default_timezone_set($saveTimeZone);
193
+
194
+ return $retValue;
195
+ }
196
+
197
+
198
+ /**
199
+ * DATENOW
200
+ *
201
+ * Returns the current date.
202
+ * The NOW function is useful when you need to display the current date and time on a worksheet or
203
+ * calculate a value based on the current date and time, and have that value updated each time you
204
+ * open the worksheet.
205
+ *
206
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
207
+ * and time format of your regional settings. PHPExcel does not change cell formatting in this way.
208
+ *
209
+ * Excel Function:
210
+ * TODAY()
211
+ *
212
+ * @access public
213
+ * @category Date/Time Functions
214
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
215
+ * depending on the value of the ReturnDateType flag
216
+ */
217
+ public static function DATENOW()
218
+ {
219
+ $saveTimeZone = date_default_timezone_get();
220
+ date_default_timezone_set('UTC');
221
+ $retValue = false;
222
+ $excelDateTime = floor(PHPExcel_Shared_Date::PHPToExcel(time()));
223
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
224
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
225
+ $retValue = (float) $excelDateTime;
226
+ break;
227
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
228
+ $retValue = (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateTime);
229
+ break;
230
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
231
+ $retValue = PHPExcel_Shared_Date::ExcelToPHPObject($excelDateTime);
232
+ break;
233
+ }
234
+ date_default_timezone_set($saveTimeZone);
235
+
236
+ return $retValue;
237
+ }
238
+
239
+
240
+ /**
241
+ * DATE
242
+ *
243
+ * The DATE function returns a value that represents a particular date.
244
+ *
245
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
246
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
247
+ *
248
+ * Excel Function:
249
+ * DATE(year,month,day)
250
+ *
251
+ * PHPExcel is a lot more forgiving than MS Excel when passing non numeric values to this function.
252
+ * A Month name or abbreviation (English only at this point) such as 'January' or 'Jan' will still be accepted,
253
+ * as will a day value with a suffix (e.g. '21st' rather than simply 21); again only English language.
254
+ *
255
+ * @access public
256
+ * @category Date/Time Functions
257
+ * @param integer $year The value of the year argument can include one to four digits.
258
+ * Excel interprets the year argument according to the configured
259
+ * date system: 1900 or 1904.
260
+ * If year is between 0 (zero) and 1899 (inclusive), Excel adds that
261
+ * value to 1900 to calculate the year. For example, DATE(108,1,2)
262
+ * returns January 2, 2008 (1900+108).
263
+ * If year is between 1900 and 9999 (inclusive), Excel uses that
264
+ * value as the year. For example, DATE(2008,1,2) returns January 2,
265
+ * 2008.
266
+ * If year is less than 0 or is 10000 or greater, Excel returns the
267
+ * #NUM! error value.
268
+ * @param integer $month A positive or negative integer representing the month of the year
269
+ * from 1 to 12 (January to December).
270
+ * If month is greater than 12, month adds that number of months to
271
+ * the first month in the year specified. For example, DATE(2008,14,2)
272
+ * returns the serial number representing February 2, 2009.
273
+ * If month is less than 1, month subtracts the magnitude of that
274
+ * number of months, plus 1, from the first month in the year
275
+ * specified. For example, DATE(2008,-3,2) returns the serial number
276
+ * representing September 2, 2007.
277
+ * @param integer $day A positive or negative integer representing the day of the month
278
+ * from 1 to 31.
279
+ * If day is greater than the number of days in the month specified,
280
+ * day adds that number of days to the first day in the month. For
281
+ * example, DATE(2008,1,35) returns the serial number representing
282
+ * February 4, 2008.
283
+ * If day is less than 1, day subtracts the magnitude that number of
284
+ * days, plus one, from the first day of the month specified. For
285
+ * example, DATE(2008,1,-15) returns the serial number representing
286
+ * December 16, 2007.
287
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
288
+ * depending on the value of the ReturnDateType flag
289
+ */
290
+ public static function DATE($year = 0, $month = 1, $day = 1)
291
+ {
292
+ $year = PHPExcel_Calculation_Functions::flattenSingleValue($year);
293
+ $month = PHPExcel_Calculation_Functions::flattenSingleValue($month);
294
+ $day = PHPExcel_Calculation_Functions::flattenSingleValue($day);
295
+
296
+ if (($month !== null) && (!is_numeric($month))) {
297
+ $month = PHPExcel_Shared_Date::monthStringToNumber($month);
298
+ }
299
+
300
+ if (($day !== null) && (!is_numeric($day))) {
301
+ $day = PHPExcel_Shared_Date::dayStringToNumber($day);
302
+ }
303
+
304
+ $year = ($year !== null) ? PHPExcel_Shared_String::testStringAsNumeric($year) : 0;
305
+ $month = ($month !== null) ? PHPExcel_Shared_String::testStringAsNumeric($month) : 0;
306
+ $day = ($day !== null) ? PHPExcel_Shared_String::testStringAsNumeric($day) : 0;
307
+ if ((!is_numeric($year)) ||
308
+ (!is_numeric($month)) ||
309
+ (!is_numeric($day))) {
310
+ return PHPExcel_Calculation_Functions::VALUE();
311
+ }
312
+ $year = (integer) $year;
313
+ $month = (integer) $month;
314
+ $day = (integer) $day;
315
+
316
+ $baseYear = PHPExcel_Shared_Date::getExcelCalendar();
317
+ // Validate parameters
318
+ if ($year < ($baseYear-1900)) {
319
+ return PHPExcel_Calculation_Functions::NaN();
320
+ }
321
+ if ((($baseYear-1900) != 0) && ($year < $baseYear) && ($year >= 1900)) {
322
+ return PHPExcel_Calculation_Functions::NaN();
323
+ }
324
+
325
+ if (($year < $baseYear) && ($year >= ($baseYear-1900))) {
326
+ $year += 1900;
327
+ }
328
+
329
+ if ($month < 1) {
330
+ // Handle year/month adjustment if month < 1
331
+ --$month;
332
+ $year += ceil($month / 12) - 1;
333
+ $month = 13 - abs($month % 12);
334
+ } elseif ($month > 12) {
335
+ // Handle year/month adjustment if month > 12
336
+ $year += floor($month / 12);
337
+ $month = ($month % 12);
338
+ }
339
+
340
+ // Re-validate the year parameter after adjustments
341
+ if (($year < $baseYear) || ($year >= 10000)) {
342
+ return PHPExcel_Calculation_Functions::NaN();
343
+ }
344
+
345
+ // Execute function
346
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year, $month, $day);
347
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
348
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
349
+ return (float) $excelDateValue;
350
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
351
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
352
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
353
+ return PHPExcel_Shared_Date::ExcelToPHPObject($excelDateValue);
354
+ }
355
+ }
356
+
357
+
358
+ /**
359
+ * TIME
360
+ *
361
+ * The TIME function returns a value that represents a particular time.
362
+ *
363
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
364
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
365
+ *
366
+ * Excel Function:
367
+ * TIME(hour,minute,second)
368
+ *
369
+ * @access public
370
+ * @category Date/Time Functions
371
+ * @param integer $hour A number from 0 (zero) to 32767 representing the hour.
372
+ * Any value greater than 23 will be divided by 24 and the remainder
373
+ * will be treated as the hour value. For example, TIME(27,0,0) =
374
+ * TIME(3,0,0) = .125 or 3:00 AM.
375
+ * @param integer $minute A number from 0 to 32767 representing the minute.
376
+ * Any value greater than 59 will be converted to hours and minutes.
377
+ * For example, TIME(0,750,0) = TIME(12,30,0) = .520833 or 12:30 PM.
378
+ * @param integer $second A number from 0 to 32767 representing the second.
379
+ * Any value greater than 59 will be converted to hours, minutes,
380
+ * and seconds. For example, TIME(0,0,2000) = TIME(0,33,22) = .023148
381
+ * or 12:33:20 AM
382
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
383
+ * depending on the value of the ReturnDateType flag
384
+ */
385
+ public static function TIME($hour = 0, $minute = 0, $second = 0)
386
+ {
387
+ $hour = PHPExcel_Calculation_Functions::flattenSingleValue($hour);
388
+ $minute = PHPExcel_Calculation_Functions::flattenSingleValue($minute);
389
+ $second = PHPExcel_Calculation_Functions::flattenSingleValue($second);
390
+
391
+ if ($hour == '') {
392
+ $hour = 0;
393
+ }
394
+ if ($minute == '') {
395
+ $minute = 0;
396
+ }
397
+ if ($second == '') {
398
+ $second = 0;
399
+ }
400
+
401
+ if ((!is_numeric($hour)) || (!is_numeric($minute)) || (!is_numeric($second))) {
402
+ return PHPExcel_Calculation_Functions::VALUE();
403
+ }
404
+ $hour = (integer) $hour;
405
+ $minute = (integer) $minute;
406
+ $second = (integer) $second;
407
+
408
+ if ($second < 0) {
409
+ $minute += floor($second / 60);
410
+ $second = 60 - abs($second % 60);
411
+ if ($second == 60) {
412
+ $second = 0;
413
+ }
414
+ } elseif ($second >= 60) {
415
+ $minute += floor($second / 60);
416
+ $second = $second % 60;
417
+ }
418
+ if ($minute < 0) {
419
+ $hour += floor($minute / 60);
420
+ $minute = 60 - abs($minute % 60);
421
+ if ($minute == 60) {
422
+ $minute = 0;
423
+ }
424
+ } elseif ($minute >= 60) {
425
+ $hour += floor($minute / 60);
426
+ $minute = $minute % 60;
427
+ }
428
+
429
+ if ($hour > 23) {
430
+ $hour = $hour % 24;
431
+ } elseif ($hour < 0) {
432
+ return PHPExcel_Calculation_Functions::NaN();
433
+ }
434
+
435
+ // Execute function
436
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
437
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
438
+ $date = 0;
439
+ $calendar = PHPExcel_Shared_Date::getExcelCalendar();
440
+ if ($calendar != PHPExcel_Shared_Date::CALENDAR_WINDOWS_1900) {
441
+ $date = 1;
442
+ }
443
+ return (float) PHPExcel_Shared_Date::FormattedPHPToExcel($calendar, 1, $date, $hour, $minute, $second);
444
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
445
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::FormattedPHPToExcel(1970, 1, 1, $hour, $minute, $second)); // -2147468400; // -2147472000 + 3600
446
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
447
+ $dayAdjust = 0;
448
+ if ($hour < 0) {
449
+ $dayAdjust = floor($hour / 24);
450
+ $hour = 24 - abs($hour % 24);
451
+ if ($hour == 24) {
452
+ $hour = 0;
453
+ }
454
+ } elseif ($hour >= 24) {
455
+ $dayAdjust = floor($hour / 24);
456
+ $hour = $hour % 24;
457
+ }
458
+ $phpDateObject = new DateTime('1900-01-01 '.$hour.':'.$minute.':'.$second);
459
+ if ($dayAdjust != 0) {
460
+ $phpDateObject->modify($dayAdjust.' days');
461
+ }
462
+ return $phpDateObject;
463
+ }
464
+ }
465
+
466
+
467
+ /**
468
+ * DATEVALUE
469
+ *
470
+ * Returns a value that represents a particular date.
471
+ * Use DATEVALUE to convert a date represented by a text string to an Excel or PHP date/time stamp
472
+ * value.
473
+ *
474
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the date
475
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
476
+ *
477
+ * Excel Function:
478
+ * DATEVALUE(dateValue)
479
+ *
480
+ * @access public
481
+ * @category Date/Time Functions
482
+ * @param string $dateValue Text that represents a date in a Microsoft Excel date format.
483
+ * For example, "1/30/2008" or "30-Jan-2008" are text strings within
484
+ * quotation marks that represent dates. Using the default date
485
+ * system in Excel for Windows, date_text must represent a date from
486
+ * January 1, 1900, to December 31, 9999. Using the default date
487
+ * system in Excel for the Macintosh, date_text must represent a date
488
+ * from January 1, 1904, to December 31, 9999. DATEVALUE returns the
489
+ * #VALUE! error value if date_text is out of this range.
490
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
491
+ * depending on the value of the ReturnDateType flag
492
+ */
493
+ public static function DATEVALUE($dateValue = 1)
494
+ {
495
+ $dateValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($dateValue), '"');
496
+ // Strip any ordinals because they're allowed in Excel (English only)
497
+ $dateValue = preg_replace('/(\d)(st|nd|rd|th)([ -\/])/Ui', '$1$3', $dateValue);
498
+ // Convert separators (/ . or space) to hyphens (should also handle dot used for ordinals in some countries, e.g. Denmark, Germany)
499
+ $dateValue = str_replace(array('/', '.', '-', ' '), array(' ', ' ', ' ', ' '), $dateValue);
500
+
501
+ $yearFound = false;
502
+ $t1 = explode(' ', $dateValue);
503
+ foreach ($t1 as &$t) {
504
+ if ((is_numeric($t)) && ($t > 31)) {
505
+ if ($yearFound) {
506
+ return PHPExcel_Calculation_Functions::VALUE();
507
+ } else {
508
+ if ($t < 100) {
509
+ $t += 1900;
510
+ }
511
+ $yearFound = true;
512
+ }
513
+ }
514
+ }
515
+ if ((count($t1) == 1) && (strpos($t, ':') != false)) {
516
+ // We've been fed a time value without any date
517
+ return 0.0;
518
+ } elseif (count($t1) == 2) {
519
+ // We only have two parts of the date: either day/month or month/year
520
+ if ($yearFound) {
521
+ array_unshift($t1, 1);
522
+ } else {
523
+ array_push($t1, date('Y'));
524
+ }
525
+ }
526
+ unset($t);
527
+ $dateValue = implode(' ', $t1);
528
+
529
+ $PHPDateArray = date_parse($dateValue);
530
+ if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
531
+ $testVal1 = strtok($dateValue, '- ');
532
+ if ($testVal1 !== false) {
533
+ $testVal2 = strtok('- ');
534
+ if ($testVal2 !== false) {
535
+ $testVal3 = strtok('- ');
536
+ if ($testVal3 === false) {
537
+ $testVal3 = strftime('%Y');
538
+ }
539
+ } else {
540
+ return PHPExcel_Calculation_Functions::VALUE();
541
+ }
542
+ } else {
543
+ return PHPExcel_Calculation_Functions::VALUE();
544
+ }
545
+ $PHPDateArray = date_parse($testVal1.'-'.$testVal2.'-'.$testVal3);
546
+ if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
547
+ $PHPDateArray = date_parse($testVal2.'-'.$testVal1.'-'.$testVal3);
548
+ if (($PHPDateArray === false) || ($PHPDateArray['error_count'] > 0)) {
549
+ return PHPExcel_Calculation_Functions::VALUE();
550
+ }
551
+ }
552
+ }
553
+
554
+ if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) {
555
+ // Execute function
556
+ if ($PHPDateArray['year'] == '') {
557
+ $PHPDateArray['year'] = strftime('%Y');
558
+ }
559
+ if ($PHPDateArray['year'] < 1900) {
560
+ return PHPExcel_Calculation_Functions::VALUE();
561
+ }
562
+ if ($PHPDateArray['month'] == '') {
563
+ $PHPDateArray['month'] = strftime('%m');
564
+ }
565
+ if ($PHPDateArray['day'] == '') {
566
+ $PHPDateArray['day'] = strftime('%d');
567
+ }
568
+ $excelDateValue = floor(
569
+ PHPExcel_Shared_Date::FormattedPHPToExcel(
570
+ $PHPDateArray['year'],
571
+ $PHPDateArray['month'],
572
+ $PHPDateArray['day'],
573
+ $PHPDateArray['hour'],
574
+ $PHPDateArray['minute'],
575
+ $PHPDateArray['second']
576
+ )
577
+ );
578
+
579
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
580
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
581
+ return (float) $excelDateValue;
582
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
583
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($excelDateValue);
584
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
585
+ return new DateTime($PHPDateArray['year'].'-'.$PHPDateArray['month'].'-'.$PHPDateArray['day'].' 00:00:00');
586
+ }
587
+ }
588
+ return PHPExcel_Calculation_Functions::VALUE();
589
+ }
590
+
591
+
592
+ /**
593
+ * TIMEVALUE
594
+ *
595
+ * Returns a value that represents a particular time.
596
+ * Use TIMEVALUE to convert a time represented by a text string to an Excel or PHP date/time stamp
597
+ * value.
598
+ *
599
+ * NOTE: When used in a Cell Formula, MS Excel changes the cell format so that it matches the time
600
+ * format of your regional settings. PHPExcel does not change cell formatting in this way.
601
+ *
602
+ * Excel Function:
603
+ * TIMEVALUE(timeValue)
604
+ *
605
+ * @access public
606
+ * @category Date/Time Functions
607
+ * @param string $timeValue A text string that represents a time in any one of the Microsoft
608
+ * Excel time formats; for example, "6:45 PM" and "18:45" text strings
609
+ * within quotation marks that represent time.
610
+ * Date information in time_text is ignored.
611
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
612
+ * depending on the value of the ReturnDateType flag
613
+ */
614
+ public static function TIMEVALUE($timeValue)
615
+ {
616
+ $timeValue = trim(PHPExcel_Calculation_Functions::flattenSingleValue($timeValue), '"');
617
+ $timeValue = str_replace(array('/', '.'), array('-', '-'), $timeValue);
618
+
619
+ $PHPDateArray = date_parse($timeValue);
620
+ if (($PHPDateArray !== false) && ($PHPDateArray['error_count'] == 0)) {
621
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
622
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(
623
+ $PHPDateArray['year'],
624
+ $PHPDateArray['month'],
625
+ $PHPDateArray['day'],
626
+ $PHPDateArray['hour'],
627
+ $PHPDateArray['minute'],
628
+ $PHPDateArray['second']
629
+ );
630
+ } else {
631
+ $excelDateValue = PHPExcel_Shared_Date::FormattedPHPToExcel(1900, 1, 1, $PHPDateArray['hour'], $PHPDateArray['minute'], $PHPDateArray['second']) - 1;
632
+ }
633
+
634
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
635
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
636
+ return (float) $excelDateValue;
637
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
638
+ return (integer) $phpDateValue = PHPExcel_Shared_Date::ExcelToPHP($excelDateValue+25569) - 3600;
639
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
640
+ return new DateTime('1900-01-01 '.$PHPDateArray['hour'].':'.$PHPDateArray['minute'].':'.$PHPDateArray['second']);
641
+ }
642
+ }
643
+ return PHPExcel_Calculation_Functions::VALUE();
644
+ }
645
+
646
+
647
+ /**
648
+ * DATEDIF
649
+ *
650
+ * @param mixed $startDate Excel date serial value, PHP date/time stamp, PHP DateTime object
651
+ * or a standard date string
652
+ * @param mixed $endDate Excel date serial value, PHP date/time stamp, PHP DateTime object
653
+ * or a standard date string
654
+ * @param string $unit
655
+ * @return integer Interval between the dates
656
+ */
657
+ public static function DATEDIF($startDate = 0, $endDate = 0, $unit = 'D')
658
+ {
659
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
660
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
661
+ $unit = strtoupper(PHPExcel_Calculation_Functions::flattenSingleValue($unit));
662
+
663
+ if (is_string($startDate = self::getDateValue($startDate))) {
664
+ return PHPExcel_Calculation_Functions::VALUE();
665
+ }
666
+ if (is_string($endDate = self::getDateValue($endDate))) {
667
+ return PHPExcel_Calculation_Functions::VALUE();
668
+ }
669
+
670
+ // Validate parameters
671
+ if ($startDate >= $endDate) {
672
+ return PHPExcel_Calculation_Functions::NaN();
673
+ }
674
+
675
+ // Execute function
676
+ $difference = $endDate - $startDate;
677
+
678
+ $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
679
+ $startDays = $PHPStartDateObject->format('j');
680
+ $startMonths = $PHPStartDateObject->format('n');
681
+ $startYears = $PHPStartDateObject->format('Y');
682
+
683
+ $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
684
+ $endDays = $PHPEndDateObject->format('j');
685
+ $endMonths = $PHPEndDateObject->format('n');
686
+ $endYears = $PHPEndDateObject->format('Y');
687
+
688
+ $retVal = PHPExcel_Calculation_Functions::NaN();
689
+ switch ($unit) {
690
+ case 'D':
691
+ $retVal = intval($difference);
692
+ break;
693
+ case 'M':
694
+ $retVal = intval($endMonths - $startMonths) + (intval($endYears - $startYears) * 12);
695
+ // We're only interested in full months
696
+ if ($endDays < $startDays) {
697
+ --$retVal;
698
+ }
699
+ break;
700
+ case 'Y':
701
+ $retVal = intval($endYears - $startYears);
702
+ // We're only interested in full months
703
+ if ($endMonths < $startMonths) {
704
+ --$retVal;
705
+ } elseif (($endMonths == $startMonths) && ($endDays < $startDays)) {
706
+ --$retVal;
707
+ }
708
+ break;
709
+ case 'MD':
710
+ if ($endDays < $startDays) {
711
+ $retVal = $endDays;
712
+ $PHPEndDateObject->modify('-'.$endDays.' days');
713
+ $adjustDays = $PHPEndDateObject->format('j');
714
+ if ($adjustDays > $startDays) {
715
+ $retVal += ($adjustDays - $startDays);
716
+ }
717
+ } else {
718
+ $retVal = $endDays - $startDays;
719
+ }
720
+ break;
721
+ case 'YM':
722
+ $retVal = intval($endMonths - $startMonths);
723
+ if ($retVal < 0) {
724
+ $retVal += 12;
725
+ }
726
+ // We're only interested in full months
727
+ if ($endDays < $startDays) {
728
+ --$retVal;
729
+ }
730
+ break;
731
+ case 'YD':
732
+ $retVal = intval($difference);
733
+ if ($endYears > $startYears) {
734
+ while ($endYears > $startYears) {
735
+ $PHPEndDateObject->modify('-1 year');
736
+ $endYears = $PHPEndDateObject->format('Y');
737
+ }
738
+ $retVal = $PHPEndDateObject->format('z') - $PHPStartDateObject->format('z');
739
+ if ($retVal < 0) {
740
+ $retVal += 365;
741
+ }
742
+ }
743
+ break;
744
+ default:
745
+ $retVal = PHPExcel_Calculation_Functions::NaN();
746
+ }
747
+ return $retVal;
748
+ }
749
+
750
+
751
+ /**
752
+ * DAYS360
753
+ *
754
+ * Returns the number of days between two dates based on a 360-day year (twelve 30-day months),
755
+ * which is used in some accounting calculations. Use this function to help compute payments if
756
+ * your accounting system is based on twelve 30-day months.
757
+ *
758
+ * Excel Function:
759
+ * DAYS360(startDate,endDate[,method])
760
+ *
761
+ * @access public
762
+ * @category Date/Time Functions
763
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
764
+ * PHP DateTime object, or a standard date string
765
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
766
+ * PHP DateTime object, or a standard date string
767
+ * @param boolean $method US or European Method
768
+ * FALSE or omitted: U.S. (NASD) method. If the starting date is
769
+ * the last day of a month, it becomes equal to the 30th of the
770
+ * same month. If the ending date is the last day of a month and
771
+ * the starting date is earlier than the 30th of a month, the
772
+ * ending date becomes equal to the 1st of the next month;
773
+ * otherwise the ending date becomes equal to the 30th of the
774
+ * same month.
775
+ * TRUE: European method. Starting dates and ending dates that
776
+ * occur on the 31st of a month become equal to the 30th of the
777
+ * same month.
778
+ * @return integer Number of days between start date and end date
779
+ */
780
+ public static function DAYS360($startDate = 0, $endDate = 0, $method = false)
781
+ {
782
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
783
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
784
+
785
+ if (is_string($startDate = self::getDateValue($startDate))) {
786
+ return PHPExcel_Calculation_Functions::VALUE();
787
+ }
788
+ if (is_string($endDate = self::getDateValue($endDate))) {
789
+ return PHPExcel_Calculation_Functions::VALUE();
790
+ }
791
+
792
+ if (!is_bool($method)) {
793
+ return PHPExcel_Calculation_Functions::VALUE();
794
+ }
795
+
796
+ // Execute function
797
+ $PHPStartDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($startDate);
798
+ $startDay = $PHPStartDateObject->format('j');
799
+ $startMonth = $PHPStartDateObject->format('n');
800
+ $startYear = $PHPStartDateObject->format('Y');
801
+
802
+ $PHPEndDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
803
+ $endDay = $PHPEndDateObject->format('j');
804
+ $endMonth = $PHPEndDateObject->format('n');
805
+ $endYear = $PHPEndDateObject->format('Y');
806
+
807
+ return self::dateDiff360($startDay, $startMonth, $startYear, $endDay, $endMonth, $endYear, !$method);
808
+ }
809
+
810
+
811
+ /**
812
+ * YEARFRAC
813
+ *
814
+ * Calculates the fraction of the year represented by the number of whole days between two dates
815
+ * (the start_date and the end_date).
816
+ * Use the YEARFRAC worksheet function to identify the proportion of a whole year's benefits or
817
+ * obligations to assign to a specific term.
818
+ *
819
+ * Excel Function:
820
+ * YEARFRAC(startDate,endDate[,method])
821
+ *
822
+ * @access public
823
+ * @category Date/Time Functions
824
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
825
+ * PHP DateTime object, or a standard date string
826
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
827
+ * PHP DateTime object, or a standard date string
828
+ * @param integer $method Method used for the calculation
829
+ * 0 or omitted US (NASD) 30/360
830
+ * 1 Actual/actual
831
+ * 2 Actual/360
832
+ * 3 Actual/365
833
+ * 4 European 30/360
834
+ * @return float fraction of the year
835
+ */
836
+ public static function YEARFRAC($startDate = 0, $endDate = 0, $method = 0)
837
+ {
838
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
839
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
840
+ $method = PHPExcel_Calculation_Functions::flattenSingleValue($method);
841
+
842
+ if (is_string($startDate = self::getDateValue($startDate))) {
843
+ return PHPExcel_Calculation_Functions::VALUE();
844
+ }
845
+ if (is_string($endDate = self::getDateValue($endDate))) {
846
+ return PHPExcel_Calculation_Functions::VALUE();
847
+ }
848
+
849
+ if (((is_numeric($method)) && (!is_string($method))) || ($method == '')) {
850
+ switch ($method) {
851
+ case 0:
852
+ return self::DAYS360($startDate, $endDate) / 360;
853
+ case 1:
854
+ $days = self::DATEDIF($startDate, $endDate);
855
+ $startYear = self::YEAR($startDate);
856
+ $endYear = self::YEAR($endDate);
857
+ $years = $endYear - $startYear + 1;
858
+ $leapDays = 0;
859
+ if ($years == 1) {
860
+ if (self::isLeapYear($endYear)) {
861
+ $startMonth = self::MONTHOFYEAR($startDate);
862
+ $endMonth = self::MONTHOFYEAR($endDate);
863
+ $endDay = self::DAYOFMONTH($endDate);
864
+ if (($startMonth < 3) ||
865
+ (($endMonth * 100 + $endDay) >= (2 * 100 + 29))) {
866
+ $leapDays += 1;
867
+ }
868
+ }
869
+ } else {
870
+ for ($year = $startYear; $year <= $endYear; ++$year) {
871
+ if ($year == $startYear) {
872
+ $startMonth = self::MONTHOFYEAR($startDate);
873
+ $startDay = self::DAYOFMONTH($startDate);
874
+ if ($startMonth < 3) {
875
+ $leapDays += (self::isLeapYear($year)) ? 1 : 0;
876
+ }
877
+ } elseif ($year == $endYear) {
878
+ $endMonth = self::MONTHOFYEAR($endDate);
879
+ $endDay = self::DAYOFMONTH($endDate);
880
+ if (($endMonth * 100 + $endDay) >= (2 * 100 + 29)) {
881
+ $leapDays += (self::isLeapYear($year)) ? 1 : 0;
882
+ }
883
+ } else {
884
+ $leapDays += (self::isLeapYear($year)) ? 1 : 0;
885
+ }
886
+ }
887
+ if ($years == 2) {
888
+ if (($leapDays == 0) && (self::isLeapYear($startYear)) && ($days > 365)) {
889
+ $leapDays = 1;
890
+ } elseif ($days < 366) {
891
+ $years = 1;
892
+ }
893
+ }
894
+ $leapDays /= $years;
895
+ }
896
+ return $days / (365 + $leapDays);
897
+ case 2:
898
+ return self::DATEDIF($startDate, $endDate) / 360;
899
+ case 3:
900
+ return self::DATEDIF($startDate, $endDate) / 365;
901
+ case 4:
902
+ return self::DAYS360($startDate, $endDate, true) / 360;
903
+ }
904
+ }
905
+ return PHPExcel_Calculation_Functions::VALUE();
906
+ }
907
+
908
+
909
+ /**
910
+ * NETWORKDAYS
911
+ *
912
+ * Returns the number of whole working days between start_date and end_date. Working days
913
+ * exclude weekends and any dates identified in holidays.
914
+ * Use NETWORKDAYS to calculate employee benefits that accrue based on the number of days
915
+ * worked during a specific term.
916
+ *
917
+ * Excel Function:
918
+ * NETWORKDAYS(startDate,endDate[,holidays[,holiday[,...]]])
919
+ *
920
+ * @access public
921
+ * @category Date/Time Functions
922
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
923
+ * PHP DateTime object, or a standard date string
924
+ * @param mixed $endDate Excel date serial value (float), PHP date timestamp (integer),
925
+ * PHP DateTime object, or a standard date string
926
+ * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
927
+ * timestamp (integer), PHP DateTime object, or a standard date
928
+ * strings that will be excluded from the working calendar, such
929
+ * as state and federal holidays and floating holidays.
930
+ * @return integer Interval between the dates
931
+ */
932
+ public static function NETWORKDAYS($startDate, $endDate)
933
+ {
934
+ // Retrieve the mandatory start and end date that are referenced in the function definition
935
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
936
+ $endDate = PHPExcel_Calculation_Functions::flattenSingleValue($endDate);
937
+ // Flush the mandatory start and end date that are referenced in the function definition, and get the optional days
938
+ $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
939
+ array_shift($dateArgs);
940
+ array_shift($dateArgs);
941
+
942
+ // Validate the start and end dates
943
+ if (is_string($startDate = $sDate = self::getDateValue($startDate))) {
944
+ return PHPExcel_Calculation_Functions::VALUE();
945
+ }
946
+ $startDate = (float) floor($startDate);
947
+ if (is_string($endDate = $eDate = self::getDateValue($endDate))) {
948
+ return PHPExcel_Calculation_Functions::VALUE();
949
+ }
950
+ $endDate = (float) floor($endDate);
951
+
952
+ if ($sDate > $eDate) {
953
+ $startDate = $eDate;
954
+ $endDate = $sDate;
955
+ }
956
+
957
+ // Execute function
958
+ $startDoW = 6 - self::DAYOFWEEK($startDate, 2);
959
+ if ($startDoW < 0) {
960
+ $startDoW = 0;
961
+ }
962
+ $endDoW = self::DAYOFWEEK($endDate, 2);
963
+ if ($endDoW >= 6) {
964
+ $endDoW = 0;
965
+ }
966
+
967
+ $wholeWeekDays = floor(($endDate - $startDate) / 7) * 5;
968
+ $partWeekDays = $endDoW + $startDoW;
969
+ if ($partWeekDays > 5) {
970
+ $partWeekDays -= 5;
971
+ }
972
+
973
+ // Test any extra holiday parameters
974
+ $holidayCountedArray = array();
975
+ foreach ($dateArgs as $holidayDate) {
976
+ if (is_string($holidayDate = self::getDateValue($holidayDate))) {
977
+ return PHPExcel_Calculation_Functions::VALUE();
978
+ }
979
+ if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
980
+ if ((self::DAYOFWEEK($holidayDate, 2) < 6) && (!in_array($holidayDate, $holidayCountedArray))) {
981
+ --$partWeekDays;
982
+ $holidayCountedArray[] = $holidayDate;
983
+ }
984
+ }
985
+ }
986
+
987
+ if ($sDate > $eDate) {
988
+ return 0 - ($wholeWeekDays + $partWeekDays);
989
+ }
990
+ return $wholeWeekDays + $partWeekDays;
991
+ }
992
+
993
+
994
+ /**
995
+ * WORKDAY
996
+ *
997
+ * Returns the date that is the indicated number of working days before or after a date (the
998
+ * starting date). Working days exclude weekends and any dates identified as holidays.
999
+ * Use WORKDAY to exclude weekends or holidays when you calculate invoice due dates, expected
1000
+ * delivery times, or the number of days of work performed.
1001
+ *
1002
+ * Excel Function:
1003
+ * WORKDAY(startDate,endDays[,holidays[,holiday[,...]]])
1004
+ *
1005
+ * @access public
1006
+ * @category Date/Time Functions
1007
+ * @param mixed $startDate Excel date serial value (float), PHP date timestamp (integer),
1008
+ * PHP DateTime object, or a standard date string
1009
+ * @param integer $endDays The number of nonweekend and nonholiday days before or after
1010
+ * startDate. A positive value for days yields a future date; a
1011
+ * negative value yields a past date.
1012
+ * @param mixed $holidays,... Optional series of Excel date serial value (float), PHP date
1013
+ * timestamp (integer), PHP DateTime object, or a standard date
1014
+ * strings that will be excluded from the working calendar, such
1015
+ * as state and federal holidays and floating holidays.
1016
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
1017
+ * depending on the value of the ReturnDateType flag
1018
+ */
1019
+ public static function WORKDAY($startDate, $endDays)
1020
+ {
1021
+ // Retrieve the mandatory start date and days that are referenced in the function definition
1022
+ $startDate = PHPExcel_Calculation_Functions::flattenSingleValue($startDate);
1023
+ $endDays = PHPExcel_Calculation_Functions::flattenSingleValue($endDays);
1024
+ // Flush the mandatory start date and days that are referenced in the function definition, and get the optional days
1025
+ $dateArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1026
+ array_shift($dateArgs);
1027
+ array_shift($dateArgs);
1028
+
1029
+ if ((is_string($startDate = self::getDateValue($startDate))) || (!is_numeric($endDays))) {
1030
+ return PHPExcel_Calculation_Functions::VALUE();
1031
+ }
1032
+ $startDate = (float) floor($startDate);
1033
+ $endDays = (int) floor($endDays);
1034
+ // If endDays is 0, we always return startDate
1035
+ if ($endDays == 0) {
1036
+ return $startDate;
1037
+ }
1038
+
1039
+ $decrementing = ($endDays < 0) ? true : false;
1040
+
1041
+ // Adjust the start date if it falls over a weekend
1042
+
1043
+ $startDoW = self::DAYOFWEEK($startDate, 3);
1044
+ if (self::DAYOFWEEK($startDate, 3) >= 5) {
1045
+ $startDate += ($decrementing) ? -$startDoW + 4: 7 - $startDoW;
1046
+ ($decrementing) ? $endDays++ : $endDays--;
1047
+ }
1048
+
1049
+ // Add endDays
1050
+ $endDate = (float) $startDate + (intval($endDays / 5) * 7) + ($endDays % 5);
1051
+
1052
+ // Adjust the calculated end date if it falls over a weekend
1053
+ $endDoW = self::DAYOFWEEK($endDate, 3);
1054
+ if ($endDoW >= 5) {
1055
+ $endDate += ($decrementing) ? -$endDoW + 4: 7 - $endDoW;
1056
+ }
1057
+
1058
+ // Test any extra holiday parameters
1059
+ if (!empty($dateArgs)) {
1060
+ $holidayCountedArray = $holidayDates = array();
1061
+ foreach ($dateArgs as $holidayDate) {
1062
+ if (($holidayDate !== null) && (trim($holidayDate) > '')) {
1063
+ if (is_string($holidayDate = self::getDateValue($holidayDate))) {
1064
+ return PHPExcel_Calculation_Functions::VALUE();
1065
+ }
1066
+ if (self::DAYOFWEEK($holidayDate, 3) < 5) {
1067
+ $holidayDates[] = $holidayDate;
1068
+ }
1069
+ }
1070
+ }
1071
+ if ($decrementing) {
1072
+ rsort($holidayDates, SORT_NUMERIC);
1073
+ } else {
1074
+ sort($holidayDates, SORT_NUMERIC);
1075
+ }
1076
+ foreach ($holidayDates as $holidayDate) {
1077
+ if ($decrementing) {
1078
+ if (($holidayDate <= $startDate) && ($holidayDate >= $endDate)) {
1079
+ if (!in_array($holidayDate, $holidayCountedArray)) {
1080
+ --$endDate;
1081
+ $holidayCountedArray[] = $holidayDate;
1082
+ }
1083
+ }
1084
+ } else {
1085
+ if (($holidayDate >= $startDate) && ($holidayDate <= $endDate)) {
1086
+ if (!in_array($holidayDate, $holidayCountedArray)) {
1087
+ ++$endDate;
1088
+ $holidayCountedArray[] = $holidayDate;
1089
+ }
1090
+ }
1091
+ }
1092
+ // Adjust the calculated end date if it falls over a weekend
1093
+ $endDoW = self::DAYOFWEEK($endDate, 3);
1094
+ if ($endDoW >= 5) {
1095
+ $endDate += ($decrementing) ? -$endDoW + 4 : 7 - $endDoW;
1096
+ }
1097
+ }
1098
+ }
1099
+
1100
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
1101
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
1102
+ return (float) $endDate;
1103
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
1104
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP($endDate);
1105
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
1106
+ return PHPExcel_Shared_Date::ExcelToPHPObject($endDate);
1107
+ }
1108
+ }
1109
+
1110
+
1111
+ /**
1112
+ * DAYOFMONTH
1113
+ *
1114
+ * Returns the day of the month, for a specified date. The day is given as an integer
1115
+ * ranging from 1 to 31.
1116
+ *
1117
+ * Excel Function:
1118
+ * DAY(dateValue)
1119
+ *
1120
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1121
+ * PHP DateTime object, or a standard date string
1122
+ * @return int Day of the month
1123
+ */
1124
+ public static function DAYOFMONTH($dateValue = 1)
1125
+ {
1126
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1127
+
1128
+ if ($dateValue === null) {
1129
+ $dateValue = 1;
1130
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
1131
+ return PHPExcel_Calculation_Functions::VALUE();
1132
+ } elseif ($dateValue == 0.0) {
1133
+ return 0;
1134
+ } elseif ($dateValue < 0.0) {
1135
+ return PHPExcel_Calculation_Functions::NaN();
1136
+ }
1137
+
1138
+ // Execute function
1139
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1140
+
1141
+ return (int) $PHPDateObject->format('j');
1142
+ }
1143
+
1144
+
1145
+ /**
1146
+ * DAYOFWEEK
1147
+ *
1148
+ * Returns the day of the week for a specified date. The day is given as an integer
1149
+ * ranging from 0 to 7 (dependent on the requested style).
1150
+ *
1151
+ * Excel Function:
1152
+ * WEEKDAY(dateValue[,style])
1153
+ *
1154
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1155
+ * PHP DateTime object, or a standard date string
1156
+ * @param int $style A number that determines the type of return value
1157
+ * 1 or omitted Numbers 1 (Sunday) through 7 (Saturday).
1158
+ * 2 Numbers 1 (Monday) through 7 (Sunday).
1159
+ * 3 Numbers 0 (Monday) through 6 (Sunday).
1160
+ * @return int Day of the week value
1161
+ */
1162
+ public static function DAYOFWEEK($dateValue = 1, $style = 1)
1163
+ {
1164
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1165
+ $style = PHPExcel_Calculation_Functions::flattenSingleValue($style);
1166
+
1167
+ if (!is_numeric($style)) {
1168
+ return PHPExcel_Calculation_Functions::VALUE();
1169
+ } elseif (($style < 1) || ($style > 3)) {
1170
+ return PHPExcel_Calculation_Functions::NaN();
1171
+ }
1172
+ $style = floor($style);
1173
+
1174
+ if ($dateValue === null) {
1175
+ $dateValue = 1;
1176
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
1177
+ return PHPExcel_Calculation_Functions::VALUE();
1178
+ } elseif ($dateValue < 0.0) {
1179
+ return PHPExcel_Calculation_Functions::NaN();
1180
+ }
1181
+
1182
+ // Execute function
1183
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1184
+ $DoW = $PHPDateObject->format('w');
1185
+
1186
+ $firstDay = 1;
1187
+ switch ($style) {
1188
+ case 1:
1189
+ ++$DoW;
1190
+ break;
1191
+ case 2:
1192
+ if ($DoW == 0) {
1193
+ $DoW = 7;
1194
+ }
1195
+ break;
1196
+ case 3:
1197
+ if ($DoW == 0) {
1198
+ $DoW = 7;
1199
+ }
1200
+ $firstDay = 0;
1201
+ --$DoW;
1202
+ break;
1203
+ }
1204
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL) {
1205
+ // Test for Excel's 1900 leap year, and introduce the error as required
1206
+ if (($PHPDateObject->format('Y') == 1900) && ($PHPDateObject->format('n') <= 2)) {
1207
+ --$DoW;
1208
+ if ($DoW < $firstDay) {
1209
+ $DoW += 7;
1210
+ }
1211
+ }
1212
+ }
1213
+
1214
+ return (int) $DoW;
1215
+ }
1216
+
1217
+
1218
+ /**
1219
+ * WEEKOFYEAR
1220
+ *
1221
+ * Returns the week of the year for a specified date.
1222
+ * The WEEKNUM function considers the week containing January 1 to be the first week of the year.
1223
+ * However, there is a European standard that defines the first week as the one with the majority
1224
+ * of days (four or more) falling in the new year. This means that for years in which there are
1225
+ * three days or less in the first week of January, the WEEKNUM function returns week numbers
1226
+ * that are incorrect according to the European standard.
1227
+ *
1228
+ * Excel Function:
1229
+ * WEEKNUM(dateValue[,style])
1230
+ *
1231
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1232
+ * PHP DateTime object, or a standard date string
1233
+ * @param boolean $method Week begins on Sunday or Monday
1234
+ * 1 or omitted Week begins on Sunday.
1235
+ * 2 Week begins on Monday.
1236
+ * @return int Week Number
1237
+ */
1238
+ public static function WEEKOFYEAR($dateValue = 1, $method = 1)
1239
+ {
1240
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1241
+ $method = PHPExcel_Calculation_Functions::flattenSingleValue($method);
1242
+
1243
+ if (!is_numeric($method)) {
1244
+ return PHPExcel_Calculation_Functions::VALUE();
1245
+ } elseif (($method < 1) || ($method > 2)) {
1246
+ return PHPExcel_Calculation_Functions::NaN();
1247
+ }
1248
+ $method = floor($method);
1249
+
1250
+ if ($dateValue === null) {
1251
+ $dateValue = 1;
1252
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
1253
+ return PHPExcel_Calculation_Functions::VALUE();
1254
+ } elseif ($dateValue < 0.0) {
1255
+ return PHPExcel_Calculation_Functions::NaN();
1256
+ }
1257
+
1258
+ // Execute function
1259
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1260
+ $dayOfYear = $PHPDateObject->format('z');
1261
+ $dow = $PHPDateObject->format('w');
1262
+ $PHPDateObject->modify('-' . $dayOfYear . ' days');
1263
+ $dow = $PHPDateObject->format('w');
1264
+ $daysInFirstWeek = 7 - (($dow + (2 - $method)) % 7);
1265
+ $dayOfYear -= $daysInFirstWeek;
1266
+ $weekOfYear = ceil($dayOfYear / 7) + 1;
1267
+
1268
+ return (int) $weekOfYear;
1269
+ }
1270
+
1271
+
1272
+ /**
1273
+ * MONTHOFYEAR
1274
+ *
1275
+ * Returns the month of a date represented by a serial number.
1276
+ * The month is given as an integer, ranging from 1 (January) to 12 (December).
1277
+ *
1278
+ * Excel Function:
1279
+ * MONTH(dateValue)
1280
+ *
1281
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1282
+ * PHP DateTime object, or a standard date string
1283
+ * @return int Month of the year
1284
+ */
1285
+ public static function MONTHOFYEAR($dateValue = 1)
1286
+ {
1287
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1288
+
1289
+ if ($dateValue === null) {
1290
+ $dateValue = 1;
1291
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
1292
+ return PHPExcel_Calculation_Functions::VALUE();
1293
+ } elseif ($dateValue < 0.0) {
1294
+ return PHPExcel_Calculation_Functions::NaN();
1295
+ }
1296
+
1297
+ // Execute function
1298
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1299
+
1300
+ return (int) $PHPDateObject->format('n');
1301
+ }
1302
+
1303
+
1304
+ /**
1305
+ * YEAR
1306
+ *
1307
+ * Returns the year corresponding to a date.
1308
+ * The year is returned as an integer in the range 1900-9999.
1309
+ *
1310
+ * Excel Function:
1311
+ * YEAR(dateValue)
1312
+ *
1313
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1314
+ * PHP DateTime object, or a standard date string
1315
+ * @return int Year
1316
+ */
1317
+ public static function YEAR($dateValue = 1)
1318
+ {
1319
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1320
+
1321
+ if ($dateValue === null) {
1322
+ $dateValue = 1;
1323
+ } elseif (is_string($dateValue = self::getDateValue($dateValue))) {
1324
+ return PHPExcel_Calculation_Functions::VALUE();
1325
+ } elseif ($dateValue < 0.0) {
1326
+ return PHPExcel_Calculation_Functions::NaN();
1327
+ }
1328
+
1329
+ // Execute function
1330
+ $PHPDateObject = PHPExcel_Shared_Date::ExcelToPHPObject($dateValue);
1331
+
1332
+ return (int) $PHPDateObject->format('Y');
1333
+ }
1334
+
1335
+
1336
+ /**
1337
+ * HOUROFDAY
1338
+ *
1339
+ * Returns the hour of a time value.
1340
+ * The hour is given as an integer, ranging from 0 (12:00 A.M.) to 23 (11:00 P.M.).
1341
+ *
1342
+ * Excel Function:
1343
+ * HOUR(timeValue)
1344
+ *
1345
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
1346
+ * PHP DateTime object, or a standard time string
1347
+ * @return int Hour
1348
+ */
1349
+ public static function HOUROFDAY($timeValue = 0)
1350
+ {
1351
+ $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
1352
+
1353
+ if (!is_numeric($timeValue)) {
1354
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1355
+ $testVal = strtok($timeValue, '/-: ');
1356
+ if (strlen($testVal) < strlen($timeValue)) {
1357
+ return PHPExcel_Calculation_Functions::VALUE();
1358
+ }
1359
+ }
1360
+ $timeValue = self::getTimeValue($timeValue);
1361
+ if (is_string($timeValue)) {
1362
+ return PHPExcel_Calculation_Functions::VALUE();
1363
+ }
1364
+ }
1365
+ // Execute function
1366
+ if ($timeValue >= 1) {
1367
+ $timeValue = fmod($timeValue, 1);
1368
+ } elseif ($timeValue < 0.0) {
1369
+ return PHPExcel_Calculation_Functions::NaN();
1370
+ }
1371
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
1372
+
1373
+ return (int) gmdate('G', $timeValue);
1374
+ }
1375
+
1376
+
1377
+ /**
1378
+ * MINUTEOFHOUR
1379
+ *
1380
+ * Returns the minutes of a time value.
1381
+ * The minute is given as an integer, ranging from 0 to 59.
1382
+ *
1383
+ * Excel Function:
1384
+ * MINUTE(timeValue)
1385
+ *
1386
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
1387
+ * PHP DateTime object, or a standard time string
1388
+ * @return int Minute
1389
+ */
1390
+ public static function MINUTEOFHOUR($timeValue = 0)
1391
+ {
1392
+ $timeValue = $timeTester = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
1393
+
1394
+ if (!is_numeric($timeValue)) {
1395
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1396
+ $testVal = strtok($timeValue, '/-: ');
1397
+ if (strlen($testVal) < strlen($timeValue)) {
1398
+ return PHPExcel_Calculation_Functions::VALUE();
1399
+ }
1400
+ }
1401
+ $timeValue = self::getTimeValue($timeValue);
1402
+ if (is_string($timeValue)) {
1403
+ return PHPExcel_Calculation_Functions::VALUE();
1404
+ }
1405
+ }
1406
+ // Execute function
1407
+ if ($timeValue >= 1) {
1408
+ $timeValue = fmod($timeValue, 1);
1409
+ } elseif ($timeValue < 0.0) {
1410
+ return PHPExcel_Calculation_Functions::NaN();
1411
+ }
1412
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
1413
+
1414
+ return (int) gmdate('i', $timeValue);
1415
+ }
1416
+
1417
+
1418
+ /**
1419
+ * SECONDOFMINUTE
1420
+ *
1421
+ * Returns the seconds of a time value.
1422
+ * The second is given as an integer in the range 0 (zero) to 59.
1423
+ *
1424
+ * Excel Function:
1425
+ * SECOND(timeValue)
1426
+ *
1427
+ * @param mixed $timeValue Excel date serial value (float), PHP date timestamp (integer),
1428
+ * PHP DateTime object, or a standard time string
1429
+ * @return int Second
1430
+ */
1431
+ public static function SECONDOFMINUTE($timeValue = 0)
1432
+ {
1433
+ $timeValue = PHPExcel_Calculation_Functions::flattenSingleValue($timeValue);
1434
+
1435
+ if (!is_numeric($timeValue)) {
1436
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1437
+ $testVal = strtok($timeValue, '/-: ');
1438
+ if (strlen($testVal) < strlen($timeValue)) {
1439
+ return PHPExcel_Calculation_Functions::VALUE();
1440
+ }
1441
+ }
1442
+ $timeValue = self::getTimeValue($timeValue);
1443
+ if (is_string($timeValue)) {
1444
+ return PHPExcel_Calculation_Functions::VALUE();
1445
+ }
1446
+ }
1447
+ // Execute function
1448
+ if ($timeValue >= 1) {
1449
+ $timeValue = fmod($timeValue, 1);
1450
+ } elseif ($timeValue < 0.0) {
1451
+ return PHPExcel_Calculation_Functions::NaN();
1452
+ }
1453
+ $timeValue = PHPExcel_Shared_Date::ExcelToPHP($timeValue);
1454
+
1455
+ return (int) gmdate('s', $timeValue);
1456
+ }
1457
+
1458
+
1459
+ /**
1460
+ * EDATE
1461
+ *
1462
+ * Returns the serial number that represents the date that is the indicated number of months
1463
+ * before or after a specified date (the start_date).
1464
+ * Use EDATE to calculate maturity dates or due dates that fall on the same day of the month
1465
+ * as the date of issue.
1466
+ *
1467
+ * Excel Function:
1468
+ * EDATE(dateValue,adjustmentMonths)
1469
+ *
1470
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1471
+ * PHP DateTime object, or a standard date string
1472
+ * @param int $adjustmentMonths The number of months before or after start_date.
1473
+ * A positive value for months yields a future date;
1474
+ * a negative value yields a past date.
1475
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
1476
+ * depending on the value of the ReturnDateType flag
1477
+ */
1478
+ public static function EDATE($dateValue = 1, $adjustmentMonths = 0)
1479
+ {
1480
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1481
+ $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths);
1482
+
1483
+ if (!is_numeric($adjustmentMonths)) {
1484
+ return PHPExcel_Calculation_Functions::VALUE();
1485
+ }
1486
+ $adjustmentMonths = floor($adjustmentMonths);
1487
+
1488
+ if (is_string($dateValue = self::getDateValue($dateValue))) {
1489
+ return PHPExcel_Calculation_Functions::VALUE();
1490
+ }
1491
+
1492
+ // Execute function
1493
+ $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths);
1494
+
1495
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
1496
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
1497
+ return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
1498
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
1499
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
1500
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
1501
+ return $PHPDateObject;
1502
+ }
1503
+ }
1504
+
1505
+
1506
+ /**
1507
+ * EOMONTH
1508
+ *
1509
+ * Returns the date value for the last day of the month that is the indicated number of months
1510
+ * before or after start_date.
1511
+ * Use EOMONTH to calculate maturity dates or due dates that fall on the last day of the month.
1512
+ *
1513
+ * Excel Function:
1514
+ * EOMONTH(dateValue,adjustmentMonths)
1515
+ *
1516
+ * @param mixed $dateValue Excel date serial value (float), PHP date timestamp (integer),
1517
+ * PHP DateTime object, or a standard date string
1518
+ * @param int $adjustmentMonths The number of months before or after start_date.
1519
+ * A positive value for months yields a future date;
1520
+ * a negative value yields a past date.
1521
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
1522
+ * depending on the value of the ReturnDateType flag
1523
+ */
1524
+ public static function EOMONTH($dateValue = 1, $adjustmentMonths = 0)
1525
+ {
1526
+ $dateValue = PHPExcel_Calculation_Functions::flattenSingleValue($dateValue);
1527
+ $adjustmentMonths = PHPExcel_Calculation_Functions::flattenSingleValue($adjustmentMonths);
1528
+
1529
+ if (!is_numeric($adjustmentMonths)) {
1530
+ return PHPExcel_Calculation_Functions::VALUE();
1531
+ }
1532
+ $adjustmentMonths = floor($adjustmentMonths);
1533
+
1534
+ if (is_string($dateValue = self::getDateValue($dateValue))) {
1535
+ return PHPExcel_Calculation_Functions::VALUE();
1536
+ }
1537
+
1538
+ // Execute function
1539
+ $PHPDateObject = self::adjustDateByMonths($dateValue, $adjustmentMonths+1);
1540
+ $adjustDays = (int) $PHPDateObject->format('d');
1541
+ $adjustDaysString = '-' . $adjustDays . ' days';
1542
+ $PHPDateObject->modify($adjustDaysString);
1543
+
1544
+ switch (PHPExcel_Calculation_Functions::getReturnDateType()) {
1545
+ case PHPExcel_Calculation_Functions::RETURNDATE_EXCEL:
1546
+ return (float) PHPExcel_Shared_Date::PHPToExcel($PHPDateObject);
1547
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC:
1548
+ return (integer) PHPExcel_Shared_Date::ExcelToPHP(PHPExcel_Shared_Date::PHPToExcel($PHPDateObject));
1549
+ case PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT:
1550
+ return $PHPDateObject;
1551
+ }
1552
+ }
1553
+ }
classes/PHPExcel/Calculation/Engineering.php ADDED
@@ -0,0 +1,2650 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+ /** EULER */
13
+ define('EULER', 2.71828182845904523536);
14
+
15
+ /**
16
+ * PHPExcel_Calculation_Engineering
17
+ *
18
+ * Copyright (c) 2006 - 2015 PHPExcel
19
+ *
20
+ * This library is free software; you can redistribute it and/or
21
+ * modify it under the terms of the GNU Lesser General Public
22
+ * License as published by the Free Software Foundation; either
23
+ * version 2.1 of the License, or (at your option) any later version.
24
+ *
25
+ * This library is distributed in the hope that it will be useful,
26
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
27
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
28
+ * Lesser General Public License for more details.
29
+ *
30
+ * You should have received a copy of the GNU Lesser General Public
31
+ * License along with this library; if not, write to the Free Software
32
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
33
+ *
34
+ * @category PHPExcel
35
+ * @package PHPExcel_Calculation
36
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
37
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
38
+ * @version ##VERSION##, ##DATE##
39
+ */
40
+ class PHPExcel_Calculation_Engineering
41
+ {
42
+ /**
43
+ * Details of the Units of measure that can be used in CONVERTUOM()
44
+ *
45
+ * @var mixed[]
46
+ */
47
+ private static $conversionUnits = array(
48
+ 'g' => array('Group' => 'Mass', 'Unit Name' => 'Gram', 'AllowPrefix' => true),
49
+ 'sg' => array('Group' => 'Mass', 'Unit Name' => 'Slug', 'AllowPrefix' => false),
50
+ 'lbm' => array('Group' => 'Mass', 'Unit Name' => 'Pound mass (avoirdupois)', 'AllowPrefix' => false),
51
+ 'u' => array('Group' => 'Mass', 'Unit Name' => 'U (atomic mass unit)', 'AllowPrefix' => true),
52
+ 'ozm' => array('Group' => 'Mass', 'Unit Name' => 'Ounce mass (avoirdupois)', 'AllowPrefix' => false),
53
+ 'm' => array('Group' => 'Distance', 'Unit Name' => 'Meter', 'AllowPrefix' => true),
54
+ 'mi' => array('Group' => 'Distance', 'Unit Name' => 'Statute mile', 'AllowPrefix' => false),
55
+ 'Nmi' => array('Group' => 'Distance', 'Unit Name' => 'Nautical mile', 'AllowPrefix' => false),
56
+ 'in' => array('Group' => 'Distance', 'Unit Name' => 'Inch', 'AllowPrefix' => false),
57
+ 'ft' => array('Group' => 'Distance', 'Unit Name' => 'Foot', 'AllowPrefix' => false),
58
+ 'yd' => array('Group' => 'Distance', 'Unit Name' => 'Yard', 'AllowPrefix' => false),
59
+ 'ang' => array('Group' => 'Distance', 'Unit Name' => 'Angstrom', 'AllowPrefix' => true),
60
+ 'Pica' => array('Group' => 'Distance', 'Unit Name' => 'Pica (1/72 in)', 'AllowPrefix' => false),
61
+ 'yr' => array('Group' => 'Time', 'Unit Name' => 'Year', 'AllowPrefix' => false),
62
+ 'day' => array('Group' => 'Time', 'Unit Name' => 'Day', 'AllowPrefix' => false),
63
+ 'hr' => array('Group' => 'Time', 'Unit Name' => 'Hour', 'AllowPrefix' => false),
64
+ 'mn' => array('Group' => 'Time', 'Unit Name' => 'Minute', 'AllowPrefix' => false),
65
+ 'sec' => array('Group' => 'Time', 'Unit Name' => 'Second', 'AllowPrefix' => true),
66
+ 'Pa' => array('Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true),
67
+ 'p' => array('Group' => 'Pressure', 'Unit Name' => 'Pascal', 'AllowPrefix' => true),
68
+ 'atm' => array('Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true),
69
+ 'at' => array('Group' => 'Pressure', 'Unit Name' => 'Atmosphere', 'AllowPrefix' => true),
70
+ 'mmHg' => array('Group' => 'Pressure', 'Unit Name' => 'mm of Mercury', 'AllowPrefix' => true),
71
+ 'N' => array('Group' => 'Force', 'Unit Name' => 'Newton', 'AllowPrefix' => true),
72
+ 'dyn' => array('Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true),
73
+ 'dy' => array('Group' => 'Force', 'Unit Name' => 'Dyne', 'AllowPrefix' => true),
74
+ 'lbf' => array('Group' => 'Force', 'Unit Name' => 'Pound force', 'AllowPrefix' => false),
75
+ 'J' => array('Group' => 'Energy', 'Unit Name' => 'Joule', 'AllowPrefix' => true),
76
+ 'e' => array('Group' => 'Energy', 'Unit Name' => 'Erg', 'AllowPrefix' => true),
77
+ 'c' => array('Group' => 'Energy', 'Unit Name' => 'Thermodynamic calorie', 'AllowPrefix' => true),
78
+ 'cal' => array('Group' => 'Energy', 'Unit Name' => 'IT calorie', 'AllowPrefix' => true),
79
+ 'eV' => array('Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true),
80
+ 'ev' => array('Group' => 'Energy', 'Unit Name' => 'Electron volt', 'AllowPrefix' => true),
81
+ 'HPh' => array('Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false),
82
+ 'hh' => array('Group' => 'Energy', 'Unit Name' => 'Horsepower-hour', 'AllowPrefix' => false),
83
+ 'Wh' => array('Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true),
84
+ 'wh' => array('Group' => 'Energy', 'Unit Name' => 'Watt-hour', 'AllowPrefix' => true),
85
+ 'flb' => array('Group' => 'Energy', 'Unit Name' => 'Foot-pound', 'AllowPrefix' => false),
86
+ 'BTU' => array('Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false),
87
+ 'btu' => array('Group' => 'Energy', 'Unit Name' => 'BTU', 'AllowPrefix' => false),
88
+ 'HP' => array('Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false),
89
+ 'h' => array('Group' => 'Power', 'Unit Name' => 'Horsepower', 'AllowPrefix' => false),
90
+ 'W' => array('Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true),
91
+ 'w' => array('Group' => 'Power', 'Unit Name' => 'Watt', 'AllowPrefix' => true),
92
+ 'T' => array('Group' => 'Magnetism', 'Unit Name' => 'Tesla', 'AllowPrefix' => true),
93
+ 'ga' => array('Group' => 'Magnetism', 'Unit Name' => 'Gauss', 'AllowPrefix' => true),
94
+ 'C' => array('Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false),
95
+ 'cel' => array('Group' => 'Temperature', 'Unit Name' => 'Celsius', 'AllowPrefix' => false),
96
+ 'F' => array('Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false),
97
+ 'fah' => array('Group' => 'Temperature', 'Unit Name' => 'Fahrenheit', 'AllowPrefix' => false),
98
+ 'K' => array('Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false),
99
+ 'kel' => array('Group' => 'Temperature', 'Unit Name' => 'Kelvin', 'AllowPrefix' => false),
100
+ 'tsp' => array('Group' => 'Liquid', 'Unit Name' => 'Teaspoon', 'AllowPrefix' => false),
101
+ 'tbs' => array('Group' => 'Liquid', 'Unit Name' => 'Tablespoon', 'AllowPrefix' => false),
102
+ 'oz' => array('Group' => 'Liquid', 'Unit Name' => 'Fluid Ounce', 'AllowPrefix' => false),
103
+ 'cup' => array('Group' => 'Liquid', 'Unit Name' => 'Cup', 'AllowPrefix' => false),
104
+ 'pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false),
105
+ 'us_pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.S. Pint', 'AllowPrefix' => false),
106
+ 'uk_pt' => array('Group' => 'Liquid', 'Unit Name' => 'U.K. Pint', 'AllowPrefix' => false),
107
+ 'qt' => array('Group' => 'Liquid', 'Unit Name' => 'Quart', 'AllowPrefix' => false),
108
+ 'gal' => array('Group' => 'Liquid', 'Unit Name' => 'Gallon', 'AllowPrefix' => false),
109
+ 'l' => array('Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true),
110
+ 'lt' => array('Group' => 'Liquid', 'Unit Name' => 'Litre', 'AllowPrefix' => true),
111
+ );
112
+
113
+ /**
114
+ * Details of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
115
+ *
116
+ * @var mixed[]
117
+ */
118
+ private static $conversionMultipliers = array(
119
+ 'Y' => array('multiplier' => 1E24, 'name' => 'yotta'),
120
+ 'Z' => array('multiplier' => 1E21, 'name' => 'zetta'),
121
+ 'E' => array('multiplier' => 1E18, 'name' => 'exa'),
122
+ 'P' => array('multiplier' => 1E15, 'name' => 'peta'),
123
+ 'T' => array('multiplier' => 1E12, 'name' => 'tera'),
124
+ 'G' => array('multiplier' => 1E9, 'name' => 'giga'),
125
+ 'M' => array('multiplier' => 1E6, 'name' => 'mega'),
126
+ 'k' => array('multiplier' => 1E3, 'name' => 'kilo'),
127
+ 'h' => array('multiplier' => 1E2, 'name' => 'hecto'),
128
+ 'e' => array('multiplier' => 1E1, 'name' => 'deka'),
129
+ 'd' => array('multiplier' => 1E-1, 'name' => 'deci'),
130
+ 'c' => array('multiplier' => 1E-2, 'name' => 'centi'),
131
+ 'm' => array('multiplier' => 1E-3, 'name' => 'milli'),
132
+ 'u' => array('multiplier' => 1E-6, 'name' => 'micro'),
133
+ 'n' => array('multiplier' => 1E-9, 'name' => 'nano'),
134
+ 'p' => array('multiplier' => 1E-12, 'name' => 'pico'),
135
+ 'f' => array('multiplier' => 1E-15, 'name' => 'femto'),
136
+ 'a' => array('multiplier' => 1E-18, 'name' => 'atto'),
137
+ 'z' => array('multiplier' => 1E-21, 'name' => 'zepto'),
138
+ 'y' => array('multiplier' => 1E-24, 'name' => 'yocto'),
139
+ );
140
+
141
+ /**
142
+ * Details of the Units of measure conversion factors, organised by group
143
+ *
144
+ * @var mixed[]
145
+ */
146
+ private static $unitConversions = array(
147
+ 'Mass' => array(
148
+ 'g' => array(
149
+ 'g' => 1.0,
150
+ 'sg' => 6.85220500053478E-05,
151
+ 'lbm' => 2.20462291469134E-03,
152
+ 'u' => 6.02217000000000E+23,
153
+ 'ozm' => 3.52739718003627E-02,
154
+ ),
155
+ 'sg' => array(
156
+ 'g' => 1.45938424189287E+04,
157
+ 'sg' => 1.0,
158
+ 'lbm' => 3.21739194101647E+01,
159
+ 'u' => 8.78866000000000E+27,
160
+ 'ozm' => 5.14782785944229E+02,
161
+ ),
162
+ 'lbm' => array(
163
+ 'g' => 4.5359230974881148E+02,
164
+ 'sg' => 3.10810749306493E-02,
165
+ 'lbm' => 1.0,
166
+ 'u' => 2.73161000000000E+26,
167
+ 'ozm' => 1.60000023429410E+01,
168
+ ),
169
+ 'u' => array(
170
+ 'g' => 1.66053100460465E-24,
171
+ 'sg' => 1.13782988532950E-28,
172
+ 'lbm' => 3.66084470330684E-27,
173
+ 'u' => 1.0,
174
+ 'ozm' => 5.85735238300524E-26,
175
+ ),
176
+ 'ozm' => array(
177
+ 'g' => 2.83495152079732E+01,
178
+ 'sg' => 1.94256689870811E-03,
179
+ 'lbm' => 6.24999908478882E-02,
180
+ 'u' => 1.70725600000000E+25,
181
+ 'ozm' => 1.0,
182
+ ),
183
+ ),
184
+ 'Distance' => array(
185
+ 'm' => array(
186
+ 'm' => 1.0,
187
+ 'mi' => 6.21371192237334E-04,
188
+ 'Nmi' => 5.39956803455724E-04,
189
+ 'in' => 3.93700787401575E+01,
190
+ 'ft' => 3.28083989501312E+00,
191
+ 'yd' => 1.09361329797891E+00,
192
+ 'ang' => 1.00000000000000E+10,
193
+ 'Pica' => 2.83464566929116E+03,
194
+ ),
195
+ 'mi' => array(
196
+ 'm' => 1.60934400000000E+03,
197
+ 'mi' => 1.0,
198
+ 'Nmi' => 8.68976241900648E-01,
199
+ 'in' => 6.33600000000000E+04,
200
+ 'ft' => 5.28000000000000E+03,
201
+ 'yd' => 1.76000000000000E+03,
202
+ 'ang' => 1.60934400000000E+13,
203
+ 'Pica' => 4.56191999999971E+06,
204
+ ),
205
+ 'Nmi' => array(
206
+ 'm' => 1.85200000000000E+03,
207
+ 'mi' => 1.15077944802354E+00,
208
+ 'Nmi' => 1.0,
209
+ 'in' => 7.29133858267717E+04,
210
+ 'ft' => 6.07611548556430E+03,
211
+ 'yd' => 2.02537182785694E+03,
212
+ 'ang' => 1.85200000000000E+13,
213
+ 'Pica' => 5.24976377952723E+06,
214
+ ),
215
+ 'in' => array(
216
+ 'm' => 2.54000000000000E-02,
217
+ 'mi' => 1.57828282828283E-05,
218
+ 'Nmi' => 1.37149028077754E-05,
219
+ 'in' => 1.0,
220
+ 'ft' => 8.33333333333333E-02,
221
+ 'yd' => 2.77777777686643E-02,
222
+ 'ang' => 2.54000000000000E+08,
223
+ 'Pica' => 7.19999999999955E+01,
224
+ ),
225
+ 'ft' => array(
226
+ 'm' => 3.04800000000000E-01,
227
+ 'mi' => 1.89393939393939E-04,
228
+ 'Nmi' => 1.64578833693305E-04,
229
+ 'in' => 1.20000000000000E+01,
230
+ 'ft' => 1.0,
231
+ 'yd' => 3.33333333223972E-01,
232
+ 'ang' => 3.04800000000000E+09,
233
+ 'Pica' => 8.63999999999946E+02,
234
+ ),
235
+ 'yd' => array(
236
+ 'm' => 9.14400000300000E-01,
237
+ 'mi' => 5.68181818368230E-04,
238
+ 'Nmi' => 4.93736501241901E-04,
239
+ 'in' => 3.60000000118110E+01,
240
+ 'ft' => 3.00000000000000E+00,
241
+ 'yd' => 1.0,
242
+ 'ang' => 9.14400000300000E+09,
243
+ 'Pica' => 2.59200000085023E+03,
244
+ ),
245
+ 'ang' => array(
246
+ 'm' => 1.00000000000000E-10,
247
+ 'mi' => 6.21371192237334E-14,
248
+ 'Nmi' => 5.39956803455724E-14,
249
+ 'in' => 3.93700787401575E-09,
250
+ 'ft' => 3.28083989501312E-10,
251
+ 'yd' => 1.09361329797891E-10,
252
+ 'ang' => 1.0,
253
+ 'Pica' => 2.83464566929116E-07,
254
+ ),
255
+ 'Pica' => array(
256
+ 'm' => 3.52777777777800E-04,
257
+ 'mi' => 2.19205948372629E-07,
258
+ 'Nmi' => 1.90484761219114E-07,
259
+ 'in' => 1.38888888888898E-02,
260
+ 'ft' => 1.15740740740748E-03,
261
+ 'yd' => 3.85802469009251E-04,
262
+ 'ang' => 3.52777777777800E+06,
263
+ 'Pica' => 1.0,
264
+ ),
265
+ ),
266
+ 'Time' => array(
267
+ 'yr' => array(
268
+ 'yr' => 1.0,
269
+ 'day' => 365.25,
270
+ 'hr' => 8766.0,
271
+ 'mn' => 525960.0,
272
+ 'sec' => 31557600.0,
273
+ ),
274
+ 'day' => array(
275
+ 'yr' => 2.73785078713210E-03,
276
+ 'day' => 1.0,
277
+ 'hr' => 24.0,
278
+ 'mn' => 1440.0,
279
+ 'sec' => 86400.0,
280
+ ),
281
+ 'hr' => array(
282
+ 'yr' => 1.14077116130504E-04,
283
+ 'day' => 4.16666666666667E-02,
284
+ 'hr' => 1.0,
285
+ 'mn' => 60.0,
286
+ 'sec' => 3600.0,
287
+ ),
288
+ 'mn' => array(
289
+ 'yr' => 1.90128526884174E-06,
290
+ 'day' => 6.94444444444444E-04,
291
+ 'hr' => 1.66666666666667E-02,
292
+ 'mn' => 1.0,
293
+ 'sec' => 60.0,
294
+ ),
295
+ 'sec' => array(
296
+ 'yr' => 3.16880878140289E-08,
297
+ 'day' => 1.15740740740741E-05,
298
+ 'hr' => 2.77777777777778E-04,
299
+ 'mn' => 1.66666666666667E-02,
300
+ 'sec' => 1.0,
301
+ ),
302
+ ),
303
+ 'Pressure' => array(
304
+ 'Pa' => array(
305
+ 'Pa' => 1.0,
306
+ 'p' => 1.0,
307
+ 'atm' => 9.86923299998193E-06,
308
+ 'at' => 9.86923299998193E-06,
309
+ 'mmHg' => 7.50061707998627E-03,
310
+ ),
311
+ 'p' => array(
312
+ 'Pa' => 1.0,
313
+ 'p' => 1.0,
314
+ 'atm' => 9.86923299998193E-06,
315
+ 'at' => 9.86923299998193E-06,
316
+ 'mmHg' => 7.50061707998627E-03,
317
+ ),
318
+ 'atm' => array(
319
+ 'Pa' => 1.01324996583000E+05,
320
+ 'p' => 1.01324996583000E+05,
321
+ 'atm' => 1.0,
322
+ 'at' => 1.0,
323
+ 'mmHg' => 760.0,
324
+ ),
325
+ 'at' => array(
326
+ 'Pa' => 1.01324996583000E+05,
327
+ 'p' => 1.01324996583000E+05,
328
+ 'atm' => 1.0,
329
+ 'at' => 1.0,
330
+ 'mmHg' => 760.0,
331
+ ),
332
+ 'mmHg' => array(
333
+ 'Pa' => 1.33322363925000E+02,
334
+ 'p' => 1.33322363925000E+02,
335
+ 'atm' => 1.31578947368421E-03,
336
+ 'at' => 1.31578947368421E-03,
337
+ 'mmHg' => 1.0,
338
+ ),
339
+ ),
340
+ 'Force' => array(
341
+ 'N' => array(
342
+ 'N' => 1.0,
343
+ 'dyn' => 1.0E+5,
344
+ 'dy' => 1.0E+5,
345
+ 'lbf' => 2.24808923655339E-01,
346
+ ),
347
+ 'dyn' => array(
348
+ 'N' => 1.0E-5,
349
+ 'dyn' => 1.0,
350
+ 'dy' => 1.0,
351
+ 'lbf' => 2.24808923655339E-06,
352
+ ),
353
+ 'dy' => array(
354
+ 'N' => 1.0E-5,
355
+ 'dyn' => 1.0,
356
+ 'dy' => 1.0,
357
+ 'lbf' => 2.24808923655339E-06,
358
+ ),
359
+ 'lbf' => array(
360
+ 'N' => 4.448222,
361
+ 'dyn' => 4.448222E+5,
362
+ 'dy' => 4.448222E+5,
363
+ 'lbf' => 1.0,
364
+ ),
365
+ ),
366
+ 'Energy' => array(
367
+ 'J' => array(
368
+ 'J' => 1.0,
369
+ 'e' => 9.99999519343231E+06,
370
+ 'c' => 2.39006249473467E-01,
371
+ 'cal' => 2.38846190642017E-01,
372
+ 'eV' => 6.24145700000000E+18,
373
+ 'ev' => 6.24145700000000E+18,
374
+ 'HPh' => 3.72506430801000E-07,
375
+ 'hh' => 3.72506430801000E-07,
376
+ 'Wh' => 2.77777916238711E-04,
377
+ 'wh' => 2.77777916238711E-04,
378
+ 'flb' => 2.37304222192651E+01,
379
+ 'BTU' => 9.47815067349015E-04,
380
+ 'btu' => 9.47815067349015E-04,
381
+ ),
382
+ 'e' => array(
383
+ 'J' => 1.00000048065700E-07,
384
+ 'e' => 1.0,
385
+ 'c' => 2.39006364353494E-08,
386
+ 'cal' => 2.38846305445111E-08,
387
+ 'eV' => 6.24146000000000E+11,
388
+ 'ev' => 6.24146000000000E+11,
389
+ 'HPh' => 3.72506609848824E-14,
390
+ 'hh' => 3.72506609848824E-14,
391
+ 'Wh' => 2.77778049754611E-11,
392
+ 'wh' => 2.77778049754611E-11,
393
+ 'flb' => 2.37304336254586E-06,
394
+ 'BTU' => 9.47815522922962E-11,
395
+ 'btu' => 9.47815522922962E-11,
396
+ ),
397
+ 'c' => array(
398
+ 'J' => 4.18399101363672E+00,
399
+ 'e' => 4.18398900257312E+07,
400
+ 'c' => 1.0,
401
+ 'cal' => 9.99330315287563E-01,
402
+ 'eV' => 2.61142000000000E+19,
403
+ 'ev' => 2.61142000000000E+19,
404
+ 'HPh' => 1.55856355899327E-06,
405
+ 'hh' => 1.55856355899327E-06,
406
+ 'Wh' => 1.16222030532950E-03,
407
+ 'wh' => 1.16222030532950E-03,
408
+ 'flb' => 9.92878733152102E+01,
409
+ 'BTU' => 3.96564972437776E-03,
410
+ 'btu' => 3.96564972437776E-03,
411
+ ),
412
+ 'cal' => array(
413
+ 'J' => 4.18679484613929E+00,
414
+ 'e' => 4.18679283372801E+07,
415
+ 'c' => 1.00067013349059E+00,
416
+ 'cal' => 1.0,
417
+ 'eV' => 2.61317000000000E+19,
418
+ 'ev' => 2.61317000000000E+19,
419
+ 'HPh' => 1.55960800463137E-06,
420
+ 'hh' => 1.55960800463137E-06,
421
+ 'Wh' => 1.16299914807955E-03,
422
+ 'wh' => 1.16299914807955E-03,
423
+ 'flb' => 9.93544094443283E+01,
424
+ 'BTU' => 3.96830723907002E-03,
425
+ 'btu' => 3.96830723907002E-03,
426
+ ),
427
+ 'eV' => array(
428
+ 'J' => 1.60219000146921E-19,
429
+ 'e' => 1.60218923136574E-12,
430
+ 'c' => 3.82933423195043E-20,
431
+ 'cal' => 3.82676978535648E-20,
432
+ 'eV' => 1.0,
433
+ 'ev' => 1.0,
434
+ 'HPh' => 5.96826078912344E-26,
435
+ 'hh' => 5.96826078912344E-26,
436
+ 'Wh' => 4.45053000026614E-23,
437
+ 'wh' => 4.45053000026614E-23,
438
+ 'flb' => 3.80206452103492E-18,
439
+ 'BTU' => 1.51857982414846E-22,
440
+ 'btu' => 1.51857982414846E-22,
441
+ ),
442
+ 'ev' => array(
443
+ 'J' => 1.60219000146921E-19,
444
+ 'e' => 1.60218923136574E-12,
445
+ 'c' => 3.82933423195043E-20,
446
+ 'cal' => 3.82676978535648E-20,
447
+ 'eV' => 1.0,
448
+ 'ev' => 1.0,
449
+ 'HPh' => 5.96826078912344E-26,
450
+ 'hh' => 5.96826078912344E-26,
451
+ 'Wh' => 4.45053000026614E-23,
452
+ 'wh' => 4.45053000026614E-23,
453
+ 'flb' => 3.80206452103492E-18,
454
+ 'BTU' => 1.51857982414846E-22,
455
+ 'btu' => 1.51857982414846E-22,
456
+ ),
457
+ 'HPh' => array(
458
+ 'J' => 2.68451741316170E+06,
459
+ 'e' => 2.68451612283024E+13,
460
+ 'c' => 6.41616438565991E+05,
461
+ 'cal' => 6.41186757845835E+05,
462
+ 'eV' => 1.67553000000000E+25,
463
+ 'ev' => 1.67553000000000E+25,
464
+ 'HPh' => 1.0,
465
+ 'hh' => 1.0,
466
+ 'Wh' => 7.45699653134593E+02,
467
+ 'wh' => 7.45699653134593E+02,
468
+ 'flb' => 6.37047316692964E+07,
469
+ 'BTU' => 2.54442605275546E+03,
470
+ 'btu' => 2.54442605275546E+03,
471
+ ),
472
+ 'hh' => array(
473
+ 'J' => 2.68451741316170E+06,
474
+ 'e' => 2.68451612283024E+13,
475
+ 'c' => 6.41616438565991E+05,
476
+ 'cal' => 6.41186757845835E+05,
477
+ 'eV' => 1.67553000000000E+25,
478
+ 'ev' => 1.67553000000000E+25,
479
+ 'HPh' => 1.0,
480
+ 'hh' => 1.0,
481
+ 'Wh' => 7.45699653134593E+02,
482
+ 'wh' => 7.45699653134593E+02,
483
+ 'flb' => 6.37047316692964E+07,
484
+ 'BTU' => 2.54442605275546E+03,
485
+ 'btu' => 2.54442605275546E+03,
486
+ ),
487
+ 'Wh' => array(
488
+ 'J' => 3.59999820554720E+03,
489
+ 'e' => 3.59999647518369E+10,
490
+ 'c' => 8.60422069219046E+02,
491
+ 'cal' => 8.59845857713046E+02,
492
+ 'eV' => 2.24692340000000E+22,
493
+ 'ev' => 2.24692340000000E+22,
494
+ 'HPh' => 1.34102248243839E-03,
495
+ 'hh' => 1.34102248243839E-03,
496
+ 'Wh' => 1.0,
497
+ 'wh' => 1.0,
498
+ 'flb' => 8.54294774062316E+04,
499
+ 'BTU' => 3.41213254164705E+00,
500
+ 'btu' => 3.41213254164705E+00,
501
+ ),
502
+ 'wh' => array(
503
+ 'J' => 3.59999820554720E+03,
504
+ 'e' => 3.59999647518369E+10,
505
+ 'c' => 8.60422069219046E+02,
506
+ 'cal' => 8.59845857713046E+02,
507
+ 'eV' => 2.24692340000000E+22,
508
+ 'ev' => 2.24692340000000E+22,
509
+ 'HPh' => 1.34102248243839E-03,
510
+ 'hh' => 1.34102248243839E-03,
511
+ 'Wh' => 1.0,
512
+ 'wh' => 1.0,
513
+ 'flb' => 8.54294774062316E+04,
514
+ 'BTU' => 3.41213254164705E+00,
515
+ 'btu' => 3.41213254164705E+00,
516
+ ),
517
+ 'flb' => array(
518
+ 'J' => 4.21400003236424E-02,
519
+ 'e' => 4.21399800687660E+05,
520
+ 'c' => 1.00717234301644E-02,
521
+ 'cal' => 1.00649785509554E-02,
522
+ 'eV' => 2.63015000000000E+17,
523
+ 'ev' => 2.63015000000000E+17,
524
+ 'HPh' => 1.56974211145130E-08,
525
+ 'hh' => 1.56974211145130E-08,
526
+ 'Wh' => 1.17055614802000E-05,
527
+ 'wh' => 1.17055614802000E-05,
528
+ 'flb' => 1.0,
529
+ 'BTU' => 3.99409272448406E-05,
530
+ 'btu' => 3.99409272448406E-05,
531
+ ),
532
+ 'BTU' => array(
533
+ 'J' => 1.05505813786749E+03,
534
+ 'e' => 1.05505763074665E+10,
535
+ 'c' => 2.52165488508168E+02,
536
+ 'cal' => 2.51996617135510E+02,
537
+ 'eV' => 6.58510000000000E+21,
538
+ 'ev' => 6.58510000000000E+21,
539
+ 'HPh' => 3.93015941224568E-04,
540
+ 'hh' => 3.93015941224568E-04,
541
+ 'Wh' => 2.93071851047526E-01,
542
+ 'wh' => 2.93071851047526E-01,
543
+ 'flb' => 2.50369750774671E+04,
544
+ 'BTU' => 1.0,
545
+ 'btu' => 1.0,
546
+ ),
547
+ 'btu' => array(
548
+ 'J' => 1.05505813786749E+03,
549
+ 'e' => 1.05505763074665E+10,
550
+ 'c' => 2.52165488508168E+02,
551
+ 'cal' => 2.51996617135510E+02,
552
+ 'eV' => 6.58510000000000E+21,
553
+ 'ev' => 6.58510000000000E+21,
554
+ 'HPh' => 3.93015941224568E-04,
555
+ 'hh' => 3.93015941224568E-04,
556
+ 'Wh' => 2.93071851047526E-01,
557
+ 'wh' => 2.93071851047526E-01,
558
+ 'flb' => 2.50369750774671E+04,
559
+ 'BTU' => 1.0,
560
+ 'btu' => 1.0,
561
+ ),
562
+ ),
563
+ 'Power' => array(
564
+ 'HP' => array(
565
+ 'HP' => 1.0,
566
+ 'h' => 1.0,
567
+ 'W' => 7.45701000000000E+02,
568
+ 'w' => 7.45701000000000E+02,
569
+ ),
570
+ 'h' => array(
571
+ 'HP' => 1.0,
572
+ 'h' => 1.0,
573
+ 'W' => 7.45701000000000E+02,
574
+ 'w' => 7.45701000000000E+02,
575
+ ),
576
+ 'W' => array(
577
+ 'HP' => 1.34102006031908E-03,
578
+ 'h' => 1.34102006031908E-03,
579
+ 'W' => 1.0,
580
+ 'w' => 1.0,
581
+ ),
582
+ 'w' => array(
583
+ 'HP' => 1.34102006031908E-03,
584
+ 'h' => 1.34102006031908E-03,
585
+ 'W' => 1.0,
586
+ 'w' => 1.0,
587
+ ),
588
+ ),
589
+ 'Magnetism' => array(
590
+ 'T' => array(
591
+ 'T' => 1.0,
592
+ 'ga' => 10000.0,
593
+ ),
594
+ 'ga' => array(
595
+ 'T' => 0.0001,
596
+ 'ga' => 1.0,
597
+ ),
598
+ ),
599
+ 'Liquid' => array(
600
+ 'tsp' => array(
601
+ 'tsp' => 1.0,
602
+ 'tbs' => 3.33333333333333E-01,
603
+ 'oz' => 1.66666666666667E-01,
604
+ 'cup' => 2.08333333333333E-02,
605
+ 'pt' => 1.04166666666667E-02,
606
+ 'us_pt' => 1.04166666666667E-02,
607
+ 'uk_pt' => 8.67558516821960E-03,
608
+ 'qt' => 5.20833333333333E-03,
609
+ 'gal' => 1.30208333333333E-03,
610
+ 'l' => 4.92999408400710E-03,
611
+ 'lt' => 4.92999408400710E-03,
612
+ ),
613
+ 'tbs' => array(
614
+ 'tsp' => 3.00000000000000E+00,
615
+ 'tbs' => 1.0,
616
+ 'oz' => 5.00000000000000E-01,
617
+ 'cup' => 6.25000000000000E-02,
618
+ 'pt' => 3.12500000000000E-02,
619
+ 'us_pt' => 3.12500000000000E-02,
620
+ 'uk_pt' => 2.60267555046588E-02,
621
+ 'qt' => 1.56250000000000E-02,
622
+ 'gal' => 3.90625000000000E-03,
623
+ 'l' => 1.47899822520213E-02,
624
+ 'lt' => 1.47899822520213E-02,
625
+ ),
626
+ 'oz' => array(
627
+ 'tsp' => 6.00000000000000E+00,
628
+ 'tbs' => 2.00000000000000E+00,
629
+ 'oz' => 1.0,
630
+ 'cup' => 1.25000000000000E-01,
631
+ 'pt' => 6.25000000000000E-02,
632
+ 'us_pt' => 6.25000000000000E-02,
633
+ 'uk_pt' => 5.20535110093176E-02,
634
+ 'qt' => 3.12500000000000E-02,
635
+ 'gal' => 7.81250000000000E-03,
636
+ 'l' => 2.95799645040426E-02,
637
+ 'lt' => 2.95799645040426E-02,
638
+ ),
639
+ 'cup' => array(
640
+ 'tsp' => 4.80000000000000E+01,
641
+ 'tbs' => 1.60000000000000E+01,
642
+ 'oz' => 8.00000000000000E+00,
643
+ 'cup' => 1.0,
644
+ 'pt' => 5.00000000000000E-01,
645
+ 'us_pt' => 5.00000000000000E-01,
646
+ 'uk_pt' => 4.16428088074541E-01,
647
+ 'qt' => 2.50000000000000E-01,
648
+ 'gal' => 6.25000000000000E-02,
649
+ 'l' => 2.36639716032341E-01,
650
+ 'lt' => 2.36639716032341E-01,
651
+ ),
652
+ 'pt' => array(
653
+ 'tsp' => 9.60000000000000E+01,
654
+ 'tbs' => 3.20000000000000E+01,
655
+ 'oz' => 1.60000000000000E+01,
656
+ 'cup' => 2.00000000000000E+00,
657
+ 'pt' => 1.0,
658
+ 'us_pt' => 1.0,
659
+ 'uk_pt' => 8.32856176149081E-01,
660
+ 'qt' => 5.00000000000000E-01,
661
+ 'gal' => 1.25000000000000E-01,
662
+ 'l' => 4.73279432064682E-01,
663
+ 'lt' => 4.73279432064682E-01,
664
+ ),
665
+ 'us_pt' => array(
666
+ 'tsp' => 9.60000000000000E+01,
667
+ 'tbs' => 3.20000000000000E+01,
668
+ 'oz' => 1.60000000000000E+01,
669
+ 'cup' => 2.00000000000000E+00,
670
+ 'pt' => 1.0,
671
+ 'us_pt' => 1.0,
672
+ 'uk_pt' => 8.32856176149081E-01,
673
+ 'qt' => 5.00000000000000E-01,
674
+ 'gal' => 1.25000000000000E-01,
675
+ 'l' => 4.73279432064682E-01,
676
+ 'lt' => 4.73279432064682E-01,
677
+ ),
678
+ 'uk_pt' => array(
679
+ 'tsp' => 1.15266000000000E+02,
680
+ 'tbs' => 3.84220000000000E+01,
681
+ 'oz' => 1.92110000000000E+01,
682
+ 'cup' => 2.40137500000000E+00,
683
+ 'pt' => 1.20068750000000E+00,
684
+ 'us_pt' => 1.20068750000000E+00,
685
+ 'uk_pt' => 1.0,
686
+ 'qt' => 6.00343750000000E-01,
687
+ 'gal' => 1.50085937500000E-01,
688
+ 'l' => 5.68260698087162E-01,
689
+ 'lt' => 5.68260698087162E-01,
690
+ ),
691
+ 'qt' => array(
692
+ 'tsp' => 1.92000000000000E+02,
693
+ 'tbs' => 6.40000000000000E+01,
694
+ 'oz' => 3.20000000000000E+01,
695
+ 'cup' => 4.00000000000000E+00,
696
+ 'pt' => 2.00000000000000E+00,
697
+ 'us_pt' => 2.00000000000000E+00,
698
+ 'uk_pt' => 1.66571235229816E+00,
699
+ 'qt' => 1.0,
700
+ 'gal' => 2.50000000000000E-01,
701
+ 'l' => 9.46558864129363E-01,
702
+ 'lt' => 9.46558864129363E-01,
703
+ ),
704
+ 'gal' => array(
705
+ 'tsp' => 7.68000000000000E+02,
706
+ 'tbs' => 2.56000000000000E+02,
707
+ 'oz' => 1.28000000000000E+02,
708
+ 'cup' => 1.60000000000000E+01,
709
+ 'pt' => 8.00000000000000E+00,
710
+ 'us_pt' => 8.00000000000000E+00,
711
+ 'uk_pt' => 6.66284940919265E+00,
712
+ 'qt' => 4.00000000000000E+00,
713
+ 'gal' => 1.0,
714
+ 'l' => 3.78623545651745E+00,
715
+ 'lt' => 3.78623545651745E+00,
716
+ ),
717
+ 'l' => array(
718
+ 'tsp' => 2.02840000000000E+02,
719
+ 'tbs' => 6.76133333333333E+01,
720
+ 'oz' => 3.38066666666667E+01,
721
+ 'cup' => 4.22583333333333E+00,
722
+ 'pt' => 2.11291666666667E+00,
723
+ 'us_pt' => 2.11291666666667E+00,
724
+ 'uk_pt' => 1.75975569552166E+00,
725
+ 'qt' => 1.05645833333333E+00,
726
+ 'gal' => 2.64114583333333E-01,
727
+ 'l' => 1.0,
728
+ 'lt' => 1.0,
729
+ ),
730
+ 'lt' => array(
731
+ 'tsp' => 2.02840000000000E+02,
732
+ 'tbs' => 6.76133333333333E+01,
733
+ 'oz' => 3.38066666666667E+01,
734
+ 'cup' => 4.22583333333333E+00,
735
+ 'pt' => 2.11291666666667E+00,
736
+ 'us_pt' => 2.11291666666667E+00,
737
+ 'uk_pt' => 1.75975569552166E+00,
738
+ 'qt' => 1.05645833333333E+00,
739
+ 'gal' => 2.64114583333333E-01,
740
+ 'l' => 1.0,
741
+ 'lt' => 1.0,
742
+ ),
743
+ ),
744
+ );
745
+
746
+
747
+ /**
748
+ * parseComplex
749
+ *
750
+ * Parses a complex number into its real and imaginary parts, and an I or J suffix
751
+ *
752
+ * @param string $complexNumber The complex number
753
+ * @return string[] Indexed on "real", "imaginary" and "suffix"
754
+ */
755
+ public static function parseComplex($complexNumber)
756
+ {
757
+ $workString = (string) $complexNumber;
758
+
759
+ $realNumber = $imaginary = 0;
760
+ // Extract the suffix, if there is one
761
+ $suffix = substr($workString, -1);
762
+ if (!is_numeric($suffix)) {
763
+ $workString = substr($workString, 0, -1);
764
+ } else {
765
+ $suffix = '';
766
+ }
767
+
768
+ // Split the input into its Real and Imaginary components
769
+ $leadingSign = 0;
770
+ if (strlen($workString) > 0) {
771
+ $leadingSign = (($workString{0} == '+') || ($workString{0} == '-')) ? 1 : 0;
772
+ }
773
+ $power = '';
774
+ $realNumber = strtok($workString, '+-');
775
+ if (strtoupper(substr($realNumber, -1)) == 'E') {
776
+ $power = strtok('+-');
777
+ ++$leadingSign;
778
+ }
779
+
780
+ $realNumber = substr($workString, 0, strlen($realNumber)+strlen($power)+$leadingSign);
781
+
782
+ if ($suffix != '') {
783
+ $imaginary = substr($workString, strlen($realNumber));
784
+
785
+ if (($imaginary == '') && (($realNumber == '') || ($realNumber == '+') || ($realNumber == '-'))) {
786
+ $imaginary = $realNumber.'1';
787
+ $realNumber = '0';
788
+ } elseif ($imaginary == '') {
789
+ $imaginary = $realNumber;
790
+ $realNumber = '0';
791
+ } elseif (($imaginary == '+') || ($imaginary == '-')) {
792
+ $imaginary .= '1';
793
+ }
794
+ }
795
+
796
+ return array(
797
+ 'real' => $realNumber,
798
+ 'imaginary' => $imaginary,
799
+ 'suffix' => $suffix
800
+ );
801
+ }
802
+
803
+
804
+ /**
805
+ * Cleans the leading characters in a complex number string
806
+ *
807
+ * @param string $complexNumber The complex number to clean
808
+ * @return string The "cleaned" complex number
809
+ */
810
+ private static function cleanComplex($complexNumber)
811
+ {
812
+ if ($complexNumber{0} == '+') {
813
+ $complexNumber = substr($complexNumber, 1);
814
+ }
815
+ if ($complexNumber{0} == '0') {
816
+ $complexNumber = substr($complexNumber, 1);
817
+ }
818
+ if ($complexNumber{0} == '.') {
819
+ $complexNumber = '0'.$complexNumber;
820
+ }
821
+ if ($complexNumber{0} == '+') {
822
+ $complexNumber = substr($complexNumber, 1);
823
+ }
824
+ return $complexNumber;
825
+ }
826
+
827
+ /**
828
+ * Formats a number base string value with leading zeroes
829
+ *
830
+ * @param string $xVal The "number" to pad
831
+ * @param integer $places The length that we want to pad this value
832
+ * @return string The padded "number"
833
+ */
834
+ private static function nbrConversionFormat($xVal, $places)
835
+ {
836
+ if (!is_null($places)) {
837
+ if (strlen($xVal) <= $places) {
838
+ return substr(str_pad($xVal, $places, '0', STR_PAD_LEFT), -10);
839
+ } else {
840
+ return PHPExcel_Calculation_Functions::NaN();
841
+ }
842
+ }
843
+
844
+ return substr($xVal, -10);
845
+ }
846
+
847
+ /**
848
+ * BESSELI
849
+ *
850
+ * Returns the modified Bessel function In(x), which is equivalent to the Bessel function evaluated
851
+ * for purely imaginary arguments
852
+ *
853
+ * Excel Function:
854
+ * BESSELI(x,ord)
855
+ *
856
+ * @access public
857
+ * @category Engineering Functions
858
+ * @param float $x The value at which to evaluate the function.
859
+ * If x is nonnumeric, BESSELI returns the #VALUE! error value.
860
+ * @param integer $ord The order of the Bessel function.
861
+ * If ord is not an integer, it is truncated.
862
+ * If $ord is nonnumeric, BESSELI returns the #VALUE! error value.
863
+ * If $ord < 0, BESSELI returns the #NUM! error value.
864
+ * @return float
865
+ *
866
+ */
867
+ public static function BESSELI($x, $ord)
868
+ {
869
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
870
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
871
+
872
+ if ((is_numeric($x)) && (is_numeric($ord))) {
873
+ $ord = floor($ord);
874
+ if ($ord < 0) {
875
+ return PHPExcel_Calculation_Functions::NaN();
876
+ }
877
+
878
+ if (abs($x) <= 30) {
879
+ $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord);
880
+ $ordK = 1;
881
+ $fSqrX = ($x * $x) / 4;
882
+ do {
883
+ $fTerm *= $fSqrX;
884
+ $fTerm /= ($ordK * ($ordK + $ord));
885
+ $fResult += $fTerm;
886
+ } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
887
+ } else {
888
+ $f_2_PI = 2 * M_PI;
889
+
890
+ $fXAbs = abs($x);
891
+ $fResult = exp($fXAbs) / sqrt($f_2_PI * $fXAbs);
892
+ if (($ord & 1) && ($x < 0)) {
893
+ $fResult = -$fResult;
894
+ }
895
+ }
896
+ return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult;
897
+ }
898
+ return PHPExcel_Calculation_Functions::VALUE();
899
+ }
900
+
901
+
902
+ /**
903
+ * BESSELJ
904
+ *
905
+ * Returns the Bessel function
906
+ *
907
+ * Excel Function:
908
+ * BESSELJ(x,ord)
909
+ *
910
+ * @access public
911
+ * @category Engineering Functions
912
+ * @param float $x The value at which to evaluate the function.
913
+ * If x is nonnumeric, BESSELJ returns the #VALUE! error value.
914
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
915
+ * If $ord is nonnumeric, BESSELJ returns the #VALUE! error value.
916
+ * If $ord < 0, BESSELJ returns the #NUM! error value.
917
+ * @return float
918
+ *
919
+ */
920
+ public static function BESSELJ($x, $ord)
921
+ {
922
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
923
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
924
+
925
+ if ((is_numeric($x)) && (is_numeric($ord))) {
926
+ $ord = floor($ord);
927
+ if ($ord < 0) {
928
+ return PHPExcel_Calculation_Functions::NaN();
929
+ }
930
+
931
+ $fResult = 0;
932
+ if (abs($x) <= 30) {
933
+ $fResult = $fTerm = pow($x / 2, $ord) / PHPExcel_Calculation_MathTrig::FACT($ord);
934
+ $ordK = 1;
935
+ $fSqrX = ($x * $x) / -4;
936
+ do {
937
+ $fTerm *= $fSqrX;
938
+ $fTerm /= ($ordK * ($ordK + $ord));
939
+ $fResult += $fTerm;
940
+ } while ((abs($fTerm) > 1e-12) && (++$ordK < 100));
941
+ } else {
942
+ $f_PI_DIV_2 = M_PI / 2;
943
+ $f_PI_DIV_4 = M_PI / 4;
944
+
945
+ $fXAbs = abs($x);
946
+ $fResult = sqrt(M_2DIVPI / $fXAbs) * cos($fXAbs - $ord * $f_PI_DIV_2 - $f_PI_DIV_4);
947
+ if (($ord & 1) && ($x < 0)) {
948
+ $fResult = -$fResult;
949
+ }
950
+ }
951
+ return (is_nan($fResult)) ? PHPExcel_Calculation_Functions::NaN() : $fResult;
952
+ }
953
+ return PHPExcel_Calculation_Functions::VALUE();
954
+ }
955
+
956
+
957
+ private static function besselK0($fNum)
958
+ {
959
+ if ($fNum <= 2) {
960
+ $fNum2 = $fNum * 0.5;
961
+ $y = ($fNum2 * $fNum2);
962
+ $fRet = -log($fNum2) * self::BESSELI($fNum, 0) +
963
+ (-0.57721566 + $y * (0.42278420 + $y * (0.23069756 + $y * (0.3488590e-1 + $y * (0.262698e-2 + $y *
964
+ (0.10750e-3 + $y * 0.74e-5))))));
965
+ } else {
966
+ $y = 2 / $fNum;
967
+ $fRet = exp(-$fNum) / sqrt($fNum) *
968
+ (1.25331414 + $y * (-0.7832358e-1 + $y * (0.2189568e-1 + $y * (-0.1062446e-1 + $y *
969
+ (0.587872e-2 + $y * (-0.251540e-2 + $y * 0.53208e-3))))));
970
+ }
971
+ return $fRet;
972
+ }
973
+
974
+
975
+ private static function besselK1($fNum)
976
+ {
977
+ if ($fNum <= 2) {
978
+ $fNum2 = $fNum * 0.5;
979
+ $y = ($fNum2 * $fNum2);
980
+ $fRet = log($fNum2) * self::BESSELI($fNum, 1) +
981
+ (1 + $y * (0.15443144 + $y * (-0.67278579 + $y * (-0.18156897 + $y * (-0.1919402e-1 + $y *
982
+ (-0.110404e-2 + $y * (-0.4686e-4))))))) / $fNum;
983
+ } else {
984
+ $y = 2 / $fNum;
985
+ $fRet = exp(-$fNum) / sqrt($fNum) *
986
+ (1.25331414 + $y * (0.23498619 + $y * (-0.3655620e-1 + $y * (0.1504268e-1 + $y * (-0.780353e-2 + $y *
987
+ (0.325614e-2 + $y * (-0.68245e-3)))))));
988
+ }
989
+ return $fRet;
990
+ }
991
+
992
+
993
+ /**
994
+ * BESSELK
995
+ *
996
+ * Returns the modified Bessel function Kn(x), which is equivalent to the Bessel functions evaluated
997
+ * for purely imaginary arguments.
998
+ *
999
+ * Excel Function:
1000
+ * BESSELK(x,ord)
1001
+ *
1002
+ * @access public
1003
+ * @category Engineering Functions
1004
+ * @param float $x The value at which to evaluate the function.
1005
+ * If x is nonnumeric, BESSELK returns the #VALUE! error value.
1006
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
1007
+ * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
1008
+ * If $ord < 0, BESSELK returns the #NUM! error value.
1009
+ * @return float
1010
+ *
1011
+ */
1012
+ public static function BESSELK($x, $ord)
1013
+ {
1014
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
1015
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
1016
+
1017
+ if ((is_numeric($x)) && (is_numeric($ord))) {
1018
+ if (($ord < 0) || ($x == 0.0)) {
1019
+ return PHPExcel_Calculation_Functions::NaN();
1020
+ }
1021
+
1022
+ switch (floor($ord)) {
1023
+ case 0:
1024
+ return self::besselK0($x);
1025
+ case 1:
1026
+ return self::besselK1($x);
1027
+ default:
1028
+ $fTox = 2 / $x;
1029
+ $fBkm = self::besselK0($x);
1030
+ $fBk = self::besselK1($x);
1031
+ for ($n = 1; $n < $ord; ++$n) {
1032
+ $fBkp = $fBkm + $n * $fTox * $fBk;
1033
+ $fBkm = $fBk;
1034
+ $fBk = $fBkp;
1035
+ }
1036
+ }
1037
+ return (is_nan($fBk)) ? PHPExcel_Calculation_Functions::NaN() : $fBk;
1038
+ }
1039
+ return PHPExcel_Calculation_Functions::VALUE();
1040
+ }
1041
+
1042
+
1043
+ private static function besselY0($fNum)
1044
+ {
1045
+ if ($fNum < 8.0) {
1046
+ $y = ($fNum * $fNum);
1047
+ $f1 = -2957821389.0 + $y * (7062834065.0 + $y * (-512359803.6 + $y * (10879881.29 + $y * (-86327.92757 + $y * 228.4622733))));
1048
+ $f2 = 40076544269.0 + $y * (745249964.8 + $y * (7189466.438 + $y * (47447.26470 + $y * (226.1030244 + $y))));
1049
+ $fRet = $f1 / $f2 + 0.636619772 * self::BESSELJ($fNum, 0) * log($fNum);
1050
+ } else {
1051
+ $z = 8.0 / $fNum;
1052
+ $y = ($z * $z);
1053
+ $xx = $fNum - 0.785398164;
1054
+ $f1 = 1 + $y * (-0.1098628627e-2 + $y * (0.2734510407e-4 + $y * (-0.2073370639e-5 + $y * 0.2093887211e-6)));
1055
+ $f2 = -0.1562499995e-1 + $y * (0.1430488765e-3 + $y * (-0.6911147651e-5 + $y * (0.7621095161e-6 + $y * (-0.934945152e-7))));
1056
+ $fRet = sqrt(0.636619772 / $fNum) * (sin($xx) * $f1 + $z * cos($xx) * $f2);
1057
+ }
1058
+ return $fRet;
1059
+ }
1060
+
1061
+
1062
+ private static function besselY1($fNum)
1063
+ {
1064
+ if ($fNum < 8.0) {
1065
+ $y = ($fNum * $fNum);
1066
+ $f1 = $fNum * (-0.4900604943e13 + $y * (0.1275274390e13 + $y * (-0.5153438139e11 + $y * (0.7349264551e9 + $y *
1067
+ (-0.4237922726e7 + $y * 0.8511937935e4)))));
1068
+ $f2 = 0.2499580570e14 + $y * (0.4244419664e12 + $y * (0.3733650367e10 + $y * (0.2245904002e8 + $y *
1069
+ (0.1020426050e6 + $y * (0.3549632885e3 + $y)))));
1070
+ $fRet = $f1 / $f2 + 0.636619772 * ( self::BESSELJ($fNum, 1) * log($fNum) - 1 / $fNum);
1071
+ } else {
1072
+ $fRet = sqrt(0.636619772 / $fNum) * sin($fNum - 2.356194491);
1073
+ }
1074
+ return $fRet;
1075
+ }
1076
+
1077
+
1078
+ /**
1079
+ * BESSELY
1080
+ *
1081
+ * Returns the Bessel function, which is also called the Weber function or the Neumann function.
1082
+ *
1083
+ * Excel Function:
1084
+ * BESSELY(x,ord)
1085
+ *
1086
+ * @access public
1087
+ * @category Engineering Functions
1088
+ * @param float $x The value at which to evaluate the function.
1089
+ * If x is nonnumeric, BESSELK returns the #VALUE! error value.
1090
+ * @param integer $ord The order of the Bessel function. If n is not an integer, it is truncated.
1091
+ * If $ord is nonnumeric, BESSELK returns the #VALUE! error value.
1092
+ * If $ord < 0, BESSELK returns the #NUM! error value.
1093
+ *
1094
+ * @return float
1095
+ */
1096
+ public static function BESSELY($x, $ord)
1097
+ {
1098
+ $x = (is_null($x)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($x);
1099
+ $ord = (is_null($ord)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($ord);
1100
+
1101
+ if ((is_numeric($x)) && (is_numeric($ord))) {
1102
+ if (($ord < 0) || ($x == 0.0)) {
1103
+ return PHPExcel_Calculation_Functions::NaN();
1104
+ }
1105
+
1106
+ switch (floor($ord)) {
1107
+ case 0:
1108
+ return self::besselY0($x);
1109
+ case 1:
1110
+ return self::besselY1($x);
1111
+ default:
1112
+ $fTox = 2 / $x;
1113
+ $fBym = self::besselY0($x);
1114
+ $fBy = self::besselY1($x);
1115
+ for ($n = 1; $n < $ord; ++$n) {
1116
+ $fByp = $n * $fTox * $fBy - $fBym;
1117
+ $fBym = $fBy;
1118
+ $fBy = $fByp;
1119
+ }
1120
+ }
1121
+ return (is_nan($fBy)) ? PHPExcel_Calculation_Functions::NaN() : $fBy;
1122
+ }
1123
+ return PHPExcel_Calculation_Functions::VALUE();
1124
+ }
1125
+
1126
+
1127
+ /**
1128
+ * BINTODEC
1129
+ *
1130
+ * Return a binary value as decimal.
1131
+ *
1132
+ * Excel Function:
1133
+ * BIN2DEC(x)
1134
+ *
1135
+ * @access public
1136
+ * @category Engineering Functions
1137
+ * @param string $x The binary number (as a string) that you want to convert. The number
1138
+ * cannot contain more than 10 characters (10 bits). The most significant
1139
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
1140
+ * Negative numbers are represented using two's-complement notation.
1141
+ * If number is not a valid binary number, or if number contains more than
1142
+ * 10 characters (10 bits), BIN2DEC returns the #NUM! error value.
1143
+ * @return string
1144
+ */
1145
+ public static function BINTODEC($x)
1146
+ {
1147
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1148
+
1149
+ if (is_bool($x)) {
1150
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1151
+ $x = (int) $x;
1152
+ } else {
1153
+ return PHPExcel_Calculation_Functions::VALUE();
1154
+ }
1155
+ }
1156
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1157
+ $x = floor($x);
1158
+ }
1159
+ $x = (string) $x;
1160
+ if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
1161
+ return PHPExcel_Calculation_Functions::NaN();
1162
+ }
1163
+ if (strlen($x) > 10) {
1164
+ return PHPExcel_Calculation_Functions::NaN();
1165
+ } elseif (strlen($x) == 10) {
1166
+ // Two's Complement
1167
+ $x = substr($x, -9);
1168
+ return '-'.(512-bindec($x));
1169
+ }
1170
+ return bindec($x);
1171
+ }
1172
+
1173
+
1174
+ /**
1175
+ * BINTOHEX
1176
+ *
1177
+ * Return a binary value as hex.
1178
+ *
1179
+ * Excel Function:
1180
+ * BIN2HEX(x[,places])
1181
+ *
1182
+ * @access public
1183
+ * @category Engineering Functions
1184
+ * @param string $x The binary number (as a string) that you want to convert. The number
1185
+ * cannot contain more than 10 characters (10 bits). The most significant
1186
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
1187
+ * Negative numbers are represented using two's-complement notation.
1188
+ * If number is not a valid binary number, or if number contains more than
1189
+ * 10 characters (10 bits), BIN2HEX returns the #NUM! error value.
1190
+ * @param integer $places The number of characters to use. If places is omitted, BIN2HEX uses the
1191
+ * minimum number of characters necessary. Places is useful for padding the
1192
+ * return value with leading 0s (zeros).
1193
+ * If places is not an integer, it is truncated.
1194
+ * If places is nonnumeric, BIN2HEX returns the #VALUE! error value.
1195
+ * If places is negative, BIN2HEX returns the #NUM! error value.
1196
+ * @return string
1197
+ */
1198
+ public static function BINTOHEX($x, $places = null)
1199
+ {
1200
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1201
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1202
+
1203
+ if (is_bool($x)) {
1204
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1205
+ $x = (int) $x;
1206
+ } else {
1207
+ return PHPExcel_Calculation_Functions::VALUE();
1208
+ }
1209
+ }
1210
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1211
+ $x = floor($x);
1212
+ }
1213
+ $x = (string) $x;
1214
+ if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
1215
+ return PHPExcel_Calculation_Functions::NaN();
1216
+ }
1217
+ if (strlen($x) > 10) {
1218
+ return PHPExcel_Calculation_Functions::NaN();
1219
+ } elseif (strlen($x) == 10) {
1220
+ // Two's Complement
1221
+ return str_repeat('F', 8).substr(strtoupper(dechex(bindec(substr($x, -9)))), -2);
1222
+ }
1223
+ $hexVal = (string) strtoupper(dechex(bindec($x)));
1224
+
1225
+ return self::nbrConversionFormat($hexVal, $places);
1226
+ }
1227
+
1228
+
1229
+ /**
1230
+ * BINTOOCT
1231
+ *
1232
+ * Return a binary value as octal.
1233
+ *
1234
+ * Excel Function:
1235
+ * BIN2OCT(x[,places])
1236
+ *
1237
+ * @access public
1238
+ * @category Engineering Functions
1239
+ * @param string $x The binary number (as a string) that you want to convert. The number
1240
+ * cannot contain more than 10 characters (10 bits). The most significant
1241
+ * bit of number is the sign bit. The remaining 9 bits are magnitude bits.
1242
+ * Negative numbers are represented using two's-complement notation.
1243
+ * If number is not a valid binary number, or if number contains more than
1244
+ * 10 characters (10 bits), BIN2OCT returns the #NUM! error value.
1245
+ * @param integer $places The number of characters to use. If places is omitted, BIN2OCT uses the
1246
+ * minimum number of characters necessary. Places is useful for padding the
1247
+ * return value with leading 0s (zeros).
1248
+ * If places is not an integer, it is truncated.
1249
+ * If places is nonnumeric, BIN2OCT returns the #VALUE! error value.
1250
+ * If places is negative, BIN2OCT returns the #NUM! error value.
1251
+ * @return string
1252
+ */
1253
+ public static function BINTOOCT($x, $places = null)
1254
+ {
1255
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1256
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1257
+
1258
+ if (is_bool($x)) {
1259
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1260
+ $x = (int) $x;
1261
+ } else {
1262
+ return PHPExcel_Calculation_Functions::VALUE();
1263
+ }
1264
+ }
1265
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1266
+ $x = floor($x);
1267
+ }
1268
+ $x = (string) $x;
1269
+ if (strlen($x) > preg_match_all('/[01]/', $x, $out)) {
1270
+ return PHPExcel_Calculation_Functions::NaN();
1271
+ }
1272
+ if (strlen($x) > 10) {
1273
+ return PHPExcel_Calculation_Functions::NaN();
1274
+ } elseif (strlen($x) == 10) {
1275
+ // Two's Complement
1276
+ return str_repeat('7', 7).substr(strtoupper(decoct(bindec(substr($x, -9)))), -3);
1277
+ }
1278
+ $octVal = (string) decoct(bindec($x));
1279
+
1280
+ return self::nbrConversionFormat($octVal, $places);
1281
+ }
1282
+
1283
+
1284
+ /**
1285
+ * DECTOBIN
1286
+ *
1287
+ * Return a decimal value as binary.
1288
+ *
1289
+ * Excel Function:
1290
+ * DEC2BIN(x[,places])
1291
+ *
1292
+ * @access public
1293
+ * @category Engineering Functions
1294
+ * @param string $x The decimal integer you want to convert. If number is negative,
1295
+ * valid place values are ignored and DEC2BIN returns a 10-character
1296
+ * (10-bit) binary number in which the most significant bit is the sign
1297
+ * bit. The remaining 9 bits are magnitude bits. Negative numbers are
1298
+ * represented using two's-complement notation.
1299
+ * If number < -512 or if number > 511, DEC2BIN returns the #NUM! error
1300
+ * value.
1301
+ * If number is nonnumeric, DEC2BIN returns the #VALUE! error value.
1302
+ * If DEC2BIN requires more than places characters, it returns the #NUM!
1303
+ * error value.
1304
+ * @param integer $places The number of characters to use. If places is omitted, DEC2BIN uses
1305
+ * the minimum number of characters necessary. Places is useful for
1306
+ * padding the return value with leading 0s (zeros).
1307
+ * If places is not an integer, it is truncated.
1308
+ * If places is nonnumeric, DEC2BIN returns the #VALUE! error value.
1309
+ * If places is zero or negative, DEC2BIN returns the #NUM! error value.
1310
+ * @return string
1311
+ */
1312
+ public static function DECTOBIN($x, $places = null)
1313
+ {
1314
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1315
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1316
+
1317
+ if (is_bool($x)) {
1318
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1319
+ $x = (int) $x;
1320
+ } else {
1321
+ return PHPExcel_Calculation_Functions::VALUE();
1322
+ }
1323
+ }
1324
+ $x = (string) $x;
1325
+ if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
1326
+ return PHPExcel_Calculation_Functions::VALUE();
1327
+ }
1328
+ $x = (string) floor($x);
1329
+ $r = decbin($x);
1330
+ if (strlen($r) == 32) {
1331
+ // Two's Complement
1332
+ $r = substr($r, -10);
1333
+ } elseif (strlen($r) > 11) {
1334
+ return PHPExcel_Calculation_Functions::NaN();
1335
+ }
1336
+
1337
+ return self::nbrConversionFormat($r, $places);
1338
+ }
1339
+
1340
+
1341
+ /**
1342
+ * DECTOHEX
1343
+ *
1344
+ * Return a decimal value as hex.
1345
+ *
1346
+ * Excel Function:
1347
+ * DEC2HEX(x[,places])
1348
+ *
1349
+ * @access public
1350
+ * @category Engineering Functions
1351
+ * @param string $x The decimal integer you want to convert. If number is negative,
1352
+ * places is ignored and DEC2HEX returns a 10-character (40-bit)
1353
+ * hexadecimal number in which the most significant bit is the sign
1354
+ * bit. The remaining 39 bits are magnitude bits. Negative numbers
1355
+ * are represented using two's-complement notation.
1356
+ * If number < -549,755,813,888 or if number > 549,755,813,887,
1357
+ * DEC2HEX returns the #NUM! error value.
1358
+ * If number is nonnumeric, DEC2HEX returns the #VALUE! error value.
1359
+ * If DEC2HEX requires more than places characters, it returns the
1360
+ * #NUM! error value.
1361
+ * @param integer $places The number of characters to use. If places is omitted, DEC2HEX uses
1362
+ * the minimum number of characters necessary. Places is useful for
1363
+ * padding the return value with leading 0s (zeros).
1364
+ * If places is not an integer, it is truncated.
1365
+ * If places is nonnumeric, DEC2HEX returns the #VALUE! error value.
1366
+ * If places is zero or negative, DEC2HEX returns the #NUM! error value.
1367
+ * @return string
1368
+ */
1369
+ public static function DECTOHEX($x, $places = null)
1370
+ {
1371
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1372
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1373
+
1374
+ if (is_bool($x)) {
1375
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1376
+ $x = (int) $x;
1377
+ } else {
1378
+ return PHPExcel_Calculation_Functions::VALUE();
1379
+ }
1380
+ }
1381
+ $x = (string) $x;
1382
+ if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
1383
+ return PHPExcel_Calculation_Functions::VALUE();
1384
+ }
1385
+ $x = (string) floor($x);
1386
+ $r = strtoupper(dechex($x));
1387
+ if (strlen($r) == 8) {
1388
+ // Two's Complement
1389
+ $r = 'FF'.$r;
1390
+ }
1391
+
1392
+ return self::nbrConversionFormat($r, $places);
1393
+ }
1394
+
1395
+
1396
+ /**
1397
+ * DECTOOCT
1398
+ *
1399
+ * Return an decimal value as octal.
1400
+ *
1401
+ * Excel Function:
1402
+ * DEC2OCT(x[,places])
1403
+ *
1404
+ * @access public
1405
+ * @category Engineering Functions
1406
+ * @param string $x The decimal integer you want to convert. If number is negative,
1407
+ * places is ignored and DEC2OCT returns a 10-character (30-bit)
1408
+ * octal number in which the most significant bit is the sign bit.
1409
+ * The remaining 29 bits are magnitude bits. Negative numbers are
1410
+ * represented using two's-complement notation.
1411
+ * If number < -536,870,912 or if number > 536,870,911, DEC2OCT
1412
+ * returns the #NUM! error value.
1413
+ * If number is nonnumeric, DEC2OCT returns the #VALUE! error value.
1414
+ * If DEC2OCT requires more than places characters, it returns the
1415
+ * #NUM! error value.
1416
+ * @param integer $places The number of characters to use. If places is omitted, DEC2OCT uses
1417
+ * the minimum number of characters necessary. Places is useful for
1418
+ * padding the return value with leading 0s (zeros).
1419
+ * If places is not an integer, it is truncated.
1420
+ * If places is nonnumeric, DEC2OCT returns the #VALUE! error value.
1421
+ * If places is zero or negative, DEC2OCT returns the #NUM! error value.
1422
+ * @return string
1423
+ */
1424
+ public static function DECTOOCT($x, $places = null)
1425
+ {
1426
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1427
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1428
+
1429
+ if (is_bool($x)) {
1430
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
1431
+ $x = (int) $x;
1432
+ } else {
1433
+ return PHPExcel_Calculation_Functions::VALUE();
1434
+ }
1435
+ }
1436
+ $x = (string) $x;
1437
+ if (strlen($x) > preg_match_all('/[-0123456789.]/', $x, $out)) {
1438
+ return PHPExcel_Calculation_Functions::VALUE();
1439
+ }
1440
+ $x = (string) floor($x);
1441
+ $r = decoct($x);
1442
+ if (strlen($r) == 11) {
1443
+ // Two's Complement
1444
+ $r = substr($r, -10);
1445
+ }
1446
+
1447
+ return self::nbrConversionFormat($r, $places);
1448
+ }
1449
+
1450
+
1451
+ /**
1452
+ * HEXTOBIN
1453
+ *
1454
+ * Return a hex value as binary.
1455
+ *
1456
+ * Excel Function:
1457
+ * HEX2BIN(x[,places])
1458
+ *
1459
+ * @access public
1460
+ * @category Engineering Functions
1461
+ * @param string $x the hexadecimal number you want to convert. Number cannot
1462
+ * contain more than 10 characters. The most significant bit of
1463
+ * number is the sign bit (40th bit from the right). The remaining
1464
+ * 9 bits are magnitude bits. Negative numbers are represented
1465
+ * using two's-complement notation.
1466
+ * If number is negative, HEX2BIN ignores places and returns a
1467
+ * 10-character binary number.
1468
+ * If number is negative, it cannot be less than FFFFFFFE00, and
1469
+ * if number is positive, it cannot be greater than 1FF.
1470
+ * If number is not a valid hexadecimal number, HEX2BIN returns
1471
+ * the #NUM! error value.
1472
+ * If HEX2BIN requires more than places characters, it returns
1473
+ * the #NUM! error value.
1474
+ * @param integer $places The number of characters to use. If places is omitted,
1475
+ * HEX2BIN uses the minimum number of characters necessary. Places
1476
+ * is useful for padding the return value with leading 0s (zeros).
1477
+ * If places is not an integer, it is truncated.
1478
+ * If places is nonnumeric, HEX2BIN returns the #VALUE! error value.
1479
+ * If places is negative, HEX2BIN returns the #NUM! error value.
1480
+ * @return string
1481
+ */
1482
+ public static function HEXTOBIN($x, $places = null)
1483
+ {
1484
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1485
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1486
+
1487
+ if (is_bool($x)) {
1488
+ return PHPExcel_Calculation_Functions::VALUE();
1489
+ }
1490
+ $x = (string) $x;
1491
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
1492
+ return PHPExcel_Calculation_Functions::NaN();
1493
+ }
1494
+ $binVal = decbin(hexdec($x));
1495
+
1496
+ return substr(self::nbrConversionFormat($binVal, $places), -10);
1497
+ }
1498
+
1499
+
1500
+ /**
1501
+ * HEXTODEC
1502
+ *
1503
+ * Return a hex value as decimal.
1504
+ *
1505
+ * Excel Function:
1506
+ * HEX2DEC(x)
1507
+ *
1508
+ * @access public
1509
+ * @category Engineering Functions
1510
+ * @param string $x The hexadecimal number you want to convert. This number cannot
1511
+ * contain more than 10 characters (40 bits). The most significant
1512
+ * bit of number is the sign bit. The remaining 39 bits are magnitude
1513
+ * bits. Negative numbers are represented using two's-complement
1514
+ * notation.
1515
+ * If number is not a valid hexadecimal number, HEX2DEC returns the
1516
+ * #NUM! error value.
1517
+ * @return string
1518
+ */
1519
+ public static function HEXTODEC($x)
1520
+ {
1521
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1522
+
1523
+ if (is_bool($x)) {
1524
+ return PHPExcel_Calculation_Functions::VALUE();
1525
+ }
1526
+ $x = (string) $x;
1527
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
1528
+ return PHPExcel_Calculation_Functions::NaN();
1529
+ }
1530
+ return hexdec($x);
1531
+ }
1532
+
1533
+
1534
+ /**
1535
+ * HEXTOOCT
1536
+ *
1537
+ * Return a hex value as octal.
1538
+ *
1539
+ * Excel Function:
1540
+ * HEX2OCT(x[,places])
1541
+ *
1542
+ * @access public
1543
+ * @category Engineering Functions
1544
+ * @param string $x The hexadecimal number you want to convert. Number cannot
1545
+ * contain more than 10 characters. The most significant bit of
1546
+ * number is the sign bit. The remaining 39 bits are magnitude
1547
+ * bits. Negative numbers are represented using two's-complement
1548
+ * notation.
1549
+ * If number is negative, HEX2OCT ignores places and returns a
1550
+ * 10-character octal number.
1551
+ * If number is negative, it cannot be less than FFE0000000, and
1552
+ * if number is positive, it cannot be greater than 1FFFFFFF.
1553
+ * If number is not a valid hexadecimal number, HEX2OCT returns
1554
+ * the #NUM! error value.
1555
+ * If HEX2OCT requires more than places characters, it returns
1556
+ * the #NUM! error value.
1557
+ * @param integer $places The number of characters to use. If places is omitted, HEX2OCT
1558
+ * uses the minimum number of characters necessary. Places is
1559
+ * useful for padding the return value with leading 0s (zeros).
1560
+ * If places is not an integer, it is truncated.
1561
+ * If places is nonnumeric, HEX2OCT returns the #VALUE! error
1562
+ * value.
1563
+ * If places is negative, HEX2OCT returns the #NUM! error value.
1564
+ * @return string
1565
+ */
1566
+ public static function HEXTOOCT($x, $places = null)
1567
+ {
1568
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1569
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1570
+
1571
+ if (is_bool($x)) {
1572
+ return PHPExcel_Calculation_Functions::VALUE();
1573
+ }
1574
+ $x = (string) $x;
1575
+ if (strlen($x) > preg_match_all('/[0123456789ABCDEF]/', strtoupper($x), $out)) {
1576
+ return PHPExcel_Calculation_Functions::NaN();
1577
+ }
1578
+ $octVal = decoct(hexdec($x));
1579
+
1580
+ return self::nbrConversionFormat($octVal, $places);
1581
+ } // function HEXTOOCT()
1582
+
1583
+
1584
+ /**
1585
+ * OCTTOBIN
1586
+ *
1587
+ * Return an octal value as binary.
1588
+ *
1589
+ * Excel Function:
1590
+ * OCT2BIN(x[,places])
1591
+ *
1592
+ * @access public
1593
+ * @category Engineering Functions
1594
+ * @param string $x The octal number you want to convert. Number may not
1595
+ * contain more than 10 characters. The most significant
1596
+ * bit of number is the sign bit. The remaining 29 bits
1597
+ * are magnitude bits. Negative numbers are represented
1598
+ * using two's-complement notation.
1599
+ * If number is negative, OCT2BIN ignores places and returns
1600
+ * a 10-character binary number.
1601
+ * If number is negative, it cannot be less than 7777777000,
1602
+ * and if number is positive, it cannot be greater than 777.
1603
+ * If number is not a valid octal number, OCT2BIN returns
1604
+ * the #NUM! error value.
1605
+ * If OCT2BIN requires more than places characters, it
1606
+ * returns the #NUM! error value.
1607
+ * @param integer $places The number of characters to use. If places is omitted,
1608
+ * OCT2BIN uses the minimum number of characters necessary.
1609
+ * Places is useful for padding the return value with
1610
+ * leading 0s (zeros).
1611
+ * If places is not an integer, it is truncated.
1612
+ * If places is nonnumeric, OCT2BIN returns the #VALUE!
1613
+ * error value.
1614
+ * If places is negative, OCT2BIN returns the #NUM! error
1615
+ * value.
1616
+ * @return string
1617
+ */
1618
+ public static function OCTTOBIN($x, $places = null)
1619
+ {
1620
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1621
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1622
+
1623
+ if (is_bool($x)) {
1624
+ return PHPExcel_Calculation_Functions::VALUE();
1625
+ }
1626
+ $x = (string) $x;
1627
+ if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
1628
+ return PHPExcel_Calculation_Functions::NaN();
1629
+ }
1630
+ $r = decbin(octdec($x));
1631
+
1632
+ return self::nbrConversionFormat($r, $places);
1633
+ }
1634
+
1635
+
1636
+ /**
1637
+ * OCTTODEC
1638
+ *
1639
+ * Return an octal value as decimal.
1640
+ *
1641
+ * Excel Function:
1642
+ * OCT2DEC(x)
1643
+ *
1644
+ * @access public
1645
+ * @category Engineering Functions
1646
+ * @param string $x The octal number you want to convert. Number may not contain
1647
+ * more than 10 octal characters (30 bits). The most significant
1648
+ * bit of number is the sign bit. The remaining 29 bits are
1649
+ * magnitude bits. Negative numbers are represented using
1650
+ * two's-complement notation.
1651
+ * If number is not a valid octal number, OCT2DEC returns the
1652
+ * #NUM! error value.
1653
+ * @return string
1654
+ */
1655
+ public static function OCTTODEC($x)
1656
+ {
1657
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1658
+
1659
+ if (is_bool($x)) {
1660
+ return PHPExcel_Calculation_Functions::VALUE();
1661
+ }
1662
+ $x = (string) $x;
1663
+ if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
1664
+ return PHPExcel_Calculation_Functions::NaN();
1665
+ }
1666
+ return octdec($x);
1667
+ }
1668
+
1669
+
1670
+ /**
1671
+ * OCTTOHEX
1672
+ *
1673
+ * Return an octal value as hex.
1674
+ *
1675
+ * Excel Function:
1676
+ * OCT2HEX(x[,places])
1677
+ *
1678
+ * @access public
1679
+ * @category Engineering Functions
1680
+ * @param string $x The octal number you want to convert. Number may not contain
1681
+ * more than 10 octal characters (30 bits). The most significant
1682
+ * bit of number is the sign bit. The remaining 29 bits are
1683
+ * magnitude bits. Negative numbers are represented using
1684
+ * two's-complement notation.
1685
+ * If number is negative, OCT2HEX ignores places and returns a
1686
+ * 10-character hexadecimal number.
1687
+ * If number is not a valid octal number, OCT2HEX returns the
1688
+ * #NUM! error value.
1689
+ * If OCT2HEX requires more than places characters, it returns
1690
+ * the #NUM! error value.
1691
+ * @param integer $places The number of characters to use. If places is omitted, OCT2HEX
1692
+ * uses the minimum number of characters necessary. Places is useful
1693
+ * for padding the return value with leading 0s (zeros).
1694
+ * If places is not an integer, it is truncated.
1695
+ * If places is nonnumeric, OCT2HEX returns the #VALUE! error value.
1696
+ * If places is negative, OCT2HEX returns the #NUM! error value.
1697
+ * @return string
1698
+ */
1699
+ public static function OCTTOHEX($x, $places = null)
1700
+ {
1701
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
1702
+ $places = PHPExcel_Calculation_Functions::flattenSingleValue($places);
1703
+
1704
+ if (is_bool($x)) {
1705
+ return PHPExcel_Calculation_Functions::VALUE();
1706
+ }
1707
+ $x = (string) $x;
1708
+ if (preg_match_all('/[01234567]/', $x, $out) != strlen($x)) {
1709
+ return PHPExcel_Calculation_Functions::NaN();
1710
+ }
1711
+ $hexVal = strtoupper(dechex(octdec($x)));
1712
+
1713
+ return self::nbrConversionFormat($hexVal, $places);
1714
+ }
1715
+
1716
+
1717
+ /**
1718
+ * COMPLEX
1719
+ *
1720
+ * Converts real and imaginary coefficients into a complex number of the form x + yi or x + yj.
1721
+ *
1722
+ * Excel Function:
1723
+ * COMPLEX(realNumber,imaginary[,places])
1724
+ *
1725
+ * @access public
1726
+ * @category Engineering Functions
1727
+ * @param float $realNumber The real coefficient of the complex number.
1728
+ * @param float $imaginary The imaginary coefficient of the complex number.
1729
+ * @param string $suffix The suffix for the imaginary component of the complex number.
1730
+ * If omitted, the suffix is assumed to be "i".
1731
+ * @return string
1732
+ */
1733
+ public static function COMPLEX($realNumber = 0.0, $imaginary = 0.0, $suffix = 'i')
1734
+ {
1735
+ $realNumber = (is_null($realNumber)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($realNumber);
1736
+ $imaginary = (is_null($imaginary)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($imaginary);
1737
+ $suffix = (is_null($suffix)) ? 'i' : PHPExcel_Calculation_Functions::flattenSingleValue($suffix);
1738
+
1739
+ if (((is_numeric($realNumber)) && (is_numeric($imaginary))) &&
1740
+ (($suffix == 'i') || ($suffix == 'j') || ($suffix == ''))) {
1741
+ $realNumber = (float) $realNumber;
1742
+ $imaginary = (float) $imaginary;
1743
+
1744
+ if ($suffix == '') {
1745
+ $suffix = 'i';
1746
+ }
1747
+ if ($realNumber == 0.0) {
1748
+ if ($imaginary == 0.0) {
1749
+ return (string) '0';
1750
+ } elseif ($imaginary == 1.0) {
1751
+ return (string) $suffix;
1752
+ } elseif ($imaginary == -1.0) {
1753
+ return (string) '-'.$suffix;
1754
+ }
1755
+ return (string) $imaginary.$suffix;
1756
+ } elseif ($imaginary == 0.0) {
1757
+ return (string) $realNumber;
1758
+ } elseif ($imaginary == 1.0) {
1759
+ return (string) $realNumber.'+'.$suffix;
1760
+ } elseif ($imaginary == -1.0) {
1761
+ return (string) $realNumber.'-'.$suffix;
1762
+ }
1763
+ if ($imaginary > 0) {
1764
+ $imaginary = (string) '+'.$imaginary;
1765
+ }
1766
+ return (string) $realNumber.$imaginary.$suffix;
1767
+ }
1768
+
1769
+ return PHPExcel_Calculation_Functions::VALUE();
1770
+ }
1771
+
1772
+
1773
+ /**
1774
+ * IMAGINARY
1775
+ *
1776
+ * Returns the imaginary coefficient of a complex number in x + yi or x + yj text format.
1777
+ *
1778
+ * Excel Function:
1779
+ * IMAGINARY(complexNumber)
1780
+ *
1781
+ * @access public
1782
+ * @category Engineering Functions
1783
+ * @param string $complexNumber The complex number for which you want the imaginary
1784
+ * coefficient.
1785
+ * @return float
1786
+ */
1787
+ public static function IMAGINARY($complexNumber)
1788
+ {
1789
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1790
+
1791
+ $parsedComplex = self::parseComplex($complexNumber);
1792
+ return $parsedComplex['imaginary'];
1793
+ }
1794
+
1795
+
1796
+ /**
1797
+ * IMREAL
1798
+ *
1799
+ * Returns the real coefficient of a complex number in x + yi or x + yj text format.
1800
+ *
1801
+ * Excel Function:
1802
+ * IMREAL(complexNumber)
1803
+ *
1804
+ * @access public
1805
+ * @category Engineering Functions
1806
+ * @param string $complexNumber The complex number for which you want the real coefficient.
1807
+ * @return float
1808
+ */
1809
+ public static function IMREAL($complexNumber)
1810
+ {
1811
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1812
+
1813
+ $parsedComplex = self::parseComplex($complexNumber);
1814
+ return $parsedComplex['real'];
1815
+ }
1816
+
1817
+
1818
+ /**
1819
+ * IMABS
1820
+ *
1821
+ * Returns the absolute value (modulus) of a complex number in x + yi or x + yj text format.
1822
+ *
1823
+ * Excel Function:
1824
+ * IMABS(complexNumber)
1825
+ *
1826
+ * @param string $complexNumber The complex number for which you want the absolute value.
1827
+ * @return float
1828
+ */
1829
+ public static function IMABS($complexNumber)
1830
+ {
1831
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1832
+
1833
+ $parsedComplex = self::parseComplex($complexNumber);
1834
+
1835
+ return sqrt(
1836
+ ($parsedComplex['real'] * $parsedComplex['real']) +
1837
+ ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])
1838
+ );
1839
+ }
1840
+
1841
+
1842
+ /**
1843
+ * IMARGUMENT
1844
+ *
1845
+ * Returns the argument theta of a complex number, i.e. the angle in radians from the real
1846
+ * axis to the representation of the number in polar coordinates.
1847
+ *
1848
+ * Excel Function:
1849
+ * IMARGUMENT(complexNumber)
1850
+ *
1851
+ * @param string $complexNumber The complex number for which you want the argument theta.
1852
+ * @return float
1853
+ */
1854
+ public static function IMARGUMENT($complexNumber)
1855
+ {
1856
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1857
+
1858
+ $parsedComplex = self::parseComplex($complexNumber);
1859
+
1860
+ if ($parsedComplex['real'] == 0.0) {
1861
+ if ($parsedComplex['imaginary'] == 0.0) {
1862
+ return 0.0;
1863
+ } elseif ($parsedComplex['imaginary'] < 0.0) {
1864
+ return M_PI / -2;
1865
+ } else {
1866
+ return M_PI / 2;
1867
+ }
1868
+ } elseif ($parsedComplex['real'] > 0.0) {
1869
+ return atan($parsedComplex['imaginary'] / $parsedComplex['real']);
1870
+ } elseif ($parsedComplex['imaginary'] < 0.0) {
1871
+ return 0 - (M_PI - atan(abs($parsedComplex['imaginary']) / abs($parsedComplex['real'])));
1872
+ } else {
1873
+ return M_PI - atan($parsedComplex['imaginary'] / abs($parsedComplex['real']));
1874
+ }
1875
+ }
1876
+
1877
+
1878
+ /**
1879
+ * IMCONJUGATE
1880
+ *
1881
+ * Returns the complex conjugate of a complex number in x + yi or x + yj text format.
1882
+ *
1883
+ * Excel Function:
1884
+ * IMCONJUGATE(complexNumber)
1885
+ *
1886
+ * @param string $complexNumber The complex number for which you want the conjugate.
1887
+ * @return string
1888
+ */
1889
+ public static function IMCONJUGATE($complexNumber)
1890
+ {
1891
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1892
+
1893
+ $parsedComplex = self::parseComplex($complexNumber);
1894
+
1895
+ if ($parsedComplex['imaginary'] == 0.0) {
1896
+ return $parsedComplex['real'];
1897
+ } else {
1898
+ return self::cleanComplex(
1899
+ self::COMPLEX(
1900
+ $parsedComplex['real'],
1901
+ 0 - $parsedComplex['imaginary'],
1902
+ $parsedComplex['suffix']
1903
+ )
1904
+ );
1905
+ }
1906
+ }
1907
+
1908
+
1909
+ /**
1910
+ * IMCOS
1911
+ *
1912
+ * Returns the cosine of a complex number in x + yi or x + yj text format.
1913
+ *
1914
+ * Excel Function:
1915
+ * IMCOS(complexNumber)
1916
+ *
1917
+ * @param string $complexNumber The complex number for which you want the cosine.
1918
+ * @return string|float
1919
+ */
1920
+ public static function IMCOS($complexNumber)
1921
+ {
1922
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1923
+
1924
+ $parsedComplex = self::parseComplex($complexNumber);
1925
+
1926
+ if ($parsedComplex['imaginary'] == 0.0) {
1927
+ return cos($parsedComplex['real']);
1928
+ } else {
1929
+ return self::IMCONJUGATE(
1930
+ self::COMPLEX(
1931
+ cos($parsedComplex['real']) * cosh($parsedComplex['imaginary']),
1932
+ sin($parsedComplex['real']) * sinh($parsedComplex['imaginary']),
1933
+ $parsedComplex['suffix']
1934
+ )
1935
+ );
1936
+ }
1937
+ }
1938
+
1939
+
1940
+ /**
1941
+ * IMSIN
1942
+ *
1943
+ * Returns the sine of a complex number in x + yi or x + yj text format.
1944
+ *
1945
+ * Excel Function:
1946
+ * IMSIN(complexNumber)
1947
+ *
1948
+ * @param string $complexNumber The complex number for which you want the sine.
1949
+ * @return string|float
1950
+ */
1951
+ public static function IMSIN($complexNumber)
1952
+ {
1953
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1954
+
1955
+ $parsedComplex = self::parseComplex($complexNumber);
1956
+
1957
+ if ($parsedComplex['imaginary'] == 0.0) {
1958
+ return sin($parsedComplex['real']);
1959
+ } else {
1960
+ return self::COMPLEX(
1961
+ sin($parsedComplex['real']) * cosh($parsedComplex['imaginary']),
1962
+ cos($parsedComplex['real']) * sinh($parsedComplex['imaginary']),
1963
+ $parsedComplex['suffix']
1964
+ );
1965
+ }
1966
+ }
1967
+
1968
+
1969
+ /**
1970
+ * IMSQRT
1971
+ *
1972
+ * Returns the square root of a complex number in x + yi or x + yj text format.
1973
+ *
1974
+ * Excel Function:
1975
+ * IMSQRT(complexNumber)
1976
+ *
1977
+ * @param string $complexNumber The complex number for which you want the square root.
1978
+ * @return string
1979
+ */
1980
+ public static function IMSQRT($complexNumber)
1981
+ {
1982
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
1983
+
1984
+ $parsedComplex = self::parseComplex($complexNumber);
1985
+
1986
+ $theta = self::IMARGUMENT($complexNumber);
1987
+ $d1 = cos($theta / 2);
1988
+ $d2 = sin($theta / 2);
1989
+ $r = sqrt(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
1990
+
1991
+ if ($parsedComplex['suffix'] == '') {
1992
+ return self::COMPLEX($d1 * $r, $d2 * $r);
1993
+ } else {
1994
+ return self::COMPLEX($d1 * $r, $d2 * $r, $parsedComplex['suffix']);
1995
+ }
1996
+ }
1997
+
1998
+
1999
+ /**
2000
+ * IMLN
2001
+ *
2002
+ * Returns the natural logarithm of a complex number in x + yi or x + yj text format.
2003
+ *
2004
+ * Excel Function:
2005
+ * IMLN(complexNumber)
2006
+ *
2007
+ * @param string $complexNumber The complex number for which you want the natural logarithm.
2008
+ * @return string
2009
+ */
2010
+ public static function IMLN($complexNumber)
2011
+ {
2012
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
2013
+
2014
+ $parsedComplex = self::parseComplex($complexNumber);
2015
+
2016
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
2017
+ return PHPExcel_Calculation_Functions::NaN();
2018
+ }
2019
+
2020
+ $logR = log(sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary'])));
2021
+ $t = self::IMARGUMENT($complexNumber);
2022
+
2023
+ if ($parsedComplex['suffix'] == '') {
2024
+ return self::COMPLEX($logR, $t);
2025
+ } else {
2026
+ return self::COMPLEX($logR, $t, $parsedComplex['suffix']);
2027
+ }
2028
+ }
2029
+
2030
+
2031
+ /**
2032
+ * IMLOG10
2033
+ *
2034
+ * Returns the common logarithm (base 10) of a complex number in x + yi or x + yj text format.
2035
+ *
2036
+ * Excel Function:
2037
+ * IMLOG10(complexNumber)
2038
+ *
2039
+ * @param string $complexNumber The complex number for which you want the common logarithm.
2040
+ * @return string
2041
+ */
2042
+ public static function IMLOG10($complexNumber)
2043
+ {
2044
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
2045
+
2046
+ $parsedComplex = self::parseComplex($complexNumber);
2047
+
2048
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
2049
+ return PHPExcel_Calculation_Functions::NaN();
2050
+ } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
2051
+ return log10($parsedComplex['real']);
2052
+ }
2053
+
2054
+ return self::IMPRODUCT(log10(EULER), self::IMLN($complexNumber));
2055
+ }
2056
+
2057
+
2058
+ /**
2059
+ * IMLOG2
2060
+ *
2061
+ * Returns the base-2 logarithm of a complex number in x + yi or x + yj text format.
2062
+ *
2063
+ * Excel Function:
2064
+ * IMLOG2(complexNumber)
2065
+ *
2066
+ * @param string $complexNumber The complex number for which you want the base-2 logarithm.
2067
+ * @return string
2068
+ */
2069
+ public static function IMLOG2($complexNumber)
2070
+ {
2071
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
2072
+
2073
+ $parsedComplex = self::parseComplex($complexNumber);
2074
+
2075
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
2076
+ return PHPExcel_Calculation_Functions::NaN();
2077
+ } elseif (($parsedComplex['real'] > 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
2078
+ return log($parsedComplex['real'], 2);
2079
+ }
2080
+
2081
+ return self::IMPRODUCT(log(EULER, 2), self::IMLN($complexNumber));
2082
+ }
2083
+
2084
+
2085
+ /**
2086
+ * IMEXP
2087
+ *
2088
+ * Returns the exponential of a complex number in x + yi or x + yj text format.
2089
+ *
2090
+ * Excel Function:
2091
+ * IMEXP(complexNumber)
2092
+ *
2093
+ * @param string $complexNumber The complex number for which you want the exponential.
2094
+ * @return string
2095
+ */
2096
+ public static function IMEXP($complexNumber)
2097
+ {
2098
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
2099
+
2100
+ $parsedComplex = self::parseComplex($complexNumber);
2101
+
2102
+ if (($parsedComplex['real'] == 0.0) && ($parsedComplex['imaginary'] == 0.0)) {
2103
+ return '1';
2104
+ }
2105
+
2106
+ $e = exp($parsedComplex['real']);
2107
+ $eX = $e * cos($parsedComplex['imaginary']);
2108
+ $eY = $e * sin($parsedComplex['imaginary']);
2109
+
2110
+ if ($parsedComplex['suffix'] == '') {
2111
+ return self::COMPLEX($eX, $eY);
2112
+ } else {
2113
+ return self::COMPLEX($eX, $eY, $parsedComplex['suffix']);
2114
+ }
2115
+ }
2116
+
2117
+
2118
+ /**
2119
+ * IMPOWER
2120
+ *
2121
+ * Returns a complex number in x + yi or x + yj text format raised to a power.
2122
+ *
2123
+ * Excel Function:
2124
+ * IMPOWER(complexNumber,realNumber)
2125
+ *
2126
+ * @param string $complexNumber The complex number you want to raise to a power.
2127
+ * @param float $realNumber The power to which you want to raise the complex number.
2128
+ * @return string
2129
+ */
2130
+ public static function IMPOWER($complexNumber, $realNumber)
2131
+ {
2132
+ $complexNumber = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber);
2133
+ $realNumber = PHPExcel_Calculation_Functions::flattenSingleValue($realNumber);
2134
+
2135
+ if (!is_numeric($realNumber)) {
2136
+ return PHPExcel_Calculation_Functions::VALUE();
2137
+ }
2138
+
2139
+ $parsedComplex = self::parseComplex($complexNumber);
2140
+
2141
+ $r = sqrt(($parsedComplex['real'] * $parsedComplex['real']) + ($parsedComplex['imaginary'] * $parsedComplex['imaginary']));
2142
+ $rPower = pow($r, $realNumber);
2143
+ $theta = self::IMARGUMENT($complexNumber) * $realNumber;
2144
+ if ($theta == 0) {
2145
+ return 1;
2146
+ } elseif ($parsedComplex['imaginary'] == 0.0) {
2147
+ return self::COMPLEX($rPower * cos($theta), $rPower * sin($theta), $parsedComplex['suffix']);
2148
+ } else {
2149
+ return self::COMPLEX($rPower * cos($theta), $rPower * sin($theta), $parsedComplex['suffix']);
2150
+ }
2151
+ }
2152
+
2153
+
2154
+ /**
2155
+ * IMDIV
2156
+ *
2157
+ * Returns the quotient of two complex numbers in x + yi or x + yj text format.
2158
+ *
2159
+ * Excel Function:
2160
+ * IMDIV(complexDividend,complexDivisor)
2161
+ *
2162
+ * @param string $complexDividend The complex numerator or dividend.
2163
+ * @param string $complexDivisor The complex denominator or divisor.
2164
+ * @return string
2165
+ */
2166
+ public static function IMDIV($complexDividend, $complexDivisor)
2167
+ {
2168
+ $complexDividend = PHPExcel_Calculation_Functions::flattenSingleValue($complexDividend);
2169
+ $complexDivisor = PHPExcel_Calculation_Functions::flattenSingleValue($complexDivisor);
2170
+
2171
+ $parsedComplexDividend = self::parseComplex($complexDividend);
2172
+ $parsedComplexDivisor = self::parseComplex($complexDivisor);
2173
+
2174
+ if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] != '') &&
2175
+ ($parsedComplexDividend['suffix'] != $parsedComplexDivisor['suffix'])) {
2176
+ return PHPExcel_Calculation_Functions::NaN();
2177
+ }
2178
+ if (($parsedComplexDividend['suffix'] != '') && ($parsedComplexDivisor['suffix'] == '')) {
2179
+ $parsedComplexDivisor['suffix'] = $parsedComplexDividend['suffix'];
2180
+ }
2181
+
2182
+ $d1 = ($parsedComplexDividend['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['imaginary']);
2183
+ $d2 = ($parsedComplexDividend['imaginary'] * $parsedComplexDivisor['real']) - ($parsedComplexDividend['real'] * $parsedComplexDivisor['imaginary']);
2184
+ $d3 = ($parsedComplexDivisor['real'] * $parsedComplexDivisor['real']) + ($parsedComplexDivisor['imaginary'] * $parsedComplexDivisor['imaginary']);
2185
+
2186
+ $r = $d1 / $d3;
2187
+ $i = $d2 / $d3;
2188
+
2189
+ if ($i > 0.0) {
2190
+ return self::cleanComplex($r.'+'.$i.$parsedComplexDivisor['suffix']);
2191
+ } elseif ($i < 0.0) {
2192
+ return self::cleanComplex($r.$i.$parsedComplexDivisor['suffix']);
2193
+ } else {
2194
+ return $r;
2195
+ }
2196
+ }
2197
+
2198
+
2199
+ /**
2200
+ * IMSUB
2201
+ *
2202
+ * Returns the difference of two complex numbers in x + yi or x + yj text format.
2203
+ *
2204
+ * Excel Function:
2205
+ * IMSUB(complexNumber1,complexNumber2)
2206
+ *
2207
+ * @param string $complexNumber1 The complex number from which to subtract complexNumber2.
2208
+ * @param string $complexNumber2 The complex number to subtract from complexNumber1.
2209
+ * @return string
2210
+ */
2211
+ public static function IMSUB($complexNumber1, $complexNumber2)
2212
+ {
2213
+ $complexNumber1 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber1);
2214
+ $complexNumber2 = PHPExcel_Calculation_Functions::flattenSingleValue($complexNumber2);
2215
+
2216
+ $parsedComplex1 = self::parseComplex($complexNumber1);
2217
+ $parsedComplex2 = self::parseComplex($complexNumber2);
2218
+
2219
+ if ((($parsedComplex1['suffix'] != '') && ($parsedComplex2['suffix'] != '')) &&
2220
+ ($parsedComplex1['suffix'] != $parsedComplex2['suffix'])) {
2221
+ return PHPExcel_Calculation_Functions::NaN();
2222
+ } elseif (($parsedComplex1['suffix'] == '') && ($parsedComplex2['suffix'] != '')) {
2223
+ $parsedComplex1['suffix'] = $parsedComplex2['suffix'];
2224
+ }
2225
+
2226
+ $d1 = $parsedComplex1['real'] - $parsedComplex2['real'];
2227
+ $d2 = $parsedComplex1['imaginary'] - $parsedComplex2['imaginary'];
2228
+
2229
+ return self::COMPLEX($d1, $d2, $parsedComplex1['suffix']);
2230
+ }
2231
+
2232
+
2233
+ /**
2234
+ * IMSUM
2235
+ *
2236
+ * Returns the sum of two or more complex numbers in x + yi or x + yj text format.
2237
+ *
2238
+ * Excel Function:
2239
+ * IMSUM(complexNumber[,complexNumber[,...]])
2240
+ *
2241
+ * @param string $complexNumber,... Series of complex numbers to add
2242
+ * @return string
2243
+ */
2244
+ public static function IMSUM()
2245
+ {
2246
+ // Return value
2247
+ $returnValue = self::parseComplex('0');
2248
+ $activeSuffix = '';
2249
+
2250
+ // Loop through the arguments
2251
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2252
+ foreach ($aArgs as $arg) {
2253
+ $parsedComplex = self::parseComplex($arg);
2254
+
2255
+ if ($activeSuffix == '') {
2256
+ $activeSuffix = $parsedComplex['suffix'];
2257
+ } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
2258
+ return PHPExcel_Calculation_Functions::VALUE();
2259
+ }
2260
+
2261
+ $returnValue['real'] += $parsedComplex['real'];
2262
+ $returnValue['imaginary'] += $parsedComplex['imaginary'];
2263
+ }
2264
+
2265
+ if ($returnValue['imaginary'] == 0.0) {
2266
+ $activeSuffix = '';
2267
+ }
2268
+ return self::COMPLEX($returnValue['real'], $returnValue['imaginary'], $activeSuffix);
2269
+ }
2270
+
2271
+
2272
+ /**
2273
+ * IMPRODUCT
2274
+ *
2275
+ * Returns the product of two or more complex numbers in x + yi or x + yj text format.
2276
+ *
2277
+ * Excel Function:
2278
+ * IMPRODUCT(complexNumber[,complexNumber[,...]])
2279
+ *
2280
+ * @param string $complexNumber,... Series of complex numbers to multiply
2281
+ * @return string
2282
+ */
2283
+ public static function IMPRODUCT()
2284
+ {
2285
+ // Return value
2286
+ $returnValue = self::parseComplex('1');
2287
+ $activeSuffix = '';
2288
+
2289
+ // Loop through the arguments
2290
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2291
+ foreach ($aArgs as $arg) {
2292
+ $parsedComplex = self::parseComplex($arg);
2293
+
2294
+ $workValue = $returnValue;
2295
+ if (($parsedComplex['suffix'] != '') && ($activeSuffix == '')) {
2296
+ $activeSuffix = $parsedComplex['suffix'];
2297
+ } elseif (($parsedComplex['suffix'] != '') && ($activeSuffix != $parsedComplex['suffix'])) {
2298
+ return PHPExcel_Calculation_Functions::NaN();
2299
+ }
2300
+ $returnValue['real'] = ($workValue['real'] * $parsedComplex['real']) - ($workValue['imaginary'] * $parsedComplex['imaginary']);
2301
+ $returnValue['imaginary'] = ($workValue['real'] * $parsedComplex['imaginary']) + ($workValue['imaginary'] * $parsedComplex['real']);
2302
+ }
2303
+
2304
+ if ($returnValue['imaginary'] == 0.0) {
2305
+ $activeSuffix = '';
2306
+ }
2307
+ return self::COMPLEX($returnValue['real'], $returnValue['imaginary'], $activeSuffix);
2308
+ }
2309
+
2310
+
2311
+ /**
2312
+ * DELTA
2313
+ *
2314
+ * Tests whether two values are equal. Returns 1 if number1 = number2; returns 0 otherwise.
2315
+ * Use this function to filter a set of values. For example, by summing several DELTA
2316
+ * functions you calculate the count of equal pairs. This function is also known as the
2317
+ * Kronecker Delta function.
2318
+ *
2319
+ * Excel Function:
2320
+ * DELTA(a[,b])
2321
+ *
2322
+ * @param float $a The first number.
2323
+ * @param float $b The second number. If omitted, b is assumed to be zero.
2324
+ * @return int
2325
+ */
2326
+ public static function DELTA($a, $b = 0)
2327
+ {
2328
+ $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
2329
+ $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
2330
+
2331
+ return (int) ($a == $b);
2332
+ }
2333
+
2334
+
2335
+ /**
2336
+ * GESTEP
2337
+ *
2338
+ * Excel Function:
2339
+ * GESTEP(number[,step])
2340
+ *
2341
+ * Returns 1 if number >= step; returns 0 (zero) otherwise
2342
+ * Use this function to filter a set of values. For example, by summing several GESTEP
2343
+ * functions you calculate the count of values that exceed a threshold.
2344
+ *
2345
+ * @param float $number The value to test against step.
2346
+ * @param float $step The threshold value.
2347
+ * If you omit a value for step, GESTEP uses zero.
2348
+ * @return int
2349
+ */
2350
+ public static function GESTEP($number, $step = 0)
2351
+ {
2352
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
2353
+ $step = PHPExcel_Calculation_Functions::flattenSingleValue($step);
2354
+
2355
+ return (int) ($number >= $step);
2356
+ }
2357
+
2358
+
2359
+ //
2360
+ // Private method to calculate the erf value
2361
+ //
2362
+ private static $twoSqrtPi = 1.128379167095512574;
2363
+
2364
+ public static function erfVal($x)
2365
+ {
2366
+ if (abs($x) > 2.2) {
2367
+ return 1 - self::erfcVal($x);
2368
+ }
2369
+ $sum = $term = $x;
2370
+ $xsqr = ($x * $x);
2371
+ $j = 1;
2372
+ do {
2373
+ $term *= $xsqr / $j;
2374
+ $sum -= $term / (2 * $j + 1);
2375
+ ++$j;
2376
+ $term *= $xsqr / $j;
2377
+ $sum += $term / (2 * $j + 1);
2378
+ ++$j;
2379
+ if ($sum == 0.0) {
2380
+ break;
2381
+ }
2382
+ } while (abs($term / $sum) > PRECISION);
2383
+ return self::$twoSqrtPi * $sum;
2384
+ }
2385
+
2386
+
2387
+ /**
2388
+ * ERF
2389
+ *
2390
+ * Returns the error function integrated between the lower and upper bound arguments.
2391
+ *
2392
+ * Note: In Excel 2007 or earlier, if you input a negative value for the upper or lower bound arguments,
2393
+ * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
2394
+ * improved, so that it can now calculate the function for both positive and negative ranges.
2395
+ * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
2396
+ *
2397
+ * Excel Function:
2398
+ * ERF(lower[,upper])
2399
+ *
2400
+ * @param float $lower lower bound for integrating ERF
2401
+ * @param float $upper upper bound for integrating ERF.
2402
+ * If omitted, ERF integrates between zero and lower_limit
2403
+ * @return float
2404
+ */
2405
+ public static function ERF($lower, $upper = null)
2406
+ {
2407
+ $lower = PHPExcel_Calculation_Functions::flattenSingleValue($lower);
2408
+ $upper = PHPExcel_Calculation_Functions::flattenSingleValue($upper);
2409
+
2410
+ if (is_numeric($lower)) {
2411
+ if (is_null($upper)) {
2412
+ return self::erfVal($lower);
2413
+ }
2414
+ if (is_numeric($upper)) {
2415
+ return self::erfVal($upper) - self::erfVal($lower);
2416
+ }
2417
+ }
2418
+ return PHPExcel_Calculation_Functions::VALUE();
2419
+ }
2420
+
2421
+
2422
+ //
2423
+ // Private method to calculate the erfc value
2424
+ //
2425
+ private static $oneSqrtPi = 0.564189583547756287;
2426
+
2427
+ private static function erfcVal($x)
2428
+ {
2429
+ if (abs($x) < 2.2) {
2430
+ return 1 - self::erfVal($x);
2431
+ }
2432
+ if ($x < 0) {
2433
+ return 2 - self::ERFC(-$x);
2434
+ }
2435
+ $a = $n = 1;
2436
+ $b = $c = $x;
2437
+ $d = ($x * $x) + 0.5;
2438
+ $q1 = $q2 = $b / $d;
2439
+ $t = 0;
2440
+ do {
2441
+ $t = $a * $n + $b * $x;
2442
+ $a = $b;
2443
+ $b = $t;
2444
+ $t = $c * $n + $d * $x;
2445
+ $c = $d;
2446
+ $d = $t;
2447
+ $n += 0.5;
2448
+ $q1 = $q2;
2449
+ $q2 = $b / $d;
2450
+ } while ((abs($q1 - $q2) / $q2) > PRECISION);
2451
+ return self::$oneSqrtPi * exp(-$x * $x) * $q2;
2452
+ }
2453
+
2454
+
2455
+ /**
2456
+ * ERFC
2457
+ *
2458
+ * Returns the complementary ERF function integrated between x and infinity
2459
+ *
2460
+ * Note: In Excel 2007 or earlier, if you input a negative value for the lower bound argument,
2461
+ * the function would return a #NUM! error. However, in Excel 2010, the function algorithm was
2462
+ * improved, so that it can now calculate the function for both positive and negative x values.
2463
+ * PHPExcel follows Excel 2010 behaviour, and accepts nagative arguments.
2464
+ *
2465
+ * Excel Function:
2466
+ * ERFC(x)
2467
+ *
2468
+ * @param float $x The lower bound for integrating ERFC
2469
+ * @return float
2470
+ */
2471
+ public static function ERFC($x)
2472
+ {
2473
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
2474
+
2475
+ if (is_numeric($x)) {
2476
+ return self::erfcVal($x);
2477
+ }
2478
+ return PHPExcel_Calculation_Functions::VALUE();
2479
+ }
2480
+
2481
+
2482
+ /**
2483
+ * getConversionGroups
2484
+ * Returns a list of the different conversion groups for UOM conversions
2485
+ *
2486
+ * @return array
2487
+ */
2488
+ public static function getConversionGroups()
2489
+ {
2490
+ $conversionGroups = array();
2491
+ foreach (self::$conversionUnits as $conversionUnit) {
2492
+ $conversionGroups[] = $conversionUnit['Group'];
2493
+ }
2494
+ return array_merge(array_unique($conversionGroups));
2495
+ }
2496
+
2497
+
2498
+ /**
2499
+ * getConversionGroupUnits
2500
+ * Returns an array of units of measure, for a specified conversion group, or for all groups
2501
+ *
2502
+ * @param string $group The group whose units of measure you want to retrieve
2503
+ * @return array
2504
+ */
2505
+ public static function getConversionGroupUnits($group = null)
2506
+ {
2507
+ $conversionGroups = array();
2508
+ foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) {
2509
+ if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
2510
+ $conversionGroups[$conversionGroup['Group']][] = $conversionUnit;
2511
+ }
2512
+ }
2513
+ return $conversionGroups;
2514
+ }
2515
+
2516
+
2517
+ /**
2518
+ * getConversionGroupUnitDetails
2519
+ *
2520
+ * @param string $group The group whose units of measure you want to retrieve
2521
+ * @return array
2522
+ */
2523
+ public static function getConversionGroupUnitDetails($group = null)
2524
+ {
2525
+ $conversionGroups = array();
2526
+ foreach (self::$conversionUnits as $conversionUnit => $conversionGroup) {
2527
+ if ((is_null($group)) || ($conversionGroup['Group'] == $group)) {
2528
+ $conversionGroups[$conversionGroup['Group']][] = array(
2529
+ 'unit' => $conversionUnit,
2530
+ 'description' => $conversionGroup['Unit Name']
2531
+ );
2532
+ }
2533
+ }
2534
+ return $conversionGroups;
2535
+ }
2536
+
2537
+
2538
+ /**
2539
+ * getConversionMultipliers
2540
+ * Returns an array of the Multiplier prefixes that can be used with Units of Measure in CONVERTUOM()
2541
+ *
2542
+ * @return array of mixed
2543
+ */
2544
+ public static function getConversionMultipliers()
2545
+ {
2546
+ return self::$conversionMultipliers;
2547
+ }
2548
+
2549
+
2550
+ /**
2551
+ * CONVERTUOM
2552
+ *
2553
+ * Converts a number from one measurement system to another.
2554
+ * For example, CONVERT can translate a table of distances in miles to a table of distances
2555
+ * in kilometers.
2556
+ *
2557
+ * Excel Function:
2558
+ * CONVERT(value,fromUOM,toUOM)
2559
+ *
2560
+ * @param float $value The value in fromUOM to convert.
2561
+ * @param string $fromUOM The units for value.
2562
+ * @param string $toUOM The units for the result.
2563
+ *
2564
+ * @return float
2565
+ */
2566
+ public static function CONVERTUOM($value, $fromUOM, $toUOM)
2567
+ {
2568
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2569
+ $fromUOM = PHPExcel_Calculation_Functions::flattenSingleValue($fromUOM);
2570
+ $toUOM = PHPExcel_Calculation_Functions::flattenSingleValue($toUOM);
2571
+
2572
+ if (!is_numeric($value)) {
2573
+ return PHPExcel_Calculation_Functions::VALUE();
2574
+ }
2575
+ $fromMultiplier = 1.0;
2576
+ if (isset(self::$conversionUnits[$fromUOM])) {
2577
+ $unitGroup1 = self::$conversionUnits[$fromUOM]['Group'];
2578
+ } else {
2579
+ $fromMultiplier = substr($fromUOM, 0, 1);
2580
+ $fromUOM = substr($fromUOM, 1);
2581
+ if (isset(self::$conversionMultipliers[$fromMultiplier])) {
2582
+ $fromMultiplier = self::$conversionMultipliers[$fromMultiplier]['multiplier'];
2583
+ } else {
2584
+ return PHPExcel_Calculation_Functions::NA();
2585
+ }
2586
+ if ((isset(self::$conversionUnits[$fromUOM])) && (self::$conversionUnits[$fromUOM]['AllowPrefix'])) {
2587
+ $unitGroup1 = self::$conversionUnits[$fromUOM]['Group'];
2588
+ } else {
2589
+ return PHPExcel_Calculation_Functions::NA();
2590
+ }
2591
+ }
2592
+ $value *= $fromMultiplier;
2593
+
2594
+ $toMultiplier = 1.0;
2595
+ if (isset(self::$conversionUnits[$toUOM])) {
2596
+ $unitGroup2 = self::$conversionUnits[$toUOM]['Group'];
2597
+ } else {
2598
+ $toMultiplier = substr($toUOM, 0, 1);
2599
+ $toUOM = substr($toUOM, 1);
2600
+ if (isset(self::$conversionMultipliers[$toMultiplier])) {
2601
+ $toMultiplier = self::$conversionMultipliers[$toMultiplier]['multiplier'];
2602
+ } else {
2603
+ return PHPExcel_Calculation_Functions::NA();
2604
+ }
2605
+ if ((isset(self::$conversionUnits[$toUOM])) && (self::$conversionUnits[$toUOM]['AllowPrefix'])) {
2606
+ $unitGroup2 = self::$conversionUnits[$toUOM]['Group'];
2607
+ } else {
2608
+ return PHPExcel_Calculation_Functions::NA();
2609
+ }
2610
+ }
2611
+ if ($unitGroup1 != $unitGroup2) {
2612
+ return PHPExcel_Calculation_Functions::NA();
2613
+ }
2614
+
2615
+ if (($fromUOM == $toUOM) && ($fromMultiplier == $toMultiplier)) {
2616
+ // We've already factored $fromMultiplier into the value, so we need
2617
+ // to reverse it again
2618
+ return $value / $fromMultiplier;
2619
+ } elseif ($unitGroup1 == 'Temperature') {
2620
+ if (($fromUOM == 'F') || ($fromUOM == 'fah')) {
2621
+ if (($toUOM == 'F') || ($toUOM == 'fah')) {
2622
+ return $value;
2623
+ } else {
2624
+ $value = (($value - 32) / 1.8);
2625
+ if (($toUOM == 'K') || ($toUOM == 'kel')) {
2626
+ $value += 273.15;
2627
+ }
2628
+ return $value;
2629
+ }
2630
+ } elseif ((($fromUOM == 'K') || ($fromUOM == 'kel')) &&
2631
+ (($toUOM == 'K') || ($toUOM == 'kel'))) {
2632
+ return $value;
2633
+ } elseif ((($fromUOM == 'C') || ($fromUOM == 'cel')) &&
2634
+ (($toUOM == 'C') || ($toUOM == 'cel'))) {
2635
+ return $value;
2636
+ }
2637
+ if (($toUOM == 'F') || ($toUOM == 'fah')) {
2638
+ if (($fromUOM == 'K') || ($fromUOM == 'kel')) {
2639
+ $value -= 273.15;
2640
+ }
2641
+ return ($value * 1.8) + 32;
2642
+ }
2643
+ if (($toUOM == 'C') || ($toUOM == 'cel')) {
2644
+ return $value - 273.15;
2645
+ }
2646
+ return $value + 273.15;
2647
+ }
2648
+ return ($value * self::$unitConversions[$unitGroup1][$fromUOM][$toUOM]) / $toMultiplier;
2649
+ }
2650
+ }
classes/PHPExcel/Calculation/Exception.php ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_Calculation_Exception
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_Calculation
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_Calculation_Exception extends PHPExcel_Exception
29
+ {
30
+ /**
31
+ * Error handler callback
32
+ *
33
+ * @param mixed $code
34
+ * @param mixed $string
35
+ * @param mixed $file
36
+ * @param mixed $line
37
+ * @param mixed $context
38
+ */
39
+ public static function errorHandlerCallback($code, $string, $file, $line, $context)
40
+ {
41
+ $e = new self($string, $code);
42
+ $e->line = $line;
43
+ $e->file = $file;
44
+ throw $e;
45
+ }
46
+ }
classes/PHPExcel/Calculation/ExceptionHandler.php ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_Calculation_ExceptionHandler
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_Calculation
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_Calculation_ExceptionHandler
29
+ {
30
+ /**
31
+ * Register errorhandler
32
+ */
33
+ public function __construct()
34
+ {
35
+ set_error_handler(array('PHPExcel_Calculation_Exception', 'errorHandlerCallback'), E_ALL);
36
+ }
37
+
38
+ /**
39
+ * Unregister errorhandler
40
+ */
41
+ public function __destruct()
42
+ {
43
+ restore_error_handler();
44
+ }
45
+ }
classes/PHPExcel/Calculation/Financial.php ADDED
@@ -0,0 +1,2359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+ /** FINANCIAL_MAX_ITERATIONS */
13
+ define('FINANCIAL_MAX_ITERATIONS', 128);
14
+
15
+ /** FINANCIAL_PRECISION */
16
+ define('FINANCIAL_PRECISION', 1.0e-08);
17
+
18
+ /**
19
+ * PHPExcel_Calculation_Financial
20
+ *
21
+ * Copyright (c) 2006 - 2015 PHPExcel
22
+ *
23
+ * This library is free software; you can redistribute it and/or
24
+ * modify it under the terms of the GNU Lesser General Public
25
+ * License as published by the Free Software Foundation; either
26
+ * version 2.1 of the License, or (at your option) any later version.
27
+ *
28
+ * This library is distributed in the hope that it will be useful,
29
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
30
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
31
+ * Lesser General Public License for more details.
32
+ *
33
+ * You should have received a copy of the GNU Lesser General Public
34
+ * License along with this library; if not, write to the Free Software
35
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
36
+ *
37
+ * @category PHPExcel
38
+ * @package PHPExcel_Calculation
39
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
40
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
41
+ * @version ##VERSION##, ##DATE##
42
+ */
43
+ class PHPExcel_Calculation_Financial
44
+ {
45
+ /**
46
+ * isLastDayOfMonth
47
+ *
48
+ * Returns a boolean TRUE/FALSE indicating if this date is the last date of the month
49
+ *
50
+ * @param DateTime $testDate The date for testing
51
+ * @return boolean
52
+ */
53
+ private static function isLastDayOfMonth($testDate)
54
+ {
55
+ return ($testDate->format('d') == $testDate->format('t'));
56
+ }
57
+
58
+
59
+ /**
60
+ * isFirstDayOfMonth
61
+ *
62
+ * Returns a boolean TRUE/FALSE indicating if this date is the first date of the month
63
+ *
64
+ * @param DateTime $testDate The date for testing
65
+ * @return boolean
66
+ */
67
+ private static function isFirstDayOfMonth($testDate)
68
+ {
69
+ return ($testDate->format('d') == 1);
70
+ }
71
+
72
+
73
+ private static function couponFirstPeriodDate($settlement, $maturity, $frequency, $next)
74
+ {
75
+ $months = 12 / $frequency;
76
+
77
+ $result = PHPExcel_Shared_Date::ExcelToPHPObject($maturity);
78
+ $eom = self::isLastDayOfMonth($result);
79
+
80
+ while ($settlement < PHPExcel_Shared_Date::PHPToExcel($result)) {
81
+ $result->modify('-'.$months.' months');
82
+ }
83
+ if ($next) {
84
+ $result->modify('+'.$months.' months');
85
+ }
86
+
87
+ if ($eom) {
88
+ $result->modify('-1 day');
89
+ }
90
+
91
+ return PHPExcel_Shared_Date::PHPToExcel($result);
92
+ }
93
+
94
+
95
+ private static function isValidFrequency($frequency)
96
+ {
97
+ if (($frequency == 1) || ($frequency == 2) || ($frequency == 4)) {
98
+ return true;
99
+ }
100
+ if ((PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) &&
101
+ (($frequency == 6) || ($frequency == 12))) {
102
+ return true;
103
+ }
104
+ return false;
105
+ }
106
+
107
+
108
+ /**
109
+ * daysPerYear
110
+ *
111
+ * Returns the number of days in a specified year, as defined by the "basis" value
112
+ *
113
+ * @param integer $year The year against which we're testing
114
+ * @param integer $basis The type of day count:
115
+ * 0 or omitted US (NASD) 360
116
+ * 1 Actual (365 or 366 in a leap year)
117
+ * 2 360
118
+ * 3 365
119
+ * 4 European 360
120
+ * @return integer
121
+ */
122
+ private static function daysPerYear($year, $basis = 0)
123
+ {
124
+ switch ($basis) {
125
+ case 0:
126
+ case 2:
127
+ case 4:
128
+ $daysPerYear = 360;
129
+ break;
130
+ case 3:
131
+ $daysPerYear = 365;
132
+ break;
133
+ case 1:
134
+ $daysPerYear = (PHPExcel_Calculation_DateTime::isLeapYear($year)) ? 366 : 365;
135
+ break;
136
+ default:
137
+ return PHPExcel_Calculation_Functions::NaN();
138
+ }
139
+ return $daysPerYear;
140
+ }
141
+
142
+
143
+ private static function interestAndPrincipal($rate = 0, $per = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0)
144
+ {
145
+ $pmt = self::PMT($rate, $nper, $pv, $fv, $type);
146
+ $capital = $pv;
147
+ for ($i = 1; $i<= $per; ++$i) {
148
+ $interest = ($type && $i == 1) ? 0 : -$capital * $rate;
149
+ $principal = $pmt - $interest;
150
+ $capital += $principal;
151
+ }
152
+ return array($interest, $principal);
153
+ }
154
+
155
+
156
+ /**
157
+ * ACCRINT
158
+ *
159
+ * Returns the accrued interest for a security that pays periodic interest.
160
+ *
161
+ * Excel Function:
162
+ * ACCRINT(issue,firstinterest,settlement,rate,par,frequency[,basis])
163
+ *
164
+ * @access public
165
+ * @category Financial Functions
166
+ * @param mixed $issue The security's issue date.
167
+ * @param mixed $firstinterest The security's first interest date.
168
+ * @param mixed $settlement The security's settlement date.
169
+ * The security settlement date is the date after the issue date
170
+ * when the security is traded to the buyer.
171
+ * @param float $rate The security's annual coupon rate.
172
+ * @param float $par The security's par value.
173
+ * If you omit par, ACCRINT uses $1,000.
174
+ * @param integer $frequency the number of coupon payments per year.
175
+ * Valid frequency values are:
176
+ * 1 Annual
177
+ * 2 Semi-Annual
178
+ * 4 Quarterly
179
+ * If working in Gnumeric Mode, the following frequency options are
180
+ * also available
181
+ * 6 Bimonthly
182
+ * 12 Monthly
183
+ * @param integer $basis The type of day count to use.
184
+ * 0 or omitted US (NASD) 30/360
185
+ * 1 Actual/actual
186
+ * 2 Actual/360
187
+ * 3 Actual/365
188
+ * 4 European 30/360
189
+ * @return float
190
+ */
191
+ public static function ACCRINT($issue, $firstinterest, $settlement, $rate, $par = 1000, $frequency = 1, $basis = 0)
192
+ {
193
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
194
+ $firstinterest = PHPExcel_Calculation_Functions::flattenSingleValue($firstinterest);
195
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
196
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
197
+ $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par);
198
+ $frequency = (is_null($frequency)) ? 1 : PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
199
+ $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis);
200
+
201
+ // Validate
202
+ if ((is_numeric($rate)) && (is_numeric($par))) {
203
+ $rate = (float) $rate;
204
+ $par = (float) $par;
205
+ if (($rate <= 0) || ($par <= 0)) {
206
+ return PHPExcel_Calculation_Functions::NaN();
207
+ }
208
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
209
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
210
+ // return date error
211
+ return $daysBetweenIssueAndSettlement;
212
+ }
213
+
214
+ return $par * $rate * $daysBetweenIssueAndSettlement;
215
+ }
216
+ return PHPExcel_Calculation_Functions::VALUE();
217
+ }
218
+
219
+
220
+ /**
221
+ * ACCRINTM
222
+ *
223
+ * Returns the accrued interest for a security that pays interest at maturity.
224
+ *
225
+ * Excel Function:
226
+ * ACCRINTM(issue,settlement,rate[,par[,basis]])
227
+ *
228
+ * @access public
229
+ * @category Financial Functions
230
+ * @param mixed issue The security's issue date.
231
+ * @param mixed settlement The security's settlement (or maturity) date.
232
+ * @param float rate The security's annual coupon rate.
233
+ * @param float par The security's par value.
234
+ * If you omit par, ACCRINT uses $1,000.
235
+ * @param integer basis The type of day count to use.
236
+ * 0 or omitted US (NASD) 30/360
237
+ * 1 Actual/actual
238
+ * 2 Actual/360
239
+ * 3 Actual/365
240
+ * 4 European 30/360
241
+ * @return float
242
+ */
243
+ public static function ACCRINTM($issue, $settlement, $rate, $par = 1000, $basis = 0)
244
+ {
245
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
246
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
247
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
248
+ $par = (is_null($par)) ? 1000 : PHPExcel_Calculation_Functions::flattenSingleValue($par);
249
+ $basis = (is_null($basis)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($basis);
250
+
251
+ // Validate
252
+ if ((is_numeric($rate)) && (is_numeric($par))) {
253
+ $rate = (float) $rate;
254
+ $par = (float) $par;
255
+ if (($rate <= 0) || ($par <= 0)) {
256
+ return PHPExcel_Calculation_Functions::NaN();
257
+ }
258
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
259
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
260
+ // return date error
261
+ return $daysBetweenIssueAndSettlement;
262
+ }
263
+ return $par * $rate * $daysBetweenIssueAndSettlement;
264
+ }
265
+ return PHPExcel_Calculation_Functions::VALUE();
266
+ }
267
+
268
+
269
+ /**
270
+ * AMORDEGRC
271
+ *
272
+ * Returns the depreciation for each accounting period.
273
+ * This function is provided for the French accounting system. If an asset is purchased in
274
+ * the middle of the accounting period, the prorated depreciation is taken into account.
275
+ * The function is similar to AMORLINC, except that a depreciation coefficient is applied in
276
+ * the calculation depending on the life of the assets.
277
+ * This function will return the depreciation until the last period of the life of the assets
278
+ * or until the cumulated value of depreciation is greater than the cost of the assets minus
279
+ * the salvage value.
280
+ *
281
+ * Excel Function:
282
+ * AMORDEGRC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
283
+ *
284
+ * @access public
285
+ * @category Financial Functions
286
+ * @param float cost The cost of the asset.
287
+ * @param mixed purchased Date of the purchase of the asset.
288
+ * @param mixed firstPeriod Date of the end of the first period.
289
+ * @param mixed salvage The salvage value at the end of the life of the asset.
290
+ * @param float period The period.
291
+ * @param float rate Rate of depreciation.
292
+ * @param integer basis The type of day count to use.
293
+ * 0 or omitted US (NASD) 30/360
294
+ * 1 Actual/actual
295
+ * 2 Actual/360
296
+ * 3 Actual/365
297
+ * 4 European 30/360
298
+ * @return float
299
+ */
300
+ public static function AMORDEGRC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0)
301
+ {
302
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
303
+ $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased);
304
+ $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod);
305
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
306
+ $period = floor(PHPExcel_Calculation_Functions::flattenSingleValue($period));
307
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
308
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
309
+
310
+ // The depreciation coefficients are:
311
+ // Life of assets (1/rate) Depreciation coefficient
312
+ // Less than 3 years 1
313
+ // Between 3 and 4 years 1.5
314
+ // Between 5 and 6 years 2
315
+ // More than 6 years 2.5
316
+ $fUsePer = 1.0 / $rate;
317
+ if ($fUsePer < 3.0) {
318
+ $amortiseCoeff = 1.0;
319
+ } elseif ($fUsePer < 5.0) {
320
+ $amortiseCoeff = 1.5;
321
+ } elseif ($fUsePer <= 6.0) {
322
+ $amortiseCoeff = 2.0;
323
+ } else {
324
+ $amortiseCoeff = 2.5;
325
+ }
326
+
327
+ $rate *= $amortiseCoeff;
328
+ $fNRate = round(PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis) * $rate * $cost, 0);
329
+ $cost -= $fNRate;
330
+ $fRest = $cost - $salvage;
331
+
332
+ for ($n = 0; $n < $period; ++$n) {
333
+ $fNRate = round($rate * $cost, 0);
334
+ $fRest -= $fNRate;
335
+
336
+ if ($fRest < 0.0) {
337
+ switch ($period - $n) {
338
+ case 0:
339
+ case 1:
340
+ return round($cost * 0.5, 0);
341
+ default:
342
+ return 0.0;
343
+ }
344
+ }
345
+ $cost -= $fNRate;
346
+ }
347
+ return $fNRate;
348
+ }
349
+
350
+
351
+ /**
352
+ * AMORLINC
353
+ *
354
+ * Returns the depreciation for each accounting period.
355
+ * This function is provided for the French accounting system. If an asset is purchased in
356
+ * the middle of the accounting period, the prorated depreciation is taken into account.
357
+ *
358
+ * Excel Function:
359
+ * AMORLINC(cost,purchased,firstPeriod,salvage,period,rate[,basis])
360
+ *
361
+ * @access public
362
+ * @category Financial Functions
363
+ * @param float cost The cost of the asset.
364
+ * @param mixed purchased Date of the purchase of the asset.
365
+ * @param mixed firstPeriod Date of the end of the first period.
366
+ * @param mixed salvage The salvage value at the end of the life of the asset.
367
+ * @param float period The period.
368
+ * @param float rate Rate of depreciation.
369
+ * @param integer basis The type of day count to use.
370
+ * 0 or omitted US (NASD) 30/360
371
+ * 1 Actual/actual
372
+ * 2 Actual/360
373
+ * 3 Actual/365
374
+ * 4 European 30/360
375
+ * @return float
376
+ */
377
+ public static function AMORLINC($cost, $purchased, $firstPeriod, $salvage, $period, $rate, $basis = 0)
378
+ {
379
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
380
+ $purchased = PHPExcel_Calculation_Functions::flattenSingleValue($purchased);
381
+ $firstPeriod = PHPExcel_Calculation_Functions::flattenSingleValue($firstPeriod);
382
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
383
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
384
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
385
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
386
+
387
+ $fOneRate = $cost * $rate;
388
+ $fCostDelta = $cost - $salvage;
389
+ // Note, quirky variation for leap years on the YEARFRAC for this function
390
+ $purchasedYear = PHPExcel_Calculation_DateTime::YEAR($purchased);
391
+ $yearFrac = PHPExcel_Calculation_DateTime::YEARFRAC($purchased, $firstPeriod, $basis);
392
+
393
+ if (($basis == 1) && ($yearFrac < 1) && (PHPExcel_Calculation_DateTime::isLeapYear($purchasedYear))) {
394
+ $yearFrac *= 365 / 366;
395
+ }
396
+
397
+ $f0Rate = $yearFrac * $rate * $cost;
398
+ $nNumOfFullPeriods = intval(($cost - $salvage - $f0Rate) / $fOneRate);
399
+
400
+ if ($period == 0) {
401
+ return $f0Rate;
402
+ } elseif ($period <= $nNumOfFullPeriods) {
403
+ return $fOneRate;
404
+ } elseif ($period == ($nNumOfFullPeriods + 1)) {
405
+ return ($fCostDelta - $fOneRate * $nNumOfFullPeriods - $f0Rate);
406
+ } else {
407
+ return 0.0;
408
+ }
409
+ }
410
+
411
+
412
+ /**
413
+ * COUPDAYBS
414
+ *
415
+ * Returns the number of days from the beginning of the coupon period to the settlement date.
416
+ *
417
+ * Excel Function:
418
+ * COUPDAYBS(settlement,maturity,frequency[,basis])
419
+ *
420
+ * @access public
421
+ * @category Financial Functions
422
+ * @param mixed settlement The security's settlement date.
423
+ * The security settlement date is the date after the issue
424
+ * date when the security is traded to the buyer.
425
+ * @param mixed maturity The security's maturity date.
426
+ * The maturity date is the date when the security expires.
427
+ * @param mixed frequency the number of coupon payments per year.
428
+ * Valid frequency values are:
429
+ * 1 Annual
430
+ * 2 Semi-Annual
431
+ * 4 Quarterly
432
+ * If working in Gnumeric Mode, the following frequency options are
433
+ * also available
434
+ * 6 Bimonthly
435
+ * 12 Monthly
436
+ * @param integer basis The type of day count to use.
437
+ * 0 or omitted US (NASD) 30/360
438
+ * 1 Actual/actual
439
+ * 2 Actual/360
440
+ * 3 Actual/365
441
+ * 4 European 30/360
442
+ * @return float
443
+ */
444
+ public static function COUPDAYBS($settlement, $maturity, $frequency, $basis = 0)
445
+ {
446
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
447
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
448
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
449
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
450
+
451
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
452
+ return PHPExcel_Calculation_Functions::VALUE();
453
+ }
454
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
455
+ return PHPExcel_Calculation_Functions::VALUE();
456
+ }
457
+
458
+ if (($settlement > $maturity) ||
459
+ (!self::isValidFrequency($frequency)) ||
460
+ (($basis < 0) || ($basis > 4))) {
461
+ return PHPExcel_Calculation_Functions::NaN();
462
+ }
463
+
464
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
465
+ $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
466
+
467
+ return PHPExcel_Calculation_DateTime::YEARFRAC($prev, $settlement, $basis) * $daysPerYear;
468
+ }
469
+
470
+
471
+ /**
472
+ * COUPDAYS
473
+ *
474
+ * Returns the number of days in the coupon period that contains the settlement date.
475
+ *
476
+ * Excel Function:
477
+ * COUPDAYS(settlement,maturity,frequency[,basis])
478
+ *
479
+ * @access public
480
+ * @category Financial Functions
481
+ * @param mixed settlement The security's settlement date.
482
+ * The security settlement date is the date after the issue
483
+ * date when the security is traded to the buyer.
484
+ * @param mixed maturity The security's maturity date.
485
+ * The maturity date is the date when the security expires.
486
+ * @param mixed frequency the number of coupon payments per year.
487
+ * Valid frequency values are:
488
+ * 1 Annual
489
+ * 2 Semi-Annual
490
+ * 4 Quarterly
491
+ * If working in Gnumeric Mode, the following frequency options are
492
+ * also available
493
+ * 6 Bimonthly
494
+ * 12 Monthly
495
+ * @param integer basis The type of day count to use.
496
+ * 0 or omitted US (NASD) 30/360
497
+ * 1 Actual/actual
498
+ * 2 Actual/360
499
+ * 3 Actual/365
500
+ * 4 European 30/360
501
+ * @return float
502
+ */
503
+ public static function COUPDAYS($settlement, $maturity, $frequency, $basis = 0)
504
+ {
505
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
506
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
507
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
508
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
509
+
510
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
511
+ return PHPExcel_Calculation_Functions::VALUE();
512
+ }
513
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
514
+ return PHPExcel_Calculation_Functions::VALUE();
515
+ }
516
+
517
+ if (($settlement > $maturity) ||
518
+ (!self::isValidFrequency($frequency)) ||
519
+ (($basis < 0) || ($basis > 4))) {
520
+ return PHPExcel_Calculation_Functions::NaN();
521
+ }
522
+
523
+ switch ($basis) {
524
+ case 3:
525
+ // Actual/365
526
+ return 365 / $frequency;
527
+ case 1:
528
+ // Actual/actual
529
+ if ($frequency == 1) {
530
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($maturity), $basis);
531
+ return ($daysPerYear / $frequency);
532
+ }
533
+ $prev = self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
534
+ $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
535
+ return ($next - $prev);
536
+ default:
537
+ // US (NASD) 30/360, Actual/360 or European 30/360
538
+ return 360 / $frequency;
539
+ }
540
+ return PHPExcel_Calculation_Functions::VALUE();
541
+ }
542
+
543
+
544
+ /**
545
+ * COUPDAYSNC
546
+ *
547
+ * Returns the number of days from the settlement date to the next coupon date.
548
+ *
549
+ * Excel Function:
550
+ * COUPDAYSNC(settlement,maturity,frequency[,basis])
551
+ *
552
+ * @access public
553
+ * @category Financial Functions
554
+ * @param mixed settlement The security's settlement date.
555
+ * The security settlement date is the date after the issue
556
+ * date when the security is traded to the buyer.
557
+ * @param mixed maturity The security's maturity date.
558
+ * The maturity date is the date when the security expires.
559
+ * @param mixed frequency the number of coupon payments per year.
560
+ * Valid frequency values are:
561
+ * 1 Annual
562
+ * 2 Semi-Annual
563
+ * 4 Quarterly
564
+ * If working in Gnumeric Mode, the following frequency options are
565
+ * also available
566
+ * 6 Bimonthly
567
+ * 12 Monthly
568
+ * @param integer basis The type of day count to use.
569
+ * 0 or omitted US (NASD) 30/360
570
+ * 1 Actual/actual
571
+ * 2 Actual/360
572
+ * 3 Actual/365
573
+ * 4 European 30/360
574
+ * @return float
575
+ */
576
+ public static function COUPDAYSNC($settlement, $maturity, $frequency, $basis = 0)
577
+ {
578
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
579
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
580
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
581
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
582
+
583
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
584
+ return PHPExcel_Calculation_Functions::VALUE();
585
+ }
586
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
587
+ return PHPExcel_Calculation_Functions::VALUE();
588
+ }
589
+
590
+ if (($settlement > $maturity) ||
591
+ (!self::isValidFrequency($frequency)) ||
592
+ (($basis < 0) || ($basis > 4))) {
593
+ return PHPExcel_Calculation_Functions::NaN();
594
+ }
595
+
596
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
597
+ $next = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
598
+
599
+ return PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $next, $basis) * $daysPerYear;
600
+ }
601
+
602
+
603
+ /**
604
+ * COUPNCD
605
+ *
606
+ * Returns the next coupon date after the settlement date.
607
+ *
608
+ * Excel Function:
609
+ * COUPNCD(settlement,maturity,frequency[,basis])
610
+ *
611
+ * @access public
612
+ * @category Financial Functions
613
+ * @param mixed settlement The security's settlement date.
614
+ * The security settlement date is the date after the issue
615
+ * date when the security is traded to the buyer.
616
+ * @param mixed maturity The security's maturity date.
617
+ * The maturity date is the date when the security expires.
618
+ * @param mixed frequency the number of coupon payments per year.
619
+ * Valid frequency values are:
620
+ * 1 Annual
621
+ * 2 Semi-Annual
622
+ * 4 Quarterly
623
+ * If working in Gnumeric Mode, the following frequency options are
624
+ * also available
625
+ * 6 Bimonthly
626
+ * 12 Monthly
627
+ * @param integer basis The type of day count to use.
628
+ * 0 or omitted US (NASD) 30/360
629
+ * 1 Actual/actual
630
+ * 2 Actual/360
631
+ * 3 Actual/365
632
+ * 4 European 30/360
633
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
634
+ * depending on the value of the ReturnDateType flag
635
+ */
636
+ public static function COUPNCD($settlement, $maturity, $frequency, $basis = 0)
637
+ {
638
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
639
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
640
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
641
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
642
+
643
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
644
+ return PHPExcel_Calculation_Functions::VALUE();
645
+ }
646
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
647
+ return PHPExcel_Calculation_Functions::VALUE();
648
+ }
649
+
650
+ if (($settlement > $maturity) ||
651
+ (!self::isValidFrequency($frequency)) ||
652
+ (($basis < 0) || ($basis > 4))) {
653
+ return PHPExcel_Calculation_Functions::NaN();
654
+ }
655
+
656
+ return self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
657
+ }
658
+
659
+
660
+ /**
661
+ * COUPNUM
662
+ *
663
+ * Returns the number of coupons payable between the settlement date and maturity date,
664
+ * rounded up to the nearest whole coupon.
665
+ *
666
+ * Excel Function:
667
+ * COUPNUM(settlement,maturity,frequency[,basis])
668
+ *
669
+ * @access public
670
+ * @category Financial Functions
671
+ * @param mixed settlement The security's settlement date.
672
+ * The security settlement date is the date after the issue
673
+ * date when the security is traded to the buyer.
674
+ * @param mixed maturity The security's maturity date.
675
+ * The maturity date is the date when the security expires.
676
+ * @param mixed frequency the number of coupon payments per year.
677
+ * Valid frequency values are:
678
+ * 1 Annual
679
+ * 2 Semi-Annual
680
+ * 4 Quarterly
681
+ * If working in Gnumeric Mode, the following frequency options are
682
+ * also available
683
+ * 6 Bimonthly
684
+ * 12 Monthly
685
+ * @param integer basis The type of day count to use.
686
+ * 0 or omitted US (NASD) 30/360
687
+ * 1 Actual/actual
688
+ * 2 Actual/360
689
+ * 3 Actual/365
690
+ * 4 European 30/360
691
+ * @return integer
692
+ */
693
+ public static function COUPNUM($settlement, $maturity, $frequency, $basis = 0)
694
+ {
695
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
696
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
697
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
698
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
699
+
700
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
701
+ return PHPExcel_Calculation_Functions::VALUE();
702
+ }
703
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
704
+ return PHPExcel_Calculation_Functions::VALUE();
705
+ }
706
+
707
+ if (($settlement > $maturity) ||
708
+ (!self::isValidFrequency($frequency)) ||
709
+ (($basis < 0) || ($basis > 4))) {
710
+ return PHPExcel_Calculation_Functions::NaN();
711
+ }
712
+
713
+ $settlement = self::couponFirstPeriodDate($settlement, $maturity, $frequency, true);
714
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis) * 365;
715
+
716
+ switch ($frequency) {
717
+ case 1: // annual payments
718
+ return ceil($daysBetweenSettlementAndMaturity / 360);
719
+ case 2: // half-yearly
720
+ return ceil($daysBetweenSettlementAndMaturity / 180);
721
+ case 4: // quarterly
722
+ return ceil($daysBetweenSettlementAndMaturity / 90);
723
+ case 6: // bimonthly
724
+ return ceil($daysBetweenSettlementAndMaturity / 60);
725
+ case 12: // monthly
726
+ return ceil($daysBetweenSettlementAndMaturity / 30);
727
+ }
728
+ return PHPExcel_Calculation_Functions::VALUE();
729
+ }
730
+
731
+
732
+ /**
733
+ * COUPPCD
734
+ *
735
+ * Returns the previous coupon date before the settlement date.
736
+ *
737
+ * Excel Function:
738
+ * COUPPCD(settlement,maturity,frequency[,basis])
739
+ *
740
+ * @access public
741
+ * @category Financial Functions
742
+ * @param mixed settlement The security's settlement date.
743
+ * The security settlement date is the date after the issue
744
+ * date when the security is traded to the buyer.
745
+ * @param mixed maturity The security's maturity date.
746
+ * The maturity date is the date when the security expires.
747
+ * @param mixed frequency the number of coupon payments per year.
748
+ * Valid frequency values are:
749
+ * 1 Annual
750
+ * 2 Semi-Annual
751
+ * 4 Quarterly
752
+ * If working in Gnumeric Mode, the following frequency options are
753
+ * also available
754
+ * 6 Bimonthly
755
+ * 12 Monthly
756
+ * @param integer basis The type of day count to use.
757
+ * 0 or omitted US (NASD) 30/360
758
+ * 1 Actual/actual
759
+ * 2 Actual/360
760
+ * 3 Actual/365
761
+ * 4 European 30/360
762
+ * @return mixed Excel date/time serial value, PHP date/time serial value or PHP date/time object,
763
+ * depending on the value of the ReturnDateType flag
764
+ */
765
+ public static function COUPPCD($settlement, $maturity, $frequency, $basis = 0)
766
+ {
767
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
768
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
769
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
770
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
771
+
772
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
773
+ return PHPExcel_Calculation_Functions::VALUE();
774
+ }
775
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
776
+ return PHPExcel_Calculation_Functions::VALUE();
777
+ }
778
+
779
+ if (($settlement > $maturity) ||
780
+ (!self::isValidFrequency($frequency)) ||
781
+ (($basis < 0) || ($basis > 4))) {
782
+ return PHPExcel_Calculation_Functions::NaN();
783
+ }
784
+
785
+ return self::couponFirstPeriodDate($settlement, $maturity, $frequency, false);
786
+ }
787
+
788
+
789
+ /**
790
+ * CUMIPMT
791
+ *
792
+ * Returns the cumulative interest paid on a loan between the start and end periods.
793
+ *
794
+ * Excel Function:
795
+ * CUMIPMT(rate,nper,pv,start,end[,type])
796
+ *
797
+ * @access public
798
+ * @category Financial Functions
799
+ * @param float $rate The Interest rate
800
+ * @param integer $nper The total number of payment periods
801
+ * @param float $pv Present Value
802
+ * @param integer $start The first period in the calculation.
803
+ * Payment periods are numbered beginning with 1.
804
+ * @param integer $end The last period in the calculation.
805
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
806
+ * 0 or omitted At the end of the period.
807
+ * 1 At the beginning of the period.
808
+ * @return float
809
+ */
810
+ public static function CUMIPMT($rate, $nper, $pv, $start, $end, $type = 0)
811
+ {
812
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
813
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
814
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
815
+ $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start);
816
+ $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end);
817
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
818
+
819
+ // Validate parameters
820
+ if ($type != 0 && $type != 1) {
821
+ return PHPExcel_Calculation_Functions::NaN();
822
+ }
823
+ if ($start < 1 || $start > $end) {
824
+ return PHPExcel_Calculation_Functions::VALUE();
825
+ }
826
+
827
+ // Calculate
828
+ $interest = 0;
829
+ for ($per = $start; $per <= $end; ++$per) {
830
+ $interest += self::IPMT($rate, $per, $nper, $pv, 0, $type);
831
+ }
832
+
833
+ return $interest;
834
+ }
835
+
836
+
837
+ /**
838
+ * CUMPRINC
839
+ *
840
+ * Returns the cumulative principal paid on a loan between the start and end periods.
841
+ *
842
+ * Excel Function:
843
+ * CUMPRINC(rate,nper,pv,start,end[,type])
844
+ *
845
+ * @access public
846
+ * @category Financial Functions
847
+ * @param float $rate The Interest rate
848
+ * @param integer $nper The total number of payment periods
849
+ * @param float $pv Present Value
850
+ * @param integer $start The first period in the calculation.
851
+ * Payment periods are numbered beginning with 1.
852
+ * @param integer $end The last period in the calculation.
853
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
854
+ * 0 or omitted At the end of the period.
855
+ * 1 At the beginning of the period.
856
+ * @return float
857
+ */
858
+ public static function CUMPRINC($rate, $nper, $pv, $start, $end, $type = 0)
859
+ {
860
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
861
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
862
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
863
+ $start = (int) PHPExcel_Calculation_Functions::flattenSingleValue($start);
864
+ $end = (int) PHPExcel_Calculation_Functions::flattenSingleValue($end);
865
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
866
+
867
+ // Validate parameters
868
+ if ($type != 0 && $type != 1) {
869
+ return PHPExcel_Calculation_Functions::NaN();
870
+ }
871
+ if ($start < 1 || $start > $end) {
872
+ return PHPExcel_Calculation_Functions::VALUE();
873
+ }
874
+
875
+ // Calculate
876
+ $principal = 0;
877
+ for ($per = $start; $per <= $end; ++$per) {
878
+ $principal += self::PPMT($rate, $per, $nper, $pv, 0, $type);
879
+ }
880
+
881
+ return $principal;
882
+ }
883
+
884
+
885
+ /**
886
+ * DB
887
+ *
888
+ * Returns the depreciation of an asset for a specified period using the
889
+ * fixed-declining balance method.
890
+ * This form of depreciation is used if you want to get a higher depreciation value
891
+ * at the beginning of the depreciation (as opposed to linear depreciation). The
892
+ * depreciation value is reduced with every depreciation period by the depreciation
893
+ * already deducted from the initial cost.
894
+ *
895
+ * Excel Function:
896
+ * DB(cost,salvage,life,period[,month])
897
+ *
898
+ * @access public
899
+ * @category Financial Functions
900
+ * @param float cost Initial cost of the asset.
901
+ * @param float salvage Value at the end of the depreciation.
902
+ * (Sometimes called the salvage value of the asset)
903
+ * @param integer life Number of periods over which the asset is depreciated.
904
+ * (Sometimes called the useful life of the asset)
905
+ * @param integer period The period for which you want to calculate the
906
+ * depreciation. Period must use the same units as life.
907
+ * @param integer month Number of months in the first year. If month is omitted,
908
+ * it defaults to 12.
909
+ * @return float
910
+ */
911
+ public static function DB($cost, $salvage, $life, $period, $month = 12)
912
+ {
913
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
914
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
915
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
916
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
917
+ $month = PHPExcel_Calculation_Functions::flattenSingleValue($month);
918
+
919
+ // Validate
920
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($month))) {
921
+ $cost = (float) $cost;
922
+ $salvage = (float) $salvage;
923
+ $life = (int) $life;
924
+ $period = (int) $period;
925
+ $month = (int) $month;
926
+ if ($cost == 0) {
927
+ return 0.0;
928
+ } elseif (($cost < 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($month < 1)) {
929
+ return PHPExcel_Calculation_Functions::NaN();
930
+ }
931
+ // Set Fixed Depreciation Rate
932
+ $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
933
+ $fixedDepreciationRate = round($fixedDepreciationRate, 3);
934
+
935
+ // Loop through each period calculating the depreciation
936
+ $previousDepreciation = 0;
937
+ for ($per = 1; $per <= $period; ++$per) {
938
+ if ($per == 1) {
939
+ $depreciation = $cost * $fixedDepreciationRate * $month / 12;
940
+ } elseif ($per == ($life + 1)) {
941
+ $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate * (12 - $month) / 12;
942
+ } else {
943
+ $depreciation = ($cost - $previousDepreciation) * $fixedDepreciationRate;
944
+ }
945
+ $previousDepreciation += $depreciation;
946
+ }
947
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
948
+ $depreciation = round($depreciation, 2);
949
+ }
950
+ return $depreciation;
951
+ }
952
+ return PHPExcel_Calculation_Functions::VALUE();
953
+ }
954
+
955
+
956
+ /**
957
+ * DDB
958
+ *
959
+ * Returns the depreciation of an asset for a specified period using the
960
+ * double-declining balance method or some other method you specify.
961
+ *
962
+ * Excel Function:
963
+ * DDB(cost,salvage,life,period[,factor])
964
+ *
965
+ * @access public
966
+ * @category Financial Functions
967
+ * @param float cost Initial cost of the asset.
968
+ * @param float salvage Value at the end of the depreciation.
969
+ * (Sometimes called the salvage value of the asset)
970
+ * @param integer life Number of periods over which the asset is depreciated.
971
+ * (Sometimes called the useful life of the asset)
972
+ * @param integer period The period for which you want to calculate the
973
+ * depreciation. Period must use the same units as life.
974
+ * @param float factor The rate at which the balance declines.
975
+ * If factor is omitted, it is assumed to be 2 (the
976
+ * double-declining balance method).
977
+ * @return float
978
+ */
979
+ public static function DDB($cost, $salvage, $life, $period, $factor = 2.0)
980
+ {
981
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
982
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
983
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
984
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
985
+ $factor = PHPExcel_Calculation_Functions::flattenSingleValue($factor);
986
+
987
+ // Validate
988
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period)) && (is_numeric($factor))) {
989
+ $cost = (float) $cost;
990
+ $salvage = (float) $salvage;
991
+ $life = (int) $life;
992
+ $period = (int) $period;
993
+ $factor = (float) $factor;
994
+ if (($cost <= 0) || (($salvage / $cost) < 0) || ($life <= 0) || ($period < 1) || ($factor <= 0.0) || ($period > $life)) {
995
+ return PHPExcel_Calculation_Functions::NaN();
996
+ }
997
+ // Set Fixed Depreciation Rate
998
+ $fixedDepreciationRate = 1 - pow(($salvage / $cost), (1 / $life));
999
+ $fixedDepreciationRate = round($fixedDepreciationRate, 3);
1000
+
1001
+ // Loop through each period calculating the depreciation
1002
+ $previousDepreciation = 0;
1003
+ for ($per = 1; $per <= $period; ++$per) {
1004
+ $depreciation = min(($cost - $previousDepreciation) * ($factor / $life), ($cost - $salvage - $previousDepreciation));
1005
+ $previousDepreciation += $depreciation;
1006
+ }
1007
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1008
+ $depreciation = round($depreciation, 2);
1009
+ }
1010
+ return $depreciation;
1011
+ }
1012
+ return PHPExcel_Calculation_Functions::VALUE();
1013
+ }
1014
+
1015
+
1016
+ /**
1017
+ * DISC
1018
+ *
1019
+ * Returns the discount rate for a security.
1020
+ *
1021
+ * Excel Function:
1022
+ * DISC(settlement,maturity,price,redemption[,basis])
1023
+ *
1024
+ * @access public
1025
+ * @category Financial Functions
1026
+ * @param mixed settlement The security's settlement date.
1027
+ * The security settlement date is the date after the issue
1028
+ * date when the security is traded to the buyer.
1029
+ * @param mixed maturity The security's maturity date.
1030
+ * The maturity date is the date when the security expires.
1031
+ * @param integer price The security's price per $100 face value.
1032
+ * @param integer redemption The security's redemption value per $100 face value.
1033
+ * @param integer basis The type of day count to use.
1034
+ * 0 or omitted US (NASD) 30/360
1035
+ * 1 Actual/actual
1036
+ * 2 Actual/360
1037
+ * 3 Actual/365
1038
+ * 4 European 30/360
1039
+ * @return float
1040
+ */
1041
+ public static function DISC($settlement, $maturity, $price, $redemption, $basis = 0)
1042
+ {
1043
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1044
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1045
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
1046
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
1047
+ $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1048
+
1049
+ // Validate
1050
+ if ((is_numeric($price)) && (is_numeric($redemption)) && (is_numeric($basis))) {
1051
+ $price = (float) $price;
1052
+ $redemption = (float) $redemption;
1053
+ $basis = (int) $basis;
1054
+ if (($price <= 0) || ($redemption <= 0)) {
1055
+ return PHPExcel_Calculation_Functions::NaN();
1056
+ }
1057
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1058
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1059
+ // return date error
1060
+ return $daysBetweenSettlementAndMaturity;
1061
+ }
1062
+
1063
+ return ((1 - $price / $redemption) / $daysBetweenSettlementAndMaturity);
1064
+ }
1065
+ return PHPExcel_Calculation_Functions::VALUE();
1066
+ }
1067
+
1068
+
1069
+ /**
1070
+ * DOLLARDE
1071
+ *
1072
+ * Converts a dollar price expressed as an integer part and a fraction
1073
+ * part into a dollar price expressed as a decimal number.
1074
+ * Fractional dollar numbers are sometimes used for security prices.
1075
+ *
1076
+ * Excel Function:
1077
+ * DOLLARDE(fractional_dollar,fraction)
1078
+ *
1079
+ * @access public
1080
+ * @category Financial Functions
1081
+ * @param float $fractional_dollar Fractional Dollar
1082
+ * @param integer $fraction Fraction
1083
+ * @return float
1084
+ */
1085
+ public static function DOLLARDE($fractional_dollar = null, $fraction = 0)
1086
+ {
1087
+ $fractional_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($fractional_dollar);
1088
+ $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction);
1089
+
1090
+ // Validate parameters
1091
+ if (is_null($fractional_dollar) || $fraction < 0) {
1092
+ return PHPExcel_Calculation_Functions::NaN();
1093
+ }
1094
+ if ($fraction == 0) {
1095
+ return PHPExcel_Calculation_Functions::DIV0();
1096
+ }
1097
+
1098
+ $dollars = floor($fractional_dollar);
1099
+ $cents = fmod($fractional_dollar, 1);
1100
+ $cents /= $fraction;
1101
+ $cents *= pow(10, ceil(log10($fraction)));
1102
+ return $dollars + $cents;
1103
+ }
1104
+
1105
+
1106
+ /**
1107
+ * DOLLARFR
1108
+ *
1109
+ * Converts a dollar price expressed as a decimal number into a dollar price
1110
+ * expressed as a fraction.
1111
+ * Fractional dollar numbers are sometimes used for security prices.
1112
+ *
1113
+ * Excel Function:
1114
+ * DOLLARFR(decimal_dollar,fraction)
1115
+ *
1116
+ * @access public
1117
+ * @category Financial Functions
1118
+ * @param float $decimal_dollar Decimal Dollar
1119
+ * @param integer $fraction Fraction
1120
+ * @return float
1121
+ */
1122
+ public static function DOLLARFR($decimal_dollar = null, $fraction = 0)
1123
+ {
1124
+ $decimal_dollar = PHPExcel_Calculation_Functions::flattenSingleValue($decimal_dollar);
1125
+ $fraction = (int)PHPExcel_Calculation_Functions::flattenSingleValue($fraction);
1126
+
1127
+ // Validate parameters
1128
+ if (is_null($decimal_dollar) || $fraction < 0) {
1129
+ return PHPExcel_Calculation_Functions::NaN();
1130
+ }
1131
+ if ($fraction == 0) {
1132
+ return PHPExcel_Calculation_Functions::DIV0();
1133
+ }
1134
+
1135
+ $dollars = floor($decimal_dollar);
1136
+ $cents = fmod($decimal_dollar, 1);
1137
+ $cents *= $fraction;
1138
+ $cents *= pow(10, -ceil(log10($fraction)));
1139
+ return $dollars + $cents;
1140
+ }
1141
+
1142
+
1143
+ /**
1144
+ * EFFECT
1145
+ *
1146
+ * Returns the effective interest rate given the nominal rate and the number of
1147
+ * compounding payments per year.
1148
+ *
1149
+ * Excel Function:
1150
+ * EFFECT(nominal_rate,npery)
1151
+ *
1152
+ * @access public
1153
+ * @category Financial Functions
1154
+ * @param float $nominal_rate Nominal interest rate
1155
+ * @param integer $npery Number of compounding payments per year
1156
+ * @return float
1157
+ */
1158
+ public static function EFFECT($nominal_rate = 0, $npery = 0)
1159
+ {
1160
+ $nominal_rate = PHPExcel_Calculation_Functions::flattenSingleValue($nominal_rate);
1161
+ $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery);
1162
+
1163
+ // Validate parameters
1164
+ if ($nominal_rate <= 0 || $npery < 1) {
1165
+ return PHPExcel_Calculation_Functions::NaN();
1166
+ }
1167
+
1168
+ return pow((1 + $nominal_rate / $npery), $npery) - 1;
1169
+ }
1170
+
1171
+
1172
+ /**
1173
+ * FV
1174
+ *
1175
+ * Returns the Future Value of a cash flow with constant payments and interest rate (annuities).
1176
+ *
1177
+ * Excel Function:
1178
+ * FV(rate,nper,pmt[,pv[,type]])
1179
+ *
1180
+ * @access public
1181
+ * @category Financial Functions
1182
+ * @param float $rate The interest rate per period
1183
+ * @param int $nper Total number of payment periods in an annuity
1184
+ * @param float $pmt The payment made each period: it cannot change over the
1185
+ * life of the annuity. Typically, pmt contains principal
1186
+ * and interest but no other fees or taxes.
1187
+ * @param float $pv Present Value, or the lump-sum amount that a series of
1188
+ * future payments is worth right now.
1189
+ * @param integer $type A number 0 or 1 and indicates when payments are due:
1190
+ * 0 or omitted At the end of the period.
1191
+ * 1 At the beginning of the period.
1192
+ * @return float
1193
+ */
1194
+ public static function FV($rate = 0, $nper = 0, $pmt = 0, $pv = 0, $type = 0)
1195
+ {
1196
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1197
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1198
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
1199
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1200
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
1201
+
1202
+ // Validate parameters
1203
+ if ($type != 0 && $type != 1) {
1204
+ return PHPExcel_Calculation_Functions::NaN();
1205
+ }
1206
+
1207
+ // Calculate
1208
+ if (!is_null($rate) && $rate != 0) {
1209
+ return -$pv * pow(1 + $rate, $nper) - $pmt * (1 + $rate * $type) * (pow(1 + $rate, $nper) - 1) / $rate;
1210
+ }
1211
+ return -$pv - $pmt * $nper;
1212
+ }
1213
+
1214
+
1215
+ /**
1216
+ * FVSCHEDULE
1217
+ *
1218
+ * Returns the future value of an initial principal after applying a series of compound interest rates.
1219
+ * Use FVSCHEDULE to calculate the future value of an investment with a variable or adjustable rate.
1220
+ *
1221
+ * Excel Function:
1222
+ * FVSCHEDULE(principal,schedule)
1223
+ *
1224
+ * @param float $principal The present value.
1225
+ * @param float[] $schedule An array of interest rates to apply.
1226
+ * @return float
1227
+ */
1228
+ public static function FVSCHEDULE($principal, $schedule)
1229
+ {
1230
+ $principal = PHPExcel_Calculation_Functions::flattenSingleValue($principal);
1231
+ $schedule = PHPExcel_Calculation_Functions::flattenArray($schedule);
1232
+
1233
+ foreach ($schedule as $rate) {
1234
+ $principal *= 1 + $rate;
1235
+ }
1236
+
1237
+ return $principal;
1238
+ }
1239
+
1240
+
1241
+ /**
1242
+ * INTRATE
1243
+ *
1244
+ * Returns the interest rate for a fully invested security.
1245
+ *
1246
+ * Excel Function:
1247
+ * INTRATE(settlement,maturity,investment,redemption[,basis])
1248
+ *
1249
+ * @param mixed $settlement The security's settlement date.
1250
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
1251
+ * @param mixed $maturity The security's maturity date.
1252
+ * The maturity date is the date when the security expires.
1253
+ * @param integer $investment The amount invested in the security.
1254
+ * @param integer $redemption The amount to be received at maturity.
1255
+ * @param integer $basis The type of day count to use.
1256
+ * 0 or omitted US (NASD) 30/360
1257
+ * 1 Actual/actual
1258
+ * 2 Actual/360
1259
+ * 3 Actual/365
1260
+ * 4 European 30/360
1261
+ * @return float
1262
+ */
1263
+ public static function INTRATE($settlement, $maturity, $investment, $redemption, $basis = 0)
1264
+ {
1265
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1266
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1267
+ $investment = PHPExcel_Calculation_Functions::flattenSingleValue($investment);
1268
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
1269
+ $basis = PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1270
+
1271
+ // Validate
1272
+ if ((is_numeric($investment)) && (is_numeric($redemption)) && (is_numeric($basis))) {
1273
+ $investment = (float) $investment;
1274
+ $redemption = (float) $redemption;
1275
+ $basis = (int) $basis;
1276
+ if (($investment <= 0) || ($redemption <= 0)) {
1277
+ return PHPExcel_Calculation_Functions::NaN();
1278
+ }
1279
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1280
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1281
+ // return date error
1282
+ return $daysBetweenSettlementAndMaturity;
1283
+ }
1284
+
1285
+ return (($redemption / $investment) - 1) / ($daysBetweenSettlementAndMaturity);
1286
+ }
1287
+ return PHPExcel_Calculation_Functions::VALUE();
1288
+ }
1289
+
1290
+
1291
+ /**
1292
+ * IPMT
1293
+ *
1294
+ * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
1295
+ *
1296
+ * Excel Function:
1297
+ * IPMT(rate,per,nper,pv[,fv][,type])
1298
+ *
1299
+ * @param float $rate Interest rate per period
1300
+ * @param int $per Period for which we want to find the interest
1301
+ * @param int $nper Number of periods
1302
+ * @param float $pv Present Value
1303
+ * @param float $fv Future Value
1304
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1305
+ * @return float
1306
+ */
1307
+ public static function IPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0)
1308
+ {
1309
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1310
+ $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per);
1311
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1312
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1313
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1314
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
1315
+
1316
+ // Validate parameters
1317
+ if ($type != 0 && $type != 1) {
1318
+ return PHPExcel_Calculation_Functions::NaN();
1319
+ }
1320
+ if ($per <= 0 || $per > $nper) {
1321
+ return PHPExcel_Calculation_Functions::VALUE();
1322
+ }
1323
+
1324
+ // Calculate
1325
+ $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
1326
+ return $interestAndPrincipal[0];
1327
+ }
1328
+
1329
+ /**
1330
+ * IRR
1331
+ *
1332
+ * Returns the internal rate of return for a series of cash flows represented by the numbers in values.
1333
+ * These cash flows do not have to be even, as they would be for an annuity. However, the cash flows must occur
1334
+ * at regular intervals, such as monthly or annually. The internal rate of return is the interest rate received
1335
+ * for an investment consisting of payments (negative values) and income (positive values) that occur at regular
1336
+ * periods.
1337
+ *
1338
+ * Excel Function:
1339
+ * IRR(values[,guess])
1340
+ *
1341
+ * @param float[] $values An array or a reference to cells that contain numbers for which you want
1342
+ * to calculate the internal rate of return.
1343
+ * Values must contain at least one positive value and one negative value to
1344
+ * calculate the internal rate of return.
1345
+ * @param float $guess A number that you guess is close to the result of IRR
1346
+ * @return float
1347
+ */
1348
+ public static function IRR($values, $guess = 0.1)
1349
+ {
1350
+ if (!is_array($values)) {
1351
+ return PHPExcel_Calculation_Functions::VALUE();
1352
+ }
1353
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
1354
+ $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess);
1355
+
1356
+ // create an initial range, with a root somewhere between 0 and guess
1357
+ $x1 = 0.0;
1358
+ $x2 = $guess;
1359
+ $f1 = self::NPV($x1, $values);
1360
+ $f2 = self::NPV($x2, $values);
1361
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
1362
+ if (($f1 * $f2) < 0.0) {
1363
+ break;
1364
+ }
1365
+ if (abs($f1) < abs($f2)) {
1366
+ $f1 = self::NPV($x1 += 1.6 * ($x1 - $x2), $values);
1367
+ } else {
1368
+ $f2 = self::NPV($x2 += 1.6 * ($x2 - $x1), $values);
1369
+ }
1370
+ }
1371
+ if (($f1 * $f2) > 0.0) {
1372
+ return PHPExcel_Calculation_Functions::VALUE();
1373
+ }
1374
+
1375
+ $f = self::NPV($x1, $values);
1376
+ if ($f < 0.0) {
1377
+ $rtb = $x1;
1378
+ $dx = $x2 - $x1;
1379
+ } else {
1380
+ $rtb = $x2;
1381
+ $dx = $x1 - $x2;
1382
+ }
1383
+
1384
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
1385
+ $dx *= 0.5;
1386
+ $x_mid = $rtb + $dx;
1387
+ $f_mid = self::NPV($x_mid, $values);
1388
+ if ($f_mid <= 0.0) {
1389
+ $rtb = $x_mid;
1390
+ }
1391
+ if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) {
1392
+ return $x_mid;
1393
+ }
1394
+ }
1395
+ return PHPExcel_Calculation_Functions::VALUE();
1396
+ }
1397
+
1398
+
1399
+ /**
1400
+ * ISPMT
1401
+ *
1402
+ * Returns the interest payment for an investment based on an interest rate and a constant payment schedule.
1403
+ *
1404
+ * Excel Function:
1405
+ * =ISPMT(interest_rate, period, number_payments, PV)
1406
+ *
1407
+ * interest_rate is the interest rate for the investment
1408
+ *
1409
+ * period is the period to calculate the interest rate. It must be betweeen 1 and number_payments.
1410
+ *
1411
+ * number_payments is the number of payments for the annuity
1412
+ *
1413
+ * PV is the loan amount or present value of the payments
1414
+ */
1415
+ public static function ISPMT()
1416
+ {
1417
+ // Return value
1418
+ $returnValue = 0;
1419
+
1420
+ // Get the parameters
1421
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1422
+ $interestRate = array_shift($aArgs);
1423
+ $period = array_shift($aArgs);
1424
+ $numberPeriods = array_shift($aArgs);
1425
+ $principleRemaining = array_shift($aArgs);
1426
+
1427
+ // Calculate
1428
+ $principlePayment = ($principleRemaining * 1.0) / ($numberPeriods * 1.0);
1429
+ for ($i=0; $i <= $period; ++$i) {
1430
+ $returnValue = $interestRate * $principleRemaining * -1;
1431
+ $principleRemaining -= $principlePayment;
1432
+ // principle needs to be 0 after the last payment, don't let floating point screw it up
1433
+ if ($i == $numberPeriods) {
1434
+ $returnValue = 0;
1435
+ }
1436
+ }
1437
+ return($returnValue);
1438
+ }
1439
+
1440
+
1441
+ /**
1442
+ * MIRR
1443
+ *
1444
+ * Returns the modified internal rate of return for a series of periodic cash flows. MIRR considers both
1445
+ * the cost of the investment and the interest received on reinvestment of cash.
1446
+ *
1447
+ * Excel Function:
1448
+ * MIRR(values,finance_rate, reinvestment_rate)
1449
+ *
1450
+ * @param float[] $values An array or a reference to cells that contain a series of payments and
1451
+ * income occurring at regular intervals.
1452
+ * Payments are negative value, income is positive values.
1453
+ * @param float $finance_rate The interest rate you pay on the money used in the cash flows
1454
+ * @param float $reinvestment_rate The interest rate you receive on the cash flows as you reinvest them
1455
+ * @return float
1456
+ */
1457
+ public static function MIRR($values, $finance_rate, $reinvestment_rate)
1458
+ {
1459
+ if (!is_array($values)) {
1460
+ return PHPExcel_Calculation_Functions::VALUE();
1461
+ }
1462
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
1463
+ $finance_rate = PHPExcel_Calculation_Functions::flattenSingleValue($finance_rate);
1464
+ $reinvestment_rate = PHPExcel_Calculation_Functions::flattenSingleValue($reinvestment_rate);
1465
+ $n = count($values);
1466
+
1467
+ $rr = 1.0 + $reinvestment_rate;
1468
+ $fr = 1.0 + $finance_rate;
1469
+
1470
+ $npv_pos = $npv_neg = 0.0;
1471
+ foreach ($values as $i => $v) {
1472
+ if ($v >= 0) {
1473
+ $npv_pos += $v / pow($rr, $i);
1474
+ } else {
1475
+ $npv_neg += $v / pow($fr, $i);
1476
+ }
1477
+ }
1478
+
1479
+ if (($npv_neg == 0) || ($npv_pos == 0) || ($reinvestment_rate <= -1)) {
1480
+ return PHPExcel_Calculation_Functions::VALUE();
1481
+ }
1482
+
1483
+ $mirr = pow((-$npv_pos * pow($rr, $n))
1484
+ / ($npv_neg * ($rr)), (1.0 / ($n - 1))) - 1.0;
1485
+
1486
+ return (is_finite($mirr) ? $mirr : PHPExcel_Calculation_Functions::VALUE());
1487
+ }
1488
+
1489
+
1490
+ /**
1491
+ * NOMINAL
1492
+ *
1493
+ * Returns the nominal interest rate given the effective rate and the number of compounding payments per year.
1494
+ *
1495
+ * @param float $effect_rate Effective interest rate
1496
+ * @param int $npery Number of compounding payments per year
1497
+ * @return float
1498
+ */
1499
+ public static function NOMINAL($effect_rate = 0, $npery = 0)
1500
+ {
1501
+ $effect_rate = PHPExcel_Calculation_Functions::flattenSingleValue($effect_rate);
1502
+ $npery = (int)PHPExcel_Calculation_Functions::flattenSingleValue($npery);
1503
+
1504
+ // Validate parameters
1505
+ if ($effect_rate <= 0 || $npery < 1) {
1506
+ return PHPExcel_Calculation_Functions::NaN();
1507
+ }
1508
+
1509
+ // Calculate
1510
+ return $npery * (pow($effect_rate + 1, 1 / $npery) - 1);
1511
+ }
1512
+
1513
+
1514
+ /**
1515
+ * NPER
1516
+ *
1517
+ * Returns the number of periods for a cash flow with constant periodic payments (annuities), and interest rate.
1518
+ *
1519
+ * @param float $rate Interest rate per period
1520
+ * @param int $pmt Periodic payment (annuity)
1521
+ * @param float $pv Present Value
1522
+ * @param float $fv Future Value
1523
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1524
+ * @return float
1525
+ */
1526
+ public static function NPER($rate = 0, $pmt = 0, $pv = 0, $fv = 0, $type = 0)
1527
+ {
1528
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1529
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
1530
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1531
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1532
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
1533
+
1534
+ // Validate parameters
1535
+ if ($type != 0 && $type != 1) {
1536
+ return PHPExcel_Calculation_Functions::NaN();
1537
+ }
1538
+
1539
+ // Calculate
1540
+ if (!is_null($rate) && $rate != 0) {
1541
+ if ($pmt == 0 && $pv == 0) {
1542
+ return PHPExcel_Calculation_Functions::NaN();
1543
+ }
1544
+ return log(($pmt * (1 + $rate * $type) / $rate - $fv) / ($pv + $pmt * (1 + $rate * $type) / $rate)) / log(1 + $rate);
1545
+ }
1546
+ if ($pmt == 0) {
1547
+ return PHPExcel_Calculation_Functions::NaN();
1548
+ }
1549
+ return (-$pv -$fv) / $pmt;
1550
+ }
1551
+
1552
+ /**
1553
+ * NPV
1554
+ *
1555
+ * Returns the Net Present Value of a cash flow series given a discount rate.
1556
+ *
1557
+ * @return float
1558
+ */
1559
+ public static function NPV()
1560
+ {
1561
+ // Return value
1562
+ $returnValue = 0;
1563
+
1564
+ // Loop through arguments
1565
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1566
+
1567
+ // Calculate
1568
+ $rate = array_shift($aArgs);
1569
+ for ($i = 1; $i <= count($aArgs); ++$i) {
1570
+ // Is it a numeric value?
1571
+ if (is_numeric($aArgs[$i - 1])) {
1572
+ $returnValue += $aArgs[$i - 1] / pow(1 + $rate, $i);
1573
+ }
1574
+ }
1575
+
1576
+ // Return
1577
+ return $returnValue;
1578
+ }
1579
+
1580
+ /**
1581
+ * PMT
1582
+ *
1583
+ * Returns the constant payment (annuity) for a cash flow with a constant interest rate.
1584
+ *
1585
+ * @param float $rate Interest rate per period
1586
+ * @param int $nper Number of periods
1587
+ * @param float $pv Present Value
1588
+ * @param float $fv Future Value
1589
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1590
+ * @return float
1591
+ */
1592
+ public static function PMT($rate = 0, $nper = 0, $pv = 0, $fv = 0, $type = 0)
1593
+ {
1594
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1595
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1596
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1597
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1598
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
1599
+
1600
+ // Validate parameters
1601
+ if ($type != 0 && $type != 1) {
1602
+ return PHPExcel_Calculation_Functions::NaN();
1603
+ }
1604
+
1605
+ // Calculate
1606
+ if (!is_null($rate) && $rate != 0) {
1607
+ return (-$fv - $pv * pow(1 + $rate, $nper)) / (1 + $rate * $type) / ((pow(1 + $rate, $nper) - 1) / $rate);
1608
+ }
1609
+ return (-$pv - $fv) / $nper;
1610
+ }
1611
+
1612
+
1613
+ /**
1614
+ * PPMT
1615
+ *
1616
+ * Returns the interest payment for a given period for an investment based on periodic, constant payments and a constant interest rate.
1617
+ *
1618
+ * @param float $rate Interest rate per period
1619
+ * @param int $per Period for which we want to find the interest
1620
+ * @param int $nper Number of periods
1621
+ * @param float $pv Present Value
1622
+ * @param float $fv Future Value
1623
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1624
+ * @return float
1625
+ */
1626
+ public static function PPMT($rate, $per, $nper, $pv, $fv = 0, $type = 0)
1627
+ {
1628
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1629
+ $per = (int) PHPExcel_Calculation_Functions::flattenSingleValue($per);
1630
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1631
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1632
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1633
+ $type = (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
1634
+
1635
+ // Validate parameters
1636
+ if ($type != 0 && $type != 1) {
1637
+ return PHPExcel_Calculation_Functions::NaN();
1638
+ }
1639
+ if ($per <= 0 || $per > $nper) {
1640
+ return PHPExcel_Calculation_Functions::VALUE();
1641
+ }
1642
+
1643
+ // Calculate
1644
+ $interestAndPrincipal = self::interestAndPrincipal($rate, $per, $nper, $pv, $fv, $type);
1645
+ return $interestAndPrincipal[1];
1646
+ }
1647
+
1648
+
1649
+ public static function PRICE($settlement, $maturity, $rate, $yield, $redemption, $frequency, $basis = 0)
1650
+ {
1651
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1652
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1653
+ $rate = (float) PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1654
+ $yield = (float) PHPExcel_Calculation_Functions::flattenSingleValue($yield);
1655
+ $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
1656
+ $frequency = (int) PHPExcel_Calculation_Functions::flattenSingleValue($frequency);
1657
+ $basis = (is_null($basis)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1658
+
1659
+ if (is_string($settlement = PHPExcel_Calculation_DateTime::getDateValue($settlement))) {
1660
+ return PHPExcel_Calculation_Functions::VALUE();
1661
+ }
1662
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
1663
+ return PHPExcel_Calculation_Functions::VALUE();
1664
+ }
1665
+
1666
+ if (($settlement > $maturity) ||
1667
+ (!self::isValidFrequency($frequency)) ||
1668
+ (($basis < 0) || ($basis > 4))) {
1669
+ return PHPExcel_Calculation_Functions::NaN();
1670
+ }
1671
+
1672
+ $dsc = self::COUPDAYSNC($settlement, $maturity, $frequency, $basis);
1673
+ $e = self::COUPDAYS($settlement, $maturity, $frequency, $basis);
1674
+ $n = self::COUPNUM($settlement, $maturity, $frequency, $basis);
1675
+ $a = self::COUPDAYBS($settlement, $maturity, $frequency, $basis);
1676
+
1677
+ $baseYF = 1.0 + ($yield / $frequency);
1678
+ $rfp = 100 * ($rate / $frequency);
1679
+ $de = $dsc / $e;
1680
+
1681
+ $result = $redemption / pow($baseYF, (--$n + $de));
1682
+ for ($k = 0; $k <= $n; ++$k) {
1683
+ $result += $rfp / (pow($baseYF, ($k + $de)));
1684
+ }
1685
+ $result -= $rfp * ($a / $e);
1686
+
1687
+ return $result;
1688
+ }
1689
+
1690
+
1691
+ /**
1692
+ * PRICEDISC
1693
+ *
1694
+ * Returns the price per $100 face value of a discounted security.
1695
+ *
1696
+ * @param mixed settlement The security's settlement date.
1697
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
1698
+ * @param mixed maturity The security's maturity date.
1699
+ * The maturity date is the date when the security expires.
1700
+ * @param int discount The security's discount rate.
1701
+ * @param int redemption The security's redemption value per $100 face value.
1702
+ * @param int basis The type of day count to use.
1703
+ * 0 or omitted US (NASD) 30/360
1704
+ * 1 Actual/actual
1705
+ * 2 Actual/360
1706
+ * 3 Actual/365
1707
+ * 4 European 30/360
1708
+ * @return float
1709
+ */
1710
+ public static function PRICEDISC($settlement, $maturity, $discount, $redemption, $basis = 0)
1711
+ {
1712
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1713
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1714
+ $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount);
1715
+ $redemption = (float) PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
1716
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1717
+
1718
+ // Validate
1719
+ if ((is_numeric($discount)) && (is_numeric($redemption)) && (is_numeric($basis))) {
1720
+ if (($discount <= 0) || ($redemption <= 0)) {
1721
+ return PHPExcel_Calculation_Functions::NaN();
1722
+ }
1723
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1724
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1725
+ // return date error
1726
+ return $daysBetweenSettlementAndMaturity;
1727
+ }
1728
+
1729
+ return $redemption * (1 - $discount * $daysBetweenSettlementAndMaturity);
1730
+ }
1731
+ return PHPExcel_Calculation_Functions::VALUE();
1732
+ }
1733
+
1734
+
1735
+ /**
1736
+ * PRICEMAT
1737
+ *
1738
+ * Returns the price per $100 face value of a security that pays interest at maturity.
1739
+ *
1740
+ * @param mixed settlement The security's settlement date.
1741
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
1742
+ * @param mixed maturity The security's maturity date.
1743
+ * The maturity date is the date when the security expires.
1744
+ * @param mixed issue The security's issue date.
1745
+ * @param int rate The security's interest rate at date of issue.
1746
+ * @param int yield The security's annual yield.
1747
+ * @param int basis The type of day count to use.
1748
+ * 0 or omitted US (NASD) 30/360
1749
+ * 1 Actual/actual
1750
+ * 2 Actual/360
1751
+ * 3 Actual/365
1752
+ * 4 European 30/360
1753
+ * @return float
1754
+ */
1755
+ public static function PRICEMAT($settlement, $maturity, $issue, $rate, $yield, $basis = 0)
1756
+ {
1757
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1758
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1759
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
1760
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1761
+ $yield = PHPExcel_Calculation_Functions::flattenSingleValue($yield);
1762
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1763
+
1764
+ // Validate
1765
+ if (is_numeric($rate) && is_numeric($yield)) {
1766
+ if (($rate <= 0) || ($yield <= 0)) {
1767
+ return PHPExcel_Calculation_Functions::NaN();
1768
+ }
1769
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
1770
+ if (!is_numeric($daysPerYear)) {
1771
+ return $daysPerYear;
1772
+ }
1773
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
1774
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
1775
+ // return date error
1776
+ return $daysBetweenIssueAndSettlement;
1777
+ }
1778
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
1779
+ $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
1780
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
1781
+ // return date error
1782
+ return $daysBetweenIssueAndMaturity;
1783
+ }
1784
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
1785
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1786
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1787
+ // return date error
1788
+ return $daysBetweenSettlementAndMaturity;
1789
+ }
1790
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
1791
+
1792
+ return ((100 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate * 100)) /
1793
+ (1 + (($daysBetweenSettlementAndMaturity / $daysPerYear) * $yield)) -
1794
+ (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate * 100));
1795
+ }
1796
+ return PHPExcel_Calculation_Functions::VALUE();
1797
+ }
1798
+
1799
+
1800
+ /**
1801
+ * PV
1802
+ *
1803
+ * Returns the Present Value of a cash flow with constant payments and interest rate (annuities).
1804
+ *
1805
+ * @param float $rate Interest rate per period
1806
+ * @param int $nper Number of periods
1807
+ * @param float $pmt Periodic payment (annuity)
1808
+ * @param float $fv Future Value
1809
+ * @param int $type Payment type: 0 = at the end of each period, 1 = at the beginning of each period
1810
+ * @return float
1811
+ */
1812
+ public static function PV($rate = 0, $nper = 0, $pmt = 0, $fv = 0, $type = 0)
1813
+ {
1814
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
1815
+ $nper = PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1816
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
1817
+ $fv = PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1818
+ $type = PHPExcel_Calculation_Functions::flattenSingleValue($type);
1819
+
1820
+ // Validate parameters
1821
+ if ($type != 0 && $type != 1) {
1822
+ return PHPExcel_Calculation_Functions::NaN();
1823
+ }
1824
+
1825
+ // Calculate
1826
+ if (!is_null($rate) && $rate != 0) {
1827
+ return (-$pmt * (1 + $rate * $type) * ((pow(1 + $rate, $nper) - 1) / $rate) - $fv) / pow(1 + $rate, $nper);
1828
+ }
1829
+ return -$fv - $pmt * $nper;
1830
+ }
1831
+
1832
+
1833
+ /**
1834
+ * RATE
1835
+ *
1836
+ * Returns the interest rate per period of an annuity.
1837
+ * RATE is calculated by iteration and can have zero or more solutions.
1838
+ * If the successive results of RATE do not converge to within 0.0000001 after 20 iterations,
1839
+ * RATE returns the #NUM! error value.
1840
+ *
1841
+ * Excel Function:
1842
+ * RATE(nper,pmt,pv[,fv[,type[,guess]]])
1843
+ *
1844
+ * @access public
1845
+ * @category Financial Functions
1846
+ * @param float nper The total number of payment periods in an annuity.
1847
+ * @param float pmt The payment made each period and cannot change over the life
1848
+ * of the annuity.
1849
+ * Typically, pmt includes principal and interest but no other
1850
+ * fees or taxes.
1851
+ * @param float pv The present value - the total amount that a series of future
1852
+ * payments is worth now.
1853
+ * @param float fv The future value, or a cash balance you want to attain after
1854
+ * the last payment is made. If fv is omitted, it is assumed
1855
+ * to be 0 (the future value of a loan, for example, is 0).
1856
+ * @param integer type A number 0 or 1 and indicates when payments are due:
1857
+ * 0 or omitted At the end of the period.
1858
+ * 1 At the beginning of the period.
1859
+ * @param float guess Your guess for what the rate will be.
1860
+ * If you omit guess, it is assumed to be 10 percent.
1861
+ * @return float
1862
+ **/
1863
+ public static function RATE($nper, $pmt, $pv, $fv = 0.0, $type = 0, $guess = 0.1)
1864
+ {
1865
+ $nper = (int) PHPExcel_Calculation_Functions::flattenSingleValue($nper);
1866
+ $pmt = PHPExcel_Calculation_Functions::flattenSingleValue($pmt);
1867
+ $pv = PHPExcel_Calculation_Functions::flattenSingleValue($pv);
1868
+ $fv = (is_null($fv)) ? 0.0 : PHPExcel_Calculation_Functions::flattenSingleValue($fv);
1869
+ $type = (is_null($type)) ? 0 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($type);
1870
+ $guess = (is_null($guess)) ? 0.1 : PHPExcel_Calculation_Functions::flattenSingleValue($guess);
1871
+
1872
+ $rate = $guess;
1873
+ if (abs($rate) < FINANCIAL_PRECISION) {
1874
+ $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
1875
+ } else {
1876
+ $f = exp($nper * log(1 + $rate));
1877
+ $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
1878
+ }
1879
+ $y0 = $pv + $pmt * $nper + $fv;
1880
+ $y1 = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
1881
+
1882
+ // find root by secant method
1883
+ $i = $x0 = 0.0;
1884
+ $x1 = $rate;
1885
+ while ((abs($y0 - $y1) > FINANCIAL_PRECISION) && ($i < FINANCIAL_MAX_ITERATIONS)) {
1886
+ $rate = ($y1 * $x0 - $y0 * $x1) / ($y1 - $y0);
1887
+ $x0 = $x1;
1888
+ $x1 = $rate;
1889
+ if (($nper * abs($pmt)) > ($pv - $fv)) {
1890
+ $x1 = abs($x1);
1891
+ }
1892
+ if (abs($rate) < FINANCIAL_PRECISION) {
1893
+ $y = $pv * (1 + $nper * $rate) + $pmt * (1 + $rate * $type) * $nper + $fv;
1894
+ } else {
1895
+ $f = exp($nper * log(1 + $rate));
1896
+ $y = $pv * $f + $pmt * (1 / $rate + $type) * ($f - 1) + $fv;
1897
+ }
1898
+
1899
+ $y0 = $y1;
1900
+ $y1 = $y;
1901
+ ++$i;
1902
+ }
1903
+ return $rate;
1904
+ }
1905
+
1906
+
1907
+ /**
1908
+ * RECEIVED
1909
+ *
1910
+ * Returns the price per $100 face value of a discounted security.
1911
+ *
1912
+ * @param mixed settlement The security's settlement date.
1913
+ * The security settlement date is the date after the issue date when the security is traded to the buyer.
1914
+ * @param mixed maturity The security's maturity date.
1915
+ * The maturity date is the date when the security expires.
1916
+ * @param int investment The amount invested in the security.
1917
+ * @param int discount The security's discount rate.
1918
+ * @param int basis The type of day count to use.
1919
+ * 0 or omitted US (NASD) 30/360
1920
+ * 1 Actual/actual
1921
+ * 2 Actual/360
1922
+ * 3 Actual/365
1923
+ * 4 European 30/360
1924
+ * @return float
1925
+ */
1926
+ public static function RECEIVED($settlement, $maturity, $investment, $discount, $basis = 0)
1927
+ {
1928
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
1929
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
1930
+ $investment = (float) PHPExcel_Calculation_Functions::flattenSingleValue($investment);
1931
+ $discount = (float) PHPExcel_Calculation_Functions::flattenSingleValue($discount);
1932
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
1933
+
1934
+ // Validate
1935
+ if ((is_numeric($investment)) && (is_numeric($discount)) && (is_numeric($basis))) {
1936
+ if (($investment <= 0) || ($discount <= 0)) {
1937
+ return PHPExcel_Calculation_Functions::NaN();
1938
+ }
1939
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
1940
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
1941
+ // return date error
1942
+ return $daysBetweenSettlementAndMaturity;
1943
+ }
1944
+
1945
+ return $investment / ( 1 - ($discount * $daysBetweenSettlementAndMaturity));
1946
+ }
1947
+ return PHPExcel_Calculation_Functions::VALUE();
1948
+ }
1949
+
1950
+
1951
+ /**
1952
+ * SLN
1953
+ *
1954
+ * Returns the straight-line depreciation of an asset for one period
1955
+ *
1956
+ * @param cost Initial cost of the asset
1957
+ * @param salvage Value at the end of the depreciation
1958
+ * @param life Number of periods over which the asset is depreciated
1959
+ * @return float
1960
+ */
1961
+ public static function SLN($cost, $salvage, $life)
1962
+ {
1963
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
1964
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
1965
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
1966
+
1967
+ // Calculate
1968
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life))) {
1969
+ if ($life < 0) {
1970
+ return PHPExcel_Calculation_Functions::NaN();
1971
+ }
1972
+ return ($cost - $salvage) / $life;
1973
+ }
1974
+ return PHPExcel_Calculation_Functions::VALUE();
1975
+ }
1976
+
1977
+
1978
+ /**
1979
+ * SYD
1980
+ *
1981
+ * Returns the sum-of-years' digits depreciation of an asset for a specified period.
1982
+ *
1983
+ * @param cost Initial cost of the asset
1984
+ * @param salvage Value at the end of the depreciation
1985
+ * @param life Number of periods over which the asset is depreciated
1986
+ * @param period Period
1987
+ * @return float
1988
+ */
1989
+ public static function SYD($cost, $salvage, $life, $period)
1990
+ {
1991
+ $cost = PHPExcel_Calculation_Functions::flattenSingleValue($cost);
1992
+ $salvage = PHPExcel_Calculation_Functions::flattenSingleValue($salvage);
1993
+ $life = PHPExcel_Calculation_Functions::flattenSingleValue($life);
1994
+ $period = PHPExcel_Calculation_Functions::flattenSingleValue($period);
1995
+
1996
+ // Calculate
1997
+ if ((is_numeric($cost)) && (is_numeric($salvage)) && (is_numeric($life)) && (is_numeric($period))) {
1998
+ if (($life < 1) || ($period > $life)) {
1999
+ return PHPExcel_Calculation_Functions::NaN();
2000
+ }
2001
+ return (($cost - $salvage) * ($life - $period + 1) * 2) / ($life * ($life + 1));
2002
+ }
2003
+ return PHPExcel_Calculation_Functions::VALUE();
2004
+ }
2005
+
2006
+
2007
+ /**
2008
+ * TBILLEQ
2009
+ *
2010
+ * Returns the bond-equivalent yield for a Treasury bill.
2011
+ *
2012
+ * @param mixed settlement The Treasury bill's settlement date.
2013
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
2014
+ * @param mixed maturity The Treasury bill's maturity date.
2015
+ * The maturity date is the date when the Treasury bill expires.
2016
+ * @param int discount The Treasury bill's discount rate.
2017
+ * @return float
2018
+ */
2019
+ public static function TBILLEQ($settlement, $maturity, $discount)
2020
+ {
2021
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2022
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2023
+ $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount);
2024
+
2025
+ // Use TBILLPRICE for validation
2026
+ $testValue = self::TBILLPRICE($settlement, $maturity, $discount);
2027
+ if (is_string($testValue)) {
2028
+ return $testValue;
2029
+ }
2030
+
2031
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
2032
+ return PHPExcel_Calculation_Functions::VALUE();
2033
+ }
2034
+
2035
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
2036
+ ++$maturity;
2037
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
2038
+ } else {
2039
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement));
2040
+ }
2041
+
2042
+ return (365 * $discount) / (360 - $discount * $daysBetweenSettlementAndMaturity);
2043
+ }
2044
+
2045
+
2046
+ /**
2047
+ * TBILLPRICE
2048
+ *
2049
+ * Returns the yield for a Treasury bill.
2050
+ *
2051
+ * @param mixed settlement The Treasury bill's settlement date.
2052
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
2053
+ * @param mixed maturity The Treasury bill's maturity date.
2054
+ * The maturity date is the date when the Treasury bill expires.
2055
+ * @param int discount The Treasury bill's discount rate.
2056
+ * @return float
2057
+ */
2058
+ public static function TBILLPRICE($settlement, $maturity, $discount)
2059
+ {
2060
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2061
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2062
+ $discount = PHPExcel_Calculation_Functions::flattenSingleValue($discount);
2063
+
2064
+ if (is_string($maturity = PHPExcel_Calculation_DateTime::getDateValue($maturity))) {
2065
+ return PHPExcel_Calculation_Functions::VALUE();
2066
+ }
2067
+
2068
+ // Validate
2069
+ if (is_numeric($discount)) {
2070
+ if ($discount <= 0) {
2071
+ return PHPExcel_Calculation_Functions::NaN();
2072
+ }
2073
+
2074
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
2075
+ ++$maturity;
2076
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
2077
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
2078
+ // return date error
2079
+ return $daysBetweenSettlementAndMaturity;
2080
+ }
2081
+ } else {
2082
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement));
2083
+ }
2084
+
2085
+ if ($daysBetweenSettlementAndMaturity > 360) {
2086
+ return PHPExcel_Calculation_Functions::NaN();
2087
+ }
2088
+
2089
+ $price = 100 * (1 - (($discount * $daysBetweenSettlementAndMaturity) / 360));
2090
+ if ($price <= 0) {
2091
+ return PHPExcel_Calculation_Functions::NaN();
2092
+ }
2093
+ return $price;
2094
+ }
2095
+ return PHPExcel_Calculation_Functions::VALUE();
2096
+ }
2097
+
2098
+
2099
+ /**
2100
+ * TBILLYIELD
2101
+ *
2102
+ * Returns the yield for a Treasury bill.
2103
+ *
2104
+ * @param mixed settlement The Treasury bill's settlement date.
2105
+ * The Treasury bill's settlement date is the date after the issue date when the Treasury bill is traded to the buyer.
2106
+ * @param mixed maturity The Treasury bill's maturity date.
2107
+ * The maturity date is the date when the Treasury bill expires.
2108
+ * @param int price The Treasury bill's price per $100 face value.
2109
+ * @return float
2110
+ */
2111
+ public static function TBILLYIELD($settlement, $maturity, $price)
2112
+ {
2113
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2114
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2115
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
2116
+
2117
+ // Validate
2118
+ if (is_numeric($price)) {
2119
+ if ($price <= 0) {
2120
+ return PHPExcel_Calculation_Functions::NaN();
2121
+ }
2122
+
2123
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE) {
2124
+ ++$maturity;
2125
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity) * 360;
2126
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
2127
+ // return date error
2128
+ return $daysBetweenSettlementAndMaturity;
2129
+ }
2130
+ } else {
2131
+ $daysBetweenSettlementAndMaturity = (PHPExcel_Calculation_DateTime::getDateValue($maturity) - PHPExcel_Calculation_DateTime::getDateValue($settlement));
2132
+ }
2133
+
2134
+ if ($daysBetweenSettlementAndMaturity > 360) {
2135
+ return PHPExcel_Calculation_Functions::NaN();
2136
+ }
2137
+
2138
+ return ((100 - $price) / $price) * (360 / $daysBetweenSettlementAndMaturity);
2139
+ }
2140
+ return PHPExcel_Calculation_Functions::VALUE();
2141
+ }
2142
+
2143
+
2144
+ public static function XIRR($values, $dates, $guess = 0.1)
2145
+ {
2146
+ if ((!is_array($values)) && (!is_array($dates))) {
2147
+ return PHPExcel_Calculation_Functions::VALUE();
2148
+ }
2149
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
2150
+ $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
2151
+ $guess = PHPExcel_Calculation_Functions::flattenSingleValue($guess);
2152
+ if (count($values) != count($dates)) {
2153
+ return PHPExcel_Calculation_Functions::NaN();
2154
+ }
2155
+
2156
+ // create an initial range, with a root somewhere between 0 and guess
2157
+ $x1 = 0.0;
2158
+ $x2 = $guess;
2159
+ $f1 = self::XNPV($x1, $values, $dates);
2160
+ $f2 = self::XNPV($x2, $values, $dates);
2161
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
2162
+ if (($f1 * $f2) < 0.0) {
2163
+ break;
2164
+ } elseif (abs($f1) < abs($f2)) {
2165
+ $f1 = self::XNPV($x1 += 1.6 * ($x1 - $x2), $values, $dates);
2166
+ } else {
2167
+ $f2 = self::XNPV($x2 += 1.6 * ($x2 - $x1), $values, $dates);
2168
+ }
2169
+ }
2170
+ if (($f1 * $f2) > 0.0) {
2171
+ return PHPExcel_Calculation_Functions::VALUE();
2172
+ }
2173
+
2174
+ $f = self::XNPV($x1, $values, $dates);
2175
+ if ($f < 0.0) {
2176
+ $rtb = $x1;
2177
+ $dx = $x2 - $x1;
2178
+ } else {
2179
+ $rtb = $x2;
2180
+ $dx = $x1 - $x2;
2181
+ }
2182
+
2183
+ for ($i = 0; $i < FINANCIAL_MAX_ITERATIONS; ++$i) {
2184
+ $dx *= 0.5;
2185
+ $x_mid = $rtb + $dx;
2186
+ $f_mid = self::XNPV($x_mid, $values, $dates);
2187
+ if ($f_mid <= 0.0) {
2188
+ $rtb = $x_mid;
2189
+ }
2190
+ if ((abs($f_mid) < FINANCIAL_PRECISION) || (abs($dx) < FINANCIAL_PRECISION)) {
2191
+ return $x_mid;
2192
+ }
2193
+ }
2194
+ return PHPExcel_Calculation_Functions::VALUE();
2195
+ }
2196
+
2197
+
2198
+ /**
2199
+ * XNPV
2200
+ *
2201
+ * Returns the net present value for a schedule of cash flows that is not necessarily periodic.
2202
+ * To calculate the net present value for a series of cash flows that is periodic, use the NPV function.
2203
+ *
2204
+ * Excel Function:
2205
+ * =XNPV(rate,values,dates)
2206
+ *
2207
+ * @param float $rate The discount rate to apply to the cash flows.
2208
+ * @param array of float $values A series of cash flows that corresponds to a schedule of payments in dates.
2209
+ * The first payment is optional and corresponds to a cost or payment that occurs at the beginning of the investment.
2210
+ * If the first value is a cost or payment, it must be a negative value. All succeeding payments are discounted based on a 365-day year.
2211
+ * The series of values must contain at least one positive value and one negative value.
2212
+ * @param array of mixed $dates A schedule of payment dates that corresponds to the cash flow payments.
2213
+ * The first payment date indicates the beginning of the schedule of payments.
2214
+ * All other dates must be later than this date, but they may occur in any order.
2215
+ * @return float
2216
+ */
2217
+ public static function XNPV($rate, $values, $dates)
2218
+ {
2219
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
2220
+ if (!is_numeric($rate)) {
2221
+ return PHPExcel_Calculation_Functions::VALUE();
2222
+ }
2223
+ if ((!is_array($values)) || (!is_array($dates))) {
2224
+ return PHPExcel_Calculation_Functions::VALUE();
2225
+ }
2226
+ $values = PHPExcel_Calculation_Functions::flattenArray($values);
2227
+ $dates = PHPExcel_Calculation_Functions::flattenArray($dates);
2228
+ $valCount = count($values);
2229
+ if ($valCount != count($dates)) {
2230
+ return PHPExcel_Calculation_Functions::NaN();
2231
+ }
2232
+ if ((min($values) > 0) || (max($values) < 0)) {
2233
+ return PHPExcel_Calculation_Functions::VALUE();
2234
+ }
2235
+
2236
+ $xnpv = 0.0;
2237
+ for ($i = 0; $i < $valCount; ++$i) {
2238
+ if (!is_numeric($values[$i])) {
2239
+ return PHPExcel_Calculation_Functions::VALUE();
2240
+ }
2241
+ $xnpv += $values[$i] / pow(1 + $rate, PHPExcel_Calculation_DateTime::DATEDIF($dates[0], $dates[$i], 'd') / 365);
2242
+ }
2243
+ return (is_finite($xnpv)) ? $xnpv : PHPExcel_Calculation_Functions::VALUE();
2244
+ }
2245
+
2246
+
2247
+ /**
2248
+ * YIELDDISC
2249
+ *
2250
+ * Returns the annual yield of a security that pays interest at maturity.
2251
+ *
2252
+ * @param mixed settlement The security's settlement date.
2253
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
2254
+ * @param mixed maturity The security's maturity date.
2255
+ * The maturity date is the date when the security expires.
2256
+ * @param int price The security's price per $100 face value.
2257
+ * @param int redemption The security's redemption value per $100 face value.
2258
+ * @param int basis The type of day count to use.
2259
+ * 0 or omitted US (NASD) 30/360
2260
+ * 1 Actual/actual
2261
+ * 2 Actual/360
2262
+ * 3 Actual/365
2263
+ * 4 European 30/360
2264
+ * @return float
2265
+ */
2266
+ public static function YIELDDISC($settlement, $maturity, $price, $redemption, $basis = 0)
2267
+ {
2268
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2269
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2270
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
2271
+ $redemption = PHPExcel_Calculation_Functions::flattenSingleValue($redemption);
2272
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
2273
+
2274
+ // Validate
2275
+ if (is_numeric($price) && is_numeric($redemption)) {
2276
+ if (($price <= 0) || ($redemption <= 0)) {
2277
+ return PHPExcel_Calculation_Functions::NaN();
2278
+ }
2279
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
2280
+ if (!is_numeric($daysPerYear)) {
2281
+ return $daysPerYear;
2282
+ }
2283
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
2284
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
2285
+ // return date error
2286
+ return $daysBetweenSettlementAndMaturity;
2287
+ }
2288
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
2289
+
2290
+ return (($redemption - $price) / $price) * ($daysPerYear / $daysBetweenSettlementAndMaturity);
2291
+ }
2292
+ return PHPExcel_Calculation_Functions::VALUE();
2293
+ }
2294
+
2295
+
2296
+ /**
2297
+ * YIELDMAT
2298
+ *
2299
+ * Returns the annual yield of a security that pays interest at maturity.
2300
+ *
2301
+ * @param mixed settlement The security's settlement date.
2302
+ * The security's settlement date is the date after the issue date when the security is traded to the buyer.
2303
+ * @param mixed maturity The security's maturity date.
2304
+ * The maturity date is the date when the security expires.
2305
+ * @param mixed issue The security's issue date.
2306
+ * @param int rate The security's interest rate at date of issue.
2307
+ * @param int price The security's price per $100 face value.
2308
+ * @param int basis The type of day count to use.
2309
+ * 0 or omitted US (NASD) 30/360
2310
+ * 1 Actual/actual
2311
+ * 2 Actual/360
2312
+ * 3 Actual/365
2313
+ * 4 European 30/360
2314
+ * @return float
2315
+ */
2316
+ public static function YIELDMAT($settlement, $maturity, $issue, $rate, $price, $basis = 0)
2317
+ {
2318
+ $settlement = PHPExcel_Calculation_Functions::flattenSingleValue($settlement);
2319
+ $maturity = PHPExcel_Calculation_Functions::flattenSingleValue($maturity);
2320
+ $issue = PHPExcel_Calculation_Functions::flattenSingleValue($issue);
2321
+ $rate = PHPExcel_Calculation_Functions::flattenSingleValue($rate);
2322
+ $price = PHPExcel_Calculation_Functions::flattenSingleValue($price);
2323
+ $basis = (int) PHPExcel_Calculation_Functions::flattenSingleValue($basis);
2324
+
2325
+ // Validate
2326
+ if (is_numeric($rate) && is_numeric($price)) {
2327
+ if (($rate <= 0) || ($price <= 0)) {
2328
+ return PHPExcel_Calculation_Functions::NaN();
2329
+ }
2330
+ $daysPerYear = self::daysPerYear(PHPExcel_Calculation_DateTime::YEAR($settlement), $basis);
2331
+ if (!is_numeric($daysPerYear)) {
2332
+ return $daysPerYear;
2333
+ }
2334
+ $daysBetweenIssueAndSettlement = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $settlement, $basis);
2335
+ if (!is_numeric($daysBetweenIssueAndSettlement)) {
2336
+ // return date error
2337
+ return $daysBetweenIssueAndSettlement;
2338
+ }
2339
+ $daysBetweenIssueAndSettlement *= $daysPerYear;
2340
+ $daysBetweenIssueAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($issue, $maturity, $basis);
2341
+ if (!is_numeric($daysBetweenIssueAndMaturity)) {
2342
+ // return date error
2343
+ return $daysBetweenIssueAndMaturity;
2344
+ }
2345
+ $daysBetweenIssueAndMaturity *= $daysPerYear;
2346
+ $daysBetweenSettlementAndMaturity = PHPExcel_Calculation_DateTime::YEARFRAC($settlement, $maturity, $basis);
2347
+ if (!is_numeric($daysBetweenSettlementAndMaturity)) {
2348
+ // return date error
2349
+ return $daysBetweenSettlementAndMaturity;
2350
+ }
2351
+ $daysBetweenSettlementAndMaturity *= $daysPerYear;
2352
+
2353
+ return ((1 + (($daysBetweenIssueAndMaturity / $daysPerYear) * $rate) - (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) /
2354
+ (($price / 100) + (($daysBetweenIssueAndSettlement / $daysPerYear) * $rate))) *
2355
+ ($daysPerYear / $daysBetweenSettlementAndMaturity);
2356
+ }
2357
+ return PHPExcel_Calculation_Functions::VALUE();
2358
+ }
2359
+ }
classes/PHPExcel/Calculation/FormulaParser.php ADDED
@@ -0,0 +1,622 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /*
4
+ PARTLY BASED ON:
5
+ Copyright (c) 2007 E. W. Bachtal, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software
8
+ and associated documentation files (the "Software"), to deal in the Software without restriction,
9
+ including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
+ and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
11
+ subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all copies or substantial
14
+ portions of the Software.
15
+
16
+ The software is provided "as is", without warranty of any kind, express or implied, including but not
17
+ limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In
18
+ no event shall the authors or copyright holders be liable for any claim, damages or other liability,
19
+ whether in an action of contract, tort or otherwise, arising from, out of or in connection with the
20
+ software or the use or other dealings in the software.
21
+
22
+ http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html
23
+ http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html
24
+ */
25
+
26
+ /**
27
+ * PHPExcel_Calculation_FormulaParser
28
+ *
29
+ * Copyright (c) 2006 - 2015 PHPExcel
30
+ *
31
+ * This library is free software; you can redistribute it and/or
32
+ * modify it under the terms of the GNU Lesser General Public
33
+ * License as published by the Free Software Foundation; either
34
+ * version 2.1 of the License, or (at your option) any later version.
35
+ *
36
+ * This library is distributed in the hope that it will be useful,
37
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
38
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
39
+ * Lesser General Public License for more details.
40
+ *
41
+ * You should have received a copy of the GNU Lesser General Public
42
+ * License along with this library; if not, write to the Free Software
43
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
44
+ *
45
+ * @category PHPExcel
46
+ * @package PHPExcel_Calculation
47
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
48
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
49
+ * @version ##VERSION##, ##DATE##
50
+ */
51
+
52
+
53
+ class PHPExcel_Calculation_FormulaParser
54
+ {
55
+ /* Character constants */
56
+ const QUOTE_DOUBLE = '"';
57
+ const QUOTE_SINGLE = '\'';
58
+ const BRACKET_CLOSE = ']';
59
+ const BRACKET_OPEN = '[';
60
+ const BRACE_OPEN = '{';
61
+ const BRACE_CLOSE = '}';
62
+ const PAREN_OPEN = '(';
63
+ const PAREN_CLOSE = ')';
64
+ const SEMICOLON = ';';
65
+ const WHITESPACE = ' ';
66
+ const COMMA = ',';
67
+ const ERROR_START = '#';
68
+
69
+ const OPERATORS_SN = "+-";
70
+ const OPERATORS_INFIX = "+-*/^&=><";
71
+ const OPERATORS_POSTFIX = "%";
72
+
73
+ /**
74
+ * Formula
75
+ *
76
+ * @var string
77
+ */
78
+ private $formula;
79
+
80
+ /**
81
+ * Tokens
82
+ *
83
+ * @var PHPExcel_Calculation_FormulaToken[]
84
+ */
85
+ private $tokens = array();
86
+
87
+ /**
88
+ * Create a new PHPExcel_Calculation_FormulaParser
89
+ *
90
+ * @param string $pFormula Formula to parse
91
+ * @throws PHPExcel_Calculation_Exception
92
+ */
93
+ public function __construct($pFormula = '')
94
+ {
95
+ // Check parameters
96
+ if (is_null($pFormula)) {
97
+ throw new PHPExcel_Calculation_Exception("Invalid parameter passed: formula");
98
+ }
99
+
100
+ // Initialise values
101
+ $this->formula = trim($pFormula);
102
+ // Parse!
103
+ $this->parseToTokens();
104
+ }
105
+
106
+ /**
107
+ * Get Formula
108
+ *
109
+ * @return string
110
+ */
111
+ public function getFormula()
112
+ {
113
+ return $this->formula;
114
+ }
115
+
116
+ /**
117
+ * Get Token
118
+ *
119
+ * @param int $pId Token id
120
+ * @return string
121
+ * @throws PHPExcel_Calculation_Exception
122
+ */
123
+ public function getToken($pId = 0)
124
+ {
125
+ if (isset($this->tokens[$pId])) {
126
+ return $this->tokens[$pId];
127
+ } else {
128
+ throw new PHPExcel_Calculation_Exception("Token with id $pId does not exist.");
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Get Token count
134
+ *
135
+ * @return string
136
+ */
137
+ public function getTokenCount()
138
+ {
139
+ return count($this->tokens);
140
+ }
141
+
142
+ /**
143
+ * Get Tokens
144
+ *
145
+ * @return PHPExcel_Calculation_FormulaToken[]
146
+ */
147
+ public function getTokens()
148
+ {
149
+ return $this->tokens;
150
+ }
151
+
152
+ /**
153
+ * Parse to tokens
154
+ */
155
+ private function parseToTokens()
156
+ {
157
+ // No attempt is made to verify formulas; assumes formulas are derived from Excel, where
158
+ // they can only exist if valid; stack overflows/underflows sunk as nulls without exceptions.
159
+
160
+ // Check if the formula has a valid starting =
161
+ $formulaLength = strlen($this->formula);
162
+ if ($formulaLength < 2 || $this->formula{0} != '=') {
163
+ return;
164
+ }
165
+
166
+ // Helper variables
167
+ $tokens1 = $tokens2 = $stack = array();
168
+ $inString = $inPath = $inRange = $inError = false;
169
+ $token = $previousToken = $nextToken = null;
170
+
171
+ $index = 1;
172
+ $value = '';
173
+
174
+ $ERRORS = array("#NULL!", "#DIV/0!", "#VALUE!", "#REF!", "#NAME?", "#NUM!", "#N/A");
175
+ $COMPARATORS_MULTI = array(">=", "<=", "<>");
176
+
177
+ while ($index < $formulaLength) {
178
+ // state-dependent character evaluation (order is important)
179
+
180
+ // double-quoted strings
181
+ // embeds are doubled
182
+ // end marks token
183
+ if ($inString) {
184
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) {
185
+ if ((($index + 2) <= $formulaLength) && ($this->formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE)) {
186
+ $value .= PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE;
187
+ ++$index;
188
+ } else {
189
+ $inString = false;
190
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_TEXT);
191
+ $value = "";
192
+ }
193
+ } else {
194
+ $value .= $this->formula{$index};
195
+ }
196
+ ++$index;
197
+ continue;
198
+ }
199
+
200
+ // single-quoted strings (links)
201
+ // embeds are double
202
+ // end does not mark a token
203
+ if ($inPath) {
204
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) {
205
+ if ((($index + 2) <= $formulaLength) && ($this->formula{$index + 1} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE)) {
206
+ $value .= PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE;
207
+ ++$index;
208
+ } else {
209
+ $inPath = false;
210
+ }
211
+ } else {
212
+ $value .= $this->formula{$index};
213
+ }
214
+ ++$index;
215
+ continue;
216
+ }
217
+
218
+ // bracked strings (R1C1 range index or linked workbook name)
219
+ // no embeds (changed to "()" by Excel)
220
+ // end does not mark a token
221
+ if ($inRange) {
222
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_CLOSE) {
223
+ $inRange = false;
224
+ }
225
+ $value .= $this->formula{$index};
226
+ ++$index;
227
+ continue;
228
+ }
229
+
230
+ // error values
231
+ // end marks a token, determined from absolute list of values
232
+ if ($inError) {
233
+ $value .= $this->formula{$index};
234
+ ++$index;
235
+ if (in_array($value, $ERRORS)) {
236
+ $inError = false;
237
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_ERROR);
238
+ $value = "";
239
+ }
240
+ continue;
241
+ }
242
+
243
+ // scientific notation check
244
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_SN, $this->formula{$index}) !== false) {
245
+ if (strlen($value) > 1) {
246
+ if (preg_match("/^[1-9]{1}(\.[0-9]+)?E{1}$/", $this->formula{$index}) != 0) {
247
+ $value .= $this->formula{$index};
248
+ ++$index;
249
+ continue;
250
+ }
251
+ }
252
+ }
253
+
254
+ // independent character evaluation (order not important)
255
+
256
+ // establish state-dependent character evaluations
257
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_DOUBLE) {
258
+ if (strlen($value > 0)) {
259
+ // unexpected
260
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
261
+ $value = "";
262
+ }
263
+ $inString = true;
264
+ ++$index;
265
+ continue;
266
+ }
267
+
268
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::QUOTE_SINGLE) {
269
+ if (strlen($value) > 0) {
270
+ // unexpected
271
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
272
+ $value = "";
273
+ }
274
+ $inPath = true;
275
+ ++$index;
276
+ continue;
277
+ }
278
+
279
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACKET_OPEN) {
280
+ $inRange = true;
281
+ $value .= PHPExcel_Calculation_FormulaParser::BRACKET_OPEN;
282
+ ++$index;
283
+ continue;
284
+ }
285
+
286
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::ERROR_START) {
287
+ if (strlen($value) > 0) {
288
+ // unexpected
289
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
290
+ $value = "";
291
+ }
292
+ $inError = true;
293
+ $value .= PHPExcel_Calculation_FormulaParser::ERROR_START;
294
+ ++$index;
295
+ continue;
296
+ }
297
+
298
+ // mark start and end of arrays and array rows
299
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_OPEN) {
300
+ if (strlen($value) > 0) {
301
+ // unexpected
302
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN);
303
+ $value = "";
304
+ }
305
+
306
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAY", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
307
+ $tokens1[] = $tmp;
308
+ $stack[] = clone $tmp;
309
+
310
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
311
+ $tokens1[] = $tmp;
312
+ $stack[] = clone $tmp;
313
+
314
+ ++$index;
315
+ continue;
316
+ }
317
+
318
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::SEMICOLON) {
319
+ if (strlen($value) > 0) {
320
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
321
+ $value = "";
322
+ }
323
+
324
+ $tmp = array_pop($stack);
325
+ $tmp->setValue("");
326
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
327
+ $tokens1[] = $tmp;
328
+
329
+ $tmp = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
330
+ $tokens1[] = $tmp;
331
+
332
+ $tmp = new PHPExcel_Calculation_FormulaToken("ARRAYROW", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
333
+ $tokens1[] = $tmp;
334
+ $stack[] = clone $tmp;
335
+
336
+ ++$index;
337
+ continue;
338
+ }
339
+
340
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::BRACE_CLOSE) {
341
+ if (strlen($value) > 0) {
342
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
343
+ $value = "";
344
+ }
345
+
346
+ $tmp = array_pop($stack);
347
+ $tmp->setValue("");
348
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
349
+ $tokens1[] = $tmp;
350
+
351
+ $tmp = array_pop($stack);
352
+ $tmp->setValue("");
353
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
354
+ $tokens1[] = $tmp;
355
+
356
+ ++$index;
357
+ continue;
358
+ }
359
+
360
+ // trim white-space
361
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) {
362
+ if (strlen($value) > 0) {
363
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
364
+ $value = "";
365
+ }
366
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE);
367
+ ++$index;
368
+ while (($this->formula{$index} == PHPExcel_Calculation_FormulaParser::WHITESPACE) && ($index < $formulaLength)) {
369
+ ++$index;
370
+ }
371
+ continue;
372
+ }
373
+
374
+ // multi-character comparators
375
+ if (($index + 2) <= $formulaLength) {
376
+ if (in_array(substr($this->formula, $index, 2), $COMPARATORS_MULTI)) {
377
+ if (strlen($value) > 0) {
378
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
379
+ $value = "";
380
+ }
381
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(substr($this->formula, $index, 2), PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
382
+ $index += 2;
383
+ continue;
384
+ }
385
+ }
386
+
387
+ // standard infix operators
388
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_INFIX, $this->formula{$index}) !== false) {
389
+ if (strlen($value) > 0) {
390
+ $tokens1[] =new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
391
+ $value = "";
392
+ }
393
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX);
394
+ ++$index;
395
+ continue;
396
+ }
397
+
398
+ // standard postfix operators (only one)
399
+ if (strpos(PHPExcel_Calculation_FormulaParser::OPERATORS_POSTFIX, $this->formula{$index}) !== false) {
400
+ if (strlen($value) > 0) {
401
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
402
+ $value = "";
403
+ }
404
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($this->formula{$index}, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX);
405
+ ++$index;
406
+ continue;
407
+ }
408
+
409
+ // start subexpression or function
410
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_OPEN) {
411
+ if (strlen($value) > 0) {
412
+ $tmp = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
413
+ $tokens1[] = $tmp;
414
+ $stack[] = clone $tmp;
415
+ $value = "";
416
+ } else {
417
+ $tmp = new PHPExcel_Calculation_FormulaToken("", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START);
418
+ $tokens1[] = $tmp;
419
+ $stack[] = clone $tmp;
420
+ }
421
+ ++$index;
422
+ continue;
423
+ }
424
+
425
+ // function, subexpression, or array parameters, or operand unions
426
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::COMMA) {
427
+ if (strlen($value) > 0) {
428
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
429
+ $value = "";
430
+ }
431
+
432
+ $tmp = array_pop($stack);
433
+ $tmp->setValue("");
434
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
435
+ $stack[] = $tmp;
436
+
437
+ if ($tmp->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
438
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_UNION);
439
+ } else {
440
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken(",", PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_ARGUMENT);
441
+ }
442
+ ++$index;
443
+ continue;
444
+ }
445
+
446
+ // stop subexpression
447
+ if ($this->formula{$index} == PHPExcel_Calculation_FormulaParser::PAREN_CLOSE) {
448
+ if (strlen($value) > 0) {
449
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
450
+ $value = "";
451
+ }
452
+
453
+ $tmp = array_pop($stack);
454
+ $tmp->setValue("");
455
+ $tmp->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP);
456
+ $tokens1[] = $tmp;
457
+
458
+ ++$index;
459
+ continue;
460
+ }
461
+
462
+ // token accumulation
463
+ $value .= $this->formula{$index};
464
+ ++$index;
465
+ }
466
+
467
+ // dump remaining accumulation
468
+ if (strlen($value) > 0) {
469
+ $tokens1[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND);
470
+ }
471
+
472
+ // move tokenList to new set, excluding unnecessary white-space tokens and converting necessary ones to intersections
473
+ $tokenCount = count($tokens1);
474
+ for ($i = 0; $i < $tokenCount; ++$i) {
475
+ $token = $tokens1[$i];
476
+ if (isset($tokens1[$i - 1])) {
477
+ $previousToken = $tokens1[$i - 1];
478
+ } else {
479
+ $previousToken = null;
480
+ }
481
+ if (isset($tokens1[$i + 1])) {
482
+ $nextToken = $tokens1[$i + 1];
483
+ } else {
484
+ $nextToken = null;
485
+ }
486
+
487
+ if (is_null($token)) {
488
+ continue;
489
+ }
490
+
491
+ if ($token->getTokenType() != PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_WHITESPACE) {
492
+ $tokens2[] = $token;
493
+ continue;
494
+ }
495
+
496
+ if (is_null($previousToken)) {
497
+ continue;
498
+ }
499
+
500
+ if (! (
501
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
502
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
503
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
504
+ ) ) {
505
+ continue;
506
+ }
507
+
508
+ if (is_null($nextToken)) {
509
+ continue;
510
+ }
511
+
512
+ if (! (
513
+ (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
514
+ (($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) && ($nextToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_START)) ||
515
+ ($nextToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)
516
+ ) ) {
517
+ continue;
518
+ }
519
+
520
+ $tokens2[] = new PHPExcel_Calculation_FormulaToken($value, PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX, PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_INTERSECTION);
521
+ }
522
+
523
+ // move tokens to final list, switching infix "-" operators to prefix when appropriate, switching infix "+" operators
524
+ // to noop when appropriate, identifying operand and infix-operator subtypes, and pulling "@" from function names
525
+ $this->tokens = array();
526
+
527
+ $tokenCount = count($tokens2);
528
+ for ($i = 0; $i < $tokenCount; ++$i) {
529
+ $token = $tokens2[$i];
530
+ if (isset($tokens2[$i - 1])) {
531
+ $previousToken = $tokens2[$i - 1];
532
+ } else {
533
+ $previousToken = null;
534
+ }
535
+ if (isset($tokens2[$i + 1])) {
536
+ $nextToken = $tokens2[$i + 1];
537
+ } else {
538
+ $nextToken = null;
539
+ }
540
+
541
+ if (is_null($token)) {
542
+ continue;
543
+ }
544
+
545
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "-") {
546
+ if ($i == 0) {
547
+ $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
548
+ } elseif ((($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) &&
549
+ ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
550
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) &&
551
+ ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
552
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
553
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)) {
554
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
555
+ } else {
556
+ $token->setTokenType(PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPREFIX);
557
+ }
558
+
559
+ $this->tokens[] = $token;
560
+ continue;
561
+ }
562
+
563
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX && $token->getValue() == "+") {
564
+ if ($i == 0) {
565
+ continue;
566
+ } elseif ((($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) &&
567
+ ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
568
+ (($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_SUBEXPRESSION) &&
569
+ ($previousToken->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_STOP)) ||
570
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORPOSTFIX) ||
571
+ ($previousToken->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND)) {
572
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
573
+ } else {
574
+ continue;
575
+ }
576
+
577
+ $this->tokens[] = $token;
578
+ continue;
579
+ }
580
+
581
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERATORINFIX &&
582
+ $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
583
+ if (strpos("<>=", substr($token->getValue(), 0, 1)) !== false) {
584
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
585
+ } elseif ($token->getValue() == "&") {
586
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_CONCATENATION);
587
+ } else {
588
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_MATH);
589
+ }
590
+
591
+ $this->tokens[] = $token;
592
+ continue;
593
+ }
594
+
595
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_OPERAND &&
596
+ $token->getTokenSubType() == PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING) {
597
+ if (!is_numeric($token->getValue())) {
598
+ if (strtoupper($token->getValue()) == "TRUE" || strtoupper($token->getValue() == "FALSE")) {
599
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_LOGICAL);
600
+ } else {
601
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_RANGE);
602
+ }
603
+ } else {
604
+ $token->setTokenSubType(PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NUMBER);
605
+ }
606
+
607
+ $this->tokens[] = $token;
608
+ continue;
609
+ }
610
+
611
+ if ($token->getTokenType() == PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_FUNCTION) {
612
+ if (strlen($token->getValue() > 0)) {
613
+ if (substr($token->getValue(), 0, 1) == "@") {
614
+ $token->setValue(substr($token->getValue(), 1));
615
+ }
616
+ }
617
+ }
618
+
619
+ $this->tokens[] = $token;
620
+ }
621
+ }
622
+ }
classes/PHPExcel/Calculation/FormulaToken.php ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /*
4
+ PARTLY BASED ON:
5
+ Copyright (c) 2007 E. W. Bachtal, Inc.
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software
8
+ and associated documentation files (the "Software"), to deal in the Software without restriction,
9
+ including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
10
+ and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
11
+ subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all copies or substantial
14
+ portions of the Software.
15
+
16
+ The software is provided "as is", without warranty of any kind, express or implied, including but not
17
+ limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In
18
+ no event shall the authors or copyright holders be liable for any claim, damages or other liability,
19
+ whether in an action of contract, tort or otherwise, arising from, out of or in connection with the
20
+ software or the use or other dealings in the software.
21
+
22
+ http://ewbi.blogs.com/develops/2007/03/excel_formula_p.html
23
+ http://ewbi.blogs.com/develops/2004/12/excel_formula_p.html
24
+ */
25
+
26
+ /**
27
+ * PHPExcel_Calculation_FormulaToken
28
+ *
29
+ * Copyright (c) 2006 - 2015 PHPExcel
30
+ *
31
+ * This library is free software; you can redistribute it and/or
32
+ * modify it under the terms of the GNU Lesser General Public
33
+ * License as published by the Free Software Foundation; either
34
+ * version 2.1 of the License, or (at your option) any later version.
35
+ *
36
+ * This library is distributed in the hope that it will be useful,
37
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
38
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
39
+ * Lesser General Public License for more details.
40
+ *
41
+ * You should have received a copy of the GNU Lesser General Public
42
+ * License along with this library; if not, write to the Free Software
43
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
44
+ *
45
+ * @category PHPExcel
46
+ * @package PHPExcel_Calculation
47
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
48
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
49
+ * @version ##VERSION##, ##DATE##
50
+ */
51
+
52
+
53
+ class PHPExcel_Calculation_FormulaToken
54
+ {
55
+ /* Token types */
56
+ const TOKEN_TYPE_NOOP = 'Noop';
57
+ const TOKEN_TYPE_OPERAND = 'Operand';
58
+ const TOKEN_TYPE_FUNCTION = 'Function';
59
+ const TOKEN_TYPE_SUBEXPRESSION = 'Subexpression';
60
+ const TOKEN_TYPE_ARGUMENT = 'Argument';
61
+ const TOKEN_TYPE_OPERATORPREFIX = 'OperatorPrefix';
62
+ const TOKEN_TYPE_OPERATORINFIX = 'OperatorInfix';
63
+ const TOKEN_TYPE_OPERATORPOSTFIX = 'OperatorPostfix';
64
+ const TOKEN_TYPE_WHITESPACE = 'Whitespace';
65
+ const TOKEN_TYPE_UNKNOWN = 'Unknown';
66
+
67
+ /* Token subtypes */
68
+ const TOKEN_SUBTYPE_NOTHING = 'Nothing';
69
+ const TOKEN_SUBTYPE_START = 'Start';
70
+ const TOKEN_SUBTYPE_STOP = 'Stop';
71
+ const TOKEN_SUBTYPE_TEXT = 'Text';
72
+ const TOKEN_SUBTYPE_NUMBER = 'Number';
73
+ const TOKEN_SUBTYPE_LOGICAL = 'Logical';
74
+ const TOKEN_SUBTYPE_ERROR = 'Error';
75
+ const TOKEN_SUBTYPE_RANGE = 'Range';
76
+ const TOKEN_SUBTYPE_MATH = 'Math';
77
+ const TOKEN_SUBTYPE_CONCATENATION = 'Concatenation';
78
+ const TOKEN_SUBTYPE_INTERSECTION = 'Intersection';
79
+ const TOKEN_SUBTYPE_UNION = 'Union';
80
+
81
+ /**
82
+ * Value
83
+ *
84
+ * @var string
85
+ */
86
+ private $value;
87
+
88
+ /**
89
+ * Token Type (represented by TOKEN_TYPE_*)
90
+ *
91
+ * @var string
92
+ */
93
+ private $tokenType;
94
+
95
+ /**
96
+ * Token SubType (represented by TOKEN_SUBTYPE_*)
97
+ *
98
+ * @var string
99
+ */
100
+ private $tokenSubType;
101
+
102
+ /**
103
+ * Create a new PHPExcel_Calculation_FormulaToken
104
+ *
105
+ * @param string $pValue
106
+ * @param string $pTokenType Token type (represented by TOKEN_TYPE_*)
107
+ * @param string $pTokenSubType Token Subtype (represented by TOKEN_SUBTYPE_*)
108
+ */
109
+ public function __construct($pValue, $pTokenType = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN, $pTokenSubType = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING)
110
+ {
111
+ // Initialise values
112
+ $this->value = $pValue;
113
+ $this->tokenType = $pTokenType;
114
+ $this->tokenSubType = $pTokenSubType;
115
+ }
116
+
117
+ /**
118
+ * Get Value
119
+ *
120
+ * @return string
121
+ */
122
+ public function getValue()
123
+ {
124
+ return $this->value;
125
+ }
126
+
127
+ /**
128
+ * Set Value
129
+ *
130
+ * @param string $value
131
+ */
132
+ public function setValue($value)
133
+ {
134
+ $this->value = $value;
135
+ }
136
+
137
+ /**
138
+ * Get Token Type (represented by TOKEN_TYPE_*)
139
+ *
140
+ * @return string
141
+ */
142
+ public function getTokenType()
143
+ {
144
+ return $this->tokenType;
145
+ }
146
+
147
+ /**
148
+ * Set Token Type
149
+ *
150
+ * @param string $value
151
+ */
152
+ public function setTokenType($value = PHPExcel_Calculation_FormulaToken::TOKEN_TYPE_UNKNOWN)
153
+ {
154
+ $this->tokenType = $value;
155
+ }
156
+
157
+ /**
158
+ * Get Token SubType (represented by TOKEN_SUBTYPE_*)
159
+ *
160
+ * @return string
161
+ */
162
+ public function getTokenSubType()
163
+ {
164
+ return $this->tokenSubType;
165
+ }
166
+
167
+ /**
168
+ * Set Token SubType
169
+ *
170
+ * @param string $value
171
+ */
172
+ public function setTokenSubType($value = PHPExcel_Calculation_FormulaToken::TOKEN_SUBTYPE_NOTHING)
173
+ {
174
+ $this->tokenSubType = $value;
175
+ }
176
+ }
classes/PHPExcel/Calculation/Function.php ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * PHPExcel_Calculation_Function
5
+ *
6
+ * Copyright (c) 2006 - 2015 PHPExcel
7
+ *
8
+ * This library is free software; you can redistribute it and/or
9
+ * modify it under the terms of the GNU Lesser General Public
10
+ * License as published by the Free Software Foundation; either
11
+ * version 2.1 of the License, or (at your option) any later version.
12
+ *
13
+ * This library is distributed in the hope that it will be useful,
14
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16
+ * Lesser General Public License for more details.
17
+ *
18
+ * You should have received a copy of the GNU Lesser General Public
19
+ * License along with this library; if not, write to the Free Software
20
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
+ *
22
+ * @category PHPExcel
23
+ * @package PHPExcel_Calculation
24
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
25
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
26
+ * @version ##VERSION##, ##DATE##
27
+ */
28
+ class PHPExcel_Calculation_Function
29
+ {
30
+ /* Function categories */
31
+ const CATEGORY_CUBE = 'Cube';
32
+ const CATEGORY_DATABASE = 'Database';
33
+ const CATEGORY_DATE_AND_TIME = 'Date and Time';
34
+ const CATEGORY_ENGINEERING = 'Engineering';
35
+ const CATEGORY_FINANCIAL = 'Financial';
36
+ const CATEGORY_INFORMATION = 'Information';
37
+ const CATEGORY_LOGICAL = 'Logical';
38
+ const CATEGORY_LOOKUP_AND_REFERENCE = 'Lookup and Reference';
39
+ const CATEGORY_MATH_AND_TRIG = 'Math and Trig';
40
+ const CATEGORY_STATISTICAL = 'Statistical';
41
+ const CATEGORY_TEXT_AND_DATA = 'Text and Data';
42
+
43
+ /**
44
+ * Category (represented by CATEGORY_*)
45
+ *
46
+ * @var string
47
+ */
48
+ private $category;
49
+
50
+ /**
51
+ * Excel name
52
+ *
53
+ * @var string
54
+ */
55
+ private $excelName;
56
+
57
+ /**
58
+ * PHPExcel name
59
+ *
60
+ * @var string
61
+ */
62
+ private $phpExcelName;
63
+
64
+ /**
65
+ * Create a new PHPExcel_Calculation_Function
66
+ *
67
+ * @param string $pCategory Category (represented by CATEGORY_*)
68
+ * @param string $pExcelName Excel function name
69
+ * @param string $pPHPExcelName PHPExcel function mapping
70
+ * @throws PHPExcel_Calculation_Exception
71
+ */
72
+ public function __construct($pCategory = null, $pExcelName = null, $pPHPExcelName = null)
73
+ {
74
+ if (($pCategory !== null) && ($pExcelName !== null) && ($pPHPExcelName !== null)) {
75
+ // Initialise values
76
+ $this->category = $pCategory;
77
+ $this->excelName = $pExcelName;
78
+ $this->phpExcelName = $pPHPExcelName;
79
+ } else {
80
+ throw new PHPExcel_Calculation_Exception("Invalid parameters passed.");
81
+ }
82
+ }
83
+
84
+ /**
85
+ * Get Category (represented by CATEGORY_*)
86
+ *
87
+ * @return string
88
+ */
89
+ public function getCategory()
90
+ {
91
+ return $this->category;
92
+ }
93
+
94
+ /**
95
+ * Set Category (represented by CATEGORY_*)
96
+ *
97
+ * @param string $value
98
+ * @throws PHPExcel_Calculation_Exception
99
+ */
100
+ public function setCategory($value = null)
101
+ {
102
+ if (!is_null($value)) {
103
+ $this->category = $value;
104
+ } else {
105
+ throw new PHPExcel_Calculation_Exception("Invalid parameter passed.");
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Get Excel name
111
+ *
112
+ * @return string
113
+ */
114
+ public function getExcelName()
115
+ {
116
+ return $this->excelName;
117
+ }
118
+
119
+ /**
120
+ * Set Excel name
121
+ *
122
+ * @param string $value
123
+ */
124
+ public function setExcelName($value)
125
+ {
126
+ $this->excelName = $value;
127
+ }
128
+
129
+ /**
130
+ * Get PHPExcel name
131
+ *
132
+ * @return string
133
+ */
134
+ public function getPHPExcelName()
135
+ {
136
+ return $this->phpExcelName;
137
+ }
138
+
139
+ /**
140
+ * Set PHPExcel name
141
+ *
142
+ * @param string $value
143
+ */
144
+ public function setPHPExcelName($value)
145
+ {
146
+ $this->phpExcelName = $value;
147
+ }
148
+ }
classes/PHPExcel/Calculation/Functions.php ADDED
@@ -0,0 +1,760 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+
13
+ /** MAX_VALUE */
14
+ define('MAX_VALUE', 1.2e308);
15
+
16
+ /** 2 / PI */
17
+ define('M_2DIVPI', 0.63661977236758134307553505349006);
18
+
19
+ /** MAX_ITERATIONS */
20
+ define('MAX_ITERATIONS', 256);
21
+
22
+ /** PRECISION */
23
+ define('PRECISION', 8.88E-016);
24
+
25
+
26
+ /**
27
+ * PHPExcel_Calculation_Functions
28
+ *
29
+ * Copyright (c) 2006 - 2015 PHPExcel
30
+ *
31
+ * This library is free software; you can redistribute it and/or
32
+ * modify it under the terms of the GNU Lesser General Public
33
+ * License as published by the Free Software Foundation; either
34
+ * version 2.1 of the License, or (at your option) any later version.
35
+ *
36
+ * This library is distributed in the hope that it will be useful,
37
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
38
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
39
+ * Lesser General Public License for more details.
40
+ *
41
+ * You should have received a copy of the GNU Lesser General Public
42
+ * License along with this library; if not, write to the Free Software
43
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
44
+ *
45
+ * @category PHPExcel
46
+ * @package PHPExcel_Calculation
47
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
48
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
49
+ * @version ##VERSION##, ##DATE##
50
+ */
51
+ class PHPExcel_Calculation_Functions
52
+ {
53
+
54
+ /** constants */
55
+ const COMPATIBILITY_EXCEL = 'Excel';
56
+ const COMPATIBILITY_GNUMERIC = 'Gnumeric';
57
+ const COMPATIBILITY_OPENOFFICE = 'OpenOfficeCalc';
58
+
59
+ const RETURNDATE_PHP_NUMERIC = 'P';
60
+ const RETURNDATE_PHP_OBJECT = 'O';
61
+ const RETURNDATE_EXCEL = 'E';
62
+
63
+
64
+ /**
65
+ * Compatibility mode to use for error checking and responses
66
+ *
67
+ * @access private
68
+ * @var string
69
+ */
70
+ protected static $compatibilityMode = self::COMPATIBILITY_EXCEL;
71
+
72
+ /**
73
+ * Data Type to use when returning date values
74
+ *
75
+ * @access private
76
+ * @var string
77
+ */
78
+ protected static $returnDateType = self::RETURNDATE_EXCEL;
79
+
80
+ /**
81
+ * List of error codes
82
+ *
83
+ * @access private
84
+ * @var array
85
+ */
86
+ protected static $errorCodes = array(
87
+ 'null' => '#NULL!',
88
+ 'divisionbyzero' => '#DIV/0!',
89
+ 'value' => '#VALUE!',
90
+ 'reference' => '#REF!',
91
+ 'name' => '#NAME?',
92
+ 'num' => '#NUM!',
93
+ 'na' => '#N/A',
94
+ 'gettingdata' => '#GETTING_DATA'
95
+ );
96
+
97
+
98
+ /**
99
+ * Set the Compatibility Mode
100
+ *
101
+ * @access public
102
+ * @category Function Configuration
103
+ * @param string $compatibilityMode Compatibility Mode
104
+ * Permitted values are:
105
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
106
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
107
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
108
+ * @return boolean (Success or Failure)
109
+ */
110
+ public static function setCompatibilityMode($compatibilityMode)
111
+ {
112
+ if (($compatibilityMode == self::COMPATIBILITY_EXCEL) ||
113
+ ($compatibilityMode == self::COMPATIBILITY_GNUMERIC) ||
114
+ ($compatibilityMode == self::COMPATIBILITY_OPENOFFICE)) {
115
+ self::$compatibilityMode = $compatibilityMode;
116
+ return true;
117
+ }
118
+ return false;
119
+ }
120
+
121
+
122
+ /**
123
+ * Return the current Compatibility Mode
124
+ *
125
+ * @access public
126
+ * @category Function Configuration
127
+ * @return string Compatibility Mode
128
+ * Possible Return values are:
129
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_EXCEL 'Excel'
130
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC 'Gnumeric'
131
+ * PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE 'OpenOfficeCalc'
132
+ */
133
+ public static function getCompatibilityMode()
134
+ {
135
+ return self::$compatibilityMode;
136
+ }
137
+
138
+
139
+ /**
140
+ * Set the Return Date Format used by functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
141
+ *
142
+ * @access public
143
+ * @category Function Configuration
144
+ * @param string $returnDateType Return Date Format
145
+ * Permitted values are:
146
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
147
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
148
+ * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
149
+ * @return boolean Success or failure
150
+ */
151
+ public static function setReturnDateType($returnDateType)
152
+ {
153
+ if (($returnDateType == self::RETURNDATE_PHP_NUMERIC) ||
154
+ ($returnDateType == self::RETURNDATE_PHP_OBJECT) ||
155
+ ($returnDateType == self::RETURNDATE_EXCEL)) {
156
+ self::$returnDateType = $returnDateType;
157
+ return true;
158
+ }
159
+ return false;
160
+ }
161
+
162
+
163
+ /**
164
+ * Return the current Return Date Format for functions that return a date/time (Excel, PHP Serialized Numeric or PHP Object)
165
+ *
166
+ * @access public
167
+ * @category Function Configuration
168
+ * @return string Return Date Format
169
+ * Possible Return values are:
170
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_NUMERIC 'P'
171
+ * PHPExcel_Calculation_Functions::RETURNDATE_PHP_OBJECT 'O'
172
+ * PHPExcel_Calculation_Functions::RETURNDATE_EXCEL 'E'
173
+ */
174
+ public static function getReturnDateType()
175
+ {
176
+ return self::$returnDateType;
177
+ }
178
+
179
+
180
+ /**
181
+ * DUMMY
182
+ *
183
+ * @access public
184
+ * @category Error Returns
185
+ * @return string #Not Yet Implemented
186
+ */
187
+ public static function DUMMY()
188
+ {
189
+ return '#Not Yet Implemented';
190
+ }
191
+
192
+
193
+ /**
194
+ * DIV0
195
+ *
196
+ * @access public
197
+ * @category Error Returns
198
+ * @return string #Not Yet Implemented
199
+ */
200
+ public static function DIV0()
201
+ {
202
+ return self::$errorCodes['divisionbyzero'];
203
+ }
204
+
205
+
206
+ /**
207
+ * NA
208
+ *
209
+ * Excel Function:
210
+ * =NA()
211
+ *
212
+ * Returns the error value #N/A
213
+ * #N/A is the error value that means "no value is available."
214
+ *
215
+ * @access public
216
+ * @category Logical Functions
217
+ * @return string #N/A!
218
+ */
219
+ public static function NA()
220
+ {
221
+ return self::$errorCodes['na'];
222
+ }
223
+
224
+
225
+ /**
226
+ * NaN
227
+ *
228
+ * Returns the error value #NUM!
229
+ *
230
+ * @access public
231
+ * @category Error Returns
232
+ * @return string #NUM!
233
+ */
234
+ public static function NaN()
235
+ {
236
+ return self::$errorCodes['num'];
237
+ }
238
+
239
+
240
+ /**
241
+ * NAME
242
+ *
243
+ * Returns the error value #NAME?
244
+ *
245
+ * @access public
246
+ * @category Error Returns
247
+ * @return string #NAME?
248
+ */
249
+ public static function NAME()
250
+ {
251
+ return self::$errorCodes['name'];
252
+ }
253
+
254
+
255
+ /**
256
+ * REF
257
+ *
258
+ * Returns the error value #REF!
259
+ *
260
+ * @access public
261
+ * @category Error Returns
262
+ * @return string #REF!
263
+ */
264
+ public static function REF()
265
+ {
266
+ return self::$errorCodes['reference'];
267
+ }
268
+
269
+
270
+ /**
271
+ * NULL
272
+ *
273
+ * Returns the error value #NULL!
274
+ *
275
+ * @access public
276
+ * @category Error Returns
277
+ * @return string #NULL!
278
+ */
279
+ public static function NULL()
280
+ {
281
+ return self::$errorCodes['null'];
282
+ }
283
+
284
+
285
+ /**
286
+ * VALUE
287
+ *
288
+ * Returns the error value #VALUE!
289
+ *
290
+ * @access public
291
+ * @category Error Returns
292
+ * @return string #VALUE!
293
+ */
294
+ public static function VALUE()
295
+ {
296
+ return self::$errorCodes['value'];
297
+ }
298
+
299
+
300
+ public static function isMatrixValue($idx)
301
+ {
302
+ return ((substr_count($idx, '.') <= 1) || (preg_match('/\.[A-Z]/', $idx) > 0));
303
+ }
304
+
305
+
306
+ public static function isValue($idx)
307
+ {
308
+ return (substr_count($idx, '.') == 0);
309
+ }
310
+
311
+
312
+ public static function isCellValue($idx)
313
+ {
314
+ return (substr_count($idx, '.') > 1);
315
+ }
316
+
317
+
318
+ public static function ifCondition($condition)
319
+ {
320
+ $condition = PHPExcel_Calculation_Functions::flattenSingleValue($condition);
321
+ if (!isset($condition{0})) {
322
+ $condition = '=""';
323
+ }
324
+ if (!in_array($condition{0}, array('>', '<', '='))) {
325
+ if (!is_numeric($condition)) {
326
+ $condition = PHPExcel_Calculation::wrapResult(strtoupper($condition));
327
+ }
328
+ return '=' . $condition;
329
+ } else {
330
+ preg_match('/([<>=]+)(.*)/', $condition, $matches);
331
+ list(, $operator, $operand) = $matches;
332
+
333
+ if (!is_numeric($operand)) {
334
+ $operand = str_replace('"', '""', $operand);
335
+ $operand = PHPExcel_Calculation::wrapResult(strtoupper($operand));
336
+ }
337
+
338
+ return $operator.$operand;
339
+ }
340
+ }
341
+
342
+ /**
343
+ * ERROR_TYPE
344
+ *
345
+ * @param mixed $value Value to check
346
+ * @return boolean
347
+ */
348
+ public static function ERROR_TYPE($value = '')
349
+ {
350
+ $value = self::flattenSingleValue($value);
351
+
352
+ $i = 1;
353
+ foreach (self::$errorCodes as $errorCode) {
354
+ if ($value === $errorCode) {
355
+ return $i;
356
+ }
357
+ ++$i;
358
+ }
359
+ return self::NA();
360
+ }
361
+
362
+
363
+ /**
364
+ * IS_BLANK
365
+ *
366
+ * @param mixed $value Value to check
367
+ * @return boolean
368
+ */
369
+ public static function IS_BLANK($value = null)
370
+ {
371
+ if (!is_null($value)) {
372
+ $value = self::flattenSingleValue($value);
373
+ }
374
+
375
+ return is_null($value);
376
+ }
377
+
378
+
379
+ /**
380
+ * IS_ERR
381
+ *
382
+ * @param mixed $value Value to check
383
+ * @return boolean
384
+ */
385
+ public static function IS_ERR($value = '')
386
+ {
387
+ $value = self::flattenSingleValue($value);
388
+
389
+ return self::IS_ERROR($value) && (!self::IS_NA($value));
390
+ }
391
+
392
+
393
+ /**
394
+ * IS_ERROR
395
+ *
396
+ * @param mixed $value Value to check
397
+ * @return boolean
398
+ */
399
+ public static function IS_ERROR($value = '')
400
+ {
401
+ $value = self::flattenSingleValue($value);
402
+
403
+ if (!is_string($value)) {
404
+ return false;
405
+ }
406
+ return in_array($value, array_values(self::$errorCodes));
407
+ }
408
+
409
+
410
+ /**
411
+ * IS_NA
412
+ *
413
+ * @param mixed $value Value to check
414
+ * @return boolean
415
+ */
416
+ public static function IS_NA($value = '')
417
+ {
418
+ $value = self::flattenSingleValue($value);
419
+
420
+ return ($value === self::NA());
421
+ }
422
+
423
+
424
+ /**
425
+ * IS_EVEN
426
+ *
427
+ * @param mixed $value Value to check
428
+ * @return boolean
429
+ */
430
+ public static function IS_EVEN($value = null)
431
+ {
432
+ $value = self::flattenSingleValue($value);
433
+
434
+ if ($value === null) {
435
+ return self::NAME();
436
+ } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) {
437
+ return self::VALUE();
438
+ }
439
+
440
+ return ($value % 2 == 0);
441
+ }
442
+
443
+
444
+ /**
445
+ * IS_ODD
446
+ *
447
+ * @param mixed $value Value to check
448
+ * @return boolean
449
+ */
450
+ public static function IS_ODD($value = null)
451
+ {
452
+ $value = self::flattenSingleValue($value);
453
+
454
+ if ($value === null) {
455
+ return self::NAME();
456
+ } elseif ((is_bool($value)) || ((is_string($value)) && (!is_numeric($value)))) {
457
+ return self::VALUE();
458
+ }
459
+
460
+ return (abs($value) % 2 == 1);
461
+ }
462
+
463
+
464
+ /**
465
+ * IS_NUMBER
466
+ *
467
+ * @param mixed $value Value to check
468
+ * @return boolean
469
+ */
470
+ public static function IS_NUMBER($value = null)
471
+ {
472
+ $value = self::flattenSingleValue($value);
473
+
474
+ if (is_string($value)) {
475
+ return false;
476
+ }
477
+ return is_numeric($value);
478
+ }
479
+
480
+
481
+ /**
482
+ * IS_LOGICAL
483
+ *
484
+ * @param mixed $value Value to check
485
+ * @return boolean
486
+ */
487
+ public static function IS_LOGICAL($value = null)
488
+ {
489
+ $value = self::flattenSingleValue($value);
490
+
491
+ return is_bool($value);
492
+ }
493
+
494
+
495
+ /**
496
+ * IS_TEXT
497
+ *
498
+ * @param mixed $value Value to check
499
+ * @return boolean
500
+ */
501
+ public static function IS_TEXT($value = null)
502
+ {
503
+ $value = self::flattenSingleValue($value);
504
+
505
+ return (is_string($value) && !self::IS_ERROR($value));
506
+ }
507
+
508
+
509
+ /**
510
+ * IS_NONTEXT
511
+ *
512
+ * @param mixed $value Value to check
513
+ * @return boolean
514
+ */
515
+ public static function IS_NONTEXT($value = null)
516
+ {
517
+ return !self::IS_TEXT($value);
518
+ }
519
+
520
+
521
+ /**
522
+ * VERSION
523
+ *
524
+ * @return string Version information
525
+ */
526
+ public static function VERSION()
527
+ {
528
+ return 'PHPExcel ##VERSION##, ##DATE##';
529
+ }
530
+
531
+
532
+ /**
533
+ * N
534
+ *
535
+ * Returns a value converted to a number
536
+ *
537
+ * @param value The value you want converted
538
+ * @return number N converts values listed in the following table
539
+ * If value is or refers to N returns
540
+ * A number That number
541
+ * A date The serial number of that date
542
+ * TRUE 1
543
+ * FALSE 0
544
+ * An error value The error value
545
+ * Anything else 0
546
+ */
547
+ public static function N($value = null)
548
+ {
549
+ while (is_array($value)) {
550
+ $value = array_shift($value);
551
+ }
552
+
553
+ switch (gettype($value)) {
554
+ case 'double':
555
+ case 'float':
556
+ case 'integer':
557
+ return $value;
558
+ case 'boolean':
559
+ return (integer) $value;
560
+ case 'string':
561
+ // Errors
562
+ if ((strlen($value) > 0) && ($value{0} == '#')) {
563
+ return $value;
564
+ }
565
+ break;
566
+ }
567
+ return 0;
568
+ }
569
+
570
+
571
+ /**
572
+ * TYPE
573
+ *
574
+ * Returns a number that identifies the type of a value
575
+ *
576
+ * @param value The value you want tested
577
+ * @return number N converts values listed in the following table
578
+ * If value is or refers to N returns
579
+ * A number 1
580
+ * Text 2
581
+ * Logical Value 4
582
+ * An error value 16
583
+ * Array or Matrix 64
584
+ */
585
+ public static function TYPE($value = null)
586
+ {
587
+ $value = self::flattenArrayIndexed($value);
588
+ if (is_array($value) && (count($value) > 1)) {
589
+ end($value);
590
+ $a = key($value);
591
+ // Range of cells is an error
592
+ if (self::isCellValue($a)) {
593
+ return 16;
594
+ // Test for Matrix
595
+ } elseif (self::isMatrixValue($a)) {
596
+ return 64;
597
+ }
598
+ } elseif (empty($value)) {
599
+ // Empty Cell
600
+ return 1;
601
+ }
602
+ $value = self::flattenSingleValue($value);
603
+
604
+ if (($value === null) || (is_float($value)) || (is_int($value))) {
605
+ return 1;
606
+ } elseif (is_bool($value)) {
607
+ return 4;
608
+ } elseif (is_array($value)) {
609
+ return 64;
610
+ } elseif (is_string($value)) {
611
+ // Errors
612
+ if ((strlen($value) > 0) && ($value{0} == '#')) {
613
+ return 16;
614
+ }
615
+ return 2;
616
+ }
617
+ return 0;
618
+ }
619
+
620
+
621
+ /**
622
+ * Convert a multi-dimensional array to a simple 1-dimensional array
623
+ *
624
+ * @param array $array Array to be flattened
625
+ * @return array Flattened array
626
+ */
627
+ public static function flattenArray($array)
628
+ {
629
+ if (!is_array($array)) {
630
+ return (array) $array;
631
+ }
632
+
633
+ $arrayValues = array();
634
+ foreach ($array as $value) {
635
+ if (is_array($value)) {
636
+ foreach ($value as $val) {
637
+ if (is_array($val)) {
638
+ foreach ($val as $v) {
639
+ $arrayValues[] = $v;
640
+ }
641
+ } else {
642
+ $arrayValues[] = $val;
643
+ }
644
+ }
645
+ } else {
646
+ $arrayValues[] = $value;
647
+ }
648
+ }
649
+
650
+ return $arrayValues;
651
+ }
652
+
653
+
654
+ /**
655
+ * Convert a multi-dimensional array to a simple 1-dimensional array, but retain an element of indexing
656
+ *
657
+ * @param array $array Array to be flattened
658
+ * @return array Flattened array
659
+ */
660
+ public static function flattenArrayIndexed($array)
661
+ {
662
+ if (!is_array($array)) {
663
+ return (array) $array;
664
+ }
665
+
666
+ $arrayValues = array();
667
+ foreach ($array as $k1 => $value) {
668
+ if (is_array($value)) {
669
+ foreach ($value as $k2 => $val) {
670
+ if (is_array($val)) {
671
+ foreach ($val as $k3 => $v) {
672
+ $arrayValues[$k1.'.'.$k2.'.'.$k3] = $v;
673
+ }
674
+ } else {
675
+ $arrayValues[$k1.'.'.$k2] = $val;
676
+ }
677
+ }
678
+ } else {
679
+ $arrayValues[$k1] = $value;
680
+ }
681
+ }
682
+
683
+ return $arrayValues;
684
+ }
685
+
686
+
687
+ /**
688
+ * Convert an array to a single scalar value by extracting the first element
689
+ *
690
+ * @param mixed $value Array or scalar value
691
+ * @return mixed
692
+ */
693
+ public static function flattenSingleValue($value = '')
694
+ {
695
+ while (is_array($value)) {
696
+ $value = array_pop($value);
697
+ }
698
+
699
+ return $value;
700
+ }
701
+ }
702
+
703
+
704
+ //
705
+ // There are a few mathematical functions that aren't available on all versions of PHP for all platforms
706
+ // These functions aren't available in Windows implementations of PHP prior to version 5.3.0
707
+ // So we test if they do exist for this version of PHP/operating platform; and if not we create them
708
+ //
709
+ if (!function_exists('acosh')) {
710
+ function acosh($x)
711
+ {
712
+ return 2 * log(sqrt(($x + 1) / 2) + sqrt(($x - 1) / 2));
713
+ } // function acosh()
714
+ }
715
+
716
+ if (!function_exists('asinh')) {
717
+ function asinh($x)
718
+ {
719
+ return log($x + sqrt(1 + $x * $x));
720
+ } // function asinh()
721
+ }
722
+
723
+ if (!function_exists('atanh')) {
724
+ function atanh($x)
725
+ {
726
+ return (log(1 + $x) - log(1 - $x)) / 2;
727
+ } // function atanh()
728
+ }
729
+
730
+
731
+ //
732
+ // Strangely, PHP doesn't have a mb_str_replace multibyte function
733
+ // As we'll only ever use this function with UTF-8 characters, we can simply "hard-code" the character set
734
+ //
735
+ if ((!function_exists('mb_str_replace')) &&
736
+ (function_exists('mb_substr')) && (function_exists('mb_strlen')) && (function_exists('mb_strpos'))) {
737
+ function mb_str_replace($search, $replace, $subject)
738
+ {
739
+ if (is_array($subject)) {
740
+ $ret = array();
741
+ foreach ($subject as $key => $val) {
742
+ $ret[$key] = mb_str_replace($search, $replace, $val);
743
+ }
744
+ return $ret;
745
+ }
746
+
747
+ foreach ((array) $search as $key => $s) {
748
+ if ($s == '' && $s !== 0) {
749
+ continue;
750
+ }
751
+ $r = !is_array($replace) ? $replace : (array_key_exists($key, $replace) ? $replace[$key] : '');
752
+ $pos = mb_strpos($subject, $s, 0, 'UTF-8');
753
+ while ($pos !== false) {
754
+ $subject = mb_substr($subject, 0, $pos, 'UTF-8') . $r . mb_substr($subject, $pos + mb_strlen($s, 'UTF-8'), 65535, 'UTF-8');
755
+ $pos = mb_strpos($subject, $s, $pos + mb_strlen($r, 'UTF-8'), 'UTF-8');
756
+ }
757
+ }
758
+ return $subject;
759
+ }
760
+ }
classes/PHPExcel/Calculation/Logical.php ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+ /**
13
+ * PHPExcel_Calculation_Logical
14
+ *
15
+ * Copyright (c) 2006 - 2015 PHPExcel
16
+ *
17
+ * This library is free software; you can redistribute it and/or
18
+ * modify it under the terms of the GNU Lesser General Public
19
+ * License as published by the Free Software Foundation; either
20
+ * version 2.1 of the License, or (at your option) any later version.
21
+ *
22
+ * This library is distributed in the hope that it will be useful,
23
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25
+ * Lesser General Public License for more details.
26
+ *
27
+ * You should have received a copy of the GNU Lesser General Public
28
+ * License along with this library; if not, write to the Free Software
29
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30
+ *
31
+ * @category PHPExcel
32
+ * @package PHPExcel_Calculation
33
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
34
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
35
+ * @version ##VERSION##, ##DATE##
36
+ */
37
+ class PHPExcel_Calculation_Logical
38
+ {
39
+ /**
40
+ * TRUE
41
+ *
42
+ * Returns the boolean TRUE.
43
+ *
44
+ * Excel Function:
45
+ * =TRUE()
46
+ *
47
+ * @access public
48
+ * @category Logical Functions
49
+ * @return boolean True
50
+ */
51
+ public static function TRUE()
52
+ {
53
+ return true;
54
+ }
55
+
56
+
57
+ /**
58
+ * FALSE
59
+ *
60
+ * Returns the boolean FALSE.
61
+ *
62
+ * Excel Function:
63
+ * =FALSE()
64
+ *
65
+ * @access public
66
+ * @category Logical Functions
67
+ * @return boolean False
68
+ */
69
+ public static function FALSE()
70
+ {
71
+ return false;
72
+ }
73
+
74
+
75
+ /**
76
+ * LOGICAL_AND
77
+ *
78
+ * Returns boolean TRUE if all its arguments are TRUE; returns FALSE if one or more argument is FALSE.
79
+ *
80
+ * Excel Function:
81
+ * =AND(logical1[,logical2[, ...]])
82
+ *
83
+ * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
84
+ * or references that contain logical values.
85
+ *
86
+ * Boolean arguments are treated as True or False as appropriate
87
+ * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
88
+ * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
89
+ * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
90
+ *
91
+ * @access public
92
+ * @category Logical Functions
93
+ * @param mixed $arg,... Data values
94
+ * @return boolean The logical AND of the arguments.
95
+ */
96
+ public static function LOGICAL_AND()
97
+ {
98
+ // Return value
99
+ $returnValue = true;
100
+
101
+ // Loop through the arguments
102
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
103
+ $argCount = -1;
104
+ foreach ($aArgs as $argCount => $arg) {
105
+ // Is it a boolean value?
106
+ if (is_bool($arg)) {
107
+ $returnValue = $returnValue && $arg;
108
+ } elseif ((is_numeric($arg)) && (!is_string($arg))) {
109
+ $returnValue = $returnValue && ($arg != 0);
110
+ } elseif (is_string($arg)) {
111
+ $arg = strtoupper($arg);
112
+ if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) {
113
+ $arg = true;
114
+ } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) {
115
+ $arg = false;
116
+ } else {
117
+ return PHPExcel_Calculation_Functions::VALUE();
118
+ }
119
+ $returnValue = $returnValue && ($arg != 0);
120
+ }
121
+ }
122
+
123
+ // Return
124
+ if ($argCount < 0) {
125
+ return PHPExcel_Calculation_Functions::VALUE();
126
+ }
127
+ return $returnValue;
128
+ }
129
+
130
+
131
+ /**
132
+ * LOGICAL_OR
133
+ *
134
+ * Returns boolean TRUE if any argument is TRUE; returns FALSE if all arguments are FALSE.
135
+ *
136
+ * Excel Function:
137
+ * =OR(logical1[,logical2[, ...]])
138
+ *
139
+ * The arguments must evaluate to logical values such as TRUE or FALSE, or the arguments must be arrays
140
+ * or references that contain logical values.
141
+ *
142
+ * Boolean arguments are treated as True or False as appropriate
143
+ * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
144
+ * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
145
+ * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
146
+ *
147
+ * @access public
148
+ * @category Logical Functions
149
+ * @param mixed $arg,... Data values
150
+ * @return boolean The logical OR of the arguments.
151
+ */
152
+ public static function LOGICAL_OR()
153
+ {
154
+ // Return value
155
+ $returnValue = false;
156
+
157
+ // Loop through the arguments
158
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
159
+ $argCount = -1;
160
+ foreach ($aArgs as $argCount => $arg) {
161
+ // Is it a boolean value?
162
+ if (is_bool($arg)) {
163
+ $returnValue = $returnValue || $arg;
164
+ } elseif ((is_numeric($arg)) && (!is_string($arg))) {
165
+ $returnValue = $returnValue || ($arg != 0);
166
+ } elseif (is_string($arg)) {
167
+ $arg = strtoupper($arg);
168
+ if (($arg == 'TRUE') || ($arg == PHPExcel_Calculation::getTRUE())) {
169
+ $arg = true;
170
+ } elseif (($arg == 'FALSE') || ($arg == PHPExcel_Calculation::getFALSE())) {
171
+ $arg = false;
172
+ } else {
173
+ return PHPExcel_Calculation_Functions::VALUE();
174
+ }
175
+ $returnValue = $returnValue || ($arg != 0);
176
+ }
177
+ }
178
+
179
+ // Return
180
+ if ($argCount < 0) {
181
+ return PHPExcel_Calculation_Functions::VALUE();
182
+ }
183
+ return $returnValue;
184
+ }
185
+
186
+
187
+ /**
188
+ * NOT
189
+ *
190
+ * Returns the boolean inverse of the argument.
191
+ *
192
+ * Excel Function:
193
+ * =NOT(logical)
194
+ *
195
+ * The argument must evaluate to a logical value such as TRUE or FALSE
196
+ *
197
+ * Boolean arguments are treated as True or False as appropriate
198
+ * Integer or floating point arguments are treated as True, except for 0 or 0.0 which are False
199
+ * If any argument value is a string, or a Null, the function returns a #VALUE! error, unless the string holds
200
+ * the value TRUE or FALSE, in which case it is evaluated as the corresponding boolean value
201
+ *
202
+ * @access public
203
+ * @category Logical Functions
204
+ * @param mixed $logical A value or expression that can be evaluated to TRUE or FALSE
205
+ * @return boolean The boolean inverse of the argument.
206
+ */
207
+ public static function NOT($logical = false)
208
+ {
209
+ $logical = PHPExcel_Calculation_Functions::flattenSingleValue($logical);
210
+ if (is_string($logical)) {
211
+ $logical = strtoupper($logical);
212
+ if (($logical == 'TRUE') || ($logical == PHPExcel_Calculation::getTRUE())) {
213
+ return false;
214
+ } elseif (($logical == 'FALSE') || ($logical == PHPExcel_Calculation::getFALSE())) {
215
+ return true;
216
+ } else {
217
+ return PHPExcel_Calculation_Functions::VALUE();
218
+ }
219
+ }
220
+
221
+ return !$logical;
222
+ }
223
+
224
+ /**
225
+ * STATEMENT_IF
226
+ *
227
+ * Returns one value if a condition you specify evaluates to TRUE and another value if it evaluates to FALSE.
228
+ *
229
+ * Excel Function:
230
+ * =IF(condition[,returnIfTrue[,returnIfFalse]])
231
+ *
232
+ * Condition is any value or expression that can be evaluated to TRUE or FALSE.
233
+ * For example, A10=100 is a logical expression; if the value in cell A10 is equal to 100,
234
+ * the expression evaluates to TRUE. Otherwise, the expression evaluates to FALSE.
235
+ * This argument can use any comparison calculation operator.
236
+ * ReturnIfTrue is the value that is returned if condition evaluates to TRUE.
237
+ * For example, if this argument is the text string "Within budget" and the condition argument evaluates to TRUE,
238
+ * then the IF function returns the text "Within budget"
239
+ * If condition is TRUE and ReturnIfTrue is blank, this argument returns 0 (zero). To display the word TRUE, use
240
+ * the logical value TRUE for this argument.
241
+ * ReturnIfTrue can be another formula.
242
+ * ReturnIfFalse is the value that is returned if condition evaluates to FALSE.
243
+ * For example, if this argument is the text string "Over budget" and the condition argument evaluates to FALSE,
244
+ * then the IF function returns the text "Over budget".
245
+ * If condition is FALSE and ReturnIfFalse is omitted, then the logical value FALSE is returned.
246
+ * If condition is FALSE and ReturnIfFalse is blank, then the value 0 (zero) is returned.
247
+ * ReturnIfFalse can be another formula.
248
+ *
249
+ * @access public
250
+ * @category Logical Functions
251
+ * @param mixed $condition Condition to evaluate
252
+ * @param mixed $returnIfTrue Value to return when condition is true
253
+ * @param mixed $returnIfFalse Optional value to return when condition is false
254
+ * @return mixed The value of returnIfTrue or returnIfFalse determined by condition
255
+ */
256
+ public static function STATEMENT_IF($condition = true, $returnIfTrue = 0, $returnIfFalse = false)
257
+ {
258
+ $condition = (is_null($condition)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($condition);
259
+ $returnIfTrue = (is_null($returnIfTrue)) ? 0 : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfTrue);
260
+ $returnIfFalse = (is_null($returnIfFalse)) ? false : PHPExcel_Calculation_Functions::flattenSingleValue($returnIfFalse);
261
+
262
+ return ($condition) ? $returnIfTrue : $returnIfFalse;
263
+ }
264
+
265
+
266
+ /**
267
+ * IFERROR
268
+ *
269
+ * Excel Function:
270
+ * =IFERROR(testValue,errorpart)
271
+ *
272
+ * @access public
273
+ * @category Logical Functions
274
+ * @param mixed $testValue Value to check, is also the value returned when no error
275
+ * @param mixed $errorpart Value to return when testValue is an error condition
276
+ * @return mixed The value of errorpart or testValue determined by error condition
277
+ */
278
+ public static function IFERROR($testValue = '', $errorpart = '')
279
+ {
280
+ $testValue = (is_null($testValue)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($testValue);
281
+ $errorpart = (is_null($errorpart)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($errorpart);
282
+
283
+ return self::STATEMENT_IF(PHPExcel_Calculation_Functions::IS_ERROR($testValue), $errorpart, $testValue);
284
+ }
285
+ }
classes/PHPExcel/Calculation/LookupRef.php ADDED
@@ -0,0 +1,879 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+ /**
13
+ * PHPExcel_Calculation_LookupRef
14
+ *
15
+ * Copyright (c) 2006 - 2015 PHPExcel
16
+ *
17
+ * This library is free software; you can redistribute it and/or
18
+ * modify it under the terms of the GNU Lesser General Public
19
+ * License as published by the Free Software Foundation; either
20
+ * version 2.1 of the License, or (at your option) any later version.
21
+ *
22
+ * This library is distributed in the hope that it will be useful,
23
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25
+ * Lesser General Public License for more details.
26
+ *
27
+ * You should have received a copy of the GNU Lesser General Public
28
+ * License along with this library; if not, write to the Free Software
29
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30
+ *
31
+ * @category PHPExcel
32
+ * @package PHPExcel_Calculation
33
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
34
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
35
+ * @version ##VERSION##, ##DATE##
36
+ */
37
+ class PHPExcel_Calculation_LookupRef
38
+ {
39
+ /**
40
+ * CELL_ADDRESS
41
+ *
42
+ * Creates a cell address as text, given specified row and column numbers.
43
+ *
44
+ * Excel Function:
45
+ * =ADDRESS(row, column, [relativity], [referenceStyle], [sheetText])
46
+ *
47
+ * @param row Row number to use in the cell reference
48
+ * @param column Column number to use in the cell reference
49
+ * @param relativity Flag indicating the type of reference to return
50
+ * 1 or omitted Absolute
51
+ * 2 Absolute row; relative column
52
+ * 3 Relative row; absolute column
53
+ * 4 Relative
54
+ * @param referenceStyle A logical value that specifies the A1 or R1C1 reference style.
55
+ * TRUE or omitted CELL_ADDRESS returns an A1-style reference
56
+ * FALSE CELL_ADDRESS returns an R1C1-style reference
57
+ * @param sheetText Optional Name of worksheet to use
58
+ * @return string
59
+ */
60
+ public static function CELL_ADDRESS($row, $column, $relativity = 1, $referenceStyle = true, $sheetText = '')
61
+ {
62
+ $row = PHPExcel_Calculation_Functions::flattenSingleValue($row);
63
+ $column = PHPExcel_Calculation_Functions::flattenSingleValue($column);
64
+ $relativity = PHPExcel_Calculation_Functions::flattenSingleValue($relativity);
65
+ $sheetText = PHPExcel_Calculation_Functions::flattenSingleValue($sheetText);
66
+
67
+ if (($row < 1) || ($column < 1)) {
68
+ return PHPExcel_Calculation_Functions::VALUE();
69
+ }
70
+
71
+ if ($sheetText > '') {
72
+ if (strpos($sheetText, ' ') !== false) {
73
+ $sheetText = "'".$sheetText."'";
74
+ }
75
+ $sheetText .='!';
76
+ }
77
+ if ((!is_bool($referenceStyle)) || $referenceStyle) {
78
+ $rowRelative = $columnRelative = '$';
79
+ $column = PHPExcel_Cell::stringFromColumnIndex($column-1);
80
+ if (($relativity == 2) || ($relativity == 4)) {
81
+ $columnRelative = '';
82
+ }
83
+ if (($relativity == 3) || ($relativity == 4)) {
84
+ $rowRelative = '';
85
+ }
86
+ return $sheetText.$columnRelative.$column.$rowRelative.$row;
87
+ } else {
88
+ if (($relativity == 2) || ($relativity == 4)) {
89
+ $column = '['.$column.']';
90
+ }
91
+ if (($relativity == 3) || ($relativity == 4)) {
92
+ $row = '['.$row.']';
93
+ }
94
+ return $sheetText.'R'.$row.'C'.$column;
95
+ }
96
+ }
97
+
98
+
99
+ /**
100
+ * COLUMN
101
+ *
102
+ * Returns the column number of the given cell reference
103
+ * If the cell reference is a range of cells, COLUMN returns the column numbers of each column in the reference as a horizontal array.
104
+ * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
105
+ * reference of the cell in which the COLUMN function appears; otherwise this function returns 0.
106
+ *
107
+ * Excel Function:
108
+ * =COLUMN([cellAddress])
109
+ *
110
+ * @param cellAddress A reference to a range of cells for which you want the column numbers
111
+ * @return integer or array of integer
112
+ */
113
+ public static function COLUMN($cellAddress = null)
114
+ {
115
+ if (is_null($cellAddress) || trim($cellAddress) === '') {
116
+ return 0;
117
+ }
118
+
119
+ if (is_array($cellAddress)) {
120
+ foreach ($cellAddress as $columnKey => $value) {
121
+ $columnKey = preg_replace('/[^a-z]/i', '', $columnKey);
122
+ return (integer) PHPExcel_Cell::columnIndexFromString($columnKey);
123
+ }
124
+ } else {
125
+ if (strpos($cellAddress, '!') !== false) {
126
+ list($sheet, $cellAddress) = explode('!', $cellAddress);
127
+ }
128
+ if (strpos($cellAddress, ':') !== false) {
129
+ list($startAddress, $endAddress) = explode(':', $cellAddress);
130
+ $startAddress = preg_replace('/[^a-z]/i', '', $startAddress);
131
+ $endAddress = preg_replace('/[^a-z]/i', '', $endAddress);
132
+ $returnValue = array();
133
+ do {
134
+ $returnValue[] = (integer) PHPExcel_Cell::columnIndexFromString($startAddress);
135
+ } while ($startAddress++ != $endAddress);
136
+ return $returnValue;
137
+ } else {
138
+ $cellAddress = preg_replace('/[^a-z]/i', '', $cellAddress);
139
+ return (integer) PHPExcel_Cell::columnIndexFromString($cellAddress);
140
+ }
141
+ }
142
+ }
143
+
144
+
145
+ /**
146
+ * COLUMNS
147
+ *
148
+ * Returns the number of columns in an array or reference.
149
+ *
150
+ * Excel Function:
151
+ * =COLUMNS(cellAddress)
152
+ *
153
+ * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of columns
154
+ * @return integer The number of columns in cellAddress
155
+ */
156
+ public static function COLUMNS($cellAddress = null)
157
+ {
158
+ if (is_null($cellAddress) || $cellAddress === '') {
159
+ return 1;
160
+ } elseif (!is_array($cellAddress)) {
161
+ return PHPExcel_Calculation_Functions::VALUE();
162
+ }
163
+
164
+ reset($cellAddress);
165
+ $isMatrix = (is_numeric(key($cellAddress)));
166
+ list($columns, $rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
167
+
168
+ if ($isMatrix) {
169
+ return $rows;
170
+ } else {
171
+ return $columns;
172
+ }
173
+ }
174
+
175
+
176
+ /**
177
+ * ROW
178
+ *
179
+ * Returns the row number of the given cell reference
180
+ * If the cell reference is a range of cells, ROW returns the row numbers of each row in the reference as a vertical array.
181
+ * If cell reference is omitted, and the function is being called through the calculation engine, then it is assumed to be the
182
+ * reference of the cell in which the ROW function appears; otherwise this function returns 0.
183
+ *
184
+ * Excel Function:
185
+ * =ROW([cellAddress])
186
+ *
187
+ * @param cellAddress A reference to a range of cells for which you want the row numbers
188
+ * @return integer or array of integer
189
+ */
190
+ public static function ROW($cellAddress = null)
191
+ {
192
+ if (is_null($cellAddress) || trim($cellAddress) === '') {
193
+ return 0;
194
+ }
195
+
196
+ if (is_array($cellAddress)) {
197
+ foreach ($cellAddress as $columnKey => $rowValue) {
198
+ foreach ($rowValue as $rowKey => $cellValue) {
199
+ return (integer) preg_replace('/[^0-9]/i', '', $rowKey);
200
+ }
201
+ }
202
+ } else {
203
+ if (strpos($cellAddress, '!') !== false) {
204
+ list($sheet, $cellAddress) = explode('!', $cellAddress);
205
+ }
206
+ if (strpos($cellAddress, ':') !== false) {
207
+ list($startAddress, $endAddress) = explode(':', $cellAddress);
208
+ $startAddress = preg_replace('/[^0-9]/', '', $startAddress);
209
+ $endAddress = preg_replace('/[^0-9]/', '', $endAddress);
210
+ $returnValue = array();
211
+ do {
212
+ $returnValue[][] = (integer) $startAddress;
213
+ } while ($startAddress++ != $endAddress);
214
+ return $returnValue;
215
+ } else {
216
+ list($cellAddress) = explode(':', $cellAddress);
217
+ return (integer) preg_replace('/[^0-9]/', '', $cellAddress);
218
+ }
219
+ }
220
+ }
221
+
222
+
223
+ /**
224
+ * ROWS
225
+ *
226
+ * Returns the number of rows in an array or reference.
227
+ *
228
+ * Excel Function:
229
+ * =ROWS(cellAddress)
230
+ *
231
+ * @param cellAddress An array or array formula, or a reference to a range of cells for which you want the number of rows
232
+ * @return integer The number of rows in cellAddress
233
+ */
234
+ public static function ROWS($cellAddress = null)
235
+ {
236
+ if (is_null($cellAddress) || $cellAddress === '') {
237
+ return 1;
238
+ } elseif (!is_array($cellAddress)) {
239
+ return PHPExcel_Calculation_Functions::VALUE();
240
+ }
241
+
242
+ reset($cellAddress);
243
+ $isMatrix = (is_numeric(key($cellAddress)));
244
+ list($columns, $rows) = PHPExcel_Calculation::_getMatrixDimensions($cellAddress);
245
+
246
+ if ($isMatrix) {
247
+ return $columns;
248
+ } else {
249
+ return $rows;
250
+ }
251
+ }
252
+
253
+
254
+ /**
255
+ * HYPERLINK
256
+ *
257
+ * Excel Function:
258
+ * =HYPERLINK(linkURL,displayName)
259
+ *
260
+ * @access public
261
+ * @category Logical Functions
262
+ * @param string $linkURL Value to check, is also the value returned when no error
263
+ * @param string $displayName Value to return when testValue is an error condition
264
+ * @param PHPExcel_Cell $pCell The cell to set the hyperlink in
265
+ * @return mixed The value of $displayName (or $linkURL if $displayName was blank)
266
+ */
267
+ public static function HYPERLINK($linkURL = '', $displayName = null, PHPExcel_Cell $pCell = null)
268
+ {
269
+ $args = func_get_args();
270
+ $pCell = array_pop($args);
271
+
272
+ $linkURL = (is_null($linkURL)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($linkURL);
273
+ $displayName = (is_null($displayName)) ? '' : PHPExcel_Calculation_Functions::flattenSingleValue($displayName);
274
+
275
+ if ((!is_object($pCell)) || (trim($linkURL) == '')) {
276
+ return PHPExcel_Calculation_Functions::REF();
277
+ }
278
+
279
+ if ((is_object($displayName)) || trim($displayName) == '') {
280
+ $displayName = $linkURL;
281
+ }
282
+
283
+ $pCell->getHyperlink()->setUrl($linkURL);
284
+ $pCell->getHyperlink()->setTooltip($displayName);
285
+
286
+ return $displayName;
287
+ }
288
+
289
+
290
+ /**
291
+ * INDIRECT
292
+ *
293
+ * Returns the reference specified by a text string.
294
+ * References are immediately evaluated to display their contents.
295
+ *
296
+ * Excel Function:
297
+ * =INDIRECT(cellAddress)
298
+ *
299
+ * NOTE - INDIRECT() does not yet support the optional a1 parameter introduced in Excel 2010
300
+ *
301
+ * @param cellAddress $cellAddress The cell address of the current cell (containing this formula)
302
+ * @param PHPExcel_Cell $pCell The current cell (containing this formula)
303
+ * @return mixed The cells referenced by cellAddress
304
+ *
305
+ * @todo Support for the optional a1 parameter introduced in Excel 2010
306
+ *
307
+ */
308
+ public static function INDIRECT($cellAddress = null, PHPExcel_Cell $pCell = null)
309
+ {
310
+ $cellAddress = PHPExcel_Calculation_Functions::flattenSingleValue($cellAddress);
311
+ if (is_null($cellAddress) || $cellAddress === '') {
312
+ return PHPExcel_Calculation_Functions::REF();
313
+ }
314
+
315
+ $cellAddress1 = $cellAddress;
316
+ $cellAddress2 = null;
317
+ if (strpos($cellAddress, ':') !== false) {
318
+ list($cellAddress1, $cellAddress2) = explode(':', $cellAddress);
319
+ }
320
+
321
+ if ((!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress1, $matches)) ||
322
+ ((!is_null($cellAddress2)) && (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_CELLREF.'$/i', $cellAddress2, $matches)))) {
323
+ if (!preg_match('/^'.PHPExcel_Calculation::CALCULATION_REGEXP_NAMEDRANGE.'$/i', $cellAddress1, $matches)) {
324
+ return PHPExcel_Calculation_Functions::REF();
325
+ }
326
+
327
+ if (strpos($cellAddress, '!') !== false) {
328
+ list($sheetName, $cellAddress) = explode('!', $cellAddress);
329
+ $sheetName = trim($sheetName, "'");
330
+ $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
331
+ } else {
332
+ $pSheet = $pCell->getWorksheet();
333
+ }
334
+
335
+ return PHPExcel_Calculation::getInstance()->extractNamedRange($cellAddress, $pSheet, false);
336
+ }
337
+
338
+ if (strpos($cellAddress, '!') !== false) {
339
+ list($sheetName, $cellAddress) = explode('!', $cellAddress);
340
+ $sheetName = trim($sheetName, "'");
341
+ $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
342
+ } else {
343
+ $pSheet = $pCell->getWorksheet();
344
+ }
345
+
346
+ return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
347
+ }
348
+
349
+
350
+ /**
351
+ * OFFSET
352
+ *
353
+ * Returns a reference to a range that is a specified number of rows and columns from a cell or range of cells.
354
+ * The reference that is returned can be a single cell or a range of cells. You can specify the number of rows and
355
+ * the number of columns to be returned.
356
+ *
357
+ * Excel Function:
358
+ * =OFFSET(cellAddress, rows, cols, [height], [width])
359
+ *
360
+ * @param cellAddress The reference from which you want to base the offset. Reference must refer to a cell or
361
+ * range of adjacent cells; otherwise, OFFSET returns the #VALUE! error value.
362
+ * @param rows The number of rows, up or down, that you want the upper-left cell to refer to.
363
+ * Using 5 as the rows argument specifies that the upper-left cell in the reference is
364
+ * five rows below reference. Rows can be positive (which means below the starting reference)
365
+ * or negative (which means above the starting reference).
366
+ * @param cols The number of columns, to the left or right, that you want the upper-left cell of the result
367
+ * to refer to. Using 5 as the cols argument specifies that the upper-left cell in the
368
+ * reference is five columns to the right of reference. Cols can be positive (which means
369
+ * to the right of the starting reference) or negative (which means to the left of the
370
+ * starting reference).
371
+ * @param height The height, in number of rows, that you want the returned reference to be. Height must be a positive number.
372
+ * @param width The width, in number of columns, that you want the returned reference to be. Width must be a positive number.
373
+ * @return string A reference to a cell or range of cells
374
+ */
375
+ public static function OFFSET($cellAddress = null, $rows = 0, $columns = 0, $height = null, $width = null)
376
+ {
377
+ $rows = PHPExcel_Calculation_Functions::flattenSingleValue($rows);
378
+ $columns = PHPExcel_Calculation_Functions::flattenSingleValue($columns);
379
+ $height = PHPExcel_Calculation_Functions::flattenSingleValue($height);
380
+ $width = PHPExcel_Calculation_Functions::flattenSingleValue($width);
381
+ if ($cellAddress == null) {
382
+ return 0;
383
+ }
384
+
385
+ $args = func_get_args();
386
+ $pCell = array_pop($args);
387
+ if (!is_object($pCell)) {
388
+ return PHPExcel_Calculation_Functions::REF();
389
+ }
390
+
391
+ $sheetName = null;
392
+ if (strpos($cellAddress, "!")) {
393
+ list($sheetName, $cellAddress) = explode("!", $cellAddress);
394
+ $sheetName = trim($sheetName, "'");
395
+ }
396
+ if (strpos($cellAddress, ":")) {
397
+ list($startCell, $endCell) = explode(":", $cellAddress);
398
+ } else {
399
+ $startCell = $endCell = $cellAddress;
400
+ }
401
+ list($startCellColumn, $startCellRow) = PHPExcel_Cell::coordinateFromString($startCell);
402
+ list($endCellColumn, $endCellRow) = PHPExcel_Cell::coordinateFromString($endCell);
403
+
404
+ $startCellRow += $rows;
405
+ $startCellColumn = PHPExcel_Cell::columnIndexFromString($startCellColumn) - 1;
406
+ $startCellColumn += $columns;
407
+
408
+ if (($startCellRow <= 0) || ($startCellColumn < 0)) {
409
+ return PHPExcel_Calculation_Functions::REF();
410
+ }
411
+ $endCellColumn = PHPExcel_Cell::columnIndexFromString($endCellColumn) - 1;
412
+ if (($width != null) && (!is_object($width))) {
413
+ $endCellColumn = $startCellColumn + $width - 1;
414
+ } else {
415
+ $endCellColumn += $columns;
416
+ }
417
+ $startCellColumn = PHPExcel_Cell::stringFromColumnIndex($startCellColumn);
418
+
419
+ if (($height != null) && (!is_object($height))) {
420
+ $endCellRow = $startCellRow + $height - 1;
421
+ } else {
422
+ $endCellRow += $rows;
423
+ }
424
+
425
+ if (($endCellRow <= 0) || ($endCellColumn < 0)) {
426
+ return PHPExcel_Calculation_Functions::REF();
427
+ }
428
+ $endCellColumn = PHPExcel_Cell::stringFromColumnIndex($endCellColumn);
429
+
430
+ $cellAddress = $startCellColumn.$startCellRow;
431
+ if (($startCellColumn != $endCellColumn) || ($startCellRow != $endCellRow)) {
432
+ $cellAddress .= ':'.$endCellColumn.$endCellRow;
433
+ }
434
+
435
+ if ($sheetName !== null) {
436
+ $pSheet = $pCell->getWorksheet()->getParent()->getSheetByName($sheetName);
437
+ } else {
438
+ $pSheet = $pCell->getWorksheet();
439
+ }
440
+
441
+ return PHPExcel_Calculation::getInstance()->extractCellRange($cellAddress, $pSheet, false);
442
+ }
443
+
444
+
445
+ /**
446
+ * CHOOSE
447
+ *
448
+ * Uses lookup_value to return a value from the list of value arguments.
449
+ * Use CHOOSE to select one of up to 254 values based on the lookup_value.
450
+ *
451
+ * Excel Function:
452
+ * =CHOOSE(index_num, value1, [value2], ...)
453
+ *
454
+ * @param index_num Specifies which value argument is selected.
455
+ * Index_num must be a number between 1 and 254, or a formula or reference to a cell containing a number
456
+ * between 1 and 254.
457
+ * @param value1... Value1 is required, subsequent values are optional.
458
+ * Between 1 to 254 value arguments from which CHOOSE selects a value or an action to perform based on
459
+ * index_num. The arguments can be numbers, cell references, defined names, formulas, functions, or
460
+ * text.
461
+ * @return mixed The selected value
462
+ */
463
+ public static function CHOOSE()
464
+ {
465
+ $chooseArgs = func_get_args();
466
+ $chosenEntry = PHPExcel_Calculation_Functions::flattenArray(array_shift($chooseArgs));
467
+ $entryCount = count($chooseArgs) - 1;
468
+
469
+ if (is_array($chosenEntry)) {
470
+ $chosenEntry = array_shift($chosenEntry);
471
+ }
472
+ if ((is_numeric($chosenEntry)) && (!is_bool($chosenEntry))) {
473
+ --$chosenEntry;
474
+ } else {
475
+ return PHPExcel_Calculation_Functions::VALUE();
476
+ }
477
+ $chosenEntry = floor($chosenEntry);
478
+ if (($chosenEntry < 0) || ($chosenEntry > $entryCount)) {
479
+ return PHPExcel_Calculation_Functions::VALUE();
480
+ }
481
+
482
+ if (is_array($chooseArgs[$chosenEntry])) {
483
+ return PHPExcel_Calculation_Functions::flattenArray($chooseArgs[$chosenEntry]);
484
+ } else {
485
+ return $chooseArgs[$chosenEntry];
486
+ }
487
+ }
488
+
489
+
490
+ /**
491
+ * MATCH
492
+ *
493
+ * The MATCH function searches for a specified item in a range of cells
494
+ *
495
+ * Excel Function:
496
+ * =MATCH(lookup_value, lookup_array, [match_type])
497
+ *
498
+ * @param lookup_value The value that you want to match in lookup_array
499
+ * @param lookup_array The range of cells being searched
500
+ * @param match_type The number -1, 0, or 1. -1 means above, 0 means exact match, 1 means below. If match_type is 1 or -1, the list has to be ordered.
501
+ * @return integer The relative position of the found item
502
+ */
503
+ public static function MATCH($lookup_value, $lookup_array, $match_type = 1)
504
+ {
505
+ $lookup_array = PHPExcel_Calculation_Functions::flattenArray($lookup_array);
506
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
507
+ $match_type = (is_null($match_type)) ? 1 : (int) PHPExcel_Calculation_Functions::flattenSingleValue($match_type);
508
+ // MATCH is not case sensitive
509
+ $lookup_value = strtolower($lookup_value);
510
+
511
+ // lookup_value type has to be number, text, or logical values
512
+ if ((!is_numeric($lookup_value)) && (!is_string($lookup_value)) && (!is_bool($lookup_value))) {
513
+ return PHPExcel_Calculation_Functions::NA();
514
+ }
515
+
516
+ // match_type is 0, 1 or -1
517
+ if (($match_type !== 0) && ($match_type !== -1) && ($match_type !== 1)) {
518
+ return PHPExcel_Calculation_Functions::NA();
519
+ }
520
+
521
+ // lookup_array should not be empty
522
+ $lookupArraySize = count($lookup_array);
523
+ if ($lookupArraySize <= 0) {
524
+ return PHPExcel_Calculation_Functions::NA();
525
+ }
526
+
527
+ // lookup_array should contain only number, text, or logical values, or empty (null) cells
528
+ foreach ($lookup_array as $i => $lookupArrayValue) {
529
+ // check the type of the value
530
+ if ((!is_numeric($lookupArrayValue)) && (!is_string($lookupArrayValue)) &&
531
+ (!is_bool($lookupArrayValue)) && (!is_null($lookupArrayValue))) {
532
+ return PHPExcel_Calculation_Functions::NA();
533
+ }
534
+ // convert strings to lowercase for case-insensitive testing
535
+ if (is_string($lookupArrayValue)) {
536
+ $lookup_array[$i] = strtolower($lookupArrayValue);
537
+ }
538
+ if ((is_null($lookupArrayValue)) && (($match_type == 1) || ($match_type == -1))) {
539
+ $lookup_array = array_slice($lookup_array, 0, $i-1);
540
+ }
541
+ }
542
+
543
+ // if match_type is 1 or -1, the list has to be ordered
544
+ if ($match_type == 1) {
545
+ asort($lookup_array);
546
+ $keySet = array_keys($lookup_array);
547
+ } elseif ($match_type == -1) {
548
+ arsort($lookup_array);
549
+ $keySet = array_keys($lookup_array);
550
+ }
551
+
552
+ // **
553
+ // find the match
554
+ // **
555
+ foreach ($lookup_array as $i => $lookupArrayValue) {
556
+ if (($match_type == 0) && ($lookupArrayValue == $lookup_value)) {
557
+ // exact match
558
+ return ++$i;
559
+ } elseif (($match_type == -1) && ($lookupArrayValue <= $lookup_value)) {
560
+ $i = array_search($i, $keySet);
561
+ // if match_type is -1 <=> find the smallest value that is greater than or equal to lookup_value
562
+ if ($i < 1) {
563
+ // 1st cell was already smaller than the lookup_value
564
+ break;
565
+ } else {
566
+ // the previous cell was the match
567
+ return $keySet[$i-1]+1;
568
+ }
569
+ } elseif (($match_type == 1) && ($lookupArrayValue >= $lookup_value)) {
570
+ $i = array_search($i, $keySet);
571
+ // if match_type is 1 <=> find the largest value that is less than or equal to lookup_value
572
+ if ($i < 1) {
573
+ // 1st cell was already bigger than the lookup_value
574
+ break;
575
+ } else {
576
+ // the previous cell was the match
577
+ return $keySet[$i-1]+1;
578
+ }
579
+ }
580
+ }
581
+
582
+ // unsuccessful in finding a match, return #N/A error value
583
+ return PHPExcel_Calculation_Functions::NA();
584
+ }
585
+
586
+
587
+ /**
588
+ * INDEX
589
+ *
590
+ * Uses an index to choose a value from a reference or array
591
+ *
592
+ * Excel Function:
593
+ * =INDEX(range_array, row_num, [column_num])
594
+ *
595
+ * @param range_array A range of cells or an array constant
596
+ * @param row_num The row in array from which to return a value. If row_num is omitted, column_num is required.
597
+ * @param column_num The column in array from which to return a value. If column_num is omitted, row_num is required.
598
+ * @return mixed the value of a specified cell or array of cells
599
+ */
600
+ public static function INDEX($arrayValues, $rowNum = 0, $columnNum = 0)
601
+ {
602
+ if (($rowNum < 0) || ($columnNum < 0)) {
603
+ return PHPExcel_Calculation_Functions::VALUE();
604
+ }
605
+
606
+ if (!is_array($arrayValues)) {
607
+ return PHPExcel_Calculation_Functions::REF();
608
+ }
609
+
610
+ $rowKeys = array_keys($arrayValues);
611
+ $columnKeys = @array_keys($arrayValues[$rowKeys[0]]);
612
+
613
+ if ($columnNum > count($columnKeys)) {
614
+ return PHPExcel_Calculation_Functions::VALUE();
615
+ } elseif ($columnNum == 0) {
616
+ if ($rowNum == 0) {
617
+ return $arrayValues;
618
+ }
619
+ $rowNum = $rowKeys[--$rowNum];
620
+ $returnArray = array();
621
+ foreach ($arrayValues as $arrayColumn) {
622
+ if (is_array($arrayColumn)) {
623
+ if (isset($arrayColumn[$rowNum])) {
624
+ $returnArray[] = $arrayColumn[$rowNum];
625
+ } else {
626
+ return $arrayValues[$rowNum];
627
+ }
628
+ } else {
629
+ return $arrayValues[$rowNum];
630
+ }
631
+ }
632
+ return $returnArray;
633
+ }
634
+ $columnNum = $columnKeys[--$columnNum];
635
+ if ($rowNum > count($rowKeys)) {
636
+ return PHPExcel_Calculation_Functions::VALUE();
637
+ } elseif ($rowNum == 0) {
638
+ return $arrayValues[$columnNum];
639
+ }
640
+ $rowNum = $rowKeys[--$rowNum];
641
+
642
+ return $arrayValues[$rowNum][$columnNum];
643
+ }
644
+
645
+
646
+ /**
647
+ * TRANSPOSE
648
+ *
649
+ * @param array $matrixData A matrix of values
650
+ * @return array
651
+ *
652
+ * Unlike the Excel TRANSPOSE function, which will only work on a single row or column, this function will transpose a full matrix.
653
+ */
654
+ public static function TRANSPOSE($matrixData)
655
+ {
656
+ $returnMatrix = array();
657
+ if (!is_array($matrixData)) {
658
+ $matrixData = array(array($matrixData));
659
+ }
660
+
661
+ $column = 0;
662
+ foreach ($matrixData as $matrixRow) {
663
+ $row = 0;
664
+ foreach ($matrixRow as $matrixCell) {
665
+ $returnMatrix[$row][$column] = $matrixCell;
666
+ ++$row;
667
+ }
668
+ ++$column;
669
+ }
670
+ return $returnMatrix;
671
+ }
672
+
673
+
674
+ private static function vlookupSort($a, $b)
675
+ {
676
+ reset($a);
677
+ $firstColumn = key($a);
678
+ if (($aLower = strtolower($a[$firstColumn])) == ($bLower = strtolower($b[$firstColumn]))) {
679
+ return 0;
680
+ }
681
+ return ($aLower < $bLower) ? -1 : 1;
682
+ }
683
+
684
+
685
+ /**
686
+ * VLOOKUP
687
+ * The VLOOKUP function searches for value in the left-most column of lookup_array and returns the value in the same row based on the index_number.
688
+ * @param lookup_value The value that you want to match in lookup_array
689
+ * @param lookup_array The range of cells being searched
690
+ * @param index_number The column number in table_array from which the matching value must be returned. The first column is 1.
691
+ * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
692
+ * @return mixed The value of the found cell
693
+ */
694
+ public static function VLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
695
+ {
696
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
697
+ $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
698
+ $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
699
+
700
+ // index_number must be greater than or equal to 1
701
+ if ($index_number < 1) {
702
+ return PHPExcel_Calculation_Functions::VALUE();
703
+ }
704
+
705
+ // index_number must be less than or equal to the number of columns in lookup_array
706
+ if ((!is_array($lookup_array)) || (empty($lookup_array))) {
707
+ return PHPExcel_Calculation_Functions::REF();
708
+ } else {
709
+ $f = array_keys($lookup_array);
710
+ $firstRow = array_pop($f);
711
+ if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
712
+ return PHPExcel_Calculation_Functions::REF();
713
+ } else {
714
+ $columnKeys = array_keys($lookup_array[$firstRow]);
715
+ $returnColumn = $columnKeys[--$index_number];
716
+ $firstColumn = array_shift($columnKeys);
717
+ }
718
+ }
719
+
720
+ if (!$not_exact_match) {
721
+ uasort($lookup_array, array('self', 'vlookupSort'));
722
+ }
723
+
724
+ $rowNumber = $rowValue = false;
725
+ foreach ($lookup_array as $rowKey => $rowData) {
726
+ if ((is_numeric($lookup_value) && is_numeric($rowData[$firstColumn]) && ($rowData[$firstColumn] > $lookup_value)) ||
727
+ (!is_numeric($lookup_value) && !is_numeric($rowData[$firstColumn]) && (strtolower($rowData[$firstColumn]) > strtolower($lookup_value)))) {
728
+ break;
729
+ }
730
+ $rowNumber = $rowKey;
731
+ $rowValue = $rowData[$firstColumn];
732
+ }
733
+
734
+ if ($rowNumber !== false) {
735
+ if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
736
+ // if an exact match is required, we have what we need to return an appropriate response
737
+ return PHPExcel_Calculation_Functions::NA();
738
+ } else {
739
+ // otherwise return the appropriate value
740
+ return $lookup_array[$rowNumber][$returnColumn];
741
+ }
742
+ }
743
+
744
+ return PHPExcel_Calculation_Functions::NA();
745
+ }
746
+
747
+
748
+ /**
749
+ * HLOOKUP
750
+ * The HLOOKUP function searches for value in the top-most row of lookup_array and returns the value in the same column based on the index_number.
751
+ * @param lookup_value The value that you want to match in lookup_array
752
+ * @param lookup_array The range of cells being searched
753
+ * @param index_number The row number in table_array from which the matching value must be returned. The first row is 1.
754
+ * @param not_exact_match Determines if you are looking for an exact match based on lookup_value.
755
+ * @return mixed The value of the found cell
756
+ */
757
+ public static function HLOOKUP($lookup_value, $lookup_array, $index_number, $not_exact_match = true)
758
+ {
759
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
760
+ $index_number = PHPExcel_Calculation_Functions::flattenSingleValue($index_number);
761
+ $not_exact_match = PHPExcel_Calculation_Functions::flattenSingleValue($not_exact_match);
762
+
763
+ // index_number must be greater than or equal to 1
764
+ if ($index_number < 1) {
765
+ return PHPExcel_Calculation_Functions::VALUE();
766
+ }
767
+
768
+ // index_number must be less than or equal to the number of columns in lookup_array
769
+ if ((!is_array($lookup_array)) || (empty($lookup_array))) {
770
+ return PHPExcel_Calculation_Functions::REF();
771
+ } else {
772
+ $f = array_keys($lookup_array);
773
+ $firstRow = array_pop($f);
774
+ if ((!is_array($lookup_array[$firstRow])) || ($index_number > count($lookup_array[$firstRow]))) {
775
+ return PHPExcel_Calculation_Functions::REF();
776
+ } else {
777
+ $columnKeys = array_keys($lookup_array[$firstRow]);
778
+ $firstkey = $f[0] - 1;
779
+ $returnColumn = $firstkey + $index_number;
780
+ $firstColumn = array_shift($f);
781
+ }
782
+ }
783
+
784
+ if (!$not_exact_match) {
785
+ $firstRowH = asort($lookup_array[$firstColumn]);
786
+ }
787
+
788
+ $rowNumber = $rowValue = false;
789
+ foreach ($lookup_array[$firstColumn] as $rowKey => $rowData) {
790
+ if ((is_numeric($lookup_value) && is_numeric($rowData) && ($rowData > $lookup_value)) ||
791
+ (!is_numeric($lookup_value) && !is_numeric($rowData) && (strtolower($rowData) > strtolower($lookup_value)))) {
792
+ break;
793
+ }
794
+ $rowNumber = $rowKey;
795
+ $rowValue = $rowData;
796
+ }
797
+
798
+ if ($rowNumber !== false) {
799
+ if ((!$not_exact_match) && ($rowValue != $lookup_value)) {
800
+ // if an exact match is required, we have what we need to return an appropriate response
801
+ return PHPExcel_Calculation_Functions::NA();
802
+ } else {
803
+ // otherwise return the appropriate value
804
+ return $lookup_array[$returnColumn][$rowNumber];
805
+ }
806
+ }
807
+
808
+ return PHPExcel_Calculation_Functions::NA();
809
+ }
810
+
811
+
812
+ /**
813
+ * LOOKUP
814
+ * The LOOKUP function searches for value either from a one-row or one-column range or from an array.
815
+ * @param lookup_value The value that you want to match in lookup_array
816
+ * @param lookup_vector The range of cells being searched
817
+ * @param result_vector The column from which the matching value must be returned
818
+ * @return mixed The value of the found cell
819
+ */
820
+ public static function LOOKUP($lookup_value, $lookup_vector, $result_vector = null)
821
+ {
822
+ $lookup_value = PHPExcel_Calculation_Functions::flattenSingleValue($lookup_value);
823
+
824
+ if (!is_array($lookup_vector)) {
825
+ return PHPExcel_Calculation_Functions::NA();
826
+ }
827
+ $lookupRows = count($lookup_vector);
828
+ $l = array_keys($lookup_vector);
829
+ $l = array_shift($l);
830
+ $lookupColumns = count($lookup_vector[$l]);
831
+ if ((($lookupRows == 1) && ($lookupColumns > 1)) || (($lookupRows == 2) && ($lookupColumns != 2))) {
832
+ $lookup_vector = self::TRANSPOSE($lookup_vector);
833
+ $lookupRows = count($lookup_vector);
834
+ $l = array_keys($lookup_vector);
835
+ $lookupColumns = count($lookup_vector[array_shift($l)]);
836
+ }
837
+
838
+ if (is_null($result_vector)) {
839
+ $result_vector = $lookup_vector;
840
+ }
841
+ $resultRows = count($result_vector);
842
+ $l = array_keys($result_vector);
843
+ $l = array_shift($l);
844
+ $resultColumns = count($result_vector[$l]);
845
+ if ((($resultRows == 1) && ($resultColumns > 1)) || (($resultRows == 2) && ($resultColumns != 2))) {
846
+ $result_vector = self::TRANSPOSE($result_vector);
847
+ $resultRows = count($result_vector);
848
+ $r = array_keys($result_vector);
849
+ $resultColumns = count($result_vector[array_shift($r)]);
850
+ }
851
+
852
+ if ($lookupRows == 2) {
853
+ $result_vector = array_pop($lookup_vector);
854
+ $lookup_vector = array_shift($lookup_vector);
855
+ }
856
+ if ($lookupColumns != 2) {
857
+ foreach ($lookup_vector as &$value) {
858
+ if (is_array($value)) {
859
+ $k = array_keys($value);
860
+ $key1 = $key2 = array_shift($k);
861
+ $key2++;
862
+ $dataValue1 = $value[$key1];
863
+ } else {
864
+ $key1 = 0;
865
+ $key2 = 1;
866
+ $dataValue1 = $value;
867
+ }
868
+ $dataValue2 = array_shift($result_vector);
869
+ if (is_array($dataValue2)) {
870
+ $dataValue2 = array_shift($dataValue2);
871
+ }
872
+ $value = array($key1 => $dataValue1, $key2 => $dataValue2);
873
+ }
874
+ unset($value);
875
+ }
876
+
877
+ return self::VLOOKUP($lookup_value, $lookup_vector, 2);
878
+ }
879
+ }
classes/PHPExcel/Calculation/MathTrig.php ADDED
@@ -0,0 +1,1459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+ /**
13
+ * PHPExcel_Calculation_MathTrig
14
+ *
15
+ * Copyright (c) 2006 - 2015 PHPExcel
16
+ *
17
+ * This library is free software; you can redistribute it and/or
18
+ * modify it under the terms of the GNU Lesser General Public
19
+ * License as published by the Free Software Foundation; either
20
+ * version 2.1 of the License, or (at your option) any later version.
21
+ *
22
+ * This library is distributed in the hope that it will be useful,
23
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
24
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25
+ * Lesser General Public License for more details.
26
+ *
27
+ * You should have received a copy of the GNU Lesser General Public
28
+ * License along with this library; if not, write to the Free Software
29
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
30
+ *
31
+ * @category PHPExcel
32
+ * @package PHPExcel_Calculation
33
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
34
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
35
+ * @version ##VERSION##, ##DATE##
36
+ */
37
+ class PHPExcel_Calculation_MathTrig
38
+ {
39
+ //
40
+ // Private method to return an array of the factors of the input value
41
+ //
42
+ private static function factors($value)
43
+ {
44
+ $startVal = floor(sqrt($value));
45
+
46
+ $factorArray = array();
47
+ for ($i = $startVal; $i > 1; --$i) {
48
+ if (($value % $i) == 0) {
49
+ $factorArray = array_merge($factorArray, self::factors($value / $i));
50
+ $factorArray = array_merge($factorArray, self::factors($i));
51
+ if ($i <= sqrt($value)) {
52
+ break;
53
+ }
54
+ }
55
+ }
56
+ if (!empty($factorArray)) {
57
+ rsort($factorArray);
58
+ return $factorArray;
59
+ } else {
60
+ return array((integer) $value);
61
+ }
62
+ }
63
+
64
+
65
+ private static function romanCut($num, $n)
66
+ {
67
+ return ($num - ($num % $n ) ) / $n;
68
+ }
69
+
70
+
71
+ /**
72
+ * ATAN2
73
+ *
74
+ * This function calculates the arc tangent of the two variables x and y. It is similar to
75
+ * calculating the arc tangent of y ÷ x, except that the signs of both arguments are used
76
+ * to determine the quadrant of the result.
77
+ * The arctangent is the angle from the x-axis to a line containing the origin (0, 0) and a
78
+ * point with coordinates (xCoordinate, yCoordinate). The angle is given in radians between
79
+ * -pi and pi, excluding -pi.
80
+ *
81
+ * Note that the Excel ATAN2() function accepts its arguments in the reverse order to the standard
82
+ * PHP atan2() function, so we need to reverse them here before calling the PHP atan() function.
83
+ *
84
+ * Excel Function:
85
+ * ATAN2(xCoordinate,yCoordinate)
86
+ *
87
+ * @access public
88
+ * @category Mathematical and Trigonometric Functions
89
+ * @param float $xCoordinate The x-coordinate of the point.
90
+ * @param float $yCoordinate The y-coordinate of the point.
91
+ * @return float The inverse tangent of the specified x- and y-coordinates.
92
+ */
93
+ public static function ATAN2($xCoordinate = null, $yCoordinate = null)
94
+ {
95
+ $xCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($xCoordinate);
96
+ $yCoordinate = PHPExcel_Calculation_Functions::flattenSingleValue($yCoordinate);
97
+
98
+ $xCoordinate = ($xCoordinate !== null) ? $xCoordinate : 0.0;
99
+ $yCoordinate = ($yCoordinate !== null) ? $yCoordinate : 0.0;
100
+
101
+ if (((is_numeric($xCoordinate)) || (is_bool($xCoordinate))) &&
102
+ ((is_numeric($yCoordinate))) || (is_bool($yCoordinate))) {
103
+ $xCoordinate = (float) $xCoordinate;
104
+ $yCoordinate = (float) $yCoordinate;
105
+
106
+ if (($xCoordinate == 0) && ($yCoordinate == 0)) {
107
+ return PHPExcel_Calculation_Functions::DIV0();
108
+ }
109
+
110
+ return atan2($yCoordinate, $xCoordinate);
111
+ }
112
+ return PHPExcel_Calculation_Functions::VALUE();
113
+ }
114
+
115
+
116
+ /**
117
+ * CEILING
118
+ *
119
+ * Returns number rounded up, away from zero, to the nearest multiple of significance.
120
+ * For example, if you want to avoid using pennies in your prices and your product is
121
+ * priced at $4.42, use the formula =CEILING(4.42,0.05) to round prices up to the
122
+ * nearest nickel.
123
+ *
124
+ * Excel Function:
125
+ * CEILING(number[,significance])
126
+ *
127
+ * @access public
128
+ * @category Mathematical and Trigonometric Functions
129
+ * @param float $number The number you want to round.
130
+ * @param float $significance The multiple to which you want to round.
131
+ * @return float Rounded Number
132
+ */
133
+ public static function CEILING($number, $significance = null)
134
+ {
135
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
136
+ $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance);
137
+
138
+ if ((is_null($significance)) &&
139
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
140
+ $significance = $number / abs($number);
141
+ }
142
+
143
+ if ((is_numeric($number)) && (is_numeric($significance))) {
144
+ if (($number == 0.0 ) || ($significance == 0.0)) {
145
+ return 0.0;
146
+ } elseif (self::SIGN($number) == self::SIGN($significance)) {
147
+ return ceil($number / $significance) * $significance;
148
+ } else {
149
+ return PHPExcel_Calculation_Functions::NaN();
150
+ }
151
+ }
152
+ return PHPExcel_Calculation_Functions::VALUE();
153
+ }
154
+
155
+
156
+ /**
157
+ * COMBIN
158
+ *
159
+ * Returns the number of combinations for a given number of items. Use COMBIN to
160
+ * determine the total possible number of groups for a given number of items.
161
+ *
162
+ * Excel Function:
163
+ * COMBIN(numObjs,numInSet)
164
+ *
165
+ * @access public
166
+ * @category Mathematical and Trigonometric Functions
167
+ * @param int $numObjs Number of different objects
168
+ * @param int $numInSet Number of objects in each combination
169
+ * @return int Number of combinations
170
+ */
171
+ public static function COMBIN($numObjs, $numInSet)
172
+ {
173
+ $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs);
174
+ $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet);
175
+
176
+ if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
177
+ if ($numObjs < $numInSet) {
178
+ return PHPExcel_Calculation_Functions::NaN();
179
+ } elseif ($numInSet < 0) {
180
+ return PHPExcel_Calculation_Functions::NaN();
181
+ }
182
+ return round(self::FACT($numObjs) / self::FACT($numObjs - $numInSet)) / self::FACT($numInSet);
183
+ }
184
+ return PHPExcel_Calculation_Functions::VALUE();
185
+ }
186
+
187
+
188
+ /**
189
+ * EVEN
190
+ *
191
+ * Returns number rounded up to the nearest even integer.
192
+ * You can use this function for processing items that come in twos. For example,
193
+ * a packing crate accepts rows of one or two items. The crate is full when
194
+ * the number of items, rounded up to the nearest two, matches the crate's
195
+ * capacity.
196
+ *
197
+ * Excel Function:
198
+ * EVEN(number)
199
+ *
200
+ * @access public
201
+ * @category Mathematical and Trigonometric Functions
202
+ * @param float $number Number to round
203
+ * @return int Rounded Number
204
+ */
205
+ public static function EVEN($number)
206
+ {
207
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
208
+
209
+ if (is_null($number)) {
210
+ return 0;
211
+ } elseif (is_bool($number)) {
212
+ $number = (int) $number;
213
+ }
214
+
215
+ if (is_numeric($number)) {
216
+ $significance = 2 * self::SIGN($number);
217
+ return (int) self::CEILING($number, $significance);
218
+ }
219
+ return PHPExcel_Calculation_Functions::VALUE();
220
+ }
221
+
222
+
223
+ /**
224
+ * FACT
225
+ *
226
+ * Returns the factorial of a number.
227
+ * The factorial of a number is equal to 1*2*3*...* number.
228
+ *
229
+ * Excel Function:
230
+ * FACT(factVal)
231
+ *
232
+ * @access public
233
+ * @category Mathematical and Trigonometric Functions
234
+ * @param float $factVal Factorial Value
235
+ * @return int Factorial
236
+ */
237
+ public static function FACT($factVal)
238
+ {
239
+ $factVal = PHPExcel_Calculation_Functions::flattenSingleValue($factVal);
240
+
241
+ if (is_numeric($factVal)) {
242
+ if ($factVal < 0) {
243
+ return PHPExcel_Calculation_Functions::NaN();
244
+ }
245
+ $factLoop = floor($factVal);
246
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
247
+ if ($factVal > $factLoop) {
248
+ return PHPExcel_Calculation_Functions::NaN();
249
+ }
250
+ }
251
+
252
+ $factorial = 1;
253
+ while ($factLoop > 1) {
254
+ $factorial *= $factLoop--;
255
+ }
256
+ return $factorial ;
257
+ }
258
+ return PHPExcel_Calculation_Functions::VALUE();
259
+ }
260
+
261
+
262
+ /**
263
+ * FACTDOUBLE
264
+ *
265
+ * Returns the double factorial of a number.
266
+ *
267
+ * Excel Function:
268
+ * FACTDOUBLE(factVal)
269
+ *
270
+ * @access public
271
+ * @category Mathematical and Trigonometric Functions
272
+ * @param float $factVal Factorial Value
273
+ * @return int Double Factorial
274
+ */
275
+ public static function FACTDOUBLE($factVal)
276
+ {
277
+ $factLoop = PHPExcel_Calculation_Functions::flattenSingleValue($factVal);
278
+
279
+ if (is_numeric($factLoop)) {
280
+ $factLoop = floor($factLoop);
281
+ if ($factVal < 0) {
282
+ return PHPExcel_Calculation_Functions::NaN();
283
+ }
284
+ $factorial = 1;
285
+ while ($factLoop > 1) {
286
+ $factorial *= $factLoop--;
287
+ --$factLoop;
288
+ }
289
+ return $factorial ;
290
+ }
291
+ return PHPExcel_Calculation_Functions::VALUE();
292
+ }
293
+
294
+
295
+ /**
296
+ * FLOOR
297
+ *
298
+ * Rounds number down, toward zero, to the nearest multiple of significance.
299
+ *
300
+ * Excel Function:
301
+ * FLOOR(number[,significance])
302
+ *
303
+ * @access public
304
+ * @category Mathematical and Trigonometric Functions
305
+ * @param float $number Number to round
306
+ * @param float $significance Significance
307
+ * @return float Rounded Number
308
+ */
309
+ public static function FLOOR($number, $significance = null)
310
+ {
311
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
312
+ $significance = PHPExcel_Calculation_Functions::flattenSingleValue($significance);
313
+
314
+ if ((is_null($significance)) &&
315
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC)) {
316
+ $significance = $number/abs($number);
317
+ }
318
+
319
+ if ((is_numeric($number)) && (is_numeric($significance))) {
320
+ if ($significance == 0.0) {
321
+ return PHPExcel_Calculation_Functions::DIV0();
322
+ } elseif ($number == 0.0) {
323
+ return 0.0;
324
+ } elseif (self::SIGN($number) == self::SIGN($significance)) {
325
+ return floor($number / $significance) * $significance;
326
+ } else {
327
+ return PHPExcel_Calculation_Functions::NaN();
328
+ }
329
+ }
330
+
331
+ return PHPExcel_Calculation_Functions::VALUE();
332
+ }
333
+
334
+
335
+ /**
336
+ * GCD
337
+ *
338
+ * Returns the greatest common divisor of a series of numbers.
339
+ * The greatest common divisor is the largest integer that divides both
340
+ * number1 and number2 without a remainder.
341
+ *
342
+ * Excel Function:
343
+ * GCD(number1[,number2[, ...]])
344
+ *
345
+ * @access public
346
+ * @category Mathematical and Trigonometric Functions
347
+ * @param mixed $arg,... Data values
348
+ * @return integer Greatest Common Divisor
349
+ */
350
+ public static function GCD()
351
+ {
352
+ $returnValue = 1;
353
+ $allValuesFactors = array();
354
+ // Loop through arguments
355
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) {
356
+ if (!is_numeric($value)) {
357
+ return PHPExcel_Calculation_Functions::VALUE();
358
+ } elseif ($value == 0) {
359
+ continue;
360
+ } elseif ($value < 0) {
361
+ return PHPExcel_Calculation_Functions::NaN();
362
+ }
363
+ $myFactors = self::factors($value);
364
+ $myCountedFactors = array_count_values($myFactors);
365
+ $allValuesFactors[] = $myCountedFactors;
366
+ }
367
+ $allValuesCount = count($allValuesFactors);
368
+ if ($allValuesCount == 0) {
369
+ return 0;
370
+ }
371
+
372
+ $mergedArray = $allValuesFactors[0];
373
+ for ($i=1; $i < $allValuesCount; ++$i) {
374
+ $mergedArray = array_intersect_key($mergedArray, $allValuesFactors[$i]);
375
+ }
376
+ $mergedArrayValues = count($mergedArray);
377
+ if ($mergedArrayValues == 0) {
378
+ return $returnValue;
379
+ } elseif ($mergedArrayValues > 1) {
380
+ foreach ($mergedArray as $mergedKey => $mergedValue) {
381
+ foreach ($allValuesFactors as $highestPowerTest) {
382
+ foreach ($highestPowerTest as $testKey => $testValue) {
383
+ if (($testKey == $mergedKey) && ($testValue < $mergedValue)) {
384
+ $mergedArray[$mergedKey] = $testValue;
385
+ $mergedValue = $testValue;
386
+ }
387
+ }
388
+ }
389
+ }
390
+
391
+ $returnValue = 1;
392
+ foreach ($mergedArray as $key => $value) {
393
+ $returnValue *= pow($key, $value);
394
+ }
395
+ return $returnValue;
396
+ } else {
397
+ $keys = array_keys($mergedArray);
398
+ $key = $keys[0];
399
+ $value = $mergedArray[$key];
400
+ foreach ($allValuesFactors as $testValue) {
401
+ foreach ($testValue as $mergedKey => $mergedValue) {
402
+ if (($mergedKey == $key) && ($mergedValue < $value)) {
403
+ $value = $mergedValue;
404
+ }
405
+ }
406
+ }
407
+ return pow($key, $value);
408
+ }
409
+ }
410
+
411
+
412
+ /**
413
+ * INT
414
+ *
415
+ * Casts a floating point value to an integer
416
+ *
417
+ * Excel Function:
418
+ * INT(number)
419
+ *
420
+ * @access public
421
+ * @category Mathematical and Trigonometric Functions
422
+ * @param float $number Number to cast to an integer
423
+ * @return integer Integer value
424
+ */
425
+ public static function INT($number)
426
+ {
427
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
428
+
429
+ if (is_null($number)) {
430
+ return 0;
431
+ } elseif (is_bool($number)) {
432
+ return (int) $number;
433
+ }
434
+ if (is_numeric($number)) {
435
+ return (int) floor($number);
436
+ }
437
+ return PHPExcel_Calculation_Functions::VALUE();
438
+ }
439
+
440
+
441
+ /**
442
+ * LCM
443
+ *
444
+ * Returns the lowest common multiplier of a series of numbers
445
+ * The least common multiple is the smallest positive integer that is a multiple
446
+ * of all integer arguments number1, number2, and so on. Use LCM to add fractions
447
+ * with different denominators.
448
+ *
449
+ * Excel Function:
450
+ * LCM(number1[,number2[, ...]])
451
+ *
452
+ * @access public
453
+ * @category Mathematical and Trigonometric Functions
454
+ * @param mixed $arg,... Data values
455
+ * @return int Lowest Common Multiplier
456
+ */
457
+ public static function LCM()
458
+ {
459
+ $returnValue = 1;
460
+ $allPoweredFactors = array();
461
+ // Loop through arguments
462
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $value) {
463
+ if (!is_numeric($value)) {
464
+ return PHPExcel_Calculation_Functions::VALUE();
465
+ }
466
+ if ($value == 0) {
467
+ return 0;
468
+ } elseif ($value < 0) {
469
+ return PHPExcel_Calculation_Functions::NaN();
470
+ }
471
+ $myFactors = self::factors(floor($value));
472
+ $myCountedFactors = array_count_values($myFactors);
473
+ $myPoweredFactors = array();
474
+ foreach ($myCountedFactors as $myCountedFactor => $myCountedPower) {
475
+ $myPoweredFactors[$myCountedFactor] = pow($myCountedFactor, $myCountedPower);
476
+ }
477
+ foreach ($myPoweredFactors as $myPoweredValue => $myPoweredFactor) {
478
+ if (array_key_exists($myPoweredValue, $allPoweredFactors)) {
479
+ if ($allPoweredFactors[$myPoweredValue] < $myPoweredFactor) {
480
+ $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
481
+ }
482
+ } else {
483
+ $allPoweredFactors[$myPoweredValue] = $myPoweredFactor;
484
+ }
485
+ }
486
+ }
487
+ foreach ($allPoweredFactors as $allPoweredFactor) {
488
+ $returnValue *= (integer) $allPoweredFactor;
489
+ }
490
+ return $returnValue;
491
+ }
492
+
493
+
494
+ /**
495
+ * LOG_BASE
496
+ *
497
+ * Returns the logarithm of a number to a specified base. The default base is 10.
498
+ *
499
+ * Excel Function:
500
+ * LOG(number[,base])
501
+ *
502
+ * @access public
503
+ * @category Mathematical and Trigonometric Functions
504
+ * @param float $number The positive real number for which you want the logarithm
505
+ * @param float $base The base of the logarithm. If base is omitted, it is assumed to be 10.
506
+ * @return float
507
+ */
508
+ public static function LOG_BASE($number = null, $base = 10)
509
+ {
510
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
511
+ $base = (is_null($base)) ? 10 : (float) PHPExcel_Calculation_Functions::flattenSingleValue($base);
512
+
513
+ if ((!is_numeric($base)) || (!is_numeric($number))) {
514
+ return PHPExcel_Calculation_Functions::VALUE();
515
+ }
516
+ if (($base <= 0) || ($number <= 0)) {
517
+ return PHPExcel_Calculation_Functions::NaN();
518
+ }
519
+ return log($number, $base);
520
+ }
521
+
522
+
523
+ /**
524
+ * MDETERM
525
+ *
526
+ * Returns the matrix determinant of an array.
527
+ *
528
+ * Excel Function:
529
+ * MDETERM(array)
530
+ *
531
+ * @access public
532
+ * @category Mathematical and Trigonometric Functions
533
+ * @param array $matrixValues A matrix of values
534
+ * @return float
535
+ */
536
+ public static function MDETERM($matrixValues)
537
+ {
538
+ $matrixData = array();
539
+ if (!is_array($matrixValues)) {
540
+ $matrixValues = array(array($matrixValues));
541
+ }
542
+
543
+ $row = $maxColumn = 0;
544
+ foreach ($matrixValues as $matrixRow) {
545
+ if (!is_array($matrixRow)) {
546
+ $matrixRow = array($matrixRow);
547
+ }
548
+ $column = 0;
549
+ foreach ($matrixRow as $matrixCell) {
550
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
551
+ return PHPExcel_Calculation_Functions::VALUE();
552
+ }
553
+ $matrixData[$column][$row] = $matrixCell;
554
+ ++$column;
555
+ }
556
+ if ($column > $maxColumn) {
557
+ $maxColumn = $column;
558
+ }
559
+ ++$row;
560
+ }
561
+ if ($row != $maxColumn) {
562
+ return PHPExcel_Calculation_Functions::VALUE();
563
+ }
564
+
565
+ try {
566
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData);
567
+ return $matrix->det();
568
+ } catch (PHPExcel_Exception $ex) {
569
+ return PHPExcel_Calculation_Functions::VALUE();
570
+ }
571
+ }
572
+
573
+
574
+ /**
575
+ * MINVERSE
576
+ *
577
+ * Returns the inverse matrix for the matrix stored in an array.
578
+ *
579
+ * Excel Function:
580
+ * MINVERSE(array)
581
+ *
582
+ * @access public
583
+ * @category Mathematical and Trigonometric Functions
584
+ * @param array $matrixValues A matrix of values
585
+ * @return array
586
+ */
587
+ public static function MINVERSE($matrixValues)
588
+ {
589
+ $matrixData = array();
590
+ if (!is_array($matrixValues)) {
591
+ $matrixValues = array(array($matrixValues));
592
+ }
593
+
594
+ $row = $maxColumn = 0;
595
+ foreach ($matrixValues as $matrixRow) {
596
+ if (!is_array($matrixRow)) {
597
+ $matrixRow = array($matrixRow);
598
+ }
599
+ $column = 0;
600
+ foreach ($matrixRow as $matrixCell) {
601
+ if ((is_string($matrixCell)) || ($matrixCell === null)) {
602
+ return PHPExcel_Calculation_Functions::VALUE();
603
+ }
604
+ $matrixData[$column][$row] = $matrixCell;
605
+ ++$column;
606
+ }
607
+ if ($column > $maxColumn) {
608
+ $maxColumn = $column;
609
+ }
610
+ ++$row;
611
+ }
612
+ if ($row != $maxColumn) {
613
+ return PHPExcel_Calculation_Functions::VALUE();
614
+ }
615
+
616
+ try {
617
+ $matrix = new PHPExcel_Shared_JAMA_Matrix($matrixData);
618
+ return $matrix->inverse()->getArray();
619
+ } catch (PHPExcel_Exception $ex) {
620
+ return PHPExcel_Calculation_Functions::VALUE();
621
+ }
622
+ }
623
+
624
+
625
+ /**
626
+ * MMULT
627
+ *
628
+ * @param array $matrixData1 A matrix of values
629
+ * @param array $matrixData2 A matrix of values
630
+ * @return array
631
+ */
632
+ public static function MMULT($matrixData1, $matrixData2)
633
+ {
634
+ $matrixAData = $matrixBData = array();
635
+ if (!is_array($matrixData1)) {
636
+ $matrixData1 = array(array($matrixData1));
637
+ }
638
+ if (!is_array($matrixData2)) {
639
+ $matrixData2 = array(array($matrixData2));
640
+ }
641
+
642
+ try {
643
+ $rowA = 0;
644
+ foreach ($matrixData1 as $matrixRow) {
645
+ if (!is_array($matrixRow)) {
646
+ $matrixRow = array($matrixRow);
647
+ }
648
+ $columnA = 0;
649
+ foreach ($matrixRow as $matrixCell) {
650
+ if ((!is_numeric($matrixCell)) || ($matrixCell === null)) {
651
+ return PHPExcel_Calculation_Functions::VALUE();
652
+ }
653
+ $matrixAData[$rowA][$columnA] = $matrixCell;
654
+ ++$columnA;
655
+ }
656
+ ++$rowA;
657
+ }
658
+ $matrixA = new PHPExcel_Shared_JAMA_Matrix($matrixAData);
659
+ $rowB = 0;
660
+ foreach ($matrixData2 as $matrixRow) {
661
+ if (!is_array($matrixRow)) {
662
+ $matrixRow = array($matrixRow);
663
+ }
664
+ $columnB = 0;
665
+ foreach ($matrixRow as $matrixCell) {
666
+ if ((!is_numeric($matrixCell)) || ($matrixCell === null)) {
667
+ return PHPExcel_Calculation_Functions::VALUE();
668
+ }
669
+ $matrixBData[$rowB][$columnB] = $matrixCell;
670
+ ++$columnB;
671
+ }
672
+ ++$rowB;
673
+ }
674
+ $matrixB = new PHPExcel_Shared_JAMA_Matrix($matrixBData);
675
+
676
+ if ($columnA != $rowB) {
677
+ return PHPExcel_Calculation_Functions::VALUE();
678
+ }
679
+
680
+ return $matrixA->times($matrixB)->getArray();
681
+ } catch (PHPExcel_Exception $ex) {
682
+ var_dump($ex->getMessage());
683
+ return PHPExcel_Calculation_Functions::VALUE();
684
+ }
685
+ }
686
+
687
+
688
+ /**
689
+ * MOD
690
+ *
691
+ * @param int $a Dividend
692
+ * @param int $b Divisor
693
+ * @return int Remainder
694
+ */
695
+ public static function MOD($a = 1, $b = 1)
696
+ {
697
+ $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
698
+ $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
699
+
700
+ if ($b == 0.0) {
701
+ return PHPExcel_Calculation_Functions::DIV0();
702
+ } elseif (($a < 0.0) && ($b > 0.0)) {
703
+ return $b - fmod(abs($a), $b);
704
+ } elseif (($a > 0.0) && ($b < 0.0)) {
705
+ return $b + fmod($a, abs($b));
706
+ }
707
+
708
+ return fmod($a, $b);
709
+ }
710
+
711
+
712
+ /**
713
+ * MROUND
714
+ *
715
+ * Rounds a number to the nearest multiple of a specified value
716
+ *
717
+ * @param float $number Number to round
718
+ * @param int $multiple Multiple to which you want to round $number
719
+ * @return float Rounded Number
720
+ */
721
+ public static function MROUND($number, $multiple)
722
+ {
723
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
724
+ $multiple = PHPExcel_Calculation_Functions::flattenSingleValue($multiple);
725
+
726
+ if ((is_numeric($number)) && (is_numeric($multiple))) {
727
+ if ($multiple == 0) {
728
+ return 0;
729
+ }
730
+ if ((self::SIGN($number)) == (self::SIGN($multiple))) {
731
+ $multiplier = 1 / $multiple;
732
+ return round($number * $multiplier) / $multiplier;
733
+ }
734
+ return PHPExcel_Calculation_Functions::NaN();
735
+ }
736
+ return PHPExcel_Calculation_Functions::VALUE();
737
+ }
738
+
739
+
740
+ /**
741
+ * MULTINOMIAL
742
+ *
743
+ * Returns the ratio of the factorial of a sum of values to the product of factorials.
744
+ *
745
+ * @param array of mixed Data Series
746
+ * @return float
747
+ */
748
+ public static function MULTINOMIAL()
749
+ {
750
+ $summer = 0;
751
+ $divisor = 1;
752
+ // Loop through arguments
753
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
754
+ // Is it a numeric value?
755
+ if (is_numeric($arg)) {
756
+ if ($arg < 1) {
757
+ return PHPExcel_Calculation_Functions::NaN();
758
+ }
759
+ $summer += floor($arg);
760
+ $divisor *= self::FACT($arg);
761
+ } else {
762
+ return PHPExcel_Calculation_Functions::VALUE();
763
+ }
764
+ }
765
+
766
+ // Return
767
+ if ($summer > 0) {
768
+ $summer = self::FACT($summer);
769
+ return $summer / $divisor;
770
+ }
771
+ return 0;
772
+ }
773
+
774
+
775
+ /**
776
+ * ODD
777
+ *
778
+ * Returns number rounded up to the nearest odd integer.
779
+ *
780
+ * @param float $number Number to round
781
+ * @return int Rounded Number
782
+ */
783
+ public static function ODD($number)
784
+ {
785
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
786
+
787
+ if (is_null($number)) {
788
+ return 1;
789
+ } elseif (is_bool($number)) {
790
+ return 1;
791
+ } elseif (is_numeric($number)) {
792
+ $significance = self::SIGN($number);
793
+ if ($significance == 0) {
794
+ return 1;
795
+ }
796
+
797
+ $result = self::CEILING($number, $significance);
798
+ if ($result == self::EVEN($result)) {
799
+ $result += $significance;
800
+ }
801
+
802
+ return (int) $result;
803
+ }
804
+ return PHPExcel_Calculation_Functions::VALUE();
805
+ }
806
+
807
+
808
+ /**
809
+ * POWER
810
+ *
811
+ * Computes x raised to the power y.
812
+ *
813
+ * @param float $x
814
+ * @param float $y
815
+ * @return float
816
+ */
817
+ public static function POWER($x = 0, $y = 2)
818
+ {
819
+ $x = PHPExcel_Calculation_Functions::flattenSingleValue($x);
820
+ $y = PHPExcel_Calculation_Functions::flattenSingleValue($y);
821
+
822
+ // Validate parameters
823
+ if ($x == 0.0 && $y == 0.0) {
824
+ return PHPExcel_Calculation_Functions::NaN();
825
+ } elseif ($x == 0.0 && $y < 0.0) {
826
+ return PHPExcel_Calculation_Functions::DIV0();
827
+ }
828
+
829
+ // Return
830
+ $result = pow($x, $y);
831
+ return (!is_nan($result) && !is_infinite($result)) ? $result : PHPExcel_Calculation_Functions::NaN();
832
+ }
833
+
834
+
835
+ /**
836
+ * PRODUCT
837
+ *
838
+ * PRODUCT returns the product of all the values and cells referenced in the argument list.
839
+ *
840
+ * Excel Function:
841
+ * PRODUCT(value1[,value2[, ...]])
842
+ *
843
+ * @access public
844
+ * @category Mathematical and Trigonometric Functions
845
+ * @param mixed $arg,... Data values
846
+ * @return float
847
+ */
848
+ public static function PRODUCT()
849
+ {
850
+ // Return value
851
+ $returnValue = null;
852
+
853
+ // Loop through arguments
854
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
855
+ // Is it a numeric value?
856
+ if ((is_numeric($arg)) && (!is_string($arg))) {
857
+ if (is_null($returnValue)) {
858
+ $returnValue = $arg;
859
+ } else {
860
+ $returnValue *= $arg;
861
+ }
862
+ }
863
+ }
864
+
865
+ // Return
866
+ if (is_null($returnValue)) {
867
+ return 0;
868
+ }
869
+ return $returnValue;
870
+ }
871
+
872
+
873
+ /**
874
+ * QUOTIENT
875
+ *
876
+ * QUOTIENT function returns the integer portion of a division. Numerator is the divided number
877
+ * and denominator is the divisor.
878
+ *
879
+ * Excel Function:
880
+ * QUOTIENT(value1[,value2[, ...]])
881
+ *
882
+ * @access public
883
+ * @category Mathematical and Trigonometric Functions
884
+ * @param mixed $arg,... Data values
885
+ * @return float
886
+ */
887
+ public static function QUOTIENT()
888
+ {
889
+ // Return value
890
+ $returnValue = null;
891
+
892
+ // Loop through arguments
893
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
894
+ // Is it a numeric value?
895
+ if ((is_numeric($arg)) && (!is_string($arg))) {
896
+ if (is_null($returnValue)) {
897
+ $returnValue = ($arg == 0) ? 0 : $arg;
898
+ } else {
899
+ if (($returnValue == 0) || ($arg == 0)) {
900
+ $returnValue = 0;
901
+ } else {
902
+ $returnValue /= $arg;
903
+ }
904
+ }
905
+ }
906
+ }
907
+
908
+ // Return
909
+ return intval($returnValue);
910
+ }
911
+
912
+
913
+ /**
914
+ * RAND
915
+ *
916
+ * @param int $min Minimal value
917
+ * @param int $max Maximal value
918
+ * @return int Random number
919
+ */
920
+ public static function RAND($min = 0, $max = 0)
921
+ {
922
+ $min = PHPExcel_Calculation_Functions::flattenSingleValue($min);
923
+ $max = PHPExcel_Calculation_Functions::flattenSingleValue($max);
924
+
925
+ if ($min == 0 && $max == 0) {
926
+ return (mt_rand(0, 10000000)) / 10000000;
927
+ } else {
928
+ return mt_rand($min, $max);
929
+ }
930
+ }
931
+
932
+
933
+ public static function ROMAN($aValue, $style = 0)
934
+ {
935
+ $aValue = PHPExcel_Calculation_Functions::flattenSingleValue($aValue);
936
+ $style = (is_null($style)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($style);
937
+ if ((!is_numeric($aValue)) || ($aValue < 0) || ($aValue >= 4000)) {
938
+ return PHPExcel_Calculation_Functions::VALUE();
939
+ }
940
+ $aValue = (integer) $aValue;
941
+ if ($aValue == 0) {
942
+ return '';
943
+ }
944
+
945
+ $mill = array('', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM');
946
+ $cent = array('', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM');
947
+ $tens = array('', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC');
948
+ $ones = array('', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX');
949
+
950
+ $roman = '';
951
+ while ($aValue > 5999) {
952
+ $roman .= 'M';
953
+ $aValue -= 1000;
954
+ }
955
+ $m = self::romanCut($aValue, 1000);
956
+ $aValue %= 1000;
957
+ $c = self::romanCut($aValue, 100);
958
+ $aValue %= 100;
959
+ $t = self::romanCut($aValue, 10);
960
+ $aValue %= 10;
961
+
962
+ return $roman.$mill[$m].$cent[$c].$tens[$t].$ones[$aValue];
963
+ }
964
+
965
+
966
+ /**
967
+ * ROUNDUP
968
+ *
969
+ * Rounds a number up to a specified number of decimal places
970
+ *
971
+ * @param float $number Number to round
972
+ * @param int $digits Number of digits to which you want to round $number
973
+ * @return float Rounded Number
974
+ */
975
+ public static function ROUNDUP($number, $digits)
976
+ {
977
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
978
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
979
+
980
+ if ((is_numeric($number)) && (is_numeric($digits))) {
981
+ $significance = pow(10, (int) $digits);
982
+ if ($number < 0.0) {
983
+ return floor($number * $significance) / $significance;
984
+ } else {
985
+ return ceil($number * $significance) / $significance;
986
+ }
987
+ }
988
+ return PHPExcel_Calculation_Functions::VALUE();
989
+ }
990
+
991
+
992
+ /**
993
+ * ROUNDDOWN
994
+ *
995
+ * Rounds a number down to a specified number of decimal places
996
+ *
997
+ * @param float $number Number to round
998
+ * @param int $digits Number of digits to which you want to round $number
999
+ * @return float Rounded Number
1000
+ */
1001
+ public static function ROUNDDOWN($number, $digits)
1002
+ {
1003
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
1004
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
1005
+
1006
+ if ((is_numeric($number)) && (is_numeric($digits))) {
1007
+ $significance = pow(10, (int) $digits);
1008
+ if ($number < 0.0) {
1009
+ return ceil($number * $significance) / $significance;
1010
+ } else {
1011
+ return floor($number * $significance) / $significance;
1012
+ }
1013
+ }
1014
+ return PHPExcel_Calculation_Functions::VALUE();
1015
+ }
1016
+
1017
+
1018
+ /**
1019
+ * SERIESSUM
1020
+ *
1021
+ * Returns the sum of a power series
1022
+ *
1023
+ * @param float $x Input value to the power series
1024
+ * @param float $n Initial power to which you want to raise $x
1025
+ * @param float $m Step by which to increase $n for each term in the series
1026
+ * @param array of mixed Data Series
1027
+ * @return float
1028
+ */
1029
+ public static function SERIESSUM()
1030
+ {
1031
+ $returnValue = 0;
1032
+
1033
+ // Loop through arguments
1034
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1035
+
1036
+ $x = array_shift($aArgs);
1037
+ $n = array_shift($aArgs);
1038
+ $m = array_shift($aArgs);
1039
+
1040
+ if ((is_numeric($x)) && (is_numeric($n)) && (is_numeric($m))) {
1041
+ // Calculate
1042
+ $i = 0;
1043
+ foreach ($aArgs as $arg) {
1044
+ // Is it a numeric value?
1045
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1046
+ $returnValue += $arg * pow($x, $n + ($m * $i++));
1047
+ } else {
1048
+ return PHPExcel_Calculation_Functions::VALUE();
1049
+ }
1050
+ }
1051
+ return $returnValue;
1052
+ }
1053
+ return PHPExcel_Calculation_Functions::VALUE();
1054
+ }
1055
+
1056
+
1057
+ /**
1058
+ * SIGN
1059
+ *
1060
+ * Determines the sign of a number. Returns 1 if the number is positive, zero (0)
1061
+ * if the number is 0, and -1 if the number is negative.
1062
+ *
1063
+ * @param float $number Number to round
1064
+ * @return int sign value
1065
+ */
1066
+ public static function SIGN($number)
1067
+ {
1068
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
1069
+
1070
+ if (is_bool($number)) {
1071
+ return (int) $number;
1072
+ }
1073
+ if (is_numeric($number)) {
1074
+ if ($number == 0.0) {
1075
+ return 0;
1076
+ }
1077
+ return $number / abs($number);
1078
+ }
1079
+ return PHPExcel_Calculation_Functions::VALUE();
1080
+ }
1081
+
1082
+
1083
+ /**
1084
+ * SQRTPI
1085
+ *
1086
+ * Returns the square root of (number * pi).
1087
+ *
1088
+ * @param float $number Number
1089
+ * @return float Square Root of Number * Pi
1090
+ */
1091
+ public static function SQRTPI($number)
1092
+ {
1093
+ $number = PHPExcel_Calculation_Functions::flattenSingleValue($number);
1094
+
1095
+ if (is_numeric($number)) {
1096
+ if ($number < 0) {
1097
+ return PHPExcel_Calculation_Functions::NaN();
1098
+ }
1099
+ return sqrt($number * M_PI) ;
1100
+ }
1101
+ return PHPExcel_Calculation_Functions::VALUE();
1102
+ }
1103
+
1104
+
1105
+ /**
1106
+ * SUBTOTAL
1107
+ *
1108
+ * Returns a subtotal in a list or database.
1109
+ *
1110
+ * @param int the number 1 to 11 that specifies which function to
1111
+ * use in calculating subtotals within a list.
1112
+ * @param array of mixed Data Series
1113
+ * @return float
1114
+ */
1115
+ public static function SUBTOTAL()
1116
+ {
1117
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1118
+
1119
+ // Calculate
1120
+ $subtotal = array_shift($aArgs);
1121
+
1122
+ if ((is_numeric($subtotal)) && (!is_string($subtotal))) {
1123
+ switch ($subtotal) {
1124
+ case 1:
1125
+ return PHPExcel_Calculation_Statistical::AVERAGE($aArgs);
1126
+ case 2:
1127
+ return PHPExcel_Calculation_Statistical::COUNT($aArgs);
1128
+ case 3:
1129
+ return PHPExcel_Calculation_Statistical::COUNTA($aArgs);
1130
+ case 4:
1131
+ return PHPExcel_Calculation_Statistical::MAX($aArgs);
1132
+ case 5:
1133
+ return PHPExcel_Calculation_Statistical::MIN($aArgs);
1134
+ case 6:
1135
+ return self::PRODUCT($aArgs);
1136
+ case 7:
1137
+ return PHPExcel_Calculation_Statistical::STDEV($aArgs);
1138
+ case 8:
1139
+ return PHPExcel_Calculation_Statistical::STDEVP($aArgs);
1140
+ case 9:
1141
+ return self::SUM($aArgs);
1142
+ case 10:
1143
+ return PHPExcel_Calculation_Statistical::VARFunc($aArgs);
1144
+ case 11:
1145
+ return PHPExcel_Calculation_Statistical::VARP($aArgs);
1146
+ }
1147
+ }
1148
+ return PHPExcel_Calculation_Functions::VALUE();
1149
+ }
1150
+
1151
+
1152
+ /**
1153
+ * SUM
1154
+ *
1155
+ * SUM computes the sum of all the values and cells referenced in the argument list.
1156
+ *
1157
+ * Excel Function:
1158
+ * SUM(value1[,value2[, ...]])
1159
+ *
1160
+ * @access public
1161
+ * @category Mathematical and Trigonometric Functions
1162
+ * @param mixed $arg,... Data values
1163
+ * @return float
1164
+ */
1165
+ public static function SUM()
1166
+ {
1167
+ $returnValue = 0;
1168
+
1169
+ // Loop through the arguments
1170
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
1171
+ // Is it a numeric value?
1172
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1173
+ $returnValue += $arg;
1174
+ }
1175
+ }
1176
+
1177
+ return $returnValue;
1178
+ }
1179
+
1180
+
1181
+ /**
1182
+ * SUMIF
1183
+ *
1184
+ * Counts the number of cells that contain numbers within the list of arguments
1185
+ *
1186
+ * Excel Function:
1187
+ * SUMIF(value1[,value2[, ...]],condition)
1188
+ *
1189
+ * @access public
1190
+ * @category Mathematical and Trigonometric Functions
1191
+ * @param mixed $arg,... Data values
1192
+ * @param string $condition The criteria that defines which cells will be summed.
1193
+ * @return float
1194
+ */
1195
+ public static function SUMIF($aArgs, $condition, $sumArgs = array())
1196
+ {
1197
+ $returnValue = 0;
1198
+
1199
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
1200
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
1201
+ if (empty($sumArgs)) {
1202
+ $sumArgs = $aArgs;
1203
+ }
1204
+ $condition = PHPExcel_Calculation_Functions::ifCondition($condition);
1205
+ // Loop through arguments
1206
+ foreach ($aArgs as $key => $arg) {
1207
+ if (!is_numeric($arg)) {
1208
+ $arg = str_replace('"', '""', $arg);
1209
+ $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg));
1210
+ }
1211
+
1212
+ $testCondition = '='.$arg.$condition;
1213
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
1214
+ // Is it a value within our criteria
1215
+ $returnValue += $sumArgs[$key];
1216
+ }
1217
+ }
1218
+
1219
+ return $returnValue;
1220
+ }
1221
+
1222
+
1223
+ /**
1224
+ * SUMIFS
1225
+ *
1226
+ * Counts the number of cells that contain numbers within the list of arguments
1227
+ *
1228
+ * Excel Function:
1229
+ * SUMIFS(value1[,value2[, ...]],condition)
1230
+ *
1231
+ * @access public
1232
+ * @category Mathematical and Trigonometric Functions
1233
+ * @param mixed $arg,... Data values
1234
+ * @param string $condition The criteria that defines which cells will be summed.
1235
+ * @return float
1236
+ */
1237
+ public static function SUMIFS() {
1238
+ $arrayList = func_get_args();
1239
+
1240
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList));
1241
+
1242
+ while (count($arrayList) > 0) {
1243
+ $aArgsArray[] = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList));
1244
+ $conditions[] = PHPExcel_Calculation_Functions::ifCondition(array_shift($arrayList));
1245
+ }
1246
+
1247
+ // Loop through each set of arguments and conditions
1248
+ foreach ($conditions as $index => $condition) {
1249
+ $aArgs = $aArgsArray[$index];
1250
+ $wildcard = false;
1251
+ if ((strpos($condition, '*') !== false) || (strpos($condition, '?') !== false)) {
1252
+ // * and ? are wildcard characters.
1253
+ // Use ~* and ~? for literal star and question mark
1254
+ // Code logic doesn't yet handle escaping
1255
+ $condition = trim(ltrim($condition, '=<>'), '"');
1256
+ $wildcard = true;
1257
+ }
1258
+ // Loop through arguments
1259
+ foreach ($aArgs as $key => $arg) {
1260
+ if ($wildcard) {
1261
+ if (!fnmatch($condition, $arg, FNM_CASEFOLD)) {
1262
+ // Is it a value within our criteria
1263
+ $sumArgs[$key] = 0.0;
1264
+ }
1265
+ } else {
1266
+ if (!is_numeric($arg)) {
1267
+ $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg));
1268
+ }
1269
+ $testCondition = '='.$arg.$condition;
1270
+ if (!PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
1271
+ // Is it a value within our criteria
1272
+ $sumArgs[$key] = 0.0;
1273
+ }
1274
+ }
1275
+ }
1276
+ }
1277
+
1278
+ // Return
1279
+ return array_sum($sumArgs);
1280
+ }
1281
+
1282
+
1283
+ /**
1284
+ * SUMPRODUCT
1285
+ *
1286
+ * Excel Function:
1287
+ * SUMPRODUCT(value1[,value2[, ...]])
1288
+ *
1289
+ * @access public
1290
+ * @category Mathematical and Trigonometric Functions
1291
+ * @param mixed $arg,... Data values
1292
+ * @return float
1293
+ */
1294
+ public static function SUMPRODUCT()
1295
+ {
1296
+ $arrayList = func_get_args();
1297
+
1298
+ $wrkArray = PHPExcel_Calculation_Functions::flattenArray(array_shift($arrayList));
1299
+ $wrkCellCount = count($wrkArray);
1300
+
1301
+ for ($i=0; $i< $wrkCellCount; ++$i) {
1302
+ if ((!is_numeric($wrkArray[$i])) || (is_string($wrkArray[$i]))) {
1303
+ $wrkArray[$i] = 0;
1304
+ }
1305
+ }
1306
+
1307
+ foreach ($arrayList as $matrixData) {
1308
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData);
1309
+ $count = count($array2);
1310
+ if ($wrkCellCount != $count) {
1311
+ return PHPExcel_Calculation_Functions::VALUE();
1312
+ }
1313
+
1314
+ foreach ($array2 as $i => $val) {
1315
+ if ((!is_numeric($val)) || (is_string($val))) {
1316
+ $val = 0;
1317
+ }
1318
+ $wrkArray[$i] *= $val;
1319
+ }
1320
+ }
1321
+
1322
+ return array_sum($wrkArray);
1323
+ }
1324
+
1325
+
1326
+ /**
1327
+ * SUMSQ
1328
+ *
1329
+ * SUMSQ returns the sum of the squares of the arguments
1330
+ *
1331
+ * Excel Function:
1332
+ * SUMSQ(value1[,value2[, ...]])
1333
+ *
1334
+ * @access public
1335
+ * @category Mathematical and Trigonometric Functions
1336
+ * @param mixed $arg,... Data values
1337
+ * @return float
1338
+ */
1339
+ public static function SUMSQ()
1340
+ {
1341
+ $returnValue = 0;
1342
+
1343
+ // Loop through arguments
1344
+ foreach (PHPExcel_Calculation_Functions::flattenArray(func_get_args()) as $arg) {
1345
+ // Is it a numeric value?
1346
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1347
+ $returnValue += ($arg * $arg);
1348
+ }
1349
+ }
1350
+
1351
+ return $returnValue;
1352
+ }
1353
+
1354
+
1355
+ /**
1356
+ * SUMX2MY2
1357
+ *
1358
+ * @param mixed[] $matrixData1 Matrix #1
1359
+ * @param mixed[] $matrixData2 Matrix #2
1360
+ * @return float
1361
+ */
1362
+ public static function SUMX2MY2($matrixData1, $matrixData2)
1363
+ {
1364
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
1365
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
1366
+ $count = min(count($array1), count($array2));
1367
+
1368
+ $result = 0;
1369
+ for ($i = 0; $i < $count; ++$i) {
1370
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
1371
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
1372
+ $result += ($array1[$i] * $array1[$i]) - ($array2[$i] * $array2[$i]);
1373
+ }
1374
+ }
1375
+
1376
+ return $result;
1377
+ }
1378
+
1379
+
1380
+ /**
1381
+ * SUMX2PY2
1382
+ *
1383
+ * @param mixed[] $matrixData1 Matrix #1
1384
+ * @param mixed[] $matrixData2 Matrix #2
1385
+ * @return float
1386
+ */
1387
+ public static function SUMX2PY2($matrixData1, $matrixData2)
1388
+ {
1389
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
1390
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
1391
+ $count = min(count($array1), count($array2));
1392
+
1393
+ $result = 0;
1394
+ for ($i = 0; $i < $count; ++$i) {
1395
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
1396
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
1397
+ $result += ($array1[$i] * $array1[$i]) + ($array2[$i] * $array2[$i]);
1398
+ }
1399
+ }
1400
+
1401
+ return $result;
1402
+ }
1403
+
1404
+
1405
+ /**
1406
+ * SUMXMY2
1407
+ *
1408
+ * @param mixed[] $matrixData1 Matrix #1
1409
+ * @param mixed[] $matrixData2 Matrix #2
1410
+ * @return float
1411
+ */
1412
+ public static function SUMXMY2($matrixData1, $matrixData2)
1413
+ {
1414
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($matrixData1);
1415
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($matrixData2);
1416
+ $count = min(count($array1), count($array2));
1417
+
1418
+ $result = 0;
1419
+ for ($i = 0; $i < $count; ++$i) {
1420
+ if (((is_numeric($array1[$i])) && (!is_string($array1[$i]))) &&
1421
+ ((is_numeric($array2[$i])) && (!is_string($array2[$i])))) {
1422
+ $result += ($array1[$i] - $array2[$i]) * ($array1[$i] - $array2[$i]);
1423
+ }
1424
+ }
1425
+
1426
+ return $result;
1427
+ }
1428
+
1429
+
1430
+ /**
1431
+ * TRUNC
1432
+ *
1433
+ * Truncates value to the number of fractional digits by number_digits.
1434
+ *
1435
+ * @param float $value
1436
+ * @param int $digits
1437
+ * @return float Truncated value
1438
+ */
1439
+ public static function TRUNC($value = 0, $digits = 0)
1440
+ {
1441
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1442
+ $digits = PHPExcel_Calculation_Functions::flattenSingleValue($digits);
1443
+
1444
+ // Validate parameters
1445
+ if ((!is_numeric($value)) || (!is_numeric($digits))) {
1446
+ return PHPExcel_Calculation_Functions::VALUE();
1447
+ }
1448
+ $digits = floor($digits);
1449
+
1450
+ // Truncate
1451
+ $adjust = pow(10, $digits);
1452
+
1453
+ if (($digits > 0) && (rtrim(intval((abs($value) - abs(intval($value))) * $adjust), '0') < $adjust/10)) {
1454
+ return $value;
1455
+ }
1456
+
1457
+ return (intval($value * $adjust)) / $adjust;
1458
+ }
1459
+ }
classes/PHPExcel/Calculation/Statistical.php ADDED
@@ -0,0 +1,3745 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /** PHPExcel root directory */
4
+ if (!defined('PHPEXCEL_ROOT')) {
5
+ /**
6
+ * @ignore
7
+ */
8
+ define('PHPEXCEL_ROOT', dirname(__FILE__) . '/../../');
9
+ require(PHPEXCEL_ROOT . 'PHPExcel/Autoloader.php');
10
+ }
11
+
12
+
13
+ require_once PHPEXCEL_ROOT . 'PHPExcel/Shared/trend/trendClass.php';
14
+
15
+
16
+ /** LOG_GAMMA_X_MAX_VALUE */
17
+ define('LOG_GAMMA_X_MAX_VALUE', 2.55e305);
18
+
19
+ /** XMININ */
20
+ define('XMININ', 2.23e-308);
21
+
22
+ /** EPS */
23
+ define('EPS', 2.22e-16);
24
+
25
+ /** SQRT2PI */
26
+ define('SQRT2PI', 2.5066282746310005024157652848110452530069867406099);
27
+
28
+ /**
29
+ * PHPExcel_Calculation_Statistical
30
+ *
31
+ * Copyright (c) 2006 - 2015 PHPExcel
32
+ *
33
+ * This library is free software; you can redistribute it and/or
34
+ * modify it under the terms of the GNU Lesser General Public
35
+ * License as published by the Free Software Foundation; either
36
+ * version 2.1 of the License, or (at your option) any later version.
37
+ *
38
+ * This library is distributed in the hope that it will be useful,
39
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
40
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
41
+ * Lesser General Public License for more details.
42
+ *
43
+ * You should have received a copy of the GNU Lesser General Public
44
+ * License along with this library; if not, write to the Free Software
45
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
46
+ *
47
+ * @category PHPExcel
48
+ * @package PHPExcel_Calculation
49
+ * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel)
50
+ * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
51
+ * @version ##VERSION##, ##DATE##
52
+ */
53
+ class PHPExcel_Calculation_Statistical
54
+ {
55
+ private static function checkTrendArrays(&$array1, &$array2)
56
+ {
57
+ if (!is_array($array1)) {
58
+ $array1 = array($array1);
59
+ }
60
+ if (!is_array($array2)) {
61
+ $array2 = array($array2);
62
+ }
63
+
64
+ $array1 = PHPExcel_Calculation_Functions::flattenArray($array1);
65
+ $array2 = PHPExcel_Calculation_Functions::flattenArray($array2);
66
+ foreach ($array1 as $key => $value) {
67
+ if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
68
+ unset($array1[$key]);
69
+ unset($array2[$key]);
70
+ }
71
+ }
72
+ foreach ($array2 as $key => $value) {
73
+ if ((is_bool($value)) || (is_string($value)) || (is_null($value))) {
74
+ unset($array1[$key]);
75
+ unset($array2[$key]);
76
+ }
77
+ }
78
+ $array1 = array_merge($array1);
79
+ $array2 = array_merge($array2);
80
+
81
+ return true;
82
+ }
83
+
84
+
85
+ /**
86
+ * Beta function.
87
+ *
88
+ * @author Jaco van Kooten
89
+ *
90
+ * @param p require p>0
91
+ * @param q require q>0
92
+ * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
93
+ */
94
+ private static function beta($p, $q)
95
+ {
96
+ if ($p <= 0.0 || $q <= 0.0 || ($p + $q) > LOG_GAMMA_X_MAX_VALUE) {
97
+ return 0.0;
98
+ } else {
99
+ return exp(self::logBeta($p, $q));
100
+ }
101
+ }
102
+
103
+
104
+ /**
105
+ * Incomplete beta function
106
+ *
107
+ * @author Jaco van Kooten
108
+ * @author Paul Meagher
109
+ *
110
+ * The computation is based on formulas from Numerical Recipes, Chapter 6.4 (W.H. Press et al, 1992).
111
+ * @param x require 0<=x<=1
112
+ * @param p require p>0
113
+ * @param q require q>0
114
+ * @return 0 if x<0, p<=0, q<=0 or p+q>2.55E305 and 1 if x>1 to avoid errors and over/underflow
115
+ */
116
+ private static function incompleteBeta($x, $p, $q)
117
+ {
118
+ if ($x <= 0.0) {
119
+ return 0.0;
120
+ } elseif ($x >= 1.0) {
121
+ return 1.0;
122
+ } elseif (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
123
+ return 0.0;
124
+ }
125
+ $beta_gam = exp((0 - self::logBeta($p, $q)) + $p * log($x) + $q * log(1.0 - $x));
126
+ if ($x < ($p + 1.0) / ($p + $q + 2.0)) {
127
+ return $beta_gam * self::betaFraction($x, $p, $q) / $p;
128
+ } else {
129
+ return 1.0 - ($beta_gam * self::betaFraction(1 - $x, $q, $p) / $q);
130
+ }
131
+ }
132
+
133
+
134
+ // Function cache for logBeta function
135
+ private static $logBetaCacheP = 0.0;
136
+ private static $logBetaCacheQ = 0.0;
137
+ private static $logBetaCacheResult = 0.0;
138
+
139
+ /**
140
+ * The natural logarithm of the beta function.
141
+ *
142
+ * @param p require p>0
143
+ * @param q require q>0
144
+ * @return 0 if p<=0, q<=0 or p+q>2.55E305 to avoid errors and over/underflow
145
+ * @author Jaco van Kooten
146
+ */
147
+ private static function logBeta($p, $q)
148
+ {
149
+ if ($p != self::$logBetaCacheP || $q != self::$logBetaCacheQ) {
150
+ self::$logBetaCacheP = $p;
151
+ self::$logBetaCacheQ = $q;
152
+ if (($p <= 0.0) || ($q <= 0.0) || (($p + $q) > LOG_GAMMA_X_MAX_VALUE)) {
153
+ self::$logBetaCacheResult = 0.0;
154
+ } else {
155
+ self::$logBetaCacheResult = self::logGamma($p) + self::logGamma($q) - self::logGamma($p + $q);
156
+ }
157
+ }
158
+ return self::$logBetaCacheResult;
159
+ }
160
+
161
+
162
+ /**
163
+ * Evaluates of continued fraction part of incomplete beta function.
164
+ * Based on an idea from Numerical Recipes (W.H. Press et al, 1992).
165
+ * @author Jaco van Kooten
166
+ */
167
+ private static function betaFraction($x, $p, $q)
168
+ {
169
+ $c = 1.0;
170
+ $sum_pq = $p + $q;
171
+ $p_plus = $p + 1.0;
172
+ $p_minus = $p - 1.0;
173
+ $h = 1.0 - $sum_pq * $x / $p_plus;
174
+ if (abs($h) < XMININ) {
175
+ $h = XMININ;
176
+ }
177
+ $h = 1.0 / $h;
178
+ $frac = $h;
179
+ $m = 1;
180
+ $delta = 0.0;
181
+ while ($m <= MAX_ITERATIONS && abs($delta-1.0) > PRECISION) {
182
+ $m2 = 2 * $m;
183
+ // even index for d
184
+ $d = $m * ($q - $m) * $x / ( ($p_minus + $m2) * ($p + $m2));
185
+ $h = 1.0 + $d * $h;
186
+ if (abs($h) < XMININ) {
187
+ $h = XMININ;
188
+ }
189
+ $h = 1.0 / $h;
190
+ $c = 1.0 + $d / $c;
191
+ if (abs($c) < XMININ) {
192
+ $c = XMININ;
193
+ }
194
+ $frac *= $h * $c;
195
+ // odd index for d
196
+ $d = -($p + $m) * ($sum_pq + $m) * $x / (($p + $m2) * ($p_plus + $m2));
197
+ $h = 1.0 + $d * $h;
198
+ if (abs($h) < XMININ) {
199
+ $h = XMININ;
200
+ }
201
+ $h = 1.0 / $h;
202
+ $c = 1.0 + $d / $c;
203
+ if (abs($c) < XMININ) {
204
+ $c = XMININ;
205
+ }
206
+ $delta = $h * $c;
207
+ $frac *= $delta;
208
+ ++$m;
209
+ }
210
+ return $frac;
211
+ }
212
+
213
+
214
+ /**
215
+ * logGamma function
216
+ *
217
+ * @version 1.1
218
+ * @author Jaco van Kooten
219
+ *
220
+ * Original author was Jaco van Kooten. Ported to PHP by Paul Meagher.
221
+ *
222
+ * The natural logarithm of the gamma function. <br />
223
+ * Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz <br />
224
+ * Applied Mathematics Division <br />
225
+ * Argonne National Laboratory <br />
226
+ * Argonne, IL 60439 <br />
227
+ * <p>
228
+ * References:
229
+ * <ol>
230
+ * <li>W. J. Cody and K. E. Hillstrom, 'Chebyshev Approximations for the Natural
231
+ * Logarithm of the Gamma Function,' Math. Comp. 21, 1967, pp. 198-203.</li>
232
+ * <li>K. E. Hillstrom, ANL/AMD Program ANLC366S, DGAMMA/DLGAMA, May, 1969.</li>
233
+ * <li>Hart, Et. Al., Computer Approximations, Wiley and sons, New York, 1968.</li>
234
+ * </ol>
235
+ * </p>
236
+ * <p>
237
+ * From the original documentation:
238
+ * </p>
239
+ * <p>
240
+ * This routine calculates the LOG(GAMMA) function for a positive real argument X.
241
+ * Computation is based on an algorithm outlined in references 1 and 2.
242
+ * The program uses rational functions that theoretically approximate LOG(GAMMA)
243
+ * to at least 18 significant decimal digits. The approximation for X > 12 is from
244
+ * reference 3, while approximations for X < 12.0 are similar to those in reference
245
+ * 1, but are unpublished. The accuracy achieved depends on the arithmetic system,
246
+ * the compiler, the intrinsic functions, and proper selection of the
247
+ * machine-dependent constants.
248
+ * </p>
249
+ * <p>
250
+ * Error returns: <br />
251
+ * The program returns the value XINF for X .LE. 0.0 or when overflow would occur.
252
+ * The computation is believed to be free of underflow and overflow.
253
+ * </p>
254
+ * @return MAX_VALUE for x < 0.0 or when overflow would occur, i.e. x > 2.55E305
255
+ */
256
+
257
+ // Function cache for logGamma
258
+ private static $logGammaCacheResult = 0.0;
259
+ private static $logGammaCacheX = 0.0;
260
+
261
+ private static function logGamma($x)
262
+ {
263
+ // Log Gamma related constants
264
+ static $lg_d1 = -0.5772156649015328605195174;
265
+ static $lg_d2 = 0.4227843350984671393993777;
266
+ static $lg_d4 = 1.791759469228055000094023;
267
+
268
+ static $lg_p1 = array(
269
+ 4.945235359296727046734888,
270
+ 201.8112620856775083915565,
271
+ 2290.838373831346393026739,
272
+ 11319.67205903380828685045,
273
+ 28557.24635671635335736389,
274
+ 38484.96228443793359990269,
275
+ 26377.48787624195437963534,
276
+ 7225.813979700288197698961
277
+ );
278
+ static $lg_p2 = array(
279
+ 4.974607845568932035012064,
280
+ 542.4138599891070494101986,
281
+ 15506.93864978364947665077,
282
+ 184793.2904445632425417223,
283
+ 1088204.76946882876749847,
284
+ 3338152.967987029735917223,
285
+ 5106661.678927352456275255,
286
+ 3074109.054850539556250927
287
+ );
288
+ static $lg_p4 = array(
289
+ 14745.02166059939948905062,
290
+ 2426813.369486704502836312,
291
+ 121475557.4045093227939592,
292
+ 2663432449.630976949898078,
293
+ 29403789566.34553899906876,
294
+ 170266573776.5398868392998,
295
+ 492612579337.743088758812,
296
+ 560625185622.3951465078242
297
+ );
298
+ static $lg_q1 = array(
299
+ 67.48212550303777196073036,
300
+ 1113.332393857199323513008,
301
+ 7738.757056935398733233834,
302
+ 27639.87074403340708898585,
303
+ 54993.10206226157329794414,
304
+ 61611.22180066002127833352,
305
+ 36351.27591501940507276287,
306
+ 8785.536302431013170870835
307
+ );
308
+ static $lg_q2 = array(
309
+ 183.0328399370592604055942,
310
+ 7765.049321445005871323047,
311
+ 133190.3827966074194402448,
312
+ 1136705.821321969608938755,
313
+ 5267964.117437946917577538,
314
+ 13467014.54311101692290052,
315
+ 17827365.30353274213975932,
316
+ 9533095.591844353613395747
317
+ );
318
+ static $lg_q4 = array(
319
+ 2690.530175870899333379843,
320
+ 639388.5654300092398984238,
321
+ 41355999.30241388052042842,
322
+ 1120872109.61614794137657,
323
+ 14886137286.78813811542398,
324
+ 101680358627.2438228077304,
325
+ 341747634550.7377132798597,
326
+ 446315818741.9713286462081
327
+ );
328
+ static $lg_c = array(
329
+ -0.001910444077728,
330
+ 8.4171387781295e-4,
331
+ -5.952379913043012e-4,
332
+ 7.93650793500350248e-4,
333
+ -0.002777777777777681622553,
334
+ 0.08333333333333333331554247,
335
+ 0.0057083835261
336
+ );
337
+
338
+ // Rough estimate of the fourth root of logGamma_xBig
339
+ static $lg_frtbig = 2.25e76;
340
+ static $pnt68 = 0.6796875;
341
+
342
+
343
+ if ($x == self::$logGammaCacheX) {
344
+ return self::$logGammaCacheResult;
345
+ }
346
+ $y = $x;
347
+ if ($y > 0.0 && $y <= LOG_GAMMA_X_MAX_VALUE) {
348
+ if ($y <= EPS) {
349
+ $res = -log(y);
350
+ } elseif ($y <= 1.5) {
351
+ // ---------------------
352
+ // EPS .LT. X .LE. 1.5
353
+ // ---------------------
354
+ if ($y < $pnt68) {
355
+ $corr = -log($y);
356
+ $xm1 = $y;
357
+ } else {
358
+ $corr = 0.0;
359
+ $xm1 = $y - 1.0;
360
+ }
361
+ if ($y <= 0.5 || $y >= $pnt68) {
362
+ $xden = 1.0;
363
+ $xnum = 0.0;
364
+ for ($i = 0; $i < 8; ++$i) {
365
+ $xnum = $xnum * $xm1 + $lg_p1[$i];
366
+ $xden = $xden * $xm1 + $lg_q1[$i];
367
+ }
368
+ $res = $corr + $xm1 * ($lg_d1 + $xm1 * ($xnum / $xden));
369
+ } else {
370
+ $xm2 = $y - 1.0;
371
+ $xden = 1.0;
372
+ $xnum = 0.0;
373
+ for ($i = 0; $i < 8; ++$i) {
374
+ $xnum = $xnum * $xm2 + $lg_p2[$i];
375
+ $xden = $xden * $xm2 + $lg_q2[$i];
376
+ }
377
+ $res = $corr + $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
378
+ }
379
+ } elseif ($y <= 4.0) {
380
+ // ---------------------
381
+ // 1.5 .LT. X .LE. 4.0
382
+ // ---------------------
383
+ $xm2 = $y - 2.0;
384
+ $xden = 1.0;
385
+ $xnum = 0.0;
386
+ for ($i = 0; $i < 8; ++$i) {
387
+ $xnum = $xnum * $xm2 + $lg_p2[$i];
388
+ $xden = $xden * $xm2 + $lg_q2[$i];
389
+ }
390
+ $res = $xm2 * ($lg_d2 + $xm2 * ($xnum / $xden));
391
+ } elseif ($y <= 12.0) {
392
+ // ----------------------
393
+ // 4.0 .LT. X .LE. 12.0
394
+ // ----------------------
395
+ $xm4 = $y - 4.0;
396
+ $xden = -1.0;
397
+ $xnum = 0.0;
398
+ for ($i = 0; $i < 8; ++$i) {
399
+ $xnum = $xnum * $xm4 + $lg_p4[$i];
400
+ $xden = $xden * $xm4 + $lg_q4[$i];
401
+ }
402
+ $res = $lg_d4 + $xm4 * ($xnum / $xden);
403
+ } else {
404
+ // ---------------------------------
405
+ // Evaluate for argument .GE. 12.0
406
+ // ---------------------------------
407
+ $res = 0.0;
408
+ if ($y <= $lg_frtbig) {
409
+ $res = $lg_c[6];
410
+ $ysq = $y * $y;
411
+ for ($i = 0; $i < 6; ++$i) {
412
+ $res = $res / $ysq + $lg_c[$i];
413
+ }
414
+ $res /= $y;
415
+ $corr = log($y);
416
+ $res = $res + log(SQRT2PI) - 0.5 * $corr;
417
+ $res += $y * ($corr - 1.0);
418
+ }
419
+ }
420
+ } else {
421
+ // --------------------------
422
+ // Return for bad arguments
423
+ // --------------------------
424
+ $res = MAX_VALUE;
425
+ }
426
+ // ------------------------------
427
+ // Final adjustments and return
428
+ // ------------------------------
429
+ self::$logGammaCacheX = $x;
430
+ self::$logGammaCacheResult = $res;
431
+ return $res;
432
+ }
433
+
434
+
435
+ //
436
+ // Private implementation of the incomplete Gamma function
437
+ //
438
+ private static function incompleteGamma($a, $x)
439
+ {
440
+ static $max = 32;
441
+ $summer = 0;
442
+ for ($n=0; $n<=$max; ++$n) {
443
+ $divisor = $a;
444
+ for ($i=1; $i<=$n; ++$i) {
445
+ $divisor *= ($a + $i);
446
+ }
447
+ $summer += (pow($x, $n) / $divisor);
448
+ }
449
+ return pow($x, $a) * exp(0-$x) * $summer;
450
+ }
451
+
452
+
453
+ //
454
+ // Private implementation of the Gamma function
455
+ //
456
+ private static function gamma($data)
457
+ {
458
+ if ($data == 0.0) {
459
+ return 0;
460
+ }
461
+
462
+ static $p0 = 1.000000000190015;
463
+ static $p = array(
464
+ 1 => 76.18009172947146,
465
+ 2 => -86.50532032941677,
466
+ 3 => 24.01409824083091,
467
+ 4 => -1.231739572450155,
468
+ 5 => 1.208650973866179e-3,
469
+ 6 => -5.395239384953e-6
470
+ );
471
+
472
+ $y = $x = $data;
473
+ $tmp = $x + 5.5;
474
+ $tmp -= ($x + 0.5) * log($tmp);
475
+
476
+ $summer = $p0;
477
+ for ($j=1; $j<=6; ++$j) {
478
+ $summer += ($p[$j] / ++$y);
479
+ }
480
+ return exp(0 - $tmp + log(SQRT2PI * $summer / $x));
481
+ }
482
+
483
+
484
+ /***************************************************************************
485
+ * inverse_ncdf.php
486
+ * -------------------
487
+ * begin : Friday, January 16, 2004
488
+ * copyright : (C) 2004 Michael Nickerson
489
+ * email : nickersonm@yahoo.com
490
+ *
491
+ ***************************************************************************/
492
+ private static function inverseNcdf($p)
493
+ {
494
+ // Inverse ncdf approximation by Peter J. Acklam, implementation adapted to
495
+ // PHP by Michael Nickerson, using Dr. Thomas Ziegler's C implementation as
496
+ // a guide. http://home.online.no/~pjacklam/notes/invnorm/index.html
497
+ // I have not checked the accuracy of this implementation. Be aware that PHP
498
+ // will truncate the coeficcients to 14 digits.
499
+
500
+ // You have permission to use and distribute this function freely for
501
+ // whatever purpose you want, but please show common courtesy and give credit
502
+ // where credit is due.
503
+
504
+ // Input paramater is $p - probability - where 0 < p < 1.
505
+
506
+ // Coefficients in rational approximations
507
+ static $a = array(
508
+ 1 => -3.969683028665376e+01,
509
+ 2 => 2.209460984245205e+02,
510
+ 3 => -2.759285104469687e+02,
511
+ 4 => 1.383577518672690e+02,
512
+ 5 => -3.066479806614716e+01,
513
+ 6 => 2.506628277459239e+00
514
+ );
515
+
516
+ static $b = array(
517
+ 1 => -5.447609879822406e+01,
518
+ 2 => 1.615858368580409e+02,
519
+ 3 => -1.556989798598866e+02,
520
+ 4 => 6.680131188771972e+01,
521
+ 5 => -1.328068155288572e+01
522
+ );
523
+
524
+ static $c = array(
525
+ 1 => -7.784894002430293e-03,
526
+ 2 => -3.223964580411365e-01,
527
+ 3 => -2.400758277161838e+00,
528
+ 4 => -2.549732539343734e+00,
529
+ 5 => 4.374664141464968e+00,
530
+ 6 => 2.938163982698783e+00
531
+ );
532
+
533
+ static $d = array(
534
+ 1 => 7.784695709041462e-03,
535
+ 2 => 3.224671290700398e-01,
536
+ 3 => 2.445134137142996e+00,
537
+ 4 => 3.754408661907416e+00
538
+ );
539
+
540
+ // Define lower and upper region break-points.
541
+ $p_low = 0.02425; //Use lower region approx. below this
542
+ $p_high = 1 - $p_low; //Use upper region approx. above this
543
+
544
+ if (0 < $p && $p < $p_low) {
545
+ // Rational approximation for lower region.
546
+ $q = sqrt(-2 * log($p));
547
+ return ((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) /
548
+ (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1);
549
+ } elseif ($p_low <= $p && $p <= $p_high) {
550
+ // Rational approximation for central region.
551
+ $q = $p - 0.5;
552
+ $r = $q * $q;
553
+ return ((((($a[1] * $r + $a[2]) * $r + $a[3]) * $r + $a[4]) * $r + $a[5]) * $r + $a[6]) * $q /
554
+ ((((($b[1] * $r + $b[2]) * $r + $b[3]) * $r + $b[4]) * $r + $b[5]) * $r + 1);
555
+ } elseif ($p_high < $p && $p < 1) {
556
+ // Rational approximation for upper region.
557
+ $q = sqrt(-2 * log(1 - $p));
558
+ return -((((($c[1] * $q + $c[2]) * $q + $c[3]) * $q + $c[4]) * $q + $c[5]) * $q + $c[6]) /
559
+ (((($d[1] * $q + $d[2]) * $q + $d[3]) * $q + $d[4]) * $q + 1);
560
+ }
561
+ // If 0 < p < 1, return a null value
562
+ return PHPExcel_Calculation_Functions::NULL();
563
+ }
564
+
565
+
566
+ private static function inverseNcdf2($prob)
567
+ {
568
+ // Approximation of inverse standard normal CDF developed by
569
+ // B. Moro, "The Full Monte," Risk 8(2), Feb 1995, 57-58.
570
+
571
+ $a1 = 2.50662823884;
572
+ $a2 = -18.61500062529;
573
+ $a3 = 41.39119773534;
574
+ $a4 = -25.44106049637;
575
+
576
+ $b1 = -8.4735109309;
577
+ $b2 = 23.08336743743;
578
+ $b3 = -21.06224101826;
579
+ $b4 = 3.13082909833;
580
+
581
+ $c1 = 0.337475482272615;
582
+ $c2 = 0.976169019091719;
583
+ $c3 = 0.160797971491821;
584
+ $c4 = 2.76438810333863E-02;
585
+ $c5 = 3.8405729373609E-03;
586
+ $c6 = 3.951896511919E-04;
587
+ $c7 = 3.21767881768E-05;
588
+ $c8 = 2.888167364E-07;
589
+ $c9 = 3.960315187E-07;
590
+
591
+ $y = $prob - 0.5;
592
+ if (abs($y) < 0.42) {
593
+ $z = ($y * $y);
594
+ $z = $y * ((($a4 * $z + $a3) * $z + $a2) * $z + $a1) / (((($b4 * $z + $b3) * $z + $b2) * $z + $b1) * $z + 1);
595
+ } else {
596
+ if ($y > 0) {
597
+ $z = log(-log(1 - $prob));
598
+ } else {
599
+ $z = log(-log($prob));
600
+ }
601
+ $z = $c1 + $z * ($c2 + $z * ($c3 + $z * ($c4 + $z * ($c5 + $z * ($c6 + $z * ($c7 + $z * ($c8 + $z * $c9)))))));
602
+ if ($y < 0) {
603
+ $z = -$z;
604
+ }
605
+ }
606
+ return $z;
607
+ } // function inverseNcdf2()
608
+
609
+
610
+ private static function inverseNcdf3($p)
611
+ {
612
+ // ALGORITHM AS241 APPL. STATIST. (1988) VOL. 37, NO. 3.
613
+ // Produces the normal deviate Z corresponding to a given lower
614
+ // tail area of P; Z is accurate to about 1 part in 10**16.
615
+ //
616
+ // This is a PHP version of the original FORTRAN code that can
617
+ // be found at http://lib.stat.cmu.edu/apstat/
618
+ $split1 = 0.425;
619
+ $split2 = 5;
620
+ $const1 = 0.180625;
621
+ $const2 = 1.6;
622
+
623
+ // coefficients for p close to 0.5
624
+ $a0 = 3.3871328727963666080;
625
+ $a1 = 1.3314166789178437745E+2;
626
+ $a2 = 1.9715909503065514427E+3;
627
+ $a3 = 1.3731693765509461125E+4;
628
+ $a4 = 4.5921953931549871457E+4;
629
+ $a5 = 6.7265770927008700853E+4;
630
+ $a6 = 3.3430575583588128105E+4;
631
+ $a7 = 2.5090809287301226727E+3;
632
+
633
+ $b1 = 4.2313330701600911252E+1;
634
+ $b2 = 6.8718700749205790830E+2;
635
+ $b3 = 5.3941960214247511077E+3;
636
+ $b4 = 2.1213794301586595867E+4;
637
+ $b5 = 3.9307895800092710610E+4;
638
+ $b6 = 2.8729085735721942674E+4;
639
+ $b7 = 5.2264952788528545610E+3;
640
+
641
+ // coefficients for p not close to 0, 0.5 or 1.
642
+ $c0 = 1.42343711074968357734;
643
+ $c1 = 4.63033784615654529590;
644
+ $c2 = 5.76949722146069140550;
645
+ $c3 = 3.64784832476320460504;
646
+ $c4 = 1.27045825245236838258;
647
+ $c5 = 2.41780725177450611770E-1;
648
+ $c6 = 2.27238449892691845833E-2;
649
+ $c7 = 7.74545014278341407640E-4;
650
+
651
+ $d1 = 2.05319162663775882187;
652
+ $d2 = 1.67638483018380384940;
653
+ $d3 = 6.89767334985100004550E-1;
654
+ $d4 = 1.48103976427480074590E-1;
655
+ $d5 = 1.51986665636164571966E-2;
656
+ $d6 = 5.47593808499534494600E-4;
657
+ $d7 = 1.05075007164441684324E-9;
658
+
659
+ // coefficients for p near 0 or 1.
660
+ $e0 = 6.65790464350110377720;
661
+ $e1 = 5.46378491116411436990;
662
+ $e2 = 1.78482653991729133580;
663
+ $e3 = 2.96560571828504891230E-1;
664
+ $e4 = 2.65321895265761230930E-2;
665
+ $e5 = 1.24266094738807843860E-3;
666
+ $e6 = 2.71155556874348757815E-5;
667
+ $e7 = 2.01033439929228813265E-7;
668
+
669
+ $f1 = 5.99832206555887937690E-1;
670
+ $f2 = 1.36929880922735805310E-1;
671
+ $f3 = 1.48753612908506148525E-2;
672
+ $f4 = 7.86869131145613259100E-4;
673
+ $f5 = 1.84631831751005468180E-5;
674
+ $f6 = 1.42151175831644588870E-7;
675
+ $f7 = 2.04426310338993978564E-15;
676
+
677
+ $q = $p - 0.5;
678
+
679
+ // computation for p close to 0.5
680
+ if (abs($q) <= split1) {
681
+ $R = $const1 - $q * $q;
682
+ $z = $q * ((((((($a7 * $R + $a6) * $R + $a5) * $R + $a4) * $R + $a3) * $R + $a2) * $R + $a1) * $R + $a0) /
683
+ ((((((($b7 * $R + $b6) * $R + $b5) * $R + $b4) * $R + $b3) * $R + $b2) * $R + $b1) * $R + 1);
684
+ } else {
685
+ if ($q < 0) {
686
+ $R = $p;
687
+ } else {
688
+ $R = 1 - $p;
689
+ }
690
+ $R = pow(-log($R), 2);
691
+
692
+ // computation for p not close to 0, 0.5 or 1.
693
+ if ($R <= $split2) {
694
+ $R = $R - $const2;
695
+ $z = ((((((($c7 * $R + $c6) * $R + $c5) * $R + $c4) * $R + $c3) * $R + $c2) * $R + $c1) * $R + $c0) /
696
+ ((((((($d7 * $R + $d6) * $R + $d5) * $R + $d4) * $R + $d3) * $R + $d2) * $R + $d1) * $R + 1);
697
+ } else {
698
+ // computation for p near 0 or 1.
699
+ $R = $R - $split2;
700
+ $z = ((((((($e7 * $R + $e6) * $R + $e5) * $R + $e4) * $R + $e3) * $R + $e2) * $R + $e1) * $R + $e0) /
701
+ ((((((($f7 * $R + $f6) * $R + $f5) * $R + $f4) * $R + $f3) * $R + $f2) * $R + $f1) * $R + 1);
702
+ }
703
+ if ($q < 0) {
704
+ $z = -$z;
705
+ }
706
+ }
707
+ return $z;
708
+ }
709
+
710
+
711
+ /**
712
+ * AVEDEV
713
+ *
714
+ * Returns the average of the absolute deviations of data points from their mean.
715
+ * AVEDEV is a measure of the variability in a data set.
716
+ *
717
+ * Excel Function:
718
+ * AVEDEV(value1[,value2[, ...]])
719
+ *
720
+ * @access public
721
+ * @category Statistical Functions
722
+ * @param mixed $arg,... Data values
723
+ * @return float
724
+ */
725
+ public static function AVEDEV()
726
+ {
727
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
728
+
729
+ // Return value
730
+ $returnValue = null;
731
+
732
+ $aMean = self::AVERAGE($aArgs);
733
+ if ($aMean != PHPExcel_Calculation_Functions::DIV0()) {
734
+ $aCount = 0;
735
+ foreach ($aArgs as $k => $arg) {
736
+ if ((is_bool($arg)) &&
737
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
738
+ $arg = (integer) $arg;
739
+ }
740
+ // Is it a numeric value?
741
+ if ((is_numeric($arg)) && (!is_string($arg))) {
742
+ if (is_null($returnValue)) {
743
+ $returnValue = abs($arg - $aMean);
744
+ } else {
745
+ $returnValue += abs($arg - $aMean);
746
+ }
747
+ ++$aCount;
748
+ }
749
+ }
750
+
751
+ // Return
752
+ if ($aCount == 0) {
753
+ return PHPExcel_Calculation_Functions::DIV0();
754
+ }
755
+ return $returnValue / $aCount;
756
+ }
757
+ return PHPExcel_Calculation_Functions::NaN();
758
+ }
759
+
760
+
761
+ /**
762
+ * AVERAGE
763
+ *
764
+ * Returns the average (arithmetic mean) of the arguments
765
+ *
766
+ * Excel Function:
767
+ * AVERAGE(value1[,value2[, ...]])
768
+ *
769
+ * @access public
770
+ * @category Statistical Functions
771
+ * @param mixed $arg,... Data values
772
+ * @return float
773
+ */
774
+ public static function AVERAGE()
775
+ {
776
+ $returnValue = $aCount = 0;
777
+
778
+ // Loop through arguments
779
+ foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) {
780
+ if ((is_bool($arg)) &&
781
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
782
+ $arg = (integer) $arg;
783
+ }
784
+ // Is it a numeric value?
785
+ if ((is_numeric($arg)) && (!is_string($arg))) {
786
+ if (is_null($returnValue)) {
787
+ $returnValue = $arg;
788
+ } else {
789
+ $returnValue += $arg;
790
+ }
791
+ ++$aCount;
792
+ }
793
+ }
794
+
795
+ // Return
796
+ if ($aCount > 0) {
797
+ return $returnValue / $aCount;
798
+ } else {
799
+ return PHPExcel_Calculation_Functions::DIV0();
800
+ }
801
+ }
802
+
803
+
804
+ /**
805
+ * AVERAGEA
806
+ *
807
+ * Returns the average of its arguments, including numbers, text, and logical values
808
+ *
809
+ * Excel Function:
810
+ * AVERAGEA(value1[,value2[, ...]])
811
+ *
812
+ * @access public
813
+ * @category Statistical Functions
814
+ * @param mixed $arg,... Data values
815
+ * @return float
816
+ */
817
+ public static function AVERAGEA()
818
+ {
819
+ $returnValue = null;
820
+
821
+ $aCount = 0;
822
+ // Loop through arguments
823
+ foreach (PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args()) as $k => $arg) {
824
+ if ((is_bool($arg)) &&
825
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
826
+ } else {
827
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
828
+ if (is_bool($arg)) {
829
+ $arg = (integer) $arg;
830
+ } elseif (is_string($arg)) {
831
+ $arg = 0;
832
+ }
833
+ if (is_null($returnValue)) {
834
+ $returnValue = $arg;
835
+ } else {
836
+ $returnValue += $arg;
837
+ }
838
+ ++$aCount;
839
+ }
840
+ }
841
+ }
842
+
843
+ if ($aCount > 0) {
844
+ return $returnValue / $aCount;
845
+ } else {
846
+ return PHPExcel_Calculation_Functions::DIV0();
847
+ }
848
+ }
849
+
850
+
851
+ /**
852
+ * AVERAGEIF
853
+ *
854
+ * Returns the average value from a range of cells that contain numbers within the list of arguments
855
+ *
856
+ * Excel Function:
857
+ * AVERAGEIF(value1[,value2[, ...]],condition)
858
+ *
859
+ * @access public
860
+ * @category Mathematical and Trigonometric Functions
861
+ * @param mixed $arg,... Data values
862
+ * @param string $condition The criteria that defines which cells will be checked.
863
+ * @param mixed[] $averageArgs Data values
864
+ * @return float
865
+ */
866
+ public static function AVERAGEIF($aArgs, $condition, $averageArgs = array())
867
+ {
868
+ $returnValue = 0;
869
+
870
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
871
+ $averageArgs = PHPExcel_Calculation_Functions::flattenArray($averageArgs);
872
+ if (empty($averageArgs)) {
873
+ $averageArgs = $aArgs;
874
+ }
875
+ $condition = PHPExcel_Calculation_Functions::ifCondition($condition);
876
+ // Loop through arguments
877
+ $aCount = 0;
878
+ foreach ($aArgs as $key => $arg) {
879
+ if (!is_numeric($arg)) {
880
+ $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg));
881
+ }
882
+ $testCondition = '='.$arg.$condition;
883
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
884
+ if ((is_null($returnValue)) || ($arg > $returnValue)) {
885
+ $returnValue += $arg;
886
+ ++$aCount;
887
+ }
888
+ }
889
+ }
890
+
891
+ if ($aCount > 0) {
892
+ return $returnValue / $aCount;
893
+ }
894
+ return PHPExcel_Calculation_Functions::DIV0();
895
+ }
896
+
897
+
898
+ /**
899
+ * BETADIST
900
+ *
901
+ * Returns the beta distribution.
902
+ *
903
+ * @param float $value Value at which you want to evaluate the distribution
904
+ * @param float $alpha Parameter to the distribution
905
+ * @param float $beta Parameter to the distribution
906
+ * @param boolean $cumulative
907
+ * @return float
908
+ *
909
+ */
910
+ public static function BETADIST($value, $alpha, $beta, $rMin = 0, $rMax = 1)
911
+ {
912
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
913
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
914
+ $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta);
915
+ $rMin = PHPExcel_Calculation_Functions::flattenSingleValue($rMin);
916
+ $rMax = PHPExcel_Calculation_Functions::flattenSingleValue($rMax);
917
+
918
+ if ((is_numeric($value)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
919
+ if (($value < $rMin) || ($value > $rMax) || ($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax)) {
920
+ return PHPExcel_Calculation_Functions::NaN();
921
+ }
922
+ if ($rMin > $rMax) {
923
+ $tmp = $rMin;
924
+ $rMin = $rMax;
925
+ $rMax = $tmp;
926
+ }
927
+ $value -= $rMin;
928
+ $value /= ($rMax - $rMin);
929
+ return self::incompleteBeta($value, $alpha, $beta);
930
+ }
931
+ return PHPExcel_Calculation_Functions::VALUE();
932
+ }
933
+
934
+
935
+ /**
936
+ * BETAINV
937
+ *
938
+ * Returns the inverse of the beta distribution.
939
+ *
940
+ * @param float $probability Probability at which you want to evaluate the distribution
941
+ * @param float $alpha Parameter to the distribution
942
+ * @param float $beta Parameter to the distribution
943
+ * @param float $rMin Minimum value
944
+ * @param float $rMax Maximum value
945
+ * @param boolean $cumulative
946
+ * @return float
947
+ *
948
+ */
949
+ public static function BETAINV($probability, $alpha, $beta, $rMin = 0, $rMax = 1)
950
+ {
951
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
952
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
953
+ $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta);
954
+ $rMin = PHPExcel_Calculation_Functions::flattenSingleValue($rMin);
955
+ $rMax = PHPExcel_Calculation_Functions::flattenSingleValue($rMax);
956
+
957
+ if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta)) && (is_numeric($rMin)) && (is_numeric($rMax))) {
958
+ if (($alpha <= 0) || ($beta <= 0) || ($rMin == $rMax) || ($probability <= 0) || ($probability > 1)) {
959
+ return PHPExcel_Calculation_Functions::NaN();
960
+ }
961
+ if ($rMin > $rMax) {
962
+ $tmp = $rMin;
963
+ $rMin = $rMax;
964
+ $rMax = $tmp;
965
+ }
966
+ $a = 0;
967
+ $b = 2;
968
+
969
+ $i = 0;
970
+ while ((($b - $a) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
971
+ $guess = ($a + $b) / 2;
972
+ $result = self::BETADIST($guess, $alpha, $beta);
973
+ if (($result == $probability) || ($result == 0)) {
974
+ $b = $a;
975
+ } elseif ($result > $probability) {
976
+ $b = $guess;
977
+ } else {
978
+ $a = $guess;
979
+ }
980
+ }
981
+ if ($i == MAX_ITERATIONS) {
982
+ return PHPExcel_Calculation_Functions::NA();
983
+ }
984
+ return round($rMin + $guess * ($rMax - $rMin), 12);
985
+ }
986
+ return PHPExcel_Calculation_Functions::VALUE();
987
+ }
988
+
989
+
990
+ /**
991
+ * BINOMDIST
992
+ *
993
+ * Returns the individual term binomial distribution probability. Use BINOMDIST in problems with
994
+ * a fixed number of tests or trials, when the outcomes of any trial are only success or failure,
995
+ * when trials are independent, and when the probability of success is constant throughout the
996
+ * experiment. For example, BINOMDIST can calculate the probability that two of the next three
997
+ * babies born are male.
998
+ *
999
+ * @param float $value Number of successes in trials
1000
+ * @param float $trials Number of trials
1001
+ * @param float $probability Probability of success on each trial
1002
+ * @param boolean $cumulative
1003
+ * @return float
1004
+ *
1005
+ * @todo Cumulative distribution function
1006
+ *
1007
+ */
1008
+ public static function BINOMDIST($value, $trials, $probability, $cumulative)
1009
+ {
1010
+ $value = floor(PHPExcel_Calculation_Functions::flattenSingleValue($value));
1011
+ $trials = floor(PHPExcel_Calculation_Functions::flattenSingleValue($trials));
1012
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
1013
+
1014
+ if ((is_numeric($value)) && (is_numeric($trials)) && (is_numeric($probability))) {
1015
+ if (($value < 0) || ($value > $trials)) {
1016
+ return PHPExcel_Calculation_Functions::NaN();
1017
+ }
1018
+ if (($probability < 0) || ($probability > 1)) {
1019
+ return PHPExcel_Calculation_Functions::NaN();
1020
+ }
1021
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
1022
+ if ($cumulative) {
1023
+ $summer = 0;
1024
+ for ($i = 0; $i <= $value; ++$i) {
1025
+ $summer += PHPExcel_Calculation_MathTrig::COMBIN($trials, $i) * pow($probability, $i) * pow(1 - $probability, $trials - $i);
1026
+ }
1027
+ return $summer;
1028
+ } else {
1029
+ return PHPExcel_Calculation_MathTrig::COMBIN($trials, $value) * pow($probability, $value) * pow(1 - $probability, $trials - $value) ;
1030
+ }
1031
+ }
1032
+ }
1033
+ return PHPExcel_Calculation_Functions::VALUE();
1034
+ }
1035
+
1036
+
1037
+ /**
1038
+ * CHIDIST
1039
+ *
1040
+ * Returns the one-tailed probability of the chi-squared distribution.
1041
+ *
1042
+ * @param float $value Value for the function
1043
+ * @param float $degrees degrees of freedom
1044
+ * @return float
1045
+ */
1046
+ public static function CHIDIST($value, $degrees)
1047
+ {
1048
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1049
+ $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees));
1050
+
1051
+ if ((is_numeric($value)) && (is_numeric($degrees))) {
1052
+ if ($degrees < 1) {
1053
+ return PHPExcel_Calculation_Functions::NaN();
1054
+ }
1055
+ if ($value < 0) {
1056
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
1057
+ return 1;
1058
+ }
1059
+ return PHPExcel_Calculation_Functions::NaN();
1060
+ }
1061
+ return 1 - (self::incompleteGamma($degrees/2, $value/2) / self::gamma($degrees/2));
1062
+ }
1063
+ return PHPExcel_Calculation_Functions::VALUE();
1064
+ }
1065
+
1066
+
1067
+ /**
1068
+ * CHIINV
1069
+ *
1070
+ * Returns the one-tailed probability of the chi-squared distribution.
1071
+ *
1072
+ * @param float $probability Probability for the function
1073
+ * @param float $degrees degrees of freedom
1074
+ * @return float
1075
+ */
1076
+ public static function CHIINV($probability, $degrees)
1077
+ {
1078
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
1079
+ $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees));
1080
+
1081
+ if ((is_numeric($probability)) && (is_numeric($degrees))) {
1082
+ $xLo = 100;
1083
+ $xHi = 0;
1084
+
1085
+ $x = $xNew = 1;
1086
+ $dx = 1;
1087
+ $i = 0;
1088
+
1089
+ while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
1090
+ // Apply Newton-Raphson step
1091
+ $result = self::CHIDIST($x, $degrees);
1092
+ $error = $result - $probability;
1093
+ if ($error == 0.0) {
1094
+ $dx = 0;
1095
+ } elseif ($error < 0.0) {
1096
+ $xLo = $x;
1097
+ } else {
1098
+ $xHi = $x;
1099
+ }
1100
+ // Avoid division by zero
1101
+ if ($result != 0.0) {
1102
+ $dx = $error / $result;
1103
+ $xNew = $x - $dx;
1104
+ }
1105
+ // If the NR fails to converge (which for example may be the
1106
+ // case if the initial guess is too rough) we apply a bisection
1107
+ // step to determine a more narrow interval around the root.
1108
+ if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) {
1109
+ $xNew = ($xLo + $xHi) / 2;
1110
+ $dx = $xNew - $x;
1111
+ }
1112
+ $x = $xNew;
1113
+ }
1114
+ if ($i == MAX_ITERATIONS) {
1115
+ return PHPExcel_Calculation_Functions::NA();
1116
+ }
1117
+ return round($x, 12);
1118
+ }
1119
+ return PHPExcel_Calculation_Functions::VALUE();
1120
+ }
1121
+
1122
+
1123
+ /**
1124
+ * CONFIDENCE
1125
+ *
1126
+ * Returns the confidence interval for a population mean
1127
+ *
1128
+ * @param float $alpha
1129
+ * @param float $stdDev Standard Deviation
1130
+ * @param float $size
1131
+ * @return float
1132
+ *
1133
+ */
1134
+ public static function CONFIDENCE($alpha, $stdDev, $size)
1135
+ {
1136
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
1137
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
1138
+ $size = floor(PHPExcel_Calculation_Functions::flattenSingleValue($size));
1139
+
1140
+ if ((is_numeric($alpha)) && (is_numeric($stdDev)) && (is_numeric($size))) {
1141
+ if (($alpha <= 0) || ($alpha >= 1)) {
1142
+ return PHPExcel_Calculation_Functions::NaN();
1143
+ }
1144
+ if (($stdDev <= 0) || ($size < 1)) {
1145
+ return PHPExcel_Calculation_Functions::NaN();
1146
+ }
1147
+ return self::NORMSINV(1 - $alpha / 2) * $stdDev / sqrt($size);
1148
+ }
1149
+ return PHPExcel_Calculation_Functions::VALUE();
1150
+ }
1151
+
1152
+
1153
+ /**
1154
+ * CORREL
1155
+ *
1156
+ * Returns covariance, the average of the products of deviations for each data point pair.
1157
+ *
1158
+ * @param array of mixed Data Series Y
1159
+ * @param array of mixed Data Series X
1160
+ * @return float
1161
+ */
1162
+ public static function CORREL($yValues, $xValues = null)
1163
+ {
1164
+ if ((is_null($xValues)) || (!is_array($yValues)) || (!is_array($xValues))) {
1165
+ return PHPExcel_Calculation_Functions::VALUE();
1166
+ }
1167
+ if (!self::checkTrendArrays($yValues, $xValues)) {
1168
+ return PHPExcel_Calculation_Functions::VALUE();
1169
+ }
1170
+ $yValueCount = count($yValues);
1171
+ $xValueCount = count($xValues);
1172
+
1173
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1174
+ return PHPExcel_Calculation_Functions::NA();
1175
+ } elseif ($yValueCount == 1) {
1176
+ return PHPExcel_Calculation_Functions::DIV0();
1177
+ }
1178
+
1179
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues);
1180
+ return $bestFitLinear->getCorrelation();
1181
+ }
1182
+
1183
+
1184
+ /**
1185
+ * COUNT
1186
+ *
1187
+ * Counts the number of cells that contain numbers within the list of arguments
1188
+ *
1189
+ * Excel Function:
1190
+ * COUNT(value1[,value2[, ...]])
1191
+ *
1192
+ * @access public
1193
+ * @category Statistical Functions
1194
+ * @param mixed $arg,... Data values
1195
+ * @return int
1196
+ */
1197
+ public static function COUNT()
1198
+ {
1199
+ $returnValue = 0;
1200
+
1201
+ // Loop through arguments
1202
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
1203
+ foreach ($aArgs as $k => $arg) {
1204
+ if ((is_bool($arg)) &&
1205
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
1206
+ $arg = (integer) $arg;
1207
+ }
1208
+ // Is it a numeric value?
1209
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1210
+ ++$returnValue;
1211
+ }
1212
+ }
1213
+
1214
+ return $returnValue;
1215
+ }
1216
+
1217
+
1218
+ /**
1219
+ * COUNTA
1220
+ *
1221
+ * Counts the number of cells that are not empty within the list of arguments
1222
+ *
1223
+ * Excel Function:
1224
+ * COUNTA(value1[,value2[, ...]])
1225
+ *
1226
+ * @access public
1227
+ * @category Statistical Functions
1228
+ * @param mixed $arg,... Data values
1229
+ * @return int
1230
+ */
1231
+ public static function COUNTA()
1232
+ {
1233
+ $returnValue = 0;
1234
+
1235
+ // Loop through arguments
1236
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1237
+ foreach ($aArgs as $arg) {
1238
+ // Is it a numeric, boolean or string value?
1239
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
1240
+ ++$returnValue;
1241
+ }
1242
+ }
1243
+
1244
+ return $returnValue;
1245
+ }
1246
+
1247
+
1248
+ /**
1249
+ * COUNTBLANK
1250
+ *
1251
+ * Counts the number of empty cells within the list of arguments
1252
+ *
1253
+ * Excel Function:
1254
+ * COUNTBLANK(value1[,value2[, ...]])
1255
+ *
1256
+ * @access public
1257
+ * @category Statistical Functions
1258
+ * @param mixed $arg,... Data values
1259
+ * @return int
1260
+ */
1261
+ public static function COUNTBLANK()
1262
+ {
1263
+ $returnValue = 0;
1264
+
1265
+ // Loop through arguments
1266
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1267
+ foreach ($aArgs as $arg) {
1268
+ // Is it a blank cell?
1269
+ if ((is_null($arg)) || ((is_string($arg)) && ($arg == ''))) {
1270
+ ++$returnValue;
1271
+ }
1272
+ }
1273
+
1274
+ return $returnValue;
1275
+ }
1276
+
1277
+
1278
+ /**
1279
+ * COUNTIF
1280
+ *
1281
+ * Counts the number of cells that contain numbers within the list of arguments
1282
+ *
1283
+ * Excel Function:
1284
+ * COUNTIF(value1[,value2[, ...]],condition)
1285
+ *
1286
+ * @access public
1287
+ * @category Statistical Functions
1288
+ * @param mixed $arg,... Data values
1289
+ * @param string $condition The criteria that defines which cells will be counted.
1290
+ * @return int
1291
+ */
1292
+ public static function COUNTIF($aArgs, $condition)
1293
+ {
1294
+ $returnValue = 0;
1295
+
1296
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
1297
+ $condition = PHPExcel_Calculation_Functions::ifCondition($condition);
1298
+ // Loop through arguments
1299
+ foreach ($aArgs as $arg) {
1300
+ if (!is_numeric($arg)) {
1301
+ $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg));
1302
+ }
1303
+ $testCondition = '='.$arg.$condition;
1304
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
1305
+ // Is it a value within our criteria
1306
+ ++$returnValue;
1307
+ }
1308
+ }
1309
+
1310
+ return $returnValue;
1311
+ }
1312
+
1313
+
1314
+ /**
1315
+ * COVAR
1316
+ *
1317
+ * Returns covariance, the average of the products of deviations for each data point pair.
1318
+ *
1319
+ * @param array of mixed Data Series Y
1320
+ * @param array of mixed Data Series X
1321
+ * @return float
1322
+ */
1323
+ public static function COVAR($yValues, $xValues)
1324
+ {
1325
+ if (!self::checkTrendArrays($yValues, $xValues)) {
1326
+ return PHPExcel_Calculation_Functions::VALUE();
1327
+ }
1328
+ $yValueCount = count($yValues);
1329
+ $xValueCount = count($xValues);
1330
+
1331
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1332
+ return PHPExcel_Calculation_Functions::NA();
1333
+ } elseif ($yValueCount == 1) {
1334
+ return PHPExcel_Calculation_Functions::DIV0();
1335
+ }
1336
+
1337
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues);
1338
+ return $bestFitLinear->getCovariance();
1339
+ }
1340
+
1341
+
1342
+ /**
1343
+ * CRITBINOM
1344
+ *
1345
+ * Returns the smallest value for which the cumulative binomial distribution is greater
1346
+ * than or equal to a criterion value
1347
+ *
1348
+ * See http://support.microsoft.com/kb/828117/ for details of the algorithm used
1349
+ *
1350
+ * @param float $trials number of Bernoulli trials
1351
+ * @param float $probability probability of a success on each trial
1352
+ * @param float $alpha criterion value
1353
+ * @return int
1354
+ *
1355
+ * @todo Warning. This implementation differs from the algorithm detailed on the MS
1356
+ * web site in that $CumPGuessMinus1 = $CumPGuess - 1 rather than $CumPGuess - $PGuess
1357
+ * This eliminates a potential endless loop error, but may have an adverse affect on the
1358
+ * accuracy of the function (although all my tests have so far returned correct results).
1359
+ *
1360
+ */
1361
+ public static function CRITBINOM($trials, $probability, $alpha)
1362
+ {
1363
+ $trials = floor(PHPExcel_Calculation_Functions::flattenSingleValue($trials));
1364
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
1365
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
1366
+
1367
+ if ((is_numeric($trials)) && (is_numeric($probability)) && (is_numeric($alpha))) {
1368
+ if ($trials < 0) {
1369
+ return PHPExcel_Calculation_Functions::NaN();
1370
+ } elseif (($probability < 0) || ($probability > 1)) {
1371
+ return PHPExcel_Calculation_Functions::NaN();
1372
+ } elseif (($alpha < 0) || ($alpha > 1)) {
1373
+ return PHPExcel_Calculation_Functions::NaN();
1374
+ } elseif ($alpha <= 0.5) {
1375
+ $t = sqrt(log(1 / ($alpha * $alpha)));
1376
+ $trialsApprox = 0 - ($t + (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t));
1377
+ } else {
1378
+ $t = sqrt(log(1 / pow(1 - $alpha, 2)));
1379
+ $trialsApprox = $t - (2.515517 + 0.802853 * $t + 0.010328 * $t * $t) / (1 + 1.432788 * $t + 0.189269 * $t * $t + 0.001308 * $t * $t * $t);
1380
+ }
1381
+ $Guess = floor($trials * $probability + $trialsApprox * sqrt($trials * $probability * (1 - $probability)));
1382
+ if ($Guess < 0) {
1383
+ $Guess = 0;
1384
+ } elseif ($Guess > $trials) {
1385
+ $Guess = $trials;
1386
+ }
1387
+
1388
+ $TotalUnscaledProbability = $UnscaledPGuess = $UnscaledCumPGuess = 0.0;
1389
+ $EssentiallyZero = 10e-12;
1390
+
1391
+ $m = floor($trials * $probability);
1392
+ ++$TotalUnscaledProbability;
1393
+ if ($m == $Guess) {
1394
+ ++$UnscaledPGuess;
1395
+ }
1396
+ if ($m <= $Guess) {
1397
+ ++$UnscaledCumPGuess;
1398
+ }
1399
+
1400
+ $PreviousValue = 1;
1401
+ $Done = false;
1402
+ $k = $m + 1;
1403
+ while ((!$Done) && ($k <= $trials)) {
1404
+ $CurrentValue = $PreviousValue * ($trials - $k + 1) * $probability / ($k * (1 - $probability));
1405
+ $TotalUnscaledProbability += $CurrentValue;
1406
+ if ($k == $Guess) {
1407
+ $UnscaledPGuess += $CurrentValue;
1408
+ }
1409
+ if ($k <= $Guess) {
1410
+ $UnscaledCumPGuess += $CurrentValue;
1411
+ }
1412
+ if ($CurrentValue <= $EssentiallyZero) {
1413
+ $Done = true;
1414
+ }
1415
+ $PreviousValue = $CurrentValue;
1416
+ ++$k;
1417
+ }
1418
+
1419
+ $PreviousValue = 1;
1420
+ $Done = false;
1421
+ $k = $m - 1;
1422
+ while ((!$Done) && ($k >= 0)) {
1423
+ $CurrentValue = $PreviousValue * $k + 1 * (1 - $probability) / (($trials - $k) * $probability);
1424
+ $TotalUnscaledProbability += $CurrentValue;
1425
+ if ($k == $Guess) {
1426
+ $UnscaledPGuess += $CurrentValue;
1427
+ }
1428
+ if ($k <= $Guess) {
1429
+ $UnscaledCumPGuess += $CurrentValue;
1430
+ }
1431
+ if ($CurrentValue <= $EssentiallyZero) {
1432
+ $Done = true;
1433
+ }
1434
+ $PreviousValue = $CurrentValue;
1435
+ --$k;
1436
+ }
1437
+
1438
+ $PGuess = $UnscaledPGuess / $TotalUnscaledProbability;
1439
+ $CumPGuess = $UnscaledCumPGuess / $TotalUnscaledProbability;
1440
+
1441
+ // $CumPGuessMinus1 = $CumPGuess - $PGuess;
1442
+ $CumPGuessMinus1 = $CumPGuess - 1;
1443
+
1444
+ while (true) {
1445
+ if (($CumPGuessMinus1 < $alpha) && ($CumPGuess >= $alpha)) {
1446
+ return $Guess;
1447
+ } elseif (($CumPGuessMinus1 < $alpha) && ($CumPGuess < $alpha)) {
1448
+ $PGuessPlus1 = $PGuess * ($trials - $Guess) * $probability / $Guess / (1 - $probability);
1449
+ $CumPGuessMinus1 = $CumPGuess;
1450
+ $CumPGuess = $CumPGuess + $PGuessPlus1;
1451
+ $PGuess = $PGuessPlus1;
1452
+ ++$Guess;
1453
+ } elseif (($CumPGuessMinus1 >= $alpha) && ($CumPGuess >= $alpha)) {
1454
+ $PGuessMinus1 = $PGuess * $Guess * (1 - $probability) / ($trials - $Guess + 1) / $probability;
1455
+ $CumPGuess = $CumPGuessMinus1;
1456
+ $CumPGuessMinus1 = $CumPGuessMinus1 - $PGuess;
1457
+ $PGuess = $PGuessMinus1;
1458
+ --$Guess;
1459
+ }
1460
+ }
1461
+ }
1462
+ return PHPExcel_Calculation_Functions::VALUE();
1463
+ }
1464
+
1465
+
1466
+ /**
1467
+ * DEVSQ
1468
+ *
1469
+ * Returns the sum of squares of deviations of data points from their sample mean.
1470
+ *
1471
+ * Excel Function:
1472
+ * DEVSQ(value1[,value2[, ...]])
1473
+ *
1474
+ * @access public
1475
+ * @category Statistical Functions
1476
+ * @param mixed $arg,... Data values
1477
+ * @return float
1478
+ */
1479
+ public static function DEVSQ()
1480
+ {
1481
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
1482
+
1483
+ // Return value
1484
+ $returnValue = null;
1485
+
1486
+ $aMean = self::AVERAGE($aArgs);
1487
+ if ($aMean != PHPExcel_Calculation_Functions::DIV0()) {
1488
+ $aCount = -1;
1489
+ foreach ($aArgs as $k => $arg) {
1490
+ // Is it a numeric value?
1491
+ if ((is_bool($arg)) &&
1492
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) ||
1493
+ (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
1494
+ $arg = (integer) $arg;
1495
+ }
1496
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1497
+ if (is_null($returnValue)) {
1498
+ $returnValue = pow(($arg - $aMean), 2);
1499
+ } else {
1500
+ $returnValue += pow(($arg - $aMean), 2);
1501
+ }
1502
+ ++$aCount;
1503
+ }
1504
+ }
1505
+
1506
+ // Return
1507
+ if (is_null($returnValue)) {
1508
+ return PHPExcel_Calculation_Functions::NaN();
1509
+ } else {
1510
+ return $returnValue;
1511
+ }
1512
+ }
1513
+ return self::NA();
1514
+ }
1515
+
1516
+
1517
+ /**
1518
+ * EXPONDIST
1519
+ *
1520
+ * Returns the exponential distribution. Use EXPONDIST to model the time between events,
1521
+ * such as how long an automated bank teller takes to deliver cash. For example, you can
1522
+ * use EXPONDIST to determine the probability that the process takes at most 1 minute.
1523
+ *
1524
+ * @param float $value Value of the function
1525
+ * @param float $lambda The parameter value
1526
+ * @param boolean $cumulative
1527
+ * @return float
1528
+ */
1529
+ public static function EXPONDIST($value, $lambda, $cumulative)
1530
+ {
1531
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1532
+ $lambda = PHPExcel_Calculation_Functions::flattenSingleValue($lambda);
1533
+ $cumulative = PHPExcel_Calculation_Functions::flattenSingleValue($cumulative);
1534
+
1535
+ if ((is_numeric($value)) && (is_numeric($lambda))) {
1536
+ if (($value < 0) || ($lambda < 0)) {
1537
+ return PHPExcel_Calculation_Functions::NaN();
1538
+ }
1539
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
1540
+ if ($cumulative) {
1541
+ return 1 - exp(0-$value*$lambda);
1542
+ } else {
1543
+ return $lambda * exp(0-$value*$lambda);
1544
+ }
1545
+ }
1546
+ }
1547
+ return PHPExcel_Calculation_Functions::VALUE();
1548
+ }
1549
+
1550
+
1551
+ /**
1552
+ * FISHER
1553
+ *
1554
+ * Returns the Fisher transformation at x. This transformation produces a function that
1555
+ * is normally distributed rather than skewed. Use this function to perform hypothesis
1556
+ * testing on the correlation coefficient.
1557
+ *
1558
+ * @param float $value
1559
+ * @return float
1560
+ */
1561
+ public static function FISHER($value)
1562
+ {
1563
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1564
+
1565
+ if (is_numeric($value)) {
1566
+ if (($value <= -1) || ($value >= 1)) {
1567
+ return PHPExcel_Calculation_Functions::NaN();
1568
+ }
1569
+ return 0.5 * log((1+$value)/(1-$value));
1570
+ }
1571
+ return PHPExcel_Calculation_Functions::VALUE();
1572
+ }
1573
+
1574
+
1575
+ /**
1576
+ * FISHERINV
1577
+ *
1578
+ * Returns the inverse of the Fisher transformation. Use this transformation when
1579
+ * analyzing correlations between ranges or arrays of data. If y = FISHER(x), then
1580
+ * FISHERINV(y) = x.
1581
+ *
1582
+ * @param float $value
1583
+ * @return float
1584
+ */
1585
+ public static function FISHERINV($value)
1586
+ {
1587
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1588
+
1589
+ if (is_numeric($value)) {
1590
+ return (exp(2 * $value) - 1) / (exp(2 * $value) + 1);
1591
+ }
1592
+ return PHPExcel_Calculation_Functions::VALUE();
1593
+ }
1594
+
1595
+
1596
+ /**
1597
+ * FORECAST
1598
+ *
1599
+ * Calculates, or predicts, a future value by using existing values. The predicted value is a y-value for a given x-value.
1600
+ *
1601
+ * @param float Value of X for which we want to find Y
1602
+ * @param array of mixed Data Series Y
1603
+ * @param array of mixed Data Series X
1604
+ * @return float
1605
+ */
1606
+ public static function FORECAST($xValue, $yValues, $xValues)
1607
+ {
1608
+ $xValue = PHPExcel_Calculation_Functions::flattenSingleValue($xValue);
1609
+ if (!is_numeric($xValue)) {
1610
+ return PHPExcel_Calculation_Functions::VALUE();
1611
+ } elseif (!self::checkTrendArrays($yValues, $xValues)) {
1612
+ return PHPExcel_Calculation_Functions::VALUE();
1613
+ }
1614
+ $yValueCount = count($yValues);
1615
+ $xValueCount = count($xValues);
1616
+
1617
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1618
+ return PHPExcel_Calculation_Functions::NA();
1619
+ } elseif ($yValueCount == 1) {
1620
+ return PHPExcel_Calculation_Functions::DIV0();
1621
+ }
1622
+
1623
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues);
1624
+ return $bestFitLinear->getValueOfYForX($xValue);
1625
+ }
1626
+
1627
+
1628
+ /**
1629
+ * GAMMADIST
1630
+ *
1631
+ * Returns the gamma distribution.
1632
+ *
1633
+ * @param float $value Value at which you want to evaluate the distribution
1634
+ * @param float $a Parameter to the distribution
1635
+ * @param float $b Parameter to the distribution
1636
+ * @param boolean $cumulative
1637
+ * @return float
1638
+ *
1639
+ */
1640
+ public static function GAMMADIST($value, $a, $b, $cumulative)
1641
+ {
1642
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1643
+ $a = PHPExcel_Calculation_Functions::flattenSingleValue($a);
1644
+ $b = PHPExcel_Calculation_Functions::flattenSingleValue($b);
1645
+
1646
+ if ((is_numeric($value)) && (is_numeric($a)) && (is_numeric($b))) {
1647
+ if (($value < 0) || ($a <= 0) || ($b <= 0)) {
1648
+ return PHPExcel_Calculation_Functions::NaN();
1649
+ }
1650
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
1651
+ if ($cumulative) {
1652
+ return self::incompleteGamma($a, $value / $b) / self::gamma($a);
1653
+ } else {
1654
+ return (1 / (pow($b, $a) * self::gamma($a))) * pow($value, $a-1) * exp(0-($value / $b));
1655
+ }
1656
+ }
1657
+ }
1658
+ return PHPExcel_Calculation_Functions::VALUE();
1659
+ }
1660
+
1661
+
1662
+ /**
1663
+ * GAMMAINV
1664
+ *
1665
+ * Returns the inverse of the beta distribution.
1666
+ *
1667
+ * @param float $probability Probability at which you want to evaluate the distribution
1668
+ * @param float $alpha Parameter to the distribution
1669
+ * @param float $beta Parameter to the distribution
1670
+ * @return float
1671
+ *
1672
+ */
1673
+ public static function GAMMAINV($probability, $alpha, $beta)
1674
+ {
1675
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
1676
+ $alpha = PHPExcel_Calculation_Functions::flattenSingleValue($alpha);
1677
+ $beta = PHPExcel_Calculation_Functions::flattenSingleValue($beta);
1678
+
1679
+ if ((is_numeric($probability)) && (is_numeric($alpha)) && (is_numeric($beta))) {
1680
+ if (($alpha <= 0) || ($beta <= 0) || ($probability < 0) || ($probability > 1)) {
1681
+ return PHPExcel_Calculation_Functions::NaN();
1682
+ }
1683
+
1684
+ $xLo = 0;
1685
+ $xHi = $alpha * $beta * 5;
1686
+
1687
+ $x = $xNew = 1;
1688
+ $error = $pdf = 0;
1689
+ $dx = 1024;
1690
+ $i = 0;
1691
+
1692
+ while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
1693
+ // Apply Newton-Raphson step
1694
+ $error = self::GAMMADIST($x, $alpha, $beta, true) - $probability;
1695
+ if ($error < 0.0) {
1696
+ $xLo = $x;
1697
+ } else {
1698
+ $xHi = $x;
1699
+ }
1700
+ $pdf = self::GAMMADIST($x, $alpha, $beta, false);
1701
+ // Avoid division by zero
1702
+ if ($pdf != 0.0) {
1703
+ $dx = $error / $pdf;
1704
+ $xNew = $x - $dx;
1705
+ }
1706
+ // If the NR fails to converge (which for example may be the
1707
+ // case if the initial guess is too rough) we apply a bisection
1708
+ // step to determine a more narrow interval around the root.
1709
+ if (($xNew < $xLo) || ($xNew > $xHi) || ($pdf == 0.0)) {
1710
+ $xNew = ($xLo + $xHi) / 2;
1711
+ $dx = $xNew - $x;
1712
+ }
1713
+ $x = $xNew;
1714
+ }
1715
+ if ($i == MAX_ITERATIONS) {
1716
+ return PHPExcel_Calculation_Functions::NA();
1717
+ }
1718
+ return $x;
1719
+ }
1720
+ return PHPExcel_Calculation_Functions::VALUE();
1721
+ }
1722
+
1723
+
1724
+ /**
1725
+ * GAMMALN
1726
+ *
1727
+ * Returns the natural logarithm of the gamma function.
1728
+ *
1729
+ * @param float $value
1730
+ * @return float
1731
+ */
1732
+ public static function GAMMALN($value)
1733
+ {
1734
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
1735
+
1736
+ if (is_numeric($value)) {
1737
+ if ($value <= 0) {
1738
+ return PHPExcel_Calculation_Functions::NaN();
1739
+ }
1740
+ return log(self::gamma($value));
1741
+ }
1742
+ return PHPExcel_Calculation_Functions::VALUE();
1743
+ }
1744
+
1745
+
1746
+ /**
1747
+ * GEOMEAN
1748
+ *
1749
+ * Returns the geometric mean of an array or range of positive data. For example, you
1750
+ * can use GEOMEAN to calculate average growth rate given compound interest with
1751
+ * variable rates.
1752
+ *
1753
+ * Excel Function:
1754
+ * GEOMEAN(value1[,value2[, ...]])
1755
+ *
1756
+ * @access public
1757
+ * @category Statistical Functions
1758
+ * @param mixed $arg,... Data values
1759
+ * @return float
1760
+ */
1761
+ public static function GEOMEAN()
1762
+ {
1763
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1764
+
1765
+ $aMean = PHPExcel_Calculation_MathTrig::PRODUCT($aArgs);
1766
+ if (is_numeric($aMean) && ($aMean > 0)) {
1767
+ $aCount = self::COUNT($aArgs) ;
1768
+ if (self::MIN($aArgs) > 0) {
1769
+ return pow($aMean, (1 / $aCount));
1770
+ }
1771
+ }
1772
+ return PHPExcel_Calculation_Functions::NaN();
1773
+ }
1774
+
1775
+
1776
+ /**
1777
+ * GROWTH
1778
+ *
1779
+ * Returns values along a predicted emponential trend
1780
+ *
1781
+ * @param array of mixed Data Series Y
1782
+ * @param array of mixed Data Series X
1783
+ * @param array of mixed Values of X for which we want to find Y
1784
+ * @param boolean A logical value specifying whether to force the intersect to equal 0.
1785
+ * @return array of float
1786
+ */
1787
+ public static function GROWTH($yValues, $xValues = array(), $newValues = array(), $const = true)
1788
+ {
1789
+ $yValues = PHPExcel_Calculation_Functions::flattenArray($yValues);
1790
+ $xValues = PHPExcel_Calculation_Functions::flattenArray($xValues);
1791
+ $newValues = PHPExcel_Calculation_Functions::flattenArray($newValues);
1792
+ $const = (is_null($const)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const);
1793
+
1794
+ $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL, $yValues, $xValues, $const);
1795
+ if (empty($newValues)) {
1796
+ $newValues = $bestFitExponential->getXValues();
1797
+ }
1798
+
1799
+ $returnArray = array();
1800
+ foreach ($newValues as $xValue) {
1801
+ $returnArray[0][] = $bestFitExponential->getValueOfYForX($xValue);
1802
+ }
1803
+
1804
+ return $returnArray;
1805
+ }
1806
+
1807
+
1808
+ /**
1809
+ * HARMEAN
1810
+ *
1811
+ * Returns the harmonic mean of a data set. The harmonic mean is the reciprocal of the
1812
+ * arithmetic mean of reciprocals.
1813
+ *
1814
+ * Excel Function:
1815
+ * HARMEAN(value1[,value2[, ...]])
1816
+ *
1817
+ * @access public
1818
+ * @category Statistical Functions
1819
+ * @param mixed $arg,... Data values
1820
+ * @return float
1821
+ */
1822
+ public static function HARMEAN()
1823
+ {
1824
+ // Return value
1825
+ $returnValue = PHPExcel_Calculation_Functions::NA();
1826
+
1827
+ // Loop through arguments
1828
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1829
+ if (self::MIN($aArgs) < 0) {
1830
+ return PHPExcel_Calculation_Functions::NaN();
1831
+ }
1832
+ $aCount = 0;
1833
+ foreach ($aArgs as $arg) {
1834
+ // Is it a numeric value?
1835
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1836
+ if ($arg <= 0) {
1837
+ return PHPExcel_Calculation_Functions::NaN();
1838
+ }
1839
+ if (is_null($returnValue)) {
1840
+ $returnValue = (1 / $arg);
1841
+ } else {
1842
+ $returnValue += (1 / $arg);
1843
+ }
1844
+ ++$aCount;
1845
+ }
1846
+ }
1847
+
1848
+ // Return
1849
+ if ($aCount > 0) {
1850
+ return 1 / ($returnValue / $aCount);
1851
+ } else {
1852
+ return $returnValue;
1853
+ }
1854
+ }
1855
+
1856
+
1857
+ /**
1858
+ * HYPGEOMDIST
1859
+ *
1860
+ * Returns the hypergeometric distribution. HYPGEOMDIST returns the probability of a given number of
1861
+ * sample successes, given the sample size, population successes, and population size.
1862
+ *
1863
+ * @param float $sampleSuccesses Number of successes in the sample
1864
+ * @param float $sampleNumber Size of the sample
1865
+ * @param float $populationSuccesses Number of successes in the population
1866
+ * @param float $populationNumber Population size
1867
+ * @return float
1868
+ *
1869
+ */
1870
+ public static function HYPGEOMDIST($sampleSuccesses, $sampleNumber, $populationSuccesses, $populationNumber)
1871
+ {
1872
+ $sampleSuccesses = floor(PHPExcel_Calculation_Functions::flattenSingleValue($sampleSuccesses));
1873
+ $sampleNumber = floor(PHPExcel_Calculation_Functions::flattenSingleValue($sampleNumber));
1874
+ $populationSuccesses = floor(PHPExcel_Calculation_Functions::flattenSingleValue($populationSuccesses));
1875
+ $populationNumber = floor(PHPExcel_Calculation_Functions::flattenSingleValue($populationNumber));
1876
+
1877
+ if ((is_numeric($sampleSuccesses)) && (is_numeric($sampleNumber)) && (is_numeric($populationSuccesses)) && (is_numeric($populationNumber))) {
1878
+ if (($sampleSuccesses < 0) || ($sampleSuccesses > $sampleNumber) || ($sampleSuccesses > $populationSuccesses)) {
1879
+ return PHPExcel_Calculation_Functions::NaN();
1880
+ }
1881
+ if (($sampleNumber <= 0) || ($sampleNumber > $populationNumber)) {
1882
+ return PHPExcel_Calculation_Functions::NaN();
1883
+ }
1884
+ if (($populationSuccesses <= 0) || ($populationSuccesses > $populationNumber)) {
1885
+ return PHPExcel_Calculation_Functions::NaN();
1886
+ }
1887
+ return PHPExcel_Calculation_MathTrig::COMBIN($populationSuccesses, $sampleSuccesses) *
1888
+ PHPExcel_Calculation_MathTrig::COMBIN($populationNumber - $populationSuccesses, $sampleNumber - $sampleSuccesses) /
1889
+ PHPExcel_Calculation_MathTrig::COMBIN($populationNumber, $sampleNumber);
1890
+ }
1891
+ return PHPExcel_Calculation_Functions::VALUE();
1892
+ }
1893
+
1894
+
1895
+ /**
1896
+ * INTERCEPT
1897
+ *
1898
+ * Calculates the point at which a line will intersect the y-axis by using existing x-values and y-values.
1899
+ *
1900
+ * @param array of mixed Data Series Y
1901
+ * @param array of mixed Data Series X
1902
+ * @return float
1903
+ */
1904
+ public static function INTERCEPT($yValues, $xValues)
1905
+ {
1906
+ if (!self::checkTrendArrays($yValues, $xValues)) {
1907
+ return PHPExcel_Calculation_Functions::VALUE();
1908
+ }
1909
+ $yValueCount = count($yValues);
1910
+ $xValueCount = count($xValues);
1911
+
1912
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
1913
+ return PHPExcel_Calculation_Functions::NA();
1914
+ } elseif ($yValueCount == 1) {
1915
+ return PHPExcel_Calculation_Functions::DIV0();
1916
+ }
1917
+
1918
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues);
1919
+ return $bestFitLinear->getIntersect();
1920
+ }
1921
+
1922
+
1923
+ /**
1924
+ * KURT
1925
+ *
1926
+ * Returns the kurtosis of a data set. Kurtosis characterizes the relative peakedness
1927
+ * or flatness of a distribution compared with the normal distribution. Positive
1928
+ * kurtosis indicates a relatively peaked distribution. Negative kurtosis indicates a
1929
+ * relatively flat distribution.
1930
+ *
1931
+ * @param array Data Series
1932
+ * @return float
1933
+ */
1934
+ public static function KURT()
1935
+ {
1936
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
1937
+ $mean = self::AVERAGE($aArgs);
1938
+ $stdDev = self::STDEV($aArgs);
1939
+
1940
+ if ($stdDev > 0) {
1941
+ $count = $summer = 0;
1942
+ // Loop through arguments
1943
+ foreach ($aArgs as $k => $arg) {
1944
+ if ((is_bool($arg)) &&
1945
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
1946
+ } else {
1947
+ // Is it a numeric value?
1948
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1949
+ $summer += pow((($arg - $mean) / $stdDev), 4);
1950
+ ++$count;
1951
+ }
1952
+ }
1953
+ }
1954
+
1955
+ // Return
1956
+ if ($count > 3) {
1957
+ return $summer * ($count * ($count+1) / (($count-1) * ($count-2) * ($count-3))) - (3 * pow($count-1, 2) / (($count-2) * ($count-3)));
1958
+ }
1959
+ }
1960
+ return PHPExcel_Calculation_Functions::DIV0();
1961
+ }
1962
+
1963
+
1964
+ /**
1965
+ * LARGE
1966
+ *
1967
+ * Returns the nth largest value in a data set. You can use this function to
1968
+ * select a value based on its relative standing.
1969
+ *
1970
+ * Excel Function:
1971
+ * LARGE(value1[,value2[, ...]],entry)
1972
+ *
1973
+ * @access public
1974
+ * @category Statistical Functions
1975
+ * @param mixed $arg,... Data values
1976
+ * @param int $entry Position (ordered from the largest) in the array or range of data to return
1977
+ * @return float
1978
+ *
1979
+ */
1980
+ public static function LARGE()
1981
+ {
1982
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
1983
+
1984
+ // Calculate
1985
+ $entry = floor(array_pop($aArgs));
1986
+
1987
+ if ((is_numeric($entry)) && (!is_string($entry))) {
1988
+ $mArgs = array();
1989
+ foreach ($aArgs as $arg) {
1990
+ // Is it a numeric value?
1991
+ if ((is_numeric($arg)) && (!is_string($arg))) {
1992
+ $mArgs[] = $arg;
1993
+ }
1994
+ }
1995
+ $count = self::COUNT($mArgs);
1996
+ $entry = floor(--$entry);
1997
+ if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
1998
+ return PHPExcel_Calculation_Functions::NaN();
1999
+ }
2000
+ rsort($mArgs);
2001
+ return $mArgs[$entry];
2002
+ }
2003
+ return PHPExcel_Calculation_Functions::VALUE();
2004
+ }
2005
+
2006
+
2007
+ /**
2008
+ * LINEST
2009
+ *
2010
+ * Calculates the statistics for a line by using the "least squares" method to calculate a straight line that best fits your data,
2011
+ * and then returns an array that describes the line.
2012
+ *
2013
+ * @param array of mixed Data Series Y
2014
+ * @param array of mixed Data Series X
2015
+ * @param boolean A logical value specifying whether to force the intersect to equal 0.
2016
+ * @param boolean A logical value specifying whether to return additional regression statistics.
2017
+ * @return array
2018
+ */
2019
+ public static function LINEST($yValues, $xValues = null, $const = true, $stats = false)
2020
+ {
2021
+ $const = (is_null($const)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const);
2022
+ $stats = (is_null($stats)) ? false : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($stats);
2023
+ if (is_null($xValues)) {
2024
+ $xValues = range(1, count(PHPExcel_Calculation_Functions::flattenArray($yValues)));
2025
+ }
2026
+
2027
+ if (!self::checkTrendArrays($yValues, $xValues)) {
2028
+ return PHPExcel_Calculation_Functions::VALUE();
2029
+ }
2030
+ $yValueCount = count($yValues);
2031
+ $xValueCount = count($xValues);
2032
+
2033
+
2034
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
2035
+ return PHPExcel_Calculation_Functions::NA();
2036
+ } elseif ($yValueCount == 1) {
2037
+ return 0;
2038
+ }
2039
+
2040
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues, $const);
2041
+ if ($stats) {
2042
+ return array(
2043
+ array(
2044
+ $bestFitLinear->getSlope(),
2045
+ $bestFitLinear->getSlopeSE(),
2046
+ $bestFitLinear->getGoodnessOfFit(),
2047
+ $bestFitLinear->getF(),
2048
+ $bestFitLinear->getSSRegression(),
2049
+ ),
2050
+ array(
2051
+ $bestFitLinear->getIntersect(),
2052
+ $bestFitLinear->getIntersectSE(),
2053
+ $bestFitLinear->getStdevOfResiduals(),
2054
+ $bestFitLinear->getDFResiduals(),
2055
+ $bestFitLinear->getSSResiduals()
2056
+ )
2057
+ );
2058
+ } else {
2059
+ return array(
2060
+ $bestFitLinear->getSlope(),
2061
+ $bestFitLinear->getIntersect()
2062
+ );
2063
+ }
2064
+ }
2065
+
2066
+
2067
+ /**
2068
+ * LOGEST
2069
+ *
2070
+ * Calculates an exponential curve that best fits the X and Y data series,
2071
+ * and then returns an array that describes the line.
2072
+ *
2073
+ * @param array of mixed Data Series Y
2074
+ * @param array of mixed Data Series X
2075
+ * @param boolean A logical value specifying whether to force the intersect to equal 0.
2076
+ * @param boolean A logical value specifying whether to return additional regression statistics.
2077
+ * @return array
2078
+ */
2079
+ public static function LOGEST($yValues, $xValues = null, $const = true, $stats = false)
2080
+ {
2081
+ $const = (is_null($const)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const);
2082
+ $stats = (is_null($stats)) ? false : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($stats);
2083
+ if (is_null($xValues)) {
2084
+ $xValues = range(1, count(PHPExcel_Calculation_Functions::flattenArray($yValues)));
2085
+ }
2086
+
2087
+ if (!self::checkTrendArrays($yValues, $xValues)) {
2088
+ return PHPExcel_Calculation_Functions::VALUE();
2089
+ }
2090
+ $yValueCount = count($yValues);
2091
+ $xValueCount = count($xValues);
2092
+
2093
+ foreach ($yValues as $value) {
2094
+ if ($value <= 0.0) {
2095
+ return PHPExcel_Calculation_Functions::NaN();
2096
+ }
2097
+ }
2098
+
2099
+
2100
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
2101
+ return PHPExcel_Calculation_Functions::NA();
2102
+ } elseif ($yValueCount == 1) {
2103
+ return 1;
2104
+ }
2105
+
2106
+ $bestFitExponential = trendClass::calculate(trendClass::TREND_EXPONENTIAL, $yValues, $xValues, $const);
2107
+ if ($stats) {
2108
+ return array(
2109
+ array(
2110
+ $bestFitExponential->getSlope(),
2111
+ $bestFitExponential->getSlopeSE(),
2112
+ $bestFitExponential->getGoodnessOfFit(),
2113
+ $bestFitExponential->getF(),
2114
+ $bestFitExponential->getSSRegression(),
2115
+ ),
2116
+ array(
2117
+ $bestFitExponential->getIntersect(),
2118
+ $bestFitExponential->getIntersectSE(),
2119
+ $bestFitExponential->getStdevOfResiduals(),
2120
+ $bestFitExponential->getDFResiduals(),
2121
+ $bestFitExponential->getSSResiduals()
2122
+ )
2123
+ );
2124
+ } else {
2125
+ return array(
2126
+ $bestFitExponential->getSlope(),
2127
+ $bestFitExponential->getIntersect()
2128
+ );
2129
+ }
2130
+ }
2131
+
2132
+
2133
+ /**
2134
+ * LOGINV
2135
+ *
2136
+ * Returns the inverse of the normal cumulative distribution
2137
+ *
2138
+ * @param float $probability
2139
+ * @param float $mean
2140
+ * @param float $stdDev
2141
+ * @return float
2142
+ *
2143
+ * @todo Try implementing P J Acklam's refinement algorithm for greater
2144
+ * accuracy if I can get my head round the mathematics
2145
+ * (as described at) http://home.online.no/~pjacklam/notes/invnorm/
2146
+ */
2147
+ public static function LOGINV($probability, $mean, $stdDev)
2148
+ {
2149
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
2150
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2151
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2152
+
2153
+ if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2154
+ if (($probability < 0) || ($probability > 1) || ($stdDev <= 0)) {
2155
+ return PHPExcel_Calculation_Functions::NaN();
2156
+ }
2157
+ return exp($mean + $stdDev * self::NORMSINV($probability));
2158
+ }
2159
+ return PHPExcel_Calculation_Functions::VALUE();
2160
+ }
2161
+
2162
+
2163
+ /**
2164
+ * LOGNORMDIST
2165
+ *
2166
+ * Returns the cumulative lognormal distribution of x, where ln(x) is normally distributed
2167
+ * with parameters mean and standard_dev.
2168
+ *
2169
+ * @param float $value
2170
+ * @param float $mean
2171
+ * @param float $stdDev
2172
+ * @return float
2173
+ */
2174
+ public static function LOGNORMDIST($value, $mean, $stdDev)
2175
+ {
2176
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2177
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2178
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2179
+
2180
+ if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2181
+ if (($value <= 0) || ($stdDev <= 0)) {
2182
+ return PHPExcel_Calculation_Functions::NaN();
2183
+ }
2184
+ return self::NORMSDIST((log($value) - $mean) / $stdDev);
2185
+ }
2186
+ return PHPExcel_Calculation_Functions::VALUE();
2187
+ }
2188
+
2189
+
2190
+ /**
2191
+ * MAX
2192
+ *
2193
+ * MAX returns the value of the element of the values passed that has the highest value,
2194
+ * with negative numbers considered smaller than positive numbers.
2195
+ *
2196
+ * Excel Function:
2197
+ * MAX(value1[,value2[, ...]])
2198
+ *
2199
+ * @access public
2200
+ * @category Statistical Functions
2201
+ * @param mixed $arg,... Data values
2202
+ * @return float
2203
+ */
2204
+ public static function MAX()
2205
+ {
2206
+ $returnValue = null;
2207
+
2208
+ // Loop through arguments
2209
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2210
+ foreach ($aArgs as $arg) {
2211
+ // Is it a numeric value?
2212
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2213
+ if ((is_null($returnValue)) || ($arg > $returnValue)) {
2214
+ $returnValue = $arg;
2215
+ }
2216
+ }
2217
+ }
2218
+
2219
+ if (is_null($returnValue)) {
2220
+ return 0;
2221
+ }
2222
+ return $returnValue;
2223
+ }
2224
+
2225
+
2226
+ /**
2227
+ * MAXA
2228
+ *
2229
+ * Returns the greatest value in a list of arguments, including numbers, text, and logical values
2230
+ *
2231
+ * Excel Function:
2232
+ * MAXA(value1[,value2[, ...]])
2233
+ *
2234
+ * @access public
2235
+ * @category Statistical Functions
2236
+ * @param mixed $arg,... Data values
2237
+ * @return float
2238
+ */
2239
+ public static function MAXA()
2240
+ {
2241
+ $returnValue = null;
2242
+
2243
+ // Loop through arguments
2244
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2245
+ foreach ($aArgs as $arg) {
2246
+ // Is it a numeric value?
2247
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
2248
+ if (is_bool($arg)) {
2249
+ $arg = (integer) $arg;
2250
+ } elseif (is_string($arg)) {
2251
+ $arg = 0;
2252
+ }
2253
+ if ((is_null($returnValue)) || ($arg > $returnValue)) {
2254
+ $returnValue = $arg;
2255
+ }
2256
+ }
2257
+ }
2258
+
2259
+ if (is_null($returnValue)) {
2260
+ return 0;
2261
+ }
2262
+ return $returnValue;
2263
+ }
2264
+
2265
+
2266
+ /**
2267
+ * MAXIF
2268
+ *
2269
+ * Counts the maximum value within a range of cells that contain numbers within the list of arguments
2270
+ *
2271
+ * Excel Function:
2272
+ * MAXIF(value1[,value2[, ...]],condition)
2273
+ *
2274
+ * @access public
2275
+ * @category Mathematical and Trigonometric Functions
2276
+ * @param mixed $arg,... Data values
2277
+ * @param string $condition The criteria that defines which cells will be checked.
2278
+ * @return float
2279
+ */
2280
+ public static function MAXIF($aArgs, $condition, $sumArgs = array())
2281
+ {
2282
+ $returnValue = null;
2283
+
2284
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
2285
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
2286
+ if (empty($sumArgs)) {
2287
+ $sumArgs = $aArgs;
2288
+ }
2289
+ $condition = PHPExcel_Calculation_Functions::ifCondition($condition);
2290
+ // Loop through arguments
2291
+ foreach ($aArgs as $key => $arg) {
2292
+ if (!is_numeric($arg)) {
2293
+ $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg));
2294
+ }
2295
+ $testCondition = '='.$arg.$condition;
2296
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
2297
+ if ((is_null($returnValue)) || ($arg > $returnValue)) {
2298
+ $returnValue = $arg;
2299
+ }
2300
+ }
2301
+ }
2302
+
2303
+ return $returnValue;
2304
+ }
2305
+
2306
+ /**
2307
+ * MEDIAN
2308
+ *
2309
+ * Returns the median of the given numbers. The median is the number in the middle of a set of numbers.
2310
+ *
2311
+ * Excel Function:
2312
+ * MEDIAN(value1[,value2[, ...]])
2313
+ *
2314
+ * @access public
2315
+ * @category Statistical Functions
2316
+ * @param mixed $arg,... Data values
2317
+ * @return float
2318
+ */
2319
+ public static function MEDIAN()
2320
+ {
2321
+ $returnValue = PHPExcel_Calculation_Functions::NaN();
2322
+
2323
+ $mArgs = array();
2324
+ // Loop through arguments
2325
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2326
+ foreach ($aArgs as $arg) {
2327
+ // Is it a numeric value?
2328
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2329
+ $mArgs[] = $arg;
2330
+ }
2331
+ }
2332
+
2333
+ $mValueCount = count($mArgs);
2334
+ if ($mValueCount > 0) {
2335
+ sort($mArgs, SORT_NUMERIC);
2336
+ $mValueCount = $mValueCount / 2;
2337
+ if ($mValueCount == floor($mValueCount)) {
2338
+ $returnValue = ($mArgs[$mValueCount--] + $mArgs[$mValueCount]) / 2;
2339
+ } else {
2340
+ $mValueCount = floor($mValueCount);
2341
+ $returnValue = $mArgs[$mValueCount];
2342
+ }
2343
+ }
2344
+
2345
+ return $returnValue;
2346
+ }
2347
+
2348
+
2349
+ /**
2350
+ * MIN
2351
+ *
2352
+ * MIN returns the value of the element of the values passed that has the smallest value,
2353
+ * with negative numbers considered smaller than positive numbers.
2354
+ *
2355
+ * Excel Function:
2356
+ * MIN(value1[,value2[, ...]])
2357
+ *
2358
+ * @access public
2359
+ * @category Statistical Functions
2360
+ * @param mixed $arg,... Data values
2361
+ * @return float
2362
+ */
2363
+ public static function MIN()
2364
+ {
2365
+ $returnValue = null;
2366
+
2367
+ // Loop through arguments
2368
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2369
+ foreach ($aArgs as $arg) {
2370
+ // Is it a numeric value?
2371
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2372
+ if ((is_null($returnValue)) || ($arg < $returnValue)) {
2373
+ $returnValue = $arg;
2374
+ }
2375
+ }
2376
+ }
2377
+
2378
+ if (is_null($returnValue)) {
2379
+ return 0;
2380
+ }
2381
+ return $returnValue;
2382
+ }
2383
+
2384
+
2385
+ /**
2386
+ * MINA
2387
+ *
2388
+ * Returns the smallest value in a list of arguments, including numbers, text, and logical values
2389
+ *
2390
+ * Excel Function:
2391
+ * MINA(value1[,value2[, ...]])
2392
+ *
2393
+ * @access public
2394
+ * @category Statistical Functions
2395
+ * @param mixed $arg,... Data values
2396
+ * @return float
2397
+ */
2398
+ public static function MINA()
2399
+ {
2400
+ $returnValue = null;
2401
+
2402
+ // Loop through arguments
2403
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2404
+ foreach ($aArgs as $arg) {
2405
+ // Is it a numeric value?
2406
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) && ($arg != '')))) {
2407
+ if (is_bool($arg)) {
2408
+ $arg = (integer) $arg;
2409
+ } elseif (is_string($arg)) {
2410
+ $arg = 0;
2411
+ }
2412
+ if ((is_null($returnValue)) || ($arg < $returnValue)) {
2413
+ $returnValue = $arg;
2414
+ }
2415
+ }
2416
+ }
2417
+
2418
+ if (is_null($returnValue)) {
2419
+ return 0;
2420
+ }
2421
+ return $returnValue;
2422
+ }
2423
+
2424
+
2425
+ /**
2426
+ * MINIF
2427
+ *
2428
+ * Returns the minimum value within a range of cells that contain numbers within the list of arguments
2429
+ *
2430
+ * Excel Function:
2431
+ * MINIF(value1[,value2[, ...]],condition)
2432
+ *
2433
+ * @access public
2434
+ * @category Mathematical and Trigonometric Functions
2435
+ * @param mixed $arg,... Data values
2436
+ * @param string $condition The criteria that defines which cells will be checked.
2437
+ * @return float
2438
+ */
2439
+ public static function MINIF($aArgs, $condition, $sumArgs = array())
2440
+ {
2441
+ $returnValue = null;
2442
+
2443
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray($aArgs);
2444
+ $sumArgs = PHPExcel_Calculation_Functions::flattenArray($sumArgs);
2445
+ if (empty($sumArgs)) {
2446
+ $sumArgs = $aArgs;
2447
+ }
2448
+ $condition = PHPExcel_Calculation_Functions::ifCondition($condition);
2449
+ // Loop through arguments
2450
+ foreach ($aArgs as $key => $arg) {
2451
+ if (!is_numeric($arg)) {
2452
+ $arg = PHPExcel_Calculation::wrapResult(strtoupper($arg));
2453
+ }
2454
+ $testCondition = '='.$arg.$condition;
2455
+ if (PHPExcel_Calculation::getInstance()->_calculateFormulaValue($testCondition)) {
2456
+ if ((is_null($returnValue)) || ($arg < $returnValue)) {
2457
+ $returnValue = $arg;
2458
+ }
2459
+ }
2460
+ }
2461
+
2462
+ return $returnValue;
2463
+ }
2464
+
2465
+
2466
+ //
2467
+ // Special variant of array_count_values that isn't limited to strings and integers,
2468
+ // but can work with floating point numbers as values
2469
+ //
2470
+ private static function modeCalc($data)
2471
+ {
2472
+ $frequencyArray = array();
2473
+ foreach ($data as $datum) {
2474
+ $found = false;
2475
+ foreach ($frequencyArray as $key => $value) {
2476
+ if ((string) $value['value'] == (string) $datum) {
2477
+ ++$frequencyArray[$key]['frequency'];
2478
+ $found = true;
2479
+ break;
2480
+ }
2481
+ }
2482
+ if (!$found) {
2483
+ $frequencyArray[] = array(
2484
+ 'value' => $datum,
2485
+ 'frequency' => 1
2486
+ );
2487
+ }
2488
+ }
2489
+
2490
+ foreach ($frequencyArray as $key => $value) {
2491
+ $frequencyList[$key] = $value['frequency'];
2492
+ $valueList[$key] = $value['value'];
2493
+ }
2494
+ array_multisort($frequencyList, SORT_DESC, $valueList, SORT_ASC, SORT_NUMERIC, $frequencyArray);
2495
+
2496
+ if ($frequencyArray[0]['frequency'] == 1) {
2497
+ return PHPExcel_Calculation_Functions::NA();
2498
+ }
2499
+ return $frequencyArray[0]['value'];
2500
+ }
2501
+
2502
+
2503
+ /**
2504
+ * MODE
2505
+ *
2506
+ * Returns the most frequently occurring, or repetitive, value in an array or range of data
2507
+ *
2508
+ * Excel Function:
2509
+ * MODE(value1[,value2[, ...]])
2510
+ *
2511
+ * @access public
2512
+ * @category Statistical Functions
2513
+ * @param mixed $arg,... Data values
2514
+ * @return float
2515
+ */
2516
+ public static function MODE()
2517
+ {
2518
+ $returnValue = PHPExcel_Calculation_Functions::NA();
2519
+
2520
+ // Loop through arguments
2521
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2522
+
2523
+ $mArgs = array();
2524
+ foreach ($aArgs as $arg) {
2525
+ // Is it a numeric value?
2526
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2527
+ $mArgs[] = $arg;
2528
+ }
2529
+ }
2530
+
2531
+ if (!empty($mArgs)) {
2532
+ return self::modeCalc($mArgs);
2533
+ }
2534
+
2535
+ return $returnValue;
2536
+ }
2537
+
2538
+
2539
+ /**
2540
+ * NEGBINOMDIST
2541
+ *
2542
+ * Returns the negative binomial distribution. NEGBINOMDIST returns the probability that
2543
+ * there will be number_f failures before the number_s-th success, when the constant
2544
+ * probability of a success is probability_s. This function is similar to the binomial
2545
+ * distribution, except that the number of successes is fixed, and the number of trials is
2546
+ * variable. Like the binomial, trials are assumed to be independent.
2547
+ *
2548
+ * @param float $failures Number of Failures
2549
+ * @param float $successes Threshold number of Successes
2550
+ * @param float $probability Probability of success on each trial
2551
+ * @return float
2552
+ *
2553
+ */
2554
+ public static function NEGBINOMDIST($failures, $successes, $probability)
2555
+ {
2556
+ $failures = floor(PHPExcel_Calculation_Functions::flattenSingleValue($failures));
2557
+ $successes = floor(PHPExcel_Calculation_Functions::flattenSingleValue($successes));
2558
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
2559
+
2560
+ if ((is_numeric($failures)) && (is_numeric($successes)) && (is_numeric($probability))) {
2561
+ if (($failures < 0) || ($successes < 1)) {
2562
+ return PHPExcel_Calculation_Functions::NaN();
2563
+ } elseif (($probability < 0) || ($probability > 1)) {
2564
+ return PHPExcel_Calculation_Functions::NaN();
2565
+ }
2566
+ if (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_GNUMERIC) {
2567
+ if (($failures + $successes - 1) <= 0) {
2568
+ return PHPExcel_Calculation_Functions::NaN();
2569
+ }
2570
+ }
2571
+ return (PHPExcel_Calculation_MathTrig::COMBIN($failures + $successes - 1, $successes - 1)) * (pow($probability, $successes)) * (pow(1 - $probability, $failures));
2572
+ }
2573
+ return PHPExcel_Calculation_Functions::VALUE();
2574
+ }
2575
+
2576
+
2577
+ /**
2578
+ * NORMDIST
2579
+ *
2580
+ * Returns the normal distribution for the specified mean and standard deviation. This
2581
+ * function has a very wide range of applications in statistics, including hypothesis
2582
+ * testing.
2583
+ *
2584
+ * @param float $value
2585
+ * @param float $mean Mean Value
2586
+ * @param float $stdDev Standard Deviation
2587
+ * @param boolean $cumulative
2588
+ * @return float
2589
+ *
2590
+ */
2591
+ public static function NORMDIST($value, $mean, $stdDev, $cumulative)
2592
+ {
2593
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2594
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2595
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2596
+
2597
+ if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2598
+ if ($stdDev < 0) {
2599
+ return PHPExcel_Calculation_Functions::NaN();
2600
+ }
2601
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
2602
+ if ($cumulative) {
2603
+ return 0.5 * (1 + PHPExcel_Calculation_Engineering::erfVal(($value - $mean) / ($stdDev * sqrt(2))));
2604
+ } else {
2605
+ return (1 / (SQRT2PI * $stdDev)) * exp(0 - (pow($value - $mean, 2) / (2 * ($stdDev * $stdDev))));
2606
+ }
2607
+ }
2608
+ }
2609
+ return PHPExcel_Calculation_Functions::VALUE();
2610
+ }
2611
+
2612
+
2613
+ /**
2614
+ * NORMINV
2615
+ *
2616
+ * Returns the inverse of the normal cumulative distribution for the specified mean and standard deviation.
2617
+ *
2618
+ * @param float $value
2619
+ * @param float $mean Mean Value
2620
+ * @param float $stdDev Standard Deviation
2621
+ * @return float
2622
+ *
2623
+ */
2624
+ public static function NORMINV($probability, $mean, $stdDev)
2625
+ {
2626
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
2627
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2628
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
2629
+
2630
+ if ((is_numeric($probability)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
2631
+ if (($probability < 0) || ($probability > 1)) {
2632
+ return PHPExcel_Calculation_Functions::NaN();
2633
+ }
2634
+ if ($stdDev < 0) {
2635
+ return PHPExcel_Calculation_Functions::NaN();
2636
+ }
2637
+ return (self::inverseNcdf($probability) * $stdDev) + $mean;
2638
+ }
2639
+ return PHPExcel_Calculation_Functions::VALUE();
2640
+ }
2641
+
2642
+
2643
+ /**
2644
+ * NORMSDIST
2645
+ *
2646
+ * Returns the standard normal cumulative distribution function. The distribution has
2647
+ * a mean of 0 (zero) and a standard deviation of one. Use this function in place of a
2648
+ * table of standard normal curve areas.
2649
+ *
2650
+ * @param float $value
2651
+ * @return float
2652
+ */
2653
+ public static function NORMSDIST($value)
2654
+ {
2655
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2656
+
2657
+ return self::NORMDIST($value, 0, 1, true);
2658
+ }
2659
+
2660
+
2661
+ /**
2662
+ * NORMSINV
2663
+ *
2664
+ * Returns the inverse of the standard normal cumulative distribution
2665
+ *
2666
+ * @param float $value
2667
+ * @return float
2668
+ */
2669
+ public static function NORMSINV($value)
2670
+ {
2671
+ return self::NORMINV($value, 0, 1);
2672
+ }
2673
+
2674
+
2675
+ /**
2676
+ * PERCENTILE
2677
+ *
2678
+ * Returns the nth percentile of values in a range..
2679
+ *
2680
+ * Excel Function:
2681
+ * PERCENTILE(value1[,value2[, ...]],entry)
2682
+ *
2683
+ * @access public
2684
+ * @category Statistical Functions
2685
+ * @param mixed $arg,... Data values
2686
+ * @param float $entry Percentile value in the range 0..1, inclusive.
2687
+ * @return float
2688
+ */
2689
+ public static function PERCENTILE()
2690
+ {
2691
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2692
+
2693
+ // Calculate
2694
+ $entry = array_pop($aArgs);
2695
+
2696
+ if ((is_numeric($entry)) && (!is_string($entry))) {
2697
+ if (($entry < 0) || ($entry > 1)) {
2698
+ return PHPExcel_Calculation_Functions::NaN();
2699
+ }
2700
+ $mArgs = array();
2701
+ foreach ($aArgs as $arg) {
2702
+ // Is it a numeric value?
2703
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2704
+ $mArgs[] = $arg;
2705
+ }
2706
+ }
2707
+ $mValueCount = count($mArgs);
2708
+ if ($mValueCount > 0) {
2709
+ sort($mArgs);
2710
+ $count = self::COUNT($mArgs);
2711
+ $index = $entry * ($count-1);
2712
+ $iBase = floor($index);
2713
+ if ($index == $iBase) {
2714
+ return $mArgs[$index];
2715
+ } else {
2716
+ $iNext = $iBase + 1;
2717
+ $iProportion = $index - $iBase;
2718
+ return $mArgs[$iBase] + (($mArgs[$iNext] - $mArgs[$iBase]) * $iProportion) ;
2719
+ }
2720
+ }
2721
+ }
2722
+ return PHPExcel_Calculation_Functions::VALUE();
2723
+ }
2724
+
2725
+
2726
+ /**
2727
+ * PERCENTRANK
2728
+ *
2729
+ * Returns the rank of a value in a data set as a percentage of the data set.
2730
+ *
2731
+ * @param array of number An array of, or a reference to, a list of numbers.
2732
+ * @param number The number whose rank you want to find.
2733
+ * @param number The number of significant digits for the returned percentage value.
2734
+ * @return float
2735
+ */
2736
+ public static function PERCENTRANK($valueSet, $value, $significance = 3)
2737
+ {
2738
+ $valueSet = PHPExcel_Calculation_Functions::flattenArray($valueSet);
2739
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2740
+ $significance = (is_null($significance)) ? 3 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($significance);
2741
+
2742
+ foreach ($valueSet as $key => $valueEntry) {
2743
+ if (!is_numeric($valueEntry)) {
2744
+ unset($valueSet[$key]);
2745
+ }
2746
+ }
2747
+ sort($valueSet, SORT_NUMERIC);
2748
+ $valueCount = count($valueSet);
2749
+ if ($valueCount == 0) {
2750
+ return PHPExcel_Calculation_Functions::NaN();
2751
+ }
2752
+
2753
+ $valueAdjustor = $valueCount - 1;
2754
+ if (($value < $valueSet[0]) || ($value > $valueSet[$valueAdjustor])) {
2755
+ return PHPExcel_Calculation_Functions::NA();
2756
+ }
2757
+
2758
+ $pos = array_search($value, $valueSet);
2759
+ if ($pos === false) {
2760
+ $pos = 0;
2761
+ $testValue = $valueSet[0];
2762
+ while ($testValue < $value) {
2763
+ $testValue = $valueSet[++$pos];
2764
+ }
2765
+ --$pos;
2766
+ $pos += (($value - $valueSet[$pos]) / ($testValue - $valueSet[$pos]));
2767
+ }
2768
+
2769
+ return round($pos / $valueAdjustor, $significance);
2770
+ }
2771
+
2772
+
2773
+ /**
2774
+ * PERMUT
2775
+ *
2776
+ * Returns the number of permutations for a given number of objects that can be
2777
+ * selected from number objects. A permutation is any set or subset of objects or
2778
+ * events where internal order is significant. Permutations are different from
2779
+ * combinations, for which the internal order is not significant. Use this function
2780
+ * for lottery-style probability calculations.
2781
+ *
2782
+ * @param int $numObjs Number of different objects
2783
+ * @param int $numInSet Number of objects in each permutation
2784
+ * @return int Number of permutations
2785
+ */
2786
+ public static function PERMUT($numObjs, $numInSet)
2787
+ {
2788
+ $numObjs = PHPExcel_Calculation_Functions::flattenSingleValue($numObjs);
2789
+ $numInSet = PHPExcel_Calculation_Functions::flattenSingleValue($numInSet);
2790
+
2791
+ if ((is_numeric($numObjs)) && (is_numeric($numInSet))) {
2792
+ $numInSet = floor($numInSet);
2793
+ if ($numObjs < $numInSet) {
2794
+ return PHPExcel_Calculation_Functions::NaN();
2795
+ }
2796
+ return round(PHPExcel_Calculation_MathTrig::FACT($numObjs) / PHPExcel_Calculation_MathTrig::FACT($numObjs - $numInSet));
2797
+ }
2798
+ return PHPExcel_Calculation_Functions::VALUE();
2799
+ }
2800
+
2801
+
2802
+ /**
2803
+ * POISSON
2804
+ *
2805
+ * Returns the Poisson distribution. A common application of the Poisson distribution
2806
+ * is predicting the number of events over a specific time, such as the number of
2807
+ * cars arriving at a toll plaza in 1 minute.
2808
+ *
2809
+ * @param float $value
2810
+ * @param float $mean Mean Value
2811
+ * @param boolean $cumulative
2812
+ * @return float
2813
+ *
2814
+ */
2815
+ public static function POISSON($value, $mean, $cumulative)
2816
+ {
2817
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2818
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
2819
+
2820
+ if ((is_numeric($value)) && (is_numeric($mean))) {
2821
+ if (($value < 0) || ($mean <= 0)) {
2822
+ return PHPExcel_Calculation_Functions::NaN();
2823
+ }
2824
+ if ((is_numeric($cumulative)) || (is_bool($cumulative))) {
2825
+ if ($cumulative) {
2826
+ $summer = 0;
2827
+ for ($i = 0; $i <= floor($value); ++$i) {
2828
+ $summer += pow($mean, $i) / PHPExcel_Calculation_MathTrig::FACT($i);
2829
+ }
2830
+ return exp(0-$mean) * $summer;
2831
+ } else {
2832
+ return (exp(0-$mean) * pow($mean, $value)) / PHPExcel_Calculation_MathTrig::FACT($value);
2833
+ }
2834
+ }
2835
+ }
2836
+ return PHPExcel_Calculation_Functions::VALUE();
2837
+ }
2838
+
2839
+
2840
+ /**
2841
+ * QUARTILE
2842
+ *
2843
+ * Returns the quartile of a data set.
2844
+ *
2845
+ * Excel Function:
2846
+ * QUARTILE(value1[,value2[, ...]],entry)
2847
+ *
2848
+ * @access public
2849
+ * @category Statistical Functions
2850
+ * @param mixed $arg,... Data values
2851
+ * @param int $entry Quartile value in the range 1..3, inclusive.
2852
+ * @return float
2853
+ */
2854
+ public static function QUARTILE()
2855
+ {
2856
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
2857
+
2858
+ // Calculate
2859
+ $entry = floor(array_pop($aArgs));
2860
+
2861
+ if ((is_numeric($entry)) && (!is_string($entry))) {
2862
+ $entry /= 4;
2863
+ if (($entry < 0) || ($entry > 1)) {
2864
+ return PHPExcel_Calculation_Functions::NaN();
2865
+ }
2866
+ return self::PERCENTILE($aArgs, $entry);
2867
+ }
2868
+ return PHPExcel_Calculation_Functions::VALUE();
2869
+ }
2870
+
2871
+
2872
+ /**
2873
+ * RANK
2874
+ *
2875
+ * Returns the rank of a number in a list of numbers.
2876
+ *
2877
+ * @param number The number whose rank you want to find.
2878
+ * @param array of number An array of, or a reference to, a list of numbers.
2879
+ * @param mixed Order to sort the values in the value set
2880
+ * @return float
2881
+ */
2882
+ public static function RANK($value, $valueSet, $order = 0)
2883
+ {
2884
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
2885
+ $valueSet = PHPExcel_Calculation_Functions::flattenArray($valueSet);
2886
+ $order = (is_null($order)) ? 0 : (integer) PHPExcel_Calculation_Functions::flattenSingleValue($order);
2887
+
2888
+ foreach ($valueSet as $key => $valueEntry) {
2889
+ if (!is_numeric($valueEntry)) {
2890
+ unset($valueSet[$key]);
2891
+ }
2892
+ }
2893
+
2894
+ if ($order == 0) {
2895
+ rsort($valueSet, SORT_NUMERIC);
2896
+ } else {
2897
+ sort($valueSet, SORT_NUMERIC);
2898
+ }
2899
+ $pos = array_search($value, $valueSet);
2900
+ if ($pos === false) {
2901
+ return PHPExcel_Calculation_Functions::NA();
2902
+ }
2903
+
2904
+ return ++$pos;
2905
+ }
2906
+
2907
+
2908
+ /**
2909
+ * RSQ
2910
+ *
2911
+ * Returns the square of the Pearson product moment correlation coefficient through data points in known_y's and known_x's.
2912
+ *
2913
+ * @param array of mixed Data Series Y
2914
+ * @param array of mixed Data Series X
2915
+ * @return float
2916
+ */
2917
+ public static function RSQ($yValues, $xValues)
2918
+ {
2919
+ if (!self::checkTrendArrays($yValues, $xValues)) {
2920
+ return PHPExcel_Calculation_Functions::VALUE();
2921
+ }
2922
+ $yValueCount = count($yValues);
2923
+ $xValueCount = count($xValues);
2924
+
2925
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
2926
+ return PHPExcel_Calculation_Functions::NA();
2927
+ } elseif ($yValueCount == 1) {
2928
+ return PHPExcel_Calculation_Functions::DIV0();
2929
+ }
2930
+
2931
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues);
2932
+ return $bestFitLinear->getGoodnessOfFit();
2933
+ }
2934
+
2935
+
2936
+ /**
2937
+ * SKEW
2938
+ *
2939
+ * Returns the skewness of a distribution. Skewness characterizes the degree of asymmetry
2940
+ * of a distribution around its mean. Positive skewness indicates a distribution with an
2941
+ * asymmetric tail extending toward more positive values. Negative skewness indicates a
2942
+ * distribution with an asymmetric tail extending toward more negative values.
2943
+ *
2944
+ * @param array Data Series
2945
+ * @return float
2946
+ */
2947
+ public static function SKEW()
2948
+ {
2949
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
2950
+ $mean = self::AVERAGE($aArgs);
2951
+ $stdDev = self::STDEV($aArgs);
2952
+
2953
+ $count = $summer = 0;
2954
+ // Loop through arguments
2955
+ foreach ($aArgs as $k => $arg) {
2956
+ if ((is_bool($arg)) &&
2957
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
2958
+ } else {
2959
+ // Is it a numeric value?
2960
+ if ((is_numeric($arg)) && (!is_string($arg))) {
2961
+ $summer += pow((($arg - $mean) / $stdDev), 3);
2962
+ ++$count;
2963
+ }
2964
+ }
2965
+ }
2966
+
2967
+ if ($count > 2) {
2968
+ return $summer * ($count / (($count-1) * ($count-2)));
2969
+ }
2970
+ return PHPExcel_Calculation_Functions::DIV0();
2971
+ }
2972
+
2973
+
2974
+ /**
2975
+ * SLOPE
2976
+ *
2977
+ * Returns the slope of the linear regression line through data points in known_y's and known_x's.
2978
+ *
2979
+ * @param array of mixed Data Series Y
2980
+ * @param array of mixed Data Series X
2981
+ * @return float
2982
+ */
2983
+ public static function SLOPE($yValues, $xValues)
2984
+ {
2985
+ if (!self::checkTrendArrays($yValues, $xValues)) {
2986
+ return PHPExcel_Calculation_Functions::VALUE();
2987
+ }
2988
+ $yValueCount = count($yValues);
2989
+ $xValueCount = count($xValues);
2990
+
2991
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
2992
+ return PHPExcel_Calculation_Functions::NA();
2993
+ } elseif ($yValueCount == 1) {
2994
+ return PHPExcel_Calculation_Functions::DIV0();
2995
+ }
2996
+
2997
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues);
2998
+ return $bestFitLinear->getSlope();
2999
+ }
3000
+
3001
+
3002
+ /**
3003
+ * SMALL
3004
+ *
3005
+ * Returns the nth smallest value in a data set. You can use this function to
3006
+ * select a value based on its relative standing.
3007
+ *
3008
+ * Excel Function:
3009
+ * SMALL(value1[,value2[, ...]],entry)
3010
+ *
3011
+ * @access public
3012
+ * @category Statistical Functions
3013
+ * @param mixed $arg,... Data values
3014
+ * @param int $entry Position (ordered from the smallest) in the array or range of data to return
3015
+ * @return float
3016
+ */
3017
+ public static function SMALL()
3018
+ {
3019
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
3020
+
3021
+ // Calculate
3022
+ $entry = array_pop($aArgs);
3023
+
3024
+ if ((is_numeric($entry)) && (!is_string($entry))) {
3025
+ $mArgs = array();
3026
+ foreach ($aArgs as $arg) {
3027
+ // Is it a numeric value?
3028
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3029
+ $mArgs[] = $arg;
3030
+ }
3031
+ }
3032
+ $count = self::COUNT($mArgs);
3033
+ $entry = floor(--$entry);
3034
+ if (($entry < 0) || ($entry >= $count) || ($count == 0)) {
3035
+ return PHPExcel_Calculation_Functions::NaN();
3036
+ }
3037
+ sort($mArgs);
3038
+ return $mArgs[$entry];
3039
+ }
3040
+ return PHPExcel_Calculation_Functions::VALUE();
3041
+ }
3042
+
3043
+
3044
+ /**
3045
+ * STANDARDIZE
3046
+ *
3047
+ * Returns a normalized value from a distribution characterized by mean and standard_dev.
3048
+ *
3049
+ * @param float $value Value to normalize
3050
+ * @param float $mean Mean Value
3051
+ * @param float $stdDev Standard Deviation
3052
+ * @return float Standardized value
3053
+ */
3054
+ public static function STANDARDIZE($value, $mean, $stdDev)
3055
+ {
3056
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
3057
+ $mean = PHPExcel_Calculation_Functions::flattenSingleValue($mean);
3058
+ $stdDev = PHPExcel_Calculation_Functions::flattenSingleValue($stdDev);
3059
+
3060
+ if ((is_numeric($value)) && (is_numeric($mean)) && (is_numeric($stdDev))) {
3061
+ if ($stdDev <= 0) {
3062
+ return PHPExcel_Calculation_Functions::NaN();
3063
+ }
3064
+ return ($value - $mean) / $stdDev ;
3065
+ }
3066
+ return PHPExcel_Calculation_Functions::VALUE();
3067
+ }
3068
+
3069
+
3070
+ /**
3071
+ * STDEV
3072
+ *
3073
+ * Estimates standard deviation based on a sample. The standard deviation is a measure of how
3074
+ * widely values are dispersed from the average value (the mean).
3075
+ *
3076
+ * Excel Function:
3077
+ * STDEV(value1[,value2[, ...]])
3078
+ *
3079
+ * @access public
3080
+ * @category Statistical Functions
3081
+ * @param mixed $arg,... Data values
3082
+ * @return float
3083
+ */
3084
+ public static function STDEV()
3085
+ {
3086
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3087
+
3088
+ // Return value
3089
+ $returnValue = null;
3090
+
3091
+ $aMean = self::AVERAGE($aArgs);
3092
+ if (!is_null($aMean)) {
3093
+ $aCount = -1;
3094
+ foreach ($aArgs as $k => $arg) {
3095
+ if ((is_bool($arg)) &&
3096
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
3097
+ $arg = (integer) $arg;
3098
+ }
3099
+ // Is it a numeric value?
3100
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3101
+ if (is_null($returnValue)) {
3102
+ $returnValue = pow(($arg - $aMean), 2);
3103
+ } else {
3104
+ $returnValue += pow(($arg - $aMean), 2);
3105
+ }
3106
+ ++$aCount;
3107
+ }
3108
+ }
3109
+
3110
+ // Return
3111
+ if (($aCount > 0) && ($returnValue >= 0)) {
3112
+ return sqrt($returnValue / $aCount);
3113
+ }
3114
+ }
3115
+ return PHPExcel_Calculation_Functions::DIV0();
3116
+ }
3117
+
3118
+
3119
+ /**
3120
+ * STDEVA
3121
+ *
3122
+ * Estimates standard deviation based on a sample, including numbers, text, and logical values
3123
+ *
3124
+ * Excel Function:
3125
+ * STDEVA(value1[,value2[, ...]])
3126
+ *
3127
+ * @access public
3128
+ * @category Statistical Functions
3129
+ * @param mixed $arg,... Data values
3130
+ * @return float
3131
+ */
3132
+ public static function STDEVA()
3133
+ {
3134
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3135
+
3136
+ $returnValue = null;
3137
+
3138
+ $aMean = self::AVERAGEA($aArgs);
3139
+ if (!is_null($aMean)) {
3140
+ $aCount = -1;
3141
+ foreach ($aArgs as $k => $arg) {
3142
+ if ((is_bool($arg)) &&
3143
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
3144
+ } else {
3145
+ // Is it a numeric value?
3146
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
3147
+ if (is_bool($arg)) {
3148
+ $arg = (integer) $arg;
3149
+ } elseif (is_string($arg)) {
3150
+ $arg = 0;
3151
+ }
3152
+ if (is_null($returnValue)) {
3153
+ $returnValue = pow(($arg - $aMean), 2);
3154
+ } else {
3155
+ $returnValue += pow(($arg - $aMean), 2);
3156
+ }
3157
+ ++$aCount;
3158
+ }
3159
+ }
3160
+ }
3161
+
3162
+ if (($aCount > 0) && ($returnValue >= 0)) {
3163
+ return sqrt($returnValue / $aCount);
3164
+ }
3165
+ }
3166
+ return PHPExcel_Calculation_Functions::DIV0();
3167
+ }
3168
+
3169
+
3170
+ /**
3171
+ * STDEVP
3172
+ *
3173
+ * Calculates standard deviation based on the entire population
3174
+ *
3175
+ * Excel Function:
3176
+ * STDEVP(value1[,value2[, ...]])
3177
+ *
3178
+ * @access public
3179
+ * @category Statistical Functions
3180
+ * @param mixed $arg,... Data values
3181
+ * @return float
3182
+ */
3183
+ public static function STDEVP()
3184
+ {
3185
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3186
+
3187
+ $returnValue = null;
3188
+
3189
+ $aMean = self::AVERAGE($aArgs);
3190
+ if (!is_null($aMean)) {
3191
+ $aCount = 0;
3192
+ foreach ($aArgs as $k => $arg) {
3193
+ if ((is_bool($arg)) &&
3194
+ ((!PHPExcel_Calculation_Functions::isCellValue($k)) || (PHPExcel_Calculation_Functions::getCompatibilityMode() == PHPExcel_Calculation_Functions::COMPATIBILITY_OPENOFFICE))) {
3195
+ $arg = (integer) $arg;
3196
+ }
3197
+ // Is it a numeric value?
3198
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3199
+ if (is_null($returnValue)) {
3200
+ $returnValue = pow(($arg - $aMean), 2);
3201
+ } else {
3202
+ $returnValue += pow(($arg - $aMean), 2);
3203
+ }
3204
+ ++$aCount;
3205
+ }
3206
+ }
3207
+
3208
+ if (($aCount > 0) && ($returnValue >= 0)) {
3209
+ return sqrt($returnValue / $aCount);
3210
+ }
3211
+ }
3212
+ return PHPExcel_Calculation_Functions::DIV0();
3213
+ }
3214
+
3215
+
3216
+ /**
3217
+ * STDEVPA
3218
+ *
3219
+ * Calculates standard deviation based on the entire population, including numbers, text, and logical values
3220
+ *
3221
+ * Excel Function:
3222
+ * STDEVPA(value1[,value2[, ...]])
3223
+ *
3224
+ * @access public
3225
+ * @category Statistical Functions
3226
+ * @param mixed $arg,... Data values
3227
+ * @return float
3228
+ */
3229
+ public static function STDEVPA()
3230
+ {
3231
+ $aArgs = PHPExcel_Calculation_Functions::flattenArrayIndexed(func_get_args());
3232
+
3233
+ $returnValue = null;
3234
+
3235
+ $aMean = self::AVERAGEA($aArgs);
3236
+ if (!is_null($aMean)) {
3237
+ $aCount = 0;
3238
+ foreach ($aArgs as $k => $arg) {
3239
+ if ((is_bool($arg)) &&
3240
+ (!PHPExcel_Calculation_Functions::isMatrixValue($k))) {
3241
+ } else {
3242
+ // Is it a numeric value?
3243
+ if ((is_numeric($arg)) || (is_bool($arg)) || ((is_string($arg) & ($arg != '')))) {
3244
+ if (is_bool($arg)) {
3245
+ $arg = (integer) $arg;
3246
+ } elseif (is_string($arg)) {
3247
+ $arg = 0;
3248
+ }
3249
+ if (is_null($returnValue)) {
3250
+ $returnValue = pow(($arg - $aMean), 2);
3251
+ } else {
3252
+ $returnValue += pow(($arg - $aMean), 2);
3253
+ }
3254
+ ++$aCount;
3255
+ }
3256
+ }
3257
+ }
3258
+
3259
+ if (($aCount > 0) && ($returnValue >= 0)) {
3260
+ return sqrt($returnValue / $aCount);
3261
+ }
3262
+ }
3263
+ return PHPExcel_Calculation_Functions::DIV0();
3264
+ }
3265
+
3266
+
3267
+ /**
3268
+ * STEYX
3269
+ *
3270
+ * Returns the standard error of the predicted y-value for each x in the regression.
3271
+ *
3272
+ * @param array of mixed Data Series Y
3273
+ * @param array of mixed Data Series X
3274
+ * @return float
3275
+ */
3276
+ public static function STEYX($yValues, $xValues)
3277
+ {
3278
+ if (!self::checkTrendArrays($yValues, $xValues)) {
3279
+ return PHPExcel_Calculation_Functions::VALUE();
3280
+ }
3281
+ $yValueCount = count($yValues);
3282
+ $xValueCount = count($xValues);
3283
+
3284
+ if (($yValueCount == 0) || ($yValueCount != $xValueCount)) {
3285
+ return PHPExcel_Calculation_Functions::NA();
3286
+ } elseif ($yValueCount == 1) {
3287
+ return PHPExcel_Calculation_Functions::DIV0();
3288
+ }
3289
+
3290
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues);
3291
+ return $bestFitLinear->getStdevOfResiduals();
3292
+ }
3293
+
3294
+
3295
+ /**
3296
+ * TDIST
3297
+ *
3298
+ * Returns the probability of Student's T distribution.
3299
+ *
3300
+ * @param float $value Value for the function
3301
+ * @param float $degrees degrees of freedom
3302
+ * @param float $tails number of tails (1 or 2)
3303
+ * @return float
3304
+ */
3305
+ public static function TDIST($value, $degrees, $tails)
3306
+ {
3307
+ $value = PHPExcel_Calculation_Functions::flattenSingleValue($value);
3308
+ $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees));
3309
+ $tails = floor(PHPExcel_Calculation_Functions::flattenSingleValue($tails));
3310
+
3311
+ if ((is_numeric($value)) && (is_numeric($degrees)) && (is_numeric($tails))) {
3312
+ if (($value < 0) || ($degrees < 1) || ($tails < 1) || ($tails > 2)) {
3313
+ return PHPExcel_Calculation_Functions::NaN();
3314
+ }
3315
+ // tdist, which finds the probability that corresponds to a given value
3316
+ // of t with k degrees of freedom. This algorithm is translated from a
3317
+ // pascal function on p81 of "Statistical Computing in Pascal" by D
3318
+ // Cooke, A H Craven & G M Clark (1985: Edward Arnold (Pubs.) Ltd:
3319
+ // London). The above Pascal algorithm is itself a translation of the
3320
+ // fortran algoritm "AS 3" by B E Cooper of the Atlas Computer
3321
+ // Laboratory as reported in (among other places) "Applied Statistics
3322
+ // Algorithms", editied by P Griffiths and I D Hill (1985; Ellis
3323
+ // Horwood Ltd.; W. Sussex, England).
3324
+ $tterm = $degrees;
3325
+ $ttheta = atan2($value, sqrt($tterm));
3326
+ $tc = cos($ttheta);
3327
+ $ts = sin($ttheta);
3328
+ $tsum = 0;
3329
+
3330
+ if (($degrees % 2) == 1) {
3331
+ $ti = 3;
3332
+ $tterm = $tc;
3333
+ } else {
3334
+ $ti = 2;
3335
+ $tterm = 1;
3336
+ }
3337
+
3338
+ $tsum = $tterm;
3339
+ while ($ti < $degrees) {
3340
+ $tterm *= $tc * $tc * ($ti - 1) / $ti;
3341
+ $tsum += $tterm;
3342
+ $ti += 2;
3343
+ }
3344
+ $tsum *= $ts;
3345
+ if (($degrees % 2) == 1) {
3346
+ $tsum = M_2DIVPI * ($tsum + $ttheta);
3347
+ }
3348
+ $tValue = 0.5 * (1 + $tsum);
3349
+ if ($tails == 1) {
3350
+ return 1 - abs($tValue);
3351
+ } else {
3352
+ return 1 - abs((1 - $tValue) - $tValue);
3353
+ }
3354
+ }
3355
+ return PHPExcel_Calculation_Functions::VALUE();
3356
+ }
3357
+
3358
+
3359
+ /**
3360
+ * TINV
3361
+ *
3362
+ * Returns the one-tailed probability of the chi-squared distribution.
3363
+ *
3364
+ * @param float $probability Probability for the function
3365
+ * @param float $degrees degrees of freedom
3366
+ * @return float
3367
+ */
3368
+ public static function TINV($probability, $degrees)
3369
+ {
3370
+ $probability = PHPExcel_Calculation_Functions::flattenSingleValue($probability);
3371
+ $degrees = floor(PHPExcel_Calculation_Functions::flattenSingleValue($degrees));
3372
+
3373
+ if ((is_numeric($probability)) && (is_numeric($degrees))) {
3374
+ $xLo = 100;
3375
+ $xHi = 0;
3376
+
3377
+ $x = $xNew = 1;
3378
+ $dx = 1;
3379
+ $i = 0;
3380
+
3381
+ while ((abs($dx) > PRECISION) && ($i++ < MAX_ITERATIONS)) {
3382
+ // Apply Newton-Raphson step
3383
+ $result = self::TDIST($x, $degrees, 2);
3384
+ $error = $result - $probability;
3385
+ if ($error == 0.0) {
3386
+ $dx = 0;
3387
+ } elseif ($error < 0.0) {
3388
+ $xLo = $x;
3389
+ } else {
3390
+ $xHi = $x;
3391
+ }
3392
+ // Avoid division by zero
3393
+ if ($result != 0.0) {
3394
+ $dx = $error / $result;
3395
+ $xNew = $x - $dx;
3396
+ }
3397
+ // If the NR fails to converge (which for example may be the
3398
+ // case if the initial guess is too rough) we apply a bisection
3399
+ // step to determine a more narrow interval around the root.
3400
+ if (($xNew < $xLo) || ($xNew > $xHi) || ($result == 0.0)) {
3401
+ $xNew = ($xLo + $xHi) / 2;
3402
+ $dx = $xNew - $x;
3403
+ }
3404
+ $x = $xNew;
3405
+ }
3406
+ if ($i == MAX_ITERATIONS) {
3407
+ return PHPExcel_Calculation_Functions::NA();
3408
+ }
3409
+ return round($x, 12);
3410
+ }
3411
+ return PHPExcel_Calculation_Functions::VALUE();
3412
+ }
3413
+
3414
+
3415
+ /**
3416
+ * TREND
3417
+ *
3418
+ * Returns values along a linear trend
3419
+ *
3420
+ * @param array of mixed Data Series Y
3421
+ * @param array of mixed Data Series X
3422
+ * @param array of mixed Values of X for which we want to find Y
3423
+ * @param boolean A logical value specifying whether to force the intersect to equal 0.
3424
+ * @return array of float
3425
+ */
3426
+ public static function TREND($yValues, $xValues = array(), $newValues = array(), $const = true)
3427
+ {
3428
+ $yValues = PHPExcel_Calculation_Functions::flattenArray($yValues);
3429
+ $xValues = PHPExcel_Calculation_Functions::flattenArray($xValues);
3430
+ $newValues = PHPExcel_Calculation_Functions::flattenArray($newValues);
3431
+ $const = (is_null($const)) ? true : (boolean) PHPExcel_Calculation_Functions::flattenSingleValue($const);
3432
+
3433
+ $bestFitLinear = trendClass::calculate(trendClass::TREND_LINEAR, $yValues, $xValues, $const);
3434
+ if (empty($newValues)) {
3435
+ $newValues = $bestFitLinear->getXValues();
3436
+ }
3437
+
3438
+ $returnArray = array();
3439
+ foreach ($newValues as $xValue) {
3440
+ $returnArray[0][] = $bestFitLinear->getValueOfYForX($xValue);
3441
+ }
3442
+
3443
+ return $returnArray;
3444
+ }
3445
+
3446
+
3447
+ /**
3448
+ * TRIMMEAN
3449
+ *
3450
+ * Returns the mean of the interior of a data set. TRIMMEAN calculates the mean
3451
+ * taken by excluding a percentage of data points from the top and bottom tails
3452
+ * of a data set.
3453
+ *
3454
+ * Excel Function:
3455
+ * TRIMEAN(value1[,value2[, ...]], $discard)
3456
+ *
3457
+ * @access public
3458
+ * @category Statistical Functions
3459
+ * @param mixed $arg,... Data values
3460
+ * @param float $discard Percentage to discard
3461
+ * @return float
3462
+ */
3463
+ public static function TRIMMEAN()
3464
+ {
3465
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
3466
+
3467
+ // Calculate
3468
+ $percent = array_pop($aArgs);
3469
+
3470
+ if ((is_numeric($percent)) && (!is_string($percent))) {
3471
+ if (($percent < 0) || ($percent > 1)) {
3472
+ return PHPExcel_Calculation_Functions::NaN();
3473
+ }
3474
+ $mArgs = array();
3475
+ foreach ($aArgs as $arg) {
3476
+ // Is it a numeric value?
3477
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3478
+ $mArgs[] = $arg;
3479
+ }
3480
+ }
3481
+ $discard = floor(self::COUNT($mArgs) * $percent / 2);
3482
+ sort($mArgs);
3483
+ for ($i=0; $i < $discard; ++$i) {
3484
+ array_pop($mArgs);
3485
+ array_shift($mArgs);
3486
+ }
3487
+ return self::AVERAGE($mArgs);
3488
+ }
3489
+ return PHPExcel_Calculation_Functions::VALUE();
3490
+ }
3491
+
3492
+
3493
+ /**
3494
+ * VARFunc
3495
+ *
3496
+ * Estimates variance based on a sample.
3497
+ *
3498
+ * Excel Function:
3499
+ * VAR(value1[,value2[, ...]])
3500
+ *
3501
+ * @access public
3502
+ * @category Statistical Functions
3503
+ * @param mixed $arg,... Data values
3504
+ * @return float
3505
+ */
3506
+ public static function VARFunc()
3507
+ {
3508
+ $returnValue = PHPExcel_Calculation_Functions::DIV0();
3509
+
3510
+ $summerA = $summerB = 0;
3511
+
3512
+ // Loop through arguments
3513
+ $aArgs = PHPExcel_Calculation_Functions::flattenArray(func_get_args());
3514
+ $aCount = 0;
3515
+ foreach ($aArgs as $arg) {
3516
+ if (is_bool($arg)) {
3517
+ $arg = (integer) $arg;
3518
+ }
3519
+ // Is it a numeric value?
3520
+ if ((is_numeric($arg)) && (!is_string($arg))) {
3521
+ $summerA += ($arg * $arg);
3522
+ $sum